Step one of [mobile diagnostic reporting](https://github.com/block/buzz/blob/main/docs/mobile-diagnostic-reporting.md), first piece: the reporting module, plus capture of crashes and uncaught errors. A build given a `BUZZ_SENTRY_DSN` now reports native crashes, Flutter framework errors and uncaught asynchronous Dart errors to that Sentry project, attributed to the signed-in member's public key. A build without one (every build made from this repository alone) uses a do-nothing reporter and never initializes the SDK, as [ADR 0007](https://github.com/block/buzz/blob/main/docs/adr/0007-diagnostic-reporting-follows-the-destination.md) requires. A destination the SDK cannot parse is treated as none, so a configuration mistake never stops the app from starting. ### What's in it - **One interface** in `mobile/lib/shared/diagnostics/`: report an error, count a networking event, leave a breadcrumb, and set the member. It has a Sentry-backed and a do-nothing implementation. Only this folder imports the SDK. The explicit error reports and the networking counts that use it come in the next PRs. - **Startup** wraps `runBuzzApp` and installs the SDK's crash and error handlers only when a usable destination is set: one with an HTTP(S) host, a public key and a project, which the native SDKs also require. On Android, the manifest removes the SDK's startup performance provider, which would otherwise run before that check. - **Member:** set from the active community's key, changed when the account switches, cleared on sign-out. Adding the Builderlab origin and account subject is left to a later PR. Every report also carries a random per-install identifier the app creates on first launch, as its own `install.id` tag, signed in or not, so a device's reports can be matched to its members. It lives in a file that device backups and transfers skip, so a phone restored from another gets its own: on Android in the app's files directory, excluded in both backup rule sets; on iOS in an Application Support folder that a small native call marks as excluded from backup (not the caches folder, which iOS can clear when storage runs low). Set on the SDK scope, it also reaches native crash and hang reports. With no member set (before sign-in or after sign-out), the SDK also fills the report's user with its own random per-install identifier, on Dart and native reports alike. - **One filter** runs on every Dart report, breadcrumb and count before it leaves the device: - It replaces every error's own text with fixed wording, since an error can quote its input, a server's response body or a URL. The error keeps its type, mechanism type and stack trace. - It drops what the SDK adds about the failing platform call (`mechanism.data`) and the failing widget (`flutter_error_details`), which can quote what is on screen. - It removes URL query strings and fragments, and keeps only tags and count attributes on the allowed list. - It drops every breadcrumb except networking events and the SDK's foreground/background entries. - **SDK options:** personal data, screenshots, view hierarchy, replay and tracing stay off. The SDK's session records stay on, for a crash-free rate. A session begins each time the app starts or returns after 30 seconds or more in the background; the SDK sends a record when it begins, an update each time an error is counted, and a last one when it ends, carrying the start time, error count, outcome, time from start to end, release, environment and the random per-install identifier. Native auto-breadcrumbs, Android's network-change breadcrumbs (VPN state, signal strength, bandwidth; turned off in the manifest, since the Flutter bridge leaves them on), Cocoa's network breadcrumbs (which keep each request's query and reach native crash reports) and print breadcrumbs are off. With print breadcrumbs on, the SDK would replace `debugPrint` in non-debug builds with one that prints nothing. - **Main-thread hangs:** iOS app hang tracking, Android ANR detection and iOS watchdog-termination tracking are set on explicitly, at the SDK's default thresholds. iOS reports the main thread blocked, fully or mostly, for 2 s or more while the app is active, including freezes it recovers from; a hang still going when the system kills the app is sent on the next launch as a fatal hang, and watchdog-termination tracking reports a foreground run that ended with nothing else to explain it. Android reports only system-declared ANRs: on Android 11 and later, the most recent one that ended the process (read on the next launch, when the system kept a thread dump); before 11, after 5 s once the system marks the app not responding. So recoverable freezes are reported on iOS, and on Android only before 11 once the system marks the app not responding. Dart runs on the main thread, so blocking Dart work shows up with the main thread's stack; Dart frames need the Dart debug symbols at the destination, as crashes do. The spec now has a bullet and a user story for this. - **What the filter does not cover:** native crashes and app hangs are captured and sent by the native SDKs, which never call the Dart filter. They carry stack traces and, for a native exception, its reason text. No app code puts content in a native exception today. The spec now says this. - **Reporting never blocks the app or reaches it with an error:** every call returns at once, and a failure inside reporting is dropped with a `debugPrint`. ### Regressions None for builds without a destination, which includes every build from this repository: they run the same startup with one extra synchronous check, and the SDK is never initialized. The SDK still adds to the app's binary size on both platforms. With a destination, the first frame waits for the SDK to start, native SDK included, and for the install ID to be read from (or, on first launch, written to) a small file. On a debug simulator build the first frame came about 0.3 s later (median of 6 cold launches: 768 ms with a destination, 431 ms without), measured before the install ID was added. Device builds will differ. Uncaught errors still reach Flutter's default handling, and the SDK sends in the background. ### Validation Added tests (`test/shared/diagnostics/diagnostic_reporting_test.dart`): - A table of inputs run through the production Sentry options callbacks: SDK HTTP and navigation breadcrumbs are dropped, network breadcrumbs keep only their four attributes, URLs lose their query string and fragment, unknown tags and count attributes are dropped, and the privacy and breadcrumb options stay off. - Errors sent through a real SDK hub, with the SDK's own platform-error processor and Flutter error integration, into an in-memory transport: for a parse failure, a bad argument, a server response and a platform failure, the serialized event keeps the type and stack but none of the error's text; a real framework build error leaves out the widget text. - A release-mode check that `debugPrint` keeps printing with reporting on. - A build with no destination, one the SDK cannot parse, one without a public key or one without an HTTP(S) host starts the do-nothing reporter and the SDK stays disabled. - Reporting calls whose SDK calls throw, either synchronously or asynchronously, never reach the caller. - Hang detection is on and its thresholds equal the SDK's defaults. - An installation keeps one install ID across launches, a new installation gets a new one, and the filter keeps the `install.id` tag. - Signing in, switching accounts and signing out change the member that later reports are attributed to. I checked that each guard is real by removing it: the print-breadcrumb setting, the destination check, the error-text replacement, the `mechanism.data` and `flutter_error_details` removal, the network-breadcrumb setting, the dropped-failure catch and the tag filter each made a test fail. End to end on an iPhone 17 Pro simulator, with a local server standing in as the destination and a throwaway probe (not committed) that made an HTTPS request with a secret in its query, then raised an uncaught Dart error and a framework error with secrets in their text, then crashed natively: - All four reports arrived (two Dart, one framework, one native crash on the next launch), and none of the secrets appeared in any envelope. - Dart reports carried only the foreground/background breadcrumb; the native crash carried none. - As a control, a build with Cocoa's network breadcrumbs switched back on put the request's secret query and fragment into the native crash report, so that setting is what keeps them out. - `debugPrint` lines still appeared in the device log. Hangs, on a fresh iPhone 17 Pro simulator with no debugger attached and the same local server: a throwaway probe busy-looped the main isolate for 5 s after the first frame. The SDK sent an `App Hang Fully Blocked` event ("App hanging between 5.7 and 6.5 seconds", mechanism `AppHang`) carrying the main thread's stack: Flutter engine frames around 12 frames of Dart code. This was a debug build, where Dart is compiled just in time, so those frames have no image to symbolicate against; in release builds they fall in the app's compiled Dart framework and need its debug symbols at the destination. Install ID, rechecked after moving it to its own file, on a fresh simulator with the same local server, launched twice with a probe that raised a Dart error and then crashed natively: both Dart errors and the native crash carried the same `install.id`, while the signed-out user was the SDK's own identifier. The ID file was in the backup-excluded `Library/Application Support/Diagnostics` folder, not in the app's preferences. The merged Android debug manifest has neither of the SDK's startup providers and has the network-change setting off. The NDK preload provider is still merged in, but it does nothing unless its own manifest flag is set, and it isn't. Full mobile suite passes. Dart errors are captured in the main Flutter engine only; the iOS sheets that start their own engine are out of scope for this PR (native crashes while they are open are still caught), as the spec now says. iOS simulator and Android debug builds with a destination set both build; on iOS the SDK resolves through Swift Package Manager. --------- Signed-off-by: Tom Brow <tomb@squareup.com> Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
16 KiB
Mobile diagnostic reporting
Status: step one agreed, not yet implemented.
Terminology is defined in CONTEXT.md. The decisions behind this spec are in ADR 0007 and ADR 0008.
Problem statement
When the mobile app crashes or misbehaves, nobody who can fix it finds out. Uncaught errors are dropped, failures are caught and shown as a generic message or nothing, and there is no record of how often the app's connections to its backends fail. A member who reports "it was slow" or "it crashed" cannot be helped without their phone in hand, and a backend problem that affects many members at once is invisible from the client side.
Solution
A build that is given a reporting destination does diagnostic reporting: it sends crashes, unexpected errors and networking measurements to that destination, tagged with the member who hit them. A build without a reporting destination sends nothing and behaves exactly as today. Reports never contain what people write or the names of the places they write it.
User stories
- As a developer, I want every crash of the app reported with a readable stack trace, so that I can fix crashes I never saw myself.
- As a developer, I want every uncaught Dart and Flutter error reported, so that errors the app currently drops become visible.
- As a developer, I want a report when the relay sends something the app cannot decode, so that protocol mismatches are found quickly.
- As a developer, I want a report when the relay rejects something the app sent as invalid, so that client bugs in what we send are found.
- As a developer, I want a report when a Builderlab or push gateway response cannot be understood, so that contract drift is caught.
- As a developer, I want a report when data saved on the device cannot be read back, so that storage corruption and migration bugs surface.
- As a developer, I want each report to carry the trail of recent networking events, so that I can see what the connection was doing before the fault.
- As a developer, I want each report to carry the member's public key, so that I can follow up with the person who hit it.
- As a developer, I want timeouts, disconnects, being offline, rate limits and refused sign-ins counted and not reported as errors, so that the error list contains only bugs someone can fix.
- As a developer, I want every network request and relay connection event counted with its backend, endpoint, outcome and kind of failure, so that I can see which backend and which operation is failing.
- As a developer, I want request durations measured per backend and endpoint, so that slowness shows up as well as failure.
- As a developer, I want those counts to carry the member, so that I can answer "who hit this failure, and when" without a separate log.
- As a person on call, I want to be alerted when the failure rate for a backend or endpoint spikes, so that an outage seen only by clients is noticed.
- As a distributor of an internal build, I want to turn reporting on by supplying one build-time setting, so that my organization's reports go to my own destination.
- As a distributor, I want stack traces from my release builds to be readable, so that reports are usable.
- As someone building the app from source, I want a build with no reporting destination to send nothing and start no reporting code, so that the open-source app reports to no one by default.
- As a member, I want reports to never include message content, channel or community names, private keys or other secrets, so that diagnosing faults does not expose what I write.
- As a member, I want reporting to never slow the app or block what I am doing, so that diagnosis does not cost me anything.
- As a developer, I want signing out or switching accounts to change who later reports are attributed to, so that reports are never tagged with the wrong member.
- As a reviewer, I want all reporting to go through one small interface, so that I can check what leaves the device in one place.
- As a developer, I want freezes of the main thread reported with their stack (on iOS when the app is blocked for long enough, and on both platforms when the system ends the app for not responding), so that I can fix freezes that never show up as crashes.
Implementation decisions
- One reporting module. All app code reports through a single interface with three operations: report an error, count a networking event (with an optional duration), and leave a breadcrumb. It has two implementations: one backed by the Sentry Flutter SDK and one that does nothing. Nothing outside this module imports the SDK.
- The reporting destination is a build-time setting, named with the implementation to match the existing
BUZZ_build settings. When it is absent, the app uses the do-nothing implementation and never initializes the SDK. There is no check on the kind of build, no in-app switch and no notice (ADR 0007). - Crashes and uncaught errors are captured by the SDK's own handlers for native crashes, Flutter framework errors and uncaught asynchronous Dart errors, installed at startup around the app.
- Explicit error reports are added at the places where the app meets something that should never happen: a relay frame or query response that cannot be decoded, a relay rejection whose reason says the app sent something invalid (except a refusal the app already handles as an expected outcome, such as an archived channel or a channel name that is taken, which is counted), an account or push gateway response that cannot be understood, saved data that cannot be read back, and an event subscriber that throws while handling an event.
- Routine failures are counted, never reported. Timeouts, disconnects, unreachable or insecure hosts, rate limits, refused or expired sign-ins and server errors increment a count. That includes the relay's own errors, such as a query that timed out or too many subscriptions. Of the reasons a relay gives for a rejection, only the one that marks the request as invalid is reported, with the exception above; every other reason is counted.
- Networking measurements. Every request through the app's shared HTTP client and every relay connection event (connected, disconnected, reconnect attempt, request timed out, subscription closed by the relay) is counted with four attributes: backend, endpoint, outcome and kind of failure. The backend is the host name of the server the app was talking to. Endpoints are names from a fixed list, never raw paths. Durations are recorded for requests and for time to connect. HTTP is measured where the app's shared HTTP client already classifies transport failures; relay connections are measured by hand in the relay session, since the SDK documents no WebSocket instrumentation.
- Counts are handed to the SDK as they happen, including while the network is down. The app does no buffering of its own, and the SDK's default limit on unsent data is kept. Accepted consequence: in a long outage the oldest unsent reports can be dropped.
- No log lines in step one. The counts carry the member and the time. The first implementation task confirms that the destination can filter counts by member; if it cannot, the fallback is one log line per outage, sent after it ends.
- Breadcrumbs come from a fixed list: networking events, written by the app, and the app moving to the foreground or background, written by the SDK. The SDK's other automatic breadcrumbs, which could carry content or addresses, are turned off or filtered.
- Who a report is about. The member's public key is set as the report's user when a session starts and cleared when it ends. When the session is a Builderlab account, the Builderlab's origin and the account's subject identifier are added, never its email address. Every report also carries the app's own random per-install identifier, created on first launch and kept in a file that device backups and transfers skip, so a phone restored from another gets its own, as a separate field, signed in or not, so reports from one device can be matched to the members who used it, and a member's reports to the devices they used. With no member set, for example before sign-in, the SDK fills the report's user with its own random per-install identifier, on Dart and native reports alike. On iOS, native crash and hang reports also carry the SDK's device app hash: a hash of the identifier iOS gives the app's vendor, the hardware model and the bundle identifier, stable across launches and across a reinstall while another app from the same vendor stays installed. The Dart filter drops it, so Dart reports don't carry it. The SDK also sends session records, so the destination can show a crash-free rate. A session begins each time the app starts or returns after 30 seconds or more in the background. The SDK sends a record when it begins, an update each time an error is counted, and a last record when it ends. Together they carry when the session started, how many errors it had, how it ended (normally, crashed or abnormally), the time from start to end (not time in active use), the release, the environment and the SDK's identifier.
- One filter before anything leaves. Errors, breadcrumbs and counts from Dart all pass through a single filter that removes URL query strings and fragments, drops any attribute not on the allowed list, replaces every error's own text with fixed wording, drops what the SDK adds about the failing widget or platform call, and keeps only the app, operating system, device and runtime details among the report's contexts, so the SDK's accessibility settings, locale and the device's own name stay on the device. An error keeps its type and stack trace. The SDK's options for sending personal data, screenshots, view hierarchies and session recordings stay off.
- Main-thread hangs are captured by the SDK's own hang detection, at the SDK's default thresholds. The app's Dart code runs on the platform's main thread, so Dart work that blocks it shows up here. On iOS, the SDK reports the main thread being blocked, fully or mostly, for 2 seconds or more while the app is active, with the main thread's stack taken during the hang, including freezes the app recovers from. A hang that is still going when the app is killed, for example by the system watchdog, is sent on the next launch as a fatal hang. The SDK's separate watchdog-termination tracking also reports, on the next launch, a run that ended while the app was in the foreground with nothing else to explain it; it never reports on simulators or for kills in the background. App hang detection is off while a debugger is attached (sentry-cocoa 9.35.0). On Android the SDK reports only freezes the system itself declared "app not responding". On Android 11 and later it reports only one that ended the process, read from the system's exit records on the next launch: the most recent unreported one, and only when the system kept a usable thread dump. Before Android 11 it reports when the main thread has been blocked for 5 seconds and the system has marked the app not responding, never with a debugger attached (sentry-java 8.64.0). So with these defaults, a freeze the app recovers from is reported on iOS, and on Android only before Android 11 and only once the system has marked the app not responding. Dart frames in a hang's stack are readable only with the Dart code's debug symbols at the destination, the same as for crashes.
- Native reports skip that filter. Native crashes and app hangs are captured and sent by the native SDKs, which never call the Dart filter. They carry stack traces and, for a native exception, its reason text. No app code puts content in a native exception today, and the SDK's native network breadcrumbs, which would carry request addresses, are off.
- Readable stack traces need the build's debug symbols at the destination. Uploading them belongs to the release process of whoever distributes the build; this repository documents the requirement and adds nothing organization-specific.
- Both platforms. Step one covers the main app on iOS and Android. Background work that runs the app's Dart code in its own engine, as decided for Android push handling in ADR 0006, starts the reporting module the same way once it exists. Dart errors are captured in the main app's Flutter engine only: the iOS sheets that start their own engine (channel settings and the profile photo editor) are not covered, though native crashes while they are open still are.
- Reporting never blocks the app. A call into the reporting module returns at once and nothing waits on the destination. A failure inside reporting is dropped and never reaches the code that made the call.
Testing decisions
- A good test here asserts what would be reported for something the user or the network does, never how the reporting module is called internally.
- Tests replace the reporting interface with a fake that records what it was given. This is the only new seam.
- Journey tests extend the existing relay and account journeys with steps such as: a malformed relay frame produces exactly one error report; a timeout or disconnect is counted with the right backend, endpoint and failure kind and produces no report; signing out changes who later reports are about.
- One table-driven test covers the filter: each row is an input (a URL with a query string, an attribute not on the list, a free-text relay message) and what must come out.
- One test checks that a build with no reporting destination never starts the SDK.
- One test checks that a reporting call that fails does not fail or delay the operation that made it.
- The SDK itself is not tested. Prior art: the existing widget tests that override boundary providers for the relay, HTTP and storage.
Out of scope
- The iOS notification service extension and the iOS share extension.
- Log lines, traces and spans, and joining mobile reports to relay traces.
- Holding counts back in the app while the network is down. The SDK's own store of unsent data is the only buffer.
- Requests that bypass the shared HTTP client, such as those made by native media players and image loaders.
- Alert rules, dashboards and the destination's own configuration, which belong to whoever owns the destination.
- Diagnostic reporting in a public build. Nothing prevents it, but what a report carries was chosen for internal builds. Turning it on there first needs the member's public key and the server host names removed, the rest of the list reviewed, and a way to tell people (ADR 0007). Because identity and every attribute pass through one module, that is a small code change.
- Usage or behavior data of any kind, beyond the SDK's session records described above.
- Fixing the bugs the reports will reveal, including two found while planning: one subscriber that throws can lose the rest of a batch of events, and a catch-all in account requests presents every error as an outage.
Further notes
- Depends on the iOS move to Swift Package Manager, since the current Sentry SDK installs on iOS only that way (ADR 0008).
- Not yet verified: whether the destination can filter counts by member, and how Android's store of unsent data behaves.
- A relay's host name can identify a community. It is reported anyway so that two relays can be told apart; an internal build talks only to its own organization's relay, so the name tells the destination's owner nothing new.