Skip to content

Commit 89d8e9d

Browse files
fix(cache): Clear the persisted session id when the write fails
writeSessionToDisk truncates the current session file before serializing, so a failed persist leaves it corrupt. lastPersistedSessionId kept pointing at it, and isAlreadyPersisted then skipped the rotation that would have replaced the file, on the premise that it still held the live session. Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent d285ae6 commit 89d8e9d

2 files changed

Lines changed: 31 additions & 3 deletions

File tree

‎sentry/src/main/java/io/sentry/cache/EnvelopeCache.java‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -391,9 +391,8 @@ public void persistCurrentSession(final @NotNull Session session) {
391391
final boolean written =
392392
writeSessionToDisk(
393393
getCurrentSessionFile(directory.getOrCreate().getAbsolutePath()), session);
394-
if (written) {
395-
lastPersistedSessionId = session.getSessionId();
396-
}
394+
// a failed write truncates the file, so there is no good copy left to protect
395+
lastPersistedSessionId = written ? session.getSessionId() : null;
397396
}
398397
}
399398

‎sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,35 @@ class EnvelopeCacheTest {
214214
assertThat(previousSessionFile.exists()).isFalse()
215215
}
216216

217+
@Test
218+
fun `failed persist stops the delayed same SID SessionStart from being skipped`() {
219+
val cache = fixture.getSUT()
220+
val sid = SentryUUID.generateSentryId()
221+
val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!)
222+
val newerSession = createSession(sessionId = sid)
223+
newerSession.recordNonTerminatingUnhandledError()
224+
cache.persistCurrentSession(newerSession)
225+
226+
// a directory where the session file belongs makes the write fail
227+
assertTrue(currentSessionFile.delete())
228+
assertTrue(currentSessionFile.mkdir())
229+
cache.persistCurrentSession(newerSession)
230+
assertTrue(currentSessionFile.delete())
231+
232+
val delayedStart = createSession(sessionId = sid)
233+
val envelope = SentryEnvelope.from(fixture.options.serializer, delayedStart, null)
234+
cache.storeEnvelope(envelope, HintUtils.createWithTypeCheckHint(SessionStartHint()))
235+
236+
val persistedSession =
237+
fixture.options.serializer.deserialize(
238+
currentSessionFile.bufferedReader(),
239+
Session::class.java,
240+
)!!
241+
assertThat(persistedSession.sessionId).isEqualTo(sid)
242+
assertThat(persistedSession.hasNonTerminatingUnhandledError()).isFalse()
243+
assertThat(persistedSession.errorCount()).isEqualTo(0)
244+
}
245+
217246
@Test
218247
fun `null SIDs on SessionStart rotate instead of preserving as same session`() {
219248
val cache = fixture.getSUT()

0 commit comments

Comments
 (0)