[Due for payment 2026-11-30] [$175] Scan - Multiple ReplaceReceipt API calls triggered after offline replacements
If you haven’t already, check out our contributing guidelines for onboarding and email [email protected] 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:
- Go to https://staging.new.expensify.com/
- Go to workspace chat
- Create a scan request with a valid receipt
- After scanning, go offline
- Replace the receipt multiple times
- Delete the receipt
- Open DevTools > Network tab
- 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
- [x] Windows: Chrome
- [ ] MacOS: Chrome / Safari
Screenshots/Videos
https://github.com/user-attachments/assets/be4bb328-7430-4667-8c7a-e1966a1742e3
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022122731030780167209
- Upwork Job ID: 2122731030780167209
- Last Price Increase: 2026-11-17
Issue Owner
Current Issue Owner: @mallenexpensify
Triggered auto assignment to Contributor-plus team member for initial proposal review - @DylanDylann (External)
Job added to Upwork: https://www.upwork.com/jobs/~022122731030780167209
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
- 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.
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.
Contributor details Your Expensify account email: [email protected] 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:
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:
- Each
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 queuedReplaceReceipt#1 withReplaceReceipt#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). - Each non-
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. - Scanning the queue must scope by
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):- Add a helper
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). - 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 supersededREPLACE_RECEIPTrequests for thattransactionIDinstead 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 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.) - Add a helper
-
Preserve pre-offline
failureDatabaseline and clean up superseded audit actions insrc/libs/actions/IOU/Receipt.ts:- Before calling
API.write, inspect the trailing queuedREPLACE_RECEIPTrequests returned byfindTrailingReplaceReceiptIndices(getAllPersistedRequests(), transactionID):- Preserve pre-offline rollback baseline: Copy the earliest superseded
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. - Clean up superseded
MODIFIED_EXPENSEaudit actions & handleisSameReceipt:- When
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. - Also guard two edge cases when a queued
REPLACE_RECEIPTexists:- If
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). - If the earliest superseded
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.
- If
- When
- Preserve pre-offline rollback baseline: Copy the earliest superseded
- Pass
{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).
- Before calling
-
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:- Update the 3 existing strict 3-argument
expect(writeSpy).toHaveBeenCalledWith(...)checks atlines 383,635, and1142to include the 4thconflictResolverargument (expect.objectContaining({checkAndFixConflictingRequest: expect.any(Function)})). - Add tests verifying offline sequential
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.
- Update the 3 existing strict 3-argument
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.
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
I’m at full capacity, reassign this to another C+
Triggered auto assignment to Contributor-plus team member for initial proposal review - @ikevin127 (External)
Proposal 1 (MelvinBot) is the only proposal in scope because this issue doesn't have the I reproduced this on The root cause is correct. The solution isn't actionable yet: 🟠 The solution section is a list of requirements. It doesn't name a resolver, a file or a queue action ( 🟠 The deletion behavior is left as an open question. The Expected Result asks for one 🟡 The rollback and audit-action concerns are real, and the refinement needs a concrete answer for both. 🟡 Keep the resolver pure. 🟢 The test plan is fine. It should cover the resolver in The RCA is right, but I'm not selecting a proposal yet. I'll ask MelvinBot to refine the solution along these lines.Detailed proposals review
Help Wanted label.main. After 3 offline replacements and a delete, the persisted queue held ReplaceReceipt x3 followed by DetachReceipt, and all 4 were sent (200) on reconnect.replaceReceipt calls API.write without a conflict resolver (Receipt.ts:486), so SequentialQueue.push saves every replacement as its own request, and detachReceipt (Receipt.ts:226) just appends a detach behind them.replace / delete), so there's nothing concrete to implement or review. We already have this pattern in resolveCommentDeletionConflicts (RequestConflictUtils.ts:220), which drops queued requests that a later delete supersedes and cleans up the optimistic actions they left behind. I'd expect the proposal to spell out a transaction-scoped REPLACE_RECEIPT resolver there and show how it's wired into API.write in Receipt.ts.ReplaceReceipt on reconnect, so collapsing unsent replacements for the same transaction down to the latest one should be the baseline. Dropping that last replacement when a DetachReceipt follows changes what ends up in the receipt history, so it needs internal sign-off and shouldn't be part of the baseline fix.oldReceipt is read from the optimistic state (Receipt.ts:256), so if only replacement 3 is left in the queue and it fails, the transaction rolls back to replacement 2's unsent local file instead of the server receipt. The superseded requests' successData never runs either, so their optimistic receiptAdded / receiptRemoved actions stay at pendingAction: add for good. The request we keep needs the earliest queued request's rollback baseline, and the superseded audit action IDs need to be nulled in optimisticData.SEQUENTIAL_QUEUE.md notes that resolvers run twice (prepareRequest and push), so the audit cleanup belongs in replaceReceipt's own optimisticData and not in an Onyx.update inside the resolver.RequestConflictUtilsTest.ts (different transaction, a DETACH_RECEIPT boundary, several queued replacements) and a ReceiptTest.ts flow of three offline replacements, a delete, then reconnect.
@MelvinBot update your proposal to turn the solution into a concrete change: add a transaction-scoped REPLACE_RECEIPT conflict resolver in RequestConflictUtils.ts that stops at a DETACH_RECEIPT for the same transaction, pass it to API.write in replaceReceipt, and collapse unsent replacements to the latest one. Carry the earliest queued request's failureData rollback baseline over to the request we keep, null the superseded optimistic audit actions in replaceReceipt's optimisticData, and keep the resolver pure. Leave DetachReceipt behavior unchanged for now. Include code snippets and the test cases.
Proposal
What is the root cause of that problem?
Each offline replacement is queued separately because replaceReceipt calls API.write without a conflict resolver. Deletion then appends DetachReceipt, so reconnect sends all replacements before detaching.
Simply dropping earlier requests is insufficient: their optimistic audit actions would remain pending, and the surviving request’s failure handler would restore an intermediate, never-uploaded receipt.
What changes do you think we should make in order to solve the problem?
Collapse unsent replacements for the same transaction to the latest one. Leave detachReceipt unchanged. Three offline replacements followed by deletion must produce one ReplaceReceipt, then one DetachReceipt.
1. Add a pure, transaction-scoped resolver
Add getReplaceReceiptConflictIndices and resolveReplaceReceiptConflicts to RequestConflictUtils.ts.
The selector scans backward, ignores other transactions, and stops at the most recent same-transaction DETACH_RECEIPT. It returns matching indices in chronological order. Previously attempted replacements marked isRollback should also be retained as a boundary rather than treated as unsent.
function resolveReplaceReceiptConflicts<TKey extends OnyxKey>(
persistedRequests: Array<OnyxRequest<TKey>>,
transactionID: string,
): ConflictActionData {
const indices = getReplaceReceiptConflictIndices(
persistedRequests,
transactionID,
);
const index = indices.at(-1);
if (index === undefined) {
return {conflictAction: {type: 'push'}};
}
return {
conflictAction: {
type: 'replace',
index,
additionalRemovalIndices: indices.slice(0, -1),
},
};
}
The resolver only computes an action: no Onyx writes, input mutations, ID generation, or audit cleanup. This matters because it runs during both request preparation and queue insertion.
Small queue-support change: additionalRemovalIndices is a proposed optional addition to the existing replace action type. Pass it through the replace executor to PersistedRequests.update. Replace the selected entry and filter the additional original-array indices synchronously, then persist once. Preserve existing request-ID bookkeeping.
This avoids delete followed by push: the current executor awaits deletion before appending, allowing a quickly queued detach to slip ahead of the replacement.
2. Preserve rollback state and remove superseded audit actions
In replaceReceipt, use the same selector against the waiting queue before constructing the new updates. Do not include the ongoing request.
Add a pure inheritReplaceReceiptRollback helper that returns a new failure-data array. Carry forward rollback state selectively, not the earliest failureData wholesale:
| Rollback entry | What the survivor inherits |
|---|---|
| Transaction | Earliest queued receipt baseline, including explicit null. Keep the latest request’s errors, filename, retry parameters, and pending-field cleanup. |
| Transaction violations | Earliest rollback value, including []. |
| Search snapshots | Earliest receipt rollback per exact snapshot key; retain previously touched keys omitted by the latest call. |
| Thread report | Earliest lastVisibleActionCreated and lastReadTime rollback values. |
| Report actions | Keep only the latest request’s failure handling; never restore superseded actions. |
These entries currently originate in the transaction/snapshot rollback and audit/report rollback. Use property-presence checks so null and empty arrays are not mistaken for missing baselines.
For audit cleanup, collect each superseded request’s reportActionID and receiptRemovedReportActionID. Locate their report-actions collection keys from the old failure entries, then prepend cleanup merges to the new request’s optimisticData:
optimisticData.unshift({
onyxMethod: Onyx.METHOD.MERGE,
key: supersededActionsKey,
value: Object.fromEntries(
supersededActionIDs.map((id) => [id, null]),
),
});
Group IDs by collection key. Prepending cleanup allows any deliberately reused retry IDs to be recreated by the latest optimistic action updates.
Also preserve the operation’s net meaning: cropping an unsent replacement must retain replacement auditing, while replacing an unsent attachment that started from no receipt must not invent a “receipt removed” action.
Finally, wire the resolver into the existing API.write call:
API.write(
WRITE_COMMANDS.REPLACE_RECEIPT,
parameters,
{
optimisticData,
successData,
failureData: inheritReplaceReceiptRollback(
supersededRequests,
failureData,
transactionID,
),
},
{
checkAndFixConflictingRequest: (requests) =>
resolveReplaceReceiptConflicts(requests, transactionID),
},
);
No resolver or rollback changes are added to detachReceipt.
3. Regression tests
- Empty queue or another transaction →
push. - One matching replacement →
replace. - Several matches → replace the latest predecessor and remove earlier eligible matches.
- Same-transaction detach stops scanning; another transaction’s detach does not.
- Replacements before a detach remain untouched.
- Repeated evaluation with frozen inputs produces identical results without side effects.
- Three offline replacements → delete → reconnect sends only the latest replacement, followed by the unchanged detach.
- Superseded audit IDs become
nullimmediately offline and never reappear after success or failure. - Replacement failure restores the original server receipt, violations, snapshots, and report timestamps—not an intermediate local file—while retaining the latest upload’s error/retry data.
- Cover an original receipt of
null, empty violations, replacement followed by crop/rotation, and reused retry action IDs. - Update replacement-write assertions to accept the fourth resolver argument.
- An ongoing replacement remains untouched while waiting replacements collapse.
- Multiple pre-existing duplicates compact in one queue update.
- With persistence deferred, immediately enqueueing detach still leaves replacement before detach.
These are proposed tests; no implementation or test execution is claimed.
What alternative solutions did you explore? (Optional)
Generic deduplication does not preserve the detach boundary, rollback baseline, or audit cleanup. Cancelling the final replacement when detach follows is intentionally excluded because it changes receipt-history behavior.
Next Steps for Contributor+ team:
To accept: @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.
@MelvinBot I applied your refined proposal locally, fixed the regression risks I found while reviewing it, and tested the result on dev. Please update your proposal to match this fix. The full diff is below.
How it differs from your proposal:
- The resolver returns
deletewithpushNewRequest, so the keptReplaceReceiptgoes to the end of the queue instead of into the last matching slot. Replacing in place can move it ahead of requests queued after the old replacement, like theOpenReportthat creates the transaction thread its auditreportActionIDs point to. ConflictRequestReplacedoesn't get anadditionalRemovalIndicesfield. The ordering race is fixed inhandleConflictActionsinstead: fordeletewithpushNewRequest, the new request is saved before the deletion is written to disk, so aDetachReceiptqueued right after can't land ahead of it. The existing resolvers that use this path only get stricter ordering.- The scan also stops at a same-transaction
REPLACE_RECEIPTmarkedisRollback, since the server may already have stored it. replaceReceiptreads the superseded requests in the same tick asAPI.write. It takes over the oldest one's rollback values (receipt, violations, snapshots, thread timestamps), keeps its own errors and retry data, and nulls the superseded audit actions inoptimisticData.- A crop or rotate of an unsent replacement is sent with
isSameReceipt: false. When the expense had no receipt before the offline replacements, noreceiptRemovedReportActionIDis sent. logReceiptSupersededrecords the dropped uploads, so they don't show up as stuck receipts in the receipt telemetry.DetachReceiptis unchanged.
Testing:
- On local dev, three offline replacements followed by a delete now send one
ReplaceReceiptwith the latest file, then oneDetachReceipt, both 200. The thread ends with no pending or failed audit actions. - New tests: 6 cases in
RequestConflictUtilsTest.ts, 1 queue ordering case inSequentialQueueTest.tsand 4 offline flows inReceiptTest.ts(collapse and detach, failure rollback, crop after replacement, no receipt before). All of them fail without the fix. - The 60 test suites that touch the queue, persisted requests, conflict resolvers and receipts pass (3,795 tests), and so do typecheck,
lint-changedandspell-changed.
One thing this doesn't change: if the replacements are made in a tab that isn't the leader, the leader tab still sends all of them. That's how it works today and how every other conflict resolver behaves, so it's out of scope here.
Please update the proposal to match this diff, tests included, so we can move to implementation.
Full diff
diff --git a/src/libs/Network/SequentialQueue.ts b/src/libs/Network/SequentialQueue.ts
index aae36752426..37b035983ce 100644
--- a/src/libs/Network/SequentialQueue.ts
+++ b/src/libs/Network/SequentialQueue.ts
@@ -830,12 +830,16 @@ async function handleConflictActions<TKey extends OnyxKey>(conflictAction: Confl
willPushNewRequest: conflictAction.pushNewRequest ?? false,
hasNextAction: !!conflictAction.nextAction,
});
- await deletePersistedRequestsByIndices(conflictAction.indices);
+ const deletion = deletePersistedRequestsByIndices(conflictAction.indices);
if (conflictAction.pushNewRequest) {
Log.info('[SequentialQueue] Pushing new request after delete', false, {
command: newRequest.command,
});
- await savePersistedRequest(newRequest);
+ // Both update the queue in memory before they return, so saving before the deletion reaches the disk keeps the
+ // new request in place. Waiting first would let a request queued in the meantime be saved, and sent, ahead of it.
+ await Promise.all([deletion, savePersistedRequest(newRequest)]);
+ } else {
+ await deletion;
}
if (conflictAction.nextAction) {
Log.info('[SequentialQueue] Processing next conflict action', false, {
diff --git a/src/libs/actions/IOU/Receipt.ts b/src/libs/actions/IOU/Receipt.ts
index a6380f22df3..3d76bb28d22 100644
--- a/src/libs/actions/IOU/Receipt.ts
+++ b/src/libs/actions/IOU/Receipt.ts
@@ -8,13 +8,16 @@ import {navigateToStartMoneyRequestStep} from '@libs/IOUUtils';
import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute';
import Navigation from '@libs/Navigation/Navigation';
import {rand64} from '@libs/NumberUtils';
+import {isRecord} from '@libs/ObjectUtils';
import {hasDependentTags, isGroupPolicy} from '@libs/PolicyUtils';
import ReceiptStorage from '@libs/ReceiptStorage';
import {buildOptimisticReceiptAddedAction, buildOptimisticReceiptRemovedAction, isInvoiceReport as isInvoiceReportReportUtils} from '@libs/ReportUtils';
import {getCurrentSearchQueryJSON} from '@libs/SearchQueryUtils';
-import {logReceiptCaptured, mintAndStampReceiptTraceId} from '@libs/telemetry/ReceiptObservability';
+import {logReceiptCaptured, logReceiptSuperseded, mintAndStampReceiptTraceId} from '@libs/telemetry/ReceiptObservability';
import {hasReceiptSource, hasUploadedReceipt} from '@libs/TransactionUtils';
import ViolationsUtils from '@libs/Violations/ViolationsUtils';
+import {getAll as getAllPersistedRequests} from '@userActions/PersistedRequests';
+import {getSupersededReplaceReceiptIndices, resolveReplaceReceiptConflicts} from '@userActions/RequestConflictUtils';
import type {IOURequestType, IOUType} from '@src/CONST';
import CONST from '@src/CONST';
@@ -22,6 +25,7 @@ import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES, {DYNAMIC_ROUTES} from '@src/ROUTES';
import type * as OnyxTypes from '@src/types/onyx';
import type {CurrentUserPersonalDetails} from '@src/types/onyx/PersonalDetails';
+import type {AnyOnyxUpdate, AnyRequest} from '@src/types/onyx/Request';
import type {SearchResultDataType} from '@src/types/onyx/SearchResults';
import type {Receipt, ReceiptSource} from '@src/types/onyx/Transaction';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
@@ -226,6 +230,75 @@ function detachReceipt({
API.write(WRITE_COMMANDS.DETACH_RECEIPT, parameters, {optimisticData, successData, failureData});
}
+/** The keys `replaceReceipt` writes in its failure data */
+type ReplaceReceiptOnyxKey =
+ | typeof ONYXKEYS.COLLECTION.TRANSACTION
+ | typeof ONYXKEYS.COLLECTION.SNAPSHOT
+ | typeof ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS
+ | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS
+ | typeof ONYXKEYS.COLLECTION.REPORT;
+
+/** Returns the value the oldest of these requests would restore for a key on failure, as written by `replaceReceipt`. */
+function getOriginalRollbackUpdates(supersededRequests: AnyRequest[]): Map<string, AnyOnyxUpdate> {
+ const originalUpdates = new Map<string, AnyOnyxUpdate>();
+ for (const request of supersededRequests) {
+ for (const update of request.failureData ?? []) {
+ const key: unknown = update.key;
+ // Audit actions are left out because the superseded ones are removed, so a failure must not bring them back
+ if (typeof key !== 'string' || key.startsWith(ONYXKEYS.COLLECTION.REPORT_ACTIONS) || originalUpdates.has(key)) {
+ continue;
+ }
+ originalUpdates.set(key, update);
+ }
+ }
+ return originalUpdates;
+}
+
+/**
+ * The oldest queued replacement recorded the state from before any of the offline replacements, while this request's
+ * rollback points at a file that was never uploaded. So on failure this request restores the oldest one's values,
+ * keeping its own errors and retry data on the transaction.
+ */
+function inheritOriginalRollback(
+ failureData: Array<OnyxUpdate<ReplaceReceiptOnyxKey>>,
+ originalUpdates: Map<string, AnyOnyxUpdate>,
+ transactionKey: string,
+): Array<OnyxUpdate<ReplaceReceiptOnyxKey>> {
+ if (originalUpdates.size === 0) {
+ return failureData;
+ }
+
+ const inheritedFailureData = failureData.map((update): OnyxUpdate<ReplaceReceiptOnyxKey> => {
+ const originalUpdate = originalUpdates.get(update.key);
+ if (!originalUpdate) {
+ return update;
+ }
+ if (update.key !== transactionKey) {
+ return originalUpdate;
+ }
+ const originalValue: unknown = originalUpdate.value;
+ if (!isRecord(originalValue) || !('receipt' in originalValue) || !isRecord(update.value)) {
+ return update;
+ }
+ const transactionUpdate: AnyOnyxUpdate = {...update, value: {...update.value, receipt: originalValue.receipt}};
+ return transactionUpdate;
+ });
+
+ // A key only an older request touched, like the snapshot of a search that is no longer open, still has to be restored
+ const ownKeys = new Set<string>(failureData.map((update) => update.key));
+ for (const [key, originalUpdate] of originalUpdates) {
+ if (!ownKeys.has(key)) {
+ inheritedFailureData.push(originalUpdate);
+ }
+ }
+ return inheritedFailureData;
+}
+
+function getStringField(request: AnyRequest, field: string): string | undefined {
+ const value = request.data?.[field];
+ return typeof value === 'string' ? value : undefined;
+}
+
function replaceReceipt({
transaction,
file,
@@ -253,6 +326,29 @@ function replaceReceipt({
const receiptTraceId = mintAndStampReceiptTraceId(file);
logReceiptCaptured({file, captureSource: 'replace', receiptTraceId});
+ // Replacements of this receipt that are still waiting in the queue are dropped when this one is queued (see
+ // resolveReplaceReceiptConflicts), so this request takes over their rollback data and removes their audit actions.
+ // The queue is read in the same tick as API.write, so the resolver drops exactly these requests.
+ const persistedRequests = getAllPersistedRequests();
+ const supersededRequests = getSupersededReplaceReceiptIndices(persistedRequests, transactionID).flatMap((index) => persistedRequests.at(index) ?? []);
+ for (const request of supersededRequests) {
+ const queuedReceipt = request.data?.receipt;
+ logReceiptSuperseded({
+ receiptTraceId: isRecord(queuedReceipt) && typeof queuedReceipt.receiptTraceId === 'string' ? queuedReceipt.receiptTraceId : undefined,
+ transactionID,
+ command: request.command,
+ });
+ }
+ const transactionKey = `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`;
+ const originalRollbackUpdates = getOriginalRollbackUpdates(supersededRequests);
+ const originalTransactionRollback: unknown = originalRollbackUpdates.get(transactionKey)?.value;
+ const hasOriginalReceiptRollback = isRecord(originalTransactionRollback) && 'receipt' in originalTransactionRollback;
+ const originalReceipt = hasOriginalReceiptRollback ? originalTransactionRollback.receipt : undefined;
+
+ // The server never saw the file a crop or rotate edits if that file was itself an unsent replacement, so it has to get
+ // a replacement. Otherwise it would skip the audit actions while the superseded request's ones are already removed.
+ const isSameReceiptOnServer = !!isSameReceipt && !supersededRequests.some((request) => !request.data?.isSameReceipt);
+
const oldReceipt = transaction?.receipt ?? {};
const receiptOptimistic = {
source,
@@ -264,23 +360,27 @@ function replaceReceipt({
pageCount: null,
// A new receipt must not keep the old one's reservation dates, or the per-night limit check would use them.
// A crop or rotate keeps the same receipt, so its dates stay.
- ...(isSameReceipt ? {} : {hotelReservationStartDate: null, hotelReservationEndDate: null}),
+ ...(isSameReceiptOnServer ? {} : {hotelReservationStartDate: null, hotelReservationEndDate: null}),
};
const newTransaction = transaction && {...transaction, receipt: receiptOptimistic};
// The audit action IDs are chosen before the optimistic data is built. A retry passes the same IDs back
// so it updates the failed actions. Nothing is posted for a crop or rotate, or when the thread does not exist yet.
const transactionThreadReportID = transactionThreadReport?.reportID;
- const optimisticReceiptAddedActionID = !isSameReceipt && transactionThreadReportID ? (receiptAddedReportActionID ?? rand64()) : undefined;
+ const optimisticReceiptAddedActionID = !isSameReceiptOnServer && transactionThreadReportID ? (receiptAddedReportActionID ?? rand64()) : undefined;
// A receipt added offline has a file but no receipt ID yet, and that still counts as one being replaced.
- const isReplacingReceipt = !!transaction && (hasReceiptSource(transaction) || hasUploadedReceipt(transaction));
+ // When earlier replacements are dropped, what counts is the receipt from before them, so replacing an unsent
+ // file on an expense that had no receipt does not tell the server a receipt was removed.
+ const isReplacingReceipt = hasOriginalReceiptRollback
+ ? isRecord(originalReceipt) && (!!originalReceipt.source || !!originalReceipt.receiptID)
+ : !!transaction && (hasReceiptSource(transaction) || hasUploadedReceipt(transaction));
const optimisticReceiptRemovedActionID = optimisticReceiptAddedActionID && isReplacingReceipt ? (receiptRemovedReportActionID ?? rand64()) : undefined;
const retryParams: ReplaceReceiptRetryParams = {
transactionID: transaction.transactionID,
file: undefined,
source,
state,
- isSameReceipt,
+ isSameReceipt: isSameReceiptOnServer,
transactionPolicy,
transactionPolicyCategories,
transactionPolicyTagList,
@@ -325,15 +425,7 @@ function replaceReceipt({
},
];
- const failureData: Array<
- OnyxUpdate<
- | typeof ONYXKEYS.COLLECTION.TRANSACTION
- | typeof ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS
- | typeof ONYXKEYS.COLLECTION.SNAPSHOT
- | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS
- | typeof ONYXKEYS.COLLECTION.REPORT
- >
- > = [
+ const failureData: Array<OnyxUpdate<ReplaceReceiptOnyxKey>> = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`,
@@ -424,6 +516,18 @@ function replaceReceipt({
const optimisticAuditActions = [optimisticReceiptRemovedAction, optimisticReceiptAddedAction].filter((action) => !!action);
+ // The superseded requests are never sent, so their audit actions would otherwise stay pending in the thread for good
+ const supersededAuditActionIDs = supersededRequests
+ .flatMap((request) => [getStringField(request, 'reportActionID'), getStringField(request, 'receiptRemovedReportActionID')])
+ .filter((reportActionID): reportActionID is string => !!reportActionID && reportActionID !== optimisticReceiptAddedActionID && reportActionID !== optimisticReceiptRemovedActionID);
+ if (supersededAuditActionIDs.length > 0 && transactionThreadReportID) {
+ optimisticData.push({
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadReportID}`,
+ value: Object.fromEntries(supersededAuditActionIDs.map((reportActionID) => [reportActionID, null])),
+ });
+ }
+
if (optimisticAuditActions.length > 0 && transactionThreadReportID) {
const lastAuditAction = optimisticAuditActions.at(-1);
optimisticData.push(
@@ -478,12 +582,17 @@ function replaceReceipt({
transactionID,
receipt,
receiptState: state,
- isSameReceipt,
+ isSameReceipt: isSameReceiptOnServer,
reportActionID: optimisticReceiptAddedAction?.reportActionID,
receiptRemovedReportActionID: optimisticReceiptRemovedAction?.reportActionID,
};
- API.write(WRITE_COMMANDS.REPLACE_RECEIPT, parameters, {optimisticData, successData, failureData});
+ API.write(
+ WRITE_COMMANDS.REPLACE_RECEIPT,
+ parameters,
+ {optimisticData, successData, failureData: inheritOriginalRollback(failureData, originalRollbackUpdates, transactionKey)},
+ {checkAndFixConflictingRequest: (requests) => resolveReplaceReceiptConflicts(requests, transactionID)},
+ );
}
function setMoneyRequestReceipt(
diff --git a/src/libs/actions/RequestConflictUtils.ts b/src/libs/actions/RequestConflictUtils.ts
index 358d5d9847e..3826c3202ef 100644
--- a/src/libs/actions/RequestConflictUtils.ts
+++ b/src/libs/actions/RequestConflictUtils.ts
@@ -275,6 +275,52 @@ function resolveCommentDeletionConflicts<TKey extends OnyxKey>(persistedRequests
};
}
+/**
+ * Returns the indices of this transaction's receipt replacements that are still waiting in the queue, oldest first.
+ * The scan stops at a detach of the same receipt, because a replacement made before a deletion is part of the receipt
+ * history. It also stops at a replacement that was already sent once (`isRollback`), because the server may have stored it.
+ */
+function getSupersededReplaceReceiptIndices(persistedRequests: AnyRequest[], transactionID: string): number[] {
+ const indices: number[] = [];
+ for (let index = persistedRequests.length - 1; index >= 0; index--) {
+ const request = persistedRequests.at(index);
+ if (request?.data?.transactionID !== transactionID) {
+ continue;
+ }
+ if (request.command === WRITE_COMMANDS.DETACH_RECEIPT || (request.command === WRITE_COMMANDS.REPLACE_RECEIPT && request.isRollback)) {
+ break;
+ }
+ if (request.command === WRITE_COMMANDS.REPLACE_RECEIPT) {
+ indices.unshift(index);
+ }
+ }
+ return indices;
+}
+
+/**
+ * Only the latest file of a receipt replaced several times offline needs to be uploaded, so the waiting replacements are
+ * dropped and the new one goes to the end of the queue, after anything queued since. `replaceReceipt` reads the same
+ * requests to take over their rollback data and audit actions, so this has to stay free of side effects.
+ */
+function resolveReplaceReceiptConflicts(persistedRequests: AnyRequest[], transactionID: string): ConflictActionData {
+ const indices = getSupersededReplaceReceiptIndices(persistedRequests, transactionID);
+ if (indices.length === 0) {
+ return {
+ conflictAction: {
+ type: 'push',
+ },
+ };
+ }
+
+ return {
+ conflictAction: {
+ type: 'delete',
+ indices,
+ pushNewRequest: true,
+ },
+ };
+}
+
/**
* The server reads the stored file's extension from the name it is uploaded under, and a download can only put back
* an extension the stored copy already has. So dropping it in a rename would leave the file with none for good.
@@ -446,6 +492,8 @@ export {
resolveEnableFeatureConflicts,
enablePolicyFeatureCommand,
resolveVacationDelegateDeletionConflicts,
+ getSupersededReplaceReceiptIndices,
+ resolveReplaceReceiptConflicts,
};
export type {EnablePolicyFeatureCommand, AnyRequestMatcher};
diff --git a/src/libs/telemetry/ReceiptObservability.ts b/src/libs/telemetry/ReceiptObservability.ts
index 67670cf03d0..714bd3e6716 100644
--- a/src/libs/telemetry/ReceiptObservability.ts
+++ b/src/libs/telemetry/ReceiptObservability.ts
@@ -240,6 +240,19 @@ function logReceiptGaveUp({
});
}
+/**
+ * Records the superseded milestone: the receipt was replaced again before its upload was sent, so its request was dropped
+ * from the queue and this file is never uploaded. Without it the receipt looks enqueued but never sent, like a stuck queue.
+ */
+function logReceiptSuperseded({receiptTraceId, transactionID, command}: {receiptTraceId: string | undefined; transactionID: string | undefined; command: string}) {
+ Log.info(`${RECEIPT_LOG_PREFIX} superseded`, true, {
+ event: 'superseded',
+ receiptTraceId,
+ transactionID,
+ command,
+ });
+}
+
function logReceiptStatFailed(code: string | undefined) {
Log.info(`${RECEIPT_LOG_PREFIX} stat failed`, false, {
event: 'statFailed',
@@ -395,6 +408,7 @@ export {
logReceiptEnqueued,
logReceiptDropped,
logReceiptGaveUp,
+ logReceiptSuperseded,
logReceiptStatFailed,
logReceiptAdoptFailed,
logCameraCaptureFailed,
diff --git a/tests/actions/IOUTest/ReceiptTest.ts b/tests/actions/IOUTest/ReceiptTest.ts
index 6c8c5015967..8fb7e283612 100644
--- a/tests/actions/IOUTest/ReceiptTest.ts
+++ b/tests/actions/IOUTest/ReceiptTest.ts
@@ -6,8 +6,11 @@ import type {SearchQueryJSON} from '@components/Search/types';
import {detachReceipt, replaceReceipt, setMoneyRequestReceipt} from '@libs/actions/IOU/Receipt';
import initOnyxDerivedValues from '@libs/actions/OnyxDerived';
import {WRITE_COMMANDS} from '@libs/API/types';
+import {flush as flushSequentialQueue, waitForIdle} from '@libs/Network/SequentialQueue';
import type * as PolicyUtils from '@libs/PolicyUtils';
+import {clear as clearPersistedRequests, getAll as getAllPersistedRequests} from '@userActions/PersistedRequests';
+
import CONST from '@src/CONST';
import OnyxUpdateManager from '@src/libs/actions/OnyxUpdateManager';
import * as API from '@src/libs/API';
@@ -27,7 +30,8 @@ import {createRandomReport} from '../../utils/collections/reports';
import createRandomTransaction from '../../utils/collections/transaction';
import createMock from '../../utils/createMock';
import getOnyxValue from '../../utils/getOnyxValue';
-import {getGlobalFetchMock, getRequiredOnyxUpdate, getRequiredOnyxUpdates, getRequiredWriteCall} from '../../utils/TestHelper';
+import type {MockFetch} from '../../utils/TestHelper';
+import {expectAPICommandToHaveBeenCalled, getGlobalFetchMock, getRequiredOnyxUpdate, getRequiredOnyxUpdates, getRequiredWriteCall} from '../../utils/TestHelper';
import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates';
jest.mock('@src/libs/Navigation/Navigation', () => ({
@@ -380,7 +384,12 @@ describe('actions/IOU/Receipt', () => {
await waitForBatchedUpdates();
// Then API.write is invoked with the REPLACE_RECEIPT command and the correct transactionID
- expect(writeSpy).toHaveBeenCalledWith(WRITE_COMMANDS.REPLACE_RECEIPT, expect.objectContaining({transactionID}), expect.anything());
+ expect(writeSpy).toHaveBeenCalledWith(
+ WRITE_COMMANDS.REPLACE_RECEIPT,
+ expect.objectContaining({transactionID}),
+ expect.anything(),
+ expect.objectContaining({checkAndFixConflictingRequest: expect.any(Function)}),
+ );
} finally {
writeSpy.mockRestore();
}
@@ -641,6 +650,7 @@ describe('actions/IOU/Receipt', () => {
receipt: expect.any(Object),
}),
expect.anything(),
+ expect.objectContaining({checkAndFixConflictingRequest: expect.any(Function)}),
);
} finally {
writeSpy.mockRestore();
@@ -981,6 +991,156 @@ describe('actions/IOU/Receipt', () => {
writeSpy.mockRestore();
}
});
+
+ describe('several times while offline', () => {
+ const threadReportID = 'replaceReceiptOfflineCollapseThreadReportID';
+ const currentUserPersonalDetails = {accountID: RORY_ACCOUNT_ID, email: RORY_EMAIL};
+ let mockFetch: MockFetch;
+
+ const getThreadReport = () => getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${threadReportID}`);
+
+ // Each call reads the transaction again, like the receipt view does after the previous replacement
+ const replaceWithLatestState = async (replacementSource: string, isSameReceipt?: boolean) => {
+ replaceReceipt({
+ transaction: await getUpdatedTransaction(transactionID),
+ file: createFile(),
+ source: replacementSource,
+ isSameReceipt,
+ transactionPolicy: undefined,
+ transactionPolicyTagList: undefined,
+ transactionReport: undefined,
+ isVendorMatchingBetaEnabled: false,
+ delegateAccountID: undefined,
+ currentUserPersonalDetails,
+ transactionThreadReport: await getThreadReport(),
+ });
+ await waitForBatchedUpdates();
+ };
+
+ const getQueuedReplacement = () => getAllPersistedRequests().find((request) => request.command === WRITE_COMMANDS.REPLACE_RECEIPT);
+
+ const getAuditActionIDs = (request: ReturnType<typeof getQueuedReplacement>) =>
+ [request?.data?.reportActionID, request?.data?.receiptRemovedReportActionID].filter((reportActionID) => typeof reportActionID === 'string');
+
+ const reconnect = async () => {
+ await Onyx.set(ONYXKEYS.NETWORK, {shouldForceOffline: false});
+ flushSequentialQueue();
+ await waitForIdle();
+ await waitForBatchedUpdates();
+ };
+
+ beforeEach(async () => {
+ mockFetch = getGlobalFetchMock();
+ global.fetch = mockFetch;
+ clearPersistedRequests();
+ await Onyx.set(ONYXKEYS.NETWORK, {shouldForceOffline: true});
+ await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${threadReportID}`, {...createRandomReport(2, undefined), reportID: threadReportID, lastVisibleActionCreated: '2026-01-01 00:00:00.000'});
+ await setupTransactionWithSnapshot(transactionID, {receipt: OLD_RECEIPT});
+ });
+
+ afterEach(async () => {
+ await Onyx.set(ONYXKEYS.NETWORK, {shouldForceOffline: false});
+ clearPersistedRequests();
+ });
+
+ it('should send only the latest replacement, followed by the detach', async () => {
+ // Given three replacements of the receipt and a delete, all made offline
+ await replaceWithLatestState('first.jpg');
+ await replaceWithLatestState('second.jpg');
+ const supersededAuditActionIDs = getAuditActionIDs(getQueuedReplacement());
+ await replaceWithLatestState('third.jpg');
+ const keptAuditActionIDs = getAuditActionIDs(getQueuedReplacement());
+ detachReceipt({
+ transaction: await getUpdatedTransaction(transactionID),
+ transactionPolicy: undefined,
+ transactionPolicyTagList: undefined,
+ transactionViolations: undefined,
+ transactionReport: undefined,
+ isVendorMatchingBetaEnabled: false,
+ transactionThreadReport: await getThreadReport(),
+ delegateAccountID: undefined,
+ currentUserPersonalDetails,
+ });
+ await waitForBatchedUpdates();
+
+ // Then the queue holds the third file and the detach, and the audit actions of the dropped uploads are gone,
+ // because they would otherwise stay pending in the thread with no request left to clear them
+ expect(getAllPersistedRequests()).toEqual([
+ expect.objectContaining({command: WRITE_COMMANDS.REPLACE_RECEIPT, data: expect.objectContaining({receipt: expect.objectContaining({source: 'third.jpg'})})}),
+ expect.objectContaining({command: WRITE_COMMANDS.DETACH_RECEIPT}),
+ ]);
+ expect(supersededAuditActionIDs).toHaveLength(2);
+ const threadActions = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${threadReportID}`);
+ for (const reportActionID of supersededAuditActionIDs) {
+ expect(threadActions?.[reportActionID]).toBeUndefined();
+ }
+ for (const reportActionID of keptAuditActionIDs) {
+ expect(threadActions?.[reportActionID]).toBeDefined();
+ }
+
+ // When the connection comes back
+ await reconnect();
+
+ // Then one ReplaceReceipt and one DetachReceipt are sent, and the dropped audit actions do not come back
+ expectAPICommandToHaveBeenCalled(WRITE_COMMANDS.REPLACE_RECEIPT, 1);
+ expectAPICommandToHaveBeenCalled(WRITE_COMMANDS.DETACH_RECEIPT, 1);
+ const threadActionsAfterSync = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${threadReportID}`);
+ for (const reportActionID of supersededAuditActionIDs) {
+ expect(threadActionsAfterSync?.[reportActionID]).toBeUndefined();
+ }
+ });
+
+ it('should restore the receipt from before the offline replacements when the kept upload fails', async () => {
+ // Given three replacements made offline
+ await replaceWithLatestState('first.jpg');
+ await replaceWithLatestState('second.jpg');
+ await replaceWithLatestState('third.jpg');
+
+ // When the only upload left fails after reconnecting
+ mockFetch.fail();
+ await reconnect();
+
+ // Then the expense and the search snapshot show the receipt it had before, not the unsent second file,
+ // and the failure keeps the error and retry data of the third file
+ const transaction = await getUpdatedTransaction(transactionID);
+ expect(transaction?.receipt?.source).toBe(OLD_RECEIPT.source);
+ const snapshot = await getSearchSnapshot(snapshotHash);
+ expect(snapshot?.data?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]?.receipt?.source).toBe(OLD_RECEIPT.source);
+ const receiptError = Object.values(transaction?.errors ?? {}).at(0);
+ expect(receiptError).toEqual(expect.objectContaining({source: 'third.jpg'}));
+ const threadReport = await getThreadReport();
+ expect(threadReport?.lastVisibleActionCreated).toBe('2026-01-01 00:00:00.000');
+ });
+
+ it('should send a crop of an unsent replacement as a replacement', async () => {
+ // Given a replacement made offline
+ await replaceWithLatestState('first.jpg');
+
+ // When the new file is cropped before it is sent
+ await replaceWithLatestState('first-cropped.jpg', true);
+
+ // Then the server is told about a replacement, with both audit actions, because it never saw the file being cropped
+ const queuedReplacement = getQueuedReplacement();
+ expect(getAllPersistedRequests()).toHaveLength(1);
+ expect(queuedReplacement?.data).toEqual(expect.objectContaining({isSameReceipt: false}));
+ expect(getAuditActionIDs(queuedReplacement)).toHaveLength(2);
+ });
+
+ it('should not report a removed receipt when the expense had none before the offline replacements', async () => {
+ // Given an expense without a receipt that gets one offline
+ await setupTransactionWithSnapshot(transactionID, {receipt: null});
+ await replaceWithLatestState('first.jpg');
+
+ // When that unsent receipt is replaced again
+ await replaceWithLatestState('second.jpg');
+
+ // Then only "added a receipt" is sent, because the server never had a receipt to remove
+ const queuedReplacement = getQueuedReplacement();
+ expect(getAllPersistedRequests()).toHaveLength(1);
+ expect(queuedReplacement?.data?.reportActionID).toEqual(expect.any(String));
+ expect(queuedReplacement?.data?.receiptRemovedReportActionID).toBeUndefined();
+ });
+ });
});
describe('detachReceipt', () => {
diff --git a/tests/unit/RequestConflictUtilsTest.ts b/tests/unit/RequestConflictUtilsTest.ts
index 1e8daea6724..3068d3b8661 100644
--- a/tests/unit/RequestConflictUtilsTest.ts
+++ b/tests/unit/RequestConflictUtilsTest.ts
@@ -7,6 +7,7 @@ import {
resolveOpenAppDuplicationConflictAction,
resolveOpenReportDuplicationConflictAction,
resolveReconnectDuplicationConflictAction,
+ resolveReplaceReceiptConflicts,
resolveVacationDelegateDeletionConflicts,
} from '@libs/actions/RequestConflictUtils';
import {WRITE_COMMANDS} from '@libs/API/types';
@@ -467,4 +468,45 @@ describe('RequestConflictUtils', () => {
expect(resolveOpenAppDuplicationConflictAction(persistedRequests, ongoingRequest, shouldDedupeWithInFlight)).toEqual(expected);
});
});
+
+ describe('resolveReplaceReceiptConflicts', () => {
+ const replace = (transactionID: string, isRollback?: boolean): AnyRequest => ({command: WRITE_COMMANDS.REPLACE_RECEIPT, data: {transactionID}, isRollback});
+ const detach = (transactionID: string): AnyRequest => ({command: WRITE_COMMANDS.DETACH_RECEIPT, data: {transactionID}});
+
+ it.each<[string, AnyRequest[], ReturnType<typeof resolveReplaceReceiptConflicts>]>([
+ // Given no queued replacement of this receipt, the new one is simply queued
+ ['pushes when the queue is empty', [], {conflictAction: {type: 'push'}}],
+ ['pushes when only another expense has a queued replacement', [replace('2')], {conflictAction: {type: 'push'}}],
+ // Given unsent replacements of this receipt, only the newest file needs uploading, so they are all dropped
+ [
+ 'drops every waiting replacement of the receipt and keeps the rest of the queue',
+ [replace('1'), {command: WRITE_COMMANDS.OPEN_REPORT, data: {reportID: '3'}}, replace('2'), replace('1')],
+ {conflictAction: {type: 'delete', indices: [0, 3], pushNewRequest: true}},
+ ],
+ // Given a detach in between, the replacement before it is part of the receipt history and has to be sent
+ ['stops at a detach of the same receipt', [replace('1'), detach('1'), replace('1')], {conflictAction: {type: 'delete', indices: [2], pushNewRequest: true}}],
+ ['looks past a detach of another expense', [replace('1'), detach('2'), replace('1')], {conflictAction: {type: 'delete', indices: [0, 2], pushNewRequest: true}}],
+ // Given a replacement that was already sent once, the server may have stored it, so it is kept with everything before it
+ ['stops at a replacement that was already sent', [replace('1'), replace('1', true), replace('1')], {conflictAction: {type: 'delete', indices: [2], pushNewRequest: true}}],
+ ])('%s', (_case, persistedRequests, expected) => {
+ // When the conflict is resolved for transaction 1
+ const result = resolveReplaceReceiptConflicts(persistedRequests, '1');
+
+ // Then the result matches the expected queue action
+ expect(result).toEqual(expected);
+ });
+
+ it('returns the same action on every run without changing the queue', () => {
+ // Given a frozen queue, because the resolver runs once when the request is prepared and again when it is queued
+ const persistedRequests = Object.freeze([Object.freeze(replace('1')), Object.freeze(replace('1'))]);
+
+ // When it is resolved twice
+ const first = resolveReplaceReceiptConflicts([...persistedRequests], '1');
+ const second = resolveReplaceReceiptConflicts([...persistedRequests], '1');
+
+ // Then both runs agree and nothing was written
+ expect(first).toEqual(second);
+ expect(first).toEqual({conflictAction: {type: 'delete', indices: [0, 1], pushNewRequest: true}});
+ });
+ });
});
diff --git a/tests/unit/SequentialQueueTest.ts b/tests/unit/SequentialQueueTest.ts
index 7e5abb8ae08..5ba05d45d35 100644
--- a/tests/unit/SequentialQueueTest.ts
+++ b/tests/unit/SequentialQueueTest.ts
@@ -1,4 +1,4 @@
-import {resolveOpenAppDuplicationConflictAction, resolveReconnectDuplicationConflictAction} from '@libs/actions/RequestConflictUtils';
+import {resolveOpenAppDuplicationConflictAction, resolveReconnectDuplicationConflictAction, resolveReplaceReceiptConflicts} from '@libs/actions/RequestConflictUtils';
import {isClientTheLeader} from '@libs/ActiveClientManager';
import type {WriteCommand} from '@libs/API/types';
import {WRITE_COMMANDS} from '@libs/API/types';
@@ -163,6 +163,35 @@ describe('SequentialQueue', () => {
}
});
+ it('should keep a request that replaces deleted ones ahead of a request queued right after it', async () => {
+ SequentialQueue.pause();
+ try {
+ // Given a receipt replacement for transaction 1 waiting behind an unrelated request
+ await SequentialQueue.push({command: WRITE_COMMANDS.REPLACE_RECEIPT, data: {transactionID: '1', receiptState: 'first'}});
+ await SequentialQueue.push({command: WRITE_COMMANDS.OPEN_REPORT, data: {reportID: '2'}});
+
+ // When a newer replacement drops it, and the receipt is detached before the deletion reaches the disk
+ const replacement: AnyRequest = {
+ command: WRITE_COMMANDS.REPLACE_RECEIPT,
+ data: {transactionID: '1', receiptState: 'latest'},
+ checkAndFixConflictingRequest: (persistedRequests) => resolveReplaceReceiptConflicts(persistedRequests, '1'),
+ };
+ const replacementPush = SequentialQueue.push(replacement);
+ const detachPush = SequentialQueue.push({command: WRITE_COMMANDS.DETACH_RECEIPT, data: {transactionID: '1'}});
+ await Promise.all([replacementPush, detachPush]);
+
+ // Then only the latest replacement is left, still ahead of the detach that followed it, because sending the
+ // detach first would leave the expense with the replaced receipt instead of no receipt
+ expect(getAll().map((queuedRequest) => [queuedRequest.command, queuedRequest.data?.receiptState])).toEqual([
+ [WRITE_COMMANDS.OPEN_REPORT, undefined],
+ [WRITE_COMMANDS.REPLACE_RECEIPT, 'latest'],
+ [WRITE_COMMANDS.DETACH_RECEIPT, undefined],
+ ]);
+ } finally {
+ SequentialQueue.unpause();
+ }
+ });
+
it('should push two requests with conflict resolution and push', () => {
SequentialQueue.push(request);
const requestWithConflictResolution: Request<never> = {
Proposal
Revised to match ikevin127’s supplied fix, replacing the earlier in-place replacement design.
What is the root cause of that problem?
replaceReceipt queues every offline replacement without conflict resolution. Reconnecting therefore uploads every file before the separately queued detach.
Discarding requests alone would leave their optimistic audit actions pending and let the surviving request restore an unsent intermediate receipt on failure.
What changes do you think we should make in order to solve the problem?
Keep only the latest unsent replacement for each transaction, appended after existing requests. Leave DetachReceipt unchanged.
Queue resolution and ordering
Add getSupersededReplaceReceiptIndices and resolveReplaceReceiptConflicts to RequestConflictUtils.ts.
The selector scans backward, returns matching indices oldest-first, ignores other transactions, and stops at either:
- A same-transaction
DETACH_RECEIPT. - A same-transaction
REPLACE_RECEIPTmarkedisRollback, because the server may already have stored it.
The pure resolver returns:
return indices.length === 0
? {conflictAction: {type: 'push'}}
: {conflictAction: {type: 'delete', indices, pushNewRequest: true}};
Appending—not replacing in place—keeps the latest upload behind intervening dependencies such as the OpenReport that creates its audit thread.
Fix the asynchronous gap in handleConflictActions:
const deletion = deletePersistedRequestsByIndices(conflictAction.indices);
if (conflictAction.pushNewRequest) {
await Promise.all([deletion, savePersistedRequest(newRequest)]);
} else {
await deletion;
}
Both operations update the queue in memory before returning their persistence promises. Starting both before awaiting prevents a subsequent detach from being inserted ahead of the replacement. Preserve subsequent nextAction handling.
No additionalRemovalIndices field or changes to PersistedRequests.update are needed.
Rollback, audit actions, crop semantics, and telemetry
In replaceReceipt, read superseded waiting requests in the same synchronous tick as API.write, using the shared selector.
- Rollback: Add
getOriginalRollbackUpdatesto collect the oldest failure update per key, excluding report actions. AddinheritOriginalRollbackto inherit those values. For the transaction, inherit onlyreceipt, retaining the latest request’s errors and retry data. Carry forward violations, snapshot updates, and thread timestamps, including keys absent from the latest request. - Audit cleanup: Null superseded
reportActionIDandreceiptRemovedReportActionIDentries in the current thread’soptimisticData, excluding IDs used by the surviving request. Do not inherit superseded audit-action failure updates. - Crop/rotate: Compute
isSameReceiptOnServer. Cropping an unsent ordinary replacement must sendisSameReceipt: false; use that effective value consistently for receipt metadata, auditing, retry data, and API parameters. - Initially receipt-less expense: Determine removal eligibility from the original rollback receipt, not an intermediate local file. Do not send
receiptRemovedReportActionIDwhen there was originally no receipt. - Telemetry: Add and export
logReceiptSupersededinReceiptObservability.ts, recordingevent: 'superseded', receipt trace ID, transaction ID, and command for each dropped upload.
Wire the resolver through API.write’s fourth argument:
API.write(
WRITE_COMMANDS.REPLACE_RECEIPT,
parameters,
{optimisticData, successData,
failureData: inheritOriginalRollback(
failureData, originalRollbackUpdates, transactionKey,
)},
{checkAndFixConflictingRequest: (requests) =>
resolveReplaceReceiptConflicts(requests, transactionID)},
);
Keep queue reads, telemetry, and optimistic cleanup outside the resolver so evaluating it twice has no side effects.
Tests and reported validation
RequestConflictUtilsTest.ts: Six table-driven cases covering empty queue, another transaction, multiple replacements with unrelated requests, same-transaction detach, another transaction’s detach, and an isRollback boundary. Include the separate repeatability/input-immutability test.
SequentialQueueTest.ts: Immediately enqueue detach after a superseding replacement without awaiting persistence. Assert the order remains OpenReport → latest ReplaceReceipt → DetachReceipt.
ReceiptTest.ts: Add four offline flows:
- Three replacements and deletion send one latest-file replacement followed by detach; superseded audit actions disappear.
- Failed surviving upload restores the original receipt, snapshot, and thread timestamp while retaining the latest file’s error.
- Crop after an unsent replacement retains replacement semantics and auditing.
- An originally receipt-less expense sends no removal action.
Update existing write assertions for the fourth argument.
Validation reported by ikevin127: Local dev sends the latest replacement and then detach, both HTTP 200, with no pending or failed audit actions. The regression tests fail without the fix; 60 suites / 3,795 tests, typecheck, lint-changed, and spell-changed pass. These results were not independently rerun here.
Scope: Non-leader-tab deduplication remains unchanged and out of scope.
What alternative solutions did you explore? (Optional)
In-place replacement can move the upload ahead of dependencies, so it is excluded. Dropping the final replacement when detach follows would change receipt history and is also excluded.
Next Steps for Contributor+ team:
To accept: @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.
Proposal 3 (MelvinBot) is the only proposal in scope since this issue doesn't have the Help Wanted label. It now matches the fix I tested on local dev: the resolver adds the kept ReplaceReceipt to the end of the queue, handleConflictActions saves the new request before the deletion is written to disk, and replaceReceipt handles the rollback, audit cleanup, crop and "no receipt before" cases.
On local dev, three offline replacements followed by a delete now send one ReplaceReceipt with the latest file, then one DetachReceipt, both 200, and the thread ends with no pending or failed audit actions. The new tests fail without the fix, and the 60 related suites pass.
One known gap, out of scope here: if the replacements are made in a tab that isn't the leader, the leader tab still sends all of them, because it never picks up deletions made in another tab. Every existing conflict resolver has the same gap and this fix doesn't change it, so it's better handled in a separate issue if we think it's worth fixing.
🎀👀🎀 C+ reviewed
Triggered auto assignment to @francoisl, see https://stackoverflow.com/c/expensify/questions/7972 for more details.
@francoisl Let me know if you agree with the proposal, then we can move to implementation.
Yes sounds good, let's go with Melvin's proposal.
One more thing though, this seems to be a regression, right? I haven't checked in detail but it seems to be from https://github.com/Expensify/App/pull/103279, let's make sure that we're not reintroducing an issue this PR was fixing.
@MelvinBot Implement this and open a draft PR, making sure to consider PR https://github.com/Expensify/App/pull/103279 to make sure that we're not reintroducing an issue this PR was fixing.
🤖 Web test steps verification results: ❌ fail
Implemented and opened draft PR: Collapse unsent receipt replacements while preserving audit history, assigned to ikevin127. Browser verification was blocked by a suspended session—not a product failure.
| Step | Status |
|---|---|
Three offline replacements, delete, then reconnectNot exercised: browser returned session_suspended. Screenshot upload was also blocked by tool permissions. |
❌ |
Preserve both offline add/delete cyclesNot exercised because of the same browser blocker. Automated regression coverage passes. |
❌ |
Automated validation: 16 suites / 1,159 tests pass, plus typecheck, changed-file lint, spelling, formatting, and Storybook smoke checks. Broad Jest runs timed out without reporting failures.
Reviewed Add an audit trail for receipt additions and added regression coverage preserving additions and removals across detach boundaries. DetachReceipt remains unchanged.
view run · no recording available
@ikevin127
The solution for this issue has been :rocket: deployed to production :rocket: in version 9.5.52-4 and is now subject to a 7-day regression period :calendar:. Here is the list of pull requests that resolve this issue:
- https://github.com/Expensify/App/pull/107358
If no regressions arise, payment will be issued on 2026-11-30. :confetti_ball:
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]
Contributor+ Checklist:
-
[x] [Contributor] The offending PR and associated issue have been commented on, pointing out the bug it caused and why, so the author and reviewers can learn from the mistake.
Link to the comment on the PR: https://github.com/Expensify/App/pull/103279/changes#r4689658045 Link to the comment on the Issue: https://github.com/Expensify/App/issues/102533#issuecomment-7151053579
-
[x] [Contributor] If the regression was CRITICAL (e.g. interrupts a core flow) A discussion in #expensify-open-source has been started about whether any other steps should be taken (e.g. updating the PR review checklist) in order to catch this type of bug sooner.
Link to discussion: N/A
-
[x] [Contributor] If it was decided to create a regression test for the bug, please propose the regression test steps using the template below to ensure the same bug will not reach production again.
Regression Test Proposal
- Go to a workspace chat.
- Create a scan expense with a valid receipt and wait for scanning to finish.
- Open the expense.
- Go offline.
- Click the receipt, click
Replaceand choose a different image. - Repeat step 5 two more times, with a different image each time.
- Click the receipt, open the three dots menu, click
Delete receiptand confirm withDelete. - Go online and wait for the expense to sync.
- Verify that the expense has no receipt, that the expense thread shows a single "added a receipt" message for the offline replacements (not one per replacement) followed by "removed a receipt", and that no errors appear.
Do we agree 👍 or 👎.
Triggered auto assignment to @mallenexpensify (Awaiting Payment)