Skip to content

fix(pos): make cart identity and append retries collision-safe - #293

Merged
khaira777 merged 18 commits into
mainfrom
fm/flocafe-255-fix
Aug 13, 2026
Merged

khaira777 merged 18 commits into
mainfrom
fm/flocafe-255-fix

Conversation

@khaira777

Copy link
Copy Markdown
Contributor

Intent

Implement only FloCafe issue #255, fix(pos): make cart identity and append retries collision-safe, from the current main baseline. Do not touch issue #241/Iran work or unrelated open issues. Reproduce and fix delimiter-joined cart identity collisions between distinct configurations, preserving every relevant product/add-on/option/note field and leading-zero semantics using a canonical unambiguous identity. Reproduce and fix the renderer reload/response-loss path where an append actually committed but a new idempotency key caused duplicate order items. Inspect and preserve the existing backend idempotency contract. Make the logical append retry key durable across the renderer reload/response-loss boundary, reuse it for the same logical attempt, reject mismatched payload reuse safely, and clear it only after confirmed completion while preserving API compatibility and cleanup behavior. Add behavioral regression tests for delimiter collisions, normal distinct carts, response loss after committed append followed by reload/retry, mismatched reuse, and cleanup/expiry, preferring non-Electron route/store tests and documenting any known Electron installation race if blocked. Keep the PR narrowly scoped to #255. Commit on the task branch. Run complete no-mistakes validation and, after checks-passed, publish a new PR without merging using a conventional title and body covering the full #255 delta, with bug and appropriate area labels. Keep #241/Iran untouched.

What Changed

  • Replaced delimiter-joined cart IDs with typed canonical identities that preserve product IDs, all selected add-on fields, notes, and leading-zero distinctions while normalizing equivalent cart lines.
  • Added durable, user-scoped append retry recovery across renderer reloads, with payload fingerprints, key reuse, legacy migration, expiry handling, and completion-safe cleanup; backend replays committed appends before mutable-order guards and rejects mismatched key reuse with 409.
  • Documented the append endpoint contract and added issue fix(pos): make cart identity and append retries collision-safe #255 regression coverage for cart collisions, response-loss retries, mismatches, cleanup, expiry, and storage failures.

Risk Assessment

⚠️ Medium: The change is scoped to #255 and preserves the reviewed replay and ownership invariants, but it introduces a substantial client-side persistent retry state machine that warrants the pipeline's dedicated validation.

Testing

After restoring local dependencies, both focused #255 behavioral suites and a live API/database response-loss replay scenario passed; evidence is saved above, the final diff is clean and scoped to #255 files, and no renderer screenshot was possible because this isolated environment had no available browser session.

Evidence: Issue #255 live replay result

Live replay evidence: canonical delimiter/leading-zero identities remain distinct; renderer recovery reused its key; replay after a split kept rows at 2; changed payload returned HTTP 409.

{
  "cartIdentity": {
    "delimiterConfigurationsAreDistinct": true,
    "leadingZeroProductIsDistinctFromNumeric": true
  },
  "rendererReload": {
    "initialKey": "renderer-retry-key",
    "recoveredKey": "renderer-retry-key",
    "sameLogicalAttemptReused": true
  },
  "appendResponseLossReplay": {
    "firstAppendStatus": 200,
    "retryAfterSplitStatus": 200,
    "responseItemCountsMatch": true,
    "orderItemRows": {
      "afterCommit": 2,
      "afterRetry": 2,
      "afterMismatchedRetry": 2
    },
    "mismatchedRetry": {
      "status": 409,
      "error": "Idempotency-Key was already used for a different order request"
    }
  }
}

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 3 issues found → auto-fixed (15) ✅
  • 🚨 main/routes/orders.ts:589 - The replay lookup runs before the waiter ownership check at line 599. A waiter presenting a matching key can therefore replay an append response for an order they do not own, including legacy records permitted by the existing compatibility query. Perform order lookup and authorization first, while keeping replay ahead of split/status guards.
  • ⚠️ main/routes/orders.ts:24 - The required intent says “preserving API compatibility,” but lines 21–25 change a supplied whitespace-only Idempotency-Key from the baseline’s “treat as absent” behavior to HTTP 400; the new regression test codifies this change. Confirm whether this intentional API break is allowed.
  • 🚨 frontend/src/lib/append-attempt.ts:186 - The required intent says to “clear it only after confirmed completion,” but a pending attempt is deleted whenever a different order or fingerprint is started, before any successful response. If the original append committed and its response was lost, changing the cart removes its only durable retry key and prevents later reconciliation. Retain/refuse unresolved attempts unless this abandonment behavior is explicitly authorized.

🔧 Fix: Fix auth, blank-key compatibility, pending retry retention (tests blocked)
1 error still open:

  • 🚨 frontend/src/lib/append-attempt.ts:48 - The required criterion says “Make the logical append retry key durable across the renderer reload/response-loss boundary,” but lines 43–49 continue after a failed localStorage write using only a per-renderer in-memory key. If the append commits and the response is lost while storage is unavailable/full, reload loses the key and a new retry can duplicate items. Persist durably or block the mutation when persistence fails.

🔧 Fix: Require durable retry storage; focused test blocked by missing ts-node
3 issues (1 error, 2 warnings) still open:

  • 🚨 frontend/src/app/(dashboard)/pos/page.tsx:272 - The criterion “Make the logical append retry key durable across the renderer reload/response-loss boundary” is not met for existing records: recovery reads only the new storage key, while the baseline stored pending appends under flo.postpaid.order.attempt. An upgrade/reload can therefore ignore and overwrite the old key, allowing duplicate items. Migrate old append records before creating new attempts.
  • ⚠️ frontend/src/lib/cart-identity.ts:50 - Raw add-on canonicalization distinguishes quantity: undefined from quantity: 1, although POS paths treat missing quantity as one. Held or legacy cart data can therefore create duplicate lines instead of merging equivalent add-ons. Normalize the default quantity before canonicalizing.
  • ⚠️ frontend/src/lib/append-attempt.ts:220 - If durable cleanup fails after a successful append, the in-memory tombstone disappears on reload and the old completed attempt blocks every different append until expiry because mismatches are rejected. Persist a completion marker or otherwise prevent cleanup failures from becoming unresolved blockers.

🔧 Fix: Migrate legacy retries, normalize addons, persist completion markers
2 issues (1 error, 1 warning) still open:

  • 🚨 frontend/src/lib/append-attempt.ts:182 - The legacy migration returns without moving records owned by another user, but the old append and new-order flows share flo.postpaid.order.attempt; POSPage.readPostpaidAttempt deletes records whose user differs. Cashier A’s committed response-loss append can therefore be deleted when cashier B starts a new order, defeating the required durable retry guarantee. Migrate recognized legacy append records to the recorded owner’s scoped key before other flows can remove them.
  • ⚠️ frontend/src/lib/cart-identity.ts:50 - Only undefined add-on quantities are normalized to one. Existing POS and backend paths coerce other falsy quantities such as 0 with || 1, so held/legacy data can create separate cart lines for configurations that serialize and price identically. Normalize the same default before canonicalization.

🔧 Fix: Normalize falsy add-on quantities in cart identity
1 error still open:

  • 🚨 frontend/src/lib/append-attempt.ts:203 - The required intent says “reuse it for the same logical attempt.” Legacy append records store numeric order_id in their fingerprint, but migration preserves that raw fingerprint while current fingerprints stringify the order ID. After automatic recovery fails once, retrying the same migrated payload reaches the mismatch check and throws instead of reusing the durable key. Normalize migrated fingerprints or compare normalized payloads.

🔧 Fix: Migrate legacy append retries and normalize retry fingerprints
4 issues (3 errors, 1 warning) still open:

  • 🚨 frontend/src/app/(dashboard)/orders/page.tsx:710 - The new durable helper is used by POSPage, but the sibling dashboard append flow still keeps its key only in a renderer ref. The criterion “Make the logical append retry key durable across the renderer reload/response-loss boundary” remains unmet: reload clears the ref, the retry creates a new key, and items can duplicate.
  • 🚨 frontend/src/lib/append-attempt.ts:217 - Migration removes the legacy record whenever any owner-scoped value exists, without verifying it is the same logical attempt. A stale, corrupt, or different-payload scoped record can therefore discard an unresolved legacy retry key, violating “clear it only after confirmed completion.” Preserve the legacy record unless the scoped copy is validated as equivalent.
  • 🚨 frontend/src/app/(dashboard)/pos/page.tsx:125 - If writing the scoped migration copy fails, the caller ignores that failure and reads the old shared slot directly. Another user can then delete it, or the new-order flow can overwrite it, losing the only retry key for a committed response-loss append. Fail closed until migration succeeds or preserve the legacy append record from other writers.
  • ⚠️ frontend/src/lib/append-attempt.ts:352 - The completion tombstone is only persisted when marker storage succeeds. If marker persistence and removal both fail, a confirmed append remains pending after reload and blocks different appends until expiry. Add a retryable/equivalent durable completion state or prevent this blocker.

🔧 Fix: Harden append migration and cleanup durability
2 warnings still open:

  • ⚠️ frontend/src/app/(dashboard)/pos/page.tsx:136 - The new catch throws on malformed/unreadable flo.postpaid.order.attempt instead of discarding it as the baseline did. A corrupt legacy order-attempt record can now make every postpaid checkout fail indefinitely, changing unrelated cleanup behavior. Preserve the prior discard path or explicitly confirm this fail-closed behavior.
  • ⚠️ frontend/src/lib/append-attempt.ts:317 - Migration of the pre-user-scoped append key ignores a failed removeItem. If the scoped copy is later confirmed and cleared, the durable unscoped copy remains; after reload it is migrated and replayed again, repeatedly blocking or reprocessing stale recovery. Verify/remove the source or persist equivalent completion state for both keys.

🔧 Fix: Preserve malformed cleanup and verify append migration removals
2 warnings still open:

  • ⚠️ frontend/src/lib/append-attempt.ts:321 - migrateLegacyAppendAttempt throws when the shared legacy append belongs to user A but A already has a non-equivalent scoped attempt. readUserAttempt invokes migration before checking the requested user, so an unrelated user B’s append/new-order path also fails until the conflict expires. Preserve both A records while allowing foreign callers to proceed safely.
  • ⚠️ frontend/src/lib/append-attempt.ts:432 - If writing both completion states fails and removeItem also fails, the confirmed attempt remains durable without a tombstone. Reload then treats it as pending and blocks mismatched appends until expiry. Ensure this combined storage-failure path has durable completion state or cannot become a retry blocker.

🔧 Fix: Preserve retry conflicts and harden completion durability
2 warnings still open:

  • ⚠️ frontend/src/lib/append-attempt.ts:469 - The required criterion is to “clear it only after confirmed completion.” If both completion writes fail and removeItem also fails, lines 454–470 leave the original pending record without a durable completion marker. After reload, a different append is blocked for up to 24 hours. Preserve a durable completion state or prevent this confirmed attempt from remaining a retry blocker.
  • ⚠️ tests/issue-255-pos-cart-retry.test.ts:56 - This new assertion does not reproduce the old delimiter collision: the baseline IDs for extra-a/b-c and extra/a-b-c are different. Use a genuinely colliding pair, such as the second note a:1-b-c, so the regression fails before the fix.

🔧 Fix: Harden completion fallback and delimiter collision coverage
3 issues (2 errors, 1 warning) still open:

  • 🚨 frontend/src/lib/append-attempt.ts:496 - The required durable-retry/cleanup criterion is still violated. If both completion writes fail at lines 483–493, line 496 can return false while the in-memory tombstone hides the pending record only in the current renderer; after reload, the durable attempt is read as pending and blocks every different append until expiry despite the append having completed. Persist and verify a durable completion state, or make cleanup retryable before allowing this state.
  • 🚨 frontend/src/app/(dashboard)/pos/page.tsx:129 - The requirement to keep the append retry key durable across reloads remains reachable through the legacy conflict path. When a shared legacy append belongs to a user who already has a non-equivalent scoped attempt, migration returns the legacy record without moving/removing it (helper line 303). readPostpaidAttempt then returns null at line 130, and the postpaid new-order flow can overwrite the shared flo.postpaid.order.attempt at line 150, destroying the unresolved legacy retry key for that user. Preserve the legacy record at the shared boundary or prevent this writer until migration is resolved.
  • ⚠️ frontend/src/lib/append-attempt.ts:262 - This contradicts the required preservation of cleanup behavior for legacy state. A corrupt shared record containing JSON null parses successfully, then line 262 dereferences parsed.userId and throws; the POS caller converts that into Unable to recover append retry state instead of reaching the prior cleanup path. Every postpaid checkout can therefore fail indefinitely until the corrupt storage entry is manually removed. Guard non-object parsed values and preserve the baseline discard behavior.

🔧 Fix: Harden completion recovery and legacy conflict handling
3 errors still open:

  • 🚨 frontend/src/lib/append-attempt.ts:532 - If both durable completion writes fail and removal also fails, the in-memory tombstone hides the original attempt only until reload. The durable pending record then blocks different appends until expiry and may be retried despite confirmed completion, violating the required durable reload boundary and cleanup criterion. Persist a retryable durable completion state or prevent this state.
  • 🚨 frontend/src/app/(dashboard)/pos/page.tsx:135 - When user A has a conflicting shared legacy append and scoped retry, migration returns A’s legacy record unchanged for unrelated user B. readPostpaidAttempt treats that as null, after which B’s new-order flow writes the same shared key and overwrites A’s unresolved retry before confirmed completion. Protect the shared record at this writer boundary or migrate it safely first.
  • 🚨 frontend/src/lib/append-attempt.ts:13 - Appending .completed to the encoded attempt key creates a namespace collision: user IDs cashier and cashier.completed produce one user’s completion key as the other user’s attempt key because periods remain unescaped. Completing one append can overwrite or suppress another user’s pending retry. Use disjoint key namespaces.

🔧 Fix: Isolated completion keys and protected legacy retries
3 issues (2 errors, 1 warning) still open:

  • 🚨 frontend/src/app/(dashboard)/pos/page.tsx:135 - When a shared append record for user A conflicts with A’s scoped retry, migration returns it unchanged for user B; readPostpaidAttempt then throws because the shared slot remains. User B’s normal postpaid order flow is blocked until expiry. Preserve A’s records while allowing B to proceed safely.
  • 🚨 frontend/src/lib/append-attempt.ts:539 - If the completion marker write, fallback write, and attempt removal all fail, clearAppendAttempt leaves the confirmed append without durable completion state. After reload, the old key is recovered as pending, so a different append is rejected or the old request is retried. This violates the required durable cleanup/recovery behavior.
  • ⚠️ frontend/src/lib/append-attempt.ts:543 - confirmedAppendTombstones retains full fingerprints, including item and note payloads, in a module-level map. Successful cleanup removes the durable attempt, so these entries are never queried and deleted; a long-running POS renderer accumulates completed append payloads. Bound or independently expire this map, or store a compact bounded key.

🔧 Fix: Isolated completion state and protected legacy order retries
2 errors still open:

  • 🚨 frontend/src/lib/append-attempt.ts:103 - The required criterion is “Make the logical append retry key durable across the renderer reload/response-loss boundary.” setItem accepts success from any fallback store, but getItem always prefers the first non-null store. If localStorage retains an older value while its write fails, sessionStorage/cookie receives the new attempt but a reload reads the stale localStorage value, losing or blocking recovery. Use an authoritative verified store or fail closed before sending.
  • 🚨 frontend/src/lib/append-attempt.ts:570 - The required criterion is to “clear it only after confirmed completion while preserving API compatibility and cleanup behavior.” If completion-marker writes and attempt removal all fail, clearAppendAttempt returns false and leaves the confirmed attempt durable without a marker. After reload, it is treated as pending and can block different appends for 24 hours or replay the already-committed request. Establish durable completion state or otherwise make this confirmed-completion failure recoverable.

