From 0cea47a47d5114232e764762fadc48c2ad9cc608 Mon Sep 17 00:00:00 2001 From: Roman Zavarnitsyn Date: Fri, 27 Nov 2026 14:12:54 +0100 Subject: [PATCH 1/6] 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 2/6] 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 3/6] 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 4/6] 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 5/6] 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 6/6] 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