Skip to content

Commit f3997a1

Browse files
antonisclaude
andauthored
fix(android): Prevent fatal 'JavaCallback was already settled' crash from getNewScreenTimeToDisplay (#6722)
* fix(android): Prevent fatal 'JavaCallback was already settled' crash from getNewScreenTimeToDisplay `RNSentryTimeToDisplay.getTimeToDisplay` settles the promise from a deferred Choreographer frame callback. Under rapid navigation the bridge callback backing the promise can already have been settled/invalidated by the runtime by the time the frame callback runs (on Expo bridgeless this surfaces as "JavaCallback was already settled"). Because the settle happened inside the frame callback, the throw was uncaught and reached the host app as a fatal crash. Route every settle through guarded helpers that settle at most once and swallow any settle failure (logging at WARNING), so a late/duplicate settle drops the time-to-display measurement instead of crashing the app. Shared impl, so this covers both the old and new architecture. Fixes #6709 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * docs(changelog): Reference PR link for the TTID crash fix Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * refactor(android): Use coded reject overload for TTID measurement failures Switch the null-cause branch of rejectSafely from the deprecated reject(String) overload to reject(code, message) so JS receives a specific error code ("SentryTimeToDisplay") instead of the generic "EUNSPECIFIED". Update the affected tests to match the two-arg overload. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * Use explicit error code for TTID promise rejections --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
1 parent aecf0c8 commit f3997a1

4 files changed

Lines changed: 218 additions & 11 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
2828
### Fixes
2929
30+
- Prevent a fatal `JavaCallback was already settled` crash from `getNewScreenTimeToDisplay` under rapid navigation on Android ([#6722](https://github.com/getsentry/sentry-react-native/pull/6722))
3031
- Mask React Native `<Image>` in Session Replay on the iOS New Architecture when `maskAllImages` is enabled ([#6726](https://github.com/getsentry/sentry-react-native/pull/6726))
3132
- Background root spans (app-start, expo-updates) no longer overwrite the native propagation context of an active navigation trace ([#6720](https://github.com/getsentry/sentry-react-native/pull/6720))
3233
- Honor the host app's pinned `ndkVersion` on Android instead of letting AGP download its own default NDK for the module's native code ([#6724](https://github.com/getsentry/sentry-react-native/pull/6724))

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

Lines changed: 151 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,30 @@
11
package io.sentry.react
22

3+
import android.os.Looper
4+
import com.facebook.react.bridge.Promise
5+
import io.sentry.ILogger
6+
import io.sentry.SentryDate
7+
import io.sentry.SentryDateProvider
8+
import io.sentry.SentryLevel
39
import org.junit.Assert.assertEquals
410
import org.junit.Assert.assertNotNull
511
import org.junit.Assert.assertNull
612
import org.junit.Before
713
import org.junit.Test
814
import org.junit.runner.RunWith
9-
import org.junit.runners.JUnit4
15+
import org.mockito.kotlin.any
16+
import org.mockito.kotlin.doThrow
17+
import org.mockito.kotlin.eq
18+
import org.mockito.kotlin.mock
19+
import org.mockito.kotlin.never
20+
import org.mockito.kotlin.times
21+
import org.mockito.kotlin.verify
22+
import org.mockito.kotlin.whenever
23+
import org.robolectric.RobolectricTestRunner
24+
import org.robolectric.Shadows.shadowOf
25+
import java.util.concurrent.atomic.AtomicBoolean
1026

11-
@RunWith(JUnit4::class)
27+
@RunWith(RobolectricTestRunner::class)
1228
class RNSentryTimeToDisplayTest {
1329
companion object {
1430
val TEST_ID = "test-id"
@@ -45,4 +61,137 @@ class RNSentryTimeToDisplayTest {
4561
assertNotNull(secondOldestEntry)
4662
assertNotNull(newestEntry)
4763
}
64+
65+
@Test
66+
fun `resolveSafely settles the promise only once`() {
67+
val promise = mock<Promise>()
68+
val logger = mock<ILogger>()
69+
val settled = AtomicBoolean(false)
70+
71+
RNSentryTimeToDisplay.resolveSafely(promise, settled, 1.0, logger)
72+
RNSentryTimeToDisplay.resolveSafely(promise, settled, 2.0, logger)
73+
74+
verify(promise, times(1)).resolve(1.0)
75+
verify(promise, never()).resolve(2.0)
76+
}
77+
78+
@Test
79+
fun `resolveSafely does not throw when the bridge callback was already settled`() {
80+
val promise = mock<Promise>()
81+
val logger = mock<ILogger>()
82+
val settled = AtomicBoolean(false)
83+
// Simulate the runtime having already settled/invalidated the bridge callback, as happens
84+
// on Expo bridgeless under rapid navigation ("JavaCallback was already settled"). (#6709)
85+
doThrow(RuntimeException("JavaCallback was already settled. Cannot invoke it again"))
86+
.whenever(promise)
87+
.resolve(any())
88+
89+
// Must not propagate - a throw here reaches the host app as a fatal uncaught exception.
90+
RNSentryTimeToDisplay.resolveSafely(promise, settled, 1.0, logger)
91+
92+
verify(logger).log(eq(SentryLevel.WARNING), any<String>(), any<Throwable>())
93+
}
94+
95+
@Test
96+
fun `rejectSafely is a no-op once the promise has been resolved`() {
97+
val promise = mock<Promise>()
98+
val logger = mock<ILogger>()
99+
val settled = AtomicBoolean(false)
100+
101+
RNSentryTimeToDisplay.resolveSafely(promise, settled, 1.0, logger)
102+
RNSentryTimeToDisplay.rejectSafely(promise, settled, "boom", null, logger)
103+
104+
verify(promise, times(1)).resolve(1.0)
105+
verify(promise, never()).reject(any<String>(), any<String>())
106+
}
107+
108+
@Test
109+
fun `rejectSafely does not throw when the bridge callback was already settled`() {
110+
val promise = mock<Promise>()
111+
val logger = mock<ILogger>()
112+
val settled = AtomicBoolean(false)
113+
doThrow(RuntimeException("JavaCallback was already settled. Cannot invoke it again"))
114+
.whenever(promise)
115+
.reject(any<String>(), any<String>())
116+
117+
RNSentryTimeToDisplay.rejectSafely(promise, settled, "boom", null, logger)
118+
119+
verify(logger).log(eq(SentryLevel.WARNING), any<String>(), any<Throwable>())
120+
}
121+
122+
@Test
123+
fun `rejectSafely with a cause passes an explicit error code to the coded overload`() {
124+
val promise = mock<Promise>()
125+
val logger = mock<ILogger>()
126+
val settled = AtomicBoolean(false)
127+
val cause = RuntimeException("boom")
128+
129+
RNSentryTimeToDisplay.rejectSafely(promise, settled, "message", cause, logger)
130+
131+
// The code must be the stable "SentryReactNative" identifier, not the descriptive message -
132+
// reject(String, Throwable) would otherwise use the message as the error code.
133+
verify(promise, times(1)).reject(eq("SentryReactNative"), eq("message"), eq(cause))
134+
}
135+
136+
@Test
137+
fun `resolveSafely swallows failures that are not the already-settled case`() {
138+
val promise = mock<Promise>()
139+
val logger = mock<ILogger>()
140+
val settled = AtomicBoolean(false)
141+
// The guard must degrade on any settle failure, not only the literal "already settled"
142+
// message - e.g. a torn-down Catalyst instance - so it can never crash the host app.
143+
doThrow(IllegalStateException("Tried to access a JS module after the React instance was destroyed"))
144+
.whenever(promise)
145+
.resolve(any())
146+
147+
RNSentryTimeToDisplay.resolveSafely(promise, settled, 1.0, logger)
148+
149+
verify(logger).log(eq(SentryLevel.WARNING), any<String>(), any<Throwable>())
150+
}
151+
152+
// End-to-end tests that drive the real getTimeToDisplay path (main-thread Handler post +
153+
// Choreographer frame callback), so the crashing production code - not just the helpers - is
154+
// covered.
155+
156+
private fun mockDateProvider(nanoTimestamp: Long): SentryDateProvider {
157+
val date = mock<SentryDate>()
158+
whenever(date.nanoTimestamp()).thenReturn(nanoTimestamp)
159+
val dateProvider = mock<SentryDateProvider>()
160+
whenever(dateProvider.now()).thenReturn(date)
161+
return dateProvider
162+
}
163+
164+
@Test
165+
fun `getTimeToDisplay resolves once with the frame timestamp in seconds`() {
166+
val promise = mock<Promise>()
167+
val logger = mock<ILogger>()
168+
val dateProvider = mockDateProvider(2_000_000_000L) // 2s expressed in nanoseconds
169+
170+
RNSentryTimeToDisplay.getTimeToDisplay(promise, dateProvider, logger)
171+
172+
// Run the posted main-thread runnable and the Choreographer frame callback.
173+
shadowOf(Looper.getMainLooper()).idle()
174+
175+
verify(promise, times(1)).resolve(2.0)
176+
verify(promise, never()).reject(any<String>(), any<String>())
177+
}
178+
179+
@Test
180+
fun `getTimeToDisplay does not crash the host app when the promise was already settled`() {
181+
val promise = mock<Promise>()
182+
val logger = mock<ILogger>()
183+
val dateProvider = mockDateProvider(2_000_000_000L)
184+
// Reproduce the reported crash: the bridge callback backing the promise has already been
185+
// settled by the runtime, so resolving it from the frame callback throws. (#6709)
186+
doThrow(RuntimeException("JavaCallback was already settled. Cannot invoke it again"))
187+
.whenever(promise)
188+
.resolve(any())
189+
190+
RNSentryTimeToDisplay.getTimeToDisplay(promise, dateProvider, logger)
191+
192+
// Before the fix this propagated out of the frame callback as a fatal uncaught exception.
193+
shadowOf(Looper.getMainLooper()).idle()
194+
195+
verify(logger).log(eq(SentryLevel.WARNING), any<String>(), any<Throwable>())
196+
}
48197
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -934,7 +934,7 @@ private void stopFrameMetricsCollection() {
934934
}
935935

936936
public void getNewScreenTimeToDisplay(Promise promise) {
937-
RNSentryTimeToDisplay.getTimeToDisplay(promise, dateProvider);
937+
RNSentryTimeToDisplay.getTimeToDisplay(promise, dateProvider, logger);
938938
}
939939

940940
private String getProfilingTracesDirPath() {

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

Lines changed: 65 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,15 @@
33
import android.os.Handler;
44
import android.os.Looper;
55
import android.view.Choreographer;
6+
import androidx.annotation.VisibleForTesting;
67
import com.facebook.react.bridge.Promise;
8+
import io.sentry.ILogger;
79
import io.sentry.SentryDate;
810
import io.sentry.SentryDateProvider;
11+
import io.sentry.SentryLevel;
912
import java.util.LinkedHashMap;
1013
import java.util.Map;
14+
import java.util.concurrent.atomic.AtomicBoolean;
1115
import org.jetbrains.annotations.Nullable;
1216

1317
public final class RNSentryTimeToDisplay {
@@ -48,13 +52,25 @@ public static void putTimeToDisplayFor(String screenId, Double value) {
4852
screenIdToRenderDuration.put(screenId, value);
4953
}
5054

51-
public static void getTimeToDisplay(Promise promise, SentryDateProvider dateProvider) {
52-
Looper mainLooper = Looper.getMainLooper();
55+
public static void getTimeToDisplay(
56+
Promise promise, SentryDateProvider dateProvider, ILogger logger) {
57+
// The promise is settled from a deferred Choreographer frame callback. Under rapid
58+
// navigation the bridge callback backing the promise may already have been settled or
59+
// invalidated by the runtime by the time the frame callback runs (on Expo bridgeless this
60+
// surfaces as "JavaCallback was already settled"). Settling it again throws, and because the
61+
// settle happens inside the frame callback the exception is uncaught and reaches the host app
62+
// as a fatal crash. Guard against settling more than once and swallow any settle failure -
63+
// dropping a late time-to-display measurement is the expected degradation here. (#6709)
64+
final AtomicBoolean settled = new AtomicBoolean(false);
5365

66+
Looper mainLooper = Looper.getMainLooper();
5467
if (mainLooper == null) {
55-
promise.reject(
56-
"GetTimeToDisplay is not able to measure the time to display: Main looper not"
57-
+ " available.");
68+
rejectSafely(
69+
promise,
70+
settled,
71+
"GetTimeToDisplay is not able to measure the time to display: Main looper not available.",
72+
null,
73+
logger);
5874
return;
5975
}
6076

@@ -69,11 +85,52 @@ public static void getTimeToDisplay(Promise promise, SentryDateProvider dateProv
6985
choreographer.postFrameCallback(
7086
frameTimeNanos -> {
7187
final SentryDate endDate = dateProvider.now();
72-
promise.resolve(endDate.nanoTimestamp() / 1e9);
88+
resolveSafely(promise, settled, endDate.nanoTimestamp() / 1e9, logger);
7389
});
74-
} catch (Exception exception) {
75-
promise.reject("Failed to receive the instance of Choreographer", exception);
90+
} catch (Throwable exception) { // NOPMD - We don't want to crash the host app
91+
rejectSafely(
92+
promise,
93+
settled,
94+
"Failed to receive the instance of Choreographer",
95+
exception,
96+
logger);
7697
}
7798
});
7899
}
100+
101+
@VisibleForTesting
102+
static void resolveSafely(Promise promise, AtomicBoolean settled, double value, ILogger logger) {
103+
if (!settled.compareAndSet(false, true)) {
104+
return;
105+
}
106+
try {
107+
promise.resolve(value);
108+
} catch (Throwable t) { // NOPMD - We don't want to crash the host app
109+
logger.log(SentryLevel.WARNING, "Failed to resolve time to display measurement.", t);
110+
}
111+
}
112+
113+
@VisibleForTesting
114+
static void rejectSafely(
115+
Promise promise,
116+
AtomicBoolean settled,
117+
String message,
118+
@Nullable Throwable cause,
119+
ILogger logger) {
120+
if (!settled.compareAndSet(false, true)) {
121+
return;
122+
}
123+
try {
124+
// Always pass an explicit error code ("SentryReactNative", matching the rest of the module)
125+
// so JS receives a stable code. Without a code, reject(String, Throwable) would treat the
126+
// message as the code and reject(String) would fall back to the generic "EUNSPECIFIED".
127+
if (cause != null) {
128+
promise.reject("SentryReactNative", message, cause);
129+
} else {
130+
promise.reject("SentryReactNative", message);
131+
}
132+
} catch (Throwable t) { // NOPMD - We don't want to crash the host app
133+
logger.log(SentryLevel.WARNING, "Failed to reject time to display measurement.", t);
134+
}
135+
}
79136
}

0 commit comments

Comments
 (0)