Skip to content

[Due for payment 2026-11-30] [$175] Scan - Multiple ReplaceReceipt API calls triggered after offline replacements #107135

Done

Description

@lanitochka17

If you haven’t already, check out our contributing guidelines for onboarding and email contributors@expensify.com to request to join our Slack channel!


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:

Action Performed:

  1. Go to https://staging.new.expensify.com/
  2. Go to workspace chat
  3. Create a scan request with a valid receipt
  4. After scanning, go offline
  5. Replace the receipt multiple times
  6. Delete the receipt
  7. Open DevTools > Network tab
  8. Go online

Expected Result:

One ReplaceReceipt API call triggered on reconnection after offline replacements.

Actual Result:

Multiple ReplaceReceipt API calls triggered on reconnection after offline replacements.

Workaround:

Unknown

Platforms:

  • Android: App
  • Android: mWeb Chrome
  • iOS: App
  • iOS: mWeb Safari
  • iOS: mWeb Chrome
  • Windows: Chrome
  • MacOS: Chrome / Safari

Screenshots/Videos

Bug7288900_1792230705977.Video_1.mp4

View all open jobs on GitHub

Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @mallenexpensify

Activity

  1. added
    Daily
    Bug
    on Nov 17, 2026
  2. added
    External
    on Nov 17, 2026
  3. expensify-chore-bot commented on Nov 17, 2026

    @expensify-chore-bot

    Triggered auto assignment to Contributor-plus team member for initial proposal review - @DylanDylann (External)

  4. 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
  5. expensify-chore-bot commented on Nov 17, 2026

    @expensify-chore-bot
  6. MelvinBot commented on Nov 17, 2026

    @MelvinBot
    Contributor

    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

    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.

    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

  7. andregrunert-ctrl commented on Nov 17, 2026

    @andregrunert-ctrl

    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 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).

    What is the root cause of that problem?

    In src/libs/actions/IOU/Receipt.ts:

    1. replaceReceipt (lines 229-487, calling API.write(WRITE_COMMANDS.REPLACE_RECEIPT, ...) at line 486) passes no RequestConflictResolver (checkAndFixConflictingRequest). Each offline replacement appends a separate ReplaceReceipt request to PersistedRequests.
    2. detachReceipt (lines 73-227, calling API.write(WRITE_COMMANDS.DETACH_RECEIPT, ...) at line 226) also passes no RequestConflictResolver, 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 ReplaceReceipt Some initial fixes and code style updates #1 with ReplaceReceipt Fix spaces #2 loses the pre-offline oldReceipt, 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-isSameReceipt replaceReceipt 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?

    1. 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 resolveReplaceReceiptConflicts(persistedRequests, transactionID):
        function resolveReplaceReceiptConflicts<TKey extends OnyxKey>(persistedRequests: Array<OnyxRequest<TKey>>, transactionID: string): ConflictActionData {
            const trailingIndices = findTrailingReplaceReceiptIndices(persistedRequests, transactionID);
            if (trailingIndices.length === 0) {
                return {conflictAction: {type: 'push'}};
            }
            if (trailingIndices.length === 1) {
                return {
                    conflictAction: {
                        type: 'replace',
                        index: trailingIndices[0],
                    },
                };
            }
            return {
                conflictAction: {
                    type: 'delete',
                    indices: trailingIndices,
                    pushNewRequest: true,
                },
            };
        }
      • 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:
        function resolveDetachReceiptConflicts<TKey extends OnyxKey>(persistedRequests: Array<OnyxRequest<TKey>>, transactionID: string): ConflictActionData {
            const trailingIndices = findTrailingReplaceReceiptIndices(persistedRequests, transactionID);
            if (trailingIndices.length === 0) {
                return {conflictAction: {type: 'push'}};
            }
            return {
                conflictAction: {
                    type: 'delete',
                    indices: trailingIndices,
                    pushNewRequest: true,
                },
            };
        }

      (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.)

    2. 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:
            1. 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).
            2. 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).
    3. 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.

  8. melvin-bot commented on Nov 17, 2026

    @melvin-bot

    ✅ Contributor details stored successfully. Thank you for contributing to Expensify!

  9. DylanDylann commented on Nov 17, 2026

    @DylanDylann
    Contributor

    I’m at full capacity, reassign this to another C+

  10. removed their assignment
    on Nov 17, 2026
  11. added
    External
    and removed
    External
    on Nov 17, 2026
  12. 23 remaining items

  13. added
    Weekly
    and removed
    Daily
    Weekly
    on Nov 25, 2026
  14. added
    Daily
    Awaiting Payment
    on Nov 29, 2026
  15. expensify-chore-bot commented on Nov 29, 2026

    @expensify-chore-bot

    Triggered auto assignment to @mallenexpensify (Awaiting Payment)

  16. expensify-chore-bot commented on Nov 29, 2026

    @expensify-chore-bot

    Payment Summary

    Resolving PRs:

    BugZero Checklist (@mallenexpensify)

    • I have confirmed assignees, roles, and Upwork contracts look correct
    • I have paid out Upwork contracts / manual NewDot requests
    • [BugZero Assignee] I have created a GH issue for creating/updating the regression test once above steps have been agreed upon
  17. mallenexpensify commented on Dec 2, 2026

    @mallenexpensify
    Contributor

    Matt's AI agent:

    Will pay tomorrow, apologies for the delay

  18. mallenexpensify commented on Dec 2, 2026

    @mallenexpensify
    Contributor

    Payment Summary

    Contributor+: @ikevin127 due $175 via NewDot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Awaiting PaymentBugDailyExternal

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions