Skip to content

[Due for payment 2026-12-08] [$175] A new expense request can drop from the queue, so a later move of that expense fails with a 456 error #106959

Todo

Description

@mountiny

Part of #106153 (receipt retention). Found by @adhorodyski.

Problem

Example: a user shares a receipt into a new expense, then moves that expense to a report.

  1. The request that creates the expense never reaches the server.
  2. The move request queued after it does reach the server.
  3. The server rejects the move with a 456 error, because the expense does not exist.
  4. The receipt is lost, and the app does not tell the user.

Likely cause: the queue picks the request to replace by its position in the list, and that position can shift.

Impact

  • Severity: P2
  • 10 to 21 a day.

Code

Related pull requests

Expected behavior

Every queued request that creates an expense reaches the server before the requests that depend on it.

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

Activity

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

    @expensify-chore-bot

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

  4. changed the title [-]A new expense request can drop from the queue, so a later move of that expense fails with a 456 error[/-] [+][$175] A new expense request can drop from the queue, so a later move of that expense fails with a 456 error[/+] on Nov 16, 2026
  5. expensify-chore-bot commented on Nov 16, 2026

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

    @MelvinBot
    Contributor

    Proposal

    Confidence: Medium. The stale-position overwrite is supported by code. Its attribution to the reported receipt losses—and the estimate of 10–21 occurrences/day—remains unverified.

    What is the root cause of that problem?

    Conflict handling can replace the wrong queued request because it retains an array position across an asynchronous operation.

    A comment-edit conflict first deletes obsolete updates, waits for persistence, and then applies a replacement using the previously calculated position. If queue processing advances during that wait, the position can now contain an unrelated expense-creation request. Overwriting that request bypasses both its HTTP submission and its normal failure/retry handling.

    Important qualification: Sharing a receipt and moving the expense do not, by themselves, trigger the identified path. It additionally requires a queued comment creation, a matching queued comment update, and concurrent queue advancement.

    Code evidence and a concrete failure sequence

    The relevant operations are:

    For example:

    1. Waiting queue: [AddComment, matching UpdateComment, CreateExpense, MoveExpense].
    2. Conflict resolution deletes UpdateComment, retaining replacement position 0.
    3. During the persistence wait, AddComment becomes ongoing. Waiting queue: [CreateExpense, MoveExpense].
    4. The follow-up replaces position 0 with AddComment, destroying CreateExpense.
    5. MoveExpense survives and can reach the server without the expense having been created.

    The move sends existing transaction IDs; it does not recreate the missing expense: Transaction.ts:2213–2237.

    This explains how creation and its error handling can disappear. It does not independently prove the reported server-side 456 reason or permanent deletion of the receipt image.

    What changes do you think we should make in order to solve the problem?

    Use the target request’s identity—not its saved array position—for asynchronous conflict follow-ups. If the target has already been promoted or cannot be identified uniquely, preserve unrelated requests rather than replacing the current occupant.

    The closed, unmerged Fix a queued request being overwritten when the queue drains mid-conflict implements this approach and addresses the identified mechanism by inspection.

    Validation required before treating this as the receipt-loss solution
    • Adapt the prior patch to current code and add deterministic receipt-specific regression coverage: delay conflict-deletion persistence, advance the queue, and verify receipt-bearing creation survives in memory and storage and is sent exactly once before its move.
    • Cover both a shifted target and a target already promoted to ongoing.
    • Establish how the required queued comment-create/update combination occurs. Ordinary repeated offline edits usually fold into the queued creation; they do not establish this prerequisite.
    • Correlate one affected session’s enqueue/replacement events with the missing create and the move’s full 456 response. A 456 alone could also indicate a deleted, inaccessible, or otherwise invalid transaction.

    The three existing queue/conflict suites passed: 160 tests. That is baseline coverage, not a forced-race or browser reproduction.

    Production confirmation was blocked by unavailable log tools and the absence of occurrence timestamps or correlation IDs in this issue.

    What alternative solutions did you explore? (Optional)

    Retrying the move cannot reconstruct a creation request that never reached the server. User-visible recovery remains important but is separately tracked in Let the user recover from every failed receipt or expense request; identity addressing does not resolve that issue’s 426/retry problems.


    Next Steps for Contributor+ team:
    To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/106959) to create a draft PR.
    To refine: @MelvinBot <your feedback>
    To reject: Explain why you are rejecting Melvin's proposal.


    view run

  7. kevinjosh10 commented on Nov 16, 2026

    @kevinjosh10

    Proposal

    What is the root cause of that problem?

    In src/libs/Network/SequentialQueue.ts:819–846 and src/libs/actions/PersistedRequests.ts:370–388, conflict resolution replaces queued requests by raw array index (conflictAction.index):

    function update<TKey extends OnyxKey>(oldRequestIndex: number, newRequest: Request<TKey>): Promise<void> {
        const requests = [...persistedRequests];
        const oldRequest = requests.at(oldRequestIndex);
        requests.splice(oldRequestIndex, 1, newRequest as AnyRequest);
        ...

    When a compound conflict action executes (such as type: 'delete' followed by nextAction: {type: 'replace'} in RequestConflictUtils.ts:308–375), or while the sequential queue processes and shifts items concurrently:

    1. deletePersistedRequestsByIndices removes preceding items, shifting subsequent items forward.
    2. Concurrent queue advancement pops the head of persistedRequests.
    3. The stored conflictAction.index becomes stale.
    4. When updatePersistedRequest(conflictAction.index, newRequest) executes, requests.splice(oldRequestIndex, 1, newRequest) operates on the wrong item. An unrelated subsequent request—such as a newly enqueued CreateMoneyRequest—is overwritten and erased from the queue.
    5. The subsequent ChangeTransactionsReport (move request) then proceeds to the server. Because the expense was never created on the backend, the server rejects the move with a 456 error, permanently dropping the receipt.

    What changes do you think we should make in order to solve the problem?

    1. Target requests by unique request identity rather than numeric index:
    • In RequestConflictUtils.ts and SequentialQueue.ts:
      • When constructing conflict actions (replace or delete), capture the target request's unique identifier (e.g. request.data?.idempotencyKey, requestIndex, or client request ID) rather than a volatile numeric array index.
    • In src/libs/actions/PersistedRequests.ts:
      • Update updatePersistedRequest to find the target item by matching request identity (requests.findIndex((req) => getRequestID(req) === targetRequestID)).
      • Verify that the target request being replaced matches the expected command and parameters before mutating the array.
      • If the target request is no longer in the queue (e.g. already promoted to ongoing or finished), do NOT splice the current occupant; instead, safely append or discard as appropriate.
    1. Synchronize array mutation across compound conflict resolution:
    • Ensure that compound conflict actions (e.g. delete followed by replace) recalculate indices or perform all mutations atomically in a single pass to prevent race conditions during asynchronous persistence waits.

    What alternative solutions did you explore? (Optional)

    • We explored pausing the queue completely during conflict resolution. However, pausing the queue does not protect against compound conflict actions where the deletion within the same conflict action shifts the index before the subsequent replacement. Identifying requests by unique request ID resolves the index drift completely and reliably under all queue conditions.

    Contributor Details:

  8. cocvn157 commented on Nov 16, 2026

    @cocvn157

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    When a user creates a new expense (RequestMoney / TrackExpense) while the SequentialQueue is actively draining or resolving conflict actions (replace / delete), the expense-creation request in PERSISTED_REQUESTS can be silently overwritten or dropped from the queue. When the user subsequently moves that expense to another report (ChangeTransactionsReport), the move request is sent to the server for a transaction that was never created, failing with a 456 error (jsonCode: 456).

    What is the root cause of that problem?

    1. handleConflictActions resolves replace and delete using mutable array positional indices while the queue is concurrently shifting:
      • In src/libs/Network/SequentialQueue.ts, push() computes conflictAction via newRequest.checkAndFixConflictingRequest( getAllPersistedRequests() ), which returns positional array indices (conflictAction.index for replace, conflictAction.indices for delete) relative to a snapshot of persistedRequests at that moment.
      • However, handleConflictActions is async (await deletePersistedRequestsByIndices(...) followed by recursive await handleConflictActions(conflictAction.nextAction, newRequest)), and SequentialQueue can concurrently shift index 0 out of persistedRequests into ongoingRequest (in PersistedRequests.processNextRequest() via persistedRequests.slice(1)) or finish and remove a request (endRequestAndRemoveFromQueue).
    2. Shifted array indices cause updatePersistedRequest(conflictAction.index, ...) or deleteRequestsByIndices to target the wrong queued request:
      • Once persistedRequests shifts by 1 (because index 0 moved to ongoingRequest or earlier indices were deleted before nextAction executes), conflictAction.index now points to the next item in persistedRequests—such as a newly enqueued RequestMoney / TrackExpense request!
      • Calling updatePersistedRequest(conflictAction.index, requestToReplaceWith) (in src/libs/actions/PersistedRequests.ts:190-207) blindly overwrites persistedRequests[index] by position without verifying that the request at persistedRequests[index] is still the matched target request (or without adjusting indices after deleteRequestsByIndices).
      • As a result, the queued RequestMoney / TrackExpense creation request is overwritten in place by an unrelated follow-up request (e.g. OpenReport or an edit/move command), never reaches the server, and never emits a [Receipt] drop warning unless RECEIPT_BEARING_COMMANDS is explicitly checked before overwrite. Later, ChangeTransactionsReport references that transactionID and fails with 456.

    What changes do you think we should make in order to solve the problem?

    1. Assign a stable monotonic ID (requestID / persistedIndex) or validate target identity before mutating persistedRequests in src/libs/actions/PersistedRequests.ts and src/libs/Network/SequentialQueue.ts:

      • In src/libs/actions/PersistedRequests.ts, when save() or processNextRequest() mutates persistedRequests, ensure update(oldRequestIndex, newRequest) and deleteRequestsByIndices(indices) verify that the request currently at that index has not shifted into ongoingRequest (or resolve targets by stable request reference / monotonic ID rather than raw array offset after async boundaries).
      • Specifically, in src/libs/Network/SequentialQueue.ts inside handleConflictActions:
        • Capture the actual target request reference(s) from getAllPersistedRequests() before the first await when checkAndFixConflictingRequest runs, or re-resolve the index of the target request in getAllPersistedRequests() immediately before executing updatePersistedRequest / deletePersistedRequestsByIndices.
        • If a replace target request is no longer in getAllPersistedRequests() (because it was already promoted to ongoingRequest while awaiting), do not overwrite whatever request shifted into conflictAction.index; instead, fall back to savePersistedRequest(requestToReplaceWith) (push to queue) so neither the in-flight request nor the newly shifted expense-creation request is clobbered.
      • When a delete action is followed by a chained nextAction (replace), adjust nextAction.index for any deleted indices < nextAction.index (or resolve by captured request reference):
      // In src/libs/Network/SequentialQueue.ts
      async function handleConflictActions<TKey extends OnyxKey>(
          conflictAction: ConflictActionData,
          newRequest: OnyxRequest<TKey>,
          snapshotRequests: Array<OnyxRequest<TKey>> = getAllPersistedRequests() as Array<OnyxRequest<TKey>>,
      ) {
          if (conflictAction.type === 'push') {
              await savePersistedRequest(newRequest);
          } else if (conflictAction.type === 'replace') {
              const requestToReplaceWith = (conflictAction.request ?? newRequest) as OnyxRequest<TKey>;
              const expectedTarget = snapshotRequests[conflictAction.index];
              const currentRequests = getAllPersistedRequests();
              const currentIndex = expectedTarget ? currentRequests.indexOf(expectedTarget as AnyRequest) : -1;
      
              if (currentIndex !== -1) {
                  const displaced = currentRequests[currentIndex];
                  if (displaced && RECEIPT_BEARING_COMMANDS.has(displaced.command) && !RECEIPT_BEARING_COMMANDS.has(requestToReplaceWith.command)) {
                      logReceiptDropped({
                          receiptTraceId: getRequestReceiptTraceId(displaced),
                          transactionID: getRequestTransactionID(displaced),
                          command: displaced.command,
                          reason: `replaced_by_${requestToReplaceWith.command}`,
                      });
                  }
                  await updatePersistedRequest(currentIndex, requestToReplaceWith);
              } else {
                  // Target already moved to ongoingRequest or was removed; append safely instead of overwriting a shifted request
                  await savePersistedRequest(requestToReplaceWith);
              }
          } else if (conflictAction.type === 'delete') {
              const targetsToDelete = new Set(conflictAction.indices.map((i) => snapshotRequests[i]).filter(Boolean));
              const currentRequests = getAllPersistedRequests();
              const currentIndicesToDelete: number[] = [];
              currentRequests.forEach((req, idx) => {
                  if (targetsToDelete.has(req as OnyxRequest<TKey>)) {
                      currentIndicesToDelete.push(idx);
                  }
              });
              // Log any receipt-bearing requests being deleted...
              if (currentIndicesToDelete.length > 0) {
                  await deletePersistedRequestsByIndices(currentIndicesToDelete);
              }
              if (conflictAction.pushNewRequest) {
                  await savePersistedRequest(newRequest);
              }
              if (conflictAction.nextAction) {
                  await handleConflictActions(conflictAction.nextAction, newRequest, snapshotRequests);
              }
          }
      }
    2. Log receipt-bearing request overwrites in replace:

      • Currently SequentialQueue.ts only calls logReceiptDropped in the conflictAction.type === 'delete' branch (lines 838-848), but never in the conflictAction.type === 'replace' branch (lines 828-830). Adding the RECEIPT_BEARING_COMMANDS check when a request is replaced ensures any future replacement of a receipt-bearing request is also surfaced in Sentry.
    3. Add unit tests in tests/unit/SequentialQueueTest.ts:

      • Add a test simulating processNextRequest() shifting index 0 into ongoingRequest (and a chained delete + nextAction: replace) while RequestMoney is in persistedRequests, verifying that RequestMoney is never overwritten and both requests are sent in order.

    What alternative solutions did you explore? (Optional)

    • Re-running checkAndFixConflictingRequest inside a synchronous mutex in PersistedRequests.ts: resolving currentIndex against the snapshot object reference (or a monotonic _persistedId) directly in handleConflictActions is simpler, works across await boundaries, and avoids changing the signature of every conflict resolver in the codebase.
  9. dankezo commented on Nov 16, 2026

    @dankezo

    Contributor details
    Your Expensify account email: dannyphan190@gmail.com
    Upwork Profile Link: https://www.upwork.com/freelancers/~013b564a690d9bcdab

    Proposal

    Problem

    A newly created expense request can be silently dropped from the persisted
    queue. The expense is never created on the server, and when the user later
    tries to move it, the move fails with a 456 because the expense does not exist.

    Root cause

    Conflict resolution addresses queued requests by their POSITIONAL index, and
    that index can go stale before it is used:

    • checkAndFixConflictingRequest computes a conflict action containing an
      index into the persisted queue.
    • handleConflictActions (src/libs/Network/SequentialQueue.ts:807) then
      awaits, and applies the action with the raw index:
      updatePersistedRequest(conflictAction.index, ...) at line 825.
    • PersistedRequests.update (src/libs/actions/PersistedRequests.ts:370)
      splices at that index with no identity check and no bounds check.
    • Meanwhile processNextRequest shifts index 0 off the queue concurrently,
      and another tab can merge changes into the same queue.

    If the queue shifted between computing the index and applying it, the splice
    overwrites a DIFFERENT request than the one the conflict was about. When that
    different request is the pending CreateMoneyRequest, it is lost: the expense
    is never sent, nothing logs the loss, and the later move fails 456. If the
    index is out of range, the splice appends instead, leaving both the stale
    target and the replacement in the queue.

    ConflictRequestReplace (src/types/onyx/Request.ts:138-153) carries only
    type, index and request - no identity - so today there is nothing to
    check the index against.

    Prior art: PR #101207 ("fix: resolve edit comment conflicts by request
    id") already implemented identity-based resolution for the replace path, with
    tests, and was closed unmerged with PROPOSAL: N/A in its body - it died for
    lack of a proposal, not for a technical flaw. This proposal revives that
    approach, extends it to the delete path and to every resolver, and changes one
    behaviour: where #101207 skipped (dropped) a replacement whose target had
    already left the queue, this design appends it, because in the expense flow
    the replacement is a newer user edit and dropping it loses data.

    Changes

    1. src/types/onyx/Request.ts - carry identity. Add
      requestIndex?: number to ConflictRequestReplace and
      ConflictRequestDelete: the client request index of the target request,
      from getClientRequestIndex (which returns request.requestIndex ?? request.requestID).

    2. src/libs/actions/PersistedRequests.ts - export the identity helper.
      Export the existing getClientRequestIndex (line 40) so resolvers and the
      queue can use it.

    3. src/libs/actions/RequestConflictUtils.ts - stamp every action. Every
      resolver that returns a replace or delete action sets requestIndex from
      the target request it matched. The conflict RULES (which requests conflict)
      do not change; only the addressing does.

    4. src/libs/actions/PersistedRequests.ts - resolve by identity in
      update().
      update(oldRequestIndex, newRequest, requestIndexToReplace?):
      when requestIndexToReplace is provided, find the live index of the
      request carrying that identity in the current queue.

      • Carried by more than one request: Log.alert and skip - never guess,
        never append.
      • Found: splice at the RESOLVED index (log both the stale index and the
        resolved index).
      • Not in the queue, but it IS the ongoing request: skip with Log.info -
        in the flows that merge parameters into the target in place, the ongoing
        request already carries the update.
      • Not anywhere: append the replacement and Log.info with the stale index.
        The replacement is a newer user intent; appending sends it late, dropping
        it loses it. (This is the deliberate difference from Fix a queued request being overwritten when the queue drains mid-conflict #101207.)
    5. src/libs/Network/SequentialQueue.ts - delete by identity too. In
      handleConflictActions, resolve the delete path's indices to request
      indexes BEFORE the first await, then delete by identity. For a chained
      nextAction of type replace, require requestIndex; if it is absent,
      refuse and Log.alert instead of applying a positional guess (the same
      guard Fix a queued request being overwritten when the queue drains mid-conflict #101207 added as handleFollowUpConflictAction).

    Not changed: which requests are considered conflicting, the queue's
    processing order, the cross-tab dedup semantics (the diskIDs logic in
    PersistedRequests), and the ongoing-request fast path.

    Tests

    Baseline verified before writing this: tests/unit/SequentialQueueTest.ts
    and tests/unit/RequestConflictUtilsTest.ts pass 146/146 on current HEAD.

    • tests/unit/PersistedRequests.ts: update with a requestIndexToReplace
      replaces the request carrying that identity even after an unrelated request
      was inserted at the front; an ambiguous identity is skipped with no queue
      change; a missing identity appends; the ongoing-request case skips.
    • tests/unit/SequentialQueueTest.ts: reproduce the race with the technique
      from Fix a queued request being overwritten when the queue drains mid-conflict #101207 - intercept the ONYX write for the persisted requests and run
      processNextRequest inside it, so the queue shifts between the conflict
      computation and its application. Assert the replacement lands on the
      intended request and the pending CreateMoneyRequest is still in the queue
      afterwards (the 456 scenario: the create request must survive).
    • tests/unit/RequestConflictUtilsTest.ts: every resolver that returns a
      replace/delete action now stamps requestIndex, and the stamped value
      matches getClientRequestIndex of the matched request.
    • Regression: the existing SequentialQueue, RequestConflictUtils and
      PersistedRequests suites keep passing unchanged apart from the additions.

    Alternatives considered

    • Match by object reference (as in one existing proposal). Rejected as
      the sole mechanism: references do not survive the Onyx persistence
      round-trip or a cross-tab merge, while the client request index does - it
      is already the identity the cross-tab dedup logic uses.
    • Match by idempotencyKey / requestID alone. Rejected: not every queued
      request carries the same fields; getClientRequestIndex already defines
      the canonical fallback (requestIndex ?? requestID) and is what the rest
      of PersistedRequests uses.
    • Lock the queue while a conflict action is applied. Rejected: the shift
      can also come from another tab's merge, which a local lock cannot prevent,
      and locking the hot path risks stalling the queue.
    • Ship Fix a queued request being overwritten when the queue drains mid-conflict #101207 unchanged. Rejected: it stamps only the edit-comment
      resolver, leaves the delete path positional, and drops replacements whose
      target already left the queue - acceptable for comment edits, not for
      expense creation.
  10. melvin-bot commented on Nov 16, 2026

    @melvin-bot

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

  11. 7 remaining items

  12. mountiny commented on Nov 21, 2026

    @mountiny
    ContributorAuthor

    Yes this will be handled by callstack

  13. expensify-chore-bot commented on Nov 23, 2026

    @expensify-chore-bot

    @adhorodyski Still overdue 6 days?! Let's take care of this!

  14. added
    Reviewing
    Weekly
    and removed
    Daily
    on Nov 25, 2026
  15. elirangoshen commented on Nov 25, 2026

    @elirangoshen
    Contributor

    Hi, please assign it to me. @mountiny

    Summary of the investigation:

    Problem: an expense is created offline, then moved to a report. Sometimes the move fails with a 456 error ("Could not retrieve all transactionIDs") because the server never got the expense.

    What I found in VictoriaLogs (59 failed moves, Nov 16-19):

    • 41 moves (70%): the server has the expense. In almost all of them the user had already submitted the report and then tried to move the expense out of it. The App allows that and the server refuses. need to check if it should be allowed and server need to support or not and then we can block in in the app - happy to share relevant logs
    • 18 (30%): the server doesn't have the expense. About 13 unique expenses:
      • 6: the server rejected the create (rate deleted, no permission, report closed, bad file), and the user then moved the leftover expense.
      • 1: iOS app killed while a receipt was uploading. This is the bug the issue describes.
      • 1: a web retry loop.
      • The rest: the expense was deleted or merged, or the cause is unclear.

    Root cause of the iOS case: while a receipt create is being sent, the app doesn't save it to disk. A native receipt is a File, and those were skipped. If the app is killed during upload, the create is lost and only the move is sent after restart.

    I opened a pr to fix that 30% of the errors the we know its app related.
    #107935

  16. added
    Daily
    and removed
    Reviewing
    Weekly
    on Dec 1, 2026
  17. changed the title [-][$175] A new expense request can drop from the queue, so a later move of that expense fails with a 456 error[/-] [+][Due for payment 2026-12-08] [$175] A new expense request can drop from the queue, so a later move of that expense fails with a 456 error[/+] on Dec 1, 2026
  18. melvin-bot commented on Dec 1, 2026

    @melvin-bot

    @jayeshmangwani

    The solution for this issue has been 🚀 deployed to production 🚀 in version 9.5.56-2 and is now subject to a 7-day regression period 📆. Here is the list of pull requests that resolve this issue:

    If no regressions arise, payment will be issued on 2026-12-08. 🎊

    The following checklist (instructions) will need to be completed before the issue can be closed. Please copy/paste the Contributor+ Checklist from here into a new comment on this GH and complete it. If you have the K2 extension, you can simply click: [this button]. If no checklist is needed for this issue, you can click: [no checklist button]

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

Metadata

Metadata

Labels

BugDailyExternalOverdue

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions