#17055·medusa

Cart tax lines are duplicated every time a workflow compensates after upsertTaxLinesForItemsStep

Author: danlapteacruCreated Sep 28, 2026Updated Sep 28, 2026
Labelstype: bugrequires-team

A cart's line item tax lines are duplicated every time a workflow compensates after upsertTaxLinesForItemsStep. Nothing surfaces when it happens: the cart's own total stays correct, and the copies only become visible once completeCartWorkflow carries them onto the order — where tax_total is a multiple of the real tax and no longer matches what the payment provider was asked to charge.

Verified on @medusajs/core-flows 2.17.2 and 2.21.2. dist/cart/steps/upsert-tax-lines-for-items.js is unchanged between the two apart from metadata/data being carried through, so this is present on latest.

The order-side twin, setOrderTaxLinesForItemsStep, was given exactly this treatment in 2.19.0 — its compensation now deletes what is currently attached to the affected entities and recreates the captured snapshot. The cart-side step was left as it was.

What it costs

Found on a real order: one line item shipped to Prescott, Arizona, which returns three rates (state 5.6 + county 0.75 + city 2.95). The order carries nine tax lines on that one item — the three rates, three times over — for a tax_total of $4.9383 against a correct $1.6461. The payment provider captured $25.0261, the cart's total at the time, which was right. order.total says $28.3183 and the confirmation page told the buyer $28.32. $3.29 of the order was never charged, and the order no longer reconciles against the payment.

It stays invisible in a single-rate jurisdiction: the duplicated rows there are the zero-rate calculations that ran before the address was complete, so they add nothing to the total. On the same deployment 87 of 300 recent orders carry duplicate tax lines and none of them cost anything, because every duplicated row is zero-rate. A multi-rate address is what turns it into money.

Reproduction

upsertTaxLinesForItemsStep is reached from refreshCartItemsWorkflow's non-force branch, so from any line item add, removal or quantity change. Any failure after it triggers the compensation. Run this with medusa exec:

typescript
import { ExecArgs } from "@medusajs/framework/types"
import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
import { createStep, createWorkflow } from "@medusajs/framework/workflows-sdk"
const {
  upsertTaxLinesForItemsStep,
} = require("@medusajs/core-flows/dist/cart/steps/upsert-tax-lines-for-items.js")

const boom = createStep("boom", async () => {
  throw new Error("simulated downstream failure")
})

const failing = createWorkflow("probe-failing-upsert", (input: any) => {
  upsertTaxLinesForItemsStep({
    cart: input.cart,
    item_tax_lines: input.item_tax_lines,
    shipping_tax_lines: [],
  } as any)
  boom()
  return undefined as any
})

export default async function probe({ container }: ExecArgs) {
  const cartModule: any = container.resolve(Modules.CART)
  const knex: any = container.resolve(ContainerRegistrationKeys.PG_CONNECTION)

  const [cart] = await cartModule.createCarts([
    { currency_code: "usd", email: "[email protected]" },
  ])
  const added = await cartModule.addLineItems(cart.id, [
    { title: "Tee", unit_price: 17.7, quantity: 1 },
  ])
  const itemId = (Array.isArray(added) ? added[0] : added).id

  // Prescott AZ: state + county + city
  const lines = () =>
    [
      ["AZ_STATE", 5.6],
      ["AZ_COUNTY", 0.75],
      ["AZ_CITY", 2.95],
    ].map(([code, rate]) => ({
      rate: rate as number,
      code: code as string,
      name: `tax-${code}`,
      provider_id: "probe",
      line_item_id: itemId,
    }))

  const report = async (label: string) => {
    const rows = await knex.raw(
      `select count(*) filter (where deleted_at is null) as live
         from cart_line_item_tax_line where item_id = ?`,
      [itemId]
    )
    const live = await cartModule.listLineItemTaxLines({ item_id: [itemId] })
    console.log(label, rows.rows[0], live.map((t: any) => `${t.code}=${t.rate}`).join(","))
  }

  for (const i of [1, 2, 3]) {
    await failing(container).run({
      input: { cart, item_tax_lines: lines() },
      throwOnError: false,
    })
    await report(`after failed run ${i}:`)
  }
}

Measured on 2.17.2:

after failed run 1: { live: '3' }  AZ_STATE=5.6,AZ_COUNTY=0.75,AZ_CITY=2.95
after failed run 2: { live: '6' }  AZ_CITY=2.95,AZ_COUNTY=0.75,AZ_CITY=2.95,AZ_STATE=5.6,AZ_CITY=2.95,AZ_COUNTY=0.75
after failed run 3: { live: '12' } ...

Three failed runs, and the item's tax lines go 3 → 6 → 12. Note also that the rates are no longer the three real ones (see the second defect below).

Expected behaviour

The compensation restores the cart to its pre-step state: the tax lines the step inserted are gone, and the ones that were there before are back, once each.

Cause

packages/core/core-flows/src/cart/steps/upsert-tax-lines-for-items.ts:

typescript
if (existingLineItemTaxLines) {
  await cartService.upsertLineItemTaxLines(
    existingLineItemTaxLines.map((taxLine) => ({
      description: taxLine.description,
      tax_rate_id: taxLine.tax_rate_id,
      code: taxLine.code,
      rate: taxLine.rate,
      provider_id: taxLine.provider_id,
      item_id: taxLine.item_id,
      metadata: taxLine.metadata,
      data: taxLine.data,
    }))
  )
}

The mapped snapshot drops id, and the Cart Module's upsert treats an entry with no id as an insert (MikroOrmAbstractBaseRepository.upsert looks the row up by primary key and creates when it finds nothing). So the compensation adds a second copy of every pre-step tax line. It also never removes the rows the forward step inserted, so those stay behind too — which is why a failed run against an item that had no tax lines at all leaves three behind rather than none.

Second defect in the same step, for the record

normalizeItemTaxLinesForCart resolves the existing row to update by item_id alone:

typescript
id: existingTaxLines.find((t) => t.item_id === taxLine.line_item_id)?.id

One line item in a multi-rate jurisdiction has several tax lines, so all of the incoming lines are assigned the same existing row id. The upsert then writes all three onto one row, last one wins, and the other rows keep their old values. Measured against the three Arizona rates, (5.6, 0.75, 2.95) became (2.95, 2.95, 5.6) — the wrong tax, in this case higher than the real one. It cannot add rows, so it is not the duplication above, but it does mean a successful run can produce a total that was never correct. Happy to open that separately if you would prefer it tracked on its own.

System information

  • @medusajs/core-flows 2.17.2, reproduced against 2.21.2's identical code
  • Node.js 22
  • PostgreSQL 15