Skip to content

Fix dead-code async-catch in tryOrDegradePerformance App#784

Open
elirangoshen wants to merge 2 commits into
Expensify:mainfrom
callstack-internal:elirangoshen/fix/90632-tryOrDegradePerformance-async-catch
Open

Fix dead-code async-catch in tryOrDegradePerformance App#784
elirangoshen wants to merge 2 commits into
Expensify:mainfrom
callstack-internal:elirangoshen/fix/90632-tryOrDegradePerformance-async-catch

Conversation

@elirangoshen
Copy link
Copy Markdown

@elirangoshen elirangoshen commented May 14, 2026

Details

tryOrDegradePerformance in lib/storage/index.ts was supposed to detect known critical IndexedDB failures and gracefully fall back to an in-memory storage provider via degradePerformance. It wrapped every storage call in a synchronous try/catch — but every storage provider method is async and the helper did resolve(fn()) (no await). Any rejection from fn() propagated through the promise chain and never re-entered the catch. Result: the fallback branch has been dead code, and the Logger.logHmmm("Falling back to only using cache and dropping storage…") message has never fired in production.

This PR fixes it by replacing the synchronous wrapper with a .then(() => fn()).catch(...) chain so the helper handles both sync throws and async rejections from fn uniformly:

function tryOrDegradePerformance<T>(
  fn: () => Promise<T> | T,
  waitForInitialization = true,
): Promise<T> {
  const initialization = waitForInitialization
    ? initPromise
    : Promise.resolve();
  return initialization
    .then(() => fn())
    .catch((error: unknown) => {
      // catch the error if DB connection can not be established/DB can not be created
      if (
        error instanceof Error &&
        error.message.includes("IDBKeyVal store could not be created")
      ) {
        degradePerformance(error);
      }
      return Promise.reject(error);
    });
}

Notes on the chosen shape:

  • initialization.then(() => fn()) runs fn inside a .then callback. If fn throws synchronously, the .then returns a rejected promise; if it returns a value/promise, .then follows the chain. Either way, the trailing .catch sees the error. This matches the original helper's intent — be a uniform safety net regardless of whether fn happens to throw sync or reject async — addressing the Codex review concern and the follow-up from @fabioh8010.

While here, the 'Internal error opening backing store for indexedDB.open' branch has been removed from this function. Per the parent investigation in Expensify/App#87862 (comment), that error class indicates permanent IndexedDB corruption that a provider swap to MemoryOnlyProvider cannot recover from — it will be routed to a dedicated heal path in Expensify/App#90636. Leaving the check here would conflict with that heal mechanism. The 'IDBKeyVal store could not be created' branch stays — that's an init-time failure where falling back to memory is still the correct behavior.

Related Issues

Expensify/App#90632

Automated Tests

Added tests/unit/storage/tryOrDegradePerformanceTest.ts with four cases that exercise the storage module via its public API (since tryOrDegradePerformance itself isn't exported):

  1. Async rejection with the target error triggers degrade — replaces the live provider's method with one that returns Promise.reject(new Error('IDBKeyVal store could not be created')), calls a storage op, and asserts: (a) the promise rejects with that error, (b) Logger.logHmmm was called with the "Falling back to only using cache…" message — proving degradePerformance ran, (c) storage.getStorageProvider().name === 'MemoryOnlyProvider'.
  2. Async rejection with an unrelated message does not trigger degrade — same setup with new Error('Some unrelated storage failure'). Asserts the rejection propagates, Logger.logHmmm is not called, and the active provider stays the same.
  3. Sync throw with the target error triggers degrade — provider method is mocked to throw (not reject) the target error. Asserts the same three outcomes as case (1), proving the new .then(() => fn()).catch(...) form catches synchronous throws as well.
  4. Sync throw with an unrelated message does not trigger degrade — symmetric to case (2) but for sync throws.

All four use jest.isolateModules to load a fresh lib/storage per case so the module-private provider variable doesn't leak between tests, and jest.unmock('../../../lib/storage') to bypass the global mock applied by jestSetup.js.

Without the fix in this PR, cases (1) and (2) fail — the async rejection escapes the old synchronous catch block and degradePerformance is never called.

Full test suite (npm test) passes: 17 suites / 453 tests. Typecheck (npm run typecheck) and lint on the changed files are clean.

Manual Tests

Tested end-to-end against Expensify/App in this draft PR: Expensify/App#90768 (bumps react-native-onyx to this branch's head commit via the git+https://…#<sha> hash trick in package.json).

The fix targets the IndexedDB code path. IndexedDB is web-only — mobile uses SQLiteProvider and never reaches the changed branch — so the meaningful manual tests are all on web; mobile is purely a non-regression check.

  1. Check out Expensify/App#90768, npm install, npm run web. Confirm the App boots and behaves identically to main on the happy path: log in, view reports, open a chat, send a message, refresh.
  2. Confirm Logger.logHmmm("Falling back to only using cache and dropping storage") is not logged during normal use.
  3. To exercise the fixed degrade path, induce an IDB failure: in DevTools → Sources, set a breakpoint inside IDBKeyValProvider.setItem (or any other provider method) in node_modules/react-native-onyx/dist/storage/providers/IDBKeyValProvider.js. When the breakpoint hits, throw/reject new Error('IDBKeyVal store could not be created') from the debugger console.
  4. Continue and observe. Expected with this fix:
    • The App keeps working for the rest of the session (in-memory storage only, persistence dropped — same UX as today).
    • Console shows: [Onyx] Error while using IDBKeyValProvider. Falling back to only using cache and dropping storage. plus the error stack.
  5. Without this fix (E/App main), step 4's log message never appears even though the same underlying IDB error fires — confirming the dead-code bug.
  6. Offline regression check on web: boot online → log in → DevTools → Network → Offline → navigate reports/chats → send a message (should queue optimistically) → reload while offline (state should persist from IDB) → re-enable network (queued message should flush). Identical to main.
  7. Spot-check useOnyx-heavy screens (Reports list, Money Request flows) on web, iOS, and Android — no observable behavior change vs. main.

Author Checklist

  • I linked the correct issue in the ### Related 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 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 / Chrome
    • iOS / native
    • iOS / 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 the left part of a conditional rendering a React component is a boolean and NOT a string, e.g. myBool && <MyComponent />.
    • 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 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.js 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 a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • 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
    • If we are not using the full Onyx data that we loaded, I've added the proper selector in order to ensure the component only re-renders when the data it is using changes
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • 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 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 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 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 author checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari
Screen.Recording.2026-05-15.at.13.56.18.mov
Screen.Recording.2026-05-15.at.13.58.09.mov

@elirangoshen elirangoshen requested a review from a team as a code owner May 14, 2026 14:39
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 14, 2026

All contributors have signed the CLA ✍️ ✅
Posted by the CLA Assistant Lite bot.

@melvin-bot melvin-bot Bot requested review from cristipaval and removed request for a team May 14, 2026 14:39
@elirangoshen elirangoshen changed the title fix Fix dead-code async-catch in tryOrDegradePerformance App May 14, 2026
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: dd82e39dc9

ℹ️ 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 lib/storage/index.ts Outdated
@elirangoshen
Copy link
Copy Markdown
Author


I have read the CLA Document and I hereby sign the CLA


@fabioh8010
Copy link
Copy Markdown
Contributor

@elirangoshen I will review soon, but meanwhile:

  1. Please provide a E/App PR in the PR description where we could test this change, you can link to your onyx PR by using this hash trick in package.json (replace <last_pr_commit_sha> with the SHA): "react-native-onyx": "git+https://github.com/Expensify/react-native-onyx.git#<last_pr_commit_sha>",
  2. Please attach recordings in all platform sections as evidence

@Julesssss Julesssss self-requested a review May 14, 2026 23:18
@Julesssss
Copy link
Copy Markdown
Contributor

@elirangoshen could you try with just I have read the CLA Document and I hereby sign the CLA

@elirangoshen
Copy link
Copy Markdown
Author

I have read the CLA Document and I hereby sign the CLA

@elirangoshen
Copy link
Copy Markdown
Author

@elirangoshen I will review soon, but meanwhile:

  1. Please provide a E/App PR in the PR description where we could test this change, you can link to your onyx PR by using this hash trick in package.json (replace <last_pr_commit_sha> with the SHA): "react-native-onyx": "git+https://github.com/Expensify/react-native-onyx.git#<last_pr_commit_sha>",
  2. Please attach recordings in all platform sections as evidence

Sure I added

@elirangoshen
Copy link
Copy Markdown
Author

@elirangoshen could you try with just I have read the CLA Document and I hereby sign the CLA

did but still have error there

Copy link
Copy Markdown
Contributor

@fabioh8010 fabioh8010 left a comment

Choose a reason for hiding this comment

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

Per Expensify#784 (comment),
switch from `Promise.resolve(fn()).catch(...)` to `.then(() => fn()).catch(...)`
so synchronous throws from `fn` are also routed through the degrade-detection
catch handler. Add two test cases covering the sync-throw paths.
exfy-clabot Bot added a commit to Expensify/CLA that referenced this pull request May 18, 2026
elirangoshen added a commit to callstack-internal/Expensify-App that referenced this pull request May 18, 2026
@elirangoshen
Copy link
Copy Markdown
Author

@elirangoshen Please check #784 (comment)

fixed, please check again

@elirangoshen elirangoshen requested a review from fabioh8010 May 18, 2026 11:16
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.

3 participants