From b1955f61937519acf8b9234750e59564bddd0169 Mon Sep 17 00:00:00 2001 From: FanouZeng-TT <18280587072@163.com> Date: Wed, 21 Oct 2026 15:35:14 +0800 Subject: [PATCH 1/2] fix(rest/nodejs): commit completion as one SQLite transaction Complete Checkout reserved stock, saved the order and marked the checkout completed as three independent writes. A failure after the reservation answered 500 while leaving stock decremented and, for a checkout-write failure, an order the checkout could not reference. Run all three writes inside a single better-sqlite3 transaction so any failure rolls the reservation, order and status back together and the client can retry safely. The webhook stays outside the transaction. --- rest/nodejs/src/api/checkout.ts | 69 ++++++++++---------- rest/nodejs/src/data/transactions.ts | 17 +++++ rest/nodejs/test/lifecycle.test.ts | 98 ++++++++++++++++++++++++++++ 3 files changed, 151 insertions(+), 33 deletions(-) diff --git a/rest/nodejs/src/api/checkout.ts b/rest/nodejs/src/api/checkout.ts index da774cdc..f16119e6 100644 --- a/rest/nodejs/src/api/checkout.ts +++ b/rest/nodejs/src/api/checkout.ts @@ -25,8 +25,8 @@ import { getOrder, getProduct, logRequest, - releaseStock, reserveStock, + runInTransaction, saveCheckout, saveIdempotencyRecord, saveOrder, @@ -1067,30 +1067,9 @@ export class CheckoutService { // Atomic Inventory Reservation and Completion try { - const reservedItems: Array<{ id: string; qty: number }> = []; - - for (const line of checkout.line_items) { - const product = getProduct(line.item.id); - if (product) { - const success = reserveStock(line.item.id, line.quantity); - if (!success) { - // Rollback - for (const reserved of reservedItems) { - releaseStock(reserved.id, reserved.qty); - } - return ucpErrorResponse( - c, - new OutOfStockError(`Item ${line.item.id} is out of stock`, 409) - ); - } - reservedItems.push({ id: line.item.id, qty: line.quantity }); - } - } - - // Success - checkout.status = CheckoutResponseStatusSchema.enum.completed; - - // Create Order + // Build the order before opening the transaction: constructing it is + // pure computation, while the transaction must stay synchronous so the + // SQLite write lock never spans external I/O. const orderId = `ord_${uuidv4()}`; // Order Fulfillment @@ -1184,17 +1163,41 @@ export class CheckoutService { currency: checkout.currency, }; - saveOrder(order.id, order); + // Reserve stock, persist the order and mark the checkout completed as + // one SQLite transaction: a failure at any step (including an order or + // checkout write) rolls the reservations back instead of leaving stock + // decremented behind a failed 500. + const outcome = runInTransaction(() => { + for (const line of checkout.line_items) { + const product = getProduct(line.item.id); + if (product && !reserveStock(line.item.id, line.quantity)) { + return { outOfStockItem: line.item.id }; + } + } + + checkout.status = CheckoutResponseStatusSchema.enum.completed; + checkout.order = { + id: orderId, + permalink_url: order.permalink_url, + }; - // Save Checkout - checkout.order = { - id: orderId, - permalink_url: order.permalink_url, - }; + saveOrder(order.id, order); + saveCheckout(id, checkout.status, checkout); + return {}; + }); - saveCheckout(id, checkout.status, checkout); + if (outcome.outOfStockItem) { + return ucpErrorResponse( + c, + new OutOfStockError( + `Item ${outcome.outOfStockItem} is out of stock`, + 409 + ) + ); + } - // Notify webhook + // Notify webhook (outside the transaction: external I/O must not hold + // the SQLite write lock). await this.notifyWebhook( checkout, "order_placed", diff --git a/rest/nodejs/src/data/transactions.ts b/rest/nodejs/src/data/transactions.ts index d6e4dff5..b805fda0 100644 --- a/rest/nodejs/src/data/transactions.ts +++ b/rest/nodejs/src/data/transactions.ts @@ -163,3 +163,20 @@ export function saveIdempotencyRecord( ); stmt.run(key, requestHash, status, responseBody); } + +/** + * Runs `fn` as a single SQLite transaction on the transactions database. + * + * Every write performed by `fn` (inventory, checkouts, orders) commits + * together; if `fn` throws, SQLite rolls all of them back and the error is + * rethrown so callers keep their existing error handling. + * + * @param fn The synchronous unit of work to commit atomically. It must not + * await: an external I/O call inside the transaction would hold the write + * lock across a network round trip. + * @returns Whatever `fn` returns. + */ +export function runInTransaction(fn: () => T): T { + const db = getTransactionsDb(); + return db.transaction(fn)(); +} diff --git a/rest/nodejs/test/lifecycle.test.ts b/rest/nodejs/test/lifecycle.test.ts index 7ac3916f..2278c41b 100644 --- a/rest/nodejs/test/lifecycle.test.ts +++ b/rest/nodejs/test/lifecycle.test.ts @@ -19,6 +19,7 @@ import { zValidator } from "@hono/zod-validator"; import { Hono } from "hono"; import { CheckoutService } from "../src/api/checkout"; +import { getInventory, getOrder } from "../src/data"; import { getProductsDb, getTransactionsDb, initDbs } from "../src/data/db"; import { CheckoutCompleteRequestSchema, @@ -374,3 +375,100 @@ test("an idempotent create replay still carries ucp.payment_handlers", async () const replayed = (await replay.json()) as { ucp?: unknown }; assertPaymentHandlers("idempotent replay", replayed.ucp); }); + +// Completion writes three tables (inventory, orders, checkouts). A technical +// failure partway through must not leave stock decremented behind a 500: the +// whole unit has to roll back so the client can retry safely. +function countRows(table: "orders"): number { + const row = getTransactionsDb() + .prepare(`SELECT COUNT(*) AS n FROM ${table}`) + .get() as { n: number }; + return row.n; +} + +function failOnWrite(table: "orders" | "checkouts"): void { + // Fail only the completion writes, so the checkout can still be created and + // updated before the fault is armed. + const sql = + table === "orders" + ? `CREATE TRIGGER fail_completion BEFORE INSERT ON orders + BEGIN SELECT RAISE(ABORT, 'injected order failure'); END` + : `CREATE TRIGGER fail_completion BEFORE UPDATE ON checkouts + WHEN NEW.status = 'completed' + BEGIN SELECT RAISE(ABORT, 'injected checkout failure'); END`; + getTransactionsDb().exec(sql); +} + +function clearFault(): void { + getTransactionsDb().exec("DROP TRIGGER IF EXISTS fail_completion"); +} + +test("an order write failure rolls back the inventory reservation", async () => { + const app = buildApp(); + const id = await createReadyToComplete(app); + const stockBefore = getInventory("bouquet_roses"); + const ordersBefore = countRows("orders"); + + failOnWrite("orders"); + try { + const res = await complete(app, id); + assert.equal(res.status, 500); + } finally { + clearFault(); + } + + assert.equal( + getInventory("bouquet_roses"), + stockBefore, + "a failed completion must not consume stock" + ); + assert.equal(countRows("orders"), ordersBefore, "no order may be persisted"); + const checkout = (await ( + await app.request(`/checkout-sessions/${id}`) + ).json()) as { status: string }; + assert.equal( + checkout.status, + "ready_for_complete", + "the checkout must remain completable after the rollback" + ); +}); + +test("a checkout write failure rolls back the order and the reservation", async () => { + const app = buildApp(); + const id = await createReadyToComplete(app); + const stockBefore = getInventory("bouquet_roses"); + const ordersBefore = countRows("orders"); + + failOnWrite("checkouts"); + try { + const res = await complete(app, id); + assert.equal(res.status, 500); + } finally { + clearFault(); + } + + assert.equal(getInventory("bouquet_roses"), stockBefore); + assert.equal( + countRows("orders"), + ordersBefore, + "the order inserted before the failing checkout update must roll back" + ); + const checkout = (await ( + await app.request(`/checkout-sessions/${id}`) + ).json()) as { status: string; order?: unknown }; + assert.equal(checkout.status, "ready_for_complete"); + assert.equal(checkout.order, undefined, "no order reference may survive"); +}); + +test("a successful completion reserves stock exactly once", async () => { + const app = buildApp(); + const id = await createReadyToComplete(app); + const stockBefore = getInventory("bouquet_roses"); + + const res = await complete(app, id); + assert.equal(res.status, 200); + const body = (await res.json()) as { order?: { id: string } }; + assert.ok(body.order?.id); + assert.equal(getInventory("bouquet_roses"), (stockBefore ?? 0) - 1); + assert.ok(getOrder(body.order.id), "the order must be readable"); +}); From cdf0bf78682a3b7290dd9b9cf0aec3a3c4900cf7 Mon Sep 17 00:00:00 2001 From: FanouZeng-TT <18280587072@163.com> Date: Tue, 27 Oct 2026 14:12:30 +0800 Subject: [PATCH 2/2] fix(rest/nodejs): roll back a partially reserved multi-item completion Returning a sentinel from the transaction callback commits it: better-sqlite3 commits whenever the callback returns normally. A multi-item checkout whose second line is out of stock therefore kept the first line's stock decrement while answering 409. The out-of-stock path now throws inside the transaction so every reservation rolls back, and the handler forwards UcpError instances instead of collapsing them into a 500. The idempotency record is written inside the same transaction, before the webhook, so a retry that lands while delivery is in flight replays the response rather than seeing 'completed' and answering 409. Regression: a two-line checkout whose second line sells out now returns 409 with the first line's stock intact (99 !== 100 before the fix), and an idempotent replay reserves stock once. --- rest/nodejs/src/api/checkout.ts | 54 +++++++++--------- rest/nodejs/test/lifecycle.test.ts | 91 +++++++++++++++++++++++++++--- 2 files changed, 111 insertions(+), 34 deletions(-) diff --git a/rest/nodejs/src/api/checkout.ts b/rest/nodejs/src/api/checkout.ts index f16119e6..f8346e47 100644 --- a/rest/nodejs/src/api/checkout.ts +++ b/rest/nodejs/src/api/checkout.ts @@ -1163,15 +1163,22 @@ export class CheckoutService { currency: checkout.currency, }; - // Reserve stock, persist the order and mark the checkout completed as - // one SQLite transaction: a failure at any step (including an order or - // checkout write) rolls the reservations back instead of leaving stock - // decremented behind a failed 500. - const outcome = runInTransaction(() => { + // Reserve stock, persist the order, mark the checkout completed and + // record the idempotent response as one SQLite transaction: a failure at + // any step — including a line item that runs out of stock after earlier + // lines were reserved — rolls every write back instead of leaving stock + // decremented behind a 409 or 500. + runInTransaction(() => { for (const line of checkout.line_items) { const product = getProduct(line.item.id); + // Throw rather than return: `db.transaction(fn)()` commits whenever + // the callback returns normally, so an early return here would + // commit the reservations made for the lines before this one. if (product && !reserveStock(line.item.id, line.quantity)) { - return { outOfStockItem: line.item.id }; + throw new OutOfStockError( + `Item ${line.item.id} is out of stock`, + 409 + ); } } @@ -1183,18 +1190,19 @@ export class CheckoutService { saveOrder(order.id, order); saveCheckout(id, checkout.status, checkout); - return {}; - }); - if (outcome.outOfStockItem) { - return ucpErrorResponse( - c, - new OutOfStockError( - `Item ${outcome.outOfStockItem} is out of stock`, - 409 - ) - ); - } + // Recorded before the webhook so a retry that arrives while delivery + // is in flight replays this response instead of seeing `completed` + // and being answered 409. + if (idempotencyKey) { + saveIdempotencyRecord( + idempotencyKey, + requestHash, + 200, + JSON.stringify(checkout) + ); + } + }); // Notify webhook (outside the transaction: external I/O must not hold // the SQLite write lock). @@ -1204,17 +1212,11 @@ export class CheckoutService { new URL(c.req.url).origin ); - if (idempotencyKey) { - saveIdempotencyRecord( - idempotencyKey, - requestHash, - 200, - JSON.stringify(checkout) - ); - } - return c.json(checkout, 200); } catch (e) { + if (e instanceof UcpError) { + return ucpErrorResponse(c, e); + } console.error("Error completing checkout", e); return c.json({ detail: "Internal server error" }, 500); } diff --git a/rest/nodejs/test/lifecycle.test.ts b/rest/nodejs/test/lifecycle.test.ts index 2278c41b..7885b9b8 100644 --- a/rest/nodejs/test/lifecycle.test.ts +++ b/rest/nodejs/test/lifecycle.test.ts @@ -77,9 +77,14 @@ before(() => { db.prepare( "INSERT INTO products (id, title, price, image_url) VALUES (?, ?, ?, ?)" ).run("bouquet_roses", "Red Rose", 3500, ""); - getTransactionsDb() - .prepare("INSERT INTO inventory (product_id, quantity) VALUES (?, ?)") - .run("bouquet_roses", 100); + db.prepare( + "INSERT INTO products (id, title, price, image_url) VALUES (?, ?, ?, ?)" + ).run("mug_blue", "Blue Mug", 1500, ""); + const inventory = getTransactionsDb().prepare( + "INSERT INTO inventory (product_id, quantity) VALUES (?, ?)" + ); + inventory.run("bouquet_roses", 100); + inventory.run("mug_blue", 100); }); const JSON_HEADERS = { "Content-Type": "application/json" }; @@ -135,8 +140,11 @@ async function complete( // with a known-customer shipping destination, then choose the quoted option) // and return its id ready to complete. See fulfillment.test.ts for the // dedicated coverage of that selection flow. +type CheckoutItem = { id: string; quantity: number }; + async function createReadyToComplete( - app: ReturnType + app: ReturnType, + items: CheckoutItem[] = [{ id: "bouquet_roses", quantity: 1 }] ): Promise { const created = (await ( await app.request("/checkout-sessions", { @@ -144,7 +152,10 @@ async function createReadyToComplete( headers: JSON_HEADERS, body: JSON.stringify({ currency: "USD", - line_items: [{ item: { id: "bouquet_roses" }, quantity: 1 }], + line_items: items.map((item) => ({ + item: { id: item.id }, + quantity: item.quantity, + })), payment: {}, buyer: { email: "john.doe@example.com" }, fulfillment: { @@ -154,6 +165,7 @@ async function createReadyToComplete( }) ).json()) as { id: string; + line_items: { id: string; item: { id: string }; quantity: number }[]; fulfillment: { methods: { groups: { @@ -171,9 +183,11 @@ async function createReadyToComplete( headers: JSON_HEADERS, body: JSON.stringify({ currency: "USD", - line_items: [ - { id: "line_1", item: { id: "bouquet_roses" }, quantity: 1 }, - ], + line_items: created.line_items.map((line) => ({ + id: line.id, + item: { id: line.item.id }, + quantity: line.quantity, + })), buyer: { email: "john.doe@example.com" }, fulfillment: { methods: [ @@ -460,6 +474,67 @@ test("a checkout write failure rolls back the order and the reservation", async assert.equal(checkout.order, undefined, "no order reference may survive"); }); +test("an out-of-stock second line rolls back the first reservation", async () => { + const app = buildApp(); + const id = await createReadyToComplete(app, [ + { id: "bouquet_roses", quantity: 1 }, + { id: "mug_blue", quantity: 1 }, + ]); + // The mug sells out between checkout creation and completion, so the first + // line is reserved and the second is not. + getTransactionsDb() + .prepare("UPDATE inventory SET quantity = 0 WHERE product_id = ?") + .run("mug_blue"); + const rosesBefore = getInventory("bouquet_roses"); + const ordersBefore = countRows("orders"); + + const res = await complete(app, id); + assert.equal(res.status, 409); + + assert.equal( + getInventory("bouquet_roses"), + rosesBefore, + "the first line's reservation must roll back with the failure" + ); + assert.equal(countRows("orders"), ordersBefore, "no order may be persisted"); + const checkout = (await ( + await app.request(`/checkout-sessions/${id}`) + ).json()) as { status: string }; + assert.equal(checkout.status, "ready_for_complete"); +}); + +test("an idempotent completion replay reserves stock once", async () => { + const app = buildApp(); + const id = await createReadyToComplete(app); + const stockBefore = getInventory("bouquet_roses"); + const ordersBefore = countRows("orders"); + const headers = { ...JSON_HEADERS, "Idempotency-Key": "complete-replay" }; + const body = JSON.stringify(SUCCESS_PAYMENT); + + const first = await app.request(`/checkout-sessions/${id}/complete`, { + method: "POST", + headers, + body, + }); + assert.equal(first.status, 200); + + const replay = await app.request(`/checkout-sessions/${id}/complete`, { + method: "POST", + headers, + body, + }); + assert.equal(replay.status, 200); + const replayed = (await replay.json()) as { status: string }; + assert.equal(replayed.status, "completed"); + + assert.equal( + getInventory("bouquet_roses"), + (stockBefore ?? 0) - 1, + "a replayed completion must not reserve stock again" + ); + assert.equal(countRows("orders"), ordersBefore + 1); +}); + test("a successful completion reserves stock exactly once", async () => { const app = buildApp(); const id = await createReadyToComplete(app);