Repository navigation
fix(pos): make cart identity and append retries collision-safe - #293
Merged
Merged
Conversation
… retention (tests blocked)
…ked by missing ts-node
…t completion markers
…and cookie privacy
khaira777
force-pushed
the
fm/flocafe-255-fix
branch
from
August 13, 2026 20:55
7132296 to
fb0e84e
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
409.Risk Assessment
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.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 underflo.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 distinguishesquantity: undefinedfromquantity: 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 shareflo.postpaid.order.attempt;POSPage.readPostpaidAttemptdeletes 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- Onlyundefinedadd-on quantities are normalized to one. Existing POS and backend paths coerce other falsy quantities such as0with|| 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 numericorder_idin 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/unreadableflo.postpaid.order.attemptinstead 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 failedremoveItem. 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-migrateLegacyAppendAttemptthrows when the shared legacy append belongs to user A but A already has a non-equivalent scoped attempt.readUserAttemptinvokes 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 andremoveItemalso 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 andremoveItemalso 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 forextra-a/b-candextra/a-b-care different. Use a genuinely colliding pair, such as the second notea: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 returnfalsewhile 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).readPostpaidAttemptthen returnsnullat line 130, and the postpaid new-order flow can overwrite the sharedflo.postpaid.order.attemptat 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 JSONnullparses successfully, then line 262 dereferencesparsed.userIdand throws; the POS caller converts that intoUnable to recover append retry stateinstead 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.readPostpaidAttempttreats 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.completedto the encoded attempt key creates a namespace collision: user IDscashierandcashier.completedproduce 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;readPostpaidAttemptthen 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,clearAppendAttemptleaves 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-confirmedAppendTombstonesretains 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.”setItemaccepts success from any fallback store, butgetItemalways 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,clearAppendAttemptreturns 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 scopedcreatedAtas 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 makeremoveItemreturn false even when session/cookie fallback storage durably holds the completion marker.ensureCompletionStoragethen 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, atPath=/; becausesetItemwrites 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:readPersistedrecords an unverified read but returns the fallback value, andgetOrCreateAppendAttemptproceeds 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.clearAppendAttemptreturnsfalsewhile 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; removednode_modulesafterward)npm run test:issue-255-cartnpm run test:issue-255-appendnode - <<'NODE'live Express/SQLite reproduction: cart identity, reload key reuse, committed append replay after split, and mismatched retry rejectiongit diff --check ae4c31e...2a029049and final targeted-diff inspectionAttempted 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.