Skip to content

fix: pause and resume sessions when mobile apps move to the background - #5863

Merged
jamescrosswell merged 7 commits into
mainfrom
fix/maui-session-pause-resume
Nov 8, 2026
Merged

jamescrosswell merged 7 commits into
mainfrom
fix/maui-session-pause-resume

Conversation

@bitsandfoxes

@bitsandfoxes bitsandfoxes commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

On iOS, Mac Catalyst and Android, the SDK starts the session when the app comes to the foreground, pauses it when the app goes to the background and resumes it when the app comes back. A background longer than AutoSessionTrackingInterval ends the session as exited at the time it was paused and starts a new one. An app killed while in the background recovers its session as exited on the next launch instead of abnormal. A process launched in the background (a push, a broadcast, a job, a background fetch) doesn't start a session, the same as sentry-java and sentry-cocoa.

Closes #5842

Changelog Entry

  • Sessions on iOS, Mac Catalyst and Android now pause when the app moves to the background. A background longer than AutoSessionTrackingInterval ends the session, and an app killed in the background reports exited instead of abnormal.
  • On those platforms, background launches no longer start a session, the same as in sentry-java and sentry-cocoa. On iOS and Mac Catalyst, sessions now start when the app first becomes active, so a crash before that no longer counts as a crashed session.

How it works

  • AutoSessionTrackingIntegration recovers the previous run's session at init. On mobile it then subscribes to the app lifecycle, which starts the session on the first foreground; other platforms still start it at init. The Hub disposes the subscription with the integration. This covers MAUI and plain net-android / net-ios apps; Sentry.Maui is unchanged.
  • Android: a ProcessLifecycleOwner observer pauses on ON_STOP, and on ON_START resumes the session or starts one if there is none. It is process-wide, so switching between activities doesn't pause. Like SentryAndroid.init in sentry-java, it also starts a session at init if the process has foreground importance, so a foreground launch has a session from the start. If the observer can't be added, or ProcessLifecycleOwner was never initialized (the app removed androidx.startup's InitializationProvider), a foreground launch gets a session that doesn't pause. A background launch gets none, even if the user opens the app later, the same as sentry-java.
  • iOS / Mac Catalyst: DidEnterBackground and WillTerminate pause; WillEnterForeground and DidBecomeActive resume or start. An app that is already Active at init (the SDK initialized late) starts its session straight away.
  • With iOS Session Replay enabled, the Cocoa SDK owns sessions and AutoSessionTracking is off, so nothing subscribes.

GlobalSessionManager:

  • Recovering the previous session deletes its file. Otherwise a background launch that never starts a session would send it again on the next launch, as crashed if that background run crashed.
  • A resume within the interval re-persists the session without the pause timestamp, so a later kill in the foreground still recovers as abnormal.
  • A second pause keeps the first pause timestamp; a resume without a pause only logs at debug.
  • The first error persists the session (keeping the pause state), so a recovered session reports errors: 1.
  • Session state and the session file are guarded by one lock, since errors are reported from capture threads.

Behaviour changes worth noting

  • SentrySdk.IsSessionActive is false between Init and the first foreground on iOS and Mac Catalyst, and after a background launch on Android.
  • Release health shows fewer sessions on mobile, since background launches no longer create short exited sessions.
  • On iOS and Mac Catalyst, a crash before the app first becomes active sends the crash event but no session update, so it doesn't count as a crashed session. On MAUI, that window covers the App and main page constructors. Session counts and crash-free rates can shift after an upgrade. sentry-cocoa works the same way. On Android, the same crash during a foreground launch still counts as crashed.

Verified on devices

MAUI sample pointed at a local envelope logger, default 30s interval. On main, a Pixel 6 reproduces the issue (no split after 45s, background kill recovers as abnormal with errors: 0). With the first version of this change, before sessions waited for the foreground:

Scenario Pixel 6 (Android 16) iPhone (iOS)
45s background, foreground exited at pause time + new session same
10s background, foreground same session same
Background, kill, relaunch recovered exited same
Short background, kill in foreground recovered abnormal same
Error, kill in foreground recovered abnormal, errors: 1 same
Error in background, kill recovered exited, errors: 1 not run (iOS suspends the app first)
Foreground cold launch no pause no pause

Re-run after the foreground-start change, with the same app and envelope logger. Launch, 45s background then foreground, and background kill then relaunch gave the same results on an Android emulator (API 37, 947d62d) and an iOS 26.5 simulator (34a4de1). The other rows haven't been re-run.

Also on the Android emulator at 947d62d:

Scenario Default manifest InitializationProvider removed
Background launch (BroadcastReceiver) no session no session
Background launch, then foreground session starts at foreground no session
Foreground launch, Home, kill, relaunch recovered exited recovered abnormal
Crash in the App constructor event + crashed session not run

Background launches haven't been run on iOS.

🤖 Generated with Claude Code

bitsandfoxes and others added 3 commits November 3, 2026 13:49
Closes #5842

Co-Authored-By: Claude <noreply@anthropic.com>
Delay the Android background-launch pause past a cold start, resume on
DidBecomeActive on iOS, use the Lock type, and test the platform trackers.

Co-Authored-By: Claude <noreply@anthropic.com>
…enter

Co-Authored-By: Claude <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.95833% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 76.71%. Comparing base (bd29a48) to head (947d62d).
⚠️ Report is 15 commits behind head on main.

Files with missing lines Patch % Lines
src/Sentry/SentryOptions.cs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5863      +/-   ##
==========================================
+ Coverage   76.67%   76.71%   +0.04%     
==========================================
  Files         528      531       +3     
  Lines       19527    19757     +230     
  Branches     3840     3899      +59     
==========================================
+ Hits        14972    15157     +185     
- Misses       3670     3715      +45     
  Partials      885      885              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@jamescrosswell

Copy link
Copy Markdown
Collaborator

No red flags from my clunker (I haven't read in detail yet)... the only question it raised is a discrepancy between how we do this in .NET vs the native SDKs:

Start the session only when the app comes to the foreground. This is the main way it differs from sentry-java and sentry-cocoa, which only start a session once the app is in the foreground. So an app woken in the background for a push, a broadcast or a job gets no session there. .NET still starts one at Init, then pauses it (after 5s on Android, at startup on iOS). Those wake-ups therefore still show up as short exited sessions. This behaviour existed before the PR. The PR turns those sessions from abnormal into exited but doesn’t bring the counting in line with the native SDKs. Fixing that properly means changing when StartSession runs on mobile, which is a bigger change.

Given that this behaviour predates this PR, probably not something to address/change in this PR but more a question of whether we want to change this for consistency in a follow up @ric-oliv @bitsandfoxes ?

@ric-oliv

ric-oliv commented Nov 4, 2026

Copy link
Copy Markdown
Member

Looking good!

I'd actually do the follow up here... The work needed is not too big, and it removes both background-launch checks.
Two things to watch: keep recovering the previous session at Init (split it out of StartSession), and delete the session file once it's recovered. Otherwise a background launch that never starts a session sends the previous one again on the next launch, as crashed if that background run crashed.

Background launches (a push, a broadcast, a job, a background fetch) no
longer start a session, matching sentry-java and sentry-cocoa. This
replaces the Android 5-second and iOS at-init background checks.

The previous run's session is still recovered at init, split out of
Hub.StartSession, and its file is deleted once recovered. Otherwise a
background launch that never starts a session would send it again on
the next launch, as crashed if that background run crashed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jamescrosswell

Copy link
Copy Markdown
Collaborator

I'd actually do the follow up here

@ric-oliv / @bitsandfoxes I added a commit for this.

@jamescrosswell
jamescrosswell marked this pull request as ready for review November 4, 2026 21:26
@github-actions github-actions Bot added the risk: high PR risk score: high label Nov 4, 2026

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Want reviews to match your repository better? Bugbot Learning can learn team-specific rules from PR activity. A team admin can enable Learning in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 77e0624. Configure here.

…not attached

Apps that remove androidx.startup's InitializationProvider never attach
ProcessLifecycleOwner, so ON_START never fires and no session would start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@ric-oliv ric-oliv 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.

Thanks @jamescrosswell! One more thing:

A crash before the first foreground no longer counts as a crashed session. On MAUI that window covers the App and main page constructors. I threw from the App constructor on an Android emulator and an iOS simulator, and both sent the crash event but no session update. sentry-java and sentry-cocoa work the same way, so I'm fine with it. I'd still list it under the behavior changes and add a ### Changelog Entry, since session counts and crash-free rates can shift after an upgrade. Maybe something like this:

### Changelog Entry

- Sessions on iOS, Mac Catalyst and Android now pause when the app moves to the background. A background longer than `AutoSessionTrackingInterval` ends the session, and an app killed in the background reports `exited` instead of `abnormal`.
- On those platforms, sessions now start when the app first comes to the foreground, the same as in sentry-java and sentry-cocoa. Background launches no longer start a session, and a crash before the first foreground no longer counts as a crashed session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jamescrosswell

Copy link
Copy Markdown
Collaborator

@ric-oliv Thanks. I added the crash before the first foreground to "Behaviour changes worth noting", added the ### Changelog Entry section, and applied both test suggestions in 34a4de1.

I also re-ran launch, 45s background then foreground, and background kill then relaunch against a local envelope logger, on an Android emulator and an iOS simulator. Both gave the expected session updates. The PR description lists what has not been re-run.

…e foreground

Matches SentryAndroid.init in sentry-java: a foreground launch has a session
from init, so a crash before ON_START counts as a crashed session, and a
background launch never starts one, even when ProcessLifecycleOwner is not
attached.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jamescrosswell

Copy link
Copy Markdown
Collaborator

@ric-oliv One correction since your review: sentry-java doesn't wait for the first foreground in the way we both assumed. SentryAndroid.init also starts a session at init if the process has IMPORTANCE_FOREGROUND. sentry-cocoa only does that if the app is already active, so iOS and Mac Catalyst are unchanged.

947d62d does the same on Android:

  • A foreground launch has a session from init. Throwing from the App constructor on an Android emulator now sends the event and a crashed session, so the crash trade-off you accepted now only applies to iOS and Mac Catalyst.
  • A background launch sends no session, and that now includes apps that removed InitializationProvider. Those apps get no session if the user opens the app after a background launch, which is the same gap sentry-java has.

I reworded the second ### Changelog Entry bullet and the behaviour notes to match. The PR description has the emulator results. Android hardware and iOS background launches haven't been run.

@ric-oliv

ric-oliv commented Nov 6, 2026

Copy link
Copy Markdown
Member

Good catch, LGMT!

@jamescrosswell
jamescrosswell merged commit 6998c4b into main Nov 8, 2026
60 checks passed
@jamescrosswell
jamescrosswell deleted the fix/maui-session-pause-resume branch November 8, 2026 20:22
This was referenced Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk: high PR risk score: high

Projects

None yet

3 participants