Skip to content

Move the unread indicator onto useOnyx so report updates stop slowing down - #104568

Merged
mountiny merged 9 commits into
Expensify:mainfrom
callstack-internal:eliran/3042-report-write-perf
Nov 17, 2026
Merged

mountiny merged 9 commits into
Expensify:mainfrom
callstack-internal:eliran/3042-report-write-perf

Conversation

@elirangoshen

@elirangoshen elirangoshen commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

The unread indicator (browser tab title on web, app badge on iOS) counts unread reports after every report update. It ran as a plain module: it read reports, report actions, name-value pairs, drafts and report attributes through Onyx.connectWithoutView, and cached the count with memoize. That cache compared deeply and had no size limit. Every report update passes a new reports collection, so the cache never matched: each update stored a full copy of all reports and compared against every older copy. Memory and cost grew for the whole session.

This PR moves the logic into a small UnreadIndicatorUpdater component that renders nothing:

  • It reads its data with useOnyx and takes the current report ID from useCurrentReportIDState. React Compiler caches the count, so it is only redone when one of its inputs changes, and no old copies are kept.
  • getUnreadReportsForUnreadIndicator is now a pure function that takes all its data as arguments. The module-level Onyx subscriptions, the memoize cache, the debounce and the navigation and app-state listeners are removed.
  • The component is mounted in Expensify.tsx once the splash screen is hidden, which replaces the lazy load.ts import. On Android it renders null, as before there is no tab title or badge to update.

There is no user-facing behavior change.

Measured (heavy test account with 4,061 reports, production web build, 4x CPU throttle, 200 simulated updates to one report, main and this PR on the same day):

  • On main, the unread check costs about 0.9 ms more with every update, with no limit: 26 ms at the start, 187 ms after 200 updates. The whole update goes from 519 ms to 678 ms.
  • With this PR, the unread check stays flat at about 14 ms and the whole update stays at about 510 ms, with no growth over the session.
  • After 200 updates: 678 ms on main vs 508 ms with this PR, 170 ms (25%) less per update. The unread check alone drops from 187 ms to 13 ms (93% less), and the gap keeps growing as the session goes on.
  • Averaged over all 200 updates: 590 ms vs 513 ms, 77 ms (13%) less per update.

Fixed Issues

$#105827

PROPOSAL:

Tests

  1. Run npx jest tests/ui/UnreadIndicatorUpdaterTest.tsx and verify all tests pass.
  2. Open a chat with unread messages. Verify the unread badge count in the LHN and the browser tab title is correct.
  3. Receive a new message in another chat. Verify the unread count goes up in the LHN and the tab title.
  4. Open that chat so the messages are marked as read. Verify the unread count goes down in the LHN and the tab title.
  5. Switch between a few chats without any new messages. Verify the unread count stays the same.
  6. Go to the Account tab (Settings) and back to Inbox. Verify the unread count stays correct.
  7. On iOS, verify the app icon badge shows the same unread count.
  • Verify that no errors appear in the JS console

Offline tests

  1. Go offline.
  2. Mark a chat as unread, then open it. Verify the unread count in the LHN and the tab title goes up and then down.
  3. Verify no errors appear.

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 verified any copy / text that was added to the app 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 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 new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If the PR adds or modifies the UI:
    • I asked an AI agent to review the changes for accessibility issues and addressed its findings.
    • I tested with a screen reader (VoiceOver on macOS) and verified all new/changed elements are reachable with a logical focus order.
    • I verified all new/changed elements have meaningful accessible names and roles.
    • I verified state changes are announced (e.g. checked/unchecked, expanded/collapsed, selected).
  • 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 web-2-two-unread web-3-read-one web-4-switch-chats web-5-account web-6-back-to-inbox web-7-all-read b-1-one-unread.png…]()

Several report_ subscribers redid work over every report on each write,
even when nothing they use changed:
- UnreadIndicatorUpdater: memoize used deep equality with no size limit, so each
  write added a cache entry and deep-compared all previous reports snapshots;
  keep only the last call, compared by reference
- replaceOptimisticReportWithActualReport: skip reports without preexistingReportID early
- Parser and ReportUtils: build reportIDToNameMap and reportsByPolicyID lazily
- WideRHPContextProvider: select only invoice/task report keys
- FAB and floating camera button: stop at the first workspace chat
- SuggestionMention: select mentionable room names instead of full reports
- Unread indicator memo keeps one cache entry across report updates and reuses the result for the same collection
- Parser report mentions use the current report name after a rename
- getFirstWorkspaceChat matches the first result of getWorkspaceChats
@codecov

codecov Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Coverage Δ
src/Expensify.tsx 85.95% <100.00%> (+0.11%) ⬆️
src/SplashScreenStateContext.tsx 96.00% <ø> (ø)
src/components/UnreadIndicatorUpdater/index.tsx 100.00% <100.00%> (ø)
src/libs/UnreadIndicatorUpdater/index.ts 100.00% <100.00%> (+6.89%) ⬆️
...omponents/UnreadIndicatorUpdater/index.android.tsx 0.00% <0.00%> (ø)
... and 1938 files with indirect coverage changes

Drop the ReportUtils policy grouping, FAB first-workspace-chat and mention-names
changes; each saved under 2 ms per report update.
Revert the Parser, replaceOptimisticReportWithActualReport and WideRHPContextProvider changes. They save only a few ms each, so they will go through metric issues as separate PRs.
@elirangoshen elirangoshen changed the title Stop recomputing whole-report work on every report write Keep only the latest unread indicator result instead of every report snapshot Oct 30, 2026
The unread count now lives in a small UnreadIndicatorUpdater component that
reads its data with useOnyx and lets React Compiler cache the result, so the
module-level Onyx subscriptions, the memoize cache and the debounce go away.
The counting logic is a pure function that takes all its data as arguments.
@elirangoshen elirangoshen changed the title Keep only the latest unread indicator result instead of every report snapshot Move the unread indicator onto useOnyx so report updates stop slowing down Nov 3, 2026
@elirangoshen
elirangoshen marked this pull request as ready for review November 4, 2026 10:01
@elirangoshen
elirangoshen requested review from a team as code owners November 4, 2026 10:01
@melvin-bot
melvin-bot Bot requested review from abdulrahuman5196 and garrettmknight and removed request for a team November 4, 2026 10:01
@melvin-bot

melvin-bot Bot commented Nov 4, 2026

Copy link
Copy Markdown

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

@elirangoshen

Copy link
Copy Markdown
Contributor Author

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

Hi is there anything you need from me to push the review forward ? :)

@garrettmknight
garrettmknight removed their request for review November 6, 2026 15:43
@abdulrahuman5196

Copy link
Copy Markdown
Contributor

Hi, Checking now

@abdulrahuman5196

Copy link
Copy Markdown
Contributor

@MelvinBot review

1 similar comment
@abdulrahuman5196

Copy link
Copy Markdown
Contributor

@MelvinBot review

@MelvinBot

Copy link
Copy Markdown
Contributor

🤖 Web test steps verification results: ⚠️ partial

Completed onboarding and exercised Account settings → Inbox on dev NewDot web. Unread-count assertions remain blocked by fixture and tooling limitations; no product failure was established.

Inbox after returning from Account settings

Step Status
1. Run unread-indicator testsTest execution was blocked by command permissions; tests were not verified.
⚠️
2. Open unread chat and verify countsOpened Concierge, but numeric LHN and browser-title counts could not be read through the available tooling.
Inbox after returning from Account settings
⚠️
3. Receive another message; verify count increasesNo incoming-message fixture was available.
⚠️
4. Open that chat; verify count decreasesBlocked by the unavailable incoming-message fixture.
⚠️
5. Switch chats; verify count stays unchangedOnly one conversation was available.
⚠️
6. Settings → Inbox; verify count remains correctNavigation succeeded, but numeric count correctness could not be verified.
⚠️
7. Verify iOS app-icon badgeOutside this web-only run.
⚠️
8. Verify no JavaScript console errorsConsole inspection was unavailable.
⚠️
9. Go offlineOffline mode could not be established through the available controls.
⚠️
10. Offline: mark unread, then open chatCount transitions were not tested because offline mode was unavailable.
⚠️
11. Verify no errors offlineOffline mode and console inspection were unavailable.
⚠️

view run

@MelvinBot

Copy link
Copy Markdown
Contributor

🤖 Web test steps verification results: ⚠️ partial

Verified navigation on dev NewDot web, but unread-count correctness remains unverified. Only the existing Concierge conversation was available; no messages or accounts were fabricated.

Inbox after returning from Account settings, showing the existing Concierge welcome conversation

Step Status
1. Run unread-indicator testsTest execution was blocked by command permissions; no test results obtained.
⚠️
2. Open unread chat; verify LHN and tab countsOpened Concierge, but numeric unread counts and browser-title readback were unavailable.
⚠️
3. Receive another message; verify counts increaseNo incoming-message fixture or second conversation was available.
⚠️
4. Open that chat; verify counts decreaseBlocked by the unavailable incoming-message fixture.
⚠️
5. Switch chats; verify count stays unchangedNo second chat or readable baseline count was available.
⚠️
6. Settings → Inbox; verify count remains correctNavigation succeeded and returned to the same conversation; count correctness remains unverified.
Inbox after returning from Account settings, showing the existing Concierge welcome conversation
⚠️
7. Verify iOS app-icon badgeOutside this web-only run.
⚠️
8. Verify no JavaScript console errorsBrowser console collection was unavailable.
⚠️
9. Go offlineOffline toggling was unavailable through the supported tooling.
⚠️
10. Offline: mark unread, then open chatNot tested because offline mode was not established.
⚠️
11. Verify no errors offlineOffline mode and console collection were unavailable.
⚠️

view run

@elirangoshen

Copy link
Copy Markdown
Contributor Author

Hi, so is there anything you need from me about this pr ? I see ,Melvin tested it but seems like its better to also have qa to test as it seems didn't finish.

@elirangoshen

Copy link
Copy Markdown
Contributor Author

Hi @abdulrahuman5196 any update on this ?

@abdulrahuman5196

Copy link
Copy Markdown
Contributor

Hi, Checking now again

@abdulrahuman5196

Copy link
Copy Markdown
Contributor

@MelvinBot I see you tried to run the tests, but did you run the code review?

@MelvinBot

Copy link
Copy Markdown
Contributor

Not a complete code review. I inspected the diff and some related code, but did not finish a systematic review or report code findings. My previous replies covered attempted test verification only—not a code-review verdict. Sorry for missing that part of your request.


view run

@abdulrahuman5196

Copy link
Copy Markdown
Contributor

@MelvinBot Could you kindly do a code review of this PR?

@MelvinBot

Copy link
Copy Markdown
Contributor

Code review

Reviewed all eight changed files and the related navigation, Onyx, and unread-publication code at fe365d4.

Finding: P2 — Avoid deep-comparing the entire report-attributes map

In src/components/UnreadIndicatorUpdater/index.tsx:20–22, the selector returns the complete reports map. Onyx deep-compares selector results, so this introduces a potentially account-wide comparison whenever report attributes change—on the performance-sensitive path this PR is improving.

Subscribe without a selector and access .reports afterward. This preserves reference-based comparison and follows PERF-11. This is bounded comparison overhead, not a recurrence of the unbounded cache leak.

Test coverage

The new tests cover initial publication and marking a report read. Additional regression coverage would be useful for navigation/draft changes, foreground refresh, and Concierge-response completion, especially because the registered callback now republishes a render-time snapshot rather than recalculating.

No other definite blocking defect found. This was a static code review; I did not rerun tests or independently validate the performance measurements.


view run

The selector returned the whole reports map, so Onyx deep-compared it on
every derived-value write. Use useReportAttributes() for reference
comparison, and cover navigation and foreground republish in tests.
@elirangoshen

Copy link
Copy Markdown
Contributor Author

Code review

Reviewed all eight changed files and the related navigation, Onyx, and unread-publication code at fe365d4.

Finding: P2 — Avoid deep-comparing the entire report-attributes map

In src/components/UnreadIndicatorUpdater/index.tsx:20–22, the selector returns the complete reports map. Onyx deep-compares selector results, so this introduces a potentially account-wide comparison whenever report attributes change—on the performance-sensitive path this PR is improving.

Subscribe without a selector and access .reports afterward. This preserves reference-based comparison and follows PERF-11. This is bounded comparison overhead, not a recurrence of the unbounded cache leak.

Test coverage

The new tests cover initial publication and marking a report read. Additional regression coverage would be useful for navigation/draft changes, foreground refresh, and Concierge-response completion, especially because the registered callback now republishes a render-time snapshot rather than recalculating.

No other definite blocking defect found. This was a static code review; I did not rerun tests or independently validate the performance measurements.

view run

ok I addressed those

@elirangoshen

Copy link
Copy Markdown
Contributor Author

Hi @abdulrahuman5196 is there an update ?

@elirangoshen

Copy link
Copy Markdown
Contributor Author

Hi is there anything that I should do to promote it to be merged ? @abdulrahuman5196

@abdulrahuman5196

Copy link
Copy Markdown
Contributor

@elirangoshen the code looks good to me. Could you kindly fix the TS errors? I can proceed to platform specific testing then

@elirangoshen

Copy link
Copy Markdown
Contributor Author

@elirangoshen the code looks good to me. Could you kindly fix the TS errors? I can proceed to platform specific testing then

done

@abdulrahuman5196

Copy link
Copy Markdown
Contributor

checking now

@abdulrahuman5196

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 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
    • 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
    • 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 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.
  • If the PR adds or modifies the UI:
    • I asked an AI agent to review the changes for accessibility issues and addressed its findings.
    • I tested with a screen reader (VoiceOver on macOS) and verified all new/changed elements are reachable with a logical focus order.
    • I verified all new/changed elements have meaningful accessible names and roles.
    • I verified state changes are announced (e.g. checked/unchecked, expanded/collapsed, selected).
  • 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
androidHybrid-0-Screen_Recording_2026-11-17_at_12.28.13.AM.mov
Android: mWeb Chrome
androidMWeb-0-Screen_Recording_2026-11-17_at_12.32.39.AM.mov
iOS: HybridApp
iosHybrid-0-Screen_Recording_2026-11-17_at_12.12.47.AM.mov
iOS: mWeb Safari
iosMWeb-0-Screen_Recording_2026-11-17_at_12.14.34.AM.mov
MacOS: Chrome / Safari
macOS-0-Screen_Recording_2026-11-16_at_11.47.37.PM.mov

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

Changes looks good and works well. Reviewers checklist is also complete.

All yours.

🎀 👀 🎀
C+ Reviewed

@melvin-bot
melvin-bot Bot requested a review from mountiny November 16, 2026 19:06

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

Nice, thank you!

@mountiny
mountiny merged commit 41df97e into Expensify:main Nov 17, 2026
37 of 39 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

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

@github-actions

Copy link
Copy Markdown
Contributor

@OSBotify

Copy link
Copy Markdown
Contributor

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

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

@MelvinBot

Copy link
Copy Markdown
Contributor

No help site update needed — this PR refactors unread-indicator calculations for performance without adding a feature, changing user workflows, removing a beta, or making existing article text incorrect.


view run

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/marcaaron in version: 9.5.41-2 🚀

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.

5 participants