Skip to content

perf: Share policy collection scans between subscribers - #108442

Merged
mountiny merged 4 commits into
Expensify:mainfrom
callstack-internal:perf/pebl-policy-index
Dec 2, 2026
Merged

mountiny merged 4 commits into
Expensify:mainfrom
callstack-internal:perf/pebl-policy-index

Conversation

@sosek108

@sosek108 sosek108 commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

On accounts with thousands of workspaces, every write to any one workspace made about 30 subscribers each go through the whole policy collection with the same few checks: active workspaces, admin workspaces, owned paid workspaces, and the Workspaces tab red dot. On an account with about 6000 workspaces, one unrelated policy write cost about 290 to 370 ms of JavaScript on Home.

The shared policy helpers now cache their result per Onyx collection snapshot. Onyx hands every subscriber the same frozen snapshot until the collection changes, so the first subscriber on a write does the scan and the rest reuse it. Collections that aren't frozen are never cached, and each answer is also keyed by the login, account ID or offline state it depends on. The cached arrays are now typed as readonly, so no caller can sort or change a shared result; the Wallet page sorted one in place and now uses sortPoliciesByName, which copies first.

The Workspaces tab red dot also remembers each policy's check results for as long as Onyx keeps that policy object, so a write only re-checks the policy it changed. The sync and HR connection checks now only look at admin workspaces that have connections, the only ones that can fail them.

Web, Home, about 6000 workspaces, one unrelated policy write: JavaScript work outside garbage collection went from 286 to 373 ms to 183 to 222 ms. The red dot went from 28 to 41 ms to 5 to 6 ms, and product training, the subscription, trial and marketing checks and the create report hook dropped by about 60 to 90 ms together.

Fixed Issues

$ #108486
PROPOSAL:

Tests

  1. Sign in with an account that is an admin of a workspace
  2. Verify the Workspaces tab shows a red dot when that workspace has an error (for example an employee invite error or a broken accounting connection), and that it clears when the error is resolved
  3. Go to Account > Wallet and verify the admin workspaces are listed in alphabetical order
  4. Open the Create menu and create a report, and verify the default workspace is picked as before
  5. Go to Account > Subscription and verify the plan and the trial or discount banner show as before
  • Verify that no errors appear in the JS console

Offline tests

  1. Go offline and verify the Workspaces tab red dot and the Wallet workspace list still show as they did online

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

@codecov

codecov Bot commented Dec 1, 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/hooks/usePoliciesWithCardFeedErrors.ts 100.00% <100.00%> (ø)
src/hooks/usePolicyIndicatorChecks.ts 100.00% <100.00%> (ø)
src/libs/Fullstory/utils.ts 89.53% <100.00%> (ø)
src/libs/PaymentUtils.ts 97.14% <ø> (ø)
src/libs/PolicyUtils/createPolicyCollectionMemo.ts 100.00% <100.00%> (ø)
src/libs/PolicyUtils/permissions.ts 99.15% <100.00%> (ø)
src/libs/PolicyUtils/xero.ts 61.53% <100.00%> (ø)
src/libs/isTeachersUnitePolicyID.ts 100.00% <100.00%> (ø)
src/libs/actions/Policy/Policy.ts 75.98% <0.00%> (ø)
src/libs/PolicyUtils/policy.ts 86.78% <88.46%> (-0.32%) ⬇️
... and 5528 files with indirect coverage changes

@mountiny
mountiny marked this pull request as ready for review December 1, 2026 15:59
@mountiny
mountiny requested review from a team as code owners December 1, 2026 15:59
@expensify-chore-bot
expensify-chore-bot Bot requested review from joekaufmanexpensify and mountiny and removed request for a team December 1, 2026 15:59
@expensify-chore-bot

Copy link
Copy Markdown

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

@expensify-chore-bot
expensify-chore-bot Bot removed the request for review from a team December 1, 2026 15:59
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-01T16:19:30.090737Z 9287ef7 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@samranahm

Copy link
Copy Markdown
Contributor

@MelvinBot Review.

@MelvinBot

Copy link
Copy Markdown
Contributor

Reviewed commit 9287ef7, including cache invalidation, cache keys, indicator checks, and readonly-array callers. No actionable findings.

Both targeted unit suites passed: 34 tests. Browser behavior and performance gains were not independently verified.


view run

@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: 9287ef7bad

ℹ️ 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 src/libs/PolicyUtils/policy.ts Outdated
Comment on lines +334 to +335
return policiesWhereReportCanBeCreatedMemo(policies, currentUserLogin ?? '', () =>
Object.values(policies).filter((policy): policy is Policy => canCreateReportOnPolicy(policy, currentUserLogin)),

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 Include environment readiness in the report-policy cache key

When restored policies are scanned before the asynchronous iOS environment check completes, this memo can retain an incorrect Teachers Unite eligibility result. canCreateReportOnPolicy() calls isTeachersUnitePolicyID(), whose environment changes asynchronously (src/libs/isTeachersUnitePolicyID.ts:7-14), so collection and login are not all of the scan's inputs. Once the environment resolves, the uncached predicate rejects the production Teachers Unite workspace, but this helper continues returning the old array to later callers and remounts until a policy write changes the collection. Consequently, the workspace picker at src/pages/DynamicNewReportWorkspaceSelectionPage.tsx:260 can keep offering an explicitly excluded workspace, particularly while offline. Include environment readiness/value in the cache key, or avoid caching this scan until it has resolved.

Useful? React with 👍 / 👎.

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.

@sosek108 I reproduced it with a unit test. Scanned a frozen collection before the environment resolved, then again after. The helper returned the old array including the "PROD Teachers Unite" workspace, while the uncached canCreateReportOnPolicy excluded it. Should we add the Teachers Unite policy ID, or the resolved environment, to the cache key?

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, thanks! Added the Teachers Unite policy ID to the cache key and a test that resolves the environment between two calls on the same snapshot.

@samranahm

samranahm commented Dec 1, 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 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 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 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
Android: mWeb Chrome
iOS: HybridApp
iOS: mWeb Safari
MacOS: Chrome / Safari
Kapture.2026-12-01.at.23.25.30.mp4

@samranahm

Copy link
Copy Markdown
Contributor

Failing Unit test is not related to this PR.

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

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

@sosek108 @fabioh8010 I'm going to approve this, but it feels like a bit of an anti-pattern right now. I would love us to create a follow-up issue to see how we could solve this more holistically within Onyx, because it feels like we should not be creating these cached maps for individual selectors manually.

@mountiny

mountiny commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

The checks are fixed on main, so this is just about merging main to the PR. It should be safe to merge it right now.

@mountiny
mountiny merged commit 73c04c8 into Expensify:main Dec 2, 2026
57 of 61 checks passed
@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

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

@OSBotify

OSBotify commented Dec 2, 2026

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.

@melvin-bot melvin-bot Bot added the Emergency label Dec 2, 2026
@melvin-bot

melvin-bot Bot commented Dec 2, 2026

Copy link
Copy Markdown

@mountiny looks like this was merged without a test passing. These checks had not passed on 1e8d578 when it was merged:

Please add a note explaining why this was done and remove the Emergency label if this is not an emergency.

@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

@mountiny mountiny removed the Emergency label Dec 2, 2026
@mountiny

mountiny commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

This is not an emergency. The tests are confirmed to be fixed on main.

@sosek108

sosek108 commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@sosek108 @fabioh8010 I'm going to approve this, but it feels like a bit of an anti-pattern right now. I would love us to create a follow-up issue to see how we could solve this more holistically within Onyx, because it feels like we should not be creating these cached maps for individual selectors manually.

We agree with you @mountiny. We are testing a global solution to this problem.

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