Skip to content

fix: back off GetMissingOnyxMessages once it stops advancing the client#94974

Open
elirangoshen wants to merge 2 commits into
Expensify:mainfrom
callstack-internal:eliran/92541-gmom-convergence-guard
Open

fix: back off GetMissingOnyxMessages once it stops advancing the client#94974
elirangoshen wants to merge 2 commits into
Expensify:mainfrom
callstack-internal:eliran/92541-gmom-convergence-guard

Conversation

@elirangoshen

@elirangoshen elirangoshen commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

Explanation of Change

When the app detects a gap in server update IDs it fetches the missing ones via GetMissingOnyxMessages (GMOM). A prior fix (#93948) coalesced concurrent GMOM requests — the "is one already running right now" guard in OnyxUpdateManager's gap branch.

That guard only catches fetches that overlap in time. Production telemetry shows the loop survives across sequential fetches: a request finishes, finalizeUpdatesAndResumeQueue clears the in-flight marker, the server's next push still reports a gap, and because nothing is running at that instant the guard lets a new GMOM through. When the gap never closes — lastUpdateIDAppliedToClient does not advance — the app fires GMOM ~once a second while the screen sits frozen (a real trace fired 25 requests in ~8s under a single 14.8s route change).

This adds a convergence guard to the same gap branch:

  • It counts consecutive gap fetches fired against an unchanged client update ID (consecutiveStalledGapFetches). When a fetch advances the client, lastUpdateIDFromClient differs on the next entry and the counter resets.
  • Once the count reaches CONST.MAX_CONSECUTIVE_STALLED_GAP_FETCHES (3), it resumes the SequentialQueue without firing another GMOM and logs an alert. The counter stays tripped until the client advances via any other path (a ReconnectApp on app foreground / network reconnect, or a contiguous Pusher update), which self-heals — so no queue freeze and no dropped catch-up.

The change is scoped to the gap branch decision; the demand/pending/reconnect branches are untouched.

Fixed Issues

$ #92541
PROPOSAL:

Tests

  1. Check out this branch and run npm run test -- tests/unit/OnyxUpdateManagerTest.ts.
  2. Verify all tests pass, including the new regression test should stop re-fetching missing updates once GetMissingOnyxMessages stops advancing the client, which:
    • simulates a server that keeps reporting a gap it never closes (fetch resolves but the client never advances),
    • asserts GMOM stops firing after MAX_CONSECUTIVE_STALLED_GAP_FETCHES cycles,
    • asserts GMOM fetching resumes once the client's applied update ID advances.
  3. Sign in with a high-traffic account, trigger a burst of incoming updates (e.g. open a busy chat while another client posts), and verify the app stays responsive — no ~1/s GMOM loop and no dead-click freeze — and data stays in sync.
  4. Verify that no errors appear in the JS console.
  • Verify that no errors appear in the JS console

Offline tests

  1. Go offline, then come back online with pending updates on the server.
  2. Verify the client fetches missing updates in order, applies them, and resumes the SequentialQueue, with no repeating GMOM loop and no stuck/paused queue.

QA Steps

  1. Sign in with a high-traffic account.
  2. Generate a burst of incoming updates (e.g. have another user post rapidly in a shared chat, or reconnect after being offline).
  3. Verify the app stays responsive during and after the burst, with no freezes or dead clicks.
  4. Verify reports and chats stay in sync with the server after the burst settles.
  5. Verify that no errors appear in the JS console.
  • 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 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 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 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)
  • 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 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.
  • 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
Screen.Recording.2026-07-01.at.14.02.47.mov

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@codecov

codecov Bot commented Jun 30, 2026

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Coverage Δ
src/CONST/index.ts 93.33% <ø> (ø)
src/libs/actions/OnyxUpdateManager/index.ts 84.37% <100.00%> (+2.23%) ⬆️
... and 9 files with indirect coverage changes

@elirangoshen elirangoshen marked this pull request as ready for review July 1, 2026 12:07
@elirangoshen elirangoshen requested review from a team as code owners July 1, 2026 12:07
@melvin-bot melvin-bot Bot requested review from mkhutornyi and trjExpensify July 1, 2026 12:07
@melvin-bot

melvin-bot Bot commented Jul 1, 2026

Copy link
Copy Markdown

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

@melvin-bot melvin-bot Bot removed request for a team July 1, 2026 12:07
@elirangoshen

Copy link
Copy Markdown
Contributor Author

that CLA seems error flaky check, can you run it again ?

@mkhutornyi

mkhutornyi commented Jul 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 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
Android: mWeb Chrome
iOS: HybridApp
iOS: mWeb Safari
MacOS: Chrome / Safari

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

ℹ️ 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 on lines +209 to +210
setMissingOnyxUpdatesQueryPromise(Promise.resolve());
return true;

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 the deferred update when backing off

When this backoff branch runs after enqueueing the gap update, returning true attaches finalizeUpdatesAndResumeQueue, which calls clearDeferredOnyxUpdates() and clears the just-deferred server update without fetching or applying it. In the scenario where the guard trips for update 3 while the client is at 1, and update 2 later arrives contiguously and advances the client, update 3 has already been discarded, so the client remains stale until an unrelated later update or reconnect happens.

Useful? React with 👍 / 👎.

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.

This is intentional — the deferred update is dropped here on purpose, and it's not permanently lost. The guard only trips after the client has been stuck for 3 consecutive stalled fetches, i.e. the gap isn't closing. Once the client advances again (via reconnect or the next gap push), the counter resets and the following GetMissingOnyxMessages re-fetches the whole range, including this update — so it self-heals.

Preserving it here would actually be worse: a kept deferred update hits the areDeferredUpdatesQueued → return false gate, and contiguous updates don't drain the deferred queue, so it could stall until a reconnect instead of self-healing. The bounded staleness is the intended trade-off for breaking the request loop.

@trjExpensify

Copy link
Copy Markdown
Contributor

PR doesn’t need product input as a performance PR. Unassigning and unsubscribing myself.

@trjExpensify trjExpensify removed their request for review July 1, 2026 15:36
# Conflicts:
#	tests/unit/OnyxUpdateManagerTest.ts
@mkhutornyi

Copy link
Copy Markdown
Contributor

Please fix lint

@adhorodyski

Copy link
Copy Markdown
Contributor

I think this also needs updates to the SEQUENTIAL_QUEUE.md doc, let me draft some proposed fixes.

@adhorodyski

Copy link
Copy Markdown
Contributor

hm after the guard trips, the user stops getting data until they reload (if you're on an active tab, refocus guards to not work and sync you back). Why not fire one full ReconnectApp, like the branch above does? I see this PR does not really hit on the root cause that the app never fully syncs but just stops the bleeding, that does not seem like a proper fix we should aim at.

@mkhutornyi

Copy link
Copy Markdown
Contributor

@MelvinBot review

@MelvinBot

Copy link
Copy Markdown
Contributor

Review

Verdict: The approach is sound and well-scoped — it correctly closes the sequential-fetch gap that the concurrency guard in #93948 left open. Logic traces cleanly, the self-heal is real, and the backoff resumes the queue. No blocking bugs found. A couple of things worth confirming before merge.

Why the logic holds up
  • The convergence counter only increments when a fetch is actually about to fire — it sits after the concurrency/deferred guard at OnyxUpdateManager/index.ts:196-216, so concurrent pushes (handled by getMissingOnyxUpdatesQueryPromise()) don't inflate it.
  • Self-heal is genuine and does not depend on resetDeferralLogicVariables (that reset is test-only — its only callers are the export and the test beforeEach). Recovery works purely through lastUpdateIDFromClient !== lastGapFetchClientUpdateID: once a ReconnectApp or a contiguous Pusher update advances lastUpdateIDAppliedToClient, the next gap sees a different client ID, resets the counter to 0, and GMOM fires again. The regression test exercises exactly this.
  • Backoff resumes the SequentialQueue: setMissingOnyxUpdatesQueryPromise(Promise.resolve())shouldFinalizeAndResumefinalizeUpdatesAndResumeQueueclearDeferredOnyxUpdates(), which defaults shouldUnpauseSequentialQueue to true. So the UI unfreezes as intended.
  • No false trips during healthy catch-up: any fetch that advances the client changes lastUpdateIDFromClient, resetting the counter. Only 3 zero-progress fetches in a row trip it.
  • No permanent data loss: the deferred update discarded on backoff can't be applied anyway (it's behind an unclosed gap), and its range is re-fetched after the next reconnect/contiguous update.

Two things to confirm:

  1. Stale-but-responsive tradeoff. Once tripped, a client stuck on a genuine persistent gap stops pulling new data via GMOM until a foreground/network ReconnectApp (or a lucky contiguous Pusher update) advances it. That's the right call over a frozen UI, but it means the Log.alert at index.ts:208 is the only signal these clients are silently behind — worth confirming that alert is actually monitored so recurring stalls get visibility rather than being masked.

  2. Scope of the guard. The fix is deliberately limited to the gap branch; the shouldFetchPendingUpdates branch has no equivalent guard. If a stalled pendingLastUpdateID can drive the same ~1/s loop, it'd be unprotected. Fine to leave out of this PR, but confirming that branch can't stall the same way (or noting it as follow-up) would close the loop.

Nit: The new regression test asserts GMOM call counts but not that the queue actually unpauses on backoff (SequentialQueue.unpause is already imported in the test). A one-line assertion there would lock in the "no freeze" guarantee, which is the whole point of the fix.

I couldn't run tests/unit/OnyxUpdateManagerTest.ts in this environment (execution is gated here) — CI will. Everything above is from static analysis.

@adhorodyski

Copy link
Copy Markdown
Contributor

Honestly I don't believe that Melvin is right here, this does not feel right to me as we're working around the problem and not on it.

Backing off silently leaves users stale: after the guard trips, the only recovery is a ReconnectApp from refocus or a network change. The storming traces can be always-on desktop tabs where that may not happen. A "gap push" doesn't reset the counter, since it doesn't advance lastUpdateIDFromClient.

Here's what I'd do for this as per my comment above:

  1. Escalate instead of going silent. When the counter trips, fire one ReconnectApp. Same recovery idiom as the !lastUpdateIDFromClient branch above. The reconnect should advance the client to the server head, which closes the gap. There is no loop risk with the queue's in-flight dedup that now covers reconnect stacking I shipped earlier).
  2. Make sure the Log.alert is monitored. Post-merge it's the only signal that clients are stuck behind a gap.
  3. Investigate this on the BE. The real question to me is why the server keeps reporting a gap that GMOM can't close: in stalled traces the GMOM responses average ~1.2KB, min 276 bytes (according to claude via sentry mcp), these are near-empty answers. Likely either the updates were pruned from the server's log or a range mismatch between what the client asks for and what the server serves. No client patch fixes that imo.

@adhorodyski

Copy link
Copy Markdown
Contributor

Spoke to Eliran, I will take over this PR.

@adhorodyski

Copy link
Copy Markdown
Contributor

fyi I will recreate this PR so I can own it end to end with the description.

@adhorodyski

Copy link
Copy Markdown
Contributor

Continuing this here #95477

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