Skip to content

Batch collection member removals and coalesce cross-tab sync events - #820

Merged
mountiny merged 4 commits into
Expensify:mainfrom
callstack-internal:eliran/94839-batch-collection-removals
Aug 12, 2026
Merged

Batch collection member removals and coalesce cross-tab sync events#820
mountiny merged 4 commits into
Expensify:mainfrom
callstack-internal:eliran/94839-batch-collection-removals

Conversation

@elirangoshen

@elirangoshen elirangoshen commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Details

Fixes the two tabs with a heavy account crash both tabs

Root cause. A collection write (mergeCollection/multiSet/setCollection/partialSetCollection) persists its non-null members in one batched multiMerge/multiSet call (one cross-tab SYNC_ONYX event), but every null member went through remove(key) individually — one storage call and one cross-tab event per removed key, with no check that the key even exists. On a heavy account, OpenApp's transactionViolations_ mergeCollection contains ~2,000 null members on every boot (keys that were never stored, so the removals are pure no-ops). Each refresh therefore flooded the other tab with ~2,000 single-key events; each event is its own macrotask, so the receiving tab ran one keysChanged → one derived-value recompute (reportAttributes, reportTransactionsAndViolations) → one Onyx.set of an MB-sized derived value per event, saturating the main thread for ~1 minute and broadcasting ~4,000 derived-key events back to the first tab, which then performed ~4,000 IndexedDB reads of those MB-sized values. On Applause-sized accounts both tabs run out of memory and crash.

Fix (two layers):

  1. Sender — batch and skip removals. prepareKeyValuePairsForStorage no longer removes null keys as a side effect; it returns them as keysToRemove. All four collection-write paths now:
    • skip removals that are complete no-ops (key neither cached nor persisted);
    • fold real removals into the existing single keysChanged() batch (as undefined, with previous values snapshotted for the diff);
    • delete them from storage with one Storage.removeItems() call, which raises one cross-tab event for the whole batch.
  2. Receiver — coalesce event floods. InstanceSync (web) now buffers incoming SYNC_ONYX storage events and flushes once per tick (single multiGet + single dispatch). A tab still running an older bundle during a deploy emits one event per key; the flush timer is scheduled on the first event of the burst, so every event already in the task queue joins one batch instead of re-running the notification pipeline per key.

Measured on a heavy (Applause) account, two tabs, per boot: cross-tab events 1,971 → 41 (zero per-key transactionViolations_ events); derived-value writes in the other tab 3,891 → 8; no crash; pin/draft/read-unread/message sync, a 19.5 MB state import, and Clear cache and restart all work across tabs without refresh.

Related Issues

Expensify/App#94839

Linked E/App PR

Expensify/App#98121

Automated Tests

  • tests/unit/onyxTest.ts — new describe('batched collection member removals'):
    • mergeCollection deletes null members from cache and storage via one batched removeItems call (and never per-key removeItem);
    • member subscribers are notified about batched removals (undefined delivered);
    • removals of members that are neither cached nor persisted are skipped entirely;
    • setCollection deletes missing members via one batched removeItems call;
    • multiSet deletes null keys via one batched removeItems call.
  • tests/unit/storage/instanceSyncWebTest.ts — new coalescing tests:
    • a burst of storage events collapses into one multiGet and one dispatch (with key dedup);
    • separate bursts still dispatch separately.

Manual Tests

With this branch pinned in E/App (web dev build), on a heavy account:

  1. Open two tabs signed in to the same heavy account (e.g. Applause).
  2. Refresh both tabs and stay in Tab A. Wait ~30 seconds.
  3. Assert neither tab crashes and both stay responsive (before this fix: ~2,000 cross-tab events per boot, derived-value recompute storm, eventual crash of both tabs).
  4. In Tab A: pin/unpin a report, draft a message in a mid-list report, mark a report unread/read, and send a message. Assert each action syncs to Tab B without refreshing.
  5. In Tab A, import a really heavy Onyx state (Account > Troubleshoot > Import Onyx state). Assert Tab B adopts the imported state.
  6. Go to Account > Troubleshoot > Clear cache and restart. Assert Tab B is restored to the normal state as well.

Author Checklist

  • I linked the correct issue in the ### Related Issues section above
  • I linked the corresponding Expensify/App PR in the ### Linked E/App PR section above, and verified this change against it (E/App CI passed and manual testing completed)
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android / native
    • Android / Chrome
    • iOS / native
    • iOS / Safari
    • MacOS / Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that the left part of a conditional rendering a React component is a boolean and NOT a string, e.g. myBool && <MyComponent />.
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.js or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • If we are not using the full Onyx data that we loaded, I've added the proper selector in order to ensure the component only re-renders when the data it is using changes
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR author checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari
Screen.Recording.2026-08-10.at.11.23.39.mov
Screen.Recording.2026-08-10.at.11.29.33.mov

Collection writes fanned out null members as one remove() per key, raising one
cross-tab SYNC_ONYX event per removed key. On heavy accounts OpenApp nulls
~2k transactionViolations members on every boot, so each refresh flooded the
other tab with thousands of single-key events, each triggering a derived-value
recompute in its own macrotask until the tab ran out of memory.

- prepareKeyValuePairsForStorage now returns the null keys instead of removing
  them; mergeCollection/multiSet/setCollection/partialSetCollection drop no-op
  removals (neither cached nor persisted), fold real ones into the single
  keysChanged batch, and delete them with one Storage.removeItems call.
- InstanceSync (web) coalesces incoming SYNC_ONYX storage events into one
  multiGet + one dispatch per tick, so per-key senders (e.g. tabs on an older
  bundle during a deploy) can no longer flood the receiving tab.
@elirangoshen
elirangoshen marked this pull request as ready for review August 10, 2026 10:25
@elirangoshen
elirangoshen requested a review from a team as a code owner August 10, 2026 10:25
@melvin-bot
melvin-bot Bot requested review from deetergp and removed request for a team August 10, 2026 10:25

@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: 9ecff96823

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread lib/OnyxUtils.ts
… subscribers

Covers the partialSetCollection path for RAM-only collection members. getAllKeys()
returns the cache-augmented key set, so cached-only members are part of existingKeys
and their previous values are present in the keysChanged() diff snapshot.
@mountiny
mountiny self-requested a review August 10, 2026 15:15
@mountiny

Copy link
Copy Markdown
Contributor

@codex review
@MelvinBot review

@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: a37d06b5f9

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread lib/OnyxUtils.ts Outdated

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

Reviewed this locally on the branch. The core fix looks right and the win is real, so nothing here blocks it.

What I checked and found clean:

  • npx jest tests/unit passes (567 tests). The only failing suite is SQLiteProviderTest, which is a better-sqlite3 native binding problem in my environment and has nothing to do with this diff.
  • eslint is clean on all four changed files.
  • RAM-only keys are guarded on all four write paths.
  • SQLiteProvider.removeItems chunks by the SQLite variable limit, and the IndexedDB provider does one transaction, so batching a few thousand keys into one call is safe on every platform.
  • keysChanged() does deliver undefined to member subscribers for a batched removal.
  • The coalescing in InstanceSync uses a fixed one-tick window rather than a debounce, so a steady stream of events cannot delay a dispatch indefinitely.
  • Storage.removeItems is wired to raiseStorageSyncManyKeysEvent, so the batch really is one cross-tab event.

Two things I could not check locally: the two-tab measurements on a heavy account, and the native platforms.

I left two comments below. The first is a behaviour change I was able to reproduce and I think it is worth fixing. The second is smaller.

A few nits that need no action, just flagging:

  • multiSet did not get the same "skip removals that are no-ops" filter the other three paths got.
  • isProcessingCollectionUpdate is now dead. Nothing passes the second argument to remove() any more, so the if (isProcessingCollectionUpdate) branch in keyChanged() can no longer be reached.
  • setCollection and partialSetCollection notify with null for removed members, while mergeCollection and multiSet notify with undefined. Same result either way, but it would read better if all four matched.
  • A mergeCollection made up entirely of nulls that are all no-ops now notifies collection subscribers zero times, where main notified them once. That is where most of the win comes from, so this is intended, but it is worth calling out to the App reviewers in case anything treats a collection callback as a signal that data arrived.

Comment thread lib/OnyxUtils.ts Outdated
Comment thread lib/OnyxUtils.ts Outdated
…hed removal from retry

Addresses review feedback on Expensify#820:
- mergeCollection: cache.drop + Storage.removeItems now issue before the
  pre-warm multiGet await, so a concurrent write to a removed key during
  the pre-warm is no longer wiped out by a late drop.
- All four collection-write paths: a failed batched removal is logged
  instead of re-running the whole write via retryOperation (keysToRemove
  cannot be re-derived after the cache update).
- multiSet: skip removals of keys that are neither cached nor persisted.
- setCollection/partialSetCollection: notify removed members as undefined,
  matching mergeCollection/multiSet.
- Remove dead isProcessingCollectionUpdate plumbing.
@mountiny
mountiny requested a review from FitseTLT August 11, 2026 20:01
@mountiny

Copy link
Copy Markdown
Contributor

@FitseTLT please complete checklist and the testing. Thank you very much

@FitseTLT

FitseTLT commented Aug 11, 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
2026-08-12.01-48-14.mp4
2026-08-12.15-21-31.mp4
Android: mWeb Chrome
2026-08-12.02-28-05.mp4
iOS: HybridApp
iOS: mWeb Safari
iw.mp4
2026-08-12.02-21-51.mp4
MacOS: Chrome / Safari
2026-08-12.01-08-48.mp4
2026-08-12.14-57-22.mp4

@FitseTLT

Copy link
Copy Markdown
Contributor

Test is mostly looking good. But
I receive uninconsistent bug on clear cache which I am not sure it is from this pr
Android web - On the end of the vid below there was a lack of correct report name until I refreshed the pages

2026-08-12.02-28-05.mp4

Also regarding the heavy onyx state can you provide me with one @elirangoshen which you used to test it. Thx

@elirangoshen

Copy link
Copy Markdown
Contributor Author

Test is mostly looking good. But I receive uninconsistent bug on clear cache which I am not sure it is from this pr Android web - On the end of the vid below there was a lack of correct report name until I refreshed the pages

2026-08-12.02-28-05.mp4
Also regarding the heavy onyx state can you provide me with one @elirangoshen which you used to test it. Thx

I couldn't reproduce the report names issue also on main , but I did notice stale data - some reports that needs attention right after clear cache - happens on main as well so its not related to this pr.

this is onyx state you can use onyx-state (6).txt

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

Thanks for the unit tests added to cover this change

@mountiny
mountiny merged commit 8aef460 into Expensify:main Aug 12, 2026
12 of 17 checks passed
@os-botify

os-botify Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

🚀 Published to npm in 3.0.100 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants