Skip to content

feat(android): Recover MemoryLimiter app exits on startup (JAVA-687) - #6111

Merged
0xadam-brown merged 8 commits into
mainfrom
feat/memory-limiter-integration
Sep 16, 2026
Merged

0xadam-brown merged 8 commits into
mainfrom
feat/memory-limiter-integration

Conversation

@0xadam-brown

@0xadam-brown 0xadam-brown commented Sep 14, 2026

Copy link
Copy Markdown
Member

📜 Description

Introduces a new MemoryLimiterIntegration that captures process deaths attributable to Android 17's new MemoryLimiter system service (see also here).

Process death info is extracted from ApplicationExitInfo on the next app launch. We then enrich it with persisted SDK state and send it to Relay as a fatal Sentry event.

Integration is experimental; is disabled by default; and is only available for Android API >= 37.

💡 Motivation and Context

Android 17 (API 37) introduced a new system service called MemoryLimiter that's responsible for killing app processes if they threaten to consume too much system memory.

The tricky part for us is that MemoryLimiter-caused process deaths don't involve an exception or a stack trace, making them invisible to our current instrumentation. This PR fills the gap by using ApplicationExitInfo to extract info about relevant exits on subsequent app launches. It does so by piggybacking on the ApplicationExitInfo processing pipeline used by ANRs and tombstones.

resolves: JAVA-687

Out of scope

This PR doesn't implement:

  • The reporting of non-fatal memory pressure or anomaly signals. (MemoryLimiter can throttle processes' memory allocations before killing them.) For now we only record process deaths.
  • Binding profiling artifacts to MemoryLimiter events, when available (e.g., trigger-based profiling generated by ProfilingManager).

We can revisit both going forward as we discover what will be most helpful to developers.

Basic flow

App process dies 
             |
             v                                                                                                                                                                                                                                                                                                                                             Android OS keeps a retained ApplicationExitInfo record                                                                                                                                                                                                                                                                                              
             |                                                                                                                                                                                                                                                                                                                                        
             v                                                                                                                                                                                                                                                                                                                                        
Next app launch initializes Sentry                                                                                                                                                                                                                                                                                                               
             |                                                                                                                                                                                                                                                                                                                                        
             +--> ApplicationExitInfo integrations (incl. MemoryLimiterIntegration) register a policy                                                                                                                                                                                                                                                                                                      
             |       ANR / Tombstone / MemoryLimiter                                                                                                                                                                                                                                                                                                  
             |                                                                                                                                                                                                                                                                                                                                        
             v                                                                                                                                                                                                                                                                                                                                        
Each integration creates its own ApplicationExitInfoHistoryDispatcher which...                                                                                                                                                                                                                                                                                                             
             |                                                                                                                                                                                                                                                                                                                                        
             +--> finds the latest matching exit, if any
             +--> optionally reports older matching exits                                                                                                                                                                                                                                                                                              
             +--> captures synthetic Sentry event(s) for all reported exits                                                                                                                                                                                                                                                                                                  
             |                                                                                                                                                                                                                                                                                                                                        
             v               
ApplicationExitInfoEventProcessor                                                                                                                                                                                                                                                                                                                
             |                                                                                                                                                                                                                                                                                                                                        
             +--> makes sure Sentry events for exits are bound to contextual data from previous process (not current).
             +--> attaches persisted scope/options when safe                                                                                                                                                                                                                                                                                            
             +--> keeps old historical exits lighter                                                                                                                                                                                                                                                                                                   
             |                                                                                                                                                                                                                                                                                                                                        
             v                                                                                                                                                                                                                                                                                                                                        
Envelope cache writes event and dedupe marker                                                                    

Each integration's ApplicationExitInfoHistoryDispatcher asks the ActivityManager for all recorded exits and does the following per policy:

Pick first matching exit as "latest"                                                                                                                                                                                                                                                                                                           
             |                                                                                                                                                                                                                                                                                                                                        
             +--> if too old or already reported: stop                                                                                                                                                                                                                                                                                                
             |                                                                                                                                                                                                                                                                                                                                        
             +--> if historical reporting enabled: report historical matches oldest -> newest  with shouldEnrich = false                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
             |                                                                                                                                                                                                                                                                                                                                        
             v                                                                                                                                                                                                                                                                                                                                        
Report latest match with shouldEnrich = true 
             |
             v
Delegate to the policy to synthesize the base Sentry event  (to be enriched downstream if shouldEnrich = true)   

Note: there's definitely room for optimization here, in that each integration (when enabled) creates its own ApplicationExitInfoHistoryDispatcher, each dispatcher asks ActivityManager for the exit list, and each dispatcher scans the same exit list looking for matches against the policy it manages. But that's work for another day. Atm, this PR simply extends the pattern that already existed with ANRs and tombstones.

Screenshot

memory-limiter-3

I highlighted relevant info via the red boxes.

Screenshot URL: link

💚 How did you test it?

  1. Added plenty of integration and unit tests. Hooray.
  2. Had my clanker verify via our existing ANR and tombstone sample apps that enabling the MemoryLimiterIntegration doesn't interfere with current ANR or tombstone collection.
  3. I also created a sample app that verified everything downstream of actual OS functionality.

⚠️ W/r/t (3), current Android emulator images disable MemoryLimiter and I lack a physical device, so I haven't been able to test against actual OS behavior. That means we're depending on the Android 17 docs's accuracy when they claim that MemoryLimiter kills will be accompanied by REASON_OTHER and a "MemoryLimiter:AnonSwap" description. It'd be nice to see what actual OEM OS's return in the wild, however.

📝 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

  1. Follow-on PR to be merged in same release as this one: For the sake of release health, recovered MemoryLimiter exits should mark the previous session abnormal at the recorded exit timestamp. (At present, the killed session is finalized as if it exited normally.) --> See chore(android): Mark MemoryLimiter sessions as having exited abnormally (JAVA-687) #6113.
  2. PR for the MemoryLimiterIntegration sample app.
  3. sentry-docs PR

Event path vs session path

The follow-on PR from (1) is needed because the current PR only covers the event path from the diagram below. The follow-on will cover the session path:

 Recovered process death on next launch                                                                                                                                                                                                                                                                                                           
             |                                                                                                                                                                                                                                                                                                                                        
             +--> Event path  (condensed from "Basic Flow" section above)                                                                                                                                                                                                                                                                                                                        
             |       dispatcher -> synthetic event -> backfill -> envelope                                                                                                                                                                                                                                                                            
             |                                                                                                                                                                                                                                                                                                                                        
             +--> Session path                                                                                                                                                                                                                                                                                                                        
                     previous session file -> abnormal/crashed end state 

@linear-code

linear-code Bot commented Sep 14, 2026

Copy link
Copy Markdown

JAVA-687

@github-actions

github-actions Bot commented Sep 14, 2026

Copy link
Copy Markdown
Contributor
Fails
🚫 Please consider adding a changelog entry for the next release.
Messages
📖 Do not forget to update Sentry-docs with your feature once the pull request gets approved.

Instructions and example for changelog

Please add an entry to CHANGELOG.md to the "Unreleased" section. Make sure the entry includes this PR's number.

Example:

## Unreleased

### Features

- Recover MemoryLimiter app exits on startup (JAVA-687) ([#6111](https://github.com/getsentry/sentry-java/pull/6111))

If none of the above apply, you can opt out of this check by adding #skip-changelog to the PR description or adding a skip-changelog label.

Generated by 🚫 dangerJS against 014e7c6

@sentry

sentry Bot commented Sep 14, 2026

Copy link
Copy Markdown

📲 Install Builds

Android

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

⚙️ sentry-android Build Distribution Settings

Comment thread sentry-android-core/api/sentry-android-core.api
Introduce a new MemoryLimiterIntegration that captures process deaths attributable to Android 17's new [MemoryLimiter](https://source.android.com/docs/core/perf/memory-limiter#process-monitoring) system service (see also [here](https://android-developers.googleblog.com/2026/06/prioritizing-memory-efficiency-steps-for-android-17.html)).

Process death info is extracted from ApplicationExitInfo on the next app launch. We then enrich it with persisted SDK state and send it to Relay as a fatal Sentry event.

Integration is experimental; is only available for Android API >= 37; and is disabled by default.
Add a data-driven test over every ApplicationExitInfo importance band,
including the default fallback, to lock the getProcessVisibility mapping.
… prefix

Match the "MemoryLimiter:" prefix instead of the full "MemoryLimiter:AnonSwap"
string. Per AOSP, AnonSwap is the only MemoryLimiter kill sub-reason on
Android 17, but the memory and swap limits it also tracks may start killing in a
future release; matching the namespace prefix keeps capturing those without a
code change, while the colon still anchors matching to the MemoryLimiter
namespace. The raw description is retained on the event mechanism.
@0xadam-brown
0xadam-brown force-pushed the feat/memory-limiter-integration branch from c38bf03 to cc0773d Compare September 14, 2026 12:35
@0xadam-brown
0xadam-brown marked this pull request as ready for review September 14, 2026 12:51
@0xadam-brown 0xadam-brown added the deep-dive PR needs a thorough review of design, behavior, and edge cases label Sep 14, 2026

@runningcode runningcode left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The overall pattern looks good to me! just some comments.

@markushi markushi 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.

Looking good, left a few minor comments. I'm holding off to approving it for now, due to the follow up PR.

Also renames "importance" -> "process_importance" and "process_visibility" -> "memory_limit_class" to better match the language used in the MemoryLimiter docs here: https://source.android.com/docs/core/perf/memory-limiter#process-monitoring
… int from message

The deprecated process importance info was unneeded as it's only present pre-API 37, while our integration is only available starting on API 37.

The process importance int in the message ended up being redundant, b/c the error detail view shows a separarate listing for that int immediately below the importance string.
@0xadam-brown
0xadam-brown merged commit bc5c4c9 into main Sep 16, 2026
96 of 98 checks passed
@0xadam-brown
0xadam-brown deleted the feat/memory-limiter-integration branch September 16, 2026 12:46
runningcode added a commit that referenced this pull request Sep 18, 2026
* ref(android): Mark AppStartMetrics.setAppStartType as @testonly (#6121)

No production code calls this setter; the cold/warm classification assigns
the field directly. Its only callers are tests, so annotate it the way the
neighboring test seams (setFirstIdle, getFirstIdle, clear) already are.

It has to stay public: most of those call sites live in
io.sentry.android.core, a different package from AppStartMetrics.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(android): Recover MemoryLimiter app exits on startup (JAVA-687) (#6111)

Introduce a new MemoryLimiterIntegration that captures process deaths attributable to Android 17's new [MemoryLimiter](https://source.android.com/docs/core/perf/memory-limiter#process-monitoring) system service (see also [here](https://android-developers.googleblog.com/2026/06/prioritizing-memory-efficiency-steps-for-android-17.html)).

Process death info is extracted from ApplicationExitInfo on the next app launch. We then enrich it with persisted SDK state and send it to Relay as a fatal Sentry event.

Integration is experimental; is only available for Android API >= 37; and is disabled by default.

* fix(core): Keep resolving the hostname after Sentry.close() (#6119)

* fix(core): Keep resolving the hostname after Sentry.close()

MainEventProcessor was Closeable, so Scopes.close() closed it, and it shut
down the process-wide HostnameCache singleton. Nothing ever replaced that
singleton: INSTANCE is assigned once and never cleared, so a re-init handed the
same shut-down cache to the new MainEventProcessor, and to MetricsApi and
LoggerApi, which read it directly.

The damage was silent and permanent. While the cache was still fresh,
getHostname() kept returning the value it already had. On the first expiry
after the close, getHostname() flipped updateRunning to true and then
submit() threw RejectedExecutionException on the terminated executor. That is
a RuntimeException, so it was swallowed into handleCacheUpdateFailure(), but
the updateRunning reset lives in the submitted callable's finally block, which
never ran. updateRunning stayed true, so the compareAndSet guard failed from
then on and no refresh was ever attempted again. server_name froze at its last
resolved value for the life of the process, with no exception and no log line.

Nothing needs to close this cache. Its executor is a single daemon thread with
allowCoreThreadTimeOut(true) and a 30 second keep-alive, so the worker exits on
its own once idle and never holds up process exit; the thread exists for about
30 seconds out of every 5 hour refresh interval. Scopes.close() already leaves
the timer executor running for exactly this reason.

The one test that covered this path, SentryClientTest's `when client is closed,
hostname cache is closed`, asserted isClosed() on a processor that had never
resolved a hostname, where isClosed() returned true because the cache was still
null. It never exercised the behavior it named. Replaced with an assertion that
MainEventProcessor is not Closeable, which fails if the wiring comes back.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* changelog

* fix(core): Clear updateRunning when a refresh cannot be queued

updateRunning is cleared in exactly one place, the submitted callable's finally
block, so it is cleared if and only if the callable runs. Every failure from
Future.get() leaves the callable running, so it still clears the flag itself.
A failure from submit() does not: the callable was never queued, nothing clears
the flag, and the compareAndSet guard in getHostname() then fails forever, so
no refresh is ever attempted again.

Removing MainEventProcessor's close() took away the only reachable way to make
submit() throw, but the invariant was still wrong: a bounded queue, a shutdown
added later, or a failure to start a thread would silently resurrect the same
permanent freeze.

Splitting submit() out of the try means the two cases can be told apart.
Clearing the flag on a timeout or an interrupt as well would be wrong, since
the callable is still running there and refreshes would pile up behind a slow
lookup; MainEventProcessorTest's `sets servername to null if retrieving takes
longer time` covers that path.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(core): Drop the not-Closeable assertion

It asserted a type relationship rather than behavior, which says nothing about
whether the hostname keeps resolving. The behavior that matters is covered by
HostnameCacheTest: `worker thread times out while idle instead of staying
alive` guards the self-terminating executor that makes closing unnecessary, and
`a refresh that cannot be queued does not stop later refreshes` guards the
latch that turned a one-off failure into a permanent one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(core): Order breadcrumbs by their own timestamp (JAVA-579) (#6097)

* fix(core): Order breadcrumbs by their own timestamp (JAVA-579)

Breadcrumb.compareTo ordered purely by a System.nanoTime() reading taken
in the constructor. A breadcrumb rebuilt from a serialized one — read
back from disk, or handed over by a hybrid SDK — got that reading at
parse time, so a breadcrumb recorded yesterday sorted as if it had just
happened, and the merged order in CombinedScopeView became parse order.
The clone constructor had the same problem: copying a breadcrumb moved
it to the end of the order.

Order by the recorded timestamp instead, and keep the creation tick only
as the tie-breaker it was added for in #3355, since timestamps are
millisecond-granular. A deserialized breadcrumb carries no tick, and a
clone carries the original's, so neither jumps position.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* changelog

* ref(core): Keep the creation tick on deserialized breadcrumbs

Always fill the tick and let the timestamp comparison carry the fix, so
ordering no longer depends on every caller using a stable sort.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* ref(core): Sort breadcrumbs by their natural ordering in SentryClient

SortBreadcrumbsByDate compared timestamps only, so ties fell through to
the sort's stability. Breadcrumb.compareTo now defines that same order
with a defined tie-breaker, leaving the comparator a weaker duplicate of
it and the codebase with two definitions of breadcrumb order.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(android): Mark MemoryLimiter sessions as having exited abnormally (JAVA-687) (#6113)

Mark recovered MemoryLimiter exits as abnormal session endings so release health no longer treats the terminated process as a healthy exit. Reuses the existing AbnormalExit cache repair path with a stable memory_limiter mechanism and the OS exit timestamp.

* fix(changelog): Relocate misplaced CHANGELOG entries ahead of release (#6123)

* release: 8.57.0

* fix(core): Disable manifest URL caching when reading versions (JAVA-730) (#6124)

ManifestVersionReader was retaining jar-backed inflater state while scanning META-INF/MANIFEST.MF entries. Disable URL caching for those reads and close the stream after parsing.

* chore(deps): bump the github-actions group across 1 directory with 4 updates (#6110)

Bumps the github-actions group with 4 updates in the / directory: [actions/setup-java](https://github.com/actions/setup-java), [github/codeql-action/init](https://github.com/github/codeql-action), [github/codeql-action/analyze](https://github.com/github/codeql-action) and [getsentry/craft](https://github.com/getsentry/craft).


Updates `actions/setup-java` from 6.0.0 to 6.0.1
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](actions/setup-java@dd06d9c...de7274f)

Updates `github/codeql-action/init` from 4.37.9 to 4.38.0
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](github/codeql-action@cdf488f...b96794f)

Updates `github/codeql-action/analyze` from 4.37.9 to 4.38.0
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](github/codeql-action@cdf488f...b96794f)

Updates `getsentry/craft` from 2.30.1 to 2.31.0
- [Release notes](https://github.com/getsentry/craft/releases)
- [Changelog](https://github.com/getsentry/craft/blob/master/CHANGELOG.md)
- [Commits](getsentry/craft@cd1e829...55694f8)

---
updated-dependencies:
- dependency-name: actions/setup-java
  dependency-version: 6.0.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: github-actions
- dependency-name: getsentry/craft
  dependency-version: 2.31.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
- dependency-name: github/codeql-action/analyze
  dependency-version: 4.38.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
- dependency-name: github/codeql-action/init
  dependency-version: 4.38.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Adam Brown <adam.brown@sentry.io>
Co-authored-by: 0xadam-brown <281682121+0xadam-brown@users.noreply.github.com>
Co-authored-by: sentry-release-bot[bot] <180476844+sentry-release-bot[bot]@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

deep-dive PR needs a thorough review of design, behavior, and edge cases

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants