Skip to content

fix(core): Do not move the live session file at init - #6800

Open
romtsn wants to merge 14 commits into
mainfrom
romtsn/fix/live-session-move-race
Open

romtsn wants to merge 14 commits into
mainfrom
romtsn/fix/live-session-move-race

Conversation

@romtsn

@romtsn romtsn commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

📜 Description

At init, Sentry.init queues MovePreviousSession on the options executor. That task renames session.json to previous_session.json. Two writers can write session.json before that task runs:

  • EnvelopeCache.persistCurrentSession, called on the caller's thread by the non-terminating hybrid APIs in InternalSentrySdk. This is the case in the issue.
  • A SessionStart envelope that gets to EnvelopeCache.storeInternal first. 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 PreviousSessionFinalizer ends and sends it while the scope keeps updating it. In the persistCurrentSession case, 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.json did not check whose session was in the file (see "Safe deletes" below).

This PR checks the session id in session.json before it moves or deletes the file:

  • Init-time move: MovePreviousSession now gets the root scopes and calls a new internal EnvelopeCache.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's sessionLock, so the file cannot get a newer session between the two reads. It uses the usual configureScope + scope.getSession() pattern, which takes no lock (getSession() reads a volatile field). It must not use withSession, because persistCurrentSession takes the scope's session lock before sessionLock. Because the check uses the file and not cache state, a re-init that reuses the same SentryOptions (and so the same cache) also moves the earlier init's session again.

  • persistCurrentSession: while the previous session is not handled yet (previousSessionLatch still 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 stale previous_session.json for 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 next SessionStart would 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, and PreviousSessionFinalizer later fails to parse it and deletes it.

  • Safe deletes: SessionEnd in EnvelopeCache.storeInternal and InternalSentrySdk.deleteCurrentSessionFile now delete session.json only when it holds the session that ended, holds no valid session, or the ended session's id is unknown (new internal EnvelopeCache.deleteCurrentSessionFile(String); a cache that is not an EnvelopeCache deletes as before). Before, they deleted the file whatever it held. The file can hold another session in three cases:

    • The next session, persisted by a hybrid SDK. A hybrid persistCurrentSession(B) lands between a queued SessionEnd(A) and SessionStart(B). SessionEnd(A) deleted B's file, and the delayed SessionStart(B) then wrote B's older start snapshot, so B's non-terminating error marker was lost.
    • The next session after a hybrid crash. InternalSentrySdk.captureEnvelope with maybeStartNewSession on the main thread queues the delete on the options executor and then starts a new session, whose SessionStart is stored on the transport thread. If that write ran first, the delete removed the new session's file.
    • The last run's session, before the init-time move. A session of this process that ends before MovePreviousSession runs (for example, a hybrid crash right after start) deleted the last run's session, so it was never finalized.

    readSessionFromEnvelope now finds the session item in any position, because a crash envelope (UncaughtExceptionHint, which counts as a SessionEnd) has the event first. The SessionEnd read runs on the transport thread. The InternalSentrySdk delete runs on the calling thread only when the process is about to crash (maybeStartNewSession false) or the caller is not on the main thread; otherwise it runs on the options executor.

  • The SessionStart path and the two-argument movePreviousSession behave as on main.

💡 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?

EnvelopeCacheTest cases for both init race orders (persistCurrentSession, then the init-time move; a SessionStart store, then the init-time move): previous_session.json holds the last run's session and session.json holds the live one. Both fail without the sid check. More cases cover:

  • the init-time move with a live session that is not written yet, and with no live session (both move the last run's session);
  • persistCurrentSession after the previous session was handled (an earlier session of this process is not moved; fails without the latch check);
  • a failed rename (the live session is still written and the init-time move skips it);
  • a failed rename plus a failed write (the file is not deleted, and a later move picks it up; the test's throwing serializer truncates the file, so it checks that the file is kept and moved, not its content);
  • a failed write after a successful move (the next SessionStart does not delete the saved previous session).

MovePreviousSessionTest checks that the task passes its scopes to the cache.

Safe deletes: a queued SessionEnd of 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; deleteCurrentSessionFile deletes for the ended session, keeps another session, and deletes when no id is given; in InternalSentrySdkTest, captureEnvelope deletes 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, LifecycleWatcherTest and the ApplicationExit* tests.

📝 Checklist

  • I added GH Issue ID & Linear ID
  • I added tests to verify the changes.
  • No new PII added or SDK only sends newly added PII if sendDefaultPII is enabled.
  • I updated the docs if needed.
  • I updated the wizard if needed.
  • Review from the native team if needed.
  • No breaking change or entry added to the changelog.
  • No breaking change for hybrid SDKs or communicated to hybrid SDKs.
  • Public API changes reviewed by another Mobile SDK team member or implemented according to the develop docs spec.

🔮 Next steps

🤖 Generated with Claude Code

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>
@linear-code

linear-code Bot commented Nov 27, 2026

Copy link
Copy Markdown

JAVA-792

@github-actions github-actions Bot added the risk: medium PR risk score: medium label Nov 27, 2026
@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

PR risk: medium

For commit 2f787fe.

Main concerns: reach, public contract, data sent to Sentry.

Rules that block low also fired:

  • R4: a public API record changed: sentry/api/sentry.api

This label is a hint for reviewers, not an approval.

@romtsn
romtsn marked this pull request as ready for review November 27, 2026 13:15
@romtsn
romtsn requested review from a team and adinauer as code owners November 27, 2026 13:15
@romtsn
romtsn requested review from markushi and runningcode and removed request for a team November 27, 2026 13:15
@romtsn romtsn added the sanity-check PR needs a lightweight review for obvious issues label Nov 27, 2026
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Nov 27, 2026
@sentry

sentry Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

📲 Install Builds

Android

🔗 App Name App ID Version Configuration
SDK Size io.sentry.tests.size 8.67.0 (1) release

⚙️ sentry-android Build Distribution Settings

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>
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Nov 27, 2026
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>
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Nov 27, 2026
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>
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Nov 27, 2026
…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>
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Nov 27, 2026

@0xadam-brown 0xadam-brown left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
  • persistCurrentSession rotates 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...

@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 2, 2026
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 2, 2026
romtsn and others added 2 commits December 3, 2026 13:43
…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>
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 3, 2026
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>
@github-actions github-actions Bot removed the risk: medium PR risk score: medium label Dec 3, 2026
@github-actions

github-actions Bot commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

🚨 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:

  • sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java

@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 3, 2026
…tact

Co-Authored-By: Claude <noreply@anthropic.com>
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 3, 2026
Co-Authored-By: Claude <noreply@anthropic.com>
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 3, 2026
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>
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 3, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk: medium PR risk score: medium sanity-check PR needs a lightweight review for obvious issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Investigate startup race moving the live session file

3 participants