Skip to content

Snapshot picked files into memory-backed Files to prevent request queue poisoning - #96940

Merged
mountiny merged 7 commits into
Expensify:mainfrom
callstack-internal:eliran/2397-snapshot-picked-files
Jul 28, 2026
Merged

Snapshot picked files into memory-backed Files to prevent request queue poisoning#96940
mountiny merged 7 commits into
Expensify:mainfrom
callstack-internal:eliran/2397-snapshot-picked-files

Conversation

@elirangoshen

@elirangoshen elirangoshen commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Explanation of Change

On web, a File picked from disk (file picker, drag-and-drop) is only a lazy reference to its OS file. If the user modifies, deletes, renames, or moves that file after picking it but before the queued request is first persisted (for example while the attachment preview or the expense confirmation screen is open — whether by user action, a download still completing, or background software touching the file), the first IndexedDB write of the persisted request queue fails with:

DataError: Failed to write blobs (InvalidBlob)   (Windows)
DataError: Failed to write blobs (IOError)       (macOS)

The dead File then poisons networkRequestQueue: the storage write is retried 5×, and every subsequent queue rewrite re-serializes the same dead blob and fails again. Production logs show ~46k of these events over 3 days across AddAttachment, ReplaceReceipt, and RequestMoney (SmartScan) — all failing on the very first persist (retryAttempt: 0/5), which pins the failure to the pick → first-write window.

This PR snapshots the picked file's bytes into a memory-backed File in validateAttachmentFile (the single choke point all attachment/receipt flows go through via useFilesValidation). A memory-backed File cannot be invalidated by later disk changes, so the queued request always serializes. If the backing file is already unreadable at validation time, the user gets an immediate "file invalid" error instead of a silent failure later.

The snapshot lives in a platform-split module (src/libs/snapshotPickedFile/index.ts + index.native.ts): the web variant copies the bytes, the native variant keeps the existing rename-only behavior — native file objects never enter the IndexedDB blob path, and production logs show this error class exclusively from web user agents.

Related follow-up (independent, no dependency): Expensify/react-native-onyx#814 classifies this error as never-retriable at the storage layer, so any remaining inline File/Blob path fails once instead of retrying 5x. It ships separately via #96957.

Fixed Issues

$ #97050
PROPOSAL:

Tests

  1. Run the web app in Chrome, sign in, and open DevTools console (enable the Verbose level).
  2. Create a small image file on disk.
  3. In a report, click the compose +Add attachment and pick the file. Keep the preview modal open.
  4. While the preview is open, delete (or overwrite) the file on disk.
  5. Click Send.
  6. Verify the attachment uploads successfully and the console shows no Failed to write blobs / [Onyx] Failed to save to storage errors.
  7. Repeat steps 2–6 using the receipt scan flow (FAB → Create expenseScan → choose the file, delete it on disk while on the confirmation screen, then submit). Verify the expense is created and no storage errors appear.
  8. Run npx jest tests/unit/ValidateAttachmentFileTest.ts and verify all tests pass.
  • Verify that no errors appear in the JS console

Offline tests

  1. Enable Force offline (Settings → Troubleshoot).
  2. Create a scan expense with a file picked from disk, then delete the file on disk.
  3. Create a second (manual) expense so the persisted request queue is rewritten.
  4. Verify no Failed to write blobs errors appear in the console.
  5. Go back online and verify both expenses sync successfully.

QA Steps

Same as Tests (steps 1–7).

  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari

before

before.mov

after

after.mov

…ning

A File picked from disk only references its OS file. If that file is
modified or deleted before the queued request is persisted (e.g. while
the preview modal is open), the IndexedDB write fails with
"DataError: Failed to write blobs" (InvalidBlob/IOError) and the dead
File poisons the persisted request queue, failing every later rewrite.

Copy the bytes into a memory-backed File at validation time, so the
queued request can never reference a stale OS file. If the file is
already unreadable at validation, surface FILE_INVALID to the user
instead of failing silently later.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
elirangoshen and others added 2 commits July 24, 2026 10:15
eslint-seatbelt caps no-unsafe-type-assertion at the grandfathered count
for this file; use Object.defineProperty instead of casting.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Replace the arrayBuffer feature-detect with snapshotPickedFile/index.ts
(web: copy bytes into a memory-backed File) and index.native.ts (keep
the original rename-only behavior; native has no IndexedDB blob path).
Snapshot tests move to their own file that pins the web implementation,
since Jest resolves the .native variant by default.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown
Contributor

⚠️ This PR is possibly changing native code and/or updating libraries, it may cause problems with HybridApp. Please check if any patch updates are required in the HybridApp repo and run an AdHoc build to verify that HybridApp will not break. Ask Contributor Plus for help if you are not sure how to handle this. ⚠️

@elirangoshen
elirangoshen force-pushed the eliran/2397-snapshot-picked-files branch from 5974a7f to 04ed14c Compare July 24, 2026 12:12
@elirangoshen

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 04ed14ced5

ℹ️ 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".

Comment thread src/libs/snapshotPickedFile/index.ts
Mobile browsers hand over sandboxed temp copies the OS won't modify after
picking, so the queue-poisoning scenario doesn't apply there — and copying
every file's bytes would multiply peak memory by batch size on
memory-constrained mobile Safari. Keep the lazy File on mobile and only
clean the name.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@codecov

codecov Bot commented Jul 27, 2026

Copy link
Copy Markdown

Codecov Report

✅ Changes either increased or maintained existing code coverage, great job!

Files with missing lines Coverage Δ
src/libs/snapshotPickedFile/index.native.ts 100.00% <100.00%> (ø)
src/libs/validateAttachmentFile.ts 97.56% <100.00%> (+0.06%) ⬆️
src/libs/snapshotPickedFile/index.ts 87.50% <87.50%> (ø)
... and 139 files with indirect coverage changes

@elirangoshen
elirangoshen marked this pull request as ready for review July 27, 2026 09:52
@elirangoshen
elirangoshen requested review from a team as code owners July 27, 2026 09:52
@melvin-bot
melvin-bot Bot requested review from JmillsExpensify and nyomanjyotisa and removed request for a team and JmillsExpensify July 27, 2026 09:52
@melvin-bot

melvin-bot Bot commented Jul 27, 2026

Copy link
Copy Markdown

@nyomanjyotisa 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]

@melvin-bot
melvin-bot Bot removed the request for review from a team July 27, 2026 09:52

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: af128f9f72

ℹ️ 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".

Comment thread src/libs/snapshotPickedFile/index.ts Outdated
elirangoshen and others added 2 commits July 27, 2026 12:05
iPadOS Safari defaults to "Request Desktop Website", reporting a Macintosh
user agent that isMobile() can't recognize, so a memory-constrained iPad
would copy every picked file's bytes. Detect it via Macintosh UA plus touch
points (real Macs report zero) and keep the lazy File there too.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR prevents web request-queue persistence failures (“Failed to write blobs”) caused by OS-backed File objects becoming unreadable after a user picks them but before the first IndexedDB write, by snapshotting picked files into memory-backed Files during attachment validation.

Changes:

  • Snapshot desktop-web picked files into a memory-backed File during validateAttachmentFile() so later disk changes can’t poison networkRequestQueue.
  • Add a platform-split snapshotPickedFile helper (web copies bytes; native preserves existing rename-only behavior).
  • Add unit tests covering snapshot success, unreadable-file failure, and mobile/iPadOS desktop-mode exceptions.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

File Description
src/libs/validateAttachmentFile.ts Uses snapshotPickedFile() during validation to ensure queued requests serialize reliably on web.
src/libs/snapshotPickedFile/index.ts Web implementation: copies bytes into memory-backed File, with mobile/iPadOS desktop-mode opt-outs.
src/libs/snapshotPickedFile/index.native.ts Native implementation: rename-only behavior (no byte snapshotting).
tests/unit/ValidateAttachmentFileSnapshotTest.ts Adds tests for the new snapshotting behavior and error handling.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/libs/validateAttachmentFile.ts Outdated
@@ -0,0 +1,28 @@
import {isMobile} from '@libs/Browser';

@nyomanjyotisa nyomanjyotisa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with this review comment. updatedFile is guaranteed to be a fresh File only on desktop web, while the mobile and iPad paths preserve the existing behavior. The implementation looks correct. Could you please update the comment accordingly?

@nyomanjyotisa

nyomanjyotisa commented Jul 28, 2026

Copy link
Copy Markdown
Member

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified that the composer does not automatically focus or open the keyboard on mobile unless explicitly intended. This includes checking that returning the app from the background does not unexpectedly open the keyboard.
  • I verified tests pass on all platforms & I tested again on:
    • Android: HybridApp
    • Android: mWeb Chrome
    • iOS: HybridApp
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • For any bug fix or new feature in this PR, I verified that sufficient unit tests are included to prevent regressions in this flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: HybridApp
Android-pr96940.mp4
Android: mWeb Chrome
Android-mWeb-pr96940.mp4
iOS: HybridApp
ios-pr96940.mp4
iOS: mWeb Safari
ios-mWeb-pr96940.mp4
MacOS: Chrome / Safari
Chrome-pr96940.mp4

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
@elirangoshen

Copy link
Copy Markdown
Contributor Author

I agree with this review comment. updatedFile is guaranteed to be a fresh File only on desktop web, while the mobile and iPad paths preserve the existing behavior. The implementation looks correct. Could you please update the comment accordingly?

Sure, done

@nyomanjyotisa nyomanjyotisa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@melvin-bot
melvin-bot Bot requested a review from mountiny July 28, 2026 12:57
@mountiny
mountiny merged commit c0fb3e1 into Expensify:main Jul 28, 2026
34 checks passed
@OSBotify

Copy link
Copy Markdown
Contributor

✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release.

@github-actions

Copy link
Copy Markdown
Contributor

🚧 mountiny has triggered a test Expensify/App build. You can view the workflow run here.

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/mountiny in version: 9.4.46-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

@MelvinBot

Copy link
Copy Markdown
Contributor

🤖 No help site changes required — I did not create a draft PR.

I reviewed the changes in this PR against the help articles under App/docs/articles (including the attachment/receipt/SmartScan guides such as Attach-and-edit-receipts-on-expenses.md, Create-an-Expense.md, and Troubleshoot-SmartScan-Issues.md) and applied the naming, authoring, and template guidelines.

Why no docs update is needed:

This is an internal engineering bug fix, not a product/behavior change that the help site documents:

  • It snapshots a web-picked File's bytes into a memory-backed File in validateAttachmentFile so a later disk change can't poison the persisted request queue (the Failed to write blobs / IndexedDB failure).
  • The user-facing workflow is unchanged — adding attachments and scanning receipts follow the exact same steps already documented.
  • There are no new features, tabs, settings, labels, or buttons.
  • The only observable difference is an edge case (a file deleted/modified on disk between picking and sending) now surfaces an immediate "file invalid" error instead of failing silently — internal error-handling behavior that isn't described in any existing help article.

Since nothing in the documented user experience changed, there's no accurate help-site content to add or revise here.

@elirangoshen — since no help-site changes are required, I didn't open a docs PR. If you believe a specific article should still be updated, let me know which one and what behavior you'd like documented, and I'll draft it.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants