Skip to content

Add Sentry monitoring for OnyxDerived recompute loops - #98133

Open
TMisiukiewicz wants to merge 8 commits into
Expensify:mainfrom
callstack-internal:feature/onyx-derived-loop-monitoring
Open

Add Sentry monitoring for OnyxDerived recompute loops#98133
TMisiukiewicz wants to merge 8 commits into
Expensify:mainfrom
callstack-internal:feature/onyx-derived-loop-monitoring

Conversation

@TMisiukiewicz

@TMisiukiewicz TMisiukiewicz commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Explanation of Change

Adds a rate tripwire that detects runaway Onyx derived-value recompute loops and reports them once per derived key per session.

  • New detectOnyxDerivedLoop (src/libs/telemetry/detectOnyxDerivedLoop.ts): per-derived-key rolling 10s window (WINDOW_MS) of recompute timestamps; trips at 50 recomputes (RECOMPUTE_THRESHOLD, ~5/s sustained). On trip it reports [OnyxDerived] recompute loop detected for <key> to Sentry via captureMessage with fingerprint: ['onyx-derived-loop', <key>] plus extra.dependencyCounts (a per-dependency count showing which dependency drives the churn), and mirrors the same message to the server log via Log.alert (no stack trace) so it lands in VictoriaLogs next to the surrounding [OnyxDerived] lines. Latched once per key per session; window cleared on trip so a tripped key retains nothing.
  • Wired as one call in flushRecompute, right after the existing triggeredKeys set is built — so it counts flushes, not per-dependency callbacks, and costs one Map lookup + one small push in steady state.
  • Recomputes are ignored while the app-startup span is open (getSpan(SPAN_APP_STARTUP)), since dependencies legitimately hydrate in bursts during startup.
  • captureMessage rather than a span deliberately: startSpan early-returns unless AppState === active, so span-based detection is blind exactly when a backgrounded client is spinning.

Fixed Issues

$ #97711
PROPOSAL:

Tests

  1. Open console
  2. Enable all levels of logs
  3. Paste in the console the following code:
const k = 'cards_TEST_LOOP';
for (let i = 0; i < 60; i++) { await Onyx.merge(k, {[`card${i}`]: {cardID: i}}); }
await Onyx.set(k, null);
  1. Verify [alrt] [OnyxDerived] recompute loop detected for... showed up in the console
  • Verify that no errors appear in the JS console

Offline tests

N/A

QA Steps

// TODO: These must be filled out, or the issue title must include "[No QA]."

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 followed proper code patterns (see Reviewing the code)
    • 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 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

Comment thread src/libs/telemetry/detectOnyxDerivedLoop.ts
Comment thread src/libs/telemetry/detectOnyxDerivedLoop.ts
@TMisiukiewicz
TMisiukiewicz marked this pull request as ready for review August 10, 2026 13:17
@TMisiukiewicz
TMisiukiewicz requested review from a team and tgolen as code owners August 10, 2026 13:17
@melvin-bot
melvin-bot Bot requested review from abzokhattab, garrettmknight and mountiny and removed request for a team August 10, 2026 13:17
@melvin-bot

melvin-bot Bot commented Aug 10, 2026

Copy link
Copy Markdown

@abzokhattab @mountiny One of you needs to 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 the request for review from a team August 10, 2026 13:17
@abzokhattab

Copy link
Copy Markdown
Contributor

reviewing 👀

Comment thread src/libs/telemetry/detectOnyxDerivedLoop.ts Outdated
Comment thread src/libs/telemetry/detectOnyxDerivedLoop.ts Outdated
Comment thread src/libs/telemetry/detectOnyxDerivedLoop.ts
@mountiny

Copy link
Copy Markdown
Contributor

@codex @MelvinBot review

@MelvinBot

Copy link
Copy Markdown
Contributor

🤖 Code review — this is a clean, well-scoped telemetry addition. The core logic is correct, it follows the existing src/libs/telemetry conventions (bootsplashTelemetry.ts uses the same Sentry.captureMessage + fingerprint shape), and the detector is read-only so it can't alter derived-value behavior. No blocking issues. A couple of things worth noting:

1. False-positive tuning — worth watching on rollout (not a blocker). The threshold is 50 recomputes / 10s (5/s sustained). Because flushRecompute coalesces a synchronous burst into a single microtask flush, tripping this requires ~50 separate async batches in 10s, which is genuinely abnormal — so the risk is low. But a post-startup burst (reconnect resync, a busy chat receiving many distinct Pusher batches, or opening a very large report) could conceivably trip it for a key like report_attributes. The startup-span guard only covers the initial hydrate, not these later bursts. Since it's warning-level and latched once per key per session, the blast radius of a false positive is tiny (one Sentry warning + one log line), so this is fine to ship and tune from real data — just keep an eye on the first production window and adjust RECOMPUTE_THRESHOLD if it's noisy.

2. Nit: at detectOnyxDerivedLoop.ts:57, the ?? now fallback in state.window.at(0)?.at ?? now is dead — the push on the line above guarantees window.length >= 1. Harmless; optional to simplify.

What I checked
  • Correctness of the rolling window — half-open pruning (at <= now - WINDOW_MS evicts entries exactly at the boundary), trips at exactly 50 within any 10s sliding window, then clears the window and latches hasReported. All correct.
  • Cost in steady state — one Map.get + early return once latched; otherwise one Date.now(), one push, and amortized shifts. Matches the PR's claim.
  • Report payload is actionabledependencyCounts naming the churning dependency is the most useful part for triage.
  • ConventionscaptureMessage (not a span) with the documented "spans drop while backgrounded" rationale is sound; import * as Sentry from '@sentry/react-native' and Log.alert(msg, params, false) match existing usage.
  • Tests cover the three meaningful cases: trip + culprit attribution, startup-span suppression, and window-spread negative. resetOnyxDerivedLoopDetection is test-only and used only in the spec.
  • I could not execute jest/tsc in this environment (sandbox denied the run), so I verified the test logic by reading rather than running it — worth confirming CI is green before merge.

Overall LGTM pending green CI. 👍

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

ℹ️ 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/telemetry/detectOnyxDerivedLoop.ts Outdated
tgolen
tgolen previously approved these changes Aug 10, 2026

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

Very cool feature!

@garrettmknight
garrettmknight removed their request for review August 10, 2026 15:19
@abzokhattab

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 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
    • 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 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
Screen.Recording.2026-08-10.at.19.10.35.mov

@abzokhattab

Copy link
Copy Markdown
Contributor

i found the following bug while testing:

  1. Open the app on web and sign in
  2. Open the console and enable all log levels.
  3. Paste the PR's snippet to trip the detector:
const k = 'cards_TEST_LOOP';
for (let i = 0; i < 60; i++) { await Onyx.merge(k, {[`card${i}`]: {cardID: i}}); }
await Onyx.set(k, null);
  1. Confirm [alrt] [OnyxDerived] recompute loop detected for ... appears.
  2. Sign out, then sign back in. Do not reload the page .. a reload resets JS memory and hides the bug.
  3. Paste the same snippet again.

Expected: the alert appears again. Actual: nothing is logged or sent to Sentry, for the rest of that session.

Step 5 also reproduces via Settings → Troubleshoot → Clear cache and restart

Screen.Recording.2026-08-10.at.19.15.56.mov

@github-actions
github-actions Bot requested a review from luacmartins August 11, 2026 06:43
@github-actions

Copy link
Copy Markdown
Contributor

This PR adds a new Onyx.connectWithoutView call, so I've requested a review from the Onyx performance reviewers (@tgolen, @mountiny, @luacmartins) — a review from any one of them is enough. Please add a link in your PR description to the Slack discussion where the @frontend-performance team approved using connectWithoutView here.

@TMisiukiewicz

Copy link
Copy Markdown
Contributor Author

@abzokhattab mind checking again?

@abzokhattab abzokhattab 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 LGTM 🚀

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

Left a few comments. In general, can we de-AI the comments please?

Comment thread contributingGuides/philosophies/ONYX-DATA-MANAGEMENT.md Outdated
Comment thread contributingGuides/philosophies/ONYX-DATA-MANAGEMENT.md Outdated
Comment thread src/libs/telemetry/detectOnyxDerivedLoop.ts Outdated
Comment thread src/libs/telemetry/detectOnyxDerivedLoop.ts Outdated
Comment thread src/libs/telemetry/detectOnyxDerivedLoop.ts Outdated
Comment thread src/libs/telemetry/detectOnyxDerivedLoop.ts Outdated
@TMisiukiewicz

Copy link
Copy Markdown
Contributor Author

@luacmartins mind checking again?

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

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.

6 participants