🔧 Fix: Hardened retry storage authority and completion recovery
3 issues (2 errors, 1 warning) still open:

  • 🚨 frontend/src/lib/append-attempt.ts:404 - Legacy migration treats any numeric scoped createdAt as equivalent. If a fresh shared retry coexists with an expired scoped copy, line 411 removes the fresh source; parsing then removes the expired scoped copy, leaving only an in-memory attempt and allowing a reload to generate a duplicate-prone key. Validate freshness/equivalent timestamps or persist the fresh copy before removal.
  • 🚨 frontend/src/lib/append-attempt.ts:160 - An unavailable primary storage can make removeItem return false even when session/cookie fallback storage durably holds the completion marker. ensureCompletionStorage then rejects every later different append during probe cleanup, so a confirmed append can block sales until storage recovers or expiry. Make the verified fallback authoritative or exclude unavailable stores from cleanup verification.
  • ⚠️ frontend/src/lib/append-attempt.ts:96 - The cookie fallback stores the full append payload, including item names and notes, at Path=/; because setItem writes every configured store, this payload is sent in Cookie headers on every same-origin API request, increasing header size and exposing order data to server/proxy logs. Use the cookie only when other durable stores fail and scope/minimize its contents.

🔧 Fix: Hardened migration freshness, fallback cleanup, and cookie privacy
4 issues (2 errors, 2 warnings) still open:

  • 🚨 frontend/src/lib/append-attempt.ts:137 - The required criterion “Make the logical append retry key durable across the renderer reload/response-loss boundary” is still violated when the primary store is unreadable: readPersisted records an unverified read but returns the fallback value, and getOrCreateAppendAttempt proceeds with a new fallback-only key. If localStorage hides an older committed attempt while sessionStorage is empty, the new request can duplicate items. Fail closed on an unverified attempt read or establish an authoritative store before sending.
  • 🚨 frontend/src/lib/append-attempt.ts:690 - The criterion “clear it only after confirmed completion” remains violated when completion-marker writes and attempt removal all fail. clearAppendAttempt returns false while leaving the durable pending attempt unchanged; after reload it is treated as unresolved, blocking different appends or replaying a confirmed append until expiry. Provide durable retryable completion state or prevent this post-confirmation state.
  • ⚠️ frontend/src/app/(dashboard)/pos/page.tsx:139 - After migrating any legacy append owned by another user, this early return skips reading the current user's scoped postpaid-order retry. A user with a committed-but-response-lost new-order attempt can therefore generate a new idempotency key and create a duplicate order when an unrelated legacy append is migrated. Continue loading the current user's postpaid attempt after append migration.
  • ⚠️ frontend/src/lib/append-attempt.ts:254 - The collision-safety requirement is weakened by storing only a 32-bit FNV hash in the cookie completion marker and in-memory tombstone. Two distinct fingerprints with the same hash are treated as the same completed attempt when the same idempotency key is present, allowing mismatched reuse to be suppressed instead of rejected. Use an exact fingerprint or a collision-resistant representation for this fallback path.

🔧 Fix: Fail closed on uncertain retry recovery
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • npm run test:issue-255-cart (initially blocked by absent local dependencies)
  • npm ci (lockfile-pinned local test setup; removed node_modules afterward)
  • npm run test:issue-255-cart
  • npm run test:issue-255-append
  • node - <<'NODE' live Express/SQLite reproduction: cart identity, reload key reuse, committed append replay after split, and mismatched retry rejection
  • git diff --check ae4c31e...2a029049 and final targeted-diff inspection
  • Attempted in-app browser renderer capture; no browser session was available.
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@khaira777
khaira777 requested a review from itsbkm as a code owner August 13, 2026 20:49
@khaira777
khaira777 merged commit 8c0999d into main Aug 13, 2026
5 checks passed
@khaira777 khaira777 linked an issue Aug 13, 2026 that may be closed by this pull request
@khaira777
khaira777 deleted the fm/flocafe-255-fix branch August 13, 2026 23:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(pos): make cart identity and append retries collision-safe

1 participant