Skip to content

Commit 40929e9

Browse files
fix(android): Persist the non-terminating session synchronously
Deferring the write to the executor service meant the unhandled marker could be lost if the process died before the task drained, which is the guarantee this path exists for. It also let a queued snapshot land after the session was ended or replaced, rewriting an already-sent session or overwriting a newer current session, both of which surface as a duplicated session on the next launch. Writing under the scope's session lock closes that window, since every scope-side rotation takes the same lock. Also narrow captureEnvelope's blanket catch (Throwable) to the two checked exceptions actually thrown there: Exception from eventStateOf, whose getEvent reads through a Callable, and IOException from SentryEnvelopeItem.fromSession. Everything else in that method already has its own boundary catch in Scopes. Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent 10e6545 commit 40929e9

2 files changed

Lines changed: 43 additions & 56 deletions

File tree

‎sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java‎

Lines changed: 41 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@
4141
import java.util.List;
4242
import java.util.Locale;
4343
import java.util.Map;
44-
import java.util.concurrent.RejectedExecutionException;
4544
import java.util.concurrent.atomic.AtomicReference;
4645
import org.jetbrains.annotations.ApiStatus;
4746
import org.jetbrains.annotations.NotNull;
@@ -175,39 +174,45 @@ public static SentryId captureEnvelope(
175174
return null;
176175
}
177176

177+
final @NotNull ISerializer serializer = options.getSerializer();
178+
final @NotNull EnvelopeEventState eventState;
178179
try {
179-
final @NotNull ISerializer serializer = options.getSerializer();
180-
final @NotNull EnvelopeEventState eventState = eventStateOf(envelope, serializer);
180+
eventState = eventStateOf(envelope, serializer);
181+
} catch (Exception e) {
182+
// getEvent reads through a Callable, whose call() declares Exception
183+
options.getLogger().log(SentryLevel.ERROR, "Failed to inspect envelope events", e);
184+
return null;
185+
}
181186

182-
final @NotNull List<SentryEnvelopeItem> envelopeItems = new ArrayList<>();
183-
for (SentryEnvelopeItem item : envelope.getItems()) {
184-
envelopeItems.add(item);
185-
}
187+
final @NotNull List<SentryEnvelopeItem> envelopeItems = new ArrayList<>();
188+
for (SentryEnvelopeItem item : envelope.getItems()) {
189+
envelopeItems.add(item);
190+
}
186191

187-
// update session and add it to envelope if necessary
188-
final @Nullable Session.State status =
189-
eventState == EnvelopeEventState.UNHANDLED ? Session.State.Crashed : null;
190-
final @Nullable Session session =
191-
updateSession(scopes, options, status, eventState != EnvelopeEventState.NONE);
192-
if (session != null) {
193-
final SentryEnvelopeItem sessionItem = SentryEnvelopeItem.fromSession(serializer, session);
194-
envelopeItems.add(sessionItem);
195-
deleteCurrentSessionFile(
196-
options,
197-
// should be sync if going to crash or already not a main thread
198-
!maybeStartNewSession || !scopes.getOptions().getThreadChecker().isMainThread());
199-
if (maybeStartNewSession) {
200-
scopes.startSession();
201-
}
192+
// update session and add it to envelope if necessary
193+
final @Nullable Session.State status =
194+
eventState == EnvelopeEventState.UNHANDLED ? Session.State.Crashed : null;
195+
final @Nullable Session session =
196+
updateSession(scopes, options, status, eventState != EnvelopeEventState.NONE);
197+
if (session != null) {
198+
try {
199+
envelopeItems.add(SentryEnvelopeItem.fromSession(serializer, session));
200+
} catch (IOException e) {
201+
options.getLogger().log(SentryLevel.ERROR, "Failed to add session to envelope", e);
202+
return null;
203+
}
204+
deleteCurrentSessionFile(
205+
options,
206+
// should be sync if going to crash or already not a main thread
207+
!maybeStartNewSession || !scopes.getOptions().getThreadChecker().isMainThread());
208+
if (maybeStartNewSession) {
209+
scopes.startSession();
202210
}
203-
204-
final SentryEnvelope repackagedEnvelope =
205-
new SentryEnvelope(envelope.getHeader(), envelopeItems);
206-
return scopes.captureEnvelope(repackagedEnvelope);
207-
} catch (Throwable t) {
208-
options.getLogger().log(SentryLevel.ERROR, "Failed to capture envelope", t);
209211
}
210-
return null;
212+
213+
final SentryEnvelope repackagedEnvelope =
214+
new SentryEnvelope(envelope.getHeader(), envelopeItems);
215+
return scopes.captureEnvelope(repackagedEnvelope);
211216
}
212217

213218
/**
@@ -262,7 +267,11 @@ public static SentryId captureEnvelopeNonTerminating(final @NotNull byte[] envel
262267
}
263268

264269
/**
265-
* Flags and persists the current session for a non-terminating hybrid error.
270+
* Flags the current session for a non-terminating hybrid error and persists it before returning,
271+
* so the marker survives an immediate process death.
272+
*
273+
* <p>The write stays inside {@code withSession}: the scope's session lock is what keeps the
274+
* session from being ended or replaced mid-write.
266275
*
267276
* @param unhandled {@code true} if the error was unhandled ({@code mechanism.handled=false})
268277
*/
@@ -287,32 +296,12 @@ private static void updateSessionNonTerminating(final boolean unhandled) {
287296
unhandled
288297
? session.recordNonTerminatingUnhandledError()
289298
: session.update(null, null, true, null);
290-
if (recorded) {
291-
schedulePersistSession(options, session.clone());
299+
if (recorded && options.getEnvelopeDiskCache() instanceof EnvelopeCache) {
300+
((EnvelopeCache) options.getEnvelopeDiskCache()).persistCurrentSession(session);
292301
}
293302
}));
294303
}
295304

296-
/**
297-
* This function is mostly called from Flutter where capturing envelope is run in a background
298-
* thread.
299-
*
300-
* <p>Nonetheless we should run this in the same executor service as the deleteCurrentSessionFile
301-
* function for consistency.
302-
*/
303-
private static void schedulePersistSession(
304-
final @NotNull SentryOptions options, final @NotNull Session session) {
305-
if (!(options.getEnvelopeDiskCache() instanceof EnvelopeCache)) {
306-
return;
307-
}
308-
final @NotNull EnvelopeCache cache = (EnvelopeCache) options.getEnvelopeDiskCache();
309-
try {
310-
options.getExecutorService().submit(() -> cache.persistCurrentSession(session));
311-
} catch (RejectedExecutionException e) {
312-
options.getLogger().log(WARNING, "Submission of session persisting rejected.", e);
313-
}
314-
}
315-
316305
/** What the events inside an envelope amount to, from the session's point of view. */
317306
private enum EnvelopeEventState {
318307
/** No event carried an exception. */

‎sentry-android-core/src/test/java/io/sentry/android/core/InternalSentrySdkTest.kt‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@ import io.sentry.protocol.Contexts
3030
import io.sentry.protocol.Mechanism
3131
import io.sentry.protocol.SentryId
3232
import io.sentry.protocol.User
33-
import io.sentry.test.ImmediateExecutorService
3433
import io.sentry.test.createTestScopes
3534
import io.sentry.transport.ITransport
3635
import io.sentry.transport.RateLimiter
@@ -62,8 +61,6 @@ class InternalSentrySdkTest {
6261
initForTest(context) { options ->
6362
this@Fixture.options = options
6463
options.dsn = "https://key@host/proj"
65-
// the non-terminating path persists the session off the calling thread
66-
options.executorService = ImmediateExecutorService()
6764
options.setTransportFactory { _, _ ->
6865
object : ITransport {
6966
override fun close(isRestarting: Boolean) {
@@ -509,7 +506,8 @@ class InternalSentrySdkTest {
509506
assertThat(scopeSession.get().hasNonTerminatingUnhandledError()).isTrue()
510507
assertThat(scopeSession.get().sessionId).isEqualTo(originalSid.get())
511508

512-
// and it is persisted so the flag survives process death
509+
// and it is persisted so the flag survives process death. The fixture leaves the real executor
510+
// service in place, so this only holds if the write happened on the calling thread.
513511
val sessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!)
514512
val persistedSession =
515513
fixture.options.serializer.deserialize(sessionFile.reader(), Session::class.java)!!

0 commit comments

Comments
 (0)