Skip to content

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

Open
elirangoshen wants to merge 3 commits into
Expensify:mainfrom
callstack-internal:eliran/94839-batch-collection-removals
Open

Batch collection member removals and coalesce cross-tab sync events#820
elirangoshen wants to merge 3 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
Comment on lines +1741 to +1743
for (const key of keysToRemove) {
removedPreviousValues[key] = cache.get(key);
cache.drop(key);

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 Preserve removal keys when retrying batched deletes

When Storage.removeItems(keysToRemove) rejects with a retryable error, retryOperation() re-enters this method, but this loop has already dropped the removed members from the cache. On the retry, keysToRemove is recomputed from cache.get(key) !== undefined || persistedKeys.has(key), and getAllKeys() normally returns the cache-backed key set, so the failed removal is filtered out and never retried; the stale member remains in persistent storage and can reappear after reload. Preserve the original removal list across retries, or avoid deriving retry deletions from the cache after it has been mutated.

Useful? React with 👍 / 👎.

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.

2 participants