App icon indicating copy to clipboard operation
App copied to clipboard

[$175] Receipt retention bug

Open mountiny opened this issue 3 weeks ago • 17 comments

Customer report

A customer using New Expensify reports that receipts are intermittently missing after they add them, and that expense descriptions are being erased. They now retain separate copies of their receipts because they do not trust capture to persist reliably.

These are customer-reported symptoms, not yet reproduced or independently verified. It is not yet known whether the receipts fail to upload, fail to sync, become detached, or are simply not displayed. It is also unknown whether the description loss shares the same cause.

Expected behavior

Receipts added to expenses remain accessible, and saved descriptions persist unless explicitly changed or removed.

Investigation

  • [ ] Review the affected sessions and available receipt-upload/sync telemetry through an appropriately private channel.
  • [ ] Establish the capture method, device/OS, app version, connectivity state, and timing of an affected attempt.
  • [ ] Trace an affected receipt from capture through upload, expense creation, and subsequent updates to identify where it stops being accessible.
  • [ ] Investigate which operation clears the description and whether it is related to the receipt symptom.
  • [ ] Record verified reproduction steps and scope; add regression coverage once the cause is established.

Known limitations

No reproduction steps, affected expense/receipt IDs, session timestamps, or confirmed root cause are available in this sanitized report. Default platform was reported as New Expensify; the exact client is unconfirmed.

Privacy

Customer names, email addresses, company information, account identifiers, customer quotes, and links to customer records or identifying source material are intentionally omitted.

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

mountiny avatar Nov 05 '26 22:11 mountiny

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

melvin-bot[bot] avatar Nov 05 '26 22:11 melvin-bot[bot]

Job added to Upwork: https://www.upwork.com/jobs/~022118472441771038138

melvin-bot[bot] avatar Nov 05 '26 22:11 melvin-bot[bot]

Proposal

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

Customers on New Expensify report that receipts attached to expenses intermittently disappear, and that expense descriptions (comments) get erased. No reproduction exists yet — the failure is intermittent and the affected sessions were not captured. We need the actual root cause, verified reproduction steps, and a fix.

What is the root cause of that problem?

I've traced the write paths, and I believe both symptoms share one mechanism: when a queued transaction write gives up after exhausting retries, its failureData reverts the entire transaction snapshot captured at queue time — wiping out any receipt/description changes that were made after that write was queued.

The chain:

  1. updateMoneyRequestDescription, updateMoneyRequestMerchant, etc. all build their failure revert in getUpdateMoneyRequestParams (src/libs/actions/IOU/UpdateMoneyRequest.ts:2323-2333) as a whole-object snapshot: value: {...transaction, pendingFields: clearedPendingFields, ...}. Note the asymmetry — pendingFields is carefully field-scoped (getUpdatedTransaction.ts:45), but the value revert is not.
  2. SequentialQueue fires that revert on retry exhaustion (src/libs/Network/SequentialQueue.ts:580-601 — "Request failed too many times, giving up" → Onyx.update(requestToProcess.failureData)).
  3. There is no conflict dedup for UPDATE_MONEY_REQUEST_* commands — RequestConflictUtils.ts only matches OpenReport/reconnect/comment/policy commands — so a description edit and a merchant edit on the same expense queue as independent entries, each carrying its own full-snapshot revert.

So the customer scenario is: edit a field (merchant/amount) while flaky-networked → queue backs up → user then adds a receipt and edits the description (optimistic merges land locally) → the original write fails permanently and exhausts retries → its failureData merges the stale snapshot back over the transaction → description reverts to the old value and the receipt reverts to whatever existed before (or null) — both reported symptoms in one mechanism.

Two adjacent contributors for the receipt-specific symptom:

  • replaceReceipt's failureData (src/libs/actions/IOU/Receipt.ts:328-348) reverts receipt to oldReceipt ?? null — when a first-ever receipt attach gives up, the receipt silently becomes null (only a logReceiptGaveUp telemetry line, invisible to the user).
  • ReceiptUploadRetryHandler (src/libs/ReceiptUploadRetryHandler/index.ts:81-84) gives up permanently if the local file was evicted mid-retry-window — no recovery path.

This explains the intermittency (requires failure + retry exhaustion), why it survives app restarts (queue is persisted via PersistedRequests.ts), and why the customer "no longer trusts capture to persist."

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

  1. Make the failure revert field-scoped: in getUpdateMoneyRequestParams, revert only the fields the command actually changed (mirror getClearedPendingFields), instead of spreading the whole queued snapshot. This is the core fix.
  2. Add conflict dedup for UPDATE_MONEY_REQUEST_* commands keyed on transactionID (coalesce queued updates for the same transaction to the latest, following the existing checkAndFixConflictingRequest pattern) so multiple independent full-snapshot reverts can't interleave.
  3. For the receipt path: when a first-ever receipt attach gives up, surface a user-visible error state on the expense instead of silently nulling.

What specific scenarios should be covered by automated tests?

  • Offline queue: edit merchant → add receipt → edit description → merchant write fails with retry exhaustion → assert description and receipt survive (currently they would revert).
  • First-ever REPLACE_RECEIPT retry exhaustion → assert receipt state and user-visible error.
  • Two queued UPDATE_MONEY_REQUEST_* for the same transactionID → assert no stale-snapshot clobber after one fails.
  • Onyx merge semantics: whole-object snapshot revert vs field-scoped revert unit test.

What alternative solutions did you explore?

  • Server-side push overwrite (OnyxUpdates.ts flat merges): possible for the description symptom when two clients are involved, but doesn't explain receipt disappearance — kept as secondary diagnostic.
  • ReceiptStorage eviction alone: explains receipts only, not descriptions. The unified failureData mechanism explains both and matches "intermittent" precisely.

Investigation plan (the issue's checkboxes)

  1. Verify merge semantics of the whole-snapshot revert against react-native-onyx's MERGE contract (code).
  2. Reproduce locally: force-offline, queue merchant→description→receipt writes, fail the merchant command with a 500, observe the clobber via Onyx devtools.
  3. Mine logReceiptGaveUp + "Request failed too many times" telemetry for transactionIDs with 2+ queued UPDATE_MONEY_REQUEST commands followed by the symptom.
  4. Confirm the fix (field-scoped revert + dedup) against the reproduction.

PR

PR will be linked here once created.

vanshshah11 avatar Nov 06 '26 16:11 vanshshah11

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01b6a593fd295a20bf

vanshshah11 avatar Nov 06 '26 18:11 vanshshah11

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

melvin-bot[bot] avatar Nov 06 '26 18:11 melvin-bot[bot]

Proposal

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

If a user edits a field on an expense (such as description or merchant) while offline or while a network request is queued, and then attaches or replaces a receipt (or edits another field) before the first request fails, the failure of the earlier request overwrites the entire transaction in Onyx with a stale snapshot captured when the earlier request was queued, wiping out the newly attached receipt.

What is the root cause of that problem?

In src/libs/actions/IOU/UpdateMoneyRequest.ts (lines 2323–2333), getUpdateMoneyRequestParams constructs failureData for ONYXKEYS.COLLECTION.TRANSACTION by spreading the entire transaction object captured at the moment the field update was called (value: {...transaction, pendingFields: clearedPendingFields, errors: ...}). When SequentialQueue (src/libs/Network/SequentialQueue.ts, lines 580–601) exhausts retries and applies failureData, Onyx.Method.MERGE merges every top-level property of that stale transaction snapshot back into Onyx—including the old receipt: undefined (or old comment, merchant, category, etc.)—overwriting any receipt or other fields updated on the transaction after the failed request was originally queued.

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

  1. In src/libs/actions/IOU/UpdateMoneyRequest.ts inside getUpdateMoneyRequestParams (around lines 2323–2333), stop spreading the entire transaction object in failureData for ${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}.
  2. Instead, compute only the specific fields modified by transactionChanges (mirroring how getUpdatedTransaction in src/libs/actions/IOU/getUpdatedTransaction.ts updates only modified fields) and populate failureData with only the reverted values for keys present in transactionChanges (e.g. comment: transaction.comment when 'comment' in transactionChanges, merchant: transaction.merchant when 'merchant' in transactionChanges, category: transaction.category when 'category' in transactionChanges, etc.) alongside pendingFields: clearedPendingFields and errorFields.
  3. Add a unit test in tests/unit/UpdateMoneyRequestTest.ts verifying that failureData for a description or merchant update does not include receipt or overwrite a receipt added after the update was queued.

What alternative solutions did you explore? (Optional)

We considered resolving failureData dynamically via a callback inside SequentialQueue, but PersistedRequests serializes failureData to Onyx storage across app restarts, so scoping failureData to only the modified fields is both serializable and consistent with the rest of the codebase.

jeffrey-graham avatar Nov 07 '26 04:11 jeffrey-graham

📣 @jeffrey-graham! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:

  1. Make sure you've read and understood the contributing guidelines.
  2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
  3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
  4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details. Screen Shot 2022-11-16 at 4 42 54 PM Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>

melvin-bot[bot] avatar Nov 07 '26 04:11 melvin-bot[bot]

Proposal

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

Two receipt/transaction retention regressions occur across mobile and offline-to-online edit flows:

  1. Receipt lost after replacing a receipt or picking from gallery on native: When an expense receipt is picked from the gallery in ScanEditReceipt or replaced via IOU.replaceReceipt (MoneyRequestReceiptView / useReceiptDrop), the receipt image can disappear after closing/reopening the app or when the OS evicts temporary cache files.
  2. Receipt / description reverted when an earlier queued field edit fails: When a user updates transaction fields (e.g., description, merchant, or category) and attaches/replaces a receipt while an earlier queued UpdateMoneyRequest or DetachReceipt command is still in the SequentialQueue, if that earlier command fails after retry exhaustion, its failureData overwrites the entire ONYXKEYS.COLLECTION.TRANSACTION entry with a stale transaction snapshot—wiping out the newly attached receipt and/or updated description.

What is the root cause of that problem?

There are three specific root causes in the current codebase:

  1. Gallery-picked receipts in ScanEditReceipt.tsx skip ReceiptStorage.adopt, leaving native files in the OS temporary cache:

  2. replaceReceipt in src/libs/actions/IOU/Receipt.ts:257-268 clears localSource: null and never retains the new receipt:

  3. getUpdateMoneyRequestParams (UpdateMoneyRequest.ts:2323-2333) and detachReceipt (Receipt.ts:125-135) spread the full stale ...transaction snapshot into failureData:

    • In src/libs/actions/IOU/UpdateMoneyRequest.ts:2323-2333, failureData sets:
      {
          onyxMethod: Onyx.METHOD.MERGE,
          key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`,
          value: {
              ...transaction,
              pendingFields: clearedPendingFields,
              isLoading: false,
              errorFields,
              reportID: transaction?.reportID,
          },
      }
      
    • Onyx.METHOD.MERGE merges top-level keys of the object into the existing Onyx entry. Because ...transaction is a full snapshot captured at the time the earlier update was queued (before the user attached a receipt or edited another field), applying failureData when that queued request fails in SequentialQueue.ts:580-596 overwrites every top-level field on the transaction (receipt, filename, comment, merchant, etc.) with the stale snapshot!
    • The exact same full-snapshot spread exists in detachReceipt (src/libs/actions/IOU/Receipt.ts:125-135).

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

  1. Adopt gallery-picked/replaced receipts into ReceiptStorage before passing source to handleCapture / replaceReceipt:

    • In src/pages/iou/request/step/IOURequestStepScan/components/ScanEditReceipt.tsx:83-114, adopt the picked file in validateFiles (matching Camera/index.native.tsx:253-256 and TransactionReceiptModalContent.tsx:345-351):
      const rawSource = getFileSource(file);
      ReceiptStorage.adopt(rawSource, file.name)
          .then((durableName) => {
              const source = durableName ? ReceiptStorage.toLocalUri(durableName) : rawSource;
              handleCapture(file, source);
          })
          .catch(() => {
              handleCapture(file, rawSource);
          });
      
    • Apply the same ReceiptStorage.adopt helper in src/components/ReportActionItem/MoneyRequestReceiptView.tsx:644-652 (onReceiptPicked / handleReplacingReceipt) so replacing a receipt from MoneyRequestReceiptView also moves native picker files into durable storage.
  2. Preserve localSource: source and call ReceiptStorage.retain(source) in replaceReceipt (src/libs/actions/IOU/Receipt.ts:257-268):

    • In src/libs/actions/IOU/Receipt.ts:257-268, retain the new receipt and set localSource: source on receiptOptimistic, while preserving localSource: source in failureData if the previous receipt had none or restoring oldReceipt:
      ReceiptStorage.retain(source);
      const receiptOptimistic = {
          source,
          localSource: source,
          state: state ?? CONST.IOU.RECEIPT_STATE.SCAN_READY,
          filename: file.name,
      };
      
  3. Scope failureData in getUpdateMoneyRequestParams (UpdateMoneyRequest.ts:2323-2333) and detachReceipt (Receipt.ts:125-135) to only the modified fields instead of spreading ...transaction:

    • In src/libs/actions/IOU/UpdateMoneyRequest.ts:2323-2333, instead of spreading ...transaction (which clobbers unrelated fields like receipt or comment updated by subsequent actions), revert only the keys present in transactionChanges (using Object.fromEntries( updatedFields.map((field) => [field, transaction?.[field] ?? null]) )):
      const revertedTransactionFields = Object.fromEntries(
          (Object.keys(transactionChanges) as Array<keyof typeof transactionChanges>).map((field) => [
              field,
              transaction?.[field] ?? null,
          ]),
      );
      failureData.push({
          onyxMethod: Onyx.METHOD.MERGE,
          key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`,
          value: {
              ...revertedTransactionFields,
              pendingFields: clearedPendingFields,
              isLoading: false,
              errorFields,
              ...(transaction?.reportID ? {reportID: transaction.reportID} : {}),
          },
      });
      
    • In src/libs/actions/IOU/Receipt.ts:125-135 (detachReceipt), revert only receipt: transaction?.receipt ?? null, filename: transaction?.filename ?? null, pendingFields: {receipt: null}, and errorFields instead of spreading ...(transaction ?? null).
  4. Unit Tests:

    • Add unit tests in tests/unit/IOUUtilsTest.ts / tests/actions/IOUTest.ts verifying that:
      • replaceReceipt sets localSource: source and calls ReceiptStorage.retain(source).
      • When a queued updateMoneyRequestDescription (or merchant/tag update) fails after a subsequent replaceReceipt / setMoneyRequestReceipt, applying failureData reverts only the failed field and preserves the newly attached transaction.receipt.

What alternative solutions did you explore? (Optional)

  • Reading the live transaction inside failureData at failure time is not possible because OnyxData payloads are serialized into persistedRequests when queued. Scoping failureData with Onyx.METHOD.MERGE to only the fields touched by transactionChanges (instead of spreading the entire ...transaction snapshot) is the standard Expensify pattern used across other atomic Onyx updates and prevents cross-field clobbering.

zaidrain06 avatar Nov 07 '26 19:11 zaidrain06

Proposal

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

Users report that receipts are intermittently missing or erased after uploading/capturing, and expense descriptions can be cleared during receipt replacement or offline-to-online reconciliation flows.

What is the root cause of that problem?

  1. In TransactionUtils.ts and IOU.ts, when a receipt is captured or replaced (e.g. from gallery or camera), the optimistic transaction state updates receipt properties but does not properly merge or retain preexisting comment / description fields if the optimistic action uses a shallow copy of the transaction object.
  2. In the offline queue reconciliation within PersistedRequests, when an offline receipt upload finishes, the server response payload is merged back via Onyx without preserving local pending transaction modifications, causing local descriptions and newly attached receipt file URIs to be overwritten by stale server state.

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

  1. In IOU.ts (replaceReceipt / setMoneyRequestDescription):
    • Ensure transaction updates perform a deep merge preserving all non-receipt metadata (comment, description, billable, category, tag) when updating the receipt object.
  2. In Receipt.ts / OnyxUpdates:
    • Prevent Onyx merge conflicts from wiping out dirty/pending client fields when the backend upload completion callback returns. Only update receipt-specific fields (receipt.source, receipt.state, receipt.transactionID) rather than overwriting the entire transaction object.
  3. In local file caching:
    • Ensure the local cached receipt URI is retained until the remote receipt URL is completely confirmed and verified by the backend.

What alternative solutions did you explore? (Optional)

Blocking description edits while a receipt is uploading, but this degrades the user experience by locking form fields unnecessarily.

TassioSales avatar Nov 08 '26 00:11 TassioSales

@rinej Whoops! This issue is 2 days overdue. Let's get this updated quick!

melvin-bot[bot] avatar Nov 09 '26 21:11 melvin-bot[bot]

@rinej @adhorodyski there are still a bunch of reviews by customers coming in, reporting various issues with the receipts retention. Let's keep on going through the logs and full story sessions to try to identify the flows where we might be missing the receipts

mountiny avatar Nov 10 '26 03:11 mountiny

@rinej @adhorodyski another user email to check is here https://expensify.slack.com/archives/C05LX9D6E07/p1794343608742559

mountiny avatar Nov 10 '26 20:11 mountiny

@rinej Huh... This is 4 days overdue. Who can take care of this?

melvin-bot[bot] avatar Nov 11 '26 21:11 melvin-bot[bot]

Not overdue, investigating it. I'll post an update in Slack on my findings.

adhorodyski avatar Nov 13 '26 10:11 adhorodyski

@rinej 10 days overdue. Is anyone even seeing these? Hello?

Not overdue, after investigation @adhorodyski created multiple subissues, currently working on them

rinej avatar Nov 17 '26 21:11 rinej

@rinej @mountiny @adhorodyski @abdulrahuman5196 this issue was created 2 weeks ago. Are we close to approving a proposal? If not, what's blocking us from getting this issue assigned? Don't hesitate to create a thread in #expensify-open-source to align faster in real time. Thanks!