Skip to content

Commit d285ae6

Browse files
fix(sessions): don't let the persisted session guard swallow a SessionStart
The guard skipped the SessionStart write whenever the id matched the last persisted one, even when session.json no longer held that session: - a queued SessionEnd for the prior session deletes the file the live session was just persisted to, so the skipped write left no session on disk at all - a failed persist still recorded the id, so the queued write that would have repaired the truncated file was skipped too Clear the id on SessionEnd and only record it when the write succeeded. Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent a3220ff commit d285ae6

2 files changed

Lines changed: 67 additions & 6 deletions

File tree

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

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ public class EnvelopeCache extends CacheStrategy implements IEnvelopeCache {
8080
* Session id last written to the current session file by {@link #persistCurrentSession(Session)},
8181
* which bypasses the transport queue that every other write to that file goes through.
8282
*/
83-
private volatile @Nullable String lastPersistedSessionId;
83+
private @Nullable String lastPersistedSessionId;
8484

8585
public static @NotNull IEnvelopeCache create(final @NotNull SentryOptions options) {
8686
final String cacheDirPath = options.getCacheDirPath();
@@ -124,8 +124,11 @@ private boolean storeInternal(final @NotNull SentryEnvelope envelope, final @Not
124124
final File previousSessionFile = getPreviousSessionFile(directoryPath);
125125

126126
if (HintUtils.hasType(hint, SessionEnd.class)) {
127-
if (!currentSessionFile.delete()) {
128-
options.getLogger().log(WARNING, "Current envelope doesn't exist.");
127+
try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) {
128+
lastPersistedSessionId = null;
129+
if (!currentSessionFile.delete()) {
130+
options.getLogger().log(WARNING, "Current envelope doesn't exist.");
131+
}
129132
}
130133
}
131134

@@ -365,7 +368,7 @@ private boolean writeEnvelopeToDisk(
365368
return true;
366369
}
367370

368-
private void writeSessionToDisk(final @NotNull File file, final @NotNull Session session) {
371+
private boolean writeSessionToDisk(final @NotNull File file, final @NotNull Session session) {
369372
try (final OutputStream outputStream = new FileOutputStream(file);
370373
final Writer writer = new BufferedWriter(new OutputStreamWriter(outputStream, UTF_8))) {
371374
options
@@ -377,14 +380,20 @@ private void writeSessionToDisk(final @NotNull File file, final @NotNull Session
377380
options
378381
.getLogger()
379382
.log(ERROR, e, "Error writing Session to offline storage: %s", session.getSessionId());
383+
return false;
380384
}
385+
return true;
381386
}
382387

383388
@ApiStatus.Internal
384389
public void persistCurrentSession(final @NotNull Session session) {
385390
try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) {
386-
writeSessionToDisk(getCurrentSessionFile(directory.getOrCreate().getAbsolutePath()), session);
387-
lastPersistedSessionId = session.getSessionId();
391+
final boolean written =
392+
writeSessionToDisk(
393+
getCurrentSessionFile(directory.getOrCreate().getAbsolutePath()), session);
394+
if (written) {
395+
lastPersistedSessionId = session.getSessionId();
396+
}
388397
}
389398
}
390399

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

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import io.sentry.hints.SessionStartHint
2424
import io.sentry.protocol.SentryId
2525
import io.sentry.util.HintUtils
2626
import java.io.File
27+
import java.io.Writer
2728
import java.nio.file.Files
2829
import java.nio.file.Path
2930
import java.util.Date
@@ -35,8 +36,10 @@ import kotlin.test.assertFalse
3536
import kotlin.test.assertNotNull
3637
import kotlin.test.assertTrue
3738
import org.mockito.kotlin.any
39+
import org.mockito.kotlin.eq
3840
import org.mockito.kotlin.mock
3941
import org.mockito.kotlin.same
42+
import org.mockito.kotlin.verify
4043
import org.mockito.kotlin.whenever
4144

4245
class EnvelopeCacheTest {
@@ -266,6 +269,55 @@ class EnvelopeCacheTest {
266269
assertThat(persistedPrevious.sessionId).isEqualTo(currentSession.sessionId)
267270
}
268271

272+
@Test
273+
fun `SessionEnd deleting the persisted session lets the delayed SessionStart write it again`() {
274+
val cache = fixture.getSUT()
275+
val sid = SentryUUID.generateSentryId()
276+
val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!)
277+
cache.persistCurrentSession(createSession(sessionId = sid))
278+
279+
// the previous session's end envelope is still queued and deletes the file the live session
280+
// was just written to
281+
val endedSession = createSession()
282+
cache.storeEnvelope(
283+
SentryEnvelope.from(fixture.options.serializer, endedSession, null),
284+
HintUtils.createWithTypeCheckHint(SessionEndHint()),
285+
)
286+
assertThat(currentSessionFile.exists()).isFalse()
287+
288+
val delayedStart = createSession(sessionId = sid)
289+
cache.storeEnvelope(
290+
SentryEnvelope.from(fixture.options.serializer, delayedStart, null),
291+
HintUtils.createWithTypeCheckHint(SessionStartHint()),
292+
)
293+
294+
val persistedSession =
295+
fixture.options.serializer.deserialize(
296+
currentSessionFile.bufferedReader(),
297+
Session::class.java,
298+
)!!
299+
assertThat(persistedSession.sessionId).isEqualTo(sid)
300+
}
301+
302+
@Test
303+
fun `failed persist lets the delayed SessionStart write the session`() {
304+
val sid = SentryUUID.generateSentryId()
305+
val liveSession = createSession(sessionId = sid)
306+
val delayedStart = createSession(sessionId = sid)
307+
val serializer = mock<ISerializer>()
308+
whenever(serializer.serialize(same(liveSession), any<Writer>()))
309+
.thenThrow(RuntimeException("forced ex"))
310+
whenever(serializer.deserialize(any(), eq(Session::class.java))).thenReturn(delayedStart)
311+
val cache = fixture.getSUT { options -> options.setSerializer(serializer) }
312+
313+
cache.persistCurrentSession(liveSession)
314+
315+
val envelope = SentryEnvelope.from(SentryOptions.empty().serializer, delayedStart, null)
316+
cache.storeEnvelope(envelope, HintUtils.createWithTypeCheckHint(SessionStartHint()))
317+
318+
verify(serializer).serialize(same(delayedStart), any<Writer>())
319+
}
320+
269321
@Test
270322
fun `updates current file on session update and read it back`() {
271323
val cache = fixture.getSUT()

0 commit comments

Comments
 (0)