Skip to content

feat(core): Add the task context to the long task metric - #7119

Open
alwx wants to merge 5 commits into
mainfrom
alwx/feature/7074
Open

alwx wants to merge 5 commits into
mainfrom
alwx/feature/7074

Conversation

@alwx

@alwx alwx commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

📢 Type of change

  • Bugfix
  • New feature
  • Enhancement
  • Refactoring

📜 Description

Each react_native.long_task.duration metric now has the context at the start of the task: router.navigation.route.id (the route name, not the full path), app.in_foreground, app.start_phase (app_start or steady_state), and the name and op of the root span (sentry.segment.name, sentry.op). React Native delivers long task entries late with idle priority, so the integration keeps a short history of these values and reads them at the task start time. The phase uses the same app start end as the app start transaction, and the tasks wait for it only when the app start integration runs.

💡 Motivation and Context

Without these attributes, long tasks cannot be broken down by screen, app state or app start. Closes #7074.

💚 How did you test it?

Unit tests cover each attribute, the app start end from the bundle start, appLoaded() and extendAppStart(), the waiting, and the sending of waiting tasks on flush and close. I have not tested it on a device yet.

📝 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 (packages/core/etc/sentry-react-native.api.md) reviewed by another Mobile SDK team member or implemented according to the develop docs spec.
  • No breaking changes.

🔮 Next steps

Agree on the keys for the root span op and the app start phase in sentry-conventions, then rename sentry.op and app.start_phase before merge. Check the attributes on a device.

@github-actions

github-actions Bot commented Nov 26, 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(core): Add the task context to the long task metric by alwx in #7119
  • 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 26, 2026 •

Copy link
Copy Markdown
Contributor
Messages
📖 Do not forget to update Sentry-docs with your feature once the pull request gets approved.

Generated by 🚫 dangerJS against 8704027

@linear-code

linear-code Bot commented Nov 26, 2026

Copy link
Copy Markdown

RN-875

@antonis

antonis commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

@sentry-junior verify

@antonis antonis added the ready-to-merge Triggers the full CI test suite label Nov 30, 2026
@sentry-junior

sentry-junior Bot commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

Experimental end-to-end verification by Junior, run on an Android emulator in CI. A maintainer decides what it means.

Gate: Verifiable on Android or iOS (one is enough). The claim (from #7074) is runtime JS behavior that the sample can trigger on an emulator ("Block JS thread for 5s" with longTaskIntegration and enableMetrics on, React Native 0.88.1 New Architecture), with no native dependency.

Not run: the evidence is the attributes of the react_native.long_task.duration metric, and the full run doesn't support a metric yet (it only compares JavaScript error events).

Asked by antonis.

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

Added some comments inline. Let's also add Sentry links to verify the changes 🙇

@github-actions github-actions Bot added the risk: medium PR risk score: medium label Nov 30, 2026
@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

PR risk: medium

For commit 8704027.

Main concerns: data sent to Sentry, host performance, reach.

Rules that block low also fired:

  • R4: a public API record changed: packages/core/etc/sentry-react-native.api.md

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 added 3 commits December 1, 2026 10:51
The react_native.long_task.duration metric had only sentry.origin, so long tasks could not be broken down by where they happened. Each metric now has the route (route), the foreground state (app.in_foreground), the app start phase (app.start_phase: app_start or steady_state) and the name and op of the root span (sentry.segment.name, sentry.op).

React Native delivers long task entries to the observer callback with idle priority, which can run up to 5 minutes after the task when the JS thread is busy. The context at callback time can then belong to a later screen. So the integration keeps a short history of route changes, app state changes and root spans, and reads the values at the start time of each task. The long tasks that a transaction reads with takeRecords() before the observer delivers them go through the same path, so they get the same context. The tracing integration and the app start code emit the new currentRouteChange and appStartEnd client hooks for this.

The app start end comes from Sentry.wrap, ReactNativeProfiler or appLoaded(). Tasks wait for it, so the long tasks of the app start get the phase too. If the app records no app start end within 30 seconds, the waiting tasks are reported without the phase. The oldest task is reported without the phase when more than 50 tasks wait, and the client close reports the waiting tasks. The root span op is used instead of the op of the active leaf span, because the leaf span at the task start is not known and its op has more values.
The integration released the long tasks that wait for the app start end on the client close hook. Client.close() emits close after the last flush and after it disables the client, so these metrics were never sent.

The tasks are now released on the flush hook, which close() also runs. The client drains the metric buffer in a flush hook that it registers before the integrations, so the integration drains the buffer again after it releases the tasks. A flush before the app start end, for example on a fatal error, now sends the waiting tasks without the phase instead of losing them.

The test checks the request body that reaches the transport, because beforeSendMetric runs before the buffer and passed also when nothing was sent.
The app start phase compared each task with the end that Sentry.wrap, ReactNativeProfiler or appLoaded() recorded first. The app start transaction uses a different end: the bundle start when the app records none, the appLoaded() end when it overrides an auto capture, and the extended end with extendAppStart(). Tasks in these windows got steady_state, and apps without wrap held all tasks for 30 seconds.

The app start integration now emits appStartEnd where it computes the final end for the transaction, and the long task phase uses that value. The tasks wait for it only when the app start integration runs. Without it, for example without tracing, no app start end comes, so the tasks are sent at once without the phase.

The route moves from the deprecated route key to router.navigation.route.id. The navigation integrations emit the route name, or the templated path of a route override, instead of the full path of useFullPathsForNavigationRoutes, because the full path can contain IDs and makes the metric high in cardinality. setCurrentRoute is unchanged, so contexts.app.view_names keeps the full path.
@github-actions github-actions Bot added the risk: medium PR risk score: medium label Dec 1, 2026
@alwx
alwx force-pushed the alwx/feature/7074 branch from 2c747f8 to c6d842e Compare December 1, 2026 09:52
@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

Thanks for the review. All comments were valid. Here is what changed.

The bundle start fallback, appLoaded() and extendAppStart() comments had one cause: the phase used the first recorded app start end, but the app start transaction uses its final end. The app start integration now emits appStartEnd with that final end, and the phase uses it. The tasks wait for it only when the app start integration runs. Without it, for example without tracing, they are sent at once without the phase, so the 30 second wait is gone.

The waiting tasks are now released on flush, which close() also runs, and the integration drains the metric buffer again after that (5a8ac12). The client drains the buffer in an earlier flush hook, so without the second drain the tasks were still lost. The test now checks the request that reaches the transport.

The route key is now router.navigation.route.id, which is in sentry-conventions and is not deprecated. The value is the route name or the templated path of a route override, never the full path, so it contains no IDs.

sentry-conventions has no key for the root span op or the app start phase. I will propose sentry.segment.op and app.start_phase there and rename the keys before this PR merges. The op comes from the root span because the active span at the task start is not known when the entry arrives.

The _setAppStartEndData line in the test setup is gone, because the default setup no longer waits.

@alwx
alwx requested a review from antonis December 1, 2026 09:59
}

appStartDataFlushed = true;
(_client as ReactNativeClient | undefined)?.emit('appStartEnd', appStartEndTimestampMs);

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.

h: When the first transaction isn't sampled, startup tasks still wait 30s.

appStartEnd is only emitted here, after app start data is attached to a transaction. The cases that skip it:

  • No sampled transaction yet. In non-standalone mode the integration locks onto the first sampled root span (L488-490). With a typical tracesSampleRate (0.1–0.2), the first navigation is usually unsampled, so the hook comes late or never.
  • First sampled transaction too late. If it starts more than 60s after app start, the bounds check returns early without emitting (L696-702).
  • Standalone mode, span unsampled. The function returns before attaching (L562-565).
  • Other early returns. has_fetched is already set (e.g. after a JS reload such as an OTA update or CodePush restart), native data is missing, or the duration is over the cap (L655-722).

afterAllSetup in longTask.ts (L205-207) only stops the wait when the integration is missing or disabled. So in all these cases startup tasks are held until the 30s deadline (longTask.ts L322). They are then sent without app.start_phase and with a metric timestamp up to 30s late.

Suggestion: in every path that ends the app start attempt (appStartDataFlushed = true, the unsampled standalone return), emit the hook with the best end time available, i.e. appStartEndData?.timestampMs || getBundleStartTimestampMs(), the same fallback as L687. Waiting tasks would then be released immediately.

Comment on lines +506 to +511
const setupWithAppStart = (clientOptions?: Partial<TestClientOptions>): void =>
setup(undefined, {
integrations: [{ name: 'AppStart' }, longTaskIntegration()],
enableAppStartTracking: true,
...clientOptions,
});

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.

m: These tests don't use the real app start integration. setupWithAppStart registers a stand-in { name: 'AppStart' } and emits appStartEnd by hand. appStart.test.ts covers the emit side, but no test runs the real pairing. A test with the real appStartIntegration and an unsampled first root span would catch the gap in the appStart.ts L725 comment.

Comment on lines +325 to +329
client.on('flush', () => {
if (waitingForAppStartEnd?.length) {
reportWaitingForAppStartEnd();
_INTERNAL_flushMetricsBuffer(client);
}

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.

nit: Any flush() permanently ends the wait. A user's Sentry.flush() or the fatal-error handler's flush (reactnativeerrorhandlers.ts L252) releases the waiting tasks without the phase and sets waitingForAppStartEnd = undefined (L294). Later tasks still get the phase once the hook arrives (L303), so the loss is limited to the tasks waiting at that moment. That's probably acceptable, but a one-line comment would make it clear it's intended.

Comment on lines +275 to +285
attributes['app.start_phase'] = startTimestamp * 1000 < appStartEndMs ? 'app_start' : 'steady_state';
}

const rootSpan = rootSpanAt(rootSpans, startTimestamp);
if (rootSpan) {
const { description, op } = spanToJSON(rootSpan);
if (description) {
attributes[SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME] = description;
}
if (op) {
attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] = op;

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.

m: app.start_phase (L275) and sentry.op (L285) still need settling before merge. Neither is in sentry-conventions for this use. As mentioned, the plan is to propose sentry.segment.op and app.start_phase there and rename the keys before merge. Let's hold the merge until that's done or a decision is recorded, since renaming a shipped metric attribute breaks users' dashboards.

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

Thank you for iterating on this 🙇
Added some comments inline. Let's also add Sentry links in the test section of the description.

The app start integration emitted appStartEnd only after it attached the app start to a transaction. When the first root span was not sampled, when the standalone app start span was not sampled, or when the attach stopped early (no native data, has_fetched after a JS reload, the age or duration check), no hook came. The long tasks of the app start then waited for the 30 second deadline and were sent without the phase.

Every path that ends the app start attempt now emits appStartEnd. The failed attach and the unsampled standalone span use the same fallback as the app start transaction: the recorded app start end, or the bundle start. In non-standalone mode the first unsampled root span emits it once per app run, because the integration waits for a sampled transaction that can come late or never. A later sampled attach still emits the final end, and only the tasks released before it keep the fallback phase.

A long task test now runs the real app start integration with an unsampled root span instead of a stand-in. The flush handler has a comment that a flush ends the wait on purpose.
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 1, 2026
When React Native runs the application again in the same JS runtime, for example after Android recreates the activity, the app start integration starts a new app start. The long task integration kept the end of the previous run and did not wait again, so the long tasks of the new app start were compared with an old end and got steady_state.

The app start integration now emits appStartBegin when it resets for a new run. The long task integration then waits again, forgets the old end and restarts the deadline.

The app start integration reset only after it attached or captured an app start. With a low sample rate, the run can end with only the fallback appStartEnd of an unsampled root span, and then the next runApplication did not reset and the new run never emitted an end. An emitted app start end now also ends the run.
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 1, 2026
Comment on lines +323 to +328
rnClient.on('appStartBegin', () => {
waitingForAppStartEnd = waitingForAppStartEnd ?? [];
appStartEndMs = undefined;
clearTimeout(appStartEndDeadline);
appStartEndDeadline = setTimeout(reportWaitingForAppStartEnd, APP_START_END_DEADLINE_MS);
});

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.

appStartBegin drops prior end so delayed steady_state tasks get wrong phase

After appStartBegin, long tasks that started in the previous run’s steady state but are delivered late are queued again and classified against the new run’s app start end, so app.start_phase becomes app_start (or is omitted on the deadline) instead of steady_state. Keep a timestamped history of app-start ends/begins like routes and resolve phase at the task start time.

Evidence
  • After appStartEnd, reportWaitingForAppStartEnd() sets waitingForAppStartEnd to undefined and later tasks report immediately using the stored appStartEndMs.
  • appStartBegin clears appStartEndMs and recreates waitingForAppStartEnd as [] without recording the prior end or the begin time.
  • A task with startTimestamp after the old end can still be delivered after appStartBegin (idle-priority delivery); it is queued, then report sets phase with startTimestamp * 1000 < appStartEndMs against the new end → app_start.
  • Routes/app state use Change[] history for delayed lookup; app start phase is a single scalar, so it cannot recover the previous run’s end.

Identified by Warden · code-review · AUH-TUL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-to-merge Triggers the full CI test suite risk: medium PR risk score: medium

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add screen, app-state and span context to long task metric

2 participants