Skip to content

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

Open
elirangoshen wants to merge 1 commit 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 1 commit into
Expensify:mainfrom
callstack-internal:elirangoshen/fix/90632-tryOrDegradePerformance-async-catch

Conversation

@elirangoshen
Copy link
Copy Markdown

@elirangoshen elirangoshen commented May 14, 2026

Details

The tryOrDegradePerformance helper in lib/storage/index.ts wraps storage operations in a try/catch intended to detect critical IndexedDB failures and fall back to the in-memory provider via degradePerformance().

The problem is that the try/catch only handles synchronous exceptions, while all storage provider operations are asynchronous.

The previous implementation effectively did:

resolve(fn())

This forwards the eventual result of fn() into the promise chain, but asynchronous rejections bypass the surrounding catch block entirely.

As a result:

  • Known IndexedDB failures never triggered degradePerformance()
  • The app never switched to the in-memory fallback provider
  • The following log message was effectively dead code in production:
Logger.logHmmm('Falling back to only using cache and dropping storage...')

This PR fixes the issue by converting the synchronous try/catch flow into proper promise rejection handling:

function tryOrDegradePerformance<T>(fn: () => Promise<T> | T, waitForInitialization = true): Promise<T> {
    const initialization = waitForInitialization ? initPromise : Promise.resolve();

    return initialization.then(() =>
        Promise.resolve(fn()).catch((error: unknown) => {
            if (error instanceof Error && error.message.includes('IDBKeyVal store could not be created')) {
                degradePerformance(error);
            }

            return Promise.reject(error);
        }),
    );
}

Promise.resolve(fn()) normalizes both synchronous and asynchronous return paths so .catch(...) consistently handles sync throws and async rejections.

While updating this logic, the 'Internal error opening backing store for indexedDB.open' branch was removed from this function.

Per the investigation in:
Expensify/App#87862 (comment)

that error indicates permanent IndexedDB corruption that cannot be recovered by switching to MemoryOnlyProvider. A dedicated heal flow will instead handle that case in:
Expensify/App#90636

The 'IDBKeyVal store could not be created' branch remains because falling back to in-memory storage is still the correct behavior for initialization failures.

Related Issues

Automated Tests

Added tests/unit/storage/tryOrDegradePerformanceTest.ts with two test cases that exercise the storage module through its public API (since tryOrDegradePerformance is not exported).

1. Async rejection with the target error message triggers degradation

Replaces the active provider method with one that returns:

Promise.reject(new Error('IDBKeyVal store could not be created'))

Then performs a storage operation and verifies that:

  • The promise rejects with the expected error
  • Logger.logHmmm is called with the "Falling back to only using cache..." message, confirming that degradePerformance() executed
  • storage.getStorageProvider().name === 'MemoryOnlyProvider'

2. Async rejection with an unrelated error does not trigger degradation

Uses the same setup, but with:

new Error('Some unrelated storage failure')

Verifies that:

  • The rejection propagates normally
  • Logger.logHmmm is not called
  • The active storage provider remains unchanged

Both tests use jest.isolateModules() to load a fresh instance of lib/storage for each test, preventing leakage of the module-private provider state between runs.

The tests also use:

jest.unmock('../../../lib/storage')

to bypass the global mock configured in jestSetup.js.

Without this fix, the first test fails because the async rejection bypasses the previous synchronous catch block and degradePerformance() is never called.

Validation

  • npm test passes (17 suites / 451 tests)
  • npm run typecheck passes
  • ✅ Lint passes for the new test file

Manual Tests

  1. In a local Expensify/App checkout, point react-native-onyx to this branch (for example via local path install or a prerelease version).

  2. Launch the app on web and verify normal storage functionality works without regressions:

    • Login
    • Viewing reports
    • Sending messages
    • Refreshing the app
  3. To trigger the fixed failure path:

    • Open DevTools → Application → IndexedDB
    • Delete the OnyxDB database while the app is running

    Alternatively, temporarily patch IDBKeyValProvider.setItem() (or another provider method) to return:

Promise.reject(new Error('IDBKeyVal store could not be created'))

Then reload the app.

Expected behavior

  • The app continues functioning using in-memory storage only
  • Persistence is disabled for the remainder of the session
  • The console logs:
Error while using IDBKeyValProvider. Falling back to only using cache and dropping storage.

Before this fix, the underlying async error occurred but the fallback logic was never triggered, so this log message did not appear.

  1. After release, verify production logs begin showing the "Falling back to only using cache and dropping storage" message for users hitting this failure mode (currently observed 0 times, confirming the previous fallback path was effectively dead code).

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

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


Thank you for your submission, we really appreciate it. Like many open-source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution. You can sign the CLA by just posting a Pull Request Comment same as the below format.


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


You can retrigger this bot by commenting recheck in this Pull Request. 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
@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 commented May 14, 2026

recheck

@elirangoshen
Copy link
Copy Markdown
Author

recheck

@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

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