Skip to content

Commit b4352d6

Browse files
authored
fix(profiling): Drive the native UI profiler from JS (#6916)
* fix(profiling): Drive the native UI profiler from JS UI profiling never ran after app start. React Native turns off native tracing, so the native trace lifecycle never sees a sampled transaction. Also, no API let JS start or stop the native profiler, so the manual lifecycle could not work either. Add the startProfiler and stopProfiler bridge methods. On Android, they call Sentry.startProfiler() and Sentry.stopProfiler(), and startProfiler returns the profiler id. On iOS, they call SentrySDK. sentry-cocoa has no public API for the profiler id, so iOS returns nil. Always set the manual lifecycle on the native side, because both native SDKs refuse manual calls in trace mode. A new default integration, ProfilingIntegration, now chooses when the profiler runs. In trace mode, it runs while a sampled root span is active. In manual mode, it follows Sentry.profiler.startProfiler() and stopProfiler(), which are now exported. The integration waits for native init, stops an app start profile that is no longer needed, and adds the profiler id to transactions so that they link to the profile. * docs(changelog): Add the PR link for the UI profiler fix Replace the PR number placeholder in the CHANGELOG entry with #6916. * fix(profiling): Link profiles per session and delay the trace stop Warden found two problems with the profiler id. The integration kept one id for all transactions, so transactions that ran after the profile stopped still got the id of the stopped profile. Also, the id arrived asynchronously and was dropped when the root span ended before the native start call resolved. Each start call now creates a session that holds the promise of the native start call. Each sampled root span that is active while a session runs is mapped to that session, and processEvent waits for the promise before it adds the id. A transaction now gets only the id of a profile that ran during its root span. In trace mode, the integration now waits one 60 second chunk after the last root span ends before it calls stop. The native SDKs ignore a start call that comes before a requested stop takes effect at the end of the chunk, so back-to-back root spans lost their profile after the chunk ended. * feat(profiling): Add the native JS thread id to spans Sentry opens the profile of a span on the thread from the span's thread.id. React Native spans had no thread.id, so the profile opened on the main thread, and the JS work was in another, unnamed thread. Add the getCurrentThreadId bridge method. It runs synchronously on the JS thread and returns the thread id in the format of the native profiler: the Linux thread id on Android and the Mach thread port on iOS. The UI profiling integration reads it once and sets thread.id on every span that does not have one. * fix(profiling): Keep the first session of a root span and stop on unsampled roots Warden found two more problems in the UI profiling integration. In manual mode, a new session overwrote the session of root spans that started under an earlier session. A transaction could then get the id of a later profile. A root span now keeps the session that was running when it started. In trace mode with startOnAppStart, unsampled root spans were not tracked, so their end never cleared the pending app start profile. With tracesSampleRate: 0, the profiler then ran for the whole session. The end of any root span now ends the app start profile. * fix(profiling): Link root spans that start before native init to the app start profile With startOnAppStart, the native SDK starts the profile before JS runs. Root spans that started and ended before native init had no session, so their transactions got no profiler id. Also, the afterInit handler then saw nothing to run and stopped the app start profile at once, without the delay that trace mode uses. The integration now creates the app start session in setup. Root spans that start before native init map to it, and its id resolves when native init completes. After that, the normal logic decides when the profiler stops. The session resolves without an id if the client closes before native init, so no transaction waits forever. * feat(profiling): Export uiProfilingIntegration for defaultIntegrations: false With defaultIntegrations: false, the UI profiling integration was not installed and could not be added, because it was not exported. The native SDK still received profilingOptions, so trace mode never ran, Sentry.profiler did nothing, and with startOnAppStart nothing ever stopped the app start profile. Export uiProfilingIntegration. It now reads profilingOptions from the client options, so users add it without arguments. If profilingOptions is set but the integration is not installed, the client logs a warning and does not send profilingOptions to the native SDK.
1 parent 45b07b7 commit b4352d6

24 files changed

Lines changed: 839 additions & 106 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@
2828
- Remove the `@sentry/browser` feedback modules and the server-only `@sentry/core` modules from native bundles built on Windows. Before this fix, `includeWebFeedback: false` made these bundles fail at launch ([#6915](https://github.com/getsentry/sentry-react-native/pull/6915))
2929
- Stop wrapping the SDK's own `RNSentry` module in `turboModuleContextIntegration` by default. Each wrapped call wrote to the native scope several times, which added CPU time to every SDK call on iOS ([#6921](https://github.com/getsentry/sentry-react-native/pull/6921))
3030
- To wrap `RNSentry` again, add `{ name: 'RNSentry' }` to the `modules` option.
31+
- Start and stop the native UI profiler for `_experiments.profilingOptions` in both the `trace` and `manual` lifecycles, and export `Sentry.profiler` ([#6916](https://github.com/getsentry/sentry-react-native/pull/6916))
32+
- Before, the profiler ran only for the app start profile, because native tracing is off in React Native and no API controlled the profiler from JS.
33+
- The SDK adds the new `uiProfilingIntegration` by default when `profilingOptions` is set. If you set `defaultIntegrations: false`, add `Sentry.uiProfilingIntegration()` to `integrations`, because the SDK ignores `profilingOptions` without it.
3134

3235
### Dependencies
3336

‎packages/core/RNSentryAndroidTester/app/src/test/java/io/sentry/react/RNSentryProfilingOptionsTest.kt‎

Lines changed: 2 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ import org.junit.runners.JUnit4
1616
import org.mockito.ArgumentMatchers.anyString
1717
import org.mockito.ArgumentMatchers.eq
1818
import org.mockito.Mockito.mock
19-
import org.mockito.Mockito.never
2019
import org.mockito.Mockito.times
2120
import org.mockito.Mockito.verify
2221

@@ -38,7 +37,7 @@ class RNSentryProfilingOptionsTest {
3837
}
3938

4039
@Test
41-
fun `profilingOptions wires sessionSampleRate, trace lifecycle, and startOnAppStart`() {
40+
fun `profilingOptions wires sessionSampleRate, startOnAppStart, and a MANUAL native lifecycle`() {
4241
val rnOptions =
4342
JavaOnlyMap.of(
4443
"_experiments",
@@ -59,42 +58,8 @@ class RNSentryProfilingOptionsTest {
5958
RNSentryStart.getSentryAndroidOptions(options, rnOptions, logger)
6059

6160
assertEquals(1.0, options.profileSessionSampleRate!!, 0.0)
62-
assertEquals(ProfileLifecycle.TRACE, options.profileLifecycle)
63-
assertTrue(options.isStartProfilerOnAppStart)
64-
}
65-
66-
@Test
67-
fun `profilingOptions lifecycle manual maps to ProfileLifecycle MANUAL`() {
68-
val rnOptions =
69-
JavaOnlyMap.of(
70-
"_experiments",
71-
JavaOnlyMap.of(
72-
"profilingOptions",
73-
JavaOnlyMap.of("lifecycle", "manual"),
74-
),
75-
)
76-
val options = SentryAndroidOptions()
77-
78-
RNSentryStart.getSentryAndroidOptions(options, rnOptions, logger)
79-
8061
assertEquals(ProfileLifecycle.MANUAL, options.profileLifecycle)
81-
}
82-
83-
@Test
84-
fun `profilingOptions lifecycle is case-insensitive`() {
85-
val rnOptions =
86-
JavaOnlyMap.of(
87-
"_experiments",
88-
JavaOnlyMap.of(
89-
"profilingOptions",
90-
JavaOnlyMap.of("lifecycle", "TRACE"),
91-
),
92-
)
93-
val options = SentryAndroidOptions()
94-
95-
RNSentryStart.getSentryAndroidOptions(options, rnOptions, logger)
96-
97-
assertEquals(ProfileLifecycle.TRACE, options.profileLifecycle)
62+
assertTrue(options.isStartProfilerOnAppStart)
9863
}
9964

10065
@Test
@@ -172,24 +137,6 @@ class RNSentryProfilingOptionsTest {
172137
verify(logger, times(1)).log(eq(SentryLevel.WARNING), anyString())
173138
}
174139

175-
@Test
176-
fun `non-string lifecycle logs a warning and is ignored`() {
177-
val rnOptions =
178-
JavaOnlyMap.of(
179-
"_experiments",
180-
JavaOnlyMap.of(
181-
"profilingOptions",
182-
JavaOnlyMap.of("lifecycle", 1),
183-
),
184-
)
185-
val options = SentryAndroidOptions()
186-
187-
RNSentryStart.getSentryAndroidOptions(options, rnOptions, logger)
188-
189-
assertEquals(ProfileLifecycle.MANUAL, options.profileLifecycle)
190-
verify(logger, times(1)).log(eq(SentryLevel.WARNING), anyString())
191-
}
192-
193140
@Test
194141
fun `non-boolean startOnAppStart logs a warning and is ignored`() {
195142
val rnOptions =
@@ -207,24 +154,4 @@ class RNSentryProfilingOptionsTest {
207154
assertFalse(options.isStartProfilerOnAppStart)
208155
verify(logger, times(1)).log(eq(SentryLevel.WARNING), anyString())
209156
}
210-
211-
@Test
212-
fun `unknown lifecycle string is silently ignored without warning`() {
213-
val rnOptions =
214-
JavaOnlyMap.of(
215-
"_experiments",
216-
JavaOnlyMap.of(
217-
"profilingOptions",
218-
JavaOnlyMap.of("lifecycle", "not-a-real-mode"),
219-
),
220-
)
221-
val options = SentryAndroidOptions()
222-
223-
RNSentryStart.getSentryAndroidOptions(options, rnOptions, logger)
224-
225-
// Implementation only logs a warning for type mismatches, not unknown string values.
226-
// Lifecycle stays at the default.
227-
assertEquals(ProfileLifecycle.MANUAL, options.profileLifecycle)
228-
verify(logger, never()).log(eq(SentryLevel.WARNING), anyString())
229-
}
230157
}

‎packages/core/RNSentryCocoaTester/RNSentryCocoaTesterTests/RNSentryTests.m‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -644,7 +644,7 @@ - (void)testStartWithDictionaryInstallsConfigureProfilingFromExperimentsProfilin
644644
SentryProfileOptions *probe = [[SentryProfileOptions alloc] init];
645645
actualOptions.configureProfiling(probe);
646646
XCTAssertEqual(probe.sessionSampleRate, 1.0f);
647-
XCTAssertEqual(probe.lifecycle, SentryProfileLifecycleTrace);
647+
XCTAssertEqual(probe.lifecycle, SentryProfileLifecycleManual);
648648
XCTAssertTrue(probe.profileAppStarts);
649649
}
650650

@@ -673,7 +673,7 @@ - (void)testStartCreateOptionsWithDictionaryProfilingOptionsInstallsConfigurePro
673673
SentryProfileOptions *probe = [[SentryProfileOptions alloc] init];
674674
actualOptions.configureProfiling(probe);
675675
XCTAssertEqual(probe.sessionSampleRate, 1.0f);
676-
XCTAssertEqual(probe.lifecycle, SentryProfileLifecycleTrace);
676+
XCTAssertEqual(probe.lifecycle, SentryProfileLifecycleManual);
677677
XCTAssertTrue(probe.profileAppStarts);
678678
}
679679

‎packages/core/android/src/main/java/io/sentry/react/RNSentryModuleImpl.java‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import android.content.pm.PackageManager;
1212
import android.content.res.AssetManager;
1313
import android.net.Uri;
14+
import android.os.Process;
1415
import android.util.SparseIntArray;
1516
import androidx.annotation.VisibleForTesting;
1617
import androidx.core.app.FrameMetricsAggregator;
@@ -556,6 +557,32 @@ public void flushReplay(Promise promise) {
556557
}
557558
}
558559

560+
public void startProfiler(Promise promise) {
561+
try {
562+
Sentry.startProfiler();
563+
final SentryId profilerId =
564+
Sentry.getCurrentScopes().getOptions().getContinuousProfiler().getProfilerId();
565+
promise.resolve(SentryId.EMPTY_ID.equals(profilerId) ? null : profilerId.toString());
566+
} catch (Throwable e) { // NOPMD - degrade at the bridge boundary, never crash the host app
567+
logger.log(SentryLevel.ERROR, "Failed to start the profiler", e);
568+
promise.reject("SentryReactNative", e.getMessage(), e);
569+
}
570+
}
571+
572+
public String getCurrentThreadId() {
573+
return String.valueOf(Process.myTid());
574+
}
575+
576+
public void stopProfiler(Promise promise) {
577+
try {
578+
Sentry.stopProfiler();
579+
promise.resolve(null);
580+
} catch (Throwable e) { // NOPMD - degrade at the bridge boundary, never crash the host app
581+
logger.log(SentryLevel.ERROR, "Failed to stop the profiler", e);
582+
promise.reject("SentryReactNative", e.getMessage(), e);
583+
}
584+
}
585+
559586
public void registerReplayTraceId(String traceId) {
560587
// Forward a trace id seen on a sent event to Session Replay so it lands in
561588
// the current segment's `trace_ids`. The controller owns dedup, the

‎packages/core/android/src/main/java/io/sentry/react/RNSentryStart.java‎

Lines changed: 2 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -318,22 +318,8 @@ private static void configureAndroidProfiling(
318318
}
319319
}
320320

321-
// Set profiling lifecycle mode
322-
if (profilingOptions.hasKey("lifecycle")) {
323-
if (profilingOptions.getType("lifecycle") == ReadableType.String) {
324-
final String lifecycle = profilingOptions.getString("lifecycle");
325-
if ("manual".equalsIgnoreCase(lifecycle)) {
326-
options.setProfileLifecycle(ProfileLifecycle.MANUAL);
327-
logger.log(SentryLevel.INFO, "UI Profile Lifecycle set to MANUAL");
328-
} else if ("trace".equalsIgnoreCase(lifecycle)) {
329-
options.setProfileLifecycle(ProfileLifecycle.TRACE);
330-
logger.log(SentryLevel.INFO, "UI Profile Lifecycle set to TRACE");
331-
}
332-
} else {
333-
logger.log(
334-
SentryLevel.WARNING, "UI Profiling lifecycle must be a string, ignoring invalid value");
335-
}
336-
}
321+
// Native tracing is off, so JS drives both lifecycles through startProfiler/stopProfiler.
322+
options.setProfileLifecycle(ProfileLifecycle.MANUAL);
337323

338324
// Set start on app start
339325
if (profilingOptions.hasKey("startOnAppStart")) {

‎packages/core/android/src/newarch/java/io/sentry/react/RNSentryModule.java‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,21 @@ public void flushReplay(Promise promise) {
234234
this.impl.flushReplay(promise);
235235
}
236236

237+
@Override
238+
public void startProfiler(Promise promise) {
239+
this.impl.startProfiler(promise);
240+
}
241+
242+
@Override
243+
public String getCurrentThreadId() {
244+
return this.impl.getCurrentThreadId();
245+
}
246+
247+
@Override
248+
public void stopProfiler(Promise promise) {
249+
this.impl.stopProfiler(promise);
250+
}
251+
237252
@Override
238253
public void registerReplayTraceId(String traceId) {
239254
this.impl.registerReplayTraceId(traceId);

‎packages/core/android/src/oldarch/java/io/sentry/react/RNSentryModule.java‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,21 @@ public void flushReplay(Promise promise) {
234234
this.impl.flushReplay(promise);
235235
}
236236

237+
@ReactMethod
238+
public void startProfiler(Promise promise) {
239+
this.impl.startProfiler(promise);
240+
}
241+
242+
@ReactMethod(isBlockingSynchronousMethod = true)
243+
public String getCurrentThreadId() {
244+
return this.impl.getCurrentThreadId();
245+
}
246+
247+
@ReactMethod
248+
public void stopProfiler(Promise promise) {
249+
this.impl.stopProfiler(promise);
250+
}
251+
237252
@ReactMethod
238253
public void registerReplayTraceId(String traceId) {
239254
this.impl.registerReplayTraceId(traceId);

‎packages/core/etc/sentry-react-native.api.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ import { OpenAiClient } from '@sentry/core';
7676
import { OpenAiOptions } from '@sentry/core';
7777
import type { Options } from '@sentry/core';
7878
import { Profiler } from '@sentry/react';
79+
import { profiler } from '@sentry/core';
7980
import * as React_2 from 'react';
8081
import { replayIntegration } from '@sentry/react';
8182
import type { ReplayRecordingMode } from '@sentry/core';
@@ -826,6 +827,8 @@ export const primitiveTagIntegration: () => Integration;
826827

827828
export { Profiler }
828829

830+
export { profiler }
831+
829832
// @public
830833
export type ProfilingLifecycle = 'trace' | 'manual';
831834

@@ -1276,6 +1279,9 @@ export interface TurboModuleContextOptions {
12761279
slowCallThresholdMs?: number;
12771280
}
12781281

1282+
// @public
1283+
export const uiProfilingIntegration: () => Integration;
1284+
12791285
// @public (undocumented)
12801286
export const Unmask: HostComponent<ViewProps> | React_2.ComponentType<ViewProps>;
12811287

‎packages/core/ios/RNSentry.mm‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#import "RNSentry.h"
22
#import "RNSentryTimeToDisplay.h"
33
#import <dlfcn.h>
4+
#import <pthread.h>
45

56
#if __has_include(<React/RCTConvert.h>)
67
# import <React/RCTConvert.h>
@@ -1216,6 +1217,37 @@ + (BOOL)isPathUnderAllowedRootsForTesting:(NSString *)path
12161217
#endif
12171218
}
12181219

1220+
// sentry-cocoa has no public API for the current profiler id, so this resolves nil.
1221+
RCT_EXPORT_METHOD(
1222+
startProfiler : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject)
1223+
{
1224+
@try {
1225+
[SentrySDKWrapper startProfiler];
1226+
resolve(nil);
1227+
} @catch (NSException *exception) {
1228+
NSLog(@"[RNSentry] Failed to call startProfiler: %@", exception);
1229+
reject(@"SentryReactNative", exception.reason, nil);
1230+
}
1231+
}
1232+
1233+
// sentry-cocoa profiles identify threads by their Mach thread port.
1234+
RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(NSString *, getCurrentThreadId)
1235+
{
1236+
return [NSString stringWithFormat:@"%u", pthread_mach_thread_np(pthread_self())];
1237+
}
1238+
1239+
RCT_EXPORT_METHOD(
1240+
stopProfiler : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject)
1241+
{
1242+
@try {
1243+
[SentrySDKWrapper stopProfiler];
1244+
resolve(nil);
1245+
} @catch (NSException *exception) {
1246+
NSLog(@"[RNSentry] Failed to call stopProfiler: %@", exception);
1247+
reject(@"SentryReactNative", exception.reason, nil);
1248+
}
1249+
}
1250+
12191251
RCT_EXPORT_METHOD(
12201252
crashedLastRun : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject)
12211253
{

‎packages/core/ios/RNSentryExperimentalOptions.m‎

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -46,17 +46,8 @@ + (void)configureProfilingWithOptions:(NSDictionary *)profilingOptions
4646
profiling.sessionSampleRate);
4747
}
4848

49-
// Set lifecycle mode
50-
NSString *lifecycle = profilingOptions[@"lifecycle"];
51-
if ([lifecycle isKindOfClass:[NSString class]]) {
52-
if ([lifecycle caseInsensitiveCompare:@"manual"] == NSOrderedSame) {
53-
profiling.lifecycle = SentryProfileLifecycleManual;
54-
NSLog(@"Sentry: UI Profiling Lifecycle set to MANUAL");
55-
} else if ([lifecycle caseInsensitiveCompare:@"trace"] == NSOrderedSame) {
56-
profiling.lifecycle = SentryProfileLifecycleTrace;
57-
NSLog(@"Sentry: UI Profiling Lifecycle set to TRACE");
58-
}
59-
}
49+
// Native tracing is off, so JS drives both lifecycles through startProfiler/stopProfiler.
50+
profiling.lifecycle = SentryProfileLifecycleManual;
6051

6152
// Set profile app starts
6253
id startOnAppStart = profilingOptions[@"startOnAppStart"];

0 commit comments

Comments
 (0)