Skip to content

feat(browser,webview): screen_size and main_thread_lag_ms traces (ST4c) - #75

Merged
krassx merged 9 commits into
mainfrom
feat/browser-screen-size-main-thread-lag
Oct 20, 2026
Merged

krassx merged 9 commits into
mainfrom
feat/browser-screen-size-main-thread-lag

Conversation

@krassx

@krassx krassx commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Summary

  • screen_size: { width, height, dpr } (CSS px of the injected window's screen and live devicePixelRatio), emitted at start and on resize/orientationchange, held and de-duplicated, omitted when the screen or ratio is absent or not a finite positive number. Deliberately NOT named displays (Android's display LIST shape).
  • main_thread_lag_ms: TIMER DRIFT — on each 1 s sampling tick while the page is visible, lag = max(0, now() − (previousTick + interval)) from the injected window's performance.now; fresh baseline on every visible start (a hidden stretch is never lag), timer torn down while hidden, failed start rolled back, throwing/non-finite clock skips only that interval. A measured 0 is emitted.
  • Both are wired like app_state/fps (under the shared lifecycle gate, so sensors:false/a systemMetricsSampler override omits them).

Why drift, not a MessageChannel ping (measured)

Two ping designs were built and rejected after review: re-posting on every receipt is a continuous task loop (~2.2M receipts/s = a pinned core, and it overwrites a freeze's delta microseconds later); a per-tick ping reads ~0.1 ms through most real freezes in headless Chromium (a block that starts after the ping returned has nothing in flight to delay, and the 'in-flight age' branch never fires because the tick timer shares the blocked thread).

Drift, validated in real headless Chromium: idle page 0.1 ms median / 3 ms max, no positive bias; blocks ≥ 1 s always show (≥ 907 ms; 1800 ms read 907..1797, 2500 ms read 1807); one block is reported once. Honest limit: a block shorter than 1 s that crosses no due tick reads exactly 0 (≈ 1 − B/1000 of the time); catching short jank needs a finer timer (max per window) or PerformanceObserver('longtask') — documented, not built. The occluded-window throttling note is unverified (headless can't reproduce it).

Review

  • Mutator loop on all new/changed entities.
  • Three local Opus rounds: the flood, the ping blind spot (with a real-Chromium port), the doc overclaim, the performance.now this-binding test gap, a duplicate error report.

The viewer has no definition for either name yet (generic value blocks).

Test plan

  • pnpm ci:local

🤖 Generated with Claude Code

screen_size reports {width, height, dpr} as a held step trace, re-read on
resize/orientationchange. main_thread_lag_ms is a MessageChannel round-trip
delta, measured only while the page is visible (hidden aborts the ping and
clears the value), re-armed on every receipt and emitted once per tick.
Both come from the injected window and sit behind the lifecycle gate.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
…ize-main-thread-lag

# Conflicts:
#	docs/PROGRESS.md
…ST4c review)

Re-arming on every receipt was a continuous task loop and overwrote a
long-task delta with a ~0 one. A receipt now only stores the delta; each
1 s tick emits it and posts ONE new ping, and a ping still in flight at a
tick reports its age (a lower bound) instead of posting another. Also: wire
the clock only when performance.now is a function, wrap the screen-size
tracker's reporter, and document screen_size staleness.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
… ping (ST4c review)

A ping only sees a block that begins while it is in flight, so most real
freezes read ~0.1 ms in Chromium. The tracker now measures how late the 1 s
sampling timer fires (max(0, now - (previousTick + interval))), emitted every
tick while visible, with a fresh baseline on every visible start. The
MessageChannel machinery and its env plumbing are deleted.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
…ow binding; read the clock once (ST4c review)

🤖 Generated with [Claude Code](https://claude.com/claude-code)
@claude

claude Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Claude finished @krassx's task in 36s —— View job


Review of PR #75: screen_size and main_thread_lag_ms traces (ST4c)

I read the two new trackers, the producers, the createBrowserSystemTraceProducers wiring, the changeset and the docs/PROGRESS.md entry. I did not run the test suite or the gates, so nothing here is based on executed tests. I also did not re-run the Chromium measurements quoted in the PR description.

No inline findings. I looked for a concrete failure scenario in each area below and did not find one.

  • Lag tracker state:
    • #startRun takes a fresh baseline and rolls back on a throwing clock or scheduler. #running cannot be left true without a timer.
    • #stopRun is idempotent. Deactivation also tears down the visibility subscription.
    • A throwing or non-finite clock in #tick advances #expectedAt, so the skipped interval does not read as lag on the next tick.
    • Hidden-to-visible always takes a new baseline, so a hidden stretch is never counted as lag.
  • Screen-size tracker:
    • Listeners are recorded as they attach, so a throw partway through onActivate still lets onDeactivate remove what was attached.
    • current() reports and swallows errors, so a throw cannot reach the browser's event dispatch.
    • Dropping non-finite or non-positive values avoids emitting a bogus 0.
    • resize fires for every frame of a window drag, but screen.* does not change then. The producer's emitIfChanged drops those events, so the cost is one cheap read per event.
  • Wiring:
    • Reading the clock once (clock) means a hostile performance.now getter reports a single error instead of one per consumer.
    • Both traces sit under the same env.lifecycle gate as app_state and fps, and sensors:false returns before they are built. The systemMetricsSampler replacement behaviour therefore matches the changeset.
    • The widened BrowserTraceEnv types (screen and window as intersections) are backwards compatible for callers that already pass the live objects.
  • Docs: the changeset and PROGRESS entry state the drift semantics and the sub-1 s blind spot honestly. They flag the occluded-window throttling case as unverified.

Non-blocking notes (P3, no action needed):

  • defaultScheduler in the lag tracker uses global setInterval, while now comes from the injected window's performance. In production the scheduler is the shared one passed through launch() (env.scheduler), and everything runs on the same main thread, so this only matters for exotic cross-realm injection. It is worth a one-line comment if that is ever a supported setup.
  • The tracker emits one trace per second, mostly zeros, for as long as the page is visible. That matches fps, but check the trace-store budget if retention windows are tight.

Summary

  1. Overall risk: Low.
  2. Merge recommendation: Approve. I found nothing that should block the merge.
  3. Most important issues to fix: none. The only optional item is the P3 scheduler comment above.
  4. Positives:
    • The drift design is well reasoned.
    • Failure paths (throwing clock, scheduler or reporter) are isolated and tested.
    • The known limits (short jank, staleness on same-DPR monitor moves, iOS rotation) are documented rather than hidden.
    • The superseded MessageChannel approach was removed completely.

@coderabbitai

coderabbitai Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ebd63fd0-b909-402a-8125-40c559a5d35d
📥 Commits

Reviewing files that changed from the base of the PR and between e2589b9 and 170ddbd.

📒 Files selected for processing: 2
  • docs/PROGRESS.md
  • packages/browser/src/trace-producers.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

📝 Summary

Summary by CodeRabbit

  • New Features
    • Added screen_size traces that report screen dimensions and device-pixel ratio, updating when the screen changes.
    • Added main_thread_lag_ms traces that measure timer delays while the page is visible. Sampling pauses while hidden and resets when visibility returns.
    • Both traces are available in the browser and WebView.
    • Measurements are omitted when required screen values or timing support are unavailable.
    • When systemMetricsSampler is configured, it replaces these traces.

The browser trace pipeline adds screen_size and main_thread_lag_ms. screen_size reports valid dimensions and device-pixel ratio on start and screen-related events. main_thread_lag_ms reports timer drift while the page is visible and resets its baseline when visibility returns. Browser and WebView launch tests cover both traces. The changeset declares minor releases for both packages.

Sequence Diagram(s)

sequenceDiagram
  participant BrowserTraceProducerFactory
  participant ScreenSizeProducer
  participant ScreenSizeTracker
  participant MainThreadLagProducer
  participant MainThreadLagTracker
  participant TraceStream
  BrowserTraceProducerFactory->>ScreenSizeProducer: Create producer with injected screen and lifecycle
  ScreenSizeProducer->>ScreenSizeTracker: Subscribe to screen state
  ScreenSizeTracker-->>ScreenSizeProducer: Emit current and changed dimensions
  ScreenSizeProducer->>TraceStream: Publish screen_size
  BrowserTraceProducerFactory->>MainThreadLagProducer: Create producer with injected clock and lifecycle
  MainThreadLagProducer->>MainThreadLagTracker: Subscribe to lag readings
  MainThreadLagTracker-->>MainThreadLagProducer: Emit timer drift
  MainThreadLagProducer->>TraceStream: Publish main_thread_lag_ms
Loading

Priority: ⬇️ Low

Change: Feature

Merge Risk: ⚪ Minimal · up to 170dd

The new traces appear ready to merge after normal checks; no actionable issue remains identified.

Security architecture risk: 🔵 Low · up to 170dd

The change adds device characteristics and responsiveness measurements while retaining existing collection controls. No introduced security violation was established, but downstream privacy handling for the additional screen information remains unverified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The material exposure change is additional telemetry about the SDK-bound page environment, including fingerprint-adjacent screen geometry and pixel ratio. The inspected path records these values through the existing capture pipeline; it does not establish a new tenant, credential, or privileged-service authority.

Trust Boundaries and Controls

  • observed — The public WebView launch entrypoint removes window, document, clock, scheduler, capture-store, and sampler seams from page-supplied options before delegating. The new producers therefore do not make those injectable authorities newly available through that public path.
  • inferred — The readings remain page-realm diagnostic inputs, not authenticated device facts. Screen validation restricts their numeric shape but does not establish authenticity, and the inspected publishing path does not use either measurement to grant authority.

Resilience and Maintainability Implications

  • observed — Visibility transitions stop the lag timer and establish a fresh baseline on restart. Producer stop removes subscriptions and clears the sink. Although the producer base does not itself unwind a throwing start, the production system-traces provider catches producer-start failures and attempts to stop the failed producer.

Hardening Proposals

  • proposed — Confirm that the collection policy and downstream handling explicitly cover screen geometry and pixel ratio under the existing default-enabled system-traces option. This is a privacy assurance proposal, not an observed policy violation.
Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 8 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly summarizes the addition of the screen_size and main_thread_lag_ms traces for browser and webview.
Description check Passed The description explains the new traces, their sampling behavior, lifecycle conditions, limitations, and test plan.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 8 files. (1 skipped: 1 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • Fix all pre-merge checks with AI
✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@claude

claude Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Claude finished @krassx's task in 24s —— View job


Review of PR #75: screen_size and main_thread_lag_ms traces (ST4c)

This is a re-review after the latest push (170ddbd8, a merge of origin/main). It adds nothing beyond the earlier commits. I read both trackers, both producers and the createBrowserSystemTraceProducers wiring again. I also read PageLifecycleTracker to check the visibility and freeze interactions. I did not run tests or gates. I did not re-run the Chromium measurements.

No inline findings. My earlier review found no problems, and I found no new ones. I looked for a concrete failure scenario in each area and found none.

  • Lag tracker lifecycle:
    • #startRun rolls back on a throwing clock or scheduler.
    • #stopRun is idempotent.
    • Every hidden-to-visible change takes a fresh baseline, so a hidden stretch never counts as lag.
    • A throwing or non-finite clock in #tick advances #expectedAt and only skips that interval.
    • #expectedAt = now + interval after a late tick means one block is reported once.
  • Screen-size tracker:
    • Listeners are recorded as they attach, so onDeactivate removes whatever was attached before a throw.
    • current() swallows errors, so nothing throws into event dispatch.
    • Non-finite or non-positive values omit the whole reading.
  • Wiring:
    • Both traces sit under the env.lifecycle gate, and sensors:false returns before they are built.
    • clock is read once, so a hostile performance.now getter reports a single error.
    • The widened screen and window intersection types in BrowserTraceEnv are backwards compatible.

Non-blocking notes (P3, no action needed):

  • Suspend or resume while visible: if a laptop sleeps with the tab still visible, no visibilitychange fires. The next tick may then read the whole sleep as lag, depending on whether the platform's performance.now counts suspended time. This is the same family as the occluded-window case the docs already mark unverified. Consider adding it to that note.
  • Scheduler comment: defaultScheduler in main-thread-lag-tracker.ts uses the global setInterval, while now comes from the injected window. This only matters for cross-realm injection. Production passes env.scheduler, so a one-line comment would be enough.
  • Trace volume: one trace per second while the page is visible, the same cadence as fps.

Summary

  1. Overall risk: Low.
  2. Merge recommendation: Approve. Nothing blocks the merge.
  3. Most important issues to fix: none. The P3 notes above are optional.
  4. Positives:
    • Drift timing is measured and the measurements are documented.
    • Failure paths for a throwing clock, scheduler or reporter are isolated.
    • The blind spot for short blocks is stated honestly.
    • The superseded MessageChannel approach was removed completely.

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