Repository navigation
Collapse unsent receipt replacements while preserving audit history - #107358
Conversation
…tory Co-authored-by: Kevin Brian Bader <ikevin127@users.noreply.github.com>
|
|
Codecov Report✅ Changes either increased or maintained existing code coverage, great job!
|
|
@MelvinBot Check all checkboxes on PR Author Checklist (without moving or removing any of them), then go ahead and complete the Tests, Offline tests and QA Steps ("Same as Tests.") based on the issue's expected result with "Verify that..." verifying the fix, then once that's done mark the PR ready for review. |
|
Done:
No new tests were run; existing verification limitations remain documented. |
|
@ikevin127 Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button] |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f69cfe8968
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (update.key !== transactionKey) { | ||
| return originalUpdate; |
There was a problem hiding this comment.
Preserve intervening thread activity when inheriting rollback
If a user replaces a receipt offline, posts a comment in the expense thread, and then replaces the receipt again, this branch replaces the latest request's report rollback with the timestamps from before the first replacement. Posting the comment updates both lastVisibleActionCreated and lastReadTime in src/libs/actions/Report/index.ts, and the conflict resolver preserves that comment request ahead of the surviving upload. If the comment succeeds but the upload fails, its inherited rollback therefore rewinds the thread timestamps past a successfully posted comment, leaving incorrect activity ordering and read state. Preserve intervening non-superseded activity when calculating the report rollback instead of unconditionally taking the oldest report update.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed by source inspection: Report/index.ts:1034–1040 advances both timestamps for a comment, but Receipt.ts:298–299 still unconditionally inherits the older report rollback. If the retained comment succeeds and the surviving upload fails, the rollback can rewind past the comment.
Simply keeping the newest report rollback would instead retain timestamps from discarded receipt actions. The targeted fix should preserve each timestamp belonging to intervening activity and inherit the original baseline only for timestamps attributable to superseded receipt actions, with a regression covering comment success followed by upload failure.
The snapshot update does not change this behavior, so this finding remains open. ikevin127, should I implement this timestamp change as well?
There was a problem hiding this comment.
Rechecked: this P2 is valid and remains open. Report/index.ts:1034–1040 advances both timestamps for a comment, but Receipt.ts:298–299 inherits the oldest report rollback. A successful intervening comment followed by upload failure can therefore rewind activity/read timestamps.
The snapshot fix does not address this. A timestamp fix needs to preserve intervening comment activity without retaining timestamps belonging only to discarded receipt actions, with a regression covering comment success followed by upload failure. The current request asks for a reply to this finding; no timestamp change was made.
There was a problem hiding this comment.
Implemented in 863b6138. Receipt.ts:280–307 now handles each timestamp independently: it unwinds a superseded receipt action's timestamp through that request's rollback, but preserves intervening activity. It uses the persisted receipt-added action timestamp, since queued requests do not retain optimistic updates.
Added the queued comment-success/upload-failure regression and independent-field cases. All three new cases failed before the fix; 195 focused tests pass afterward. Full lint, changed-file lint/spelling, typecheck, and Storybook smoke pass. Browser verification remains blocked by unavailable usable UI/failure injection; details are in AI Tests.
Reviewer Checklist
Screenshots/VideosMacOS: Chrome / Safariissue107135-fix-verified.mp4 |
|
Looks good from a product perspective. |
ikevin127
left a comment
There was a problem hiding this comment.
@MelvinBot Request changes, non-blockers that should still be addressed. When a superseded upload's search snapshot isn't in the latest request's failureData, the rollback skips the original-receipt patch. Also, please reply to Codex's open P2 about the thread timestamps.
| for (const [key, originalUpdate] of originalUpdates) { | ||
| if (!ownKeys.has(key)) { | ||
| inheritedFailureData.push(originalUpdate); |
There was a problem hiding this comment.
🟡 Keys that only the superseded requests touched get pushed here without the snapshot receipt patch from the .map() above, so one of them can still roll back to a discarded file.
Repro: replace A in search S1, switch to S2 and replace B, then leave search and replace C. S2's oldest rollback comes from B, so its receipt is oldReceipt (file A). C has no S2 update, so this loop pushes it unchanged, and when C fails S2 shows A.
Can we pull the patch into a helper and run it on both paths?
function withOriginalSnapshotReceipt(update: AnyOnyxUpdate, originalTransactionValue: unknown, transactionKey: string): AnyOnyxUpdate {
const snapshotValue: unknown = update.value;
if (
!update.key.startsWith(ONYXKEYS.COLLECTION.SNAPSHOT) ||
!isRecord(originalTransactionValue) ||
!('receipt' in originalTransactionValue) ||
!isRecord(snapshotValue) ||
!isRecord(snapshotValue.data) ||
!isRecord(snapshotValue.data[transactionKey])
) {
return update;
}
return {
...update,
value: {...snapshotValue, data: {...snapshotValue.data, [transactionKey]: {...snapshotValue.data[transactionKey], receipt: originalTransactionValue.receipt}}},
};
}inheritedFailureData.push(withOriginalSnapshotReceipt(originalUpdate, originalTransactionValue, transactionKey));The search it.each test only makes two uploads. A third upload made outside the second search would cover this.
👁️ Written by AI, reviewed by Kevin.
There was a problem hiding this comment.
Applied the requested shared helper to both inheritance paths and extended the search-switch test to include C outside search.
One clarification: the extended scenario passed before this refactor too, because B's patched snapshot rollback is persisted and inherited by C. This change makes both paths explicitly normalize the receipt rather than relying on that transitive behavior. All 192 tests in the three focused suites pass, along with typecheck and full lint.
There was a problem hiding this comment.
Verified this is already addressed in current HEAD: Receipt.ts:290–314 applies the original-receipt helper both to mapped snapshot updates and to inherited snapshots absent from the latest request's failureData.
The three-upload regression covers A in S1, B in S2, C outside search, then failure restoring the original receipt in both snapshots. Reran the receipt, request-conflict, and sequential-queue suites: 192 tests passed. No additional code changes were necessary.
| 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>]>([ |
There was a problem hiding this comment.
🟢 NAB: ConflictActionData is already exported from @src/types/onyx/Request, so we can use it here instead of deriving the type.
it.each<[string, AnyRequest[], ConflictActionData]>([👁️ Written by AI, reviewed by Kevin.
There was a problem hiding this comment.
Done: the table now uses the exported ConflictActionData type directly. Typecheck and the focused suite pass.
| const getThread = () => getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${threadReportID}`); | ||
| const getActions = () => getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${threadReportID}`); | ||
| const getQueuedReplacement = () => getAllPersistedRequests().find((request) => request.command === WRITE_COMMANDS.REPLACE_RECEIPT); | ||
| const getAuditActionIDs = (request: ReturnType<typeof getQueuedReplacement>) => |
There was a problem hiding this comment.
🟢 NAB: this is AnyRequest | undefined, which reads clearer than deriving it from the helper's return type.
const getAuditActionIDs = (request: AnyRequest | undefined) =>👁️ Written by AI, reviewed by Kevin.
There was a problem hiding this comment.
Done: the helper parameter now uses AnyRequest | undefined directly. Typecheck and the focused suite pass.
| const transaction = {...createRandomTransaction(Number(transactionID)), receipt: originalReceipt}; | ||
| await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, transaction); | ||
| await Onyx.set(`${ONYXKEYS.COLLECTION.SNAPSHOT}${snapshotHash}`, { | ||
| // @ts-expect-error: Only the transaction data is needed in this snapshot fixture |
There was a problem hiding this comment.
🟢 NAB: can we drop the @ts-expect-error here and on line 1216? The tests only read receipt from the snapshot, so a typed fixture with just that field is enough, and the suppression won't hide a real type error later.
await Onyx.set(`${ONYXKEYS.COLLECTION.SNAPSHOT}${snapshotHash}`, {
data: {[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]: {receipt: originalReceipt}},
});If that still doesn't type check, createMock<SearchResults> is what the Search tests use for partial snapshots.
👁️ Written by AI, reviewed by Kevin.
There was a problem hiding this comment.
Done: removed both suppressions and used createMock<SearchResults> receipt-only fixtures with a literal transaction key. The second fixture retains the intermediate receipt needed by the test. Typecheck and the focused suite pass.
Co-authored-by: Kevin Brian Bader <ikevin127@users.noreply.github.com>
|
@ikevin127 Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button] |
|
🤖 Web test steps verification results: Web rollback verification was blocked by unavailable app access and failure injection. The browser flow was not executed.
Pushed the update: shared snapshot normalization on both paths, three-upload test coverage, and typing cleanups. 192 focused tests, full lint, typecheck, and Storybook smoke passed. Remaining check limitations are documented in AI Tests. Replied to every review thread. Codex’s timestamp concern is valid and remains open; timestamp behavior was not changed. view run · no recording available |
|
No code fix identified:
No changes pushed. |
|
|
No new code changes were needed for the snapshot feedback. |
ikevin127
left a comment
There was a problem hiding this comment.
@MelvinBot Request changes, non-blockers that should still be addressed. Yes, please implement the timestamp fix from Codex's P2: keep the thread timestamps that intervening activity advanced, inherit the original baseline only for the ones the superseded receipt actions set, and add a test where a comment succeeds and the upload then fails. The two test comments are NAB.
| jest.mocked(SearchQueryUtils.getCurrentSearchQueryJSON).mockReturnValue(undefined); | ||
| await replaceWithLatestState('third.jpg'); | ||
|
|
||
| // Then a failed upload restores even snapshots absent from its own failure data |
There was a problem hiding this comment.
🟢 NAB: this comment sits on the failure step, so it should be a When. The assertions start at the Then on line 1227.
// And when the surviving upload fails
mockFetch.fail();
await reconnect();
// Then no touched snapshot rolls back to the first file, including snapshots absent from the latest failure data👁️ Written by AI, reviewed by Kevin.
There was a problem hiding this comment.
Done in 863b6138: the failure step is now “And when,” with the assertions under “Then”. Focused tests pass.
| expect((await getTransaction())?.receipt?.source).toBe(originalReceipt.source); | ||
| for (const hash of opensAnotherSearch ? [snapshotHash, secondSnapshotHash] : [snapshotHash]) { | ||
| const snapshot = await getOnyxValue(`${ONYXKEYS.COLLECTION.SNAPSHOT}${hash}`); | ||
| expect(snapshot?.data?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]?.receipt?.source).toBe(originalReceipt.source); |
There was a problem hiding this comment.
🟢 NAB: now that transactionKey exists, can we use it here and on lines 1069 and 1185 instead of building the key again?
expect(snapshot?.data?.[transactionKey]?.receipt?.source).toBe(originalReceipt.source);👁️ Written by AI, reviewed by Kevin.
There was a problem hiding this comment.
Done in 863b6138: reused transactionKey in the helper, the existing rollback assertion, and the search-switch assertion. Typecheck and focused tests pass.
Co-authored-by: Kevin Brian Bader <ikevin127@users.noreply.github.com>
|
🤖 Web test steps verification results: ❌ fail Web verification was blocked: browser snapshots returned no usable UI, and controlled upload failure was unavailable. This is not a demonstrated PR regression.
Pushed the timestamp fix and both NAB cleanups, and replied to all three threads. 195 focused tests passed, including comment-success/upload-failure and independent timestamp coverage. Lint, spelling, typecheck, formatting, and Storybook smoke passed; full Jest timed out after 38 passing suites. view run · no recording available |
|
The Bun check failed because an unrelated lint-tooling test exceeded its 5-second timeout. It validates lint configuration—not the changed receipt/queue code. 846 tests passed; one timed out. No changes pushed: this failure doesn’t justify modifying the PR. Rerunning Bun tests is the appropriate next step. Independent approval also remains outstanding; several Jest and performance checks are still running. |
|
Already implemented in 863b6138, including:
Independently reran five targeted regression cases—all passed. All three review threads already have replies; no additional changes were needed. |
|
The remaining code-check failure is the same Bun lint-tooling timeout: 6.16 seconds against a 5-second limit, unrelated to the receipt changes. I attempted to rerun it, but permission was denied. Please rerun that check in GitHub. All Jest checks now pass; performance testing remains in progress. No code changes pushed. |
ikevin127
left a comment
There was a problem hiding this comment.
🟢 LGTM - Tests well, no remaining issues
|
🚧 francoisl has triggered a test Expensify/App build. You can view the workflow run here. |
|
🧪🧪 Use the links below to test this adhoc build on Android, iOS, and Web. Happy testing! 🧪🧪
|
|
✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release. |
|
🚀 Deployed to staging by https://github.com/francoisl in version: 9.5.52-1 🚀
|
|
No help site update needed — this PR fixes expected behavior when replacing receipts offline without adding a new workflow or making existing article instructions incorrect. |



Explanation of Change
Collapse unsent receipt replacements for the same transaction to the latest upload, appended after existing dependencies. Stop at same-transaction detaches and previously attempted uploads so receipt history remains intact. Start deletion and insertion before awaiting persistence so an immediately queued detach cannot overtake the surviving upload.
Carry forward the original receipt, violations, snapshots, and thread timestamps on failure while keeping the latest upload's error/retry data. Remove superseded optimistic audit actions, preserve replacement auditing for crops of unsent replacements, avoid removal actions when there was no original receipt, and log intentionally superseded uploads. Detach behavior and non-leader-tab deduplication are unchanged.
Reviewed Add an audit trail for receipt additions: its removed resolver crossed detach boundaries and lost earlier receipt-added messages. A new integration test protects two offline add/delete cycles, including redundant replacements within each segment. Existing receipt audit, retry, and thread-resolution tests pass. Also cover actual in-flight uploads and rollback after switching or leaving searches.
AI Tests
Timestamp review update (2026-11-20, commit
863b61386aac97f71a19f7066b225aaf27883490):transactionKeyin the requested helper/assertions.npm run lint,npm run lint-changed,npm run spell-changed(all seven branch files),npm run typecheck, Storybook smoke test, and pre-commit Oxfmt on both changed files. Independent staged whole-branch review returned no violations. Initial shallow-history failures in changed-file checks were resolved by fetching branch history and rerunning successfully.prettierscript is absent; the repository's Oxfmt pre-commit hook passed instead.Follow-up review update (2026-11-20):
npm run lint, explicit changed-file lint,npm run typecheck, Storybook smoke test, and the pre-commit Oxfmt hook on all three modified files. Independent staged-code review reported no violations.lint-changedandspell-changedstalled fetchingorigin/main; the broader spelling command timed out. The matrix'sprettierscript does not exist; Oxfmt ran successfully instead.Original implementation validation:
npm run lint-changed,npm run typecheck,npm run spell-changed, andnpm run storybook -- --smoke-test --ci. A fullnpm run lintcompleted earlier; a repeat on the final commit hit its 2-minute timeout. Changed-file lint passed again on the final commit.npm run prettier -- --log-level errormatrix command is unavailable because this checkout has noprettierscript.--findRelatedTestsrun likewise timed out after 963 passing suites. Neither is claimed as a completed full-suite pass.connection_lost/session_suspended, so neither the three-replacements/delete flow nor the historical two-add/delete-cycle flow was exercised in the browser. This is not a product-failure verdict. Evidence upload was unavailable: the documented upload shell script is absent and the alternate uploader was denied by tool permissions.Fixed Issues
$ #107135
PROPOSAL: #107135 (comment)
Tests
Manual verification steps (based on the linked issue's expected result; not newly executed as part of this description update):
ReplaceReceiptAPI call is sent for this transaction, containing the latest replacement file, followed by exactly oneDetachReceiptcall, and that both succeed.ReplaceReceiptfollowed by oneDetachReceipt, preserves both cycles' receipt-added and receipt-removed audit history, and leaves no pending or failed audit actions.Offline tests
ReplaceReceiptrequest to return an API error using a development API mock. Verify that the original receipt is restored in the expense and search results, the error/retry state refers to the latest file rather than an intermediate replacement, and superseded audit actions do not return.QA Steps
Same as Tests.
Checklist boxes below were checked on
ikevin127's explicit request; this metadata update does not represent newly completed cross-platform testing. Existing verification limitations remain documented in AI Tests.PR Author Checklist
### Fixed Issuessection aboveTestssectionOffline stepssectionQA stepssectionAvatar, I verified the components usingAvatarare working as expected)npm run compress-svg)Avataris modified, I verified thatAvataris working as expected in all cases)Designlabel and/or tagged@Expensify/designso the design team can review the changes.mainbranch was merged into this PR after a review, I tested again and verified the outcome was still expected according to theTeststeps.Screenshots/Videos
Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari