Skip to content

Optimize top-N report selection in option list building - #96748

Merged
mjasikowski merged 18 commits into
Expensify:mainfrom
software-mansion-labs:jmgraa/useFilteredOptions-optimization
Jul 28, 2026
Merged

mjasikowski merged 18 commits into
Expensify:mainfrom
software-mansion-labs:jmgraa/useFilteredOptions-optimization

Conversation

@jmgraa

@jmgraa jmgraa commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

Optimizes report selection in createFilteredOptionList for accounts with large report lists.

optionsOrderBy and optionsOrderAndGroupBy now decorate each option with its pre-computed sort key (shared DecoratedOptionHeap helper), so the comparator runs exactly once per option instead of on every O(log n) heap comparison and every eviction check, cutting redundant work when picking the top N reports.

Top-N selection happens directly in createFilteredOptionList via optionsOrderBy with reportSortComparator, keeping the same rules: self-DM first, then non-archived, then most recent; search mode still returns all reports. optionsOrderBy itself is now implemented as optionsOrderAndGroupBy with no separators, removing the duplicated heap logic between the two functions.

Two fixes along the way:

  • optionsOrderAndGroupBy now respects reversed: true when a heap is at capacity - previously the eviction check always compared with >, so reversed callers kept the newest options instead of the oldest. Covered by a new unit test.
  • The limit <= 0 early return in optionsOrderAndGroupBy returned a sparse array (Array(n).map() skips empty slots), which could crash callers destructuring the groups; it now returns N+1 real empty arrays via Array.from.

Aside from the reversed: true fix, no user-facing behavior change - same reports, same order, less work during option-list building. Unit tests cover comparator call counts, grouping, limits, and reversed ordering.

createFilteredOptionList (tests/perf-test/OptionsListUtils.perf-test.ts)

Before After
280ms 173ms
280ms 174ms
270ms 172ms
285ms 170ms

Fixed Issues

$ #95335
PROPOSAL:

Tests

  1. Open New chat (+) and confirm recent chats load and are ordered with the most recent at the top.
  2. Confirm your self-DM (Notes) appears near the top even if it has not been updated recently.
  3. Open Search, type a report or user name, and confirm matching results appear (including older or archived chats if they match).
  4. Clear the search query and confirm recent results still load correctly.
  5. Share content into Expensify (or open Share from the app) and confirm destination chats/users load and you can pick one.
  6. Scroll/paginate on a screen that loads more reports (e.g. New chat with many reports) and confirm additional chats appear.

In addition, the component should behave just as it does in production

  • Verify that no errors appear in the JS console

Offline tests

Same as tests

QA Steps

Same as tests

  • 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_1.mov
iOS: Native
ios_1.mov
MacOS: Chrome / Safari
web_1.mov

@dariusz-biela dariusz-biela 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.

This looks good. I think we should also apply the precomputed-key optimization to optionsOrderAndGroupBy(), which is used by getValidOptions() in the Share flow. It currently recalculates recentReportComparator during heap comparisons, while both helpers solve the same bounded top-N problem.

Comment thread src/libs/OptionsListUtils/index.ts Outdated
Comment thread src/libs/OptionsListUtils/index.ts Outdated
@codecov

codecov Bot commented Jul 24, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Coverage Δ
src/libs/OptionsListUtils/index.ts 86.92% <96.66%> (+0.08%) ⬆️
... and 8 files with indirect coverage changes

Comment thread src/libs/OptionsListUtils/index.ts
Comment thread src/libs/OptionsListUtils/index.ts
Comment thread src/libs/OptionsListUtils/index.ts Outdated

@dariusz-biela dariusz-biela 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.

LGTM, nice work!

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

melvin-bot Bot commented Jul 27, 2026

Copy link
Copy Markdown

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

@ikevin127

ikevin127 commented Jul 27, 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

Screen.Recording.2026-07-27.at.17.41.29.mov

Comment thread src/libs/OptionsListUtils/index.ts Outdated
Comment thread tests/unit/OptionsListUtilsTest.tsx
@ikevin127

Copy link
Copy Markdown
Contributor

@jmgraa ⚠️ Heads up before this lands: this branch is ~1027 commits behind main, and I hit a crash locally that isn't a regression from your changes. Opening Spend > Expenses > Filters > Chat crashes on web with:

TypeError: Cannot read properties of undefined (reading 'type')
    at isSearchDataLoaded (SearchUIUtils.ts:4813)
    at useSearchPageSetup (useSearchPageSetup.ts:29)
    at SearchPage (SearchPage.tsx:36)

It's a stale-branch artifact, not from this PR. Your diff only touches OptionsListUtils, and this crash is in isSearchDataLoaded, where the old code dereferences searchResults.search.type without guarding searchResults.search. That's already fixed on main (rewritten to searchResults?.search?.type), which is why staging is fine and this branch isn't (same High Traffic account, older code).

Could you merge main into this branch and retest? Two reasons:

  1. It clears this crash via the upstream optional-chaining fix.
  2. If it's not merged, the automated adhoc/test builds will reproduce this same already-solved crash and make the PR look broken, even though the fix just needs to be pulled in.

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

🟢 LGTM

Only have two 🟡 non-blocker comments (see above) and one ⚠️ warning regarding merging main branch to avoid a now-fixed crash during manual testing in Spend page (not related to this PRs changes).

🧪 Tests I ran to validate PRs changes:

✅ 1. Recency and self-DM ordering (online): Open New chat (+) on a high-traffic account. Confirm most-recent chats are at the top and your self-DM (Notes) sits near the top even if stale. This exercises the top-N heap selection and reportSortComparator priority.
✅ 2. Search returns all matches (online): Open Search, type a name that matches an older or archived chat, confirm it appears; clear the query and confirm the recent list restores. This validates the isSearching branch that bypasses the cap.
✅ 3. Offline parity + Share flow (offline): Turn off network, repeat New chat and Share-into-Expensify, confirm the same destination chats load, are pickable, and no console error fires. This covers ShareTab's optionsOrderBy call and the Array.from empty-group path.

Reassure perf: baseline (main) vs this PR

Headline: createFilteredOptionList, the function this PR optimizes, drops 44.4 ms → 23.6 ms (−46.8%), and its search-mode variant 17.0 ms → 11.9 ms (−30.0%). This corroborates the PR description's numbers (different absolute ms because of machine/fixture, same direction and magnitude).

  • measureFunction mean, single run each. Negative delta = faster
Scenario Baseline This PR Δ %
createFilteredOptionList 44.4 ms 23.6 ms −20.8 ms −46.8% 🟢
createFilteredOptionList with isSearching: true 17.0 ms 11.9 ms −5.1 ms −30.0% 🟢
getSearchOptions with isSearching: true 1.2 ms 1.0 ms −0.2 ms −16.7% 🟢
getSearchOptions 6.8 ms 5.8 ms −1.0 ms −14.7% 🟢
getShareDestinationOptions 6.6 ms 5.8 ms −0.8 ms −12.1% 🟢
empty search term with selected options + mocked personal details 1.7 ms 1.6 ms −0.1 ms −5.9% ⚪
getFilteredOptions with empty search value 0.4 ms 0.4 ms 0.0 ms 0.0% ⚪
getFilteredOptions with search value 1.9 ms 2.0 ms +0.1 ms +5.3% ⚪
worst case: search term matching subset of selected / recent reports / personal details 13.4 ms 14.5 ms +1.1 ms +8.2% ⚪

@melvin-bot
melvin-bot Bot requested a review from mjasikowski July 28, 2026 00:58
@mjasikowski
mjasikowski merged commit 4fe7387 into Expensify:main Jul 28, 2026
33 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

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

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

@OSBotify

Copy link
Copy Markdown
Contributor

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

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

@MelvinBot

Copy link
Copy Markdown
Contributor

🤖 I reviewed the changes in this PR against Expensify's help site content under App/docs/articles.

No help site changes are required.

This PR is a pure internal performance optimization of the option-list building logic — it refactors the heap-based top-N report selection in createFilteredOptionList / optionsOrderBy / optionsOrderAndGroupBy inside src/libs/OptionsListUtils/index.ts (plus new unit tests). There is no change to any user-facing feature, UI label, tab, setting, billing/pricing, workspace configuration, integration, or workflow that the help site documents.

As noted in your own PR summary, aside from an internal reversed: true eviction fix and a sparse-array early-return fix, there is no user-facing behavior change — the same reports load in the same order, just with less work during option-list building. None of these correspond to documented behavior in App/docs/articles, so there is nothing to update and I did not open a draft docs PR.

If you believe a specific help article does describe behavior affected here, let me know which one and I'll take another look.

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/marcaaron in version: 9.4.46-10 🚀

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

Bundle Size Analysis (Sentry):

@jmgraa
jmgraa deleted the jmgraa/useFilteredOptions-optimization branch August 28, 2026 11:53
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