From 3cde9b3e6cb7632e639046f6fe1051dffdcda254 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 20:29:16 +0500 Subject: [PATCH 01/14] Add an end-to-end symbolication run against a Bugsee backend, and its first results scripts/device/e2e_symbolication.dart builds an obfuscated release app, uploads the Dart symbols (pinned symbols.py, HTTP statuses logged) and the native symbols, crashes it on a physical iPhone or Android phone, and reads the backend back when given a server token. Run on an iPhone XS and the Android phone against apidev (the given tokens exist there only): uploads accepted; the backend's frames were not read (no server token), recorded as unverified in doc/verification.md, PLAN.md and CHANGELOG.md. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxNbNUdWru1zs68bYV8 Change-Id: I94bac486795bab26744bcb0449dd660eb3128688 --- CHANGELOG.md | 5 + PLAN.md | 9 +- doc/verification.md | 57 ++- example/lib/e2e_main.dart | 141 ++++++++ scripts/device/core/e2e.dart | 145 ++++++++ scripts/device/e2e_symbolication.dart | 493 ++++++++++++++++++++++++++ scripts/device/symbols_logged.py | 48 +++ test/device_harness_test.dart | 136 +++++++ 8 files changed, 1030 insertions(+), 4 deletions(-) create mode 100644 example/lib/e2e_main.dart create mode 100644 scripts/device/core/e2e.dart create mode 100644 scripts/device/e2e_symbolication.dart create mode 100644 scripts/device/symbols_logged.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ed76b9e..8ac7590 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,11 @@ A rewrite for the Bugsee 7.x native SDKs (Android 7.6.0, iOS 7.1.0). **Not published yet; a prerelease.** Existing 9.x apps should stay on 9.x: there is no compatibility layer (the decision is open), see `doc/migration-from-9x.md`. +### Known gaps + +* Symbolication was exercised end to end up to the upload (Dart symbols and iOS dSYMs accepted by apidev, obfuscated release builds crashed on an iPhone XS and an + Android phone) but the backend's symbolicated frames were not read back, and the production endpoint was not used (`doc/verification.md` scenario 11). + ### Features * **Launch and configuration.** `Bugsee.launch(token, {options})` returning `LaunchResult` (`launched`, `alreadyRunning`, `deferred`), diff --git a/PLAN.md b/PLAN.md index 976ae30..8e61baf 100644 --- a/PLAN.md +++ b/PLAN.md @@ -27,7 +27,7 @@ Contents: [Status](#status) | [Decisions taken](#decisions-taken) | [Open decisi | Device verification harness (emulator and simulator) | Done, not in CI | [verification](doc/verification.md) | | Documentation pass, migration guide | Done (this pass) | [doc/README.md](doc/README.md) | | **Not exposed on purpose** | APM transactions and spans, the appearance system, `relaunch`, secure rectangles and activities (replaced by `BugseeSecureView`), `deleteCollectedDataOnDevice`, native views | [api-surface](doc/api-surface.md) | -| **Not verified** | any physical device; iOS recovered crash reports and exception bundles (simulator limits); a valid token and the production backend | [verification](doc/verification.md) | +| **Not verified** | the production backend; what a backend (apidev, 2026-11-23) made of the uploaded symbols and crashes: the symbolicated frames were not read (no server token), see scenario 11 | [verification](doc/verification.md) | ## Decisions taken @@ -87,7 +87,12 @@ Other gaps, none with an issue: reports for native signals, Objective-C exceptions and a Swift trap; a `raise(7)`, which is SIGEMT on Darwin and not SIGBUS (10), left no report; SIGBUS itself is not yet measured on a device). The workbook's iOS recovery claims (off-main, capped, a late completion re-persists) were not measured. * The Gradle plugin 4.0.6 failure arm was not run; `optimizeExtensionsLoading=false` and the feedback safety-net path were not run. -* A real token and the production backend: the harness uses a loopback stand-in; server-side symbolication was run offline with the +* **End-to-end symbolication (2026-11-23, `doc/verification.md` scenario 11): symbols uploaded, backend result NOT read.** The two app tokens available exist on + `apidev.bugsee.com` only (production answers `ApplicationNotFoundError`), so the runs used apidev: Dart symbols (`symbols.py`) and iOS dSYMs (`bugsee-cli`) were accepted, + an obfuscated release build crashed on an iPhone XS and the Android phone, reports were built and (by the device log) handed to the SDK; but reading the issues back + needs an organisation server token or a dashboard login that the run did not have, so nothing says the backend symbolicated Dart 3.14 or iOS stacks (the header-stripping + risk below is still open), and Android native symbols through the Gradle plugin are unconfirmed. Next step: look at apidev versions `9.1123.2012` (iOS) and `9.1123.2016` (Android). +* A production-backend run: not done (no production tokens); the harness otherwise uses a loopback stand-in; server-side symbolication was run offline with the backend's `dart_symbolize` (2026-11-18, `doc/exceptions.md`): it decodes the Android arm64 stack of a Dart 3.14 build only because the worker strips the stack's header (with the header it crashes, as Flutter 3.50's `flutter symbolize` does: `_kDartSnapshotText`, no `_kDartIsolateSnapshotInstructions`); its vendored `native_stack_traces` copy is from 2023 and needs a bump to 0.7.x to stop depending on that (owner: the backend; not changed here). A real iOS stack diff --git a/doc/verification.md b/doc/verification.md index dfe9021..d0578ff 100644 --- a/doc/verification.md +++ b/doc/verification.md @@ -135,6 +135,7 @@ harness was run again on a new simulator (iPhone 17, iOS 26.5, Xcode 27.1) with | 8 | Hot restart | PASS | PASS | | 9 | Report screenshot by render mode | PASS at Android 7.5.0: content and the secure box redacted in BOTH modes, screenshot and video (at 7.4.2: KNOWN-GAP, all black in the default SurfaceView mode) | not applicable (the iOS screenshot has content, scenario 7) | | 10 | Crash and error matrix: native signals, Java, Dart routes | PASS on a physical phone at Android 7.5.1: see section 10 | not run (no iOS device harness yet) | +| 11 | End-to-end symbolication, real backend | UPLOADED and crashed on the phone; backend frames NOT READ (no server token); apidev only | UPLOADED and crashed on an iPhone XS; backend frames NOT READ; apidev only | ## Scenarios @@ -435,6 +436,56 @@ file (`file`: "Mach-O 64-bit dSYM companion file arm64") with `LC_UUID` and the came out as the right functions with file:line. Not verified: a real iOS stack (its header, whether its frames carry `virt`, the form of its `build_id`, which should be the `LC_UUID` as 32 hex digits, which the worker looks up by that and by the upper-case dashed UUID), and the iOS upload path. +### 11. End-to-end symbolication against a Bugsee backend (2026-11-23) + +`scripts/device/e2e_symbolication.dart` (app: `example/lib/e2e_main.dart`; parsers and verdicts: `scripts/device/core/e2e.dart`, tested in +`test/device_harness_test.dart`; `scripts/device/symbols_logged.py` runs the pinned `symbols.py` unchanged and prints each HTTP exchange). No mock. + +```bash +BUGSEE_IOS_TOKEN=... [BUGSEE_ENDPOINT=https://apidev.bugsee.com] \ + dart scripts/device/e2e_symbolication.dart ios --udid # [--run-id --reuse-build] +BUGSEE_ANDROID_TOKEN=... dart scripts/device/e2e_symbolication.dart android --serial +# reading the backend back (without these the run ends UNVERIFIED, exit 3, never a pass): +BUGSEE_SERVER_TOKEN=... BUGSEE_IOS_APP_ID=... (or BUGSEE_ANDROID_APP_ID=...) +``` + +Per run: a unique build string `9.MMDD.HHMM` (build name and the symbols' `-v`); a release build with `--obfuscate --split-debug-info` of the e2e app; +guards that make a run INVALID: the `.symbols` are the platform's format (ELF / Mach-O), the app's own function name is not in the shipped binary (iOS: `strings` +on `App.framework/App`), the pinned `symbols.py` hash, the upload (see below), the device lock, four launches all `launched` in release mode, two crashes after which the +process really ended. The app (`e2e_main.dart`) keeps a phase counter in its temp directory: launch 1 reports a handled error, an uncaught error and `logUnhandledException` +from three sites named `e2eHandledSite`, `e2eUncaughtThrower`, `e2eUnhandledSite`; launch 2 dies of `ffi-segv`; launch 3 (uploads the recovered report) dies of `objc-main` +(iOS) / `java-main` (Android); launch 4 uploads the last recovered report. The token is a `--dart-define` of a local build (an environment variable given to +`devicectl process launch` did not reach the app; Android has none), never printed or saved: every line passes `redact`. + +**Where the tokens work: not the default endpoint.** Both app tokens given for this run are unknown to `api.bugsee.com` (`POST /v2/apps//symbols` answered +`{"ok":false,"error":{"type":"ApplicationNotFoundError","code":11001}}`, with HTTP 200) and known to `https://apidev.bugsee.com` (`ok:true`, a presigned URL). So everything +below went to **apidev**, through `BUGSEE_ENDPOINT` (SDK option `endpoint`, `symbols.py -e`, `bugsee-cli`, Gradle `plugin.endpoint`). A run against production needs production +tokens. The two probe requests of that discovery left one empty `uploading` symbol record per app on apidev (uuid `e2e-probe-0000`, version `probe`). + +| | iPhone XS, iOS 18.7.9 (UDID `...2641002E`) | HONOR WOD-LX1 (`AMRJCP4718402860`) | +| --- | --- | --- | +| build | `9.1123.2012`, Flutter 3.50.0, release, `--obfuscate`; guard: `e2eHandledSite` absent from `App` | `9.1123.2016`, Flutter 3.50.0, JDK 21, release APK, R8, `--obfuscate` | +| Dart symbols (`symbols.py`, `-t -v -d -e https://apidev.bugsee.com/v2/`) | `app.ios-arm64.symbols` (Mach-O, 1.9 MB): POST `.../symbols` 200, PUT of the zip to the presigned S3 URL 200 (`symbols.py` exit 0) | three files (`android-arm64`, `-arm`, `-x64`, ELF): POST 200, PUT 200 (4.2 MB zip), exit 0 | +| native symbols | `bugsee-cli debug-files upload --type dsym` (0.8.0, `BUGSEE_APP_TOKEN` in the environment): exit 0; `App`, `Runner`, `Flutter` dSYMs uploaded, `Bugsee` already on the server | Bugsee Gradle plugin 4.1.1 (`ndk { enabled }`, token and `plugin.endpoint` in the Gradle-root `bugsee.properties`, removed after the build): **not confirmed**, the plugin prints nothing at the default log level | +| device run | 4 launches, all `launched`; launch 2 died of signal 11, launch 3 ended after the Objective-C exception (devicectl exit 1); the app's events and the SDK's report-handler lines show reports built in launches 1 to 3 | the same sequence; both crash launches ended (the process was gone within 90 s) | +| the backend's answer | **not read** | **not read** | + +**What was NOT verified, and why: the backend's symbolicated frames, on both platforms.** Reading an issue back needs the public API's organisation +**server token** (`x-auth-servertoken`, `appserver` `public_api/middleware/auth.js`; routes `GET /v2/partner/applications/:app_id/issues[/:id/recordings/:rid/crash_report]`) +or the dashboard / MCP login; an app token only uploads (the symbols endpoint accepts it) and cannot list issues. None was available to the run, so the script ended +`UNVERIFIED` (exit 3) and nothing here says the backend symbolicated or failed to. The readback half of the script is written from the appserver source and has +**never been run** against a backend; its first run may need the response shapes adjusted. To finish the check: open the issues of versions `9.1123.2012` (iOS) and `9.1123.2016` (Android) on apidev and look at the frames +(or set `BUGSEE_SERVER_TOKEN`, the apidev organisation's, and the application ids and run again: a new run id, because the script does not read an old build). Expected `e2eHandledSite`, +`e2eUnhandledSite`, `e2eUncaughtThrower` (file `e2e_main.dart`), and for the native crashes `AppDelegate` (iOS, `objc-main`) and `MainActivity` (Android, `java-main`). + +Findings of the build of this check, each a fact about the toolchain and not about the wrapper: + +* **`symbols.py` exits 0 when the registering POST is refused with a non-2xx status** (`_send_request` returns `None` and nothing is printed); it exits 1 with `ok:false` in a 200 + body (`ApplicationNotFoundError` above). The exit code alone is not proof of an upload: the harness requires the POST and the PUT, both 2xx, from the logged exchange. +* On iOS release `print` does not reach `devicectl --console`; `dart:io` `stdout` does. The e2e app writes both. +* Stopping a `devicectl --console` child terminates the app it launched, late: the next launch of the run was killed with SIGTERM 0.2 s after it started. The run waits 10 s. +* The pinned `symbols.py` needs the `requests` package (not installed by default) and prints a `SyntaxWarning` on a current Python (`'^\-+'`). + ## Findings ### Defects @@ -480,8 +531,10 @@ For follow-up (SDK or environment, not fixed here): * A handler that overruns the SDK's deadline, and a hot restart while a delivery is in flight. * The Gradle plugin 4.0.6 broken arm (only the fixed arm was run; the detection is unit-tested). * x86_64 and armeabi-v7a ABIs, a second display, rotation, split screen, a density change *during* a report. -* Server-side processing (real tokens, the symbols upload, the worker as a whole): the mock API stands in for the backend. Its `dart_symbolize` was run offline on - the Android arm64 Dart 3.14 artifacts only (see scenario 4); an iOS stack was not. +* Server-side processing: the mock API stands in for the backend in scenarios 1 to 10. Scenario 11 (2026-11-23) uploaded the Dart symbols (both platforms) and the iOS + dSYMs to apidev (accepted, 2xx) and ran the crashes on the devices, but the backend's symbolicated frames were NOT read (no server token): whether apidev symbolicated + anything is unknown. Its `dart_symbolize` was run offline on the Android arm64 Dart 3.14 artifacts only (see scenario 4); a real iOS stack was not decoded. Android native + symbols through the Gradle plugin: upload not confirmed. The default (production) endpoint was not used: the given tokens exist on apidev only. * Dart `Isolate` errors and `reportAsCrash: true` in a release build. ## Extending it diff --git a/example/lib/e2e_main.dart b/example/lib/e2e_main.dart new file mode 100644 index 0000000..86184c2 --- /dev/null +++ b/example/lib/e2e_main.dart @@ -0,0 +1,141 @@ +// The app `scripts/device/e2e_symbolication.dart` builds and drives against the REAL Bugsee backend +// (doc/verification.md, "End-to-end symbolication"). Not part of the plugin, not the example UI. +// +// It has no server and no commands. It keeps a phase counter in a file of the app's temp directory; +// every launch does the next phase and prints `E2E|` lines (the harness reads them from the console): +// +// phase 0 handled error, an uncaught Dart error, `logUnhandledException` (a crash report), then waits +// phase 1 waits for the previous reports to upload, then dies of a native signal (FFI write to address 0) +// phase 2 waits, then dies of the platform's own language (`java-main` / `objc-main`) +// phase 3 waits for the recovered crash report to upload, nothing else +// +// The token comes from `--dart-define=BUGSEE_E2E_TOKEN` (an environment variable given to `devicectl process +// launch` did not reach the app, measured; Android has no per-launch environment). The build is local, installed +// for the run and uninstalled after it, and never leaves the harness' work directory. The token is never printed. The run id +// (`--dart-define=E2E_RUN`) is the build's unique string: it is in every message and an attribute. +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:bugsee_flutter/bugsee_flutter.dart'; +import 'package:flutter/foundation.dart'; +import 'package:material_ui/material_ui.dart'; + +import 'crash_lab.dart' as crash_lab; + +const _run = String.fromEnvironment('E2E_RUN'); +const _defineToken = String.fromEnvironment('BUGSEE_E2E_TOKEN'); +const _endpoint = String.fromEnvironment('BUGSEE_ENDPOINT'); +const _wait =int.fromEnvironment('E2E_WAIT_SECONDS', defaultValue: 40); + +void _emit(String kind, [Map data = const {}]) { + final line = 'E2E|${jsonEncode({'kind': kind, 'run': _run, ...data})}'; + // Android: logcat shows `print`. iOS release: `print` is not on the devicectl console, stdout is. + // ignore: avoid_print + print(line); + if (Platform.isIOS) stdout.writeln(line); +} + +// The Dart sites whose NAMES must come back from the backend. Never inlined, so each is a frame of +// its own; obfuscation renames all of them, so a readable name in the backend is the symbolication. +@pragma('vm:never-inline') +Future e2eHandledSite() async { + try { + throw FormatException('e2e-$_run handled'); + } catch (e, s) { + await Bugsee.logException(e, s); + } +} + +@pragma('vm:never-inline') +Future e2eUnhandledSite() async { + await Bugsee.logUnhandledException(StateError('e2e-$_run unhandled')); +} + +@pragma('vm:never-inline') +void e2eUncaughtSite() { + unawaited( + Future.delayed(const Duration(milliseconds: 20)).then( + (_) => e2eUncaughtThrower(), + ), + ); +} + +@pragma('vm:never-inline') +void e2eUncaughtThrower() => throw StateError('e2e-$_run uncaught'); + +@pragma('vm:never-inline') +Future e2eNativeCrashSite(String kind) => crash_lab.crash(kind); + +int _readPhase(File f) { + try { + return int.parse(f.readAsStringSync().trim()); + } on Object { + return 0; + } +} + +Future _phases() async { + final token = _defineToken; + if (token.isEmpty || _run.isEmpty) { + _emit('invalid', {'why': 'no token or no E2E_RUN'}); + return; + } + final state = File('${Directory.systemTemp.path}/e2e_phase'); + final phase = _readPhase(state); + _emit('start', { + 'phase': phase, + 'mode': kReleaseMode ? 'release' : (kProfileMode ? 'profile' : 'debug'), + 'os': Platform.operatingSystem, + }); + WidgetsFlutterBinding.ensureInitialized(); + Bugsee.installErrorHandlers(); // reportAsCrash false: the default + // Empty = the SDK's default (production) endpoint. + final launch = await Bugsee.launch( + token, + options: BugseeOptions(endpoint: _endpoint.isEmpty ? null : _endpoint), + ); + _emit('launch', {'result': launch.name}); + if (launch.name != 'launched') { + _emit('invalid', {'why': 'launch answered ${launch.name}'}); + return; + } + await Bugsee.setAttribute('e2e_run', _run); + Future pause(String why) async { + _emit('waiting', {'why': why, 'seconds': _wait}); + await Future.delayed(const Duration(seconds: _wait)); + } + + switch (phase) { + case 0: + await e2eHandledSite(); + e2eUncaughtSite(); + await Future.delayed(const Duration(seconds: 1)); + await e2eUnhandledSite(); + _emit('reported', {'kinds': 'handled,uncaught,unhandled'}); + state.writeAsStringSync('1'); + await pause('upload of the error reports'); + _emit('phase-done', {'phase': 0}); + case 1: + await pause('upload of the phase 0 reports'); + state.writeAsStringSync('2'); + _emit('crashing', {'crash': 'ffi-segv'}); + await e2eNativeCrashSite('ffi-segv'); + case 2: + await pause('upload of the recovered ffi-segv report'); + state.writeAsStringSync('3'); + final kind = Platform.isIOS ? 'objc-main' : 'java-main'; + _emit('crashing', {'crash': kind}); + await e2eNativeCrashSite(kind); + default: + await pause('upload of the recovered platform crash report'); + _emit('phase-done', {'phase': phase}); + } +} + +void main() { + runApp( + const MaterialApp(home: Scaffold(body: Center(child: Text('e2e')))), + ); + unawaited(_phases()); +} diff --git a/scripts/device/core/e2e.dart b/scripts/device/core/e2e.dart new file mode 100644 index 0000000..5d5db54 --- /dev/null +++ b/scripts/device/core/e2e.dart @@ -0,0 +1,145 @@ +// Pure parsers and verdicts of the end-to-end symbolication run (scripts/device/e2e_symbolication.dart). +// Each one decides something the run must not take on trust, and `test/device_harness_test.dart` shows +// each failing on the input it exists to refuse. +import 'dart:convert'; + +/// Replaces every secret in [text] with a marker. Everything the run prints or saves goes through this. +String redact(String text, Iterable secrets) { + var out = text; + for (final s in secrets) { + if (s.length >= 8) out = out.replaceAll(s, ''); + } + return out; +} + +/// The `E2E|{json}` lines of a console that belong to [runId], in order. A line of another run (an +/// older build still installed, a replay) is dropped, never counted. +List> e2eEvents(String console, String runId) { + final out = >[]; + for (final line in const LineSplitter().convert(console)) { + final i = line.indexOf('E2E|'); + if (i < 0) continue; + try { + final v = jsonDecode(line.substring(i + 4)); + if (v is Map && v['run'] == runId) out.add(v.cast()); + } on FormatException { + // a truncated line + } + } + return out; +} + +/// What the pinned `symbols.py` did, read from `symbols_logged.py`'s output. `symbols.py` itself exits 0 when +/// the first request fails (it ignores a non-2xx answer), so the exit code proves nothing: the verdict needs the +/// POST (register) and the PUT (the zip to the presigned URL), both 2xx. Returns the problems; empty = uploaded. +List symbolsUploadProblems(String output, int exitCode) { + final problems = []; + final http = RegExp( + r'^HTTP (\w+) (\S+) -> (\d{3})', + multiLine: true, + ).allMatches(output).toList(); + String? status(String method, {String? pathHas}) { + for (final m in http) { + if (m[1] == method && (pathHas == null || m[2]!.contains(pathHas))) { + return m[3]; + } + } + return null; + } + + final post = status('POST', pathHas: '/symbols'); + final put = status('PUT'); + if (exitCode != 0) problems.add('symbols.py exited $exitCode'); + if (post == null) { + problems.add('no POST .../symbols was made (nothing was registered)'); + } else if (!post.startsWith('2')) { + problems.add('POST .../symbols answered $post'); + } + if (put == null) { + problems.add('no PUT of the zip was made (no presigned URL, or it was not used)'); + } else if (!put.startsWith('2')) { + problems.add('PUT of the zip answered $put'); + } + if (output.contains('Failed to upload')) { + problems.add('symbols.py said it failed to upload'); + } + return problems; +} + +/// The phases a device run must have gone through, from the app's events. Empty = the sequence is complete. +List phaseProblems( + List> events, { + required String os, + required bool release, +}) { + final problems = []; + final starts = events.where((e) => e['kind'] == 'start').toList(); + final phases = starts.map((e) => e['phase']).toList(); + if (phases.join(',') != '0,1,2,3') { + problems.add('the app started phases [${phases.join(',')}], expected 0,1,2,3'); + } + for (final s in starts) { + if (s['os'] != os) problems.add('a start event says os ${s['os']}, expected $os'); + if (release && s['mode'] != 'release') { + problems.add('a start event says mode ${s['mode']}, expected release'); + } + } + final launches = events.where((e) => e['kind'] == 'launch').toList(); + if (launches.length != 4 || launches.any((e) => e['result'] != 'launched')) { + problems.add('launch results: ${launches.map((e) => e['result']).toList()}, expected 4 x launched'); + } + if (events.any((e) => e['kind'] == 'invalid')) { + problems.add('the app reported invalid: ${events.where((e) => e['kind'] == 'invalid').toList()}'); + } + final crashes = events.where((e) => e['kind'] == 'crashing').length; + if (crashes != 2) problems.add('the app announced $crashes crashes, expected 2'); + if (!events.any((e) => e['kind'] == 'reported')) { + problems.add('phase 0 never reported its Dart errors'); + } + return problems; +} + +/// The unique build string of a run: `9.MMDD.HHMM` (three integers, valid as an iOS short version and an +/// Android versionName), so two runs in different minutes never share a build, and a backend row is told apart. +String runIdFor(DateTime now) { + String two(int n) => n.toString().padLeft(2, '0'); + return '9.${two(now.month)}${two(now.day)}.${two(now.hour)}${two(now.minute)}'; +} + +/// A `.symbols` file's format by magic bytes: `elf` (Android), `macho` (iOS), or null. +String? symbolsFormat(List head) { + if (head.length < 4) return null; + if (head[0] == 0x7f && head[1] == 0x45 && head[2] == 0x4c && head[3] == 0x46) { + return 'elf'; + } + final m = (head[0] << 24) | (head[1] << 16) | (head[2] << 8) | head[3]; + // MH_MAGIC_64 in either byte order, and the fat magic + if (m == 0xfeedfacf || m == 0xcffaedfe || m == 0xcafebabe) return 'macho'; + return null; +} + +/// What the backend's rendering of the run's reports must hold for the run to count as symbolicated. +/// [reports] are the texts of the crash reports found for the run's build. Returns the problems: +/// each expected readable name must appear, and the readable names must not be the only thing there +/// (an obfuscated build whose frames are still `_kDartSnapshotText+0x...` has failed, whatever else matches). +List readbackProblems( + List reports, { + required List expectedDartNames, + required List expectedNativeNames, +}) { + final problems = []; + if (reports.isEmpty) { + return ['the backend returned no report for this build: nothing was verified']; + } + final all = reports.join('\n'); + for (final n in [...expectedDartNames, ...expectedNativeNames]) { + if (!all.contains(n)) problems.add('"$n" is in none of the ${reports.length} report(s)'); + } + return problems; +} + +/// Frames that are still raw addresses in a rendered report (a symbolication that did not happen). +List rawFrameLines(String report) => [ + for (final l in const LineSplitter().convert(report)) + if (RegExp(r'_kDart(Isolate)?Snapshot(Text|Instructions)\+0x|^\s*#?\d+\s+abs\s+[0-9a-f]+\s+virt\s').hasMatch(l)) l.trim(), +]; diff --git a/scripts/device/e2e_symbolication.dart b/scripts/device/e2e_symbolication.dart new file mode 100644 index 0000000..b8516f1 --- /dev/null +++ b/scripts/device/e2e_symbolication.dart @@ -0,0 +1,493 @@ +// End-to-end symbolication against the REAL Bugsee backend, on a physical device (doc/verification.md, +// "End-to-end symbolication"). No mock: the default endpoint, the real app token. +// +// BUGSEE_IOS_TOKEN=... dart scripts/device/e2e_symbolication.dart ios --udid +// BUGSEE_ANDROID_TOKEN=... dart scripts/device/e2e_symbolication.dart android --serial +// +// Reading the result back needs a credential an app token is not: the organisation's SERVER token of the +// public API (`x-auth-servertoken`) and the application's id: +// BUGSEE_SERVER_TOKEN=... BUGSEE_IOS_APP_ID=... (or BUGSEE_ANDROID_APP_ID=...) +// Without them the run still builds, uploads, runs and crashes, and ends UNVERIFIED (exit 3): it never +// passes without having read the backend's symbolicated frames. +// +// What one run does: +// 1. a unique build string (`9.MMDD.HHMM`, the run id), a release build with `--obfuscate --split-debug-info` +// of example/lib/e2e_main.dart; guards: the symbols are the platform's format, the app's own function +// names are NOT in the shipped binary (obfuscation took place) +// 2. uploads: the Dart symbols with the pinned symbols.py (HTTP statuses recorded), the native symbols +// (iOS: the dSYM with bugsee-cli; Android: the Bugsee Gradle plugin during the release build) +// 3. installs, launches 4 times (doc: example/lib/e2e_main.dart): Dart errors; a native-signal crash; +// a platform-language crash; the upload of the last recovered report +// 4. reads the backend: the issues whose versions contain the run id, their crash reports; expects the +// app's readable function names and no raw addresses +// +// Exit: 0 verified, 3 UNVERIFIED (everything ran, nothing could be read back), 1 INVALID or FAILED, 64 usage. +// No token is ever printed or saved: every line goes through `redact`. +import 'dart:convert'; +import 'dart:io'; + +import 'core/e2e.dart'; +import 'shell.dart'; +import 'toolchain.dart'; + +const _symbolsPy = + 'https://raw.githubusercontent.com/bugsee/bugsee-flutter/9bc0f8645755114491235dc68fec84fdc5671755/scripts/symbols.py'; +const _symbolsPySha = + 'ef2ed4c25b87da764fd5b70238a41d776f6aa88b5e3174faa4e33de2f08453f7'; +const _iosBundle = 'com.bugsee.bugseeFlutterExample'; +const _androidPackage = 'com.bugsee.bugsee_flutter_example'; +const _devlock = '/Volumes/External2TB/tmp-claude/device-locks/devlock.sh'; + +const _expectedDart = [ + 'e2eHandledSite', + 'e2eUnhandledSite', + 'e2eUncaughtThrower', +]; + +late List _secrets; +final _log = StringBuffer(); + +void say(String s) { + final line = redact(s, _secrets); + stdout.writeln(line); + _log.writeln(line); +} + +/// The device this process holds the lock of; `exit` skips `finally`, so every exit path releases it here. +String? _lockedDevice; + +void _unlock() { + final d = _lockedDevice; + if (d == null) return; + _lockedDevice = null; + Process.runSync(_devlock, ['release', d, 'claude-e2e-symbolication']); +} + +Never invalid(String why) { + say('INVALID: $why'); + _save(); + _unlock(); + exit(1); +} + +late String _workDir; +void _save() { + try { + File('$_workDir/e2e-run.log').writeAsStringSync(_log.toString()); + } on Object { + // best effort + } +} + +Future main(List args) async { + if (args.isEmpty || !{'ios', 'android'}.contains(args.first)) { + stderr.writeln( + 'usage: e2e_symbolication.dart ios --udid | android --serial ' + '[--run-id ] [--reuse-build] [--no-lock] [--readback-wait-minutes N]', + ); + exit(64); + } + final platform = args.first; + String? opt(String name) { + final i = args.indexOf(name); + return i >= 0 && i + 1 < args.length ? args[i + 1] : null; + } + + final env = Platform.environment; + final token = env[platform == 'ios' ? 'BUGSEE_IOS_TOKEN' : 'BUGSEE_ANDROID_TOKEN'] ?? ''; + final serverToken = env['BUGSEE_SERVER_TOKEN'] ?? ''; + final appId = env[platform == 'ios' ? 'BUGSEE_IOS_APP_ID' : 'BUGSEE_ANDROID_APP_ID'] ?? ''; + _secrets = [token, serverToken]; + if (token.isEmpty) { + stderr.writeln('BUGSEE_${platform == 'ios' ? 'IOS' : 'ANDROID'}_TOKEN is not set'); + exit(64); + } + final device = opt(platform == 'ios' ? '--udid' : '--serial') ?? ''; + if (device.isEmpty) { + stderr.writeln('the device is required (the run never picks one)'); + exit(64); + } + final repo = Directory.current.path.endsWith('/scripts/device') + ? Directory.current.parent.parent.path + : Directory.current.path; + final runId = opt('--run-id') ?? runIdFor(DateTime.now()); + _workDir = '${env['E2E_WORK_DIR'] ?? '${Directory.systemTemp.path}/bugsee-e2e'}/$platform-$runId'; + Directory(_workDir).createSync(recursive: true); + final tc = Toolchain.detect(repo, _workDir); + say('run $runId on $platform $device, work dir $_workDir'); + say('flutter ${(await tc.describe())['flutter']}, java ${tc.javaHome}'); + final job = _Job(tc, platform, device, token, runId, opt('--reuse-build') != null); + + var locked = false; + if (!args.contains('--no-lock')) { + final r = await sh([_devlock, 'acquire', device, 'claude-e2e-symbolication', 'e2e symbolication run $runId', '600']); + if (!r.ok) invalid('the device lock is not ours: ${r.text}'); + locked = true; + _lockedDevice = device; + } + try { + await job.build(); + await job.uploadDartSymbols(); + await job.runOnDevice(); + } finally { + if (locked) _unlock(); + } + final verdict = await job.readBack( + serverToken, + appId, + Duration(minutes: int.tryParse(opt('--readback-wait-minutes') ?? '') ?? 15), + ); + _save(); + exit(verdict); +} + +class _Job { + _Job(this.tc, this.platform, this.device, this.token, this.runId, this.reuse); + final Toolchain tc; + final String platform; + final String device; + final String token; + final String runId; + final bool reuse; + bool get ios => platform == 'ios'; + + /// `BUGSEE_ENDPOINT` (a version-less base such as https://apidev.bugsee.com): empty means the default, + /// production, endpoint everywhere (SDK, symbols.py, bugsee-cli, Gradle plugin). The same value goes to all. + String get endpoint => + (Platform.environment['BUGSEE_ENDPOINT'] ?? '').replaceAll(RegExp(r'/+$'), ''); + String get symbolsDir => '$_workDir/symbols'; + String get buildNumber => runId.split('.').last; // HHMM + + String get example => '${tc.repoRoot}/example'; + + List get _buildArgs => [ + '--release', + '--obfuscate', + '--split-debug-info=$symbolsDir', + '-t', + 'lib/e2e_main.dart', + '--build-name', + runId, + '--build-number', + buildNumber, + '--dart-define=E2E_RUN=$runId', + if (endpoint.isNotEmpty) '--dart-define=BUGSEE_ENDPOINT=$endpoint', + // No per-launch environment reaches the app (devicectl's did not, measured): the token is compiled into this LOCAL build only. + '--dart-define=BUGSEE_E2E_TOKEN=$token', + ]; + + Future build() async { + Directory(symbolsDir).createSync(recursive: true); + final bugseeProps = File('$example/android/bugsee.properties'); + if (!ios && !reuse) { + // The Gradle plugin reads the app token here (gitignored) and uploads the native libraries' symbols + // when the release variant is assembled. Removed in the `finally` below. + bugseeProps.writeAsStringSync( + 'app_token=$token\n${endpoint.isEmpty ? '' : 'plugin.endpoint=$endpoint\n'}', + ); + await sh(['chmod', '600', bugseeProps.path]); + } + try { + if (!reuse) { + say('building ${ios ? 'ios' : 'apk'} release (obfuscated), build $runId'); + await sh([tc.flutter, 'pub', 'get'], cwd: example, env: tc.buildEnv); + final b = await sh( + [tc.flutter, 'build', if (ios) 'ios' else 'apk', ..._buildArgs], + cwd: example, + env: tc.buildEnv, + timeout: const Duration(minutes: 45), + ); + File('$_workDir/build.log').writeAsStringSync(redact('${b.stdout}\n${b.stderr}', _secrets)); + if (!b.ok) invalid('flutter build failed (see $_workDir/build.log): ${redact(b.stderr, _secrets)}'); + if (!ios) { + final up = RegExp(r'^.*(?:[Bb]ugsee).*(?:upload|symbol).*$', multiLine: true) + .allMatches(b.stdout + b.stderr) + .map((m) => m[0]!) + .toList(); + say('Gradle plugin lines about uploads: ${up.isEmpty ? 'NONE (see build.log; native symbols were probably not uploaded)' : up.join(' | ')}'); + if (up.isEmpty) nativeUploadSeen = false; + } + } + } finally { + if (!ios && bugseeProps.existsSync()) bugseeProps.deleteSync(); + } + // guard: the symbols are the platform's format + final files = Directory(symbolsDir).listSync().whereType().where((f) => f.path.endsWith('.symbols')).toList(); + if (files.isEmpty) invalid('no .symbols file in $symbolsDir: --split-debug-info did not write any'); + for (final f in files) { + final fmt = symbolsFormat(f.openSync().readSync(8)); + final want = ios ? 'macho' : 'elf'; + if (fmt != want) invalid('${f.path} is $fmt, expected $want'); + say('symbols: ${f.path.split('/').last} ($fmt, ${f.lengthSync()} bytes)'); + } + // guard: obfuscation took place: the app's own function name is not in the shipped binary + final binary = ios + ? '$example/build/ios/iphoneos/Runner.app/Frameworks/App.framework/App' + : null; + if (binary != null) { + final s = await sh(['strings', '-a', binary], timeout: const Duration(minutes: 3)); + if (s.stdout.contains('e2eHandledSite')) { + invalid('the shipped App binary still contains "e2eHandledSite": not obfuscated, a readable backend name would prove nothing'); + } + say('obfuscation guard: "e2eHandledSite" is not in the shipped App binary'); + } + } + + bool nativeUploadSeen = true; + + Future uploadDartSymbols() async { + final py = '$_workDir/symbols.py'; + final dl = await sh(['curl', '-fsSL', _symbolsPy, '-o', py]); + if (!dl.ok) invalid('could not fetch symbols.py: ${dl.text}'); + final sha = (await sh(['shasum', '-a', '256', py])).text.split(' ').first; + if (sha != _symbolsPySha) invalid('symbols.py sha256 is $sha, pinned $_symbolsPySha'); + final venv = Platform.environment['E2E_PYTHON'] ?? 'python3'; + say('uploading the Dart symbols with the pinned symbols.py (-t -d -v $runId, default endpoint)'); + final r = await sh([ + venv, + '${tc.repoRoot}/scripts/device/symbols_logged.py', + py, + '-t', + token, + '-v', + runId, + '-d', + symbolsDir, + if (endpoint.isNotEmpty) ...['-e', '$endpoint/v2/'], + ], timeout: const Duration(minutes: 10)); + final out = redact('${r.stdout}\n${r.stderr}', _secrets); + say(out.trim()); + final problems = symbolsUploadProblems(out, r.code); + if (problems.isNotEmpty) invalid('the Dart symbols upload: ${problems.join('; ')}'); + say('Dart symbols uploaded (POST and PUT both 2xx)'); + + if (ios) { + // The native side: the dSYM of this build, with bugsee-cli (docs: /cli/xcode, /cli/debug-files). + final cli = Platform.environment['BUGSEE_CLI'] ?? 'bugsee-cli'; + final dsyms = Directory('$example/build/ios').listSync(recursive: true).whereType().where((d) => d.path.endsWith('.dSYM')).map((d) => d.path).toList(); + say('dSYMs of the build: $dsyms'); + if (dsyms.isEmpty) invalid('no .dSYM was produced by the release build: the native iOS frames cannot be symbolicated'); + final dir = '$_workDir/dsyms'; + Directory(dir).createSync(recursive: true); + for (final d in dsyms) { + await sh(['cp', '-R', d, dir]); + } + final up = await sh( + [cli, 'debug-files', 'upload', dir, '--type', 'dsym', '--version', runId, '--build', buildNumber], + env: { + ...Platform.environment, + 'BUGSEE_APP_TOKEN': token, + if (endpoint.isNotEmpty) 'BUGSEE_ENDPOINT': endpoint, + }, + timeout: const Duration(minutes: 15), + ); + say('bugsee-cli debug-files upload (dsym): exit ${up.code}\n${redact('${up.stdout}\n${up.stderr}', _secrets).trim()}'); + if (!up.ok) invalid('the dSYM upload failed (exit ${up.code})'); + } else if (!nativeUploadSeen) { + say('WARNING: the Gradle plugin printed nothing about an upload; the native Android symbols may be missing'); + } + } + + // ---- the device ------------------------------------------------------------------------------- + + String get consoleFile => '$_workDir/console.txt'; + + Future runOnDevice() async { + if (ios) { + await _runIos(); + } else { + await _runAndroid(); + } + } + + Future _iosLaunch() => Child.start([ + 'xcrun', 'devicectl', 'device', 'process', 'launch', '--device', device, + '--terminate-existing', '--console', + + _iosBundle, + ]); + + Future _runIos() async { + final ctl = ['xcrun', 'devicectl']; + final app = '$example/build/ios/iphoneos/Runner.app'; + await sh([...ctl, 'device', 'uninstall', 'app', '--device', device, _iosBundle]); + final inst = await sh([...ctl, 'device', 'install', 'app', '--device', device, app], timeout: const Duration(minutes: 5)); + if (!inst.ok) invalid('install failed: ${redact(inst.text, _secrets)}'); + say('installed $_iosBundle build $runId'); + final all = StringBuffer(); + try { + for (var phase = 0; phase < 4; phase++) { + say('launch ${phase + 1} of 4 (phase $phase)'); + final c = await _iosLaunch(); + final wantsExit = phase == 1 || phase == 2; + final marker = wantsExit ? '"kind":"crashing"' : '"kind":"phase-done"'; + final ok = await c.waitFor(marker, timeout: const Duration(minutes: 5)); + if (!ok) { + all.write(redact(c.output.toString(), _secrets)); + invalid('phase $phase never reached ${wantsExit ? 'its crash' : 'its end'}:\n${redact(c.output.toString(), _secrets)}'); + } + if (wantsExit) { + final code = await c.process.exitCode.timeout(const Duration(seconds: 90), onTimeout: () => -999); + await c.drained(); + if (code == -999) { + await c.stop(); + all.write(redact(c.output.toString(), _secrets)); + invalid('phase $phase announced a crash and the process did not end within 90 s'); + } + say('phase $phase: the process ended (devicectl exit $code)'); + } else { + await c.stop(); + // Stopping the console child makes devicectl terminate the app it launched, and not at once: the next + // launch of the run was found killed by that SIGTERM 0.2 s after it started (run 7). Let it finish. + await delay(10); + } + all.writeln(redact(c.output.toString(), _secrets)); + } + } finally { + File(consoleFile).writeAsStringSync(all.toString()); + await sh([...ctl, 'device', 'uninstall', 'app', '--device', device, _iosBundle]); + } + _checkEvents('ios'); + } + + Future _runAndroid() async { + final adb = tc.adbPath; + Future a(List args, {Duration timeout = const Duration(minutes: 2)}) => sh([adb, '-s', device, ...args], timeout: timeout); + final state = (await a(['get-state'])).text; + if (state != 'device') invalid('$device is "$state" over adb, not "device"'); + final apk = '$example/build/app/outputs/flutter-apk/app-release.apk'; + await a(['uninstall', _androidPackage]); + final inst = await a(['install', '-r', apk], timeout: const Duration(minutes: 5)); + if (!inst.ok || !inst.stdout.contains('Success')) invalid('install failed: ${inst.text}'); + say('installed $_androidPackage build $runId'); + final all = StringBuffer(); + try { + for (var phase = 0; phase < 4; phase++) { + say('launch ${phase + 1} of 4 (phase $phase)'); + await a(['logcat', '-c']); + await a(['shell', 'am', 'force-stop', _androidPackage]); + final l = await a(['shell', 'am', 'start', '-W', '-n', '$_androidPackage/.MainActivity']); + if (!l.ok) invalid('am start failed: ${l.text}'); + final wantsExit = phase == 1 || phase == 2; + final marker = wantsExit ? '"kind":"crashing"' : '"kind":"phase-done"'; + final end = DateTime.now().add(const Duration(minutes: 5)); + var seen = false; + var log = ''; + while (DateTime.now().isBefore(end)) { + log = (await a(['logcat', '-d', '-s', 'flutter'])).stdout; + if (log.contains(marker)) { + seen = true; + break; + } + await delay(2); + } + all.writeln(redact(log, _secrets)); + if (!seen) invalid('phase $phase never reached ${wantsExit ? 'its crash' : 'its end'}'); + if (wantsExit) { + final gone = await until(() async => (await a(['shell', 'pidof', _androidPackage])).text.isEmpty ? true : null, timeout: const Duration(seconds: 90), every: const Duration(seconds: 2)); + if (gone != true) invalid('phase $phase announced a crash and the process is still alive after 90 s'); + say('phase $phase: the process ended'); + } + } + } finally { + File(consoleFile).writeAsStringSync(all.toString()); + await a(['shell', 'am', 'force-stop', _androidPackage]); + await a(['uninstall', _androidPackage]); + } + _checkEvents('android'); + } + + void _checkEvents(String os) { + final events = e2eEvents(File(consoleFile).readAsStringSync(), runId); + say('${events.length} events of run $runId in the console'); + final problems = phaseProblems(events, os: os, release: true); + if (problems.isNotEmpty) invalid('the device run: ${problems.join('; ')}'); + say('device run complete: 4 launches (errors, native signal, platform crash, upload), 2 crashes, all launched'); + } + + // ---- the backend -------------------------------------------------------------------------------- + + Future readBack(String serverToken, String appId, Duration wait) async { + if (serverToken.isEmpty || appId.isEmpty) { + say('UNVERIFIED: reading the backend needs the organisation SERVER token (BUGSEE_SERVER_TOKEN, the public ' + 'API\'s x-auth-servertoken) and the application id (BUGSEE_${ios ? 'IOS' : 'ANDROID'}_APP_ID). An app token ' + 'cannot read issues. Everything before this point ran: the build is $runId; find it in the dashboard ' + 'by that version string.'); + return 3; + } + final base = '${endpoint.isEmpty ? 'https://api.bugsee.com' : endpoint}/v2/partner/'; + final client = HttpClient(); + Future get(String path) async { + final req = await client.getUrl(Uri.parse('$base$path')); + req.headers.set('x-auth-servertoken', serverToken); + final res = await req.close(); + final body = await res.transform(utf8.decoder).join(); + if (res.statusCode != 200) { + throw StateError('GET $path -> ${res.statusCode} ${redact(body, _secrets)}'); + } + final v = jsonDecode(body); + return v is Map && v.containsKey('result') ? v['result'] : v; + } + + final end = DateTime.now().add(wait); + List> mine = []; + while (DateTime.now().isBefore(end)) { + try { + final r = await get('applications/$appId/issues?limit=100') as Map; + final objs = (r['objects'] as List).cast(); + mine = [ + for (final i in objs) + if (((i['statistics'] as Map?)?['versions'] as Map?)?.keys.any((k) => '$k' == runId) ?? false) + i.cast(), + ]; + say('backend: ${objs.length} issues listed, ${mine.length} with version $runId'); + if (mine.length >= 3) break; // handled+uncaught are error issues, the crashes are issues too + } on Object catch (e) { + say('backend read: $e'); + } + await delay(30); + } + final reports = []; + for (final issue in mine) { + final id = issue['_id']; + say('issue $id type=${issue['type']} summary="${issue['summary']}"'); + try { + final recs = await get('applications/$appId/issues/$id/recordings'); + final list = (recs is Map ? recs['objects'] : recs) as List? ?? []; + for (final rec in list.take(3)) { + final rid = (rec as Map)['_id']; + final text = await _text(client, '${base}applications/$appId/issues/$id/recordings/$rid/crash_report', serverToken); + reports.add(text); + File('$_workDir/backend-$id-$rid.txt').writeAsStringSync(redact(text, _secrets)); + final raw = rawFrameLines(text); + say(' recording $rid: ${text.split('\n').length} lines, ${raw.length} raw frame line(s)'); + for (final l in text.split('\n').where((l) => _expectedDart.any(l.contains)).take(6)) { + say(' $l'); + } + } + } on Object catch (e) { + say(' recording read: $e'); + } + } + final problems = readbackProblems( + reports, + expectedDartNames: _expectedDart, + expectedNativeNames: [ios ? 'AppDelegate' : 'MainActivity'], + ); + if (problems.isNotEmpty) { + say('NOT SYMBOLICATED (or not found): ${problems.join('; ')}'); + return 1; + } + say('VERIFIED: the backend shows the readable names ${_expectedDart.join(', ')} and the native side'); + return 0; + } + + Future _text(HttpClient c, String url, String serverToken) async { + final req = await c.getUrl(Uri.parse(url)); + req.headers.set('x-auth-servertoken', serverToken); + final res = await req.close(); + final body = await res.transform(utf8.decoder).join(); + if (res.statusCode != 200) throw StateError('GET crash_report -> ${res.statusCode}'); + return body; + } +} diff --git a/scripts/device/symbols_logged.py b/scripts/device/symbols_logged.py new file mode 100644 index 0000000..bb28114 --- /dev/null +++ b/scripts/device/symbols_logged.py @@ -0,0 +1,48 @@ +"""Runs the pinned 9.x `symbols.py` UNCHANGED and prints what it never does: each HTTP exchange's method, +host, path with the app token redacted, and status. Used by scripts/device/e2e_symbolication.dart. + + python3 symbols_logged.py + +The uploader's own exit code is the exit code here. The token is never printed (it is replaced in every +URL), and a presigned upload URL is shown as host and path only (its query holds a signature). +""" +import runpy +import sys +from urllib.parse import urlsplit + +import requests + +script = sys.argv[1] +argv = sys.argv[2:] +token = '' +for i, a in enumerate(argv): + if a == '-t' and i + 1 < len(argv): + token = argv[i + 1] + + +def redact(url): + p = urlsplit(url) + path = p.path.replace(token, '') if token else p.path + return f'{p.scheme}://{p.netloc}{path}' + ('?' if p.query else '') + + +_send = requests.Session.send + + +def send(self, request, **kwargs): + response = _send(self, request, **kwargs) + size = request.headers.get('Content-Length', '?') + print(f'HTTP {request.method} {redact(request.url)} -> {response.status_code} (request body {size} bytes)', flush=True) + if not response.ok: + body = (response.text or '')[:300].replace(token, '') if token else (response.text or '')[:300] + print(f'HTTP error body: {body}', flush=True) + return response + + +requests.Session.send = send +sys.argv = [script] + argv +try: + runpy.run_path(script, run_name='__main__') +except SystemExit as e: + print(f'symbols.py exit: {e.code}', flush=True) + raise diff --git a/test/device_harness_test.dart b/test/device_harness_test.dart index d9b4f36..2fd013d 100644 --- a/test/device_harness_test.dart +++ b/test/device_harness_test.dart @@ -20,6 +20,7 @@ import '../scripts/device/core/lan_host.dart'; import '../scripts/device/core/expectations.dart'; import '../scripts/device/core/image.dart'; import '../scripts/device/core/crash_kinds.dart'; +import '../scripts/device/core/e2e.dart'; import '../scripts/device/core/log_parsers.dart'; import '../scripts/device/core/symbols.dart'; import '../scripts/device/core/zip.dart'; @@ -1506,4 +1507,139 @@ Runner[1:2] (Flutter) flutter: VERIFY|{"kind":"handler","phase":"before","type": }, ); }); + + group('the end-to-end symbolication run (e2e_symbolication.dart)', () { + const post200 = + 'HTTP POST https://api.bugsee.com/v2/apps//symbols -> 200 (request body 90 bytes)\n'; + + test('redact removes every secret and ignores trivial ones', () { + const t = 'GET /apps/app-token-secret/symbols server=SRV-TOKEN-1234'; + final r = redact(t, ['app-token-secret', 'SRV-TOKEN-1234', 'ab']); + expect(r, isNot(contains('app-token'))); + expect(r, isNot(contains('SRV-TOKEN'))); + expect(r.split('').length, 3); + }); + + test('events of another run are dropped; a truncated line does not throw', () { + const console = + 'noise\nE2E|{"kind":"start","run":"9.1.1","phase":0}\n' + 'E2E|{"kind":"start","run":"OLD","phase":0}\nE2E|{"kind":"sta'; + final e = e2eEvents(console, '9.1.1'); + expect(e, hasLength(1)); + expect(e.single['phase'], 0); + }); + + test('symbols.py exiting 0 after a refused POST is NOT an upload', () { + // the pinned script returns None from a non-2xx POST and exits 0 + expect(symbolsUploadProblems('', 0), isNotEmpty); + expect( + symbolsUploadProblems( + 'HTTP POST https://x/apps//symbols -> 403 (request body 90 bytes)\n', + 0, + ), + anyElement(contains('403')), + ); + expect(symbolsUploadProblems(post200, 0), anyElement(contains('no PUT'))); + expect( + symbolsUploadProblems( + '${post200}HTTP PUT https://s3.example/k? -> 200 (request body 5 bytes)\n', + 0, + ), + isEmpty, + ); + expect( + symbolsUploadProblems( + '${post200}HTTP PUT https://s3/k -> 403 (request body 1 bytes)\n', + 0, + ), + anyElement(contains('403')), + ); + }); + + test('the device run needs all four phases, launched, release, two crashes', () { + List> good() => [ + for (var p = 0; p < 4; p++) ...[ + {'kind': 'start', 'phase': p, 'mode': 'release', 'os': 'ios'}, + {'kind': 'launch', 'result': 'launched'}, + if (p == 0) {'kind': 'reported'}, + if (p == 1 || p == 2) {'kind': 'crashing'}, + ], + ]; + expect(phaseProblems(good(), os: 'ios', release: true), isEmpty); + expect( + phaseProblems(good().sublist(4), os: 'ios', release: true), + isNotEmpty, + ); + expect( + phaseProblems( + good() + .map((e) => e['kind'] == 'start' ? {...e, 'mode': 'debug'} : e) + .toList(), + os: 'ios', + release: true, + ), + anyElement(contains('release')), + ); + expect( + phaseProblems( + good() + .map( + (e) => e['kind'] == 'launch' + ? {...e, 'result': 'already-running'} + : e, + ) + .toList(), + os: 'ios', + release: true, + ), + isNotEmpty, + ); + }); + + test('run ids are unique per minute and valid as an iOS short version', () { + final a = runIdFor(DateTime(2026, 11, 23, 14, 5)); + expect(a, '9.1123.1405'); + expect(runIdFor(DateTime(2026, 11, 23, 14, 6)), isNot(a)); + expect(RegExp(r'^\d+\.\d+\.\d+$').hasMatch(a), isTrue); + }); + + test('the symbols file must be the platform format', () { + expect(symbolsFormat([0x7f, 0x45, 0x4c, 0x46, 2, 1]), 'elf'); + expect(symbolsFormat([0xcf, 0xfa, 0xed, 0xfe, 12, 0]), 'macho'); + expect(symbolsFormat([0x50, 0x4b, 3, 4]), isNull); + }); + + test('a backend report with raw frames or without the names is not symbolicated', () { + const good = + '#0 e2eHandledSite (e2e_main.dart:40)\n#1 e2eUnhandledSite\n#2 e2eUncaughtThrower\nAppDelegate'; + const dart = ['e2eHandledSite', 'e2eUnhandledSite', 'e2eUncaughtThrower']; + expect( + readbackProblems( + [good], + expectedDartNames: dart, + expectedNativeNames: ['AppDelegate'], + ), + isEmpty, + ); + expect( + readbackProblems( + ['#0 abs 0000 virt 1234 _kDartSnapshotText+0x42'], + expectedDartNames: ['e2eHandledSite'], + expectedNativeNames: [], + ), + isNotEmpty, + ); + expect( + readbackProblems([], expectedDartNames: [], expectedNativeNames: []), + anyElement(contains('nothing was verified')), + ); + expect( + rawFrameLines( + ' #00 abs 0000007f virt 000000000012 _kDartSnapshotText+0x42 (x)', + ), + hasLength(1), + ); + expect(rawFrameLines('#0 e2eHandledSite (e2e_main.dart:40)'), isEmpty); + }); + }); } From 263c7da3fa2d098478be0d0d8c5acb9dcdeed8b7 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 20:29:46 +0500 Subject: [PATCH 02/14] Format the e2e files Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxNbNUdWru1zs68bYV8 Change-Id: I38dc93f2daef72c7c174259797ba044babda0253 --- example/lib/e2e_main.dart | 11 +- scripts/device/core/e2e.dart | 39 +++- scripts/device/e2e_symbolication.dart | 284 ++++++++++++++++++++------ test/device_harness_test.dart | 100 ++++----- 4 files changed, 312 insertions(+), 122 deletions(-) diff --git a/example/lib/e2e_main.dart b/example/lib/e2e_main.dart index 86184c2..373c2b7 100644 --- a/example/lib/e2e_main.dart +++ b/example/lib/e2e_main.dart @@ -26,7 +26,7 @@ import 'crash_lab.dart' as crash_lab; const _run = String.fromEnvironment('E2E_RUN'); const _defineToken = String.fromEnvironment('BUGSEE_E2E_TOKEN'); const _endpoint = String.fromEnvironment('BUGSEE_ENDPOINT'); -const _wait =int.fromEnvironment('E2E_WAIT_SECONDS', defaultValue: 40); +const _wait = int.fromEnvironment('E2E_WAIT_SECONDS', defaultValue: 40); void _emit(String kind, [Map data = const {}]) { final line = 'E2E|${jsonEncode({'kind': kind, 'run': _run, ...data})}'; @@ -55,9 +55,8 @@ Future e2eUnhandledSite() async { @pragma('vm:never-inline') void e2eUncaughtSite() { unawaited( - Future.delayed(const Duration(milliseconds: 20)).then( - (_) => e2eUncaughtThrower(), - ), + Future.delayed(const Duration(milliseconds: 20)) + .then((_) => e2eUncaughtThrower()), ); } @@ -135,7 +134,9 @@ Future _phases() async { void main() { runApp( - const MaterialApp(home: Scaffold(body: Center(child: Text('e2e')))), + const MaterialApp( + home: Scaffold(body: Center(child: Text('e2e'))), + ), ); unawaited(_phases()); } diff --git a/scripts/device/core/e2e.dart b/scripts/device/core/e2e.dart index 5d5db54..461d678 100644 --- a/scripts/device/core/e2e.dart +++ b/scripts/device/core/e2e.dart @@ -56,7 +56,9 @@ List symbolsUploadProblems(String output, int exitCode) { problems.add('POST .../symbols answered $post'); } if (put == null) { - problems.add('no PUT of the zip was made (no presigned URL, or it was not used)'); + problems.add( + 'no PUT of the zip was made (no presigned URL, or it was not used)', + ); } else if (!put.startsWith('2')) { problems.add('PUT of the zip answered $put'); } @@ -76,23 +78,31 @@ List phaseProblems( final starts = events.where((e) => e['kind'] == 'start').toList(); final phases = starts.map((e) => e['phase']).toList(); if (phases.join(',') != '0,1,2,3') { - problems.add('the app started phases [${phases.join(',')}], expected 0,1,2,3'); + problems.add( + 'the app started phases [${phases.join(',')}], expected 0,1,2,3', + ); } for (final s in starts) { - if (s['os'] != os) problems.add('a start event says os ${s['os']}, expected $os'); + if (s['os'] != os) + problems.add('a start event says os ${s['os']}, expected $os'); if (release && s['mode'] != 'release') { problems.add('a start event says mode ${s['mode']}, expected release'); } } final launches = events.where((e) => e['kind'] == 'launch').toList(); if (launches.length != 4 || launches.any((e) => e['result'] != 'launched')) { - problems.add('launch results: ${launches.map((e) => e['result']).toList()}, expected 4 x launched'); + problems.add( + 'launch results: ${launches.map((e) => e['result']).toList()}, expected 4 x launched', + ); } if (events.any((e) => e['kind'] == 'invalid')) { - problems.add('the app reported invalid: ${events.where((e) => e['kind'] == 'invalid').toList()}'); + problems.add( + 'the app reported invalid: ${events.where((e) => e['kind'] == 'invalid').toList()}', + ); } final crashes = events.where((e) => e['kind'] == 'crashing').length; - if (crashes != 2) problems.add('the app announced $crashes crashes, expected 2'); + if (crashes != 2) + problems.add('the app announced $crashes crashes, expected 2'); if (!events.any((e) => e['kind'] == 'reported')) { problems.add('phase 0 never reported its Dart errors'); } @@ -109,7 +119,10 @@ String runIdFor(DateTime now) { /// A `.symbols` file's format by magic bytes: `elf` (Android), `macho` (iOS), or null. String? symbolsFormat(List head) { if (head.length < 4) return null; - if (head[0] == 0x7f && head[1] == 0x45 && head[2] == 0x4c && head[3] == 0x46) { + if (head[0] == 0x7f && + head[1] == 0x45 && + head[2] == 0x4c && + head[3] == 0x46) { return 'elf'; } final m = (head[0] << 24) | (head[1] << 16) | (head[2] << 8) | head[3]; @@ -129,11 +142,14 @@ List readbackProblems( }) { final problems = []; if (reports.isEmpty) { - return ['the backend returned no report for this build: nothing was verified']; + return [ + 'the backend returned no report for this build: nothing was verified', + ]; } final all = reports.join('\n'); for (final n in [...expectedDartNames, ...expectedNativeNames]) { - if (!all.contains(n)) problems.add('"$n" is in none of the ${reports.length} report(s)'); + if (!all.contains(n)) + problems.add('"$n" is in none of the ${reports.length} report(s)'); } return problems; } @@ -141,5 +157,8 @@ List readbackProblems( /// Frames that are still raw addresses in a rendered report (a symbolication that did not happen). List rawFrameLines(String report) => [ for (final l in const LineSplitter().convert(report)) - if (RegExp(r'_kDart(Isolate)?Snapshot(Text|Instructions)\+0x|^\s*#?\d+\s+abs\s+[0-9a-f]+\s+virt\s').hasMatch(l)) l.trim(), + if (RegExp( + r'_kDart(Isolate)?Snapshot(Text|Instructions)\+0x|^\s*#?\d+\s+abs\s+[0-9a-f]+\s+virt\s', + ).hasMatch(l)) + l.trim(), ]; diff --git a/scripts/device/e2e_symbolication.dart b/scripts/device/e2e_symbolication.dart index b8516f1..bcbb5b7 100644 --- a/scripts/device/e2e_symbolication.dart +++ b/scripts/device/e2e_symbolication.dart @@ -94,12 +94,18 @@ Future main(List args) async { } final env = Platform.environment; - final token = env[platform == 'ios' ? 'BUGSEE_IOS_TOKEN' : 'BUGSEE_ANDROID_TOKEN'] ?? ''; + final token = + env[platform == 'ios' ? 'BUGSEE_IOS_TOKEN' : 'BUGSEE_ANDROID_TOKEN'] ?? + ''; final serverToken = env['BUGSEE_SERVER_TOKEN'] ?? ''; - final appId = env[platform == 'ios' ? 'BUGSEE_IOS_APP_ID' : 'BUGSEE_ANDROID_APP_ID'] ?? ''; + final appId = + env[platform == 'ios' ? 'BUGSEE_IOS_APP_ID' : 'BUGSEE_ANDROID_APP_ID'] ?? + ''; _secrets = [token, serverToken]; if (token.isEmpty) { - stderr.writeln('BUGSEE_${platform == 'ios' ? 'IOS' : 'ANDROID'}_TOKEN is not set'); + stderr.writeln( + 'BUGSEE_${platform == 'ios' ? 'IOS' : 'ANDROID'}_TOKEN is not set', + ); exit(64); } final device = opt(platform == 'ios' ? '--udid' : '--serial') ?? ''; @@ -111,16 +117,31 @@ Future main(List args) async { ? Directory.current.parent.parent.path : Directory.current.path; final runId = opt('--run-id') ?? runIdFor(DateTime.now()); - _workDir = '${env['E2E_WORK_DIR'] ?? '${Directory.systemTemp.path}/bugsee-e2e'}/$platform-$runId'; + _workDir = + '${env['E2E_WORK_DIR'] ?? '${Directory.systemTemp.path}/bugsee-e2e'}/$platform-$runId'; Directory(_workDir).createSync(recursive: true); final tc = Toolchain.detect(repo, _workDir); say('run $runId on $platform $device, work dir $_workDir'); say('flutter ${(await tc.describe())['flutter']}, java ${tc.javaHome}'); - final job = _Job(tc, platform, device, token, runId, opt('--reuse-build') != null); + final job = _Job( + tc, + platform, + device, + token, + runId, + opt('--reuse-build') != null, + ); var locked = false; if (!args.contains('--no-lock')) { - final r = await sh([_devlock, 'acquire', device, 'claude-e2e-symbolication', 'e2e symbolication run $runId', '600']); + final r = await sh([ + _devlock, + 'acquire', + device, + 'claude-e2e-symbolication', + 'e2e symbolication run $runId', + '600', + ]); if (!r.ok) invalid('the device lock is not ours: ${r.text}'); locked = true; _lockedDevice = device; @@ -153,8 +174,8 @@ class _Job { /// `BUGSEE_ENDPOINT` (a version-less base such as https://apidev.bugsee.com): empty means the default, /// production, endpoint everywhere (SDK, symbols.py, bugsee-cli, Gradle plugin). The same value goes to all. - String get endpoint => - (Platform.environment['BUGSEE_ENDPOINT'] ?? '').replaceAll(RegExp(r'/+$'), ''); + String get endpoint => (Platform.environment['BUGSEE_ENDPOINT'] ?? '') + .replaceAll(RegExp(r'/+$'), ''); String get symbolsDir => '$_workDir/symbols'; String get buildNumber => runId.split('.').last; // HHMM @@ -189,7 +210,9 @@ class _Job { } try { if (!reuse) { - say('building ${ios ? 'ios' : 'apk'} release (obfuscated), build $runId'); + say( + 'building ${ios ? 'ios' : 'apk'} release (obfuscated), build $runId', + ); await sh([tc.flutter, 'pub', 'get'], cwd: example, env: tc.buildEnv); final b = await sh( [tc.flutter, 'build', if (ios) 'ios' else 'apk', ..._buildArgs], @@ -197,14 +220,20 @@ class _Job { env: tc.buildEnv, timeout: const Duration(minutes: 45), ); - File('$_workDir/build.log').writeAsStringSync(redact('${b.stdout}\n${b.stderr}', _secrets)); - if (!b.ok) invalid('flutter build failed (see $_workDir/build.log): ${redact(b.stderr, _secrets)}'); + File('$_workDir/build.log') + .writeAsStringSync(redact('${b.stdout}\n${b.stderr}', _secrets)); + if (!b.ok) + invalid( + 'flutter build failed (see $_workDir/build.log): ${redact(b.stderr, _secrets)}', + ); if (!ios) { - final up = RegExp(r'^.*(?:[Bb]ugsee).*(?:upload|symbol).*$', multiLine: true) - .allMatches(b.stdout + b.stderr) - .map((m) => m[0]!) - .toList(); - say('Gradle plugin lines about uploads: ${up.isEmpty ? 'NONE (see build.log; native symbols were probably not uploaded)' : up.join(' | ')}'); + final up = RegExp( + r'^.*(?:[Bb]ugsee).*(?:upload|symbol).*$', + multiLine: true, + ).allMatches(b.stdout + b.stderr).map((m) => m[0]!).toList(); + say( + 'Gradle plugin lines about uploads: ${up.isEmpty ? 'NONE (see build.log; native symbols were probably not uploaded)' : up.join(' | ')}', + ); if (up.isEmpty) nativeUploadSeen = false; } } @@ -212,8 +241,15 @@ class _Job { if (!ios && bugseeProps.existsSync()) bugseeProps.deleteSync(); } // guard: the symbols are the platform's format - final files = Directory(symbolsDir).listSync().whereType().where((f) => f.path.endsWith('.symbols')).toList(); - if (files.isEmpty) invalid('no .symbols file in $symbolsDir: --split-debug-info did not write any'); + final files = Directory(symbolsDir) + .listSync() + .whereType() + .where((f) => f.path.endsWith('.symbols')) + .toList(); + if (files.isEmpty) + invalid( + 'no .symbols file in $symbolsDir: --split-debug-info did not write any', + ); for (final f in files) { final fmt = symbolsFormat(f.openSync().readSync(8)); final want = ios ? 'macho' : 'elf'; @@ -225,11 +261,19 @@ class _Job { ? '$example/build/ios/iphoneos/Runner.app/Frameworks/App.framework/App' : null; if (binary != null) { - final s = await sh(['strings', '-a', binary], timeout: const Duration(minutes: 3)); + final s = await sh([ + 'strings', + '-a', + binary, + ], timeout: const Duration(minutes: 3)); if (s.stdout.contains('e2eHandledSite')) { - invalid('the shipped App binary still contains "e2eHandledSite": not obfuscated, a readable backend name would prove nothing'); + invalid( + 'the shipped App binary still contains "e2eHandledSite": not obfuscated, a readable backend name would prove nothing', + ); } - say('obfuscation guard: "e2eHandledSite" is not in the shipped App binary'); + say( + 'obfuscation guard: "e2eHandledSite" is not in the shipped App binary', + ); } } @@ -240,9 +284,12 @@ class _Job { final dl = await sh(['curl', '-fsSL', _symbolsPy, '-o', py]); if (!dl.ok) invalid('could not fetch symbols.py: ${dl.text}'); final sha = (await sh(['shasum', '-a', '256', py])).text.split(' ').first; - if (sha != _symbolsPySha) invalid('symbols.py sha256 is $sha, pinned $_symbolsPySha'); + if (sha != _symbolsPySha) + invalid('symbols.py sha256 is $sha, pinned $_symbolsPySha'); final venv = Platform.environment['E2E_PYTHON'] ?? 'python3'; - say('uploading the Dart symbols with the pinned symbols.py (-t -d -v $runId, default endpoint)'); + say( + 'uploading the Dart symbols with the pinned symbols.py (-t -d -v $runId, default endpoint)', + ); final r = await sh([ venv, '${tc.repoRoot}/scripts/device/symbols_logged.py', @@ -258,22 +305,42 @@ class _Job { final out = redact('${r.stdout}\n${r.stderr}', _secrets); say(out.trim()); final problems = symbolsUploadProblems(out, r.code); - if (problems.isNotEmpty) invalid('the Dart symbols upload: ${problems.join('; ')}'); + if (problems.isNotEmpty) + invalid('the Dart symbols upload: ${problems.join('; ')}'); say('Dart symbols uploaded (POST and PUT both 2xx)'); if (ios) { // The native side: the dSYM of this build, with bugsee-cli (docs: /cli/xcode, /cli/debug-files). final cli = Platform.environment['BUGSEE_CLI'] ?? 'bugsee-cli'; - final dsyms = Directory('$example/build/ios').listSync(recursive: true).whereType().where((d) => d.path.endsWith('.dSYM')).map((d) => d.path).toList(); + final dsyms = Directory('$example/build/ios') + .listSync(recursive: true) + .whereType() + .where((d) => d.path.endsWith('.dSYM')) + .map((d) => d.path) + .toList(); say('dSYMs of the build: $dsyms'); - if (dsyms.isEmpty) invalid('no .dSYM was produced by the release build: the native iOS frames cannot be symbolicated'); + if (dsyms.isEmpty) + invalid( + 'no .dSYM was produced by the release build: the native iOS frames cannot be symbolicated', + ); final dir = '$_workDir/dsyms'; Directory(dir).createSync(recursive: true); for (final d in dsyms) { await sh(['cp', '-R', d, dir]); } final up = await sh( - [cli, 'debug-files', 'upload', dir, '--type', 'dsym', '--version', runId, '--build', buildNumber], + [ + cli, + 'debug-files', + 'upload', + dir, + '--type', + 'dsym', + '--version', + runId, + '--build', + buildNumber, + ], env: { ...Platform.environment, 'BUGSEE_APP_TOKEN': token, @@ -281,10 +348,14 @@ class _Job { }, timeout: const Duration(minutes: 15), ); - say('bugsee-cli debug-files upload (dsym): exit ${up.code}\n${redact('${up.stdout}\n${up.stderr}', _secrets).trim()}'); + say( + 'bugsee-cli debug-files upload (dsym): exit ${up.code}\n${redact('${up.stdout}\n${up.stderr}', _secrets).trim()}', + ); if (!up.ok) invalid('the dSYM upload failed (exit ${up.code})'); } else if (!nativeUploadSeen) { - say('WARNING: the Gradle plugin printed nothing about an upload; the native Android symbols may be missing'); + say( + 'WARNING: the Gradle plugin printed nothing about an upload; the native Android symbols may be missing', + ); } } @@ -301,8 +372,15 @@ class _Job { } Future _iosLaunch() => Child.start([ - 'xcrun', 'devicectl', 'device', 'process', 'launch', '--device', device, - '--terminate-existing', '--console', + 'xcrun', + 'devicectl', + 'device', + 'process', + 'launch', + '--device', + device, + '--terminate-existing', + '--console', _iosBundle, ]); @@ -310,8 +388,24 @@ class _Job { Future _runIos() async { final ctl = ['xcrun', 'devicectl']; final app = '$example/build/ios/iphoneos/Runner.app'; - await sh([...ctl, 'device', 'uninstall', 'app', '--device', device, _iosBundle]); - final inst = await sh([...ctl, 'device', 'install', 'app', '--device', device, app], timeout: const Duration(minutes: 5)); + await sh([ + ...ctl, + 'device', + 'uninstall', + 'app', + '--device', + device, + _iosBundle, + ]); + final inst = await sh([ + ...ctl, + 'device', + 'install', + 'app', + '--device', + device, + app, + ], timeout: const Duration(minutes: 5)); if (!inst.ok) invalid('install failed: ${redact(inst.text, _secrets)}'); say('installed $_iosBundle build $runId'); final all = StringBuffer(); @@ -324,15 +418,22 @@ class _Job { final ok = await c.waitFor(marker, timeout: const Duration(minutes: 5)); if (!ok) { all.write(redact(c.output.toString(), _secrets)); - invalid('phase $phase never reached ${wantsExit ? 'its crash' : 'its end'}:\n${redact(c.output.toString(), _secrets)}'); + invalid( + 'phase $phase never reached ${wantsExit ? 'its crash' : 'its end'}:\n${redact(c.output.toString(), _secrets)}', + ); } if (wantsExit) { - final code = await c.process.exitCode.timeout(const Duration(seconds: 90), onTimeout: () => -999); + final code = await c.process.exitCode.timeout( + const Duration(seconds: 90), + onTimeout: () => -999, + ); await c.drained(); if (code == -999) { await c.stop(); all.write(redact(c.output.toString(), _secrets)); - invalid('phase $phase announced a crash and the process did not end within 90 s'); + invalid( + 'phase $phase announced a crash and the process did not end within 90 s', + ); } say('phase $phase: the process ended (devicectl exit $code)'); } else { @@ -345,20 +446,37 @@ class _Job { } } finally { File(consoleFile).writeAsStringSync(all.toString()); - await sh([...ctl, 'device', 'uninstall', 'app', '--device', device, _iosBundle]); + await sh([ + ...ctl, + 'device', + 'uninstall', + 'app', + '--device', + device, + _iosBundle, + ]); } _checkEvents('ios'); } Future _runAndroid() async { final adb = tc.adbPath; - Future a(List args, {Duration timeout = const Duration(minutes: 2)}) => sh([adb, '-s', device, ...args], timeout: timeout); + Future a( + List args, { + Duration timeout = const Duration(minutes: 2), + }) => sh([adb, '-s', device, ...args], timeout: timeout); final state = (await a(['get-state'])).text; - if (state != 'device') invalid('$device is "$state" over adb, not "device"'); + if (state != 'device') + invalid('$device is "$state" over adb, not "device"'); final apk = '$example/build/app/outputs/flutter-apk/app-release.apk'; await a(['uninstall', _androidPackage]); - final inst = await a(['install', '-r', apk], timeout: const Duration(minutes: 5)); - if (!inst.ok || !inst.stdout.contains('Success')) invalid('install failed: ${inst.text}'); + final inst = await a([ + 'install', + '-r', + apk, + ], timeout: const Duration(minutes: 5)); + if (!inst.ok || !inst.stdout.contains('Success')) + invalid('install failed: ${inst.text}'); say('installed $_androidPackage build $runId'); final all = StringBuffer(); try { @@ -366,7 +484,14 @@ class _Job { say('launch ${phase + 1} of 4 (phase $phase)'); await a(['logcat', '-c']); await a(['shell', 'am', 'force-stop', _androidPackage]); - final l = await a(['shell', 'am', 'start', '-W', '-n', '$_androidPackage/.MainActivity']); + final l = await a([ + 'shell', + 'am', + 'start', + '-W', + '-n', + '$_androidPackage/.MainActivity', + ]); if (!l.ok) invalid('am start failed: ${l.text}'); final wantsExit = phase == 1 || phase == 2; final marker = wantsExit ? '"kind":"crashing"' : '"kind":"phase-done"'; @@ -382,10 +507,23 @@ class _Job { await delay(2); } all.writeln(redact(log, _secrets)); - if (!seen) invalid('phase $phase never reached ${wantsExit ? 'its crash' : 'its end'}'); + if (!seen) + invalid( + 'phase $phase never reached ${wantsExit ? 'its crash' : 'its end'}', + ); if (wantsExit) { - final gone = await until(() async => (await a(['shell', 'pidof', _androidPackage])).text.isEmpty ? true : null, timeout: const Duration(seconds: 90), every: const Duration(seconds: 2)); - if (gone != true) invalid('phase $phase announced a crash and the process is still alive after 90 s'); + final gone = await until( + () async => + (await a(['shell', 'pidof', _androidPackage])).text.isEmpty + ? true + : null, + timeout: const Duration(seconds: 90), + every: const Duration(seconds: 2), + ); + if (gone != true) + invalid( + 'phase $phase announced a crash and the process is still alive after 90 s', + ); say('phase $phase: the process ended'); } } @@ -402,20 +540,25 @@ class _Job { say('${events.length} events of run $runId in the console'); final problems = phaseProblems(events, os: os, release: true); if (problems.isNotEmpty) invalid('the device run: ${problems.join('; ')}'); - say('device run complete: 4 launches (errors, native signal, platform crash, upload), 2 crashes, all launched'); + say( + 'device run complete: 4 launches (errors, native signal, platform crash, upload), 2 crashes, all launched', + ); } // ---- the backend -------------------------------------------------------------------------------- Future readBack(String serverToken, String appId, Duration wait) async { if (serverToken.isEmpty || appId.isEmpty) { - say('UNVERIFIED: reading the backend needs the organisation SERVER token (BUGSEE_SERVER_TOKEN, the public ' - 'API\'s x-auth-servertoken) and the application id (BUGSEE_${ios ? 'IOS' : 'ANDROID'}_APP_ID). An app token ' - 'cannot read issues. Everything before this point ran: the build is $runId; find it in the dashboard ' - 'by that version string.'); + say( + 'UNVERIFIED: reading the backend needs the organisation SERVER token (BUGSEE_SERVER_TOKEN, the public ' + 'API\'s x-auth-servertoken) and the application id (BUGSEE_${ios ? 'IOS' : 'ANDROID'}_APP_ID). An app token ' + 'cannot read issues. Everything before this point ran: the build is $runId; find it in the dashboard ' + 'by that version string.', + ); return 3; } - final base = '${endpoint.isEmpty ? 'https://api.bugsee.com' : endpoint}/v2/partner/'; + final base = + '${endpoint.isEmpty ? 'https://api.bugsee.com' : endpoint}/v2/partner/'; final client = HttpClient(); Future get(String path) async { final req = await client.getUrl(Uri.parse('$base$path')); @@ -423,7 +566,9 @@ class _Job { final res = await req.close(); final body = await res.transform(utf8.decoder).join(); if (res.statusCode != 200) { - throw StateError('GET $path -> ${res.statusCode} ${redact(body, _secrets)}'); + throw StateError( + 'GET $path -> ${res.statusCode} ${redact(body, _secrets)}', + ); } final v = jsonDecode(body); return v is Map && v.containsKey('result') ? v['result'] : v; @@ -437,10 +582,15 @@ class _Job { final objs = (r['objects'] as List).cast(); mine = [ for (final i in objs) - if (((i['statistics'] as Map?)?['versions'] as Map?)?.keys.any((k) => '$k' == runId) ?? false) + if (((i['statistics'] as Map?)?['versions'] as Map?)?.keys.any( + (k) => '$k' == runId, + ) ?? + false) i.cast(), ]; - say('backend: ${objs.length} issues listed, ${mine.length} with version $runId'); + say( + 'backend: ${objs.length} issues listed, ${mine.length} with version $runId', + ); if (mine.length >= 3) break; // handled+uncaught are error issues, the crashes are issues too } on Object catch (e) { say('backend read: $e'); @@ -456,12 +606,23 @@ class _Job { final list = (recs is Map ? recs['objects'] : recs) as List? ?? []; for (final rec in list.take(3)) { final rid = (rec as Map)['_id']; - final text = await _text(client, '${base}applications/$appId/issues/$id/recordings/$rid/crash_report', serverToken); + final text = await _text( + client, + '${base}applications/$appId/issues/$id/recordings/$rid/crash_report', + serverToken, + ); reports.add(text); - File('$_workDir/backend-$id-$rid.txt').writeAsStringSync(redact(text, _secrets)); + File('$_workDir/backend-$id-$rid.txt') + .writeAsStringSync(redact(text, _secrets)); final raw = rawFrameLines(text); - say(' recording $rid: ${text.split('\n').length} lines, ${raw.length} raw frame line(s)'); - for (final l in text.split('\n').where((l) => _expectedDart.any(l.contains)).take(6)) { + say( + ' recording $rid: ${text.split('\n').length} lines, ${raw.length} raw frame line(s)', + ); + for (final l + in text + .split('\n') + .where((l) => _expectedDart.any(l.contains)) + .take(6)) { say(' $l'); } } @@ -478,7 +639,9 @@ class _Job { say('NOT SYMBOLICATED (or not found): ${problems.join('; ')}'); return 1; } - say('VERIFIED: the backend shows the readable names ${_expectedDart.join(', ')} and the native side'); + say( + 'VERIFIED: the backend shows the readable names ${_expectedDart.join(', ')} and the native side', + ); return 0; } @@ -487,7 +650,8 @@ class _Job { req.headers.set('x-auth-servertoken', serverToken); final res = await req.close(); final body = await res.transform(utf8.decoder).join(); - if (res.statusCode != 200) throw StateError('GET crash_report -> ${res.statusCode}'); + if (res.statusCode != 200) + throw StateError('GET crash_report -> ${res.statusCode}'); return body; } } diff --git a/test/device_harness_test.dart b/test/device_harness_test.dart index 2fd013d..0641fb4 100644 --- a/test/device_harness_test.dart +++ b/test/device_harness_test.dart @@ -1520,14 +1520,17 @@ Runner[1:2] (Flutter) flutter: VERIFY|{"kind":"handler","phase":"before","type": expect(r.split('').length, 3); }); - test('events of another run are dropped; a truncated line does not throw', () { - const console = - 'noise\nE2E|{"kind":"start","run":"9.1.1","phase":0}\n' - 'E2E|{"kind":"start","run":"OLD","phase":0}\nE2E|{"kind":"sta'; - final e = e2eEvents(console, '9.1.1'); - expect(e, hasLength(1)); - expect(e.single['phase'], 0); - }); + test( + 'events of another run are dropped; a truncated line does not throw', + () { + const console = + 'noise\nE2E|{"kind":"start","run":"9.1.1","phase":0}\n' + 'E2E|{"kind":"start","run":"OLD","phase":0}\nE2E|{"kind":"sta'; + final e = e2eEvents(console, '9.1.1'); + expect(e, hasLength(1)); + expect(e.single['phase'], 0); + }, + ); test('symbols.py exiting 0 after a refused POST is NOT an upload', () { // the pinned script returns None from a non-2xx POST and exits 0 @@ -1556,45 +1559,48 @@ Runner[1:2] (Flutter) flutter: VERIFY|{"kind":"handler","phase":"before","type": ); }); - test('the device run needs all four phases, launched, release, two crashes', () { - List> good() => [ - for (var p = 0; p < 4; p++) ...[ - {'kind': 'start', 'phase': p, 'mode': 'release', 'os': 'ios'}, - {'kind': 'launch', 'result': 'launched'}, - if (p == 0) {'kind': 'reported'}, - if (p == 1 || p == 2) {'kind': 'crashing'}, - ], - ]; - expect(phaseProblems(good(), os: 'ios', release: true), isEmpty); - expect( - phaseProblems(good().sublist(4), os: 'ios', release: true), - isNotEmpty, - ); - expect( - phaseProblems( - good() - .map((e) => e['kind'] == 'start' ? {...e, 'mode': 'debug'} : e) - .toList(), - os: 'ios', - release: true, - ), - anyElement(contains('release')), - ); - expect( - phaseProblems( - good() - .map( - (e) => e['kind'] == 'launch' - ? {...e, 'result': 'already-running'} - : e, - ) - .toList(), - os: 'ios', - release: true, - ), - isNotEmpty, - ); - }); + test( + 'the device run needs all four phases, launched, release, two crashes', + () { + List> good() => [ + for (var p = 0; p < 4; p++) ...[ + {'kind': 'start', 'phase': p, 'mode': 'release', 'os': 'ios'}, + {'kind': 'launch', 'result': 'launched'}, + if (p == 0) {'kind': 'reported'}, + if (p == 1 || p == 2) {'kind': 'crashing'}, + ], + ]; + expect(phaseProblems(good(), os: 'ios', release: true), isEmpty); + expect( + phaseProblems(good().sublist(4), os: 'ios', release: true), + isNotEmpty, + ); + expect( + phaseProblems( + good() + .map((e) => e['kind'] == 'start' ? {...e, 'mode': 'debug'} : e) + .toList(), + os: 'ios', + release: true, + ), + anyElement(contains('release')), + ); + expect( + phaseProblems( + good() + .map( + (e) => e['kind'] == 'launch' + ? {...e, 'result': 'already-running'} + : e, + ) + .toList(), + os: 'ios', + release: true, + ), + isNotEmpty, + ); + }, + ); test('run ids are unique per minute and valid as an iOS short version', () { final a = runIdFor(DateTime(2026, 11, 23, 14, 5)); From 65b215979244ef805d6264f7d3cb57db0d1bc58c Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 20:44:04 +0500 Subject: [PATCH 03/14] Braces in the e2e files (analyzer info the formatter exposed) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxNbNUdWru1zs68bYV8 Change-Id: I7620cb5ac1cec7bb4e190ddc04c2fbf486e60139 --- scripts/device/core/e2e.dart | 9 +++++--- scripts/device/e2e_symbolication.dart | 30 ++++++++++++++++++--------- 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/scripts/device/core/e2e.dart b/scripts/device/core/e2e.dart index 461d678..f52f9be 100644 --- a/scripts/device/core/e2e.dart +++ b/scripts/device/core/e2e.dart @@ -83,8 +83,9 @@ List phaseProblems( ); } for (final s in starts) { - if (s['os'] != os) + if (s['os'] != os) { problems.add('a start event says os ${s['os']}, expected $os'); + } if (release && s['mode'] != 'release') { problems.add('a start event says mode ${s['mode']}, expected release'); } @@ -101,8 +102,9 @@ List phaseProblems( ); } final crashes = events.where((e) => e['kind'] == 'crashing').length; - if (crashes != 2) + if (crashes != 2) { problems.add('the app announced $crashes crashes, expected 2'); + } if (!events.any((e) => e['kind'] == 'reported')) { problems.add('phase 0 never reported its Dart errors'); } @@ -148,8 +150,9 @@ List readbackProblems( } final all = reports.join('\n'); for (final n in [...expectedDartNames, ...expectedNativeNames]) { - if (!all.contains(n)) + if (!all.contains(n)) { problems.add('"$n" is in none of the ${reports.length} report(s)'); + } } return problems; } diff --git a/scripts/device/e2e_symbolication.dart b/scripts/device/e2e_symbolication.dart index bcbb5b7..86e2561 100644 --- a/scripts/device/e2e_symbolication.dart +++ b/scripts/device/e2e_symbolication.dart @@ -222,10 +222,11 @@ class _Job { ); File('$_workDir/build.log') .writeAsStringSync(redact('${b.stdout}\n${b.stderr}', _secrets)); - if (!b.ok) + if (!b.ok) { invalid( 'flutter build failed (see $_workDir/build.log): ${redact(b.stderr, _secrets)}', ); + } if (!ios) { final up = RegExp( r'^.*(?:[Bb]ugsee).*(?:upload|symbol).*$', @@ -246,10 +247,11 @@ class _Job { .whereType() .where((f) => f.path.endsWith('.symbols')) .toList(); - if (files.isEmpty) + if (files.isEmpty) { invalid( 'no .symbols file in $symbolsDir: --split-debug-info did not write any', ); + } for (final f in files) { final fmt = symbolsFormat(f.openSync().readSync(8)); final want = ios ? 'macho' : 'elf'; @@ -284,8 +286,9 @@ class _Job { final dl = await sh(['curl', '-fsSL', _symbolsPy, '-o', py]); if (!dl.ok) invalid('could not fetch symbols.py: ${dl.text}'); final sha = (await sh(['shasum', '-a', '256', py])).text.split(' ').first; - if (sha != _symbolsPySha) + if (sha != _symbolsPySha) { invalid('symbols.py sha256 is $sha, pinned $_symbolsPySha'); + } final venv = Platform.environment['E2E_PYTHON'] ?? 'python3'; say( 'uploading the Dart symbols with the pinned symbols.py (-t -d -v $runId, default endpoint)', @@ -305,8 +308,9 @@ class _Job { final out = redact('${r.stdout}\n${r.stderr}', _secrets); say(out.trim()); final problems = symbolsUploadProblems(out, r.code); - if (problems.isNotEmpty) + if (problems.isNotEmpty) { invalid('the Dart symbols upload: ${problems.join('; ')}'); + } say('Dart symbols uploaded (POST and PUT both 2xx)'); if (ios) { @@ -319,10 +323,11 @@ class _Job { .map((d) => d.path) .toList(); say('dSYMs of the build: $dsyms'); - if (dsyms.isEmpty) + if (dsyms.isEmpty) { invalid( 'no .dSYM was produced by the release build: the native iOS frames cannot be symbolicated', ); + } final dir = '$_workDir/dsyms'; Directory(dir).createSync(recursive: true); for (final d in dsyms) { @@ -466,8 +471,9 @@ class _Job { Duration timeout = const Duration(minutes: 2), }) => sh([adb, '-s', device, ...args], timeout: timeout); final state = (await a(['get-state'])).text; - if (state != 'device') + if (state != 'device') { invalid('$device is "$state" over adb, not "device"'); + } final apk = '$example/build/app/outputs/flutter-apk/app-release.apk'; await a(['uninstall', _androidPackage]); final inst = await a([ @@ -475,8 +481,9 @@ class _Job { '-r', apk, ], timeout: const Duration(minutes: 5)); - if (!inst.ok || !inst.stdout.contains('Success')) + if (!inst.ok || !inst.stdout.contains('Success')) { invalid('install failed: ${inst.text}'); + } say('installed $_androidPackage build $runId'); final all = StringBuffer(); try { @@ -507,10 +514,11 @@ class _Job { await delay(2); } all.writeln(redact(log, _secrets)); - if (!seen) + if (!seen) { invalid( 'phase $phase never reached ${wantsExit ? 'its crash' : 'its end'}', ); + } if (wantsExit) { final gone = await until( () async => @@ -520,10 +528,11 @@ class _Job { timeout: const Duration(seconds: 90), every: const Duration(seconds: 2), ); - if (gone != true) + if (gone != true) { invalid( 'phase $phase announced a crash and the process is still alive after 90 s', ); + } say('phase $phase: the process ended'); } } @@ -650,8 +659,9 @@ class _Job { req.headers.set('x-auth-servertoken', serverToken); final res = await req.close(); final body = await res.transform(utf8.decoder).join(); - if (res.statusCode != 200) + if (res.statusCode != 200) { throw StateError('GET crash_report -> ${res.statusCode}'); + } return body; } } From 8d6e60b30e12b7066dcfc70144b00ad8a89e2deb Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 10:02:30 +0500 Subject: [PATCH 04/14] Record the e2e symbolication read-back: Android and iOS native OK, iOS Dart exceptions raw (backend collision) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxNbNUdWru1zs68bYV8 Change-Id: Ief172dc67b2440421f2b5d3a3e75a660bfd5a6a0 --- CHANGELOG.md | 5 +++-- PLAN.md | 9 ++++----- doc/verification.md | 34 +++++++++++++++++++++------------- 3 files changed, 28 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ac7590..b8faa3b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,8 +5,9 @@ should stay on 9.x: there is no compatibility layer (the decision is open), see ### Known gaps -* Symbolication was exercised end to end up to the upload (Dart symbols and iOS dSYMs accepted by apidev, obfuscated release builds crashed on an iPhone XS and an - Android phone) but the backend's symbolicated frames were not read back, and the production endpoint was not used (`doc/verification.md` scenario 11). +* Symbolication was exercised end to end on apidev (obfuscated release builds on an iPhone XS and an Android phone): Android, including Dart 3.14 stacks, and iOS native + crashes are symbolicated; **iOS Dart exceptions stayed raw** because of a backend symbol-lookup collision (fixes in review: bugsee-appserver#280, bugsee-background-worker#182). + The production endpoint was not used (`doc/verification.md` scenario 11). ### Features diff --git a/PLAN.md b/PLAN.md index 8e61baf..e7c95ae 100644 --- a/PLAN.md +++ b/PLAN.md @@ -87,11 +87,10 @@ Other gaps, none with an issue: reports for native signals, Objective-C exceptions and a Swift trap; a `raise(7)`, which is SIGEMT on Darwin and not SIGBUS (10), left no report; SIGBUS itself is not yet measured on a device). The workbook's iOS recovery claims (off-main, capped, a late completion re-persists) were not measured. * The Gradle plugin 4.0.6 failure arm was not run; `optimizeExtensionsLoading=false` and the feedback safety-net path were not run. -* **End-to-end symbolication (2026-11-23, `doc/verification.md` scenario 11): symbols uploaded, backend result NOT read.** The two app tokens available exist on - `apidev.bugsee.com` only (production answers `ApplicationNotFoundError`), so the runs used apidev: Dart symbols (`symbols.py`) and iOS dSYMs (`bugsee-cli`) were accepted, - an obfuscated release build crashed on an iPhone XS and the Android phone, reports were built and (by the device log) handed to the SDK; but reading the issues back - needs an organisation server token or a dashboard login that the run did not have, so nothing says the backend symbolicated Dart 3.14 or iOS stacks (the header-stripping - risk below is still open), and Android native symbols through the Gradle plugin are unconfirmed. Next step: look at apidev versions `9.1123.2012` (iOS) and `9.1123.2016` (Android). +* **End-to-end symbolication (2026-11-23/24, `doc/verification.md` scenario 11):** read back from apidev. Android (obfuscated release, R8): everything symbolicated, including the + Dart 3.14 stack. iOS: native crashes symbolicated; **Dart exceptions stay raw** because two ready records share the build-id UUID and the backend's batch lookup returned the + App dSYM (not the Dart `.symbols`): backend bug, fixes in review (bugsee-appserver#280, bugsee-background-worker#182), nothing to change in the wrapper. The tokens exist on + apidev only (production answers `ApplicationNotFoundError`), so the runs used apidev. Next step: re-run the iOS scenario once both fixes are deployed. * A production-backend run: not done (no production tokens); the harness otherwise uses a loopback stand-in; server-side symbolication was run offline with the backend's `dart_symbolize` (2026-11-18, `doc/exceptions.md`): it decodes the Android arm64 stack of a Dart 3.14 build only because the worker strips the stack's header (with the header it crashes, as Flutter 3.50's `flutter symbolize` does: `_kDartSnapshotText`, no `_kDartIsolateSnapshotInstructions`); diff --git a/doc/verification.md b/doc/verification.md index d0578ff..cef14ae 100644 --- a/doc/verification.md +++ b/doc/verification.md @@ -468,15 +468,24 @@ tokens. The two probe requests of that discovery left one empty `uploading` symb | Dart symbols (`symbols.py`, `-t -v -d -e https://apidev.bugsee.com/v2/`) | `app.ios-arm64.symbols` (Mach-O, 1.9 MB): POST `.../symbols` 200, PUT of the zip to the presigned S3 URL 200 (`symbols.py` exit 0) | three files (`android-arm64`, `-arm`, `-x64`, ELF): POST 200, PUT 200 (4.2 MB zip), exit 0 | | native symbols | `bugsee-cli debug-files upload --type dsym` (0.8.0, `BUGSEE_APP_TOKEN` in the environment): exit 0; `App`, `Runner`, `Flutter` dSYMs uploaded, `Bugsee` already on the server | Bugsee Gradle plugin 4.1.1 (`ndk { enabled }`, token and `plugin.endpoint` in the Gradle-root `bugsee.properties`, removed after the build): **not confirmed**, the plugin prints nothing at the default log level | | device run | 4 launches, all `launched`; launch 2 died of signal 11, launch 3 ended after the Objective-C exception (devicectl exit 1); the app's events and the SDK's report-handler lines show reports built in launches 1 to 3 | the same sequence; both crash launches ended (the process was gone within 90 s) | -| the backend's answer | **not read** | **not read** | - -**What was NOT verified, and why: the backend's symbolicated frames, on both platforms.** Reading an issue back needs the public API's organisation -**server token** (`x-auth-servertoken`, `appserver` `public_api/middleware/auth.js`; routes `GET /v2/partner/applications/:app_id/issues[/:id/recordings/:rid/crash_report]`) -or the dashboard / MCP login; an app token only uploads (the symbols endpoint accepts it) and cannot list issues. None was available to the run, so the script ended -`UNVERIFIED` (exit 3) and nothing here says the backend symbolicated or failed to. The readback half of the script is written from the appserver source and has -**never been run** against a backend; its first run may need the response shapes adjusted. To finish the check: open the issues of versions `9.1123.2012` (iOS) and `9.1123.2016` (Android) on apidev and look at the frames -(or set `BUGSEE_SERVER_TOKEN`, the apidev organisation's, and the application ids and run again: a new run id, because the script does not read an old build). Expected `e2eHandledSite`, -`e2eUnhandledSite`, `e2eUncaughtThrower` (file `e2e_main.dart`), and for the native crashes `AppDelegate` (iOS, `objc-main`) and `MainActivity` (Android, `java-main`). +| the backend's answer (read 2026-11-24, see below) | Dart native crash and Swift crash symbolicated; **Dart exceptions stay raw (backend bug, fix in review)** | everything symbolicated | + +**Backend read-back (2026-11-24, via the Bugsee staging MCP, apidev; apps `AFTA` Android flutter and `IFTA` iOS flutter, issues of the two versions above).** + +* **Android (9.1123.2016): everything symbolicated**, all five issues `ready`: the unhandled Dart crash shows `Bugsee.logUnhandledException (.../lib/src/bugsee.dart:638:30)`, + `e2eUnhandledSite (.../e2e_main.dart:52:16)`, `_phases (.../e2e_main.dart:114:13)`; the handled errors show `e2eHandledSite`, `e2eUncaughtThrower`; the Java crash resolves + to `MainActivity.java:28` (the R8 `mapping.txt` record exists, so the Gradle plugin upload is confirmed); the ffi segfault to `crash (crash_lab.dart:54)`. A Dart 3.14 stack + with the header stripped by the worker decodes. +* **iOS (9.1123.2012): native crashes symbolicated, Dart exceptions not.** The ffi segfault shows the full chain from `crash (crash_lab.dart:54)` through the Flutter engine + to UIKit and the Swift crash `AppDelegate.swift:32`. The Dart exceptions (`IFTA-5` handled, `IFTA-6` unhandled) are `ready` but still raw + (`#00 abs ... _kDartSnapshotText+0x18a287`). +* **Root cause (reproduced with the worker's own code against staging data):** two ready symbol records share the build-id UUID `44db9327...`, both format `dsym`: the + `App.framework` dSYM and `app.ios-arm64.symbols`. The appserver batch lookup (`formatBatch`) keeps one per format, returned the App dSYM, and `dart_symbolize` on a file without + Dart information exits 0 echoing its input, so the issue was marked `ready` with raw frames. With the `.symbols` record the same crash document symbolicates. Nothing in the + wrapper or the upload is at fault (both records are the correct files). Fixes in review: bugsee-appserver#280 (batch returns every record as `candidates`) and + bugsee-background-worker#182 (tries each, accepts the first that decodes, warns when none does). Until both are deployed, an iOS Dart exception stays raw; not re-measured after the fixes. +* Not verified: the production backend (the tokens exist on apidev only); Flutter 3.41; whether iOS needs the App dSYM at all (it carries no Dart code: uploading only the + `.symbols` file would also avoid the collision, untested). Findings of the build of this check, each a fact about the toolchain and not about the wrapper: @@ -531,10 +540,9 @@ For follow-up (SDK or environment, not fixed here): * A handler that overruns the SDK's deadline, and a hot restart while a delivery is in flight. * The Gradle plugin 4.0.6 broken arm (only the fixed arm was run; the detection is unit-tested). * x86_64 and armeabi-v7a ABIs, a second display, rotation, split screen, a density change *during* a report. -* Server-side processing: the mock API stands in for the backend in scenarios 1 to 10. Scenario 11 (2026-11-23) uploaded the Dart symbols (both platforms) and the iOS - dSYMs to apidev (accepted, 2xx) and ran the crashes on the devices, but the backend's symbolicated frames were NOT read (no server token): whether apidev symbolicated - anything is unknown. Its `dart_symbolize` was run offline on the Android arm64 Dart 3.14 artifacts only (see scenario 4); a real iOS stack was not decoded. Android native - symbols through the Gradle plugin: upload not confirmed. The default (production) endpoint was not used: the given tokens exist on apidev only. +* Server-side processing: the mock API stands in for the backend in scenarios 1 to 10. Scenario 11 (2026-11-23/24) ran against apidev and read the result back: + Android (including Dart 3.14 stacks) and iOS native crashes are symbolicated, iOS Dart exceptions stayed raw because of the backend collision described there (fixes in review). + The default (production) endpoint was not used: the given tokens exist on apidev only. * Dart `Isolate` errors and `reportAsCrash: true` in a release build. ## Extending it From b863706e27531fc887d2e91aca8b46f89c284f13 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 10:42:07 +0500 Subject: [PATCH 05/14] e2e app: wait for a deferred iOS launch; keep e2e_main.dart out of the published archive A deferred launch is not a failure: the phase runs once waitUntilLaunched confirms capture. .pubignore and check_pub_archive.sh now exclude the entry point like verify_main.dart. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxNbNUdWru1zs68bYV8 Change-Id: Ie62bb9b056d1364cb2b7940dca95f3f29d288e51 --- .pubignore | 1 + example/README.md | 2 +- example/lib/e2e_main.dart | 16 +++++++++++++--- scripts/check_pub_archive.sh | 2 +- 4 files changed, 16 insertions(+), 5 deletions(-) diff --git a/.pubignore b/.pubignore index 2c2bc17..cd176f7 100644 --- a/.pubignore +++ b/.pubignore @@ -46,4 +46,5 @@ migrate_working_dir/ # The device verification harness (doc/verification.md) and the app it drives: dev tooling, never published. /scripts/device/ /example/lib/verify_main.dart +/example/lib/e2e_main.dart /test/device_harness_test.dart diff --git a/example/README.md b/example/README.md index c5d9b09..89933c9 100644 --- a/example/README.md +++ b/example/README.md @@ -39,4 +39,4 @@ SDK has launched). ## The verification app `lib/verify_main.dart` is a second entry point driven by the device verification harness (`scripts/device/`, results in -[`doc/verification.md`](../doc/verification.md)). It is not part of the published package. +[`doc/verification.md`](../doc/verification.md)). It is not part of the published package (nor is `lib/e2e_main.dart`, the entry point of the end-to-end symbolication run). diff --git a/example/lib/e2e_main.dart b/example/lib/e2e_main.dart index 373c2b7..5df5eee 100644 --- a/example/lib/e2e_main.dart +++ b/example/lib/e2e_main.dart @@ -94,9 +94,19 @@ Future _phases() async { token, options: BugseeOptions(endpoint: _endpoint.isEmpty ? null : _endpoint), ); - _emit('launch', {'result': launch.name}); - if (launch.name != 'launched') { - _emit('invalid', {'why': 'launch answered ${launch.name}'}); + // iOS answers `deferred` while the app is not active yet; the SDK then starts by itself. Capture has + // started only once the status says so, so the phase runs after that and the event carries the outcome. + var result = launch.name; + if (launch == LaunchResult.deferred) { + result = await Bugsee.waitUntilLaunched() + ? 'launched' + : 'deferred-never-launched'; + } + _emit('launch', {'result': result, 'answer': launch.name}); + if (result != 'launched') { + _emit('invalid', { + 'why': 'launch answered ${launch.name}, outcome $result', + }); return; } await Bugsee.setAttribute('e2e_run', _run); diff --git a/scripts/check_pub_archive.sh b/scripts/check_pub_archive.sh index cb483ca..c211cb0 100755 --- a/scripts/check_pub_archive.sh +++ b/scripts/check_pub_archive.sh @@ -8,7 +8,7 @@ # scripts/check_pub_archive.sh ARCHIVE... set -euo pipefail -forbidden='^(\./)?(packages/|pigeons/|ios/wrapper_tests/|ios/feedback_wrapper_tests/|scripts/device/|test/device_harness_test\.dart|example/lib/verify_main\.dart|\.git/|\.dart_tool/|\.idea/|migrate_working_dir/|build/|android/build/)|(^|/)(\.build|\.gradle|\.swiftpm)/|(^|/)(local\.properties|pubspec\.lock|\.DS_Store)$|\.(iml|ipr|iws|log|class|swp|pyc)$' +forbidden='^(\./)?(packages/|pigeons/|ios/wrapper_tests/|ios/feedback_wrapper_tests/|scripts/device/|test/device_harness_test\.dart|example/lib/verify_main\.dart|example/lib/e2e_main\.dart|\.git/|\.dart_tool/|\.idea/|migrate_working_dir/|build/|android/build/)|(^|/)(\.build|\.gradle|\.swiftpm)/|(^|/)(local\.properties|pubspec\.lock|\.DS_Store)$|\.(iml|ipr|iws|log|class|swp|pyc)$' status=0 for archive in "$@"; do From 0e6ef1672c3fada545aad0e2480ae0de6295497c Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 10:42:07 +0500 Subject: [PATCH 06/14] e2e run: verdict needs frames, no raw frame, native evidence; cleanup on every path; safe properties file readbackProblems fails on any raw frame, needs names in symbolicated frames (not mentions) and a native frame per crash in a report of its own; the read-back polls on content with deadlines. invalid() throws so finally blocks run; signals run the same cleanup; bugsee.properties is saved and restored; the build is staged per run; obfuscation guard on Android too; the lock script is configurable; build ids are per second; iOS crash exit signals and Android pid evidence are checked; symbols_logged.py no longer prints the original transport error. Tests added for each. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxNbNUdWru1zs68bYV8 Change-Id: I8097ae9b307ac5424a6e21ebd2590e192413581f --- scripts/device/core/e2e.dart | 141 +++++- scripts/device/e2e_symbolication.dart | 644 +++++++++++++++++++------- scripts/device/symbols_logged.py | 15 +- test/device_harness_test.dart | 197 +++++++- 4 files changed, 783 insertions(+), 214 deletions(-) diff --git a/scripts/device/core/e2e.dart b/scripts/device/core/e2e.dart index f52f9be..4bfb233 100644 --- a/scripts/device/core/e2e.dart +++ b/scripts/device/core/e2e.dart @@ -3,6 +3,8 @@ // each failing on the input it exists to refuse. import 'dart:convert'; +import 'log_parsers.dart'; + /// Replaces every secret in [text] with a marker. Everything the run prints or saves goes through this. String redact(String text, Iterable secrets) { var out = text; @@ -111,11 +113,13 @@ List phaseProblems( return problems; } -/// The unique build string of a run: `9.MMDD.HHMM` (three integers, valid as an iOS short version and an -/// Android versionName), so two runs in different minutes never share a build, and a backend row is told apart. +/// The unique build string of a run: `9.YYMMDD.HHMMSS` (three integers, valid as an iOS short version and an +/// Android versionName). Two runs in different seconds, days or years never share a build, so a backend row is +/// told apart by its version; the runner also refuses a fresh run whose work directory (named by this id) exists. String runIdFor(DateTime now) { String two(int n) => n.toString().padLeft(2, '0'); - return '9.${two(now.month)}${two(now.day)}.${two(now.hour)}${two(now.minute)}'; + return '9.${two(now.year % 100)}${two(now.month)}${two(now.day)}.' + '${two(now.hour)}${two(now.minute)}${two(now.second)}'; } /// A `.symbols` file's format by magic bytes: `elf` (Android), `macho` (iOS), or null. @@ -133,14 +137,30 @@ String? symbolsFormat(List head) { return null; } +/// A line of a rendered report that is a symbolicated FRAME: it carries a source position (`file.ext:line`). +/// A name in a summary, a log line or a message has none, so it never counts as evidence. +final _sourceFrame = RegExp(r'\.(dart|java|kt|swift|mm?|cc?|cpp):\d+'); + +bool _hasFrameWith(String report, String name) { + for (final l in const LineSplitter().convert(report)) { + if (l.contains(name) && _sourceFrame.hasMatch(l)) return true; + } + return false; +} + /// What the backend's rendering of the run's reports must hold for the run to count as symbolicated. /// [reports] are the texts of the crash reports found for the run's build. Returns the problems: -/// each expected readable name must appear, and the readable names must not be the only thing there -/// (an obfuscated build whose frames are still `_kDartSnapshotText+0x...` has failed, whatever else matches). +/// * no report at all: nothing was verified; +/// * ANY raw frame line in ANY report (`_kDartSnapshotText+0x...`, a frame left as an address) fails the run, +/// whatever else matches; +/// * each expected Dart name must be in a symbolicated frame (a line with a source position), not just mentioned; +/// * each expected native frame ([expectedNativeFrames], a name or a source file such as `crash_lab.dart`) likewise, +/// and each in a report of its OWN (the native-signal report and the platform-language report are different +/// crashes; one report cannot stand for both). List readbackProblems( List reports, { required List expectedDartNames, - required List expectedNativeNames, + required List expectedNativeFrames, }) { final problems = []; if (reports.isEmpty) { @@ -148,10 +168,52 @@ List readbackProblems( 'the backend returned no report for this build: nothing was verified', ]; } - final all = reports.join('\n'); - for (final n in [...expectedDartNames, ...expectedNativeNames]) { - if (!all.contains(n)) { - problems.add('"$n" is in none of the ${reports.length} report(s)'); + for (var i = 0; i < reports.length; i++) { + final raw = rawFrameLines(reports[i]); + if (raw.isNotEmpty) { + problems.add( + 'report ${i + 1} has ${raw.length} raw frame line(s), e.g. "${raw.first}"', + ); + } + } + for (final n in expectedDartNames) { + if (!reports.any((r) => _hasFrameWith(r, n))) { + problems.add( + '"$n" is in no symbolicated frame of the ${reports.length} report(s)', + ); + } + } + // each native frame needs a report of its own: a small backtracking assignment + final candidates = [ + for (final n in expectedNativeFrames) + [ + for (var i = 0; i < reports.length; i++) + if (_hasFrameWith(reports[i], n)) i, + ], + ]; + for (var k = 0; k < candidates.length; k++) { + if (candidates[k].isEmpty) { + problems.add( + 'native frame "${expectedNativeFrames[k]}" is in no symbolicated frame of the ${reports.length} report(s)', + ); + } + } + if (candidates.every((c) => c.isNotEmpty)) { + bool assign(int k, Set used) { + if (k == candidates.length) return true; + for (final i in candidates[k]) { + if (used.add(i)) { + if (assign(k + 1, used)) return true; + used.remove(i); + } + } + return false; + } + + if (!assign(0, {})) { + problems.add( + 'the expected native frames ${expectedNativeFrames.join(', ')} are not in distinct reports (one crash per frame is expected)', + ); } } return problems; @@ -165,3 +227,62 @@ List rawFrameLines(String report) => [ ).hasMatch(l)) l.trim(), ]; + +/// What is wrong with how an iOS crash launch ended. [crash] is the app's own `crashing` kind (`ffi-segv`, or +/// `objc-main`), [console] the drained devicectl output, [exitCode] devicectl's. A `crashing` line alone proves +/// nothing: the launch could have been ended by anything else (a SIGTERM from the previous console child). +/// `ffi-segv` must have ended with `App terminated due to signal 11`. `objc-main` is an uncaught Objective-C +/// exception, which aborts (signal 6); devicectl may report no signal for it, then a non-zero exit is accepted +/// (measured once: exit 1), but any OTHER signal (15 above all) is a failure. +List iosCrashExitProblems(String crash, String console, int exitCode) { + final signal = parseTerminatedSignal(console); + switch (crash) { + case 'ffi-segv': + return signal == 11 + ? const [] + : ['ffi-segv ended with ${signal == null ? 'no signal line' : 'signal $signal'}, expected signal 11']; + case 'objc-main': + if (signal == 6) return const []; + if (signal == null && exitCode != 0) return const []; + return [ + 'objc-main ended with ${signal == null ? 'no signal line and devicectl exit 0' : 'signal $signal'}, expected signal 6 (or a non-zero exit without a signal)', + ]; + } + return ['unknown crash kind $crash']; +} + +/// Whether the app process [pid] is gone, from one `adb shell pidof ` answer; `null` when the answer +/// proves nothing (an adb failure: a disconnect, `device offline`, anything on stderr). Only a successful `pidof` +/// that does not list [pid], or its documented "no process" answer (exit 1, nothing at all printed), is "gone". +bool? androidPidGone({ + required int code, + required String stdout, + required String stderr, + required int pid, +}) { + if (code == 0) { + return !stdout.trim().split(RegExp(r'\s+')).contains('$pid'); + } + if (code == 1 && stdout.trim().isEmpty && stderr.trim().isEmpty) return true; + return null; +} + +/// What is wrong with the evidence that process [pid] died of the crash [crash] (`ffi-segv` or `java-main`), from +/// a full `logcat -d`: the kernel/debuggerd line `Fatal signal 11` for THAT pid, or the Java `FATAL EXCEPTION` +/// naming `verify-java-main` for it. A process that merely vanished is not a crash. +List androidCrashProblems(String crash, String logcat, int pid) { + switch (crash) { + case 'ffi-segv': + final f = parseFatalSignal(logcat, pid); + return f?.number == 11 + ? const [] + : [ + 'no "Fatal signal 11" for pid $pid in logcat (${f == null ? 'none' : 'signal ${f.number}'})', + ]; + case 'java-main': + return parseFatalException(logcat, pid, 'verify-java-main') + ? const [] + : ['no FATAL EXCEPTION naming verify-java-main for pid $pid in logcat']; + } + return ['unknown crash kind $crash']; +} diff --git a/scripts/device/e2e_symbolication.dart b/scripts/device/e2e_symbolication.dart index 86e2561..321d175 100644 --- a/scripts/device/e2e_symbolication.dart +++ b/scripts/device/e2e_symbolication.dart @@ -4,6 +4,10 @@ // BUGSEE_IOS_TOKEN=... dart scripts/device/e2e_symbolication.dart ios --udid // BUGSEE_ANDROID_TOKEN=... dart scripts/device/e2e_symbolication.dart android --serial // +// Device lock: optional. `--devlock