From 0cea47a47d5114232e764762fadc48c2ad9cc608 Mon Sep 17 00:00:00 2001 From: Roman Zavarnitsyn Date: Fri, 27 Nov 2026 14:12:54 +0100 Subject: [PATCH 01/12] fix(core): Do not move the live session file at init A session written by persistCurrentSession or a SessionStart envelope before the init-time MovePreviousSession task ran was moved to previous_session.json and finalized as the previous session. The early write also overwrote the last run's session. Track whether this process already moved the previous session. The init-time move then skips, and persistCurrentSession moves the old session before it writes. Fixes #6361 Co-Authored-By: Claude --- .../java/io/sentry/cache/EnvelopeCache.java | 38 ++++++++++++++-- .../java/io/sentry/cache/EnvelopeCacheTest.kt | 44 +++++++++++++++++++ 2 files changed, 78 insertions(+), 4 deletions(-) diff --git a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java index d3f473cfbc9..2c0550bc2e5 100644 --- a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java +++ b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java @@ -82,6 +82,13 @@ public class EnvelopeCache extends CacheStrategy implements IEnvelopeCache { */ private @Nullable String lastPersistedSessionId; + /** + * Whether this process already moved the last run's session out of the current session file. + * After that, the current session file holds a session of this process, so the init-time {@link + * #movePreviousSession(File, File)} must not move it. + */ + private boolean previousSessionMoved; + public static @NotNull IEnvelopeCache create(final @NotNull SentryOptions options) { final String cacheDirPath = options.getCacheDirPath(); final int maxCacheItems = options.getMaxCacheItems(); @@ -141,7 +148,7 @@ private boolean storeInternal(final @NotNull SentryEnvelope envelope, final @Not try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { final @Nullable Session startingSession = readSessionFromEnvelope(envelope); if (!isAlreadyPersisted(startingSession)) { - movePreviousSession(currentSessionFile, previousSessionFile); + moveCurrentToPreviousSession(currentSessionFile, previousSessionFile); if (startingSession != null) { writeSessionToDisk(currentSessionFile, startingSession); } @@ -388,9 +395,14 @@ private boolean writeSessionToDisk(final @NotNull File file, final @NotNull Sess @ApiStatus.Internal public void persistCurrentSession(final @NotNull Session session) { try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { - final boolean written = - writeSessionToDisk( - getCurrentSessionFile(directory.getOrCreate().getAbsolutePath()), session); + final String directoryPath = directory.getOrCreate().getAbsolutePath(); + final File currentSessionFile = getCurrentSessionFile(directoryPath); + // this can run before the init-time move, so move the last run's session first instead of + // overwriting it + if (!previousSessionMoved) { + moveCurrentToPreviousSession(currentSessionFile, getPreviousSessionFile(directoryPath)); + } + final boolean written = writeSessionToDisk(currentSessionFile, session); // a failed write truncates the file, so there is no good copy left to protect lastPersistedSessionId = written ? session.getSessionId() : null; } @@ -506,9 +518,27 @@ public void flushPreviousSession() { previousSessionLatch.countDown(); } + /** + * Moves the last run's session to the previous session file. Does nothing if this process already + * did that, because the current session file then holds the live session. + */ public void movePreviousSession( final @NotNull File currentSessionFile, final @NotNull File previousSessionFile) { try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { + if (previousSessionMoved) { + options + .getLogger() + .log(DEBUG, "Previous session was already moved, not moving the live session."); + return; + } + moveCurrentToPreviousSession(currentSessionFile, previousSessionFile); + } + } + + private void moveCurrentToPreviousSession( + final @NotNull File currentSessionFile, final @NotNull File previousSessionFile) { + try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { + previousSessionMoved = true; if (!currentSessionFile.exists()) { return; } diff --git a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt index 0cc2c968195..baca68da93c 100644 --- a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt +++ b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt @@ -821,4 +821,48 @@ class EnvelopeCacheTest { assertTrue(previousSessionFile.exists()) assertEquals("current session content", previousSessionFile.readText()) } + + @Test + fun `persistCurrentSession before the init-time move keeps both sessions in place`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) + currentSessionFile.writeText("session content from last run") + val liveSession = createSession() + + // a hybrid SDK persists the live session before the executor runs MovePreviousSession + cache.persistCurrentSession(liveSession) + cache.movePreviousSession(currentSessionFile, previousSessionFile) + + assertThat(previousSessionFile.readText()).isEqualTo("session content from last run") + val persistedCurrent = + fixture.options.serializer.deserialize( + currentSessionFile.bufferedReader(), + Session::class.java, + )!! + assertThat(persistedCurrent.sessionId).isEqualTo(liveSession.sessionId) + } + + @Test + fun `SessionStart before the init-time move keeps both sessions in place`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) + currentSessionFile.writeText("session content from last run") + val liveSession = createSession() + + cache.storeEnvelope( + SentryEnvelope.from(fixture.options.serializer, liveSession, null), + HintUtils.createWithTypeCheckHint(SessionStartHint()), + ) + cache.movePreviousSession(currentSessionFile, previousSessionFile) + + assertThat(previousSessionFile.readText()).isEqualTo("session content from last run") + val persistedCurrent = + fixture.options.serializer.deserialize( + currentSessionFile.bufferedReader(), + Session::class.java, + )!! + assertThat(persistedCurrent.sessionId).isEqualTo(liveSession.sessionId) + } } From 8c88c26824defe09bc5fa07bafa3cf9b84e769db Mon Sep 17 00:00:00 2001 From: Roman Zavarnitsyn Date: Fri, 27 Nov 2026 14:13:32 +0100 Subject: [PATCH 02/12] changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 482f613041b..1948d3bc63b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ - Android: Out-of-process crash reporting now supports Android 5.0 (API level 21) and later, previously required Android 11 (API level 30) ([#6614](https://github.com/getsentry/sentry-java/pull/6614)) - Android profiling: Uploading a Perfetto profile chunk now keeps the trace in memory once instead of up to three times, lowering peak memory use for traces up to 50 MB ([#6743](https://github.com/getsentry/sentry-java/pull/6743)) - Stop a transaction's CPU and memory collection 30 seconds after it starts even when the device's wall clock changes in between ([#6739](https://github.com/getsentry/sentry-java/pull/6739)) +- Hybrid SDKs: A session written right after `Sentry.init` is no longer sent as the previous run's session while it is still in progress, and the previous run's session is no longer lost ([#6800](https://github.com/getsentry/sentry-java/pull/6800)) ### Dependencies From 5f85144bd16d80ecd49ed843100e120bf32a3a30 Mon Sep 17 00:00:00 2001 From: Roman Zavarnitsyn Date: Fri, 27 Nov 2026 14:24:47 +0100 Subject: [PATCH 03/12] fix(core): Retry the previous session move after re-init or failed move The previous-session-moved flag lived as long as the cache, so a re-init that reused the cache skipped moving the last init's session. It was also set before the rename, so a failed rename skipped the retry and persistCurrentSession overwrote the last run's session. Reset the flag on every init, set it only when the old file is gone, and skip the live write in persistCurrentSession if the move failed. Co-Authored-By: Claude --- sentry/api/sentry.api | 1 + sentry/src/main/java/io/sentry/Sentry.java | 5 +++ .../java/io/sentry/cache/EnvelopeCache.java | 33 +++++++++++--- sentry/src/test/java/io/sentry/SentryTest.kt | 17 ++++++++ .../java/io/sentry/cache/EnvelopeCacheTest.kt | 43 +++++++++++++++++++ 5 files changed, 94 insertions(+), 5 deletions(-) diff --git a/sentry/api/sentry.api b/sentry/api/sentry.api index 8dd75b41add..b89e395a524 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -5034,6 +5034,7 @@ public class io/sentry/cache/EnvelopeCache : io/sentry/cache/IEnvelopeCache { public fun iterator ()Ljava/util/Iterator; public fun movePreviousSession (Ljava/io/File;Ljava/io/File;)V public fun persistCurrentSession (Lio/sentry/Session;)V + public fun resetPreviousSessionMove ()V public fun store (Lio/sentry/SentryEnvelope;Lio/sentry/Hint;)V public fun storeEnvelope (Lio/sentry/SentryEnvelope;Lio/sentry/Hint;)Z public fun waitPreviousSessionFlush ()Z diff --git a/sentry/src/main/java/io/sentry/Sentry.java b/sentry/src/main/java/io/sentry/Sentry.java index 8112cf0ee8b..1198ee0878e 100644 --- a/sentry/src/main/java/io/sentry/Sentry.java +++ b/sentry/src/main/java/io/sentry/Sentry.java @@ -544,6 +544,11 @@ private static void handleAppStartProfilingConfig( @SuppressWarnings("FutureReturnValueIgnored") private static void movePreviousSession(final @NotNull SentryOptions options) { + // a re-init can reuse the cache of the last init, so let this init move the session file again + final IEnvelopeCache cache = options.getEnvelopeDiskCache(); + if (cache instanceof EnvelopeCache) { + ((EnvelopeCache) cache).resetPreviousSessionMove(); + } // enqueue a task to move previous unfinished session to its own file try { options.getExecutorService().submit(new MovePreviousSession(options)); diff --git a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java index 2c0550bc2e5..7896c462f9a 100644 --- a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java +++ b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java @@ -149,8 +149,9 @@ private boolean storeInternal(final @NotNull SentryEnvelope envelope, final @Not final @Nullable Session startingSession = readSessionFromEnvelope(envelope); if (!isAlreadyPersisted(startingSession)) { moveCurrentToPreviousSession(currentSessionFile, previousSessionFile); - if (startingSession != null) { - writeSessionToDisk(currentSessionFile, startingSession); + if (startingSession != null && writeSessionToDisk(currentSessionFile, startingSession)) { + // even if the move failed, the file now holds this session and not the last run's + previousSessionMoved = true; } } } @@ -401,6 +402,13 @@ public void persistCurrentSession(final @NotNull Session session) { // overwriting it if (!previousSessionMoved) { moveCurrentToPreviousSession(currentSessionFile, getPreviousSessionFile(directoryPath)); + if (!previousSessionMoved) { + options + .getLogger() + .log(WARNING, "Previous session could not be moved, not overwriting it."); + lastPersistedSessionId = null; + return; + } } final boolean written = writeSessionToDisk(currentSessionFile, session); // a failed write truncates the file, so there is no good copy left to protect @@ -519,8 +527,21 @@ public void flushPreviousSession() { } /** - * Moves the last run's session to the previous session file. Does nothing if this process already - * did that, because the current session file then holds the live session. + * Makes the next {@link #movePreviousSession(File, File)} move the current session file again. + * The SDK calls this on every init, because a re-init can reuse this cache while the current + * session file still holds the session of the last initialization. + */ + @ApiStatus.Internal + public void resetPreviousSessionMove() { + try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { + previousSessionMoved = false; + } + } + + /** + * Moves the last run's session to the previous session file. Does nothing if that already + * happened since the last {@link #resetPreviousSessionMove()}, because the current session file + * then holds the live session. */ public void movePreviousSession( final @NotNull File currentSessionFile, final @NotNull File previousSessionFile) { @@ -538,8 +559,8 @@ public void movePreviousSession( private void moveCurrentToPreviousSession( final @NotNull File currentSessionFile, final @NotNull File previousSessionFile) { try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { - previousSessionMoved = true; if (!currentSessionFile.exists()) { + previousSessionMoved = true; return; } @@ -556,6 +577,8 @@ private void moveCurrentToPreviousSession( try { final boolean renamed = currentSessionFile.renameTo(previousSessionFile); + // a failed rename leaves the last run's session in place, so a later move can retry it + previousSessionMoved = renamed; if (!renamed) { options.getLogger().log(WARNING, "Unable to move current session to previous session."); } diff --git a/sentry/src/test/java/io/sentry/SentryTest.kt b/sentry/src/test/java/io/sentry/SentryTest.kt index 24406d541ba..93cd73becc9 100644 --- a/sentry/src/test/java/io/sentry/SentryTest.kt +++ b/sentry/src/test/java/io/sentry/SentryTest.kt @@ -1729,6 +1729,23 @@ class SentryTest { inOrder.verify(mockIntegration).register(any(), any()) } + @Test + fun `init resets the previous session move before queueing it`() { + val cache = mock() + val mockExecutorService = mock() + + initForTest { + it.dsn = dsn + it.cacheDirPath = getTempPath() + it.setEnvelopeDiskCache(cache) + it.executorService = mockExecutorService + } + + val inOrder = inOrder(cache, mockExecutorService) + inOrder.verify(cache).resetPreviousSessionMove() + inOrder.verify(mockExecutorService).submit(any()) + } + @Test fun `init moves previous session to its own file`() { val cacheDir = tmpDir.newFolder().absolutePath diff --git a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt index baca68da93c..25e0d969ee2 100644 --- a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt +++ b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt @@ -843,6 +843,49 @@ class EnvelopeCacheTest { assertThat(persistedCurrent.sessionId).isEqualTo(liveSession.sessionId) } + @Test + fun `init-time move after a reset moves the session of the last initialization`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) + val firstInitSession = createSession() + cache.persistCurrentSession(firstInitSession) + cache.movePreviousSession(currentSessionFile, previousSessionFile) + assertThat(currentSessionFile.exists()).isTrue() + + // a re-init with the same options reuses this cache + cache.resetPreviousSessionMove() + cache.movePreviousSession(currentSessionFile, previousSessionFile) + + assertThat(currentSessionFile.exists()).isFalse() + val persistedPrevious = + fixture.options.serializer.deserialize( + previousSessionFile.bufferedReader(), + Session::class.java, + )!! + assertThat(persistedPrevious.sessionId).isEqualTo(firstInitSession.sessionId) + } + + @Test + fun `failed move in persistCurrentSession keeps the last run's session for a later move`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) + currentSessionFile.writeText("session content from last run") + // a non-empty directory where the previous session file belongs makes the move fail + assertTrue(File(previousSessionFile, "blocker").mkdirs()) + + cache.persistCurrentSession(createSession()) + + assertThat(currentSessionFile.readText()).isEqualTo("session content from last run") + + assertTrue(previousSessionFile.deleteRecursively()) + cache.movePreviousSession(currentSessionFile, previousSessionFile) + + assertThat(currentSessionFile.exists()).isFalse() + assertThat(previousSessionFile.readText()).isEqualTo("session content from last run") + } + @Test fun `SessionStart before the init-time move keeps both sessions in place`() { val cache = fixture.getSUT() From d5ee8c828b515753e212ba862bda6910e853ff2a Mon Sep 17 00:00:00 2001 From: Roman Zavarnitsyn Date: Fri, 27 Nov 2026 15:14:25 +0100 Subject: [PATCH 04/12] ref(core): Drop the previous session move reset on init A re-init only reuses the cache when the same SentryOptions object is passed to Sentry.init again. SentryAndroid.init always creates new options, and no public code on GitHub reuses an options object across inits, so the reset is not worth the extra internal API. Co-Authored-By: Claude --- sentry/api/sentry.api | 1 - sentry/src/main/java/io/sentry/Sentry.java | 5 ---- .../java/io/sentry/cache/EnvelopeCache.java | 17 ++------------ sentry/src/test/java/io/sentry/SentryTest.kt | 17 -------------- .../java/io/sentry/cache/EnvelopeCacheTest.kt | 23 ------------------- 5 files changed, 2 insertions(+), 61 deletions(-) diff --git a/sentry/api/sentry.api b/sentry/api/sentry.api index b89e395a524..8dd75b41add 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -5034,7 +5034,6 @@ public class io/sentry/cache/EnvelopeCache : io/sentry/cache/IEnvelopeCache { public fun iterator ()Ljava/util/Iterator; public fun movePreviousSession (Ljava/io/File;Ljava/io/File;)V public fun persistCurrentSession (Lio/sentry/Session;)V - public fun resetPreviousSessionMove ()V public fun store (Lio/sentry/SentryEnvelope;Lio/sentry/Hint;)V public fun storeEnvelope (Lio/sentry/SentryEnvelope;Lio/sentry/Hint;)Z public fun waitPreviousSessionFlush ()Z diff --git a/sentry/src/main/java/io/sentry/Sentry.java b/sentry/src/main/java/io/sentry/Sentry.java index 1198ee0878e..8112cf0ee8b 100644 --- a/sentry/src/main/java/io/sentry/Sentry.java +++ b/sentry/src/main/java/io/sentry/Sentry.java @@ -544,11 +544,6 @@ private static void handleAppStartProfilingConfig( @SuppressWarnings("FutureReturnValueIgnored") private static void movePreviousSession(final @NotNull SentryOptions options) { - // a re-init can reuse the cache of the last init, so let this init move the session file again - final IEnvelopeCache cache = options.getEnvelopeDiskCache(); - if (cache instanceof EnvelopeCache) { - ((EnvelopeCache) cache).resetPreviousSessionMove(); - } // enqueue a task to move previous unfinished session to its own file try { options.getExecutorService().submit(new MovePreviousSession(options)); diff --git a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java index 7896c462f9a..33a7d66c6e4 100644 --- a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java +++ b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java @@ -527,21 +527,8 @@ public void flushPreviousSession() { } /** - * Makes the next {@link #movePreviousSession(File, File)} move the current session file again. - * The SDK calls this on every init, because a re-init can reuse this cache while the current - * session file still holds the session of the last initialization. - */ - @ApiStatus.Internal - public void resetPreviousSessionMove() { - try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { - previousSessionMoved = false; - } - } - - /** - * Moves the last run's session to the previous session file. Does nothing if that already - * happened since the last {@link #resetPreviousSessionMove()}, because the current session file - * then holds the live session. + * Moves the last run's session to the previous session file. Does nothing if this process already + * did that, because the current session file then holds the live session. */ public void movePreviousSession( final @NotNull File currentSessionFile, final @NotNull File previousSessionFile) { diff --git a/sentry/src/test/java/io/sentry/SentryTest.kt b/sentry/src/test/java/io/sentry/SentryTest.kt index 93cd73becc9..24406d541ba 100644 --- a/sentry/src/test/java/io/sentry/SentryTest.kt +++ b/sentry/src/test/java/io/sentry/SentryTest.kt @@ -1729,23 +1729,6 @@ class SentryTest { inOrder.verify(mockIntegration).register(any(), any()) } - @Test - fun `init resets the previous session move before queueing it`() { - val cache = mock() - val mockExecutorService = mock() - - initForTest { - it.dsn = dsn - it.cacheDirPath = getTempPath() - it.setEnvelopeDiskCache(cache) - it.executorService = mockExecutorService - } - - val inOrder = inOrder(cache, mockExecutorService) - inOrder.verify(cache).resetPreviousSessionMove() - inOrder.verify(mockExecutorService).submit(any()) - } - @Test fun `init moves previous session to its own file`() { val cacheDir = tmpDir.newFolder().absolutePath diff --git a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt index 25e0d969ee2..cf96b1ea491 100644 --- a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt +++ b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt @@ -843,29 +843,6 @@ class EnvelopeCacheTest { assertThat(persistedCurrent.sessionId).isEqualTo(liveSession.sessionId) } - @Test - fun `init-time move after a reset moves the session of the last initialization`() { - val cache = fixture.getSUT() - val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) - val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) - val firstInitSession = createSession() - cache.persistCurrentSession(firstInitSession) - cache.movePreviousSession(currentSessionFile, previousSessionFile) - assertThat(currentSessionFile.exists()).isTrue() - - // a re-init with the same options reuses this cache - cache.resetPreviousSessionMove() - cache.movePreviousSession(currentSessionFile, previousSessionFile) - - assertThat(currentSessionFile.exists()).isFalse() - val persistedPrevious = - fixture.options.serializer.deserialize( - previousSessionFile.bufferedReader(), - Session::class.java, - )!! - assertThat(persistedPrevious.sessionId).isEqualTo(firstInitSession.sessionId) - } - @Test fun `failed move in persistCurrentSession keeps the last run's session for a later move`() { val cache = fixture.getSUT() From 33fc2b671ac9dca5e01aa877196140ef95323fc6 Mon Sep 17 00:00:00 2001 From: Roman Zavarnitsyn Date: Fri, 27 Nov 2026 15:48:33 +0100 Subject: [PATCH 05/12] fix(core): Delete the session file after a failed persist persistCurrentSession moves the last run's session to the previous session file and then writes the live one. If that write fails, it left a truncated session.json, and the next SessionStart moved it over the saved previous session. Delete the truncated file on a failed write. Co-Authored-By: Claude --- .../java/io/sentry/cache/EnvelopeCache.java | 8 ++++++- .../java/io/sentry/cache/EnvelopeCacheTest.kt | 23 ++++++++++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java index 33a7d66c6e4..74cf1b9695f 100644 --- a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java +++ b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java @@ -411,7 +411,13 @@ public void persistCurrentSession(final @NotNull Session session) { } } final boolean written = writeSessionToDisk(currentSessionFile, session); - // a failed write truncates the file, so there is no good copy left to protect + // a failed write truncates the file, so there is no good copy left to protect. Delete it, so + // a later move does not put it over the last run's session in the previous session file. + if (!written && !currentSessionFile.delete()) { + options + .getLogger() + .log(WARNING, "Unable to delete the current session file after a failed write."); + } lastPersistedSessionId = written ? session.getSessionId() : null; } } diff --git a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt index cf96b1ea491..c5745576e8a 100644 --- a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt +++ b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt @@ -227,7 +227,7 @@ class EnvelopeCacheTest { assertTrue(currentSessionFile.delete()) assertTrue(currentSessionFile.mkdir()) cache.persistCurrentSession(newerSession) - assertTrue(currentSessionFile.delete()) + assertThat(currentSessionFile.exists()).isFalse() val delayedStart = createSession(sessionId = sid) val envelope = SentryEnvelope.from(fixture.options.serializer, delayedStart, null) @@ -347,6 +347,27 @@ class EnvelopeCacheTest { verify(serializer).serialize(same(delayedStart), any()) } + @Test + fun `failed persist after the move keeps the last run's session from the next SessionStart`() { + val liveSession = createSession() + val serializer = mock() + whenever(serializer.serialize(same(liveSession), any())) + .thenThrow(RuntimeException("forced ex")) + whenever(serializer.deserialize(any(), eq(Session::class.java))).thenReturn(liveSession) + val cache = fixture.getSUT { options -> options.setSerializer(serializer) } + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) + currentSessionFile.writeText("session content from last run") + + cache.persistCurrentSession(liveSession) + assertThat(currentSessionFile.exists()).isFalse() + + val envelope = SentryEnvelope.from(SentryOptions.empty().serializer, liveSession, null) + cache.storeEnvelope(envelope, HintUtils.createWithTypeCheckHint(SessionStartHint())) + + assertThat(previousSessionFile.readText()).isEqualTo("session content from last run") + } + @Test fun `updates current file on session update and read it back`() { val cache = fixture.getSUT() From cb9213af228e453663b8269fa45c0a5d80ac895d Mon Sep 17 00:00:00 2001 From: Roman Zavarnitsyn Date: Fri, 27 Nov 2026 16:11:19 +0100 Subject: [PATCH 06/12] fix(core): Write the live session even if the previous session move fails Skipping the write only delayed the loss of the last run's session: a rename that fails keeps failing, and the SessionStart path then writes over the old file anyway. Write the live session and mark the move as done once the write succeeds, so the init-time move cannot take it. After a failed write, delete the truncated file only if the move worked. If the move failed, the file can still be the last run's session, so it stays for a later move to retry. Co-Authored-By: Claude --- .../java/io/sentry/cache/EnvelopeCache.java | 17 ++++------ .../java/io/sentry/cache/EnvelopeCacheTest.kt | 34 ++++++++++++++++--- 2 files changed, 37 insertions(+), 14 deletions(-) diff --git a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java index 74cf1b9695f..2b2b6ac8729 100644 --- a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java +++ b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java @@ -402,18 +402,15 @@ public void persistCurrentSession(final @NotNull Session session) { // overwriting it if (!previousSessionMoved) { moveCurrentToPreviousSession(currentSessionFile, getPreviousSessionFile(directoryPath)); - if (!previousSessionMoved) { - options - .getLogger() - .log(WARNING, "Previous session could not be moved, not overwriting it."); - lastPersistedSessionId = null; - return; - } } final boolean written = writeSessionToDisk(currentSessionFile, session); - // a failed write truncates the file, so there is no good copy left to protect. Delete it, so - // a later move does not put it over the last run's session in the previous session file. - if (!written && !currentSessionFile.delete()) { + // A written file holds this session, even if the move failed, so the init-time move must + // skip it. After a failed write, delete the truncated file only if the move worked: then it + // is ours, and a later move must not put it over the last run's session. If the move failed, + // the file can still hold the last run's session, so it stays for a later move to retry. + if (written) { + previousSessionMoved = true; + } else if (previousSessionMoved && !currentSessionFile.delete()) { options .getLogger() .log(WARNING, "Unable to delete the current session file after a failed write."); diff --git a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt index c5745576e8a..609c7b2fb21 100644 --- a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt +++ b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt @@ -865,23 +865,49 @@ class EnvelopeCacheTest { } @Test - fun `failed move in persistCurrentSession keeps the last run's session for a later move`() { + fun `failed move in persistCurrentSession still writes the live session for the init-time move to skip`() { val cache = fixture.getSUT() val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) currentSessionFile.writeText("session content from last run") // a non-empty directory where the previous session file belongs makes the move fail assertTrue(File(previousSessionFile, "blocker").mkdirs()) + val liveSession = createSession() + + cache.persistCurrentSession(liveSession) + assertTrue(previousSessionFile.deleteRecursively()) + cache.movePreviousSession(currentSessionFile, previousSessionFile) + + assertThat(previousSessionFile.exists()).isFalse() + val persistedCurrent = + fixture.options.serializer.deserialize( + currentSessionFile.bufferedReader(), + Session::class.java, + )!! + assertThat(persistedCurrent.sessionId).isEqualTo(liveSession.sessionId) + } - cache.persistCurrentSession(createSession()) + @Test + fun `failed move and failed write in persistCurrentSession leave the file for a later move`() { + val liveSession = createSession() + val serializer = mock() + whenever(serializer.serialize(same(liveSession), any())) + .thenThrow(RuntimeException("forced ex")) + val cache = fixture.getSUT { options -> options.setSerializer(serializer) } + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) + currentSessionFile.writeText("session content from last run") + assertTrue(File(previousSessionFile, "blocker").mkdirs()) - assertThat(currentSessionFile.readText()).isEqualTo("session content from last run") + cache.persistCurrentSession(liveSession) + // the file may still be the last run's session, so it is not deleted + assertThat(currentSessionFile.exists()).isTrue() assertTrue(previousSessionFile.deleteRecursively()) cache.movePreviousSession(currentSessionFile, previousSessionFile) assertThat(currentSessionFile.exists()).isFalse() - assertThat(previousSessionFile.readText()).isEqualTo("session content from last run") + assertThat(previousSessionFile.exists()).isTrue() } @Test From 1a4e24eb37a5ec7ac6e29f523959f85727dd54b6 Mon Sep 17 00:00:00 2001 From: Markus Hintersteiner Date: Wed, 2 Dec 2026 15:57:03 +0100 Subject: [PATCH 07/12] Fix Changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dfd928bcae1..63890cb0424 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ - Android: A crash long after `Sentry.init` is no longer marked as a startup crash when the device slept in between, because the time since init now counts deep sleep ([#6738](https://github.com/getsentry/sentry-java/pull/6738)) - Session Replay: Replays recovered after a crash no longer list `"null"` as a screen name when the last named frame leaves the buffer ([#6827](https://github.com/getsentry/sentry-java/pull/6827)) +- Hybrid SDKs: A session written right after `Sentry.init` is no longer sent as the previous run's session while it is still in progress, and the previous run's session is no longer lost ([#6800](https://github.com/getsentry/sentry-java/pull/6800)) ### Internal @@ -39,7 +40,6 @@ - Android: Out-of-process crash reporting now supports Android 5.0 (API level 21) and later, previously required Android 11 (API level 30) ([#6614](https://github.com/getsentry/sentry-java/pull/6614)) - Android profiling: Uploading a Perfetto profile chunk now keeps the trace in memory once instead of up to three times, lowering peak memory use for traces up to 50 MB ([#6743](https://github.com/getsentry/sentry-java/pull/6743)) - Stop a transaction's CPU and memory collection 30 seconds after it starts even when the device's wall clock changes in between ([#6739](https://github.com/getsentry/sentry-java/pull/6739)) -- Hybrid SDKs: A session written right after `Sentry.init` is no longer sent as the previous run's session while it is still in progress, and the previous run's session is no longer lost ([#6800](https://github.com/getsentry/sentry-java/pull/6800)) ### Dependencies From 1612c50a7df5191951d3c81233e7eacb82317977 Mon Sep 17 00:00:00 2001 From: Roman Zavarnitsyn Date: Thu, 3 Dec 2026 13:43:46 +0100 Subject: [PATCH 08/12] ref(core): Check the session id instead of a flag before moving the session file Replace the previousSessionMoved flag with checks of the session id in the current session file, as suggested in review. The init-time move now skips the file when it holds the scopes' live session. It reads the scopes' volatile session fields under the cache's session lock, without taking a scope lock, because persistCurrentSession takes the scope's session lock before the cache's. persistCurrentSession moves a different session out of the way only while the previous session is not handled yet (previousSessionLatch). After that, any other session in the file is an earlier one of this process, and moving it would leave a stale previous session file for the next launch to send again. The file is read only in that window, and only when this session was not the last one persisted. Co-Authored-By: Claude --- sentry/api/sentry.api | 1 + .../java/io/sentry/MovePreviousSession.java | 6 +- sentry/src/main/java/io/sentry/Sentry.java | 7 +- .../java/io/sentry/cache/EnvelopeCache.java | 117 +++++++++++----- .../java/io/sentry/MovePreviousSessionTest.kt | 19 ++- .../java/io/sentry/cache/EnvelopeCacheTest.kt | 130 +++++++++++++----- 6 files changed, 199 insertions(+), 81 deletions(-) diff --git a/sentry/api/sentry.api b/sentry/api/sentry.api index 8dd75b41add..a8af201ba65 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -5033,6 +5033,7 @@ public class io/sentry/cache/EnvelopeCache : io/sentry/cache/IEnvelopeCache { public static fun getPreviousSessionFile (Ljava/lang/String;)Ljava/io/File; public fun iterator ()Ljava/util/Iterator; public fun movePreviousSession (Ljava/io/File;Ljava/io/File;)V + public fun movePreviousSession (Ljava/io/File;Ljava/io/File;Lio/sentry/IScopes;)V public fun persistCurrentSession (Lio/sentry/Session;)V public fun store (Lio/sentry/SentryEnvelope;Lio/sentry/Hint;)V public fun storeEnvelope (Lio/sentry/SentryEnvelope;Lio/sentry/Hint;)Z diff --git a/sentry/src/main/java/io/sentry/MovePreviousSession.java b/sentry/src/main/java/io/sentry/MovePreviousSession.java index 6b7de16d81a..ece78e0b31a 100644 --- a/sentry/src/main/java/io/sentry/MovePreviousSession.java +++ b/sentry/src/main/java/io/sentry/MovePreviousSession.java @@ -10,9 +10,11 @@ final class MovePreviousSession implements Runnable { private final @NotNull SentryOptions options; + private final @NotNull IScopes scopes; - MovePreviousSession(final @NotNull SentryOptions options) { + MovePreviousSession(final @NotNull SentryOptions options, final @NotNull IScopes scopes) { this.options = options; + this.scopes = scopes; } @Override @@ -28,7 +30,7 @@ public void run() { final File currentSessionFile = EnvelopeCache.getCurrentSessionFile(cacheDirPath); final File previousSessionFile = EnvelopeCache.getPreviousSessionFile(cacheDirPath); - ((EnvelopeCache) cache).movePreviousSession(currentSessionFile, previousSessionFile); + ((EnvelopeCache) cache).movePreviousSession(currentSessionFile, previousSessionFile, scopes); ((EnvelopeCache) cache).flushPreviousSession(); } diff --git a/sentry/src/main/java/io/sentry/Sentry.java b/sentry/src/main/java/io/sentry/Sentry.java index 8112cf0ee8b..d15c5730f3d 100644 --- a/sentry/src/main/java/io/sentry/Sentry.java +++ b/sentry/src/main/java/io/sentry/Sentry.java @@ -380,7 +380,7 @@ private static void init(final @NotNull SentryOptions options, final boolean glo e); } - movePreviousSession(options); + movePreviousSession(options, rootScopes); // when integrations are registered on Scopes ctor and async integrations are fired, // it might and actually happened that integrations called captureSomething // and Scopes was still NoOp. @@ -543,10 +543,11 @@ private static void handleAppStartProfilingConfig( } @SuppressWarnings("FutureReturnValueIgnored") - private static void movePreviousSession(final @NotNull SentryOptions options) { + private static void movePreviousSession( + final @NotNull SentryOptions options, final @NotNull IScopes scopes) { // enqueue a task to move previous unfinished session to its own file try { - options.getExecutorService().submit(new MovePreviousSession(options)); + options.getExecutorService().submit(new MovePreviousSession(options, scopes)); } catch (Throwable e) { options.getLogger().log(SentryLevel.DEBUG, "Failed to move previous session.", e); } diff --git a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java index 2b2b6ac8729..982ab250b50 100644 --- a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java +++ b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java @@ -9,6 +9,7 @@ import com.jakewharton.nopen.annotation.Open; import io.sentry.DateUtils; import io.sentry.Hint; +import io.sentry.IScopes; import io.sentry.ISentryLifecycleToken; import io.sentry.SentryCrashLastRunState; import io.sentry.SentryEnvelope; @@ -82,13 +83,6 @@ public class EnvelopeCache extends CacheStrategy implements IEnvelopeCache { */ private @Nullable String lastPersistedSessionId; - /** - * Whether this process already moved the last run's session out of the current session file. - * After that, the current session file holds a session of this process, so the init-time {@link - * #movePreviousSession(File, File)} must not move it. - */ - private boolean previousSessionMoved; - public static @NotNull IEnvelopeCache create(final @NotNull SentryOptions options) { final String cacheDirPath = options.getCacheDirPath(); final int maxCacheItems = options.getMaxCacheItems(); @@ -148,10 +142,9 @@ private boolean storeInternal(final @NotNull SentryEnvelope envelope, final @Not try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { final @Nullable Session startingSession = readSessionFromEnvelope(envelope); if (!isAlreadyPersisted(startingSession)) { - moveCurrentToPreviousSession(currentSessionFile, previousSessionFile); - if (startingSession != null && writeSessionToDisk(currentSessionFile, startingSession)) { - // even if the move failed, the file now holds this session and not the last run's - previousSessionMoved = true; + movePreviousSession(currentSessionFile, previousSessionFile); + if (startingSession != null) { + writeSessionToDisk(currentSessionFile, startingSession); } } } @@ -398,24 +391,34 @@ public void persistCurrentSession(final @NotNull Session session) { try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { final String directoryPath = directory.getOrCreate().getAbsolutePath(); final File currentSessionFile = getCurrentSessionFile(directoryPath); - // this can run before the init-time move, so move the last run's session first instead of - // overwriting it - if (!previousSessionMoved) { - moveCurrentToPreviousSession(currentSessionFile, getPreviousSessionFile(directoryPath)); + final @Nullable String sessionId = session.getSessionId(); + // This can run before the init-time move, while the file still holds the last run's + // session. Move that session first instead of overwriting it. Once the previous session is + // handled, any other session in the file is an earlier one of this process, and moving it + // would leave a stale previous session file for the next launch to send again. The file is + // only read in that startup window, and only when we did not write this session to it last. + boolean moveFailed = false; + if (previousSessionLatch.getCount() > 0 + && (sessionId == null || !sessionId.equals(lastPersistedSessionId))) { + final @Nullable String fileSessionId = readSessionId(currentSessionFile); + if (fileSessionId != null && !fileSessionId.equals(sessionId)) { + moveFailed = + !moveCurrentToPreviousSession( + currentSessionFile, getPreviousSessionFile(directoryPath)); + } } + // If the move failed, this still writes: a rename that fails keeps failing, and the next + // SessionStart would write over the last run's session anyway. final boolean written = writeSessionToDisk(currentSessionFile, session); - // A written file holds this session, even if the move failed, so the init-time move must - // skip it. After a failed write, delete the truncated file only if the move worked: then it - // is ours, and a later move must not put it over the last run's session. If the move failed, - // the file can still hold the last run's session, so it stays for a later move to retry. - if (written) { - previousSessionMoved = true; - } else if (previousSessionMoved && !currentSessionFile.delete()) { + // A failed write truncates the file. Delete it so a later move does not put it over the last + // run's session, unless the move failed: then the file can still be the last run's session, + // and it stays for a later move to retry. + if (!written && !moveFailed && !currentSessionFile.delete()) { options .getLogger() .log(WARNING, "Unable to delete the current session file after a failed write."); } - lastPersistedSessionId = written ? session.getSessionId() : null; + lastPersistedSessionId = written ? sessionId : null; } } @@ -529,29 +532,73 @@ public void flushPreviousSession() { previousSessionLatch.countDown(); } + public void movePreviousSession( + final @NotNull File currentSessionFile, final @NotNull File previousSessionFile) { + moveCurrentToPreviousSession(currentSessionFile, previousSessionFile); + } + /** - * Moves the last run's session to the previous session file. Does nothing if this process already - * did that, because the current session file then holds the live session. + * The init-time move of the last run's session to the previous session file. It runs on an + * executor, so a hybrid {@link #persistCurrentSession(Session)} or a {@link SessionStart} can + * write the live session to the current session file first. Then the file holds the scopes' + * session, and it is not moved. */ + @ApiStatus.Internal public void movePreviousSession( - final @NotNull File currentSessionFile, final @NotNull File previousSessionFile) { + final @NotNull File currentSessionFile, + final @NotNull File previousSessionFile, + final @NotNull IScopes scopes) { try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { - if (previousSessionMoved) { - options - .getLogger() - .log(DEBUG, "Previous session was already moved, not moving the live session."); + // Read the live session under this lock, so the file cannot get a newer session between the + // two reads. If the scopes have no session yet, the file cannot hold a live one. + final @Nullable String liveSessionId = liveSessionId(scopes); + if (liveSessionId != null && liveSessionId.equals(readSessionId(currentSessionFile))) { + options.getLogger().log(DEBUG, "Current session file holds the live session, not moving."); return; } moveCurrentToPreviousSession(currentSessionFile, previousSessionFile); } } - private void moveCurrentToPreviousSession( + /** + * Plain reads of the scopes' volatile session fields. This must not take a scope's session lock: + * {@link #persistCurrentSession(Session)} runs with that lock held and then takes {@link + * #sessionLock}. + */ + private static @Nullable String liveSessionId(final @NotNull IScopes scopes) { + @Nullable Session session = scopes.getScope().getSession(); + if (session == null) { + session = scopes.getIsolationScope().getSession(); + } + if (session == null) { + session = scopes.getGlobalScope().getSession(); + } + return session != null ? session.getSessionId() : null; + } + + /** The session id in the file, or null if the file is missing or holds no valid session. */ + private @Nullable String readSessionId(final @NotNull File sessionFile) { + if (!sessionFile.exists()) { + return null; + } + try (final Reader reader = + new BufferedReader(new InputStreamReader(new FileInputStream(sessionFile), UTF_8))) { + final @Nullable Session session = serializer.getValue().deserialize(reader, Session.class); + return session != null ? session.getSessionId() : null; + } catch (IOException e) { + options.getLogger().log(DEBUG, e, "Unable to read the session file: %s", sessionFile); + return null; + } + } + + /** + * @return whether the current session file is out of the way: moved, or not there at all + */ + private boolean moveCurrentToPreviousSession( final @NotNull File currentSessionFile, final @NotNull File previousSessionFile) { try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { if (!currentSessionFile.exists()) { - previousSessionMoved = true; - return; + return true; } if (previousSessionFile.exists()) { @@ -567,15 +614,15 @@ private void moveCurrentToPreviousSession( try { final boolean renamed = currentSessionFile.renameTo(previousSessionFile); - // a failed rename leaves the last run's session in place, so a later move can retry it - previousSessionMoved = renamed; if (!renamed) { options.getLogger().log(WARNING, "Unable to move current session to previous session."); } + return renamed; } catch (Throwable e) { options .getLogger() .log(SentryLevel.ERROR, "Error moving current session to previous session.", e); + return false; } } } diff --git a/sentry/src/test/java/io/sentry/MovePreviousSessionTest.kt b/sentry/src/test/java/io/sentry/MovePreviousSessionTest.kt index f14cbd6d016..cda5f6fe374 100644 --- a/sentry/src/test/java/io/sentry/MovePreviousSessionTest.kt +++ b/sentry/src/test/java/io/sentry/MovePreviousSessionTest.kt @@ -13,6 +13,7 @@ import kotlin.test.assertTrue import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.never +import org.mockito.kotlin.same import org.mockito.kotlin.verify class MovePreviousSessionTest { @@ -34,7 +35,7 @@ class MovePreviousSessionTest { options.cacheDirPath = cacheDirPath options.isEnableAutoSessionTracking = isEnableSessionTracking options.setEnvelopeDiskCache(envelopeCache ?: EnvelopeCache.create(options)) - return MovePreviousSession(options) + return MovePreviousSession(options, NoOpScopes.getInstance()) } fun cleanup() { @@ -60,10 +61,22 @@ class MovePreviousSessionTest { sut.run() - verify(fixture.cache, never()).movePreviousSession(any(), any()) + verify(fixture.cache, never()).movePreviousSession(any(), any(), any()) verify(fixture.cache, never()).flushPreviousSession() } + @Test + fun `passes its scopes to the cache so the live session is not moved`() { + val scopes = mock() + fixture.options.cacheDirPath = fixture.tempDir.toAbsolutePath().toFile().absolutePath + fixture.options.setEnvelopeDiskCache(fixture.cache) + + MovePreviousSession(fixture.options, scopes).run() + + verify(fixture.cache).movePreviousSession(any(), any(), same(scopes)) + verify(fixture.cache).flushPreviousSession() + } + @Test fun `when session tracking is disabled, still moves previous session`() { val sut = fixture.getSUT(isEnableSessionTracking = false) @@ -88,7 +101,7 @@ class MovePreviousSessionTest { sut.run() - verify(fixture.cache, never()).movePreviousSession(any(), any()) + verify(fixture.cache, never()).movePreviousSession(any(), any(), any()) verify(fixture.cache, never()).flushPreviousSession() } diff --git a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt index 609c7b2fb21..2018dacc41e 100644 --- a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt +++ b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt @@ -4,6 +4,8 @@ import com.google.common.truth.Truth.assertThat import io.sentry.DateUtils import io.sentry.Hint import io.sentry.ILogger +import io.sentry.IScope +import io.sentry.IScopes import io.sentry.ISerializer import io.sentry.NoOpLogger import io.sentry.SentryCrashLastRunState @@ -353,7 +355,9 @@ class EnvelopeCacheTest { val serializer = mock() whenever(serializer.serialize(same(liveSession), any())) .thenThrow(RuntimeException("forced ex")) - whenever(serializer.deserialize(any(), eq(Session::class.java))).thenReturn(liveSession) + // first the persist reads the last run's session file, then the SessionStart reads its envelope + whenever(serializer.deserialize(any(), eq(Session::class.java))) + .thenReturn(createSession(), liveSession) val cache = fixture.getSUT { options -> options.setSerializer(serializer) } val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) @@ -848,20 +852,75 @@ class EnvelopeCacheTest { val cache = fixture.getSUT() val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) - currentSessionFile.writeText("session content from last run") + val lastRunSession = writeSession(currentSessionFile, createSession()) val liveSession = createSession() // a hybrid SDK persists the live session before the executor runs MovePreviousSession cache.persistCurrentSession(liveSession) - cache.movePreviousSession(currentSessionFile, previousSessionFile) + cache.movePreviousSession(currentSessionFile, previousSessionFile, scopesWith(liveSession)) - assertThat(previousSessionFile.readText()).isEqualTo("session content from last run") - val persistedCurrent = - fixture.options.serializer.deserialize( - currentSessionFile.bufferedReader(), - Session::class.java, - )!! - assertThat(persistedCurrent.sessionId).isEqualTo(liveSession.sessionId) + assertThat(readSessionId(previousSessionFile)).isEqualTo(lastRunSession.sessionId) + assertThat(readSessionId(currentSessionFile)).isEqualTo(liveSession.sessionId) + } + + @Test + fun `SessionStart before the init-time move keeps both sessions in place`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) + val lastRunSession = writeSession(currentSessionFile, createSession()) + val liveSession = createSession() + + cache.storeEnvelope( + SentryEnvelope.from(fixture.options.serializer, liveSession, null), + HintUtils.createWithTypeCheckHint(SessionStartHint()), + ) + cache.movePreviousSession(currentSessionFile, previousSessionFile, scopesWith(liveSession)) + + assertThat(readSessionId(previousSessionFile)).isEqualTo(lastRunSession.sessionId) + assertThat(readSessionId(currentSessionFile)).isEqualTo(liveSession.sessionId) + } + + @Test + fun `init-time move moves the last run's session when the live session is not written yet`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) + val lastRunSession = writeSession(currentSessionFile, createSession()) + + cache.movePreviousSession(currentSessionFile, previousSessionFile, scopesWith(createSession())) + + assertThat(currentSessionFile.exists()).isFalse() + assertThat(readSessionId(previousSessionFile)).isEqualTo(lastRunSession.sessionId) + } + + @Test + fun `init-time move without a live session moves the last run's session`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) + val lastRunSession = writeSession(currentSessionFile, createSession()) + + cache.movePreviousSession(currentSessionFile, previousSessionFile, scopesWith(null)) + + assertThat(currentSessionFile.exists()).isFalse() + assertThat(readSessionId(previousSessionFile)).isEqualTo(lastRunSession.sessionId) + } + + @Test + fun `persistCurrentSession after the previous session was handled does not move an earlier session of this process`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) + cache.flushPreviousSession() + // the earlier session's SessionEnd is still queued, so its file is still there + writeSession(currentSessionFile, createSession()) + val nextSession = createSession() + + cache.persistCurrentSession(nextSession) + + assertThat(previousSessionFile.exists()).isFalse() + assertThat(readSessionId(currentSessionFile)).isEqualTo(nextSession.sessionId) } @Test @@ -869,30 +928,27 @@ class EnvelopeCacheTest { val cache = fixture.getSUT() val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) - currentSessionFile.writeText("session content from last run") + writeSession(currentSessionFile, createSession()) // a non-empty directory where the previous session file belongs makes the move fail assertTrue(File(previousSessionFile, "blocker").mkdirs()) val liveSession = createSession() cache.persistCurrentSession(liveSession) assertTrue(previousSessionFile.deleteRecursively()) - cache.movePreviousSession(currentSessionFile, previousSessionFile) + cache.movePreviousSession(currentSessionFile, previousSessionFile, scopesWith(liveSession)) assertThat(previousSessionFile.exists()).isFalse() - val persistedCurrent = - fixture.options.serializer.deserialize( - currentSessionFile.bufferedReader(), - Session::class.java, - )!! - assertThat(persistedCurrent.sessionId).isEqualTo(liveSession.sessionId) + assertThat(readSessionId(currentSessionFile)).isEqualTo(liveSession.sessionId) } @Test fun `failed move and failed write in persistCurrentSession leave the file for a later move`() { + val lastRunSession = createSession() val liveSession = createSession() val serializer = mock() whenever(serializer.serialize(same(liveSession), any())) .thenThrow(RuntimeException("forced ex")) + whenever(serializer.deserialize(any(), eq(Session::class.java))).thenReturn(lastRunSession) val cache = fixture.getSUT { options -> options.setSerializer(serializer) } val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) @@ -904,32 +960,30 @@ class EnvelopeCacheTest { assertThat(currentSessionFile.exists()).isTrue() assertTrue(previousSessionFile.deleteRecursively()) - cache.movePreviousSession(currentSessionFile, previousSessionFile) + cache.movePreviousSession(currentSessionFile, previousSessionFile, scopesWith(liveSession)) assertThat(currentSessionFile.exists()).isFalse() assertThat(previousSessionFile.exists()).isTrue() } - @Test - fun `SessionStart before the init-time move keeps both sessions in place`() { - val cache = fixture.getSUT() - val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) - val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) - currentSessionFile.writeText("session content from last run") - val liveSession = createSession() + private fun writeSession(file: File, session: Session): Session { + file.bufferedWriter().use { fixture.options.serializer.serialize(session, it) } + return session + } - cache.storeEnvelope( - SentryEnvelope.from(fixture.options.serializer, liveSession, null), - HintUtils.createWithTypeCheckHint(SessionStartHint()), - ) - cache.movePreviousSession(currentSessionFile, previousSessionFile) + private fun readSessionId(file: File): String? = + file.bufferedReader().use { + fixture.options.serializer.deserialize(it, Session::class.java)?.sessionId + } - assertThat(previousSessionFile.readText()).isEqualTo("session content from last run") - val persistedCurrent = - fixture.options.serializer.deserialize( - currentSessionFile.bufferedReader(), - Session::class.java, - )!! - assertThat(persistedCurrent.sessionId).isEqualTo(liveSession.sessionId) + private fun scopesWith(session: Session?): IScopes { + val scope = mock() + whenever(scope.session).thenReturn(session) + val emptyScope = mock() + val scopes = mock() + whenever(scopes.scope).thenReturn(scope) + whenever(scopes.isolationScope).thenReturn(emptyScope) + whenever(scopes.globalScope).thenReturn(emptyScope) + return scopes } } From c4c6f12a694e8399ebdb517a8ba3d2a080b22ded Mon Sep 17 00:00:00 2001 From: Roman Zavarnitsyn Date: Thu, 3 Dec 2026 14:06:32 +0100 Subject: [PATCH 09/12] fix(core): Delete the session file only for the session that ended SessionEnd and InternalSentrySdk.deleteCurrentSessionFile deleted session.json without checking whose session was in it. The end of a session is stored on the transport thread, but a hybrid persistCurrentSession writes on the caller's thread, so a queued SessionEnd(A) could delete the file that persistCurrentSession(B) had just written. The delayed SessionStart(B) then wrote B's older start snapshot, and B's non-terminating error marker was lost. Delete the file only if it holds the session that ended, or no valid session. readSessionFromEnvelope now finds the session item in any position, because a crash envelope has the event first. The SessionEnd read runs on the transport thread; the InternalSentrySdk delete already runs off the main thread unless the process is about to crash. Co-Authored-By: Claude --- CHANGELOG.md | 2 +- .../android/core/InternalSentrySdk.java | 18 ++++- .../android/core/InternalSentrySdkTest.kt | 31 ++++++++ sentry/api/sentry.api | 1 + .../java/io/sentry/cache/EnvelopeCache.java | 64 ++++++++++----- .../java/io/sentry/cache/EnvelopeCacheTest.kt | 77 ++++++++++++++++--- 6 files changed, 157 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 63890cb0424..cc8179b5875 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,7 +15,7 @@ - Android: A crash long after `Sentry.init` is no longer marked as a startup crash when the device slept in between, because the time since init now counts deep sleep ([#6738](https://github.com/getsentry/sentry-java/pull/6738)) - Session Replay: Replays recovered after a crash no longer list `"null"` as a screen name when the last named frame leaves the buffer ([#6827](https://github.com/getsentry/sentry-java/pull/6827)) -- Hybrid SDKs: A session written right after `Sentry.init` is no longer sent as the previous run's session while it is still in progress, and the previous run's session is no longer lost ([#6800](https://github.com/getsentry/sentry-java/pull/6800)) +- Hybrid SDKs: A session written right after `Sentry.init` is no longer sent as the previous run's session while it is still in progress, and the previous run's session is no longer lost. A non-terminating error recorded right after a new session starts is no longer removed from disk when the previous session ends ([#6800](https://github.com/getsentry/sentry-java/pull/6800)) ### Internal diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java b/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java index 104d2f0c803..8379425a3df 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java @@ -26,6 +26,7 @@ import io.sentry.android.core.performance.AppStartMetrics; import io.sentry.android.core.performance.TimeSpan; import io.sentry.cache.EnvelopeCache; +import io.sentry.cache.IEnvelopeCache; import io.sentry.protocol.App; import io.sentry.protocol.Device; import io.sentry.protocol.SentryId; @@ -193,6 +194,7 @@ public static SentryId captureEnvelope( envelopeItems.add(sessionItem); deleteCurrentSessionFile( options, + session.getSessionId(), // should be sync if going to crash or already not a main thread !maybeStartNewSession || !scopes.getOptions().getThreadChecker().isMainThread()); if (maybeStartNewSession) { @@ -407,13 +409,13 @@ private static void addTimeSpanToSerializedSpans(TimeSpan span, List { - deleteCurrentSessionFile(options); + deleteCurrentSessionFile(options, sessionId); }); } catch (Throwable e) { options @@ -421,17 +423,25 @@ private static void deleteCurrentSessionFile( .log(WARNING, "Submission of deletion of the current session file rejected.", e); } } else { - deleteCurrentSessionFile(options); + deleteCurrentSessionFile(options, sessionId); } } - private static void deleteCurrentSessionFile(final @NotNull SentryOptions options) { + private static void deleteCurrentSessionFile( + final @NotNull SentryOptions options, final @Nullable String sessionId) { final String cacheDirPath = options.getCacheDirPath(); if (cacheDirPath == null) { options.getLogger().log(INFO, "Cache dir is not set, not deleting the current session."); return; } + final IEnvelopeCache cache = options.getEnvelopeDiskCache(); + if (cache instanceof EnvelopeCache) { + // keeps the file if it already holds another session + ((EnvelopeCache) cache).deleteCurrentSessionFile(sessionId); + return; + } + final File sessionFile = EnvelopeCache.getCurrentSessionFile(cacheDirPath); if (!sessionFile.delete()) { options.getLogger().log(WARNING, "Failed to delete the current session file."); diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/InternalSentrySdkTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/InternalSentrySdkTest.kt index baa46fdd3bb..9e2d350d9e4 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/InternalSentrySdkTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/InternalSentrySdkTest.kt @@ -462,6 +462,37 @@ class InternalSentrySdkTest { assertEquals(capturedSession.sessionId, sessionRef.get().sessionId) } + @Test + fun `captureEnvelope deletes the session file of the crashed session`() { + val fixture = Fixture() + fixture.init(context) + val sessionRef = AtomicReference() + Sentry.configureScope { scope -> sessionRef.set(scope.session) } + val sessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + sessionFile.parentFile!!.mkdirs() + sessionFile.bufferedWriter().use { fixture.options.serializer.serialize(sessionRef.get(), it) } + + fixture.captureEnvelopeWithEvent(fixture.createSentryEventWithUnhandledException()) + + assertThat(sessionFile.exists()).isFalse() + } + + @Test + fun `captureEnvelope keeps a session file that holds another session`() { + val fixture = Fixture() + fixture.init(context) + val otherSession = Session("other", null, "environment", "release") + val sessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + sessionFile.parentFile!!.mkdirs() + sessionFile.bufferedWriter().use { fixture.options.serializer.serialize(otherSession, it) } + + fixture.captureEnvelopeWithEvent(fixture.createSentryEventWithUnhandledException()) + + val persistedSession = + fixture.options.serializer.deserialize(sessionFile.reader(), Session::class.java)!! + assertThat(persistedSession.sessionId).isEqualTo(otherSession.sessionId) + } + @Test fun `captureEnvelope starts new session when enabled`() { val fixture = Fixture() diff --git a/sentry/api/sentry.api b/sentry/api/sentry.api index 67d1f591c52..00e4bcddd4a 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -5027,6 +5027,7 @@ public class io/sentry/cache/EnvelopeCache : io/sentry/cache/IEnvelopeCache { protected final field sessionLock Lio/sentry/util/AutoClosableReentrantLock; public fun (Lio/sentry/SentryOptions;Ljava/lang/String;I)V public static fun create (Lio/sentry/SentryOptions;)Lio/sentry/cache/IEnvelopeCache; + public fun deleteCurrentSessionFile (Ljava/lang/String;)V public fun discard (Lio/sentry/SentryEnvelope;)V public fun flushPreviousSession ()V public static fun getCurrentSessionFile (Ljava/lang/String;)Ljava/io/File; diff --git a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java index 982ab250b50..70ece8fa363 100644 --- a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java +++ b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java @@ -125,12 +125,9 @@ private boolean storeInternal(final @NotNull SentryEnvelope envelope, final @Not final File previousSessionFile = getPreviousSessionFile(directoryPath); if (HintUtils.hasType(hint, SessionEnd.class)) { - try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { - lastPersistedSessionId = null; - if (!currentSessionFile.delete()) { - options.getLogger().log(WARNING, "Current envelope doesn't exist."); - } - } + final @Nullable Session endedSession = readSessionFromEnvelope(envelope); + deleteCurrentSessionFile( + currentSessionFile, endedSession != null ? endedSession.getSessionId() : null); } if (HintUtils.hasType(hint, AbnormalExit.class) @@ -292,12 +289,9 @@ private void writeCrashMarkerFile() { } private @Nullable Session readSessionFromEnvelope(final @NotNull SentryEnvelope envelope) { - final Iterable items = envelope.getItems(); - - // we know that an envelope with a SessionStart hint has a single item inside - if (items.iterator().hasNext()) { - final SentryEnvelopeItem item = items.iterator().next(); - + // a SessionStart or SessionEnd envelope has a single session item, but a crash envelope + // (UncaughtExceptionHint, which is a SessionEnd) has the event first and the session after it + for (final SentryEnvelopeItem item : envelope.getItems()) { if (SentryItemType.Session.equals(item.getHeader().getType())) { try (final Reader reader = new BufferedReader( @@ -316,17 +310,9 @@ private void writeCrashMarkerFile() { } catch (Throwable e) { options.getLogger().log(ERROR, "Item failed to process.", e); } - } else { - options - .getLogger() - .log( - INFO, - "Current envelope has a different envelope type %s", - item.getHeader().getType()); } - } else { - options.getLogger().log(INFO, "Current envelope is empty."); } + options.getLogger().log(INFO, "Current envelope has no session item."); return null; } @@ -422,6 +408,42 @@ public void persistCurrentSession(final @NotNull Session session) { } } + /** + * Deletes the current session file for a session that ended, unless the file holds a different + * session. + * + * @param endedSessionId the id of the session that ended, or null to delete the file anyway + */ + @ApiStatus.Internal + public void deleteCurrentSessionFile(final @Nullable String endedSessionId) { + deleteCurrentSessionFile( + getCurrentSessionFile(directory.getFile().getAbsolutePath()), endedSessionId); + } + + /** + * The end of a session is stored on the transport thread, but a hybrid {@link + * #persistCurrentSession(Session)} writes on the caller's thread. So the file can already hold + * the next session, or, before the init-time move, the last run's session. Then it must stay. + */ + private void deleteCurrentSessionFile( + final @NotNull File currentSessionFile, final @Nullable String endedSessionId) { + try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { + if (endedSessionId != null) { + final @Nullable String fileSessionId = readSessionId(currentSessionFile); + if (fileSessionId != null && !fileSessionId.equals(endedSessionId)) { + options + .getLogger() + .log(DEBUG, "Current session file holds another session, not deleting it."); + return; + } + } + lastPersistedSessionId = null; + if (!currentSessionFile.delete()) { + options.getLogger().log(WARNING, "Current envelope doesn't exist."); + } + } + } + @Override public void discard(final @NotNull SentryEnvelope envelope) { Objects.requireNonNull(envelope, "Envelope is required."); diff --git a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt index 2018dacc41e..5baf29046e7 100644 --- a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt +++ b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt @@ -10,6 +10,8 @@ import io.sentry.ISerializer import io.sentry.NoOpLogger import io.sentry.SentryCrashLastRunState import io.sentry.SentryEnvelope +import io.sentry.SentryEnvelopeHeader +import io.sentry.SentryEnvelopeItem import io.sentry.SentryEvent import io.sentry.SentryOptions import io.sentry.SentryUUID @@ -301,24 +303,22 @@ class EnvelopeCacheTest { } @Test - fun `SessionEnd deleting the persisted session lets the delayed SessionStart write it again`() { + fun `queued SessionEnd of the previous session keeps the persisted live session`() { val cache = fixture.getSUT() val sid = SentryUUID.generateSentryId() val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) - cache.persistCurrentSession(createSession(sessionId = sid)) + val liveSession = createSession(sessionId = sid) + liveSession.recordNonTerminatingUnhandledError() + cache.persistCurrentSession(liveSession) - // the previous session's end envelope is still queued and deletes the file the live session - // was just written to - val endedSession = createSession() + // the previous session's end envelope is still queued when the live session is persisted cache.storeEnvelope( - SentryEnvelope.from(fixture.options.serializer, endedSession, null), + SentryEnvelope.from(fixture.options.serializer, createSession(), null), HintUtils.createWithTypeCheckHint(SessionEndHint()), ) - assertThat(currentSessionFile.exists()).isFalse() - - val delayedStart = createSession(sessionId = sid) + // so is the live session's start, which is older than the persisted copy cache.storeEnvelope( - SentryEnvelope.from(fixture.options.serializer, delayedStart, null), + SentryEnvelope.from(fixture.options.serializer, createSession(sessionId = sid), null), HintUtils.createWithTypeCheckHint(SessionStartHint()), ) @@ -328,6 +328,63 @@ class EnvelopeCacheTest { Session::class.java, )!! assertThat(persistedSession.sessionId).isEqualTo(sid) + assertThat(persistedSession.hasNonTerminatingUnhandledError()).isTrue() + } + + @Test + fun `crash envelope with the session after the event keeps a file that holds another session`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val otherSession = writeSession(currentSessionFile, createSession()) + val serializer = fixture.options.serializer + val envelope = + SentryEnvelope( + SentryEnvelopeHeader(), + listOf( + SentryEnvelopeItem.fromEvent(serializer, SentryEvent()), + SentryEnvelopeItem.fromSession(serializer, createSession()), + ), + ) + + cache.storeEnvelope( + envelope, + HintUtils.createWithTypeCheckHint(UncaughtExceptionHint(0, NoOpLogger.getInstance())), + ) + + assertThat(readSessionId(currentSessionFile)).isEqualTo(otherSession.sessionId) + } + + @Test + fun `deleteCurrentSessionFile deletes the file of the ended session`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val endedSession = writeSession(currentSessionFile, createSession()) + + cache.deleteCurrentSessionFile(endedSession.sessionId) + + assertThat(currentSessionFile.exists()).isFalse() + } + + @Test + fun `deleteCurrentSessionFile keeps a file that holds another session`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val otherSession = writeSession(currentSessionFile, createSession()) + + cache.deleteCurrentSessionFile(SentryUUID.generateSentryId()) + + assertThat(readSessionId(currentSessionFile)).isEqualTo(otherSession.sessionId) + } + + @Test + fun `deleteCurrentSessionFile without a session id deletes the file`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + writeSession(currentSessionFile, createSession()) + + cache.deleteCurrentSessionFile(null) + + assertThat(currentSessionFile.exists()).isFalse() } @Test From 5cc19c46e2799e6b0937fcafea88413ad9a6085d Mon Sep 17 00:00:00 2001 From: Roman Zavarnitsyn Date: Thu, 3 Dec 2026 14:19:02 +0100 Subject: [PATCH 10/12] docs(core): Say when a failed persist keeps the last run's session intact Co-Authored-By: Claude --- sentry/src/main/java/io/sentry/cache/EnvelopeCache.java | 9 ++++++--- .../src/test/java/io/sentry/cache/EnvelopeCacheTest.kt | 3 ++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java index 70ece8fa363..05838b76082 100644 --- a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java +++ b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java @@ -396,9 +396,12 @@ public void persistCurrentSession(final @NotNull Session session) { // If the move failed, this still writes: a rename that fails keeps failing, and the next // SessionStart would write over the last run's session anyway. final boolean written = writeSessionToDisk(currentSessionFile, session); - // A failed write truncates the file. Delete it so a later move does not put it over the last - // run's session, unless the move failed: then the file can still be the last run's session, - // and it stays for a later move to retry. + // After a failed write, delete the file so a later move does not put it over the last run's + // session. If the move failed, the file is the last run's session: it is intact if the write + // failed to open it (a read-only file, for example), so it stays for a later move to retry. + // If the write opened it before it failed, it is truncated and lost either way; a later move + // then turns it into a previous session file that PreviousSessionFinalizer cannot parse and + // deletes. if (!written && !moveFailed && !currentSessionFile.delete()) { options .getLogger() diff --git a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt index 5baf29046e7..656965a8c78 100644 --- a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt +++ b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt @@ -1013,7 +1013,8 @@ class EnvelopeCacheTest { assertTrue(File(previousSessionFile, "blocker").mkdirs()) cache.persistCurrentSession(liveSession) - // the file may still be the last run's session, so it is not deleted + // the file is not deleted, because it is the last run's session. Here the throwing serializer + // truncated it; a write that fails to open the file leaves it intact for the later move. assertThat(currentSessionFile.exists()).isTrue() assertTrue(previousSessionFile.deleteRecursively()) From 2667ac6d3c8e7f5e5d0a6322923c2103badc8de1 Mon Sep 17 00:00:00 2001 From: Roman Zavarnitsyn Date: Thu, 3 Dec 2026 16:52:17 +0100 Subject: [PATCH 11/12] ref(core): Read the session id without an exists() check first Co-Authored-By: Claude --- sentry/src/main/java/io/sentry/cache/EnvelopeCache.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java index 05838b76082..8f03384d31a 100644 --- a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java +++ b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java @@ -603,13 +603,13 @@ public void movePreviousSession( /** The session id in the file, or null if the file is missing or holds no valid session. */ private @Nullable String readSessionId(final @NotNull File sessionFile) { - if (!sessionFile.exists()) { - return null; - } try (final Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(sessionFile), UTF_8))) { final @Nullable Session session = serializer.getValue().deserialize(reader, Session.class); return session != null ? session.getSessionId() : null; + } catch (FileNotFoundException e) { + // no file is a normal case, so open it directly instead of checking exists() first + return null; } catch (IOException e) { options.getLogger().log(DEBUG, e, "Unable to read the session file: %s", sessionFile); return null; From 2f787fe0e7c5ab648f8c7b0d1f1dcca80a91bf3d Mon Sep 17 00:00:00 2001 From: Roman Zavarnitsyn Date: Thu, 3 Dec 2026 17:08:20 +0100 Subject: [PATCH 12/12] ref(core): Read the live session through configureScope Use the existing configureScope + scope.getSession() pattern instead of repeating the combined scope view's lookup order in EnvelopeCache. It runs under the cache's session lock, so it must stay lock-free; the comment says why withSession must not be used there. Co-Authored-By: Claude --- .../java/io/sentry/cache/EnvelopeCache.java | 22 +++++++++---------- .../java/io/sentry/cache/EnvelopeCacheTest.kt | 9 ++++---- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java index 8f03384d31a..95c440c6257 100644 --- a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java +++ b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java @@ -51,6 +51,7 @@ import java.util.WeakHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -586,19 +587,18 @@ public void movePreviousSession( } /** - * Plain reads of the scopes' volatile session fields. This must not take a scope's session lock: - * {@link #persistCurrentSession(Session)} runs with that lock held and then takes {@link - * #sessionLock}. + * Runs under {@link #sessionLock}, so it must stay lock-free: {@link + * #persistCurrentSession(Session)} holds a scope's session lock and then takes {@link + * #sessionLock}. {@code configureScope} only runs the callback, and {@code getSession()} reads a + * volatile field; {@code withSession} would take the scope's session lock and could deadlock. */ private static @Nullable String liveSessionId(final @NotNull IScopes scopes) { - @Nullable Session session = scopes.getScope().getSession(); - if (session == null) { - session = scopes.getIsolationScope().getSession(); - } - if (session == null) { - session = scopes.getGlobalScope().getSession(); - } - return session != null ? session.getSessionId() : null; + final @NotNull AtomicReference sessionId = new AtomicReference<>(); + scopes.configureScope(scope -> { + final @Nullable Session session = scope.getSession(); + sessionId.set(session != null ? session.getSessionId() : null); + }); + return sessionId.get(); } /** The session id in the file, or null if the file is missing or holds no valid session. */ diff --git a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt index 656965a8c78..9c4fc77ec96 100644 --- a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt +++ b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt @@ -8,6 +8,7 @@ import io.sentry.IScope import io.sentry.IScopes import io.sentry.ISerializer import io.sentry.NoOpLogger +import io.sentry.ScopeCallback import io.sentry.SentryCrashLastRunState import io.sentry.SentryEnvelope import io.sentry.SentryEnvelopeHeader @@ -40,6 +41,7 @@ import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertTrue import org.mockito.kotlin.any +import org.mockito.kotlin.doAnswer import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.same @@ -1037,11 +1039,10 @@ class EnvelopeCacheTest { private fun scopesWith(session: Session?): IScopes { val scope = mock() whenever(scope.session).thenReturn(session) - val emptyScope = mock() val scopes = mock() - whenever(scopes.scope).thenReturn(scope) - whenever(scopes.isolationScope).thenReturn(emptyScope) - whenever(scopes.globalScope).thenReturn(emptyScope) + doAnswer { (it.arguments[0] as ScopeCallback).run(scope) } + .whenever(scopes) + .configureScope(any()) return scopes } }