You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[Due for payment 2026-11-30] [$175] Scan - Multiple ReplaceReceipt API calls triggered after offline replacements #107135
Awaiting PaymentAuto-added when associated PR is deployed to productionBugSomething is broken. Auto assigns a BugZero manager.DailyKSv2ExternalAdded to denote the issue can be worked on by a contributor
Version Number: 9.5.40-0 Reproducible in staging?: Yes Reproducible in production?: yes If this was caught during regression testing, add the test name, ID and link from BrowserStack:https://github.com/Expensify/Expensify/issues/619557 Email or phone of affected tester (no customers): Issue reported by: Applause Internal Team Bug source: Device used: App Component:
changed the title [-]Scan - Multiple ReplaceReceipt API calls triggered after offline replacements[/-][+][$175] Scan - Multiple ReplaceReceipt API calls triggered after offline replacements[/+]on Nov 17, 2026
Each offline receipt replacement is queued independently; deleting the receipt does not cancel those queued uploads. Reconnecting therefore sends every replacement, followed by DetachReceipt.
Confidence: medium. The mechanism is verified in current code, but I have not reproduced the browser flow or verified the reported release.
Code evidence and alternatives checked
Receipt.ts:477–486: replacement uses ordinary API.write, without conflict resolution.
SequentialQueue.ts:881–904: requests without a conflict resolver are saved individually and remain queued offline.
Receipt.ts:218–226: deletion queues a separate DetachReceipt; it does not remove earlier replacements.
Thus, replacing with A → B → C → deleting produces three replacement writes followed by detach. Duplicate callbacks or network retries are not necessary to explain the reported count, although neither was excluded through runtime observation.
What changes do you think we should make in order to solve the problem?
First clarify the expected behavior after deletion. One replacement followed by detach matches the issue’s expectation; sending only detach could also preserve the final “no receipt” state. Those policies have different receipt-history implications.
If retaining the latest replacement is intended, introduce receipt-specific, transaction-scoped consolidation of unsent replacements:
Retain the newest receipt without affecting other expenses or active uploads.
Preserve operation order around deletion and other dependent edits.
Reconcile superseded receipt-history entries and success/failure updates.
Ensure failure cannot restore an intermediate receipt whose upload was discarded.
Do not use a simple queue-deduplication helper alone.
Why consolidation needs regression coverage
Every replacement can create separate optimistic receipt-added/removed actions with corresponding completion updates: Receipt.ts:425–484. Dropping requests alone would leave their local history updates unreconciled.
Existing offline-receipt audit coverage expects matching server action IDs, but does not establish whether every intermediate offline replacement must be preserved.
Add coverage for repeated replacements → deletion → reconnect, two different expenses, active uploads, history cleanup, and replacement/detach failures.
What alternative solutions did you explore? (Optional)
Keeping all operations preserves the current per-operation history, but does not meet the requested call-count expectation. Cancelling all unsent uploads after deletion is another option, subject to confirming history and rollback requirements.
Next Steps for Contributor+ team: To accept: After confirming deletion/history semantics, @MelvinBot implement [this](https://github.com/Expensify/App/issues/107135) to create a draft PR. To refine:@MelvinBot <your feedback> To reject: Explain why you are rejecting Melvin's proposal.
Please re-state the problem that we are trying to solve in this issue.
When a user replaces an expense receipt multiple times while offline and then reconnects, every queued ReplaceReceipt API request fires sequentially instead of only the latest effective change (and if the user subsequently deletes the receipt offline via detachReceipt, all queued ReplaceReceipt uploads still execute before DetachReceipt).
replaceReceipt (lines 229-487, calling API.write(WRITE_COMMANDS.REPLACE_RECEIPT, ...) at line 486) passes noRequestConflictResolver (checkAndFixConflictingRequest). Each offline replacement appends a separate ReplaceReceipt request to PersistedRequests.
detachReceipt (lines 73-227, calling API.write(WRITE_COMMANDS.DETACH_RECEIPT, ...) at line 226) also passes noRequestConflictResolver, so deleting the receipt offline leaves all prior queued ReplaceReceipt requests in the queue ahead of DetachReceipt.
Additionally, a naive single-line queue deduplication helper alone would introduce regressions here because:
Each replaceReceipt call reads oldReceipt = transaction?.receipt ?? {} (line 256) and builds its failureData rollback from the current optimistic Onyx state (lines 341, 364-368, 385-395, 463-470). Simply overwriting queued ReplaceReceiptSome initial fixes and code style updates #1 with ReplaceReceiptFix spaces #2 loses the pre-offlineoldReceipt, violations, snapshot receipt, and transactionThreadReport timestamps (meaning a failure on reconnect would roll back to an unsent intermediate offline receipt instead of the original server receipt). Same for detachReceipt, whose failureData (line 128) snapshots ...(transaction ?? null).
Each non-isSameReceiptreplaceReceipt mints fresh optimisticReceiptAddedActionID / optimisticReceiptRemovedActionID entries (lines 274-277, 425-472) in ${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadReportID}, which would stay orphaned/pending in Onyx when earlier queued ReplaceReceipt requests are superseded.
Scanning the queue must scope by transactionID and stop at any DETACH_RECEIPT boundary so replacements separated by a delete (Replace -> Detach -> Replace) are never collapsed across the boundary.
What changes do you think we should make in order to solve the problem?
Add receipt queue conflict resolvers in src/libs/actions/RequestConflictUtils.ts (keeping them pure, since prepareRequest calls checkAndFixConflictingRequest read-only at src/libs/API/makeRequest.ts:44-48 before SequentialQueue.push runs it authoritatively at src/libs/Network/SequentialQueue.ts:884):
Add a helper findTrailingReplaceReceiptIndices(persistedRequests, transactionID) that scans backward from the end of persistedRequests, collects indices of WRITE_COMMANDS.REPLACE_RECEIPT matching request.data?.transactionID === transactionID, and stops if it encounters a boundary request (WRITE_COMMANDS.DETACH_RECEIPT for the same transactionID).
Add resolveDetachReceiptConflicts(persistedRequests, transactionID) so deleting a receipt while offline also cancels trailing superseded REPLACE_RECEIPT requests for that transactionID instead of uploading discarded files first:
(Design note for Step 6 — @DylanDylann, please confirm your preference between the two behaviors here: cancelling trailing REPLACE_RECEIPTs in detachReceipt yields 0 ReplaceReceipt + 1 DetachReceipt so discarded offline files are never uploaded/SmartScanned right before deletion; if audit/business rules strictly require recording the final replacement before deletion matching the literal "One ReplaceReceipt API call" wording, we simply omit resolveDetachReceiptConflicts on detachReceipt and get 1 ReplaceReceipt + 1 DetachReceipt.)
Preserve pre-offline failureData baseline and clean up superseded audit actions in src/libs/actions/IOU/Receipt.ts:
Before calling API.write, inspect the trailing queued REPLACE_RECEIPT requests returned by findTrailingReplaceReceiptIndices(getAllPersistedRequests(), transactionID):
Preserve pre-offline rollback baseline: Copy the earliest superseded REPLACE_RECEIPT's pre-offline failureData updates for ${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}, ${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}, ${ONYXKEYS.COLLECTION.SNAPSHOT}*, and ${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReportID} into the new request's failureData (replacing the intermediate-receipt rollback entries generated from current Onyx state, while keeping the active request's error payload and audit-action rollback entries). Because each replacement inherits the earliest baseline, even 3+ offline replacements (or offline replaceReceipt -> detachReceipt) still roll back cleanly to the true pre-offline receipt (oldReceipt) on failure.
Clean up superseded MODIFIED_EXPENSE audit actions & handle isSameReceipt:
When replaceReceipt (!isSameReceipt) or detachReceipt supersedes queued REPLACE_RECEIPT request(s), collect any distinct reportActionID / receiptRemovedReportActionID from those superseded requests' data and merge {[supersededID]: null} into ${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadReportID} in optimisticData so intermediate audit actions do not remain orphaned/pending in chat.
Also guard two edge cases when a queued REPLACE_RECEIPT exists:
If replaceReceipt is called with isSameReceipt: true (crop/rotate) while a non-isSameReceipt replacement is still queued, preserve isSameReceipt: false and reuse the prior request's reportActionID / receiptRemovedReportActionID (so rotating a newly chosen offline replacement does not drop its audit trail).
If the earliest superseded REPLACE_RECEIPT originally started from a receipt-less transaction (!earliestRequest.data?.receiptRemovedReportActionID and !earliestRequest.data?.isSameReceipt), avoid minting a new receiptRemovedReportActionID on subsequent offline replacements of that same unsent receipt.
Pass {checkAndFixConflictingRequest: (persistedRequests) => resolveReplaceReceiptConflicts(persistedRequests, transactionID)} as the 4th argument to API.write(WRITE_COMMANDS.REPLACE_RECEIPT, ...) (Receipt.ts:486), and {checkAndFixConflictingRequest: (persistedRequests) => resolveDetachReceiptConflicts(persistedRequests, transactionID)} to API.write(WRITE_COMMANDS.DETACH_RECEIPT, ...) (Receipt.ts:226).
Update & add tests:
tests/unit/RequestConflictUtilsTest.ts: Add unit tests for resolveReplaceReceiptConflicts (pushes when empty/different transactionID, replaces single queued REPLACE_RECEIPT, stops at a DETACH_RECEIPT boundary, handles multiple queued REPLACE_RECEIPTs) and resolveDetachReceiptConflicts (deletes trailing REPLACE_RECEIPTs and pushes DETACH_RECEIPT).
tests/actions/IOUTest/ReceiptTest.ts:
Update the 3 existing strict 3-argument expect(writeSpy).toHaveBeenCalledWith(...) checks at lines 383, 635, and 1142 to include the 4th conflictResolver argument (expect.objectContaining({checkAndFixConflictingRequest: expect.any(Function)})).
Add tests verifying offline sequential replaceReceipt calls collapse to one queued REPLACE_RECEIPT while preserving pre-offline oldReceipt in failureData, cleaning up superseded audit actions, preserving audit IDs when cropping/rotating (isSameReceipt: true) after an offline replacement, and cancelling trailing REPLACE_RECEIPTs when detachReceipt runs offline.
What alternative solutions did you explore? (Optional)
Using the generic writeWithNoDuplicatesConflictAction (src/libs/API/index.ts:80-95) with a command === WRITE_COMMANDS.REPLACE_RECEIPT matcher is insufficient: it neither bounds the scan at DETACH_RECEIPT, preserves the earliest pre-offline failureData baseline across chained offline edits, cleans up orphaned optimistic REPORT_ACTIONS, nor handles detachReceipt superseding pending offline replaceReceipt uploads.
Awaiting PaymentAuto-added when associated PR is deployed to productionBugSomething is broken. Auto assigns a BugZero manager.DailyKSv2ExternalAdded to denote the issue can be worked on by a contributor
Activity
expensify-chore-bot commentedon Nov 17, 2026
Triggered auto assignment to Contributor-plus team member for initial proposal review - @DylanDylann (
External)[-]Scan - Multiple ReplaceReceipt API calls triggered after offline replacements[/-][+][$175] Scan - Multiple ReplaceReceipt API calls triggered after offline replacements[/+]expensify-chore-bot commentedon Nov 17, 2026
Job added to Upwork: https://www.upwork.com/jobs/~022122731030780167209
MelvinBot commentedon Nov 17, 2026
Proposal
What is the root cause of that problem?
Each offline receipt replacement is queued independently; deleting the receipt does not cancel those queued uploads. Reconnecting therefore sends every replacement, followed by
DetachReceipt.Confidence: medium. The mechanism is verified in current code, but I have not reproduced the browser flow or verified the reported release.
Code evidence and alternatives checked
API.write, without conflict resolution.DetachReceipt; it does not remove earlier replacements.Thus, replacing with A → B → C → deleting produces three replacement writes followed by detach. Duplicate callbacks or network retries are not necessary to explain the reported count, although neither was excluded through runtime observation.
What changes do you think we should make in order to solve the problem?
First clarify the expected behavior after deletion. One replacement followed by detach matches the issue’s expectation; sending only detach could also preserve the final “no receipt” state. Those policies have different receipt-history implications.
If retaining the latest replacement is intended, introduce receipt-specific, transaction-scoped consolidation of unsent replacements:
Do not use a simple queue-deduplication helper alone.
Why consolidation needs regression coverage
Every replacement can create separate optimistic receipt-added/removed actions with corresponding completion updates: Receipt.ts:425–484. Dropping requests alone would leave their local history updates unreconciled.
Existing offline-receipt audit coverage expects matching server action IDs, but does not establish whether every intermediate offline replacement must be preserved.
Add coverage for repeated replacements → deletion → reconnect, two different expenses, active uploads, history cleanup, and replacement/detach failures.
What alternative solutions did you explore? (Optional)
Keeping all operations preserves the current per-operation history, but does not meet the requested call-count expectation. Cancelling all unsent uploads after deletion is another option, subject to confirming history and rollback requirements.
Related issue: A failed expense edit restores an old copy and erases a newer receipt or description concerns overlapping rollback behavior, not a confirmed duplicate.
Next Steps for Contributor+ team:
To accept: After confirming deletion/history semantics,
@MelvinBot implement [this](https://github.com/Expensify/App/issues/107135)to create a draft PR.To refine:
@MelvinBot <your feedback>To reject: Explain why you are rejecting Melvin's proposal.
view run
andregrunert-ctrl commentedon Nov 17, 2026
Contributor details
Your Expensify account email: andregrunert@gmail.com
Upwork Profile Link: https://www.upwork.com/freelancers/~015c92a110b06ee5b3
Proposal
Please re-state the problem that we are trying to solve in this issue.
When a user replaces an expense receipt multiple times while offline and then reconnects, every queued
ReplaceReceiptAPI request fires sequentially instead of only the latest effective change (and if the user subsequently deletes the receipt offline viadetachReceipt, all queuedReplaceReceiptuploads still execute beforeDetachReceipt).What is the root cause of that problem?
In
src/libs/actions/IOU/Receipt.ts:replaceReceipt(lines 229-487, callingAPI.write(WRITE_COMMANDS.REPLACE_RECEIPT, ...)at line486) passes noRequestConflictResolver(checkAndFixConflictingRequest). Each offline replacement appends a separateReplaceReceiptrequest toPersistedRequests.detachReceipt(lines 73-227, callingAPI.write(WRITE_COMMANDS.DETACH_RECEIPT, ...)at line226) also passes noRequestConflictResolver, so deleting the receipt offline leaves all prior queuedReplaceReceiptrequests in the queue ahead ofDetachReceipt.Additionally, a naive single-line queue deduplication helper alone would introduce regressions here because:
replaceReceiptcall readsoldReceipt = transaction?.receipt ?? {}(line 256) and builds itsfailureDatarollback from the current optimistic Onyx state (lines 341,364-368,385-395,463-470). Simply overwriting queuedReplaceReceiptSome initial fixes and code style updates #1 withReplaceReceiptFix spaces #2 loses the pre-offlineoldReceipt, violations, snapshot receipt, andtransactionThreadReporttimestamps (meaning a failure on reconnect would roll back to an unsent intermediate offline receipt instead of the original server receipt). Same fordetachReceipt, whosefailureData(line 128) snapshots...(transaction ?? null).isSameReceiptreplaceReceiptmints freshoptimisticReceiptAddedActionID/optimisticReceiptRemovedActionIDentries (lines 274-277,425-472) in${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadReportID}, which would stay orphaned/pending in Onyx when earlier queuedReplaceReceiptrequests are superseded.transactionIDand stop at anyDETACH_RECEIPTboundary so replacements separated by a delete (Replace -> Detach -> Replace) are never collapsed across the boundary.What changes do you think we should make in order to solve the problem?
Add receipt queue conflict resolvers in
src/libs/actions/RequestConflictUtils.ts(keeping them pure, sinceprepareRequestcallscheckAndFixConflictingRequestread-only atsrc/libs/API/makeRequest.ts:44-48beforeSequentialQueue.pushruns it authoritatively atsrc/libs/Network/SequentialQueue.ts:884):findTrailingReplaceReceiptIndices(persistedRequests, transactionID)that scans backward from the end ofpersistedRequests, collects indices ofWRITE_COMMANDS.REPLACE_RECEIPTmatchingrequest.data?.transactionID === transactionID, and stops if it encounters a boundary request (WRITE_COMMANDS.DETACH_RECEIPTfor the sametransactionID).resolveReplaceReceiptConflicts(persistedRequests, transactionID):resolveDetachReceiptConflicts(persistedRequests, transactionID)so deleting a receipt while offline also cancels trailing supersededREPLACE_RECEIPTrequests for thattransactionIDinstead of uploading discarded files first:(Design note for Step 6 —
@DylanDylann, please confirm your preference between the two behaviors here: cancelling trailingREPLACE_RECEIPTs indetachReceiptyields0 ReplaceReceipt + 1 DetachReceiptso discarded offline files are never uploaded/SmartScanned right before deletion; if audit/business rules strictly require recording the final replacement before deletion matching the literal"One ReplaceReceipt API call"wording, we simply omitresolveDetachReceiptConflictsondetachReceiptand get1 ReplaceReceipt + 1 DetachReceipt.)Preserve pre-offline
failureDatabaseline and clean up superseded audit actions insrc/libs/actions/IOU/Receipt.ts:API.write, inspect the trailing queuedREPLACE_RECEIPTrequests returned byfindTrailingReplaceReceiptIndices(getAllPersistedRequests(), transactionID):REPLACE_RECEIPT's pre-offlinefailureDataupdates for${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID},${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID},${ONYXKEYS.COLLECTION.SNAPSHOT}*, and${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReportID}into the new request'sfailureData(replacing the intermediate-receipt rollback entries generated from current Onyx state, while keeping the active request's error payload and audit-action rollback entries). Because each replacement inherits the earliest baseline, even 3+ offline replacements (or offlinereplaceReceipt->detachReceipt) still roll back cleanly to the true pre-offline receipt (oldReceipt) on failure.MODIFIED_EXPENSEaudit actions & handleisSameReceipt:replaceReceipt(!isSameReceipt) ordetachReceiptsupersedes queuedREPLACE_RECEIPTrequest(s), collect any distinctreportActionID/receiptRemovedReportActionIDfrom those superseded requests'dataand merge{[supersededID]: null}into${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadReportID}inoptimisticDataso intermediate audit actions do not remain orphaned/pending in chat.REPLACE_RECEIPTexists:replaceReceiptis called withisSameReceipt: true(crop/rotate) while a non-isSameReceiptreplacement is still queued, preserveisSameReceipt: falseand reuse the prior request'sreportActionID/receiptRemovedReportActionID(so rotating a newly chosen offline replacement does not drop its audit trail).REPLACE_RECEIPToriginally started from a receipt-less transaction (!earliestRequest.data?.receiptRemovedReportActionIDand!earliestRequest.data?.isSameReceipt), avoid minting a newreceiptRemovedReportActionIDon subsequent offline replacements of that same unsent receipt.{checkAndFixConflictingRequest: (persistedRequests) => resolveReplaceReceiptConflicts(persistedRequests, transactionID)}as the 4th argument toAPI.write(WRITE_COMMANDS.REPLACE_RECEIPT, ...)(Receipt.ts:486), and{checkAndFixConflictingRequest: (persistedRequests) => resolveDetachReceiptConflicts(persistedRequests, transactionID)}toAPI.write(WRITE_COMMANDS.DETACH_RECEIPT, ...)(Receipt.ts:226).Update & add tests:
tests/unit/RequestConflictUtilsTest.ts: Add unit tests forresolveReplaceReceiptConflicts(pushes when empty/differenttransactionID, replaces single queuedREPLACE_RECEIPT, stops at aDETACH_RECEIPTboundary, handles multiple queuedREPLACE_RECEIPTs) andresolveDetachReceiptConflicts(deletes trailingREPLACE_RECEIPTs and pushesDETACH_RECEIPT).tests/actions/IOUTest/ReceiptTest.ts:expect(writeSpy).toHaveBeenCalledWith(...)checks atlines 383,635, and1142to include the 4thconflictResolverargument (expect.objectContaining({checkAndFixConflictingRequest: expect.any(Function)})).replaceReceiptcalls collapse to one queuedREPLACE_RECEIPTwhile preserving pre-offlineoldReceiptinfailureData, cleaning up superseded audit actions, preserving audit IDs when cropping/rotating (isSameReceipt: true) after an offline replacement, and cancelling trailingREPLACE_RECEIPTs whendetachReceiptruns offline.What alternative solutions did you explore? (Optional)
Using the generic
writeWithNoDuplicatesConflictAction(src/libs/API/index.ts:80-95) with acommand === WRITE_COMMANDS.REPLACE_RECEIPTmatcher is insufficient: it neither bounds the scan atDETACH_RECEIPT, preserves the earliest pre-offlinefailureDatabaseline across chained offline edits, cleans up orphaned optimisticREPORT_ACTIONS, nor handlesdetachReceiptsuperseding pending offlinereplaceReceiptuploads.melvin-bot commentedon Nov 17, 2026
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
DylanDylann commentedon Nov 17, 2026
I’m at full capacity, reassign this to another C+
23 remaining items
expensify-chore-bot commentedon Nov 29, 2026
Triggered auto assignment to @mallenexpensify (
Awaiting Payment)expensify-chore-bot commentedon Nov 29, 2026
Payment Summary
Resolving PRs:
Collapse unsent receipt replacements while preserving audit history #107358
Reviewer: @ikevin127 owed $175 via NewDot
BugZero Checklist (@mallenexpensify)
mallenexpensify commentedon Dec 2, 2026
Matt's AI agent:
Will pay tomorrow, apologies for the delay
mallenexpensify commentedon Dec 2, 2026
Payment Summary
Contributor+: @ikevin127 due $175 via NewDot