diff --git a/doc/design-rules.md b/doc/design-rules.md index 20d57f5..4fb3af8 100644 --- a/doc/design-rules.md +++ b/doc/design-rules.md @@ -20,7 +20,7 @@ Report handlers (workbook Part 7; `ReportHandlerPipeline.java`, `BGSFlutterRepor ## Managed view hierarchy (`vh`) -Managed view hierarchy (`vh`, workbook Part 6; Dart `lib/src/view_hierarchy`, `ViewHierarchyStore.java` / `BGSFlutterViewHierarchyStore`; design, payload, privacy, limits in `doc/view-hierarchy.md`): the SDK calls `requestData("vh")` on the MAIN thread on both platforms and times 500 ms from when the call returns (iOS cuts to 50 ms after three timeouts), so the wrapper answers SYNCHRONOUSLY from a native cache Dart keeps current; NEVER make that answer wait for Dart or post it (a wait is a deadlock; a late reply misses the report when an Android snapshot is made on the main thread, which bugsee-android PR #120, in 7.4.2, does not cover; iOS does not ask the wrapper at all for a snapshot made on the main thread, and waits up to 500 + 250 ms off it). The cache stores a JSON TEMPLATE (text cut at the snapshot's age and at every node's box) plus the boxes in the view's logical pixels; the stores convert boxes per answer with `SecureRectangleStore.Mapper` / `BGSFlutterPlacementMapper`, the ONE place the ratio, unit (Android physical pixels, iOS points), view scale and position are combined (the secure rectangles use the same object; a drift test keeps the arithmetic out of every other file), and answer `null` when anything is unplaceable, off screen, mis-scaled, non-finite, malformed or stuck. Never parse the JSON natively. PRIVACY IS OURS (the SDK stores the string unread): the builder (`hierarchy_builder.dart`) takes only `runtimeType` names and structure from the element/render tree: never text, controllers, semantics, `Key`s (a `ValueKey` is arbitrary app data; the spec's own example leaks one), tags, route names, `toString()` of a widget; a `BugseeSecureView` subtree is ONE node with a fixed name, its secure-rectangle box and `secure: true`, nothing below it; `id` is a counter; any error returns `null` and sends nothing. `test/view_hierarchy_drift_test.dart` allow-lists what may be read off a render object and bans the text channels by pattern: a new read must be reviewed for text. Publishing needs the SDK launched AND its `capture.view-hierarchy` option on AND the app in the foreground (`controller.dart`); the publisher builds only in a post-frame callback or a timer (never inside a frame), schedules no frames of its own, takes a walk only after 100 ms with no frame (the first snapshot, while native holds nothing, is taken at once; an endless animation gets one walk every 3 s, next to its frames), spaces builds by 20x their cost (min 300 ms, max 5 s), sends only changes, and caps the walk (12 ms, 2000 nodes, 256 KiB, 512 levels: cut and marked `truncated`, never partial JSON). A detached engine drops its snapshot (serves nothing). The age is native's (`options.age_ms`, computed per answer) because the SDK stamps the entry with the reply time; there is deliberately no maximum age (Flutter draws only on a frame). The SDK facts (type, 500 ms, 50 ms iOS backoff, the main-thread-only wait) are extracted from SDK source into `test/fixtures/data_requests.json` (`scripts/extract_data_requests.dart`; re-run when a pin moves). Public: `Bugsee.captureViewHierarchy()` (flushes, then asks the SDK). Limits: only the implicit view; a Flutter view off the screen origin is covered by JUnit/XCTest, not a device; iOS bundles are not verifiable on a simulator with a placeholder token (the device test reads the capture buffer). +Managed view hierarchy (`vh`, workbook Part 6; Dart `lib/src/view_hierarchy`, `ViewHierarchyStore.java` / `BGSFlutterViewHierarchyStore`; design, payload, privacy, limits in `doc/view-hierarchy.md`): the SDK calls `requestData("vh")` on the MAIN thread on both platforms and times 500 ms from when the call returns (iOS cuts to 50 ms after three timeouts), so the wrapper answers SYNCHRONOUSLY from a native cache Dart keeps current; NEVER make that answer wait for Dart or post it (a wait is a deadlock; a late reply misses the report when an Android snapshot is made on the main thread, which bugsee-android PR #120, in 7.4.2, does not cover; iOS does not ask the wrapper at all for a snapshot made on the main thread, and waits up to 500 + 250 ms off it). The cache stores a JSON TEMPLATE (text cut at the snapshot's age and at every node's box) plus the boxes in the view's logical pixels; the stores convert boxes per answer with `SecureRectangleStore.Mapper` / `BGSFlutterPlacementMapper`, the ONE place the ratio, unit (Android physical pixels, iOS points), view scale and position are combined (the secure rectangles use the same object; a drift test keeps the arithmetic out of every other file), and answer `null` when anything is unplaceable, off screen, mis-scaled, non-finite, malformed or stuck. Never parse the JSON natively. PRIVACY IS OURS (the SDK stores the string unread): the builder (`hierarchy_builder.dart`) takes only `runtimeType` names and structure from the element/render tree: never text, controllers, semantics, `Key`s (a `ValueKey` is arbitrary app data; the spec's own example leaks one), tags, route names, `toString()` of a widget; a `BugseeSecureView` subtree is ONE node with a fixed name, its secure-rectangle box and `secure: true`, nothing below it; `id` is a counter; any error returns `null` and sends nothing. `test/view_hierarchy_drift_test.dart` allow-lists what may be read off a render object and bans the text channels by pattern: a new read must be reviewed for text. Publishing needs the SDK launched AND its `capture.view-hierarchy` option on AND the app in the foreground (`controller.dart`); the publisher builds only in a post-frame callback or a timer (never inside a frame), schedules no frames of its own, takes a walk only after 100 ms with no frame (the first snapshot, while native holds nothing, is taken at once; an endless animation gets one walk every 3 s, next to its frames), spaces builds by 20x their cost (min 300 ms, max 5 s), sends only changes, and caps the walk (12 ms, or 35% of one frame at the display's refresh rate while a frame is due, 2000 nodes, 256 KiB, 512 levels: cut and marked `truncated`, never partial JSON). A detached engine drops its snapshot (serves nothing). The age is native's (`options.age_ms`, computed per answer) because the SDK stamps the entry with the reply time; there is deliberately no maximum age (Flutter draws only on a frame). The SDK facts (type, 500 ms, 50 ms iOS backoff, the main-thread-only wait) are extracted from SDK source into `test/fixtures/data_requests.json` (`scripts/extract_data_requests.dart`; re-run when a pin moves). Public: `Bugsee.captureViewHierarchy()` (flushes, then asks the SDK). Limits: only the implicit view; a Flutter view off the screen origin is covered by JUnit/XCTest, not a device; iOS bundles are not verifiable on a simulator with a placeholder token (the device test reads the capture buffer). ## Options and the manifests diff --git a/doc/view-hierarchy.md b/doc/view-hierarchy.md index c0e9770..29567e2 100644 --- a/doc/view-hierarchy.md +++ b/doc/view-hierarchy.md @@ -96,7 +96,7 @@ While active the publisher (`publisher.dart`): of a burst is not lost; * sends **only when the payload changed**; a failed send is retried with a doubling backoff (never given up, 30 s cap), and a clear that failed is retried until it lands; -* cuts the walk by a **12 ms budget**, **2000 nodes**, **256 KiB**, **512 element levels** (a provider of data, an `InheritedElement`, is not a level: a Material app has dozens): over a cap the tree is cut +* cuts the walk by a **12 ms budget** (the ceiling, used when no frame is due; while a frame is already due, that is an animation is running, the budget is **35% of one frame at the display's refresh rate**, at least 2 ms: 5.8 ms at 60 Hz, 2.9 ms at 120 Hz, so a walk fits the slack of the frame it is added to; an explicit `captureViewHierarchy` keeps the full 12 ms; a walk cut by the smaller budget is marked `truncated` like any other. **Consequence, chosen on purpose** (the UI thread comes first): a screen that never goes quiet (a spinner, a video, a marquee) is only walked next to its frames, so on a device where its walk takes longer than the smaller budget (an Android phone needs ~10 ms for a ~900-node list; a 60 Hz budget is 5.8 ms) every snapshot of it is cut, where the cut falls depends on the device's speed, and nothing completes it until the screen goes quiet. A screen that settles gets the full budget. `ViewHierarchyPublisher.frameShare` is the knob, if complete snapshots of such screens matter more than their frames), **2000 nodes**, **256 KiB**, **512 element levels** (a provider of data, an `InheritedElement`, is not a level: a Material app has dozens): over a cap the tree is cut and the cut nodes carry `"truncated": true` (and the root's `options.truncated`), the answer stays valid; a template over the byte cap is dropped, not trimmed. @@ -238,7 +238,7 @@ publishing is on) and asks the SDK for a pass, which the cache answers. A no-op hide an older one that is shown). * `--obfuscate` release builds: names are minified and flagged, not decoded. * A hot-restarted isolate that publishes nothing leaves the old isolate's snapshot until the engine detaches (debug only). -* The Dart walk is synchronous on the UI isolate and bounded by 12 ms / 2000 nodes, not preemptible: a huge tree is cut, not +* The Dart walk is synchronous on the UI isolate and bounded by 12 ms (35% of a frame while a frame is due) / 2000 nodes, not preemptible: a huge tree is cut, not skipped. ## Mutation checks and the mutants that were not killed diff --git a/lib/src/view_hierarchy/hierarchy_builder.dart b/lib/src/view_hierarchy/hierarchy_builder.dart index 12c5b6d..cbad705 100644 --- a/lib/src/view_hierarchy/hierarchy_builder.dart +++ b/lib/src/view_hierarchy/hierarchy_builder.dart @@ -66,8 +66,18 @@ class HierarchyLimits { final int maxBytes; /// How long the walk may run; past it the rest of the tree is cut. One walk is synchronous on - /// the UI isolate, so this bounds the jank it can cause. + /// the UI isolate, so this bounds the jank it can cause. This is the ceiling, for a walk with no + /// frame due; the publisher lowers it to a share of one frame while a frame is (see + /// `ViewHierarchyPublisher`). final Duration budget; + + /// These limits with another time [budget]. + HierarchyLimits withBudget(Duration budget) => HierarchyLimits( + maxNodes: maxNodes, + maxDepth: maxDepth, + maxBytes: maxBytes, + budget: budget, + ); } /// One snapshot of one Flutter view: a JSON template plus the numbers that fill it in. diff --git a/lib/src/view_hierarchy/publisher.dart b/lib/src/view_hierarchy/publisher.dart index d2f1bc0..3e70916 100644 --- a/lib/src/view_hierarchy/publisher.dart +++ b/lib/src/view_hierarchy/publisher.dart @@ -14,7 +14,10 @@ // * only a frame that happened can have changed anything, so no frame is ever scheduled except // the one that starts the publisher; with the app idle nothing runs; // * a snapshot identical to the one native holds is not sent; -// * a walk is cut by its own time budget and node/byte caps (see [HierarchyLimits]); +// * a walk is cut by its own time budget and node/byte caps (see [HierarchyLimits]); while a frame +// is already due (an animation is running) the budget is a share of one frame at the display's +// refresh rate ([frameShare], never over the limit's own budget), so it fits the slack of a +// 120 Hz frame as well as a 60 Hz one; with nothing due the full budget applies; // * a walk is only taken when the app has been quiet: no frame for [busyGap]. A walk straight // after a frame lands next to the following frame of a scroll, a fling, an animation or a // route transition, and delays it; after a quiet stretch it can only collide with an input @@ -23,6 +26,7 @@ // * nothing is built while the publisher is not active (not launched, option off, background). import 'dart:async'; import 'dart:math' as math; +import 'dart:ui' show PlatformDispatcher; import 'package:flutter/foundation.dart' show visibleForTesting; import 'package:flutter/scheduler.dart'; @@ -51,14 +55,42 @@ class ViewHierarchyPublisher { this.frameWait = const Duration(milliseconds: 400), this.busyGap = const Duration(milliseconds: 100), this.busyCap = const Duration(seconds: 3), + this.frameShare = 0.35, + this.minBudget = const Duration(milliseconds: 2), + Duration Function()? frameInterval, + bool Function()? framePending, Duration Function()? clock, ViewHierarchyBuilder? builder, }) : epoch = epoch ?? newIsolateEpoch(), + _frameInterval = frameInterval ?? _displayFrameInterval, + _framePending = framePending ?? _schedulerFramePending, _now = clock ?? _stopwatchClock(), _builder = builder ?? ((limits, now) => buildViewHierarchy(limits: limits, clock: now)); + /// One frame at the display's refresh rate (60 Hz when it is unknown). + static Duration _displayFrameInterval() { + try { + final views = PlatformDispatcher.instance.views; + final double hz = views.isEmpty ? 60 : views.first.display.refreshRate; + if (hz.isFinite && hz >= 24 && hz <= 480) { + return Duration(microseconds: (1e6 / hz).round()); + } + } catch (_) { + // Unknown display: assume 60 Hz. + } + return const Duration(microseconds: 16667); + } + + static bool _schedulerFramePending() { + try { + return SchedulerBinding.instance.hasScheduledFrame; + } catch (_) { + return false; + } + } + static Duration Function() _stopwatchClock() { final watch = Stopwatch()..start(); return () => watch.elapsed; @@ -94,6 +126,12 @@ class ViewHierarchyPublisher { /// The most a stretch of activity postpones a walk: after this the walk is taken anyway. final Duration busyCap; + + /// The share of one frame a walk may take while a frame is due, and the least it is given. + final double frameShare; + final Duration minBudget; + final Duration Function() _frameInterval; + final bool Function() _framePending; final Duration Function() _now; final ViewHierarchyBuilder _builder; @@ -159,7 +197,7 @@ class ViewHierarchyPublisher { await _awaitScheduledFrame(); if (!_active) return; _dirty = false; - await _buildAndSend(); + await _buildAndSend(explicit: true); } /// A change is on its way to the screen: wait for its frame (a new route needs two: it is built @@ -284,11 +322,21 @@ class ViewHierarchyPublisher { static const Duration _maxBackoff = Duration(seconds: 30); - Future _buildAndSend() async { + /// The limits for a walk taken now: the walk is cut at a share of one frame when a frame is + /// already due, because then the walk would be added to a frame on a tight budget. An explicit + /// capture keeps the full budget (the caller waits for it, nothing is drawn because of it). + HierarchyLimits _limitsNow({required bool explicit}) { + if (explicit || !_framePending()) return limits; + Duration share = _frameInterval() * frameShare; + if (share < minBudget) share = minBudget; + return share >= limits.budget ? limits : limits.withBudget(share); + } + + Future _buildAndSend({bool explicit = false}) async { HierarchySnapshot? snapshot; final Duration started = _now(); try { - snapshot = _builder(limits, _now); + snapshot = _builder(_limitsNow(explicit: explicit), _now); } catch (_) { snapshot = null; // fail closed: nothing is sent as a hierarchy } diff --git a/test/view_hierarchy_publisher_test.dart b/test/view_hierarchy_publisher_test.dart index f50694e..bb613e0 100644 --- a/test/view_hierarchy_publisher_test.dart +++ b/test/view_hierarchy_publisher_test.dart @@ -27,6 +27,8 @@ class Rig { Duration maxInterval = const Duration(seconds: 5), Duration frameWait = const Duration(milliseconds: 400), bool deferWhileBusy = false, + Duration? frameInterval, + bool Function()? framePending, }) { _start = tester.binding.clock.now(); publisher = ViewHierarchyPublisher( @@ -42,9 +44,12 @@ class Rig { busyGap: deferWhileBusy ? const Duration(milliseconds: 100) : Duration.zero, + frameInterval: frameInterval == null ? null : () => frameInterval, + framePending: framePending, clock: () => tester.binding.clock.now().difference(_start) + _cost, builder: (limits, now) { builds++; + budgets.add(limits.budget); buildTimes.add(now()); phases.add(SchedulerBinding.instance.schedulerPhase); _cost += buildCost; @@ -59,6 +64,7 @@ class Rig { late final ViewHierarchyPublisher publisher; final List sent = []; final List phases = []; + final List budgets = []; final List buildTimes = []; int builds = 0; int failSends = 0; @@ -685,6 +691,76 @@ void main() { ); }); + group('the walk budget follows the frame', () { + /// One walk, taken with a frame due or not, on a display of [hz]; the budget it was given. + Future budgetFor( + WidgetTester tester, { + required double hz, + required bool pending, + bool explicit = false, + }) async { + await tester.pumpWidget(const SizedBox()); + final r = Rig( + tester, + frameInterval: Duration(microseconds: (1e6 / hz).round()), + framePending: () => pending, + ); + r.publisher.activate(); + await r.frame(); // the first walk + if (explicit) { + // No frame is scheduled now, so the capture does not wait for one. + await r.publisher.flush(); + } + expect(r.budgets, hasLength(explicit ? 2 : 1)); + final Duration b = r.budgets.last; + await r.publisher.deactivate(); + r.publisher.dispose(); + return b; + } + + testWidgets('with nothing due the full budget applies', (tester) async { + expect( + await budgetFor(tester, hz: 120, pending: false), + const Duration(milliseconds: 12), + ); + }); + + testWidgets('a frame due at 60 Hz gets 35% of 16.7 ms', (tester) async { + final b = await budgetFor(tester, hz: 60, pending: true); + expect(b.inMicroseconds, closeTo(5833, 5)); + }); + + testWidgets('a frame due at 120 Hz gets 35% of 8.3 ms', (tester) async { + final b = await budgetFor(tester, hz: 120, pending: true); + expect(b.inMicroseconds, closeTo(2917, 5)); + }); + + testWidgets('a very fast display still gets the least budget', ( + tester, + ) async { + expect( + await budgetFor(tester, hz: 480, pending: true), + const Duration(milliseconds: 2), + ); + }); + + testWidgets('a slow display never exceeds the limit itself', ( + tester, + ) async { + expect( + await budgetFor(tester, hz: 24, pending: true), + const Duration(milliseconds: 12), + ); + }); + + testWidgets('an explicit capture keeps the full budget', (tester) async { + expect( + await budgetFor(tester, hz: 120, pending: true, explicit: true), + const Duration(milliseconds: 12), + ); + }); + }); + group('flush', () { rigTest('builds now, inside the throttle, and completes when sent', ( tester,