Skip to content

Fix performance of search router in p95 tail - #98282

Merged
mountiny merged 18 commits into
Expensify:mainfrom
software-mansion-labs:perf/search-router-p95-tail
Aug 21, 2026
Merged

mountiny merged 18 commits into
Expensify:mainfrom
software-mansion-labs:perf/search-router-p95-tail

Conversation

@sumo-slonik

@sumo-slonik sumo-slonik commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

Cuts the ManualOpenSearchRouter p95 tail (Sentry: "Opening Search bar"). Android is 12% of samples but 53% of everything above the global p95, with cold_start=false in 99.6% — the tail is the session's first open landing in post-launch JS-thread contention.

New SearchRouterWarmup/SearchRouterOptionsWarmer, mounted from AuthScreens, move that first-open work off the critical path. After OpenApp is applied, the first idle window (Scheduler.scheduleWhenIdle) evaluates the SearchRouterPage/RightModalNavigator module graphs and builds the empty-query option list into createFilteredOptionList's cache. That cache is keyed on the identity of its Onyx inputs, so the list is only built once they hold still across an idle window — otherwise post-launch writes would immediately invalidate it. The warmer unmounts when done, and skips entirely if the router is already open.

The config those options are built from now lives in searchRouterOptionsConfig.ts, so the warmer and SearchAutocompleteList can't drift apart on the values that cache is keyed on.

An earlier revision also skipped the autocomplete parser for blank queries. Dropped — parsing is 0.07ms per call, and the rest of the delta was a dev-only Hermes compile cost (see the discussion on useAutocompleteSuggestions.ts).

Local measurements (dev builds — absolute ms are not production values, only the relative change matters)

iOS

median main median branch delta
940ms 736ms -204ms (-22%)

Android

median main median branch delta
1323ms 1108ms -215ms (-16%)

Fixed Issues

$ #79353
PROPOSAL:

Tests

  • Verify that no errors appear in the JS console
  1. Open the app and tap Search — the router opens and shows recent searches and recent reports.
  2. Type a query — autocomplete suggestions appear and the results match the query. Clear the query — the recent searches/reports list comes back.
  3. Tap a recent report — it opens the right report.
  4. Go back to Home, leave the app untouched for half a minute, then tap Search again — it opens with the same list, nothing missing or duplicated.
  5. Tap Search immediately after the app finishes loading, before it has been idle — the router still opens correctly with the same list.
  6. Sign out and sign back in, then tap Search — the router opens with the new account's list.

Offline tests

Unnecessary

QA Steps

Same as tests.

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 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

@codecov

codecov Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Looks like you've decreased code coverage for some files. Please write tests to increase, or at least maintain, the existing level of code coverage. See our documentation here for how to interpret this table.

Files with missing lines Coverage Δ
src/components/Search/SearchAutocompleteList.tsx 92.22% <ø> (-0.08%) ⬇️
...s/Search/SearchRouter/searchRouterOptionsConfig.ts 100.00% <100.00%> (ø)
src/libs/Navigation/AppNavigator/AuthScreens.tsx 82.97% <100.00%> (-0.18%) ⬇️
...Navigation/AppNavigator/searchRouterLazyLoaders.ts 100.00% <100.00%> (ø)
.../Search/SearchRouter/SearchRouterOptionsWarmer.tsx 96.66% <96.66%> (ø)
...ponents/Search/SearchRouter/SearchRouterWarmup.tsx 92.30% <92.30%> (ø)
...onents/Search/SearchRouter/SearchRouterContext.tsx 79.48% <66.66%> (-2.34%) ⬇️
...rch/SearchRouter/SearchRouterPage/index.native.tsx 15.38% <0.00%> (-1.29%) ⬇️
... and 379 files with indirect coverage changes

Replace the 15s timer in SearchRouterWarmup with the state it was
approximating: wait for OpenApp to be applied, then for an idle window on
the JS thread via Scheduler.scheduleWhenIdle.

Build the option list only once its Onyx inputs hold still across a full
idle window. createFilteredOptionList keys its cache on the identity of
those inputs, so a list built while post-launch writes are still landing
is discarded before the user can open the router. A connectWithoutView
counter tracks that churn without rendering or rebuilding anything, and
a cap on the number of idle windows keeps a chatty account from
postponing the build forever. Module evaluation is unaffected by Onyx
writes, so it still happens in the first idle window.

Also:
- evict the attachment-parse cache LRU instead of clearing every entry
  at the cap
- share the useFilteredOptions config between SearchAutocompleteList and
  SearchRouterOptionsWarmer so the cache key cannot drift apart
- share the SearchRouterPage/RightModalNavigator require paths between
  AuthScreens and the warmup
- pick the empty-search predicate once per getValidOptions call instead
  of testing for it per report
Measured on the SearchRouter open path with the changes stacked one at a
time (Android emulator, high-traffic account, 3 cold opens per state):
adding this cache moved the median from 1840ms to 1936ms, i.e. no gain,
with the run ranges fully overlapping.

The reason is visible in the data: the cache lookup sits behind the
`data-expensify-source` fast path, and on the test account only 4 of 635
reports carry that attribute, so the parser barely runs on this path at
all. Keeping the cache would mean retaining message HTML strings for a
saving that does not exist here. If it is worth having, it belongs in a
change aimed at the report view, justified by measurements of that path.
Same stacked measurement as the previous commit: adding this step moved
the median from 1957ms (main) to 1985ms, with the run ranges fully
overlapping main's, so it buys nothing on the SearchRouter open path.

Building and deburring the search text for an empty query is genuinely
redundant, but at this size it does not show up next to the option-list
build that dominates the open, so it is not worth the review surface in
a perf PR.
@sumo-slonik sumo-slonik changed the title Perf/search router p95 tail Fix performance of search router in p95 tail Aug 12, 2026

@staszekscp staszekscp 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.

So far looking great!

Comment thread src/hooks/useAutocompleteSuggestions.ts Resolved
The blank-query short-circuit skipped the parser's first-use module evaluation,
which measured at ~76ms on an Android dev build. That cost is Hermes compiling the
generated parser at runtime, which a release build does not pay - its bundle is
precompiled to bytecode. The parsing itself is 0.07ms per call, so the guard is
not worth the extra branch.
@sumo-slonik
sumo-slonik marked this pull request as ready for review August 17, 2026 10:45
@sumo-slonik
sumo-slonik requested review from a team as code owners August 17, 2026 10:45
@melvin-bot
melvin-bot Bot requested review from aimane-chnaif and flaviadefaria and removed request for a team and flaviadefaria August 17, 2026 10:45
@melvin-bot

melvin-bot Bot commented Aug 17, 2026

Copy link
Copy Markdown

@aimane-chnaif 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 August 17, 2026 10:45

@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: 6864931e12

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

import {getIsSearchRouterOpenOrOpening} from './SearchRouterContext';

type OptionsWarmerProps = {
onDone: () => void;

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-13 (docs)

The newly added OptionsWarmerProps type declares the onDone prop with no /** ... */ block comment. Per STYLE.md, every component prop should be documented with a JSDoc block comment so its purpose is clear at the definition site. Note the sibling SearchRouterOptionsWarmerProps type already documents the same prop.

Add a block comment above the prop:

type OptionsWarmerProps = {
    /** Called once the option list is cached (or the warm is no longer needed), so the parent can unmount this component. */
    onDone: () => void;
};

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

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.

Fixed

onDone: () => void;
};

// Stop waiting for quiet after this many idle windows; a chatty account never fully stops writing.

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-16 (docs)

This comment uses a semicolon to join two independent clauses. Comments should read as plain sentences, so split it into two separate sentences instead of using a semicolon.

// Stop waiting for quiet after this many idle windows. A chatty account never fully stops writing.
const MAX_QUIET_WAIT_ATTEMPTS = 5;

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

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.

Fixed

The native route mounts on a deep link or a restored last-visited path without openSearchRouter, and hardware Back and the iOS gesture pop it without closeSearchRouter, so set and reset the module-level flag from the page itself.
@MelvinBot

Copy link
Copy Markdown
Contributor

Review

Overall this is a solid, well-reasoned change — the design (idle warm-up gated on Onyx inputs holding still, config extracted so the warmer and the live screen key the cache identically, unmount-when-done) is sound and unusually well-commented. The earlier bot findings (native back/gesture flag leak, comment style, prop docs) all look addressed. A few things worth a look before merge:

1. No tests for the new warm-up logic (main gap)

The 8-file diff adds no test, and Codecov flags a coverage drop — yet the author checklist claims unit tests were added. The pieces most likely to regress silently are pure logic and easy to cover:

  • The cache-hit invariant: after the warmer builds, the first empty-query open should hit createFilteredOptionList's cache rather than rebuild. That's the whole point of the PR and nothing guards it — a future change to the config or the key inputs could quietly turn the warm into dead work with no test failing.
  • The config-sharing invariant: searchRouterOptionsConfig.ts exists precisely so the warmer and SearchAutocompleteList produce the same cache key. A test asserting both call sites yield the same buildFilteredOptionListCacheKey inputs (maxRecentReports, includeP2P, isSearching, deferContactsUntilSearch) would lock that down.
  • The quiet-wait state machine in SearchRouterOptionsWarmer (reschedule while churn advances, cap at MAX_QUIET_WAIT_ATTEMPTS, bail when the router is already open) is testable with a fake scheduler.

2. Churn heuristic covers a subset of the cache inputs (non-blocking)

The warmer waits for reports/policies/personalDetails/reportAttributes/sortedActions to settle (here), but the cache key/inputs in createFilteredOptionList also include privateIsArchivedMap, conciergeReportID, isTrackIntentUser, and the locales. If one of those flips reference between the warm build and the first open, the cache simply misses and the live screen rebuilds — correct, just a missed optimization. Not a bug, but a one-line comment noting the wait is best-effort (and doesn't watch every invalidation source) would help the next reader.

3. Re-arm on every IS_LOADING_APP → false (confirm, non-blocking)

SearchRouterWarmup keys its effect on isLoadingApp, so every reconnect/OpenApp cycle that toggles the flag re-schedules an idle warm and re-mounts the options warmer. That's the intended "rewarm invalidated data" behavior, but on a flaky connection it means repeated churn-waits + builds. It self-limits (bails when the router is open, and cache hits are cheap), so likely fine — just worth confirming it doesn't thrash.

On the failing checks

The only red checks are the reviewer/author checklist gates and Codecov (item 1). Nothing in the actual failures points at a code defect in this diff — adding the tests above would clear Codecov and cover the highest-risk paths at once.

Scope of this review

Code review only — I did not exercise the app at runtime. The paths most worth a manual pass are the author's own Test steps 4–6 (idle-then-open, open-immediately-after-load-before-idle, and sign-out/sign-in), since those are exactly the cache-hit and cache-invalidation transitions this PR introduces.

@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: 8cd9dcca95

ℹ️ 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 on lines +58 to +61
if (churnVersionRef.current !== lastSeenChurn && attempts < MAX_QUIET_WAIT_ATTEMPTS) {
lastSeenChurn = churnVersionRef.current;
attempts += 1;
waitForQuiet();

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 Yield between quiet-period checks

When React Scheduler still has budget, an idle-priority callback scheduled from a currently running idle callback can execute in the same scheduler work loop; Scheduler.scheduleWhenIdle only adds a competing 300 ms fallback and does not guarantee a new event-loop window. Consequently, this recursive call can immediately observe the same churnVersionRef, enable the build, and unmount the warmer before queued post-OpenApp Onyx deliveries run. On accounts whose updates arrive just after that scheduler flush, the next delivery invalidates the transient cache entry, so the first Search open still performs the full build while startup also paid for the discarded warmup. Introduce an actual yield between checks or restart a quiet-period timer when an input changes.

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.

Confirmed: a recursive scheduleWhenIdle re-runs inside the same scheduler work loop (8 recursions in one macrotask, 0.085 ms), so the quiet-wait barely waits. I built the real debounce (300 ms per watched input, 2 s cap) and A/B'd it against this branch on Android — interleaved variants, 6 paired rounds, cold launch, tap after a 25 s settle: the debounce variant lands +8.6% slower than this branch (median 1028 ms vs 943 ms, slower in 5/6 rounds), so making the wait real buys nothing and I'd rather not grow the warm-up code for it here.
Cache hit rate is the remaining gap and I'll take it in a follow-up: the warm entry is still invalidated by Onyx writes right after launch, exactly as you point out, so this is better than before but not yet ideal.

@sumo-slonik

Copy link
Copy Markdown
Contributor Author

Hi @aimane-chnaif, I think this PR is ready for a second round of review.

@sumo-slonik

Copy link
Copy Markdown
Contributor Author

Hi @aimane-chnaif, just a small ping — I think this PR is ready for a second round of review whenever you have a chance.

@aimane-chnaif

aimane-chnaif commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

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 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 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 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
    • 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 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: mWeb Chrome
iOS: HybridApp
ios.mov
iOS: mWeb Safari
MacOS: Chrome / Safari
web.mov

@sumo-slonik

Copy link
Copy Markdown
Contributor Author

@aimane-chnaif What’s the progress on this review?

@aimane-chnaif

Copy link
Copy Markdown
Contributor

Should be done today

@sumo-slonik

Copy link
Copy Markdown
Contributor Author

Thanks!

@aimane-chnaif aimane-chnaif 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.

NAB comments:

return;
}

const task = Scheduler.scheduleWhenIdle(() => {

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.

Can we reuse TransitionTracker.runAfterTransitions which is purpose-built for "schedules a callback to run after all transitions complete", firing synchronously when nothing is active?

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.

Good idea, but I don't think it fits this spot: at launch nothing has started a transition yet, so runAfterTransitions would fire synchronously inside the Onyx commit we're trying to step out of, and waitForUpcomingTransition would instead wait for the user's next navigation and fire at the end of it, in the middle of the incoming screen's render. They're really meant to nest rather than replace scheduleWhenIdle (see usePreMountDestination), and here there's no transition to wait for .

Comment on lines +23 to +29
const [isLoadingApp] = useOnyx(ONYXKEYS.IS_LOADING_APP);
const [OptionsWarmer, setOptionsWarmer] = useState<ComponentType<SearchRouterOptionsWarmerProps> | null>(null);

useEffect(() => {
if (isLoadingApp !== false) {
return;
}

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.

Not a user-visible regression but this guard only works on the very first launch after logging in.
Once logged in, on every relaunch (force-quit and reopen), isLoadingApp is always false and lets the warm-up run before the data arrives.
Maybe it's fine assuming that data already arrived?

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.

Good catch, you're right that it's inert on a relaunch. I'd still keep it as-is: the collections are already on disk by then, and if reconnect data lands after the build we only lose the cache hit, so the first open rebuilds the list exactly as it does today. The stricter gates I looked at are worse — IS_LOADING_REPORT_DATA never clears while offline, so the warm-up would never run at all, and HAS_LOADED_APP stays true after the first launch. I've added a comment at the guard so it doesn't surprise the next reader.

@aimane-chnaif

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: d5bac355e1

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

@MelvinBot

Copy link
Copy Markdown
Contributor

Re-review

Recheck against the current head (d5bac355) after the last round. The design is sound and the earlier feedback is addressed — the one thing still standing between this and merge is tests.

Resolved since the previous review

  • Shared prop type — SearchRouterWarmup.tsx:12 now imports SearchRouterOptionsWarmerProps instead of redeclaring it, so the two contracts can't drift.
  • Config sharing — every value the cache key depends on is centralized in searchRouterOptionsConfig.ts and spread into both call sites, and I confirmed it reproduces the previous inline values exactly (maxRecentReports:100, batchSize:500, includeP2P, deferContactsUntilSearch:true) and is spread before isSearching, so no key collision.
  • Native open-flag reset, comment style, and prop JSDoc from the earlier rounds are all in.

1. Still no tests — blocking (item carried over)

The diff adds no test file and Codecov is red, yet the author checklist has "I added unit tests… to prevent regressions" checked. That box isn't accurate for the current diff. The whole PR is a cache optimization with nothing guarding it — the pieces most likely to silently rot are pure and cheap to cover:

  • Cache-hit invariant: after the warmer builds, the first empty-query open should hit createFilteredOptionList's cache rather than rebuild. This is the entire point of the PR; a config or key-input change could quietly turn the warm into dead work with no test failing.
  • Config-sharing invariant: assert both call sites produce the same buildFilteredOptionListCacheKey inputs (maxRecentReports, includeP2P, isSearching, deferContactsUntilSearch).
  • Quiet-wait state machine in SearchRouterOptionsWarmer (reschedule while churn advances, cap at MAX_QUIET_WAIT_ATTEMPTS, bail when the router is already open) — testable against a fake Scheduler.

Adding these clears Codecov and covers the highest-risk paths at once.

2. Churn heuristic watches a subset of the cache inputs (non-blocking)

The warmer waits on reports/policies/personalDetails/reportAttributes/sortedActions (here), but the cache also keys on privateIsArchivedMap, conciergeReportID, isTrackIntentUser, visibleReportActionsData, policyTags, and the locales (useFilteredOptions.ts:104-138). If one flips reference between warm and open, the cache just misses and the live screen rebuilds — correct, only a missed optimization. Worth a one-line comment noting the wait is best-effort. Note also that sortedActions gets a fresh reference on every recompute, so on an active account the warm can miss more often than the local numbers suggest — the high-traffic-account run is the real signal here.

3. Inline onDone depends on React Compiler memoization (non-blocking)

SearchRouterWarmup.tsx:49 passes an inline () => setOptionsWarmer(null), and the child lists onDone in its quiet-wait effect deps. If a compiler doesn't memoize it on some platform, the effect re-runs and resets attempts/lastSeenChurn, restarting the wait. Low risk (parent rarely re-renders once mounted), but a useCallback makes the stable-identity contract explicit rather than compiler-dependent.

4. Re-arm on every IS_LOADING_APP → false (confirm, non-blocking)

SearchRouterWarmup keys its effect on isLoadingApp, so each reconnect/OpenApp cycle re-schedules a warm. Self-limiting (bails when open, cache hits are cheap), just worth confirming it doesn't thrash on a flaky connection.

Scope of this review

Code review of the current head. The behavioral surface hasn't changed since the earlier runtime pass on web (this round is a shared type + an identical-value config extraction + two main merges), which exercised open → type → clear → open-report and the idle-then-open / open-before-idle transitions and found no regression. The paths still most worth a manual pass are Test steps 4–6 (idle-then-open, open-immediately-after-load, sign-out/sign-in) on a high-traffic account, plus a JS-console check for step 1 (the web driver can't read the console).

Recommendation: Approvable on code once the tests in item 1 land — that also clears the only real red check. Items 2–4 are polish, not blockers.


view run

@MelvinBot

Copy link
Copy Markdown
Contributor

Regression hunt

Bottom line: no regression found by static tracing of the current head (d5bac355). I could not re-confirm at runtime this round — the web dev server can't build in this environment (a missing dependency, unrelated to this PR — details at the bottom), so the runtime pass fell back to static analysis. The identical flows were exercised at runtime on web in the earlier regression hunt (all six steps passed), and nothing behavioral has changed since — the delta is a shared prop type, an identical-value config extraction, and two main merges.

Regression vectors traced and cleared

  • SearchAutocompleteList config refactor — SEARCH_ROUTER_OPTIONS_CONFIG reproduces the prior inline values exactly (enabled:true, includeP2P:true, deferContactsUntilSearch:true, maxRecentReports:100, batchSize:500) and is spread before isSearching in SearchAutocompleteList.tsx:214-218, so no key collision. The two removed constants were file-local, not exported. Behaviorally identical.
  • Moved lazy loaders — searchRouterLazyLoaders.ts sits in the same directory as the old inline loaders, so its relative require paths resolve to the same modules, and AuthScreens.tsx:291,302 still wire them as getComponent. Screen registration unchanged.
  • Module-level isSearchRouterOpenOrOpening — only read by the warmers; the writes added to the open/close paths and the native route effect are side-assignments that don't gate or alter any existing open/close logic. It's reset on provider unmount, so an open router can't leak "open" into the next session.
  • Cross-account / sign-out safety — the option-list cache is cleared on session cleanup (OptionsListUtils/index.ts:1751), and currentUserAccountID is part of the cache inputs (here), so a warmed entry from one account can never be served to another even before the clear.
  • Cache correctness — createFilteredOptionList serves a warmed entry only when every reference-equality input still matches at open time; any mismatch rebuilds. A stale or wrong list can't be served from the warm — worst case is a silent cache miss (missed optimization, not a wrong result).

Worth a runtime look (not reproducible here)

  1. Startup Onyx read cost on large accounts — SearchRouterOptionsWarmer subscribes to the full REPORT/POLICY collections + personal details during the post-launch idle window. That's the intended trade, but it's the one thing that could regress TTI/contention on a high-traffic account — that run in the checklist is the real signal.
  2. Re-arm on every IS_LOADING_APP → false — SearchRouterWarmup re-schedules on each reconnect/OpenApp cycle; self-limiting (bails when the router is open, cache hits are cheap) but repeats on flaky connections.
  3. Console cleanliness — the web driver has no JS-console access, so the PR's "no console errors" step stays unverified; worth a manual console check during QA, especially around the idle warm.
Why the runtime pass was blocked (environment, not this PR)

The dev server build failed with ERR_MODULE_NOT_FOUND: Cannot find package 'oxc-transform' from config/rsbuild/loaders/oxc-react-compiler-loader.mjs. package.json requires oxc-transform@0.136.0 but only oxc-transform-react/oxc-resolver are present in node_modules, so the app never renders past the splash screen (0 DOM nodes). The PR diff touches only Search-router components — not package.json or the rsbuild config — so this is a CI/install problem, not a defect in the PR. Re-running npm install (or npm ci) before retrying the runtime test should unblock it.

App stuck on splash screen (dev server build broken)


view run

@melvin-bot
melvin-bot Bot requested a review from mountiny August 20, 2026 15:52
Assert that a second build with the router's empty-query config is served from
createFilteredOptionList's cache rather than rebuilt, that the empty-query build
keeps contacts deferred, and that typing is a separate entry. Assert the live
list asks for the shared config too, so the warm build and the first open cannot
drift apart on the values that cache is keyed on.

Also document that isLoadingApp only gates the fresh sign-in launch, and drop
the JSDoc claim that the callback runs on an idle thread when the scheduler's
fallback timer can force it.
@sumo-slonik

Copy link
Copy Markdown
Contributor Author

Added the missing test for the cache-hit invariant — I think we're ready here.

@mountiny mountiny 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.

Alright, looks like interesting solution, I hope this will help the long tail

@mountiny
mountiny merged commit 55bcbd1 into Expensify:main Aug 21, 2026
37 of 40 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 OSBotify mentioned this pull request Aug 22, 2026
61 tasks done
@OSBotify

Copy link
Copy Markdown
Contributor

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

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

@MelvinBot

Copy link
Copy Markdown
Contributor

Help site review: no changes required

I reviewed the changes in this PR against the help site articles under docs/articles, and no documentation updates are needed. I have not created a draft PR.

Why: This is a purely internal performance optimization. It adds a warmup path (SearchRouterWarmup / SearchRouterOptionsWarmer) that pre-builds the Search router's option-list cache during an idle window after launch, moving first-open work off the critical path to cut the p95 tail when opening the Search bar. The user-visible behavior is unchanged — the Search router still opens to the same recent searches and recent reports list, autocomplete works the same, and the test steps describe the existing behavior (just faster). There is no new feature, no UI/label/tab/setting change, and no copy change.

The help articles describe what users can do with Search, not its rendering latency, so there is nothing to document here. A quick scan of docs/articles surfaced no article whose content this change would affect.

If I've misread the scope and there's a user-facing behavior change you'd like documented, reply with the specifics and I'll take another look.


view run

@mitarachim

Copy link
Copy Markdown

Deploy Blocker #99256 was identified to be related to this PR.

@aimane-chnaif

Copy link
Copy Markdown
Contributor

Deploy Blocker #99256 was identified to be related to this PR.

False alarm. This is not the offending PR.

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/AndrewGable in version: 9.4.59-5 🚀

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

Bundle Size Analysis (Sentry):

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.

7 participants