Repository navigation
feat(ios): Attach a flame graph to JS hang events - #7042
Conversation
Replace the PR link placeholder in the attachJsHangFlamegraph entry with #7042.
Semver Impact of This PR⚪ None (no version bump detected) 📋 Changelog PreviewThis is how your changes will appear in the changelog.
🤖 This preview updates automatically when you update the PR. |
|
📲 Install BuildsAndroid
|
antonis
left a comment
There was a problem hiding this comment.
Overall LGTM 🎉
Tested locally on an iOS Release build and got a flamegraph :)
Sentry link: https://sentry-sdks.sentry.io/issues/SENTRY-REACT-NATIVE-WDT/events/0992dabdb1054187bcb30475a757ddae/
Left a few comments but nothing blocking.
Let's also merge the latest from main and move the changelog to unreleased.
Good point @philprime 👍 I guess not but I think @alwx is already iterating on this. |
|
@philprime yep that's fixed already |
|
Ah yes I found it now 👍
|
|
Nothing extra to add from my side, Antonis and Philip already covered the main points from my review |
|
Debugging MetricKit is much harder but I'm doing it here: #7059 |
Replace the PR link placeholder in the attachJsHangFlamegraph entry with #7042.
philprime
left a comment
There was a problem hiding this comment.
Almost LGTM, mostly coverage feedback and open questions
| return nil; | ||
| } | ||
| if (![hermesFrame[@"category"] isEqual:@"JavaScript"]) { | ||
| return includeNative ? @{ @"function" : name, @"in_app" : @NO } : nil; |
There was a problem hiding this comment.
l: The flame graph spec says “Native frames MUST retain instruction_addr, even when already symbolicated,” but these Hermes native/host frames contain only function and in_app.
These appear to be logical runtime frames rather than captured native instruction frames, so requiring an address might not apply.
Do you think we need to clarify that distinction in the spec and explicitly permit name-only Hermes runtime frames? We should not invent addresses when Hermes does not provide them.
There was a problem hiding this comment.
Agreed, these are logical Hermes runtime frames, not captured machine frames, and Hermes gives no address for them so we actually should not invent one. Relay and the backend already accept frames with only function. I'd rather clarify the spec to explicitly allow name-only runtime frames: something like "Frames that the runtime reports without a native address, such as Hermes built-in and host function frames, MAY omit instruction_addr."
Happy to open the develop-docs PR.
There was a problem hiding this comment.
| - Create the Android view managers of the SDK on demand, so React Native 0.89+ with the New Architecture does not build their view configs at startup ([#7049](https://github.com/getsentry/sentry-react-native/pull/7049)) | ||
| - Attach a flame graph of the sampled JS stacks to JS hang events on iOS with the experimental `attachJsHangFlamegraph` option ([#7042](https://github.com/getsentry/sentry-react-native/pull/7042)) | ||
| - The flame graph shows where the JS thread spent its time in the sample window of about 300 ms when the SDK detected the hang. It requires `enableJsHangTracking` and Hermes. | ||
| - The frames in the flame graph are not yet symbolicated with source maps. |
There was a problem hiding this comment.
m: Why not? What is missing for this to work?
There was a problem hiding this comment.
It's a backend gap. The backend symbolicates flame graph attachments only for native images: _get_flamegraph_stacktraces in src/sentry/lang/native/processing.py keeps frames whose image passes is_native_image and sends them to symbolicator. There is no JS/source map processing for attachment frames, so the sourcemap debug image we put in debug_meta is ignored. The event's own stack is source-mapped as usual. What's missing is running JS processing over the attachment frames, the same way it already runs for event stacks.
Probably makes sense to open an issue in getsentry/sentry, what do you think?
There was a problem hiding this comment.
Yes, I would've expected this to be implemented but maybe I removed it from the backend implementation in later iterations.
| XCTAssertEqual([flamegraph[@"nodes"] count], 5); | ||
| } | ||
|
|
||
| - (void)testFlamegraphMergesSiblingNodesWithTheSameFrameContent |
There was a problem hiding this comment.
m: Could we add a recursive-call fixture where two positions on the same path have identical frame content? They should share a frame_id but remain distinct nodes with correct inclusive counts. The spec explicitly requires independent trees without cycles or shared nodes, which the current validation helper does not check.
There was a problem hiding this comment.
Added testFlamegraphKeepsRecursiveCallsAsSeparateNodesWithOneFrame in the latest commits
|
@buenaflor good catch, thanks! That's fixed now: the flame graph is now attached only when the event stack has JS frames. |
The JS hang tracker samples the JS thread for 300 ms but keeps only one stack for the event. Add flamegraphFromHermesTrace:newestFirst:bundleDebugId:, which turns all samples of the Hermes trace into an event.flamegraph payload (version 1, platform javascript), so the time spent during the hang becomes visible. The builder keeps the JS frames of each sample, puts each Hermes frame into the frame table once, and builds one tree per thread with inclusive sample counts from caller to callee, without recursion. For a profile trace it uses only the samples within the sample window of the newest one. The tree of the thread that gives the event stack gets thread_attributed, and a known bundle Debug ID adds a sourcemap debug image. It returns nil for traces without JS samples, for invalid traces, and for payloads larger than 10 MiB. The event stack and the flame graph now share one Hermes frame mapping and one stack walk, so their frames cannot differ. The report path does not call the builder yet. XCTest coverage is added to RNSentryCocoaTester.
The JS hang event carried only one stack, although the tracker samples the JS thread for the whole window. When the new attachFlamegraph flag is on, the tracker now builds a flame graph from the same Hermes trace and attaches it to the event as flamegraph.json with the event.flamegraph attachment type. The tracker reads the flag before it leaves the tracker thread. The capture goes through a new SentrySDKWrapper method that adds the attachment in a scope block. When the flag is off, or when the builder returns nothing (no trace, no JS samples, or more than 10 MiB), the event is captured as before. The capture stays inside the existing @try/@catch, and the event fields do not change. RNSentry exports setAttachJsHangFlamegraph as a separate method, so the released startJsHangTracking signature stays the same for older JS bundles.
The native JS hang tracker on iOS can attach a flame graph of the sampled JS stacks to its events. The new experimental attachJsHangFlamegraph option turns this on. It is off by default and works only together with enableJsHangTracking. Sentry.init passes the option to jsHangTrackingIntegration. After init, the integration calls the new setAttachJsHangFlamegraph bridge method before startJsHangTracking. The flag is a separate method, so the released startJsHangTracking signature does not change. The wrapper skips the call when an older native binary does not have the method, so JS hang tracking still starts there. initNativeSdk does not send the option to the native SDK. Android gets methods that do nothing for both architectures, because JS hang tracking is iOS only. The API report is regenerated.
Add a CHANGELOG entry for the experimental, iOS-only attachJsHangFlamegraph option. The entry says that the frames in the flame graph are not yet symbolicated with source maps. The PR link is a placeholder until the PR is open. The React Native sample already enables enableJsHangTracking. It now also enables attachJsHangFlamegraph, so the manual check of JS hang events includes the flame graph attachment.
Replace the PR link placeholder in the attachJsHangFlamegraph entry with #7042.
The existing hang buttons block the JS thread with a flat loop, so the flame graph of their JS hang event has a single path and shows nothing useful. The new button on the Errors screen blocks the JS thread for 5 seconds with nested named functions. Each batch calls hashRecords and sortRandomNumbers through processBatch, so the flame graph attached by attachJsHangFlamegraph shows a call tree with two branches.
The flame graph kept only JS frames, so time spent in built-in and host functions, such as JSON.stringify, Array.prototype.sort, or a synchronous native module call, was counted to the calling JS function. The flame graph now also keeps the non-JavaScript Hermes frames, as frames with only a function name. This matches how JS profiles map these frames. Native frames stay in their place in the stack, so a JS callback that a native function calls, such as a sort comparator, stays under it. A sample with only native frames now counts too, because a JS thread that waits in a synchronous native call is a hang. The [root] frame is still left out. The event stack does not change. It keeps only JS frames, and thread attribution still uses the JS frames. A run of the React Native sample on an iOS simulator gave 23 samples in the 300 ms window, including [Native] jsonStringify, [Native] arrayPrototypeSort with the comparator under it, [Native] stringPrototypeConcat, [Native] dateNow, and [Native] arrayFrom.
The Sentry flame graph view treats a frame without in_app as a system function, so every frame of the JS hang flame graph was shown as a system function. The flame graph now sets in_app to true for JS frames and to false for Hermes native frames. The device cannot tell app code from library code in the bundle, because only source maps show the original file. So React and React Native frames are marked in_app too, until the backend symbolicates the JS frames of flame graph attachments. The event stack does not copy in_app, so it does not change. A test checks this.
Review feedback on #7042. The default integrations test mocked jsHangTrackingIntegration to check its arguments. It now initializes the integration that getDefaultIntegrations returns and checks what reaches native: setAttachJsHangFlamegraph(true) and startJsHangTracking with the timeout in milliseconds. The wrapper test for a throwing setAttachJsHangFlamegraph now also checks that the error is logged with debug.error, not only that the call does not throw.
Review feedback on #7042. The attachJsHangFlamegraph docs said that the flame graph shows the time spent during the hang. It covers only the sample window of about 300 ms when the SDK detected the hang, so the JSDoc and the CHANGELOG entry now say that.
Review feedback on #7042. Hermes gives each call tree position its own frame id, so the same function reached from different callers got several entries in the frame table, and frames with the same content under one parent became separate sibling nodes. The develop docs say that producers should deduplicate frames by content. The builder now keys the frame table on filename, function, line, and column, and caches the result per Hermes id. The report path now parses the Hermes trace once and passes the result to the event stack and the flame graph builders. The flame graph builder logs when it fails or when the payload exceeds 10 MiB, like the capture path does. setAttachJsHangFlamegraph catches exceptions at the bridge boundary.
…rames Review feedback on #7042. When the sample window had only native Hermes frames, the event had no stack, so these events grouped together by the timeout message. The flame graph was still attached, and Relay fills a missing exception stack from it, so the events would split into issues per native function. The tracker now attaches the flame graph only when the event stack has JS frames, so the flame graph only adds detail. The capture moves into captureHangWithProfile:newestFirst:timeoutIntervalMs:bundleDebugId:attachFlamegraph:, which XCTest covers with a mocked SentrySDKWrapper: the attachment is flamegraph.json with the event.flamegraph type when the option is on, and there is no attachment when the option is off, for an invalid profile, for a flame graph larger than 10 MiB, and without JS frames. A test with a running SDK checks that the attachment does not stay on the scope, because captureEvent:withScopeBlock: applies it to a copy. New builder tests cover recursive calls, which share one frame but stay separate nodes, and frames with the same function and different columns, which stay apart. The validation helper now checks that each node belongs to exactly one tree. kMaxFlamegraphBytes links to the limit in the develop docs.
Review feedback on #7042. The compatibility test removed all JS hang bridge methods at once. A native binary from 8.34.0 has startJsHangTracking but not setAttachJsHangFlamegraph, so a new test removes only the setter and checks that the call does not throw and that JS hang tracking still starts.
009136d to
3d3275f
Compare
🚨 Detected changes in high risk code 🚨High-risk code has higher potential to break the SDK and may be hard to test. To prevent severe bugs, apply the rollout process for releasing such changes and be extra careful when changing and reviewing these files:
|
|
Rebased on main (the only conflict was the changelog entry next to #7059) and pushed the review fixes. All threads are addressed now |
From running the skill on open PRs (#7042, #7030): a "Not verifiable this way" verdict decided before any build (build-only claims, triggers a simulator can't produce, native APIs missing from the pinned SDK, low disk), guidance for feature PRs and open PRs, checks for node_modules, run tagging and spec codegen, release builds by default, and evidence for replay recording content and JS-thread blocks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* chore(tooling): Add verify-pr skill for on-device PR verification Adds a local skill that verifies a PR end to end on an Android emulator: build the sample without and with the change, drive it with Maestro, find both runs' events in sentry-sdks through the Sentry MCP, and write a draft before/after report. The sample tags events with verify.pr, verify.commit and verify.run_id when launched with matching launch arguments, and does nothing otherwise. It also enables logs in sentry.options.json, so native Android matches the JS enableLogs setting. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(tooling): Write verify-pr scenarios per run, not into the skill Scenarios were one-off per PR and nothing runs them, so a shared folder would grow and rot. Move the #7087 flow to flows/examples/ as the worked example and regression check, write each run's flow next to its report, and promote to flows/steps/ only when a second run needs it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(tooling): Add iOS simulator support to the verify-pr skill From verifying #7087 and #6974 on the iOS simulator: Pods setup and the files pod install rewrites, the iOS init path, Maestro differences (no `back`, tab icons and the Playground tab need ids), reading screenshot attachments back from Sentry, and a two-color probe for masking checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(tooling): Fold iOS acceptance-run findings into verify-pr Save the revert as a patch file, compare dist/ against packages/core/src, define verify.commit for both sides, reinstall Pods every iOS run, shut down booted devices, and keep attachment URLs out of reports. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(sample): Add a screenshot masking probe to the Playground tab A two-color view inside the existing <Sentry.Mask> demo, plus a button that captures an exception with the demo on screen. The view is neither text nor an image, so only <Sentry.Mask> can hide it in the event's screenshot; a masked probe is one flat color. Used to verify #6974. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(tooling): Add a pre-build gate and open-PR handling to verify-pr From running the skill on open PRs (#7042, #7030): a "Not verifiable this way" verdict decided before any build (build-only claims, triggers a simulator can't produce, native APIs missing from the pinned SDK, low disk), guidance for feature PRs and open PRs, checks for node_modules, run tagging and spec codegen, release builds by default, and evidence for replay recording content and JS-thread blocks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…0940) ## DESCRIBE YOUR PR Closes #20938. The flame graph attachment spec required every native frame to keep `instruction_addr`. The React Native SDK builds JS hang flame graphs from Hermes sampling profiler traces (getsentry/sentry-react-native#7042). Hermes reports built-in and JSI host function frames, such as `[Native] jsonStringify`, with only a name and no address. These are logical runtime frames, not captured machine frames, so SDKs should not invent addresses for them. Relay and the backend already accept frames with only a `function`. - The `instruction_addr` rule now applies to native frames captured from machine stacks. - Frames that a runtime reports without a native address **MAY** omit `instruction_addr` and contain only `function`. - Bumped the attachments spec to 1.8.1 and added a changelog entry. ## IS YOUR CHANGE URGENT? Help us prioritize incoming PRs by letting us know when the change needs to go live. Select exactly one option. For deadlines, replace `YYYY-MM-DD` with the due date. You can update this information later by editing the PR description. - [ ] Urgent deadline (GA date, etc.): YYYY-MM-DD - [ ] Other deadline: YYYY-MM-DD - [x] No deadline: Not urgent, can wait up to 1 week+ ## SLA - Teamwork makes the dream work, so please add a reviewer to your PRs. - Please give the docs team up to 1 week to review your PR unless you've supplied a deadline. Thanks in advance for your help! ## PRE-MERGE CHECKLIST _Make sure you've checked the following before merging your changes:_ - [ ] Checked Vercel preview for correctness, including links - [ ] PR was reviewed and approved by any necessary SMEs (subject matter experts) - [ ] PR was reviewed and approved by a member of the [Sentry docs team](https://github.com/orgs/getsentry/teams/docs) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>

📢 Type of change
📜 Description
Adds the experimental, iOS-only option
attachJsHangFlamegraph. WhenenableJsHangTrackingreports a JS hang, the native tracker now builds a flame graph from all Hermes samples of its existing 300 ms window and attaches it asflamegraph.jsonwith theevent.flamegraphattachment type. The event stack, grouping, and other event fields do not change.The flag reaches native through the new
setAttachJsHangFlamegraphbridge method, so the releasedstartJsHangTrackingsignature stays the same and older native binaries still start JS hang tracking. Android gets no-op methods.The flame graph also keeps Hermes native frames (built-in and host functions such as
[Native] jsonStringify) with only a function name, so time spent in them is not counted to the calling JS function. JS frames are markedin_app: trueand native framesin_app: false, so the flame graph view shows JS code as application functions. The device cannot tell app code from library code in the bundle, so React and React Native frames are markedin_apptoo until the backend symbolicates the JS frames of the attachment. The sample gets a button that blocks the JS thread with nested work.💡 Motivation and Context
The JS hang event kept one stack and discarded all other samples of the window. A flame graph shows where the JS thread spent its time during the hang. It uses the same attachment format as the sentry-cocoa MetricKit hang flame graphs, and Relay already accepts it with
platform: "javascript".💚 How did you test it?
300cad2a6), built in Release for the iOS 26.1 simulator, where JS frames show as application functions.RNSentryCocoaTestersuite passes (225 tests, 0 failures).yarn test,yarn lint,yarn circularDepCheck, andapi-report:checkpass.flamegraph.json(event.flamegraph). The flame graph had 23 samples in the 300 ms window, including[Native] jsonStringifyand[Native] arrayPrototypeSortwith the JS comparator under it.📝 Checklist
sendDefaultPIIis enabled.🔮 Next steps