Skip to content

perf(harness): on-device lag capture - #23413

Merged
Git-on-my-level merged 4 commits into
mainfrom
perf/mobile-lag-capture
Oct 24, 2026
Merged

Git-on-my-level merged 4 commits into
mainfrom
perf/mobile-lag-capture

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

perf(harness): on-device lag capture

What changed and why

David reports that the iOS app (TestFlight 1.0.573) "still lags quite a lot sometimes when I'm scrolling or clicking on things". The interaction harness didn't reproduce it, for three reasons:

  • Host flutter test can't see what a phone does. It can't raster, doesn't run AOT code, and its timings swung 5–10× between runs in the previous round (perf(episodes): keep the live-episode surfaces O(1) per capture notify #23278).
  • The harness didn't run under production conditions. testWidgets turns semantics on by default. Production iOS ran with semantics forced on by the rage-click tracker; that is fixed separately in the app-wide fixes PR. After that fix, production runs with semantics off. Either way, the host arm never matched the device.
  • No device-side lag signal exists. Routine Mobile Render Observation was removed from PostHog on 2026-10-17 (FinOps, ingestion drop at 0%). The client telemetry collector isn't deployed, and its flags must stay off.

This PR makes lag measurable where it's felt, without sending anything off the device:

  1. LagRecorder (app/lib/utils/analytics/lag_recorder.dart)
    • It's owned and fed by the existing MobilePerformanceTelemetry, and runs only while Settings → Developer → Debug logs is on. In release and TestFlight builds it records:
      • per surface (the pushed page's widget type for routeToPage pushes, or the Home tab): frames, slow (>16.7 ms on either thread), severe (>33.3 ms) and freeze (>100 ms) counts, build-bound versus raster-bound, and whether the user was scrolling, had just tapped or was idle;
      • the worst frames, with wall-clock time;
      • tap-to-frame latency, which includes the tap handler's own synchronous work;
      • UI-isolate stalls between frames, from a 250 ms watchdog that runs only while capture is on.
    • No change to main.dart, so test(perf): gate mobile scenarios through production app wrappers #23419's production-shell fingerprint stays valid:
      • The recorder writes through the emit that main.dart already passes; each lag event names itself in an event field.
      • Input comes from GestureBinding's global pointer route, not a widget. That route runs before the gesture-arena sweep that fires onTap, so tap timing includes the handler. A drag past touch slop counts as a scroll, with an 800 ms tail after lift for the fling; one pointer is tracked at a time.
      • The Home tab comes from a one-line hook in HomeProvider.setIndex.
      • Every input callback returns at once unless capture is on.
    • Output is local debug-log events only. A report is written on every background and every ~18k frames, and individual severe frames are capped at 20 per minute. When nothing is slow, a frame costs a few integer comparisons.
  2. app/tool/lag_report.py turns a shared debug log into a ranked table of surfaces, worst frames, slow taps and stalls.
  3. The host-harness changes moved to test(perf): gate mobile scenarios through production app wrappers #23419. An earlier revision of this PR also turned semantics off in the integration perf scenarios and added a per-phase UI split. test(perf): gate mobile scenarios through production app wrappers #23419 (the production-shell perf gate) carries both and more, in the same files, so this PR no longer touches integration_test/perf/. The device-capture how-to lives in app/docs/performance.md.

How David captures a lag

  1. Settings → Developer → turn on Debug logs, then background and reopen the app.
  2. Use the app normally until it lags, then background it once. This writes mobile_lag_report.
  3. Settings → Developer → Share logs. We run python3 app/tool/lag_report.py omi_debug_YYYYMMDD.log.

The report tells us which screen lagged, whether the GPU (raster) or the UI isolate (build) was the bottleneck, and whether it happened while scrolling, after a tap or idle. That decides which kind of fix applies.

Privacy

  • Labels are code identifiers (widget type names, Home tab names), never route arguments or content; dynamic route names collapse to page.
  • Nothing is transmitted. The events go to the same local debug log that the user shares by hand. EMISSION.md records this.

How it was verified

  • test/unit/lag_recorder_test.dart (11 tests) covers:
    • bound and context attribution;
    • attributing a frame to the surface that was on top when it started (timings arrive in batches);
    • the rate limit;
    • the stall, tap and moved-pointer thresholds;
    • label privacy;
    • the recorder running only while debug logs are on, and reporting on background;
    • drags counting as scrolls through the fling tail and never as taps, and a second finger not disturbing the first;
    • real tester drags reaching the recorder through the global pointer route, with no widget mounted, and the Home-tab hook clearing on dispose.
  • The existing mobile_performance_telemetry_test.dart (5 tests) still passes.
  • flutter analyze is clean on lib/utils/analytics.
  • The input callbacks return at once unless capture is on, and turning capture off forgets an in-flight gesture (covered by lag_recorder_test.dart, 8 tests).
  • It passes both the current check_mobile_ui_isolate.py and ci(app): add scoped mobile performance ratchets #23415's stricter version, with no allow annotations, because there's no root listener widget.
  • main.dart is byte-identical to main, so test(perf): gate mobile scenarios through production app wrappers #23419's perf_shell.py --check is unaffected.
  • The INV-PERF-1 ratchet (check_mobile_ui_isolate.py) passes.
  • app/tool/lag_report.py was checked against a synthetic log.

UI-Evidence: none -- no visual change; adds input listeners, a recorder and debug-log events only.

Product invariants affected

INV-PERF-1: the recorder runs on every frame-timings batch and stays O(frames) with no allocation unless a frame is severe; the watchdog timer runs only while the user has debug logs on. This adds the device-side measurement the invariant has lacked.

INV-DATA-1: unaffected; no routing or production data path changes (selected by touching main.dart).

Failure-Class: none

🤖 Generated with Claude Code

The host interaction harness could not see the lag David feels: host
flutter test cannot raster, its timings swung 5-10x between runs, and it
ran with semantics on, unlike production. Routine render telemetry was
removed from PostHog on 2026-10-17, so the device signal stays local.

- LagRecorder (lib/utils/analytics/lag_recorder.dart), fed by the existing
  MobilePerformanceTelemetry frame-timings callback while Settings ->
  Developer -> Debug logs is on: per surface (routeToPage page type or Home
  tab) frame counts over 16.7/33.3/100 ms, build- vs raster-bound, slow
  frames while scrolling / after a tap / idle; worst frames with
  wall-clock time; tap-to-frame latency including the tap handler's sync
  work; and UI-isolate stalls from a 250 ms watchdog that runs only while
  capture is on. Writes mobile_lag_* events to the local debug log; a
  report on every background and every ~18k frames.
- app/tool/lag_report.py turns a shared debug log into a ranked table.
- Integration perf scenarios run with semantics off (PERF_SEMANTICS=1 to
  opt back in) and report a per-phase UI split from FlutterTimeline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-24T04:54:40.441015Z 9e5e574 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d6cd20f07e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +77 to +82
_lagActive = _attached && _foreground && diagnosticsEnabled?.call() == true;
if (_lagActive) {
recorder.startWatchdog();
} else {
recorder.stopWatchdog();
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Gate all recorder state on the debug-log switch

When debug logging is disabled, this branch only stops the watchdog; LagInputScope still forwards every pointer and scroll event to the recorder, and pending frame/tap/stall aggregates are never cleared. Consequently, after a user disables and later re-enables debug logs without restarting, the next mobile_lag_report can include taps or measurements collected before the current capture session, corrupting the report and adding always-on input instrumentation. Pause input collection and reset or flush recorder state when _lagActive becomes false.

Useful? React with 👍 / 👎.

String lagSurfaceFor(Route<dynamic> route, {required int homeTab}) {
final label = lagRouteLabels[route];
if (label != null) return label;
if (route.isFirst) return homeTab == 0 ? 'home_tab:conversations' : 'home_tab:tasks';

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Derive the first route's surface from the displayed shell

For signed-out, onboarding, consent, and permissions states, the first navigator route still renders AppShell, but this branch unconditionally labels it home_tab:conversations. With debug logging enabled during those flows, their frames and stalls are therefore merged into the Home conversations bucket, defeating the screen attribution this recorder is intended to provide; the root label needs to follow the shell's actual displayed state rather than Route.isFirst alone.

Useful? React with 👍 / 👎.

Comment on lines +238 to +239
_keepWorst(_worstStalls, record, 'blocked_ms');
_emit('mobile_lag_stall', record);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Rate-limit individual stall log events

On a device experiencing sustained UI-isolate delays—the primary situation this recorder targets—the 250 ms watchdog can call this path several times per second, and every call queues a separate file append. Unlike severe-frame events, stalls have no rolling rate limit even though the report already preserves bounded worst-stall samples and aggregate counts, so prolonged lag can generate thousands of writes, perturb the performance being measured, and rotate away useful debug-log history.

Useful? React with 👍 / 👎.

if (worst <= severeUs) return;

final record = <String, Object?>{
'at': _wallClock().toIso8601String(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Timestamp slow frames at their actual vsync time

When addTimingsCallback delivers its usual batch of frame timings, this assigns every slow frame the wall-clock time at which the batch is processed rather than the time represented by vsyncStartUs. Since the code already accounts for batches arriving up to a second late, the reported at values cannot be reliably correlated with user actions or neighboring debug events, and multiple frames may receive the same clock value and be collapsed by lag_report.py's (at, surface) key. Convert the monotonic vsync timestamp to wall time instead of calling the current wall clock here.

Useful? React with 👍 / 👎.

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

SHIP — Sol/P88 review of current head d6cd20f. No P0/P1 findings. Reviewed recorder bounds, local-only DebugLogManager emission, main.dart input/navigation wiring, timing/watchdog lifecycle, report parser, production-semantics host changes and targeted test source. Source review only: I did not rerun Flutter tests or measure device overhead; existing CI and physical/TestFlight acceptance remain separate gates. No merge requested or performed.

…capture is off

#23419 (production-shell perf gate) carries the same host-harness changes
this PR made (semantics off, per-phase split) and more, in the same four
integration_test/perf files, so drop them here to avoid a conflict. The
device-capture how-to moves to app/docs/performance.md.

LagInputScope's callbacks now return at once unless Debug logs capture is
on, and turning capture off forgets an in-flight gesture. The global
listener is annotated for #23415's global-input-listener ratchet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level Git-on-my-level changed the title perf(harness): on-device lag capture and production-condition host runs perf(harness): on-device lag capture Oct 24, 2026
Git-on-my-level and others added 2 commits October 24, 2026 11:41
#23419's production-shell gate fingerprints all of main.dart and copies its
telemetry field and builder chain into a generated shell, so new root
wrappers in main.dart (LagInputScope, _LagHomeTabListener) would make the
shell stale and could not compile there. Take main.dart back to main.

- MobilePerformanceTelemetry builds its own LagRecorder and writes through
  the emit main.dart already passes; each lag event names itself in an
  'event' field (lag_report.py reads both shapes).
- Pointers come from GestureBinding's global pointer route: no widget, and
  it runs before the arena sweep that fires onTap. A drag past touch slop
  is a scroll, with an 800 ms tail after lift for the fling; one tracked
  pointer at a time.
- The Home tab comes from a one-line hook in HomeProvider.setIndex.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9e5e574585

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +174 to +175
final watch = Stopwatch()..start();
WidgetsBinding.instance.addPostFrameCallback((_) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Start tap timing before gesture recognizers process pointer-up

When a tap recognizer has already won its gesture arena before pointer-up, its synchronous onTap handler runs before this stopwatch starts: Flutter's PointerRouter implementation dispatches per-pointer routes before global routes, and the tap recognizer processes pointer-up immediately. Consequently, an expensive tap handler can block the UI for hundreds of milliseconds yet produce a fast tap_to_frame_ms, omitting precisely the synchronous work this metric claims to include. Capture the start time before recognizer dispatch rather than starting the stopwatch in the global pointer-up callback.

Useful? React with 👍 / 👎.

Comment on lines +88 to +92
if (!value && _lagActive) lag.writeReport('background');
_foreground = value;
_generation++;
_epoch = identityEpoch();
_refreshLag();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Include delayed frame batches in the background capture

In release/TestFlight builds, backgrounding immediately after a lag can omit the frames the user intended to capture. Flutter batches frame timings approximately once per second in release mode, but this writes and clears the report immediately, then disables capture; any outstanding foreground-frame batch delivered afterward is discarded by _timings's if (!_foreground) return. This particularly affects the documented workflow of backgrounding after reproducing a lag. Preserve the closing capture until outstanding timings have been processed, attributing late batches by their frame timestamps, and write a final report containing them.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant