Skip to content

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

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

romtsn wants to merge 6 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.

This PR adds an EnvelopeCache.previousSessionMoved flag, guarded by sessionLock:

  • A successful move of session.json to previous_session.json sets the flag. A failed rename leaves it unset, so a later move can retry.
  • The init-time movePreviousSession does nothing when the flag is set.
  • persistCurrentSession does the move first if the flag is not set yet, so the last run's session is kept. A successful write sets the flag even if the move failed, because the file then holds the live session. After a failed write, the truncated file is deleted only if the move worked; otherwise it can still be the last run's session and stays for a retry.
  • The SessionStart path still moves every time (now through a private helper), so session rotation after the app was in the background does not change.

💡 Motivation and Context

The race was seen as a flaky InternalSentrySdkTest (worked around on the test side in #6358). It was not observed in production, but a hybrid SDK that reports an error right after init could hit it.

💚 How did you test it?

Two new EnvelopeCacheTest cases: persistCurrentSession, then the init-time move, and a SessionStart store, then the init-time move. Both check that previous_session.json holds the last run's session and session.json holds the live one. Both fail without the fix. More cases cover 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 stays for a later move), and a failed write after a successful move (the next SessionStart does not delete the saved previous session).

Known limit: the flag lives as long as the EnvelopeCache. A re-init reuses the cache only if the same SentryOptions object goes to Sentry.init again. SentryAndroid.init always creates new options, and a GitHub code search found no public code that reuses an options object across inits, so this PR does not reset the flag on init.

Also ran EnvelopeCacheTest, MovePreviousSessionTest, PreviousSessionFinalizerTest, SentryTest, InternalSentrySdkTest 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

The workaround in InternalSentrySdkTest from #6358 can stay. It is still a valid way to wait for the init-time move.

🤖 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 cb9213a.

Main concerns: reach, data sent to Sentry, host performance.

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.66.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...

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

2 participants