[$175] Receipt retention bug
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 Owner
Current Issue Owner: @rinejUpwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022118472441771038138
- Upwork Job ID: 2118472441771038138
- Last Price Increase: 2026-11-05
Triggered auto assignment to Contributor-plus team member for initial proposal review - @abdulrahuman5196 (External)
Job added to Upwork: https://www.upwork.com/jobs/~022118472441771038138
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:
updateMoneyRequestDescription,updateMoneyRequestMerchant, etc. all build their failure revert ingetUpdateMoneyRequestParams(src/libs/actions/IOU/UpdateMoneyRequest.ts:2323-2333) as a whole-object snapshot:value: {...transaction, pendingFields: clearedPendingFields, ...}. Note the asymmetry —pendingFieldsis carefully field-scoped (getUpdatedTransaction.ts:45), but the value revert is not.SequentialQueuefires that revert on retry exhaustion (src/libs/Network/SequentialQueue.ts:580-601— "Request failed too many times, giving up" →Onyx.update(requestToProcess.failureData)).- There is no conflict dedup for
UPDATE_MONEY_REQUEST_*commands —RequestConflictUtils.tsonly 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) revertsreceipttooldReceipt ?? null— when a first-ever receipt attach gives up, the receipt silently becomesnull(only alogReceiptGaveUptelemetry 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?
- Make the failure revert field-scoped: in
getUpdateMoneyRequestParams, revert only the fields the command actually changed (mirrorgetClearedPendingFields), instead of spreading the whole queued snapshot. This is the core fix. - Add conflict dedup for
UPDATE_MONEY_REQUEST_*commands keyed ontransactionID(coalesce queued updates for the same transaction to the latest, following the existingcheckAndFixConflictingRequestpattern) so multiple independent full-snapshot reverts can't interleave. - 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_RECEIPTretry exhaustion → assert receipt state and user-visible error. - Two queued
UPDATE_MONEY_REQUEST_*for the sametransactionID→ 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.tsflat merges): possible for the description symptom when two clients are involved, but doesn't explain receipt disappearance — kept as secondary diagnostic. ReceiptStorageeviction alone: explains receipts only, not descriptions. The unified failureData mechanism explains both and matches "intermittent" precisely.
Investigation plan (the issue's checkboxes)
- Verify merge semantics of the whole-snapshot revert against react-native-onyx's MERGE contract (code).
- Reproduce locally: force-offline, queue merchant→description→receipt writes, fail the merchant command with a 500, observe the clobber via Onyx devtools.
- Mine
logReceiptGaveUp+ "Request failed too many times" telemetry for transactionIDs with 2+ queued UPDATE_MONEY_REQUEST commands followed by the symptom. - Confirm the fix (field-scoped revert + dedup) against the reproduction.
PR
PR will be linked here once created.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01b6a593fd295a20bf
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
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?
- In
src/libs/actions/IOU/UpdateMoneyRequest.tsinsidegetUpdateMoneyRequestParams(around lines 2323–2333), stop spreading the entiretransactionobject infailureDatafor${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}. - Instead, compute only the specific fields modified by
transactionChanges(mirroring howgetUpdatedTransactioninsrc/libs/actions/IOU/getUpdatedTransaction.tsupdates only modified fields) and populatefailureDatawith only the reverted values for keys present intransactionChanges(e.g.comment: transaction.commentwhen'comment' in transactionChanges,merchant: transaction.merchantwhen'merchant' in transactionChanges,category: transaction.categorywhen'category' in transactionChanges, etc.) alongsidependingFields: clearedPendingFieldsanderrorFields. - Add a unit test in
tests/unit/UpdateMoneyRequestTest.tsverifying thatfailureDatafor a description or merchant update does not includereceiptor 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! 📣 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:
- Make sure you've read and understood the contributing guidelines.
- 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.
- 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.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
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:
- Receipt lost after replacing a receipt or picking from gallery on native: When an expense receipt is picked from the gallery in
ScanEditReceiptor replaced viaIOU.replaceReceipt(MoneyRequestReceiptView/useReceiptDrop), the receipt image can disappear after closing/reopening the app or when the OS evicts temporary cache files. - 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
UpdateMoneyRequestorDetachReceiptcommand is still in theSequentialQueue, if that earlier command fails after retry exhaustion, itsfailureDataoverwrites the entireONYXKEYS.COLLECTION.TRANSACTIONentry 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:
-
Gallery-picked receipts in
ScanEditReceipt.tsxskipReceiptStorage.adopt, leaving native files in the OS temporary cache:- For camera photos,
src/pages/iou/request/step/IOURequestStepScan/components/Camera/index.native.tsx:247-267callsawait ReceiptStorage.adopt(photoSource, file.name)and converts the URI viaReceiptStorage.toLocalUri(durableName)so the file is moved into the durablereceipts/directory (src/libs/ReceiptStorage/index.native.ts:45-73). - Likewise,
src/pages/TransactionReceiptModalContent.tsx:345-351adopts the file before callingreplaceReceipt. - However, in
src/pages/iou/request/step/IOURequestStepScan/components/ScanEditReceipt.tsx:83-114,validateFiles(onPicked={validateFiles}) does:
without callingconst source = getFileSource(file); handleCapture(file, source);ReceiptStorage.adopt(source, file.name). On iOS/Android, gallery-picked files reside in the OS temporary cache directory. BecauseReceiptStorage.resolve(src/libs/ReceiptStorage/index.native.ts:75-85) checkstoDurableName(value)(value.startsWith(getReceiptsDirUri())), an unadopted picker URI is not insidereceipts/, soReceiptStorage.resolvereturnsundefinedand the OS evicts the temporary file.
- For camera photos,
-
replaceReceiptinsrc/libs/actions/IOU/Receipt.ts:257-268clearslocalSource: nulland never retains the new receipt:- In
src/libs/actions/IOU/Receipt.ts:499-515(setMoneyRequestReceipt) andsrc/libs/actions/IOU/MoneyRequestBuilder.ts:473-482(getTransactionWithPreservedLocalReceiptSource), the app callsReceiptStorage.retain(source)and storeslocalSource: sourceontransaction.receipt. - In contrast,
replaceReceipt(src/libs/actions/IOU/Receipt.ts:257-268) sets:
and never callsconst receiptOptimistic = { source, localSource: null, state: state ?? CONST.IOU.RECEIPT_STATE.SCAN_READY, filename: file.name, };ReceiptStorage.retain(source). Additionally,src/components/ReportActionItem/MoneyRequestReceiptView.tsx:647andsrc/hooks/useReceiptDrop.ts:71passsourcedirectly toreplaceReceiptwithout adopting it on native. As a result,MoneyRequestReceiptView.tsx:227(useResolvedReceiptSource(transaction?.receipt?.source, transaction?.receipt?.localSource)) loses its durable local fallback wheneversourceis overwritten by server data or revoked.
- In
-
getUpdateMoneyRequestParams(UpdateMoneyRequest.ts:2323-2333) anddetachReceipt(Receipt.ts:125-135) spread the full stale...transactionsnapshot intofailureData:- In
src/libs/actions/IOU/UpdateMoneyRequest.ts:2323-2333,failureDatasets:{ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, value: { ...transaction, pendingFields: clearedPendingFields, isLoading: false, errorFields, reportID: transaction?.reportID, }, } Onyx.METHOD.MERGEmerges top-level keys of the object into the existing Onyx entry. Because...transactionis a full snapshot captured at the time the earlier update was queued (before the user attached a receipt or edited another field), applyingfailureDatawhen that queued request fails inSequentialQueue.ts:580-596overwrites 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).
- In
What changes do you think we should make in order to solve the problem?
-
Adopt gallery-picked/replaced receipts into
ReceiptStoragebefore passingsourcetohandleCapture/replaceReceipt:- In
src/pages/iou/request/step/IOURequestStepScan/components/ScanEditReceipt.tsx:83-114, adopt the picked file invalidateFiles(matchingCamera/index.native.tsx:253-256andTransactionReceiptModalContent.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.adopthelper insrc/components/ReportActionItem/MoneyRequestReceiptView.tsx:644-652(onReceiptPicked/handleReplacingReceipt) so replacing a receipt fromMoneyRequestReceiptViewalso moves native picker files into durable storage.
- In
-
Preserve
localSource: sourceand callReceiptStorage.retain(source)inreplaceReceipt(src/libs/actions/IOU/Receipt.ts:257-268):- In
src/libs/actions/IOU/Receipt.ts:257-268, retain the new receipt and setlocalSource: sourceonreceiptOptimistic, while preservinglocalSource: sourceinfailureDataif the previous receipt had none or restoringoldReceipt:ReceiptStorage.retain(source); const receiptOptimistic = { source, localSource: source, state: state ?? CONST.IOU.RECEIPT_STATE.SCAN_READY, filename: file.name, };
- In
-
Scope
failureDataingetUpdateMoneyRequestParams(UpdateMoneyRequest.ts:2323-2333) anddetachReceipt(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 likereceiptorcommentupdated by subsequent actions), revert only the keys present intransactionChanges(usingObject.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 onlyreceipt: transaction?.receipt ?? null,filename: transaction?.filename ?? null,pendingFields: {receipt: null}, anderrorFieldsinstead of spreading...(transaction ?? null).
- In
-
Unit Tests:
- Add unit tests in
tests/unit/IOUUtilsTest.ts/tests/actions/IOUTest.tsverifying that:replaceReceiptsetslocalSource: sourceand callsReceiptStorage.retain(source).- When a queued
updateMoneyRequestDescription(or merchant/tag update) fails after a subsequentreplaceReceipt/setMoneyRequestReceipt, applyingfailureDatareverts only the failed field and preserves the newly attachedtransaction.receipt.
- Add unit tests in
What alternative solutions did you explore? (Optional)
- Reading the live transaction inside
failureDataat failure time is not possible becauseOnyxDatapayloads are serialized intopersistedRequestswhen queued. ScopingfailureDatawithOnyx.METHOD.MERGEto only the fields touched bytransactionChanges(instead of spreading the entire...transactionsnapshot) is the standard Expensify pattern used across other atomic Onyx updates and prevents cross-field clobbering.
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?
- In
TransactionUtils.tsandIOU.ts, when a receipt is captured or replaced (e.g. from gallery or camera), the optimistic transaction state updatesreceiptproperties but does not properly merge or retain preexistingcomment/descriptionfields if the optimistic action uses a shallow copy of the transaction object. - 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?
- 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.
- Ensure transaction updates perform a deep merge preserving all non-receipt metadata (
- 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.
- Prevent Onyx merge conflicts from wiping out dirty/pending client fields when the backend upload completion callback returns. Only update receipt-specific fields (
- 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.
@rinej Whoops! This issue is 2 days overdue. Let's get this updated quick!
@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
@rinej @adhorodyski another user email to check is here https://expensify.slack.com/archives/C05LX9D6E07/p1794343608742559
@rinej Huh... This is 4 days overdue. Who can take care of this?
Not overdue, investigating it. I'll post an update in Slack on my findings.
@rinej 10 days overdue. Is anyone even seeing these? Hello?
Not overdue, after investigation @adhorodyski created multiple subissues, currently working on them
@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!