Skip to content

Keep another tab's writes when Onyx.clear runs - #899

Open
elirangoshen wants to merge 2 commits into
Expensify:mainfrom
callstack-internal:eliran/3100-clear-keeps-other-tab-writes
Open

elirangoshen wants to merge 2 commits into
Expensify:mainfrom
callstack-internal:eliran/3100-clear-keeps-other-tab-writes

Conversation

@elirangoshen

@elirangoshen elirangoshen commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Details

#881 stopped Onyx.clear from overwriting writes made during the clear, but only writes made in the same tab. Production logs after #881 shipped show no change: on Nov 24–25, 59 of 88 sign-out clears that overlapped a new sign-in (20 accounts) still wiped the new session, all on web builds that have the fix.

The new session comes from another tab. When one tab signs out while another signs in, three things on web wipe it:

  • Storage write order. IndexedDB applies transactions in the order they are issued. The other tab's session write waits behind the clearing tab's removeItems, and then the defaults multiSet that clear issues afterwards overwrites it. The defaults are now written before removeItems, at the same time.
  • Writes from another tab are not tracked. A cross-tab write reaches this tab through InstanceSync, which updates the cache and notifies subscribers without going through PendingWrites, so the write listener from Keep values written while Onyx.clear is in progress #881 never sees it. InstanceSync now reports the changed keys as soon as the storage event arrives (before it reads their values), through a new PendingWrites.reportOtherInstanceWrite. clear leaves those keys out of the defaults it writes, and at the end reads them back from storage and puts the stored value (or the default, if the other tab removed it) in the cache and subscribers.
  • The writing tab's own sync read returns late. The tab that signs in also receives the sync event for the clear's writes. Its read is queued before its own session write, returns after it, and overwrites the newer session in memory. A key this tab writes while InstanceSync is reading it is now dropped from that result and read again.

Keys that no tab writes during the clear behave as before. Native has no InstanceSync, so only the write-order change applies there.

Related Issues

Expensify/App#104458

Linked E/App PR

Expensify/App#108178

Automated Tests

Added tests/unit/onyxClearCrossTabWriteTest.ts (Another tab writes while Onyx.clear is in progress). It holds Storage.removeItems and fires the keepInstancesSync callbacks the way another tab's write arrives:

  • should keep a session another tab saved while this tab was clearing
  • should read back a session another tab saved even when its value has not reached this tab yet: only the key is announced, and the value is read from storage.
  • should read back a collection member another tab saved while this tab was clearing: the key is announced late, while the defaults are being written.
  • should end with the default session when the other tab was signing out too

Added to tests/unit/storage/instanceSyncWebTest.ts (storage event parsing):

  • reports the changed keys as soon as the event arrives, before reading their values
  • reads a key again when this tab writes it while its value is being read

The full unit suite passes (795 tests).

Manual Tests

Two-tab browser test of this fix (Onyx bundled for web with IndexedDB and InstanceSync), compared with 3.0.149 from production:

  1. Open two tabs. Both have a session and some data saved.
  2. Tab A runs Onyx.clear (sign-out). Tab B saves a new session 5, 80, 300, 480 and 700 ms after the clear starts.
  3. Verify the old session and data are removed, and the new session is kept in both tabs and in IndexedDB.
  4. Repeat with tab A saving the session itself, both tabs signing out, and nothing saved during the clear. Verify each ends as expected.

On 3.0.149 the new session was wiped when it was saved 57–355 ms into the clear. With the fix every case was correct.

In the App, through the linked E/App PR:

  1. On web, sign in as account A in two tabs.
  2. In one tab, open an OldDot transition link for account B ("Switch to New Expensify" in OldDot while signed in as B) and click Switch accounts on the prompt. A Supportal link for B skips the prompt.
  3. Verify both tabs end up on account B (no infinite skeletons), and the console has no [SignInRedirect] Sign-out clear finished after a new sign-in started line with isNewSessionWiped: true.
  4. Sign out. Verify both tabs go to the sign-in page and account A's and B's data is gone.

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 1-tab1-account-a 2-tab1-switch-accounts-prompt 4-tab1-after-sign-out

When one tab signs out while another signs in, the sign-out clear wiped the
new session for every tab. Three things caused it on web:

- Storage applies writes in order, so the other tab's write waited behind
  the clear's removal and was then overwritten by the defaults the clear
  wrote afterwards. The defaults are now written before the removal.
- Writes from another tab skip the write tracking added for writes made
  during a clear. InstanceSync now reports the changed keys as soon as the
  storage event arrives, and clear leaves those keys in storage and reads
  them back at the end.
- The writing tab's own sync read, queued before its write, could return
  after it and overwrite the newer value in memory. A key this tab writes
  while it is being read is now read again.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 27, 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-11-27T12:15:47.939708Z cbb1c73 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.

@expensify-chore-bot
expensify-chore-bot Bot requested review from grgia and removed request for a team November 27, 2026 12:11

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

ℹ️ 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/Onyx.ts
.then(() => {
// Keys reported while the storage step ran are read back too
keysWrittenByOtherInstance = collectKeysWrittenByOtherInstance();
return keysWrittenByOtherInstance.size > 0 ? Storage.multiGet([...keysWrittenByOtherInstance]) : [];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Guard the final readback against newer local writes

When another tab has announced a key and a local Onyx.set() runs after this final multiGet is queued but before it resolves, the returned snapshot can predate that local write. The snapshot is still applied unconditionally, and wasWrittenOnlyByThisInstance remains false for the key, so cache and subscribers revert to the older value even though storage contains the newer local value. This can roll back a successful local sign-in. Track writes during this read and skip or re-read affected keys, as the new InstanceSync reader does.

Useful? React with 👍 / 👎.

Comment thread lib/Onyx.ts Outdated
.then((pairsWrittenByOtherInstance) => {
// Storage holds the other tab's values, so the cache and subscribers take them instead of the reset values.
for (const [key, storedValue] of pairsWrittenByOtherInstance) {
const value = storedValue ?? OnyxUtils.getNullFreeDefaultKeyState(key) ?? undefined;

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 Normalize storage values before restoring them to the cache

For simultaneous clears with an initialKeyStates value such as {errors: null, loading: false}, the other tab writes that raw default using Storage.multiSet, and IDBKeyValProvider.multiGet returns it without normalization. This branch then caches and notifies {errors: null, loading: false} instead of {loading: false}, potentially undoing normalization already performed by the regular InstanceSync callback and violating the null-free cache assumption used by removeNestedNullValues. Apply the same normalization as the regular sync callback before caching and notifying these values.

Useful? React with 👍 / 👎.

Comment thread lib/Onyx.ts Outdated
Comment on lines +551 to +555
const resetDefaultsPromise = Storage.multiSet(defaultKeyValuePairs.filter(([key]) => !keysWrittenByOtherInstance.has(key)));

// Remove only the items that we want cleared from storage
for (const key of keysToBeClearedFromStorage) cache.drop(key);
return Storage.removeItems(keysToBeClearedFromStorage)
return Promise.all([resetDefaultsPromise, Storage.removeItems(keysToBeClearedFromStorage)])

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 quota-safe clearing when writing defaults first

When IndexedDB is near its quota and restoring a missing or larger default requires additional space, this multiSet now runs before deletion can reclaim that space. Capacity errors propagate through the storage layer without retry here, so Promise.all rejects and skips the clear's subscriber notifications even though removeItems can subsequently succeed. The previous delete-then-default sequence succeeds in this scenario. Preserve a quota-safe completion path so clearing a full store does not reject and leave subscribers showing the pre-clear state.

Useful? React with 👍 / 👎.

- Ignore a read-back value for a key this tab wrote during the read, since the local write is newer
- Remove nested nulls from read-back values, as regular cross-tab sync does
- Retry the defaults write after the removal when it fails, so a full store still clears
- Shorten comments
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.

1 participant