Repository navigation
Conversation
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 <noreply@anthropic.com>
PR risk: mediumFor commit Main concerns: reach, public contract, data sent to Sentry. Rules that block low also fired:
This label is a hint for reviewers, not an approval. |
📲 Install BuildsAndroid
|
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…ails 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 <noreply@anthropic.com>
0xadam-brown
left a comment
There was a problem hiding this comment.
Excellent! Thanks for working through all these edge cases, and great tests for both race orders 💯
A high level question:
Thoughts about checking the sid that's already in session.json rather than introducing the new previousSessionMoved field into the EnvelopeCache?
Looks like every session has a unique sid, and I imagine a writer could read the file and check whether the session there is the expected one.
Something like:
- the init-time move skips the rotation when the file holds the live scope session's sid (or rotates it otherwise); and
persistCurrentSessionrotates first if the file contains a different sid, and then writes.
(I bet the SessionStart path could unchanged b/c it already rotates before writing – but TBD.)
Pro and contra
That'd^^ let us avoid introducing state that really belongs to the Sentry.init rather than the cache itself (which is always nice), and my clanker says it'd lay the groundwork for some helpful things:
- Reused-options re-init: The earlier init's session wouldn't match the new live sid, so it would be rotated and sent. With the flag, it isn't.
- Safe deletes: SessionEnd and InternalSentrySdk.deleteCurrentSessionFile delete the file without checking whose session is in it. A hybrid persistCurrentSession(B) that lands between the queued SessionEnd(A) and SessionStart(B) would have its file deleted by SessionEnd(A). Deleting only when the file holds A needs the sid. This ordering is already possible on main.
- Less in-memory state: "Same sid, skip the write" would replace both previousSessionMoved and lastPersistedSessionId.
AFAICT, both of your race orders would end up just like they do now and your new tests would still pass. Nice.
Less nice, looks like MovePreviousSession would need to read the file and parse, but seems like this would be pretty infrequent.
Up to you...
…ession 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 <noreply@anthropic.com>
…e' into romtsn/fix/live-session-move-race
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 <noreply@anthropic.com>
🚨 Detected changes in high risk code 🚨High-risk code has higher potential to break the SDK and may be hard to test. To prevent severe bugs, apply the rollout process for releasing such changes and be extra careful when changing and reviewing these files:
|
…tact Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude <noreply@anthropic.com>
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 <noreply@anthropic.com>
📜 Description
At init,
Sentry.initqueuesMovePreviousSessionon the options executor. That task renamessession.jsontoprevious_session.json. Two writers can writesession.jsonbefore that task runs:EnvelopeCache.persistCurrentSession, called on the caller's thread by the non-terminating hybrid APIs inInternalSentrySdk. This is the case in the issue.SessionStartenvelope that gets toEnvelopeCache.storeInternalfirst. That path moves the old file, then writes the new session.In both cases the late init-time move takes the live session and files it as the previous one, so
PreviousSessionFinalizerends and sends it while the scope keeps updating it. In thepersistCurrentSessioncase, the early write also overwrites the last run's session, so that session is lost.The same kind of race exists when a session ends: the deletes of
session.jsondid not check whose session was in the file (see "Safe deletes" below).This PR checks the session id in
session.jsonbefore it moves or deletes the file:Init-time move:
MovePreviousSessionnow gets the root scopes and calls a new internalEnvelopeCache.movePreviousSession(File, File, IScopes). It skips the move when the file holds the scopes' live session. If the scopes have no session yet, the file cannot hold a live one, so it moves as before, without reading the file. The live session id is read under the cache'ssessionLock, so the file cannot get a newer session between the two reads. It uses the usualconfigureScope+scope.getSession()pattern, which takes no lock (getSession()reads a volatile field). It must not usewithSession, becausepersistCurrentSessiontakes the scope's session lock beforesessionLock. Because the check uses the file and not cache state, a re-init that reuses the sameSentryOptions(and so the same cache) also moves the earlier init's session again.persistCurrentSession: while the previous session is not handled yet (previousSessionLatchstill open), it moves a different session out of the way before it writes, so the last run's session is kept. After that, any other session in the file is an earlier one of this process; moving it would leave a staleprevious_session.jsonfor the next launch to send again, so it just writes. The file is read only in that startup window, and only when this session was not the last one persisted (lastPersistedSessionId), so hybrid callers pay at most one small read per session.Failures in
persistCurrentSession: if the move fails, the live session is still written (a rename that fails keeps failing, and the nextSessionStartwould overwrite the old file anyway), and the init-time move then skips it by sid. After a failed write, the file is deleted so a later move cannot put it over the last run's session. The exception is a failed move: then the file is the last run's session and stays for a later move. It is intact if the write failed to open it (a read-only file, for example). If the write opened it before it failed, it is truncated and lost either way, andPreviousSessionFinalizerlater fails to parse it and deletes it.Safe deletes:
SessionEndinEnvelopeCache.storeInternalandInternalSentrySdk.deleteCurrentSessionFilenow deletesession.jsononly when it holds the session that ended, holds no valid session, or the ended session's id is unknown (new internalEnvelopeCache.deleteCurrentSessionFile(String); a cache that is not anEnvelopeCachedeletes as before). Before, they deleted the file whatever it held. The file can hold another session in three cases:persistCurrentSession(B)lands between a queuedSessionEnd(A)andSessionStart(B).SessionEnd(A)deleted B's file, and the delayedSessionStart(B)then wrote B's older start snapshot, so B's non-terminating error marker was lost.InternalSentrySdk.captureEnvelopewithmaybeStartNewSessionon the main thread queues the delete on the options executor and then starts a new session, whoseSessionStartis stored on the transport thread. If that write ran first, the delete removed the new session's file.MovePreviousSessionruns (for example, a hybrid crash right after start) deleted the last run's session, so it was never finalized.readSessionFromEnvelopenow finds the session item in any position, because a crash envelope (UncaughtExceptionHint, which counts as aSessionEnd) has the event first. TheSessionEndread runs on the transport thread. TheInternalSentrySdkdelete runs on the calling thread only when the process is about to crash (maybeStartNewSessionfalse) or the caller is not on the main thread; otherwise it runs on the options executor.The
SessionStartpath and the two-argumentmovePreviousSessionbehave as onmain.💡 Motivation and Context
The init race was seen as a flaky
InternalSentrySdkTest(worked around on the test side in #6358). None of these races were observed in production, but a hybrid SDK that reports an error right after init, or right after a new session starts, could hit them.💚 How did you test it?
EnvelopeCacheTestcases for both init race orders (persistCurrentSession, then the init-time move; aSessionStartstore, then the init-time move):previous_session.jsonholds the last run's session andsession.jsonholds the live one. Both fail without the sid check. More cases cover:persistCurrentSessionafter the previous session was handled (an earlier session of this process is not moved; fails without the latch check);SessionStartdoes not delete the saved previous session).MovePreviousSessionTestchecks that the task passes its scopes to the cache.Safe deletes: a queued
SessionEndof the previous session keeps the persisted live session and its error marker (this replaces the test that described the old behavior); a crash envelope with the session after the event keeps a file that holds another session;deleteCurrentSessionFiledeletes for the ended session, keeps another session, and deletes when no id is given; inInternalSentrySdkTest,captureEnvelopedeletes the crashed session's file and keeps a file that holds another session. Without the sid check in the delete, the four "keeps" tests fail.Also ran
EnvelopeCacheTest,MovePreviousSessionTest,PreviousSessionFinalizerTest,SentryTest,ScopesTest,InternalSentrySdkTest,SentryAndroidTest,AndroidEnvelopeCacheTest,LifecycleWatcherTestand theApplicationExit*tests.📝 Checklist
sendDefaultPIIis enabled.🔮 Next steps
InternalSentrySdkTestfrom test(android): Wait for the previous session move in InternalSentrySdkTest #6358 can stay. It is still a valid way to wait for the init-time move.🤖 Generated with Claude Code