Title: fix(android): Don't block callers on network status registration by 0xadam-brown · Pull Request #6537 · getsentry/sentry-java · GitHub
Open Graph Title: fix(android): Don't block callers on network status registration by 0xadam-brown · Pull Request #6537 · getsentry/sentry-java
X Title: fix(android): Don't block callers on network status registration by 0xadam-brown · Pull Request #6537 · getsentry/sentry-java
Description: This PR's diff looks more involved than it actually is. Most of the changes are new docs and tests. Prod changes are limited to introducing a new ConnectionSnapshot that combines a number of previously distinct fields + minor revisions in bookkeeping needed to update that snapshot vs the previous fields. 📜 Description AndroidConnectionStatusProvider no longer makes callers wait while it registers its network and telephony callbacks with system services. That's good because one of those callers is Sentry.init. The problem Before this change, AndroidConnectionStatusProvider used one lock to guard three code paths: callback registration, connection cache refreshes, and adding or removing observers. The SDK executor held that lock across ConnectivityManager.registerDefaultNetworkCallback and, on API 31+, TelephonyManager.registerTelephonyCallback. Both are calls into system services that can occasionally block for seconds. The main thread waited on the same lock in two places: Session Replay adding its observer during Sentry.init. Every captured event reading the connection type or status. If the system service registrations took a while, the main thread would stall. Scenario (1) in particular could lead to ANRs during app startup. Oof. A road not taken Any fix has to isolate the slow part (registration) so that the main thread can return quickly when reading cached network info or adding observers. The narrowest approach would be to give registration its own lock and keep a second lock for the cache and observers. But a refresh would then either hold the cache lock while querying Android, making readers wait on that query, or need a version counter that every write must remember to update. Even worse, two locks would need to document order they're taken in to avoid deadlock, which would be easy to get wrong. That's^^ the approach my clanker initially implemented (see commit 1). But there's a better way... A better approach (and the one this PR implements) The approach I ultimately landed on was to avoid having the main thread hold a lock entirely, and instead rely on atomically publishing cached network info (see commit 2). I did so by introducing a new ConnectionSnapshot class, which is immutable and can be safely shared across threads. I stored observers in copy-on-write lists rather than having them be explicitly locked, and I confined registration to the the SDK executor (it's still defensively guarded by its own lock). Callers that need to access cached network info or register observers can now return quickly. Either of approach would have allowed as much, of course, but the benefit of introducing the snapshot it that it also: lets us consolidate a lot of related state that the provider previously had to handle separately avoids the pain of managing (yet another) lock lays the groundwork for future PRs that confine refreshes to the SDK executor and let snapshots tell a lost network from capabilities that are simply unknown. Bonus points It took me a while to figure out exactly what policies AndroidConnectionStatusProvider implemented, and so I've updated the docs to make that clearer. I've also renamed a few things that threw me for a loop (eg, isConnected -> onAvailableForwarded, as it's actually a flag to make sure the provider only forwards onAvailable calls to clients at most once, and shouldn't be used to determine whether the network is currently connected). Reviewing by commit In case it's helpful, I got my clanker to break up this work into coherent commits. Personally, I'd limit myself to reviewing the final diff, but up to you. Commit Change 1. fix: Don't block callers on connection status registration The core fix and its concurrency tests. The cache still uses a lock plus a version counter here. 2. ref: Hold the connection cache in an immutable snapshot Replaces that lock and counter. It also fixes two races: onAvailable wrote the network without the lock, and the status lookup read the capabilities twice. 3. fix: Don't register connection callbacks again after close Fixes a leak introduced by commit 1's asynchronous registration. 4. ref: Rename isConnected to onAvailableForwarded Rename only. 5. `fix: Build the connection cache debug log only when debug logging is on 6. docs: Document the threading and exception policies Javadoc and field order. No behavior change. 7. test: Improve the concurrency tests Risks and costs Performance and memory: Negligible. One small snapshot object per network event or cache refresh. Copy-on-write lists, which only change at init and close; notifying doesn't allocate. One extra executor task per app foreground or background switch. Crash risk: No new risks, and one existing risk removed. The new copy-on-write lists eliminate a latent ConcurrentModificationException, which could happen under the previous approach when an observer removed itself on the notifying thread. Leaks: No new risks. The closed flag covers the one potential leak asynchronous registration would otherwise add. Two leaks predate this PR and are unchanged: If the executor drops the close task, the system callbacks stay registered. An observer added after close() is never cleared. Behavior changes: None visible to users under normal operation. In a rare race after the app returns to the foreground, a network breadcrumb could be duplicated or missed. No crash or data loss. Closing the SDK while registration is still pending now skips the registration entirely. Nothing is left registered either way. 💡 Motivation and Context App-start ANRs reported in #6509, a regression from #6146 (8.60.0 through 8.63.0). resolves: #6509 resolves: JAVA-828 💚 How did you test it? Concurrency tests Unit tests Had my clanker manually check via the sample app that the approach here fixes things. 📝 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 Hybrid SDKs: once released, ask them to upgrade, and add a known-issue note to 8.60.0 through 8.63.0. Possible follow-ups for AndroidConnectionStatusProvider, in separate PRs: (Existing issues I noticed while implementing the current PR . Out of scope for now.) Stale-cache reads still query the ConnectivityManager on the caller's thread. A snapshot without capabilities falls back to that query on every read. We don't extend the cache lifetime for network capability changes that don't affect the status. Concurrent stale reads can query for network info more than once. Registration state could also become an explicit state model. Fix the potential (and preexisting) leaks mentioned under "Risks and Costs".
Open Graph Description: This PR's diff looks more involved than it actually is. Most of the changes are new docs and tests. Prod changes are limited to introducing a new ConnectionSnapshot that combines a number of pr...
X Description: This PR's diff looks more involved than it actually is. Most of the changes are new docs and tests. Prod changes are limited to introducing a new ConnectionSnapshot that combines a number o...
Opengraph URL: https://github.com/getsentry/sentry-java/pull/6537
X: @github
Domain: github.com
IPv4 address: 140.82.114.4
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /:user_id/:repository/pull/:id/files(.:format) |
| route-controller | pull_requests |
| route-action | files |
| fetch-nonce | v2:c9979a5a-3595-23bc-4d05-458e0fe0e5d8 |
| current-catalog-service-hash | ae870bc5e265a340912cde392f23dad3671a0a881730ffdadd82f2f57d81641b |
| request-id | 952E:2CE84F:828689:B88353:6B0452EF |
| html-safe-nonce | 97d89c4e4749ed1012dfcdbb80c6611b2d259f40cf49ee11d0158330d6023905 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5NTJFOjJDRTg0Rjo4Mjg2ODk6Qjg4MzUzOjZCMDQ1MkVGIiwidmlzaXRvcl9pZCI6IjcwMDMwNzQ3NzA2OTkwNDc2NjMiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 7efd4811f49c7b8a931aaa630fcaf4bdbfd6543cfb6cd470f6c8750c2944d76f |
| hovercard-subject-tag | pull_request:5239311308 |
| github-keyboard-shortcuts | repository,pull-request-list,pull-request-conversation,pull-request-files-changed,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/getsentry/sentry-java/pull/6537/files |
| twitter:image | https://avatars.githubusercontent.com/u/281682121?s=400&v=4 |
| twitter:card | summary_large_image |
| og:image | https://avatars.githubusercontent.com/u/281682121?s=400&v=4 |
| og:image:alt | This PR's diff looks more involved than it actually is. Most of the changes are new docs and tests. Prod changes are limited to introducing a new ConnectionSnapshot that combines a number of pr... |
| og:site_name | GitHub |
| og:type | object |
| hostname | github.com |
| expected-hostname | github.com |
| None | 910ca0e260cfec6aff11407d8dc6a0d3a4cd381a2ec9ada56627b063426892a0 |
| turbo-cache-control | no-preview |
| diff-view | unified |
| go-import | github.com/getsentry/sentry-java git https://github.com/getsentry/sentry-java.git |
| octolytics-dimension-user_id | 1396951 |
| octolytics-dimension-user_login | getsentry |
| octolytics-dimension-repository_id | 3368190 |
| octolytics-dimension-repository_nwo | getsentry/sentry-java |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 3368190 |
| octolytics-dimension-repository_network_root_nwo | getsentry/sentry-java |
| turbo-body-classes | logged-out env-production page-responsive full-width |
| disable-turbo | true |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | e086f9b7e88322eb2b41885a6ad425b215737fa5 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
Links:
| Server | github.com |
| Content-Type | text/html; charset=utf-8 |
| Cache-Control | no-cache |
Viewport: width=device-width