Skip to content

Fix: Prevent Onyx.clear() from removing unsynced PERSISTED_REQUESTS data#87874

Open
marufsharifi wants to merge 8 commits intoExpensify:mainfrom
marufsharifi:fix/onyx-clear-preserve-persisted-requests
Open

Fix: Prevent Onyx.clear() from removing unsynced PERSISTED_REQUESTS data#87874
marufsharifi wants to merge 8 commits intoExpensify:mainfrom
marufsharifi:fix/onyx-clear-preserve-persisted-requests

Conversation

@marufsharifi
Copy link
Copy Markdown
Contributor

@marufsharifi marufsharifi commented Apr 14, 2026

Explanation of Change

These changes make offline expense creation more reliable during app recovery.

Before this, an expense created offline could disappear if the app reset local storage during recovery, or if the app closed while that expense request was already being processed. The result was that the server never received the write, and after reconnect the expense appeared to be missing.

With this update, recovery resets now reuse the safer reset flow that preserves pending work, and the request queue now treats in-flight requests as durable state instead of temporary memory-only state. That means offline-created expenses are much more likely to survive app resets, reloads, and reconnects until they successfully sync. Logout-style destructive flows were not expanded here; this is specifically about protecting recovery behavior.

Fixed Issues

$ #86710
PROPOSAL: #86710 (comment)

Tests

  1. Go to Workspace Chat
  2. Switch to Offline Mode
  3. Create a manual expense
  4. Open Developer ToolsConsole
  5. Run:
    await window.Onyx.set('resetRequired', true);
  6. Switch back to Online Mode
  7. Return to Workspace Chat
  8. Verify that the created expense is still visible in the workspace chat after going back online

Other Test Cases:

Case 1: Offline expense survives reset

  1. Open the app and sign in.
  2. Go to Settings > Troubleshoot.
  3. Turn on Force offline.
  4. Create an expense.
  5. Confirm the expense appears locally.
  6. Use Clear cache and restart / Reset and refresh.
  7. Wait for app reload.
  8. Turn Force offline off.
  9. Check that the expense is still there.
  10. Wait for sync.
  11. Verify that the expense is still present after sync.

Case 2: Multiple offline expenses survive reset

  1. Turn on Force offline.
  2. Create 2 or 3 expenses.
  3. Use Clear cache and restart.
  4. Turn offline off.
  5. Let sync finish.
  6. Verify that the expenses remain as normal

Case 3: Offline split-expense flow survives reset

  1. Turn on Force offline.
  2. Create a Split expense.
  3. Use Clear cache and restart.
  4. Turn offline off.
  5. Verify it syncs and the split expense remains.

Case 4: Track expense survives reset

  1. Turn on Force offline.
  2. Create a Track expense.
  3. Restart from Troubleshoot.
  4. Go back online.
  5. Verify that the tracked expense is still there

Case 5: Restart while request is in progress

This is important because your PR also touches ongoing request behavior.

  1. Keep the app online.
  2. In Troubleshoot, turn on Simulate poor internet connection.
  3. Create an expense.
  4. While it is still processing, quickly restart the app or kill and reopen it.
  5. Open the same report/expense again.
  6. Verify that the report/expense remains

Case 6: Normal online expense flow still works

  1. Keep the app fully online.
  2. Create an expense normally.
  3. Do not restart or force offline.
  4. Verify it syncs immediately.

Case 7: No bad side effect on non-expense navigation

  1. Open the app.
  2. Navigate between reports/settings.
  3. Restart using Troubleshoot.
  4. Return to the app and navigate again.
  5. Verify that the app opens normally.
  • Verify that no errors appear in the JS console

Offline tests

QA Steps

// TODO: These must be filled out, or the issue title must include "[No QA]."

  • 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 any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • 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 shown in the product is localized by adding it to src/languages/* files and using the translation method
      • If any non-english text was added/modified, I used JaimeGPT to get English > Spanish translation. I then posted it in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • 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)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • 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)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • 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.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • 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

Not applicable.

Android: mWeb Chrome

Not applicable.

iOS: Native

Not applicable.

iOS: mWeb Safari

Not applicable.

MacOS: Chrome / Safari
Screen.Recording.2026-04-14.at.4.31.25.PM.mp4
Screen.Recording.2026-04-20.at.1.09.35.PM.mp4
Screen.Recording.2026-04-20.at.1.11.04.PM.mp4
Screen.Recording.2026-04-20.at.1.22.09.PM.mov
Screen.Recording.2026-04-20.at.1.24.32.PM.mov
Screen.Recording.2026-04-20.at.1.27.14.PM.mov
Screen.Recording.2026-04-20.at.1.29.08.PM.mov
Screen.Recording.2026-04-20.at.1.30.31.PM.mov

@marufsharifi marufsharifi marked this pull request as ready for review April 14, 2026 12:44
@marufsharifi marufsharifi requested review from a team as code owners April 14, 2026 12:44
@melvin-bot melvin-bot Bot requested review from ShridharGoel and flaviadefaria and removed request for a team and flaviadefaria April 14, 2026 12:44
@melvin-bot
Copy link
Copy Markdown

melvin-bot Bot commented Apr 14, 2026

@ShridharGoel 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 April 14, 2026 12:44
Comment thread src/libs/actions/App.ts Outdated
}

Onyx.clear(KEYS_TO_PRESERVE).then(() => {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
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.

❌ CONSISTENCY-5 (docs)

The eslint-disable-next-line @typescript-eslint/no-use-before-define comment lacks an accompanying justification explaining why the rule needs to be suppressed. Even though the original code had a similar disable, the new usage should include a clear reason.

Add a justification comment, for example:

// eslint-disable-next-line @typescript-eslint/no-use-before-define -- clearOnyxAndResetApp is defined later in this file but must be called here in the RESET_REQUIRED callback
clearOnyxAndResetApp().finally(() => {

Reviewed at: 8fab326 | Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

Copy link
Copy Markdown

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

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: 8fab326610

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/libs/actions/PersistedRequests.ts Outdated
Comment on lines +279 to +282
Onyx.multiSet({
[ONYXKEYS.PERSISTED_REQUESTS]: persistedRequests,
[ONYXKEYS.PERSISTED_ONGOING_REQUESTS]: ongoingRequest,
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Serialize queue transition writes with concurrent saves

processNextRequest() now persists [PERSISTED_REQUESTS]: persistedRequests immediately after popping the head, but that write is async and not coordinated with save(). If a new request is queued while the current one is in flight, a later-resolving multiSet from this block can overwrite the newer save() result with a stale snapshot; the PERSISTED_REQUESTS Onyx callback then blindly assigns that stale disk value back to memory, dropping newly queued requests from retry processing.

Useful? React with 👍 / 👎.

});

if (persistedRequestsLength === 0 && !hasOnyxUpdates) {
if (persistedRequestsLength === 0 && !currentOngoingRequest && !hasOnyxUpdates) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Count ongoing request before treating flush as queue-empty

This new guard lets flush() run when there is only an ongoing request. In the offline recovery path, process() returns early, but flush completion still decides “queue empty” from getAllPersistedRequests().length only, so it can resolve readiness and flush queued Onyx updates while PERSISTED_ONGOING_REQUESTS is still pending. That reorders post-write update application relative to the recovered ongoing write.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in the queue completion path. flush() can still start when only currentOngoingRequest exists, but we now also check for an ongoing request before resolving readiness or flushing queued Onyx updates, so the queue is no longer treated as empty while PERSISTED_ONGOING_REQUESTS is still present.

@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 16, 2026

Codecov Report

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

Files with missing lines Coverage Δ
src/libs/Network/SequentialQueue.ts 86.29% <100.00%> (+1.16%) ⬆️
src/libs/actions/PersistedRequests.ts 81.63% <100.00%> (+3.37%) ⬆️
src/libs/actions/App.ts 54.02% <75.00%> (+6.89%) ⬆️
... and 13 files with indirect coverage changes

@ShridharGoel
Copy link
Copy Markdown
Contributor

@codex review

Copy link
Copy Markdown

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

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: 525ff2a3a4

ℹ️ 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/actions/PersistedRequests.ts Outdated
if (newRequest.persistWhenOngoing) {
Onyx.set(ONYXKEYS.PERSISTED_ONGOING_REQUESTS, newRequest as AnyRequest);
}
Onyx.set(ONYXKEYS.PERSISTED_ONGOING_REQUESTS, newRequest as AnyRequest);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Guard ongoing-request persistence against File/Blob payloads

Persisting every updated ongoing request unconditionally can reintroduce DataCloneError for requests whose data contains non-serializable File/Blob values (the same case already called out in processNextRequest()). HandleUnusedOptimisticID can call updateOngoingRequest() while rewriting report IDs, so if the ongoing command is attachment-related, this Onyx.set() can fail and leave the old ongoing request on disk, which means a post-crash retry may still use the stale report ID you were trying to replace.

Useful? React with 👍 / 👎.

@marufsharifi
Copy link
Copy Markdown
Contributor Author

@ShridharGoel, I've addressed AI feedback. all yours. thanks.

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.

2 participants