Skip to content

feat(android): Report JS thread hangs as errors on Android - #7111

Open
alwx wants to merge 8 commits into
mainfrom
alwx/feature/6985
Open

alwx wants to merge 8 commits into
mainfrom
alwx/feature/6985

Conversation

@alwx

@alwx alwx commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

📢 Type of change

  • Bugfix
  • New feature
  • Enhancement
  • Refactoring

📜 Description

enableJsHangTracking now also works on Android. A native thread pings the JS thread with runOnJSQueueThread every 100 ms. When the JS thread does not answer within jsHangTimeoutInterval, the tracker samples it with the Hermes sampling profiler for 300 ms and captures a handled JS Thread Hang event with the JS stack and the bundle Debug ID, the same as on iOS. The JS hang flame graph stays iOS only.

  • RNSentryHermesSampler holds the Hermes sampler for profiling and for JS hang samples under one lock, so a profile cannot start in the middle of a sample.
  • While a profile runs, a hang does not toggle the sampler. It dumps the running profile and takes the newest JS stack, and stopProfiling merges these dumps back into the profile, the same as iOS (RNSentryHermesSampler.mm).
  • invalidate() stops the tracker before anything else. On the New Architecture, the before destroy listener from fix(android): Stop the Hermes sampler before the JS thread exits on reload #7157 runs invalidate() while the JS thread still runs, so the tracker and its sampler are off before the JS thread exits. The tracker does not start again after that cleanup.

💡 Motivation and Context

Closes #6985, follow-up to #6964. The Android tracker was removed from #6964 because a reload could crash in the Hermes sampler thread (meta/hermes#1853, #5441). Hermes fixed the cause in meta/hermes@2751477d3c (the sampler calls pthread_kill on a JS thread that already exited), but the fix is not in the Hermes release that React Native 0.88 and 0.89 ship, so the SDK turns the sampler off before the JS thread exits. On the New Architecture, invalidate() alone runs too late (found by @antonis); #7157 adds the before destroy cleanup.

💚 How did you test it?

  • Robolectric tests for the tracker (fake JS thread and sampler), the shared sampler (fake Hermes profiler, including dumps during a profile and the merge), and the module start, stop, and invalidate paths. testDebugUnitTest passes (189 tests, 15 of them new).
  • yarn build, yarn test, yarn lint, and yarn circularDepCheck pass.
  • Android 16 emulator, sample release build with profilesSampleRate: 1.0, nested JS hang button:
    • Hang inside a running profile, with the stack down to onPress: event. The profile of that run kept the hang samples (1081 JS samples over 17.6 s, valid stack ids).
    • Hang outside a profile, own 300 ms sample: event.
    • Before the profile fix, a hang inside the app start profile had no stack (stackless event vs with stack, from @antonis).
  • Reload loop with fix(android): Stop the Hermes sampler before the JS thread exits on reload #7157: release arm64 build, profilesSampleRate: 1.0, JS hang tracking on, reactHost.reload() from adb every 1.5 s. 600 reloads, no abort on hermes-sampling (@antonis saw 8 in 63 reloads on the previous version). One run aborted on mqt_v_js with the sample's Reanimated installTurboModule assertion during the bundle start, which is not related to the sampler.

📝 Checklist

  • I added tests to verify changes.
  • No new PII added or SDK only sends newly added PII if sendDefaultPII is enabled.
  • I updated the docs if needed.
  • I updated the wizard if needed.
  • All tests passing.
  • Public API changes reviewed by another Mobile SDK team member or implemented according to the develop docs spec.
  • No breaking changes.

🔮 Next steps

  • Port the JS hang flame graph to Android.

alwx added a commit that referenced this pull request Nov 25, 2026
Replace the PR link placeholder in the Android JS hang tracking entry with #7111.
@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Semver Impact of This PR

⚪ None (no version bump detected)

📋 Changelog Preview

This is how your changes will appear in the changelog.
Entries from this PR are highlighted with a left border (blockquote style).


  • feat(android): Report JS thread hangs as errors on Android by alwx in #7111
  • fix(android): Stop the Hermes sampler before the JS thread exits on reload by alwx in #7157
  • chore(deps): bump cross-spawn from 7.0.6 to 7.1.2 by antonis and claude with dependabot in #7156
  • fix(core): Keep Hermes InternalBytecode.js frames out of app by antonis and claude in #7138
  • ci: Add the PR classifiers workflow by christophaigner with sentry-junior in #7142
  • chore(deps): bump getsentry/github-workflows/danger from bce11fe6eaa86dbb9d360ab45a96e659828877f0 to edc87d6f133ac6204e22dee5123167a5eff3ed79 by dependabot in #7137
  • chore(deps): bump ruby/setup-ruby from 1.342.0 to 1.345.0 by dependabot in #7136
  • chore(deps): bump getsentry/craft from 3.13.0 to 3.14.1 by dependabot in #7135
  • chore(deps): bump getsentry/craft/.github/workflows/changelog-preview.yml from 3.13.0 to 3.14.1 by dependabot in #7134
  • chore(deps): bump the codeql-action group with 3 updates by dependabot in #7133
  • chore(deps): update Sentry Android Gradle Plugin to v6.28.0 by github-actions in #7129
  • feat(tracing): Report long tasks as ui.long-task spans in transactions by alwx in #7110
  • chore(deps): update Maestro to v2.13.0 by github-actions in #7126
  • chore(tooling): Make the verify-pr gate stop at the first no by antonis and claude with sentry-junior in #7125
  • chore(tooling): Add review checks and a gate-only mode to verify-pr by antonis and claude in #7121
  • chore(tooling): Fold the open-PR run findings into verify-pr by antonis and claude in #7115

🤖 This preview updates automatically when you update the PR.

@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor
Fails
🚫 Pull request is not ready for merge, please add the "ready-to-merge" label to the pull request
Messages
📖 Do not forget to update Sentry-docs with your feature once the pull request gets approved.

Generated by 🚫 dangerJS against 298b7ca

alwx added a commit that referenced this pull request Nov 26, 2026
Review feedback on #7111. sample() cleared its enabled flag before it called disable(), so when disable() threw, the finally block skipped the best-effort disable and the global Hermes sampler could stay on. A JS hang sample does not set isProfiling, so invalidate() would not turn it off later either. The flag is now cleared only after disable() returns.

A new test uses a fake profiler whose first disable() throws and checks that the sampler tries to disable it again.
@alwx
alwx marked this pull request as ready for review November 26, 2026 10:48
Comment thread CHANGELOG.md Resolved

@antonis antonis 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 couple of comments. Let's also update the PR description and add Sentry test links.

@linear-code

linear-code Bot commented Nov 26, 2026

Copy link
Copy Markdown

RN-843

alwx added a commit that referenced this pull request Nov 30, 2026
Replace the PR link placeholder in the Android JS hang tracking entry with #7111.
@alwx
alwx force-pushed the alwx/feature/6985 branch from 84303b8 to b0582dc Compare November 30, 2026 10:12
alwx added a commit that referenced this pull request Nov 30, 2026
Review feedback on #7111. sample() cleared its enabled flag before it called disable(), so when disable() threw, the finally block skipped the best-effort disable and the global Hermes sampler could stay on. A JS hang sample does not set isProfiling, so invalidate() would not turn it off later either. The flag is now cleared only after disable() returns.

A new test uses a fake profiler whose first disable() throws and checks that the sampler tries to disable it again.
alwx added a commit that referenced this pull request Nov 30, 2026
Review feedback on #7111. While a Hermes profile ran, sample() returned null, so the JS hang event had no stack and grouped into its own issue. With profiling on, a hang soon after launch often lands inside the app start profile.

Android now does what iOS does. While a profile runs, sample() does not turn the sampler off. It dumps the running profile, keeps the dump, and returns it as a profile trace, so the tracker takes the newest JS stack of the dump. Hermes clears its samples on every dump, so stopProfiling() merges the kept dumps with the final one in time order and moves the stack frame ids of each dump past the ids of the dumps before it. When a dump cannot be merged, the profile keeps the final dump. Starting or discarding a profile drops the kept dumps.

On an Android emulator with profilesSampleRate 1.0, a hang inside the profile gave a JS Thread Hang event with the stack down to onPress, and the profile kept the hang samples.
alwx added a commit that referenced this pull request Nov 30, 2026
Review feedback on #7111: keep only the first line of the entry.
alwx added a commit that referenced this pull request Nov 30, 2026
8.37.0 was released while #7111 was open, so the rebase left the entry in the released section.
@alwx
alwx requested a review from antonis November 30, 2026 10:38
@antonis antonis added the ready-to-merge Triggers the full CI test suite label Nov 30, 2026
@sentry

sentry Bot commented Nov 30, 2026

Copy link
Copy Markdown

📲 Install Builds

Android

🔗 App Name App ID Version Configuration
Sentry RN io.sentry.reactnative.sample 8.37.0 (117) Release

⚙️ sentry-react-native Build Distribution Settings

@antonis

antonis commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

Thanks for the profiling fix. I verified it on device: hangs during a profile now keep their stack, and the merged profile is complete.

I also tested the reload-crash part, and it doesn't hold on RN 0.88 New Architecture. On Android that's the only architecture for RN ≥ 0.82.

invalidate() runs after the JS thread has exited. Bridgeless teardown quits and joins the JS thread first, and only then invalidates the TurboModules:

// ReactInstance.kt (RN 0.88.1)
fun destroy() {
  reactQueueConfiguration.destroy()   // jsQueueThread.quitSynchronous(): quit + join
  turboModuleManager.invalidate()     // RNSentryModuleImpl.invalidate() runs here

ReactInstance.kt#L419-L422, MessageQueueThreadImpl.kt#L95-L104

I logged the state at the top of invalidate() during a reload. The JS queue had already finished, and the sampler aborted 3 ms later:

14:04:44.969 invalidate: jsQueueAccepts=false trackerRunning=true profiling=true
14:04:44.972 F libc: invalid pthread_t 0x7d87a8f35fc0 passed to pthread_kill
             Fatal signal 6 (SIGABRT) in tid 5284 (hermes-sampling)

Reload loop: 80 reloads per build, 1.5 s apart, triggered from adb through a temporary receiver that calls reactHost.reload(). Release builds of the sample, arm64, Pixel 8 emulator, profilesSampleRate: 1.0.

Build Reloads during an active profile SIGABRT on hermes-sampling
main 75 2
this PR 63 8

The crash already exists on main: the HermesSamplingProfiler.disable() in invalidate() from #5441 relies on the same ordering. This PR makes it more frequent, probably because jsHangTracker.stop() now runs before the disable. It also adds hang samples as a second way for the sampler to be on during a reload. The class Javadoc and the "Motivation and Context" section say the sampler is turned off before the JS thread exits, which isn't the case on 0.88.

Suggestion: ReactHost.addBeforeDestroyListener (ReactHost.kt#L184) runs on both reload and destroy, before ReactInstance.destroy() (ReactHostImpl.kt#L1356, #L1519). The JS thread is still alive at that point. Stopping the tracker and calling RNSentryHermesSampler.disableProfiling() from there, and keeping invalidate() as the fallback for the Old Architecture and older RN, should close the race. Please check which RN version first has addBeforeDestroyListener.

Since the same fix also covers the existing profiling crash, it could go in a small PR that merges first, with this one rebased on top. Wdyt?

@alwx

alwx commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

@antonis thanks a lot for digging into this, you're right. I checked ReactInstance.destroy() in 0.88.1: the JS queue is quit and joined before turboModuleManager.invalidate() so invalidate() is too late on the New Architecture, and my reload loop didn't cover it (it ran in a debug build where the tracker is off). addBeforeDestroyListener exists since RN 0.73. I'll do the fix in a separate PR off main with your reload loop as the check, and rebase this one on top.

@alwx alwx removed the ready-to-merge Triggers the full CI test suite label Dec 1, 2026

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

@antonis thanks a lot for digging into this, you're right. I checked ReactInstance.destroy() in 0.88.1: the JS queue is quit and joined before turboModuleManager.invalidate() so invalidate() is too late on the New Architecture, and my reload loop didn't cover it (it ran in a debug build where the tracker is off). addBeforeDestroyListener exists since RN 0.73. I'll do the fix in a separate PR off main with your reload loop as the check, and rebase this one on top.

Thank you 🙇 Let's iterate once the separate PR is merged 👍

alwx added a commit that referenced this pull request Dec 1, 2026
Replace the PR link placeholder in the Android JS hang tracking entry with #7111.
alwx added a commit that referenced this pull request Dec 1, 2026
Review feedback on #7111. sample() cleared its enabled flag before it called disable(), so when disable() threw, the finally block skipped the best-effort disable and the global Hermes sampler could stay on. A JS hang sample does not set isProfiling, so invalidate() would not turn it off later either. The flag is now cleared only after disable() returns.

A new test uses a fake profiler whose first disable() throws and checks that the sampler tries to disable it again.
@alwx
alwx force-pushed the alwx/feature/6985 branch from b0582dc to d05f278 Compare December 1, 2026 11:21
alwx added a commit that referenced this pull request Dec 1, 2026
Review feedback on #7111. While a Hermes profile ran, sample() returned null, so the JS hang event had no stack and grouped into its own issue. With profiling on, a hang soon after launch often lands inside the app start profile.

Android now does what iOS does. While a profile runs, sample() does not turn the sampler off. It dumps the running profile, keeps the dump, and returns it as a profile trace, so the tracker takes the newest JS stack of the dump. Hermes clears its samples on every dump, so stopProfiling() merges the kept dumps with the final one in time order and moves the stack frame ids of each dump past the ids of the dumps before it. When a dump cannot be merged, the profile keeps the final dump. Starting or discarding a profile drops the kept dumps.

On an Android emulator with profilesSampleRate 1.0, a hang inside the profile gave a JS Thread Hang event with the stack down to onPress, and the profile kept the hang samples.
alwx added a commit that referenced this pull request Dec 1, 2026
Review feedback on #7111: keep only the first line of the entry.
alwx added a commit that referenced this pull request Dec 1, 2026
8.37.0 was released while #7111 was open, so the rebase left the entry in the released section.
alwx added a commit that referenced this pull request Dec 1, 2026
…is destroyed

Review feedback on #7111. On the New Architecture, the before destroy listener from #7157 runs invalidate(), which stops the JS hang tracker while the JS thread still runs. A start that came in after that cleanup would leave the tracker, and with it the Hermes sampler, running while the JS thread exits. startJsHangTracking now does nothing after the cleanup, and stops the tracker again when the cleanup ran between the check and the start.

With reactHost.reload() every 1.5 s in a release build with profilesSampleRate 1.0, 600 reloads gave no abort on the hermes-sampling thread.
@github-actions github-actions Bot added the risk: medium PR risk score: medium label Dec 1, 2026
@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

PR risk: medium

For commit 298b7ca.

Main concerns: data sent to Sentry, public contract, host performance.

This label is a hint for reviewers, not an approval.

@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 1, 2026
@alwx

alwx commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

@antonis here it is: #7157

alwx added 7 commits December 1, 2026 13:51
enableJsHangTracking worked only on iOS. On Android, an infinite loop in JS still sent no event, because ANR detection watches only the main thread.

RNSentryJSHangTracker uses the same design as iOS. A native thread posts an empty runnable to the JS thread with runOnJSQueueThread every 100 ms, and measures only after the first answer, so bundle loading is not a hang. It pauses in the background and while a debugger is attached. When the runnable does not run within the timeout, it samples the JS thread with the Hermes sampling profiler for 300 ms and captures a handled JS Thread Hang error event, with the oldest JS stack of the sample and the bundle Debug ID for source maps. The capture runs on its own thread, so the tracker thread never waits for disk I/O.

The iOS tracker was not ported earlier because a reload often crashed in the Hermes sampler thread (meta/hermes#1853). Hermes fixed the cause on main, where the sampler calls pthread_kill on a JS thread that already exited, but the fix is not in the Hermes release that React Native 0.88 and 0.89 ship. So the SDK keeps the sampler off before the JS thread exits. invalidate() stops the tracker first, and stop() interrupts a running sample and waits until the tracker thread ends. RNSentryHermesSampler now holds the sampler for profiling and for JS hang samples under one lock, so a profile cannot start in the middle of a sample, and stopping a profile turns the sampler off before it creates the trace file.

The JS hang flame graph stays iOS only. Robolectric tests cover the tracker with a fake JS thread and sampler, the shared sampler with a fake Hermes profiler, and the module start, stop, and invalidate paths.
Replace the PR link placeholder in the Android JS hang tracking entry with #7111.
Review feedback on #7111. sample() cleared its enabled flag before it called disable(), so when disable() threw, the finally block skipped the best-effort disable and the global Hermes sampler could stay on. A JS hang sample does not set isProfiling, so invalidate() would not turn it off later either. The flag is now cleared only after disable() returns.

A new test uses a fake profiler whose first disable() throws and checks that the sampler tries to disable it again.
Review feedback on #7111. While a Hermes profile ran, sample() returned null, so the JS hang event had no stack and grouped into its own issue. With profiling on, a hang soon after launch often lands inside the app start profile.

Android now does what iOS does. While a profile runs, sample() does not turn the sampler off. It dumps the running profile, keeps the dump, and returns it as a profile trace, so the tracker takes the newest JS stack of the dump. Hermes clears its samples on every dump, so stopProfiling() merges the kept dumps with the final one in time order and moves the stack frame ids of each dump past the ids of the dumps before it. When a dump cannot be merged, the profile keeps the final dump. Starting or discarding a profile drops the kept dumps.

On an Android emulator with profilesSampleRate 1.0, a hang inside the profile gave a JS Thread Hang event with the stack down to onPress, and the profile kept the hang samples.
Review feedback on #7111: keep only the first line of the entry.
8.37.0 was released while #7111 was open, so the rebase left the entry in the released section.
…is destroyed

Review feedback on #7111. On the New Architecture, the before destroy listener from #7157 runs invalidate(), which stops the JS hang tracker while the JS thread still runs. A start that came in after that cleanup would leave the tracker, and with it the Hermes sampler, running while the JS thread exits. startJsHangTracking now does nothing after the cleanup, and stops the tracker again when the cleanup ran between the check and the start.

With reactHost.reload() every 1.5 s in a release build with profilesSampleRate 1.0, 600 reloads gave no abort on the hermes-sampling thread.
@alwx
alwx force-pushed the alwx/feature/6985 branch from d05f278 to 8f7b837 Compare December 1, 2026 12:51
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 1, 2026
The Android JS hang tracking change added 27 tests, many of them for small mapping details or for cases that other tests already cover. The suite now keeps 15: the hang report and its false positive guards, the tracker stop during a sample, the stack selection and frame mapping, the event, the Hermes sampler safety around disable, profiles, and the lock, and the module start, timeout, and invalidate paths.

The invalidate test now also checks that the tracker runs before invalidate(), so it cannot pass when the tracker never started.
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk: medium PR risk score: medium

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Report JS thread hangs as errors on Android

2 participants