perf(ui): coalesce scroll observations and transcript measurement (#1500)

Coalesce event-driven scroll observations to one per animation frame while
preserving synchronous gesture, resize and content observations. Cancel
pending observations on deactivation, reset and disposal.

Debounce transcript retention measurements to one trailing walk after a
500 ms quiet window, reducing repeated starts during deferred highlighting.
Preserve abort-in-flight and stale-result fencing. Cancel the armed frame or
timer when synchronously flushing tool-body mounts, so a subsequent queue
cannot be drained by both an obsolete callback and its new frame.

Add scheduler regressions and CI registration. Update the cache-lifetime
test for delayed accounting, select only long-to-long samples for their
timing bound, and retain a separate host-tolerant overall backstop.
This commit is contained in:
heunghingwan 2026-11-14 07:40:01 +08:00 • committed by GitHub
parent b7c2f95c0f
commit c8dae86ea7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 361 additions and 28 deletions

View file

@ -461,6 +461,9 @@ jobs:
packages/ui/src/lib/native/browser.test.ts
packages/ui/src/lib/runtime-env.test.ts
packages/ui/src/lib/session-transcript-lru.test.ts
packages/ui/src/lib/session-transcript-measurement.test.ts
packages/ui/src/lib/markdown-highlight-schedule.test.ts
packages/ui/src/lib/frame-batch-schedule.test.ts
packages/ui/src/lib/server-meta.test.ts
packages/ui/src/lib/theme-scheme.test.ts
packages/ui/src/lib/trailing-resync.test.ts

View file

@ -23,7 +23,10 @@ it("keeps a visible over-budget transcript pinned across catalogue and loading c
useSessionCache({ instanceId: () => instanceId, activeSessionId: () => sessionId,
isActiveInstance: active, instanceSessions: () => sessions().get(instanceId)! })
})
await new Promise(resolve => setTimeout(resolve, 250))
// The transcript account's measurement debounce waits out a 500ms quiet
// window before its retained-size walk; give it time to account the
// over-budget bytes while the session stays visible and protected.
await new Promise(resolve => setTimeout(resolve, 650))
assert.deepEqual(store.getSessionMessageIds(sessionId), ["message"])
setSessions(prev => new Map(prev).set(instanceId, new Map([[sessionId, { ...session, title: "Renamed" }]])))
assert.deepEqual(store.getSessionMessageIds(sessionId), ["message"])

View file

@ -15,6 +15,7 @@ import {
getPrimaryPointerDragDirection,
SCROLL_EDGE_TOLERANCE_PX,
ScrollRestoreTokenGuard,
ScrollObservationGate,
shouldNavigateAtBoundary,
VirtualScrollController,
hasReachedBottom,
@ -589,4 +590,96 @@ describe("virtual follow behavior", () => {
assert.equal(restoredOldMode, false, path)
}
})
it("coalesces scroll-event observations to one flush per animation frame", () => {
const makeGate = () => {
const pending = new Map<number, () => void>()
let flushes = 0
let nextHandle = 0
const gate = new ScrollObservationGate(() => { flushes += 1 }, {
schedule: (callback) => { nextHandle += 1; pending.set(nextHandle, callback); return nextHandle },
cancel: (handle) => { pending.delete(handle) },
})
return {
gate, flushes: () => flushes, pendingCount: () => pending.size,
runFrame: () => { const callbacks = [...pending.values()]; pending.clear(); for (const callback of callbacks) callback() },
}
}
const harness = makeGate()
harness.gate.request()
harness.gate.request()
harness.gate.request()
assert.equal(harness.flushes(), 0)
assert.equal(harness.pendingCount(), 1)
harness.runFrame()
assert.equal(harness.flushes(), 1)
assert.equal(harness.pendingCount(), 0)
})
it("defers a re-request made during a flush to the next frame", () => {
const pending = new Map<number, () => void>()
let flushes = 0
let nextHandle = 0
const gate = new ScrollObservationGate(() => {
flushes += 1
gate.request()
}, {
schedule: (callback) => { nextHandle += 1; pending.set(nextHandle, callback); return nextHandle },
cancel: (handle) => { pending.delete(handle) },
})
const runFrame = () => { const callbacks = [...pending.values()]; pending.clear(); for (const callback of callbacks) callback() }
gate.request()
runFrame()
assert.equal(flushes, 1)
// The re-request armed the next frame; nothing else runs in this one.
assert.equal(pending.size, 1)
runFrame()
assert.equal(flushes, 2)
})
it("observes immediately through the pending frame slot without double-flushing", () => {
const pending = new Map<number, () => void>()
const cancelled: number[] = []
let flushes = 0
let nextHandle = 0
const gate = new ScrollObservationGate(() => { flushes += 1 }, {
schedule: (callback) => { nextHandle += 1; pending.set(nextHandle, callback); return nextHandle },
cancel: (handle) => { cancelled.push(handle); pending.delete(handle) },
})
const runFrame = () => { const callbacks = [...pending.values()]; pending.clear(); for (const callback of callbacks) callback() }
gate.request()
gate.observeNow()
assert.equal(flushes, 1)
assert.deepEqual(cancelled, [1])
// The frame slot was consumed: running the frame flushes nothing more.
runFrame()
assert.equal(flushes, 1)
})
it("drops a pending observation on cancel", () => {
const pending = new Map<number, () => void>()
const cancelled: number[] = []
let flushes = 0
let nextHandle = 0
const gate = new ScrollObservationGate(() => { flushes += 1 }, {
schedule: (callback) => { nextHandle += 1; pending.set(nextHandle, callback); return nextHandle },
cancel: (handle) => { cancelled.push(handle); pending.delete(handle) },
})
const runFrame = () => { const callbacks = [...pending.values()]; pending.clear(); for (const callback of callbacks) callback() }
gate.request()
gate.cancelPending()
assert.deepEqual(cancelled, [1])
runFrame()
assert.equal(flushes, 0)
// A later request works again after a cancel.
gate.request()
runFrame()
assert.equal(flushes, 1)
})
})

View file

@ -531,3 +531,51 @@ export class VirtualScrollController {
return { effect, state: this.snapshot() }
}
}
export interface ScrollObservationScheduler {
schedule(callback: () => void): number
cancel(handle: number): void
}
/**
* Bounds DOM scroll-state observations to one per animation frame. Scroll
* events arrive per rendering update while a virtualized list settles (every
* programmatic write, Virtua's measurement compensation, the follow pin each
* contribute one), and each observation reads layout and can issue a new
* write whose event lands in the same update — the observation/write feedback
* keeps the settle task long. `request` coalesces those event-driven
* observations into the frame's end; `observeNow` keeps synchronous
* observation semantics for direct entries (gestures at a clamped edge,
* content-rendered flushes) while consuming the frame slot so a frame never
* observes twice.
*/
export class ScrollObservationGate {
private handle: number | null = null
constructor(
private readonly flush: () => void,
private readonly scheduler: ScrollObservationScheduler,
) {}
/** One deferred observation per frame; further requests coalesce into it. */
request(): void {
if (this.handle !== null) return
this.handle = this.scheduler.schedule(() => {
this.handle = null
this.flush()
})
}
/** Observes now, consuming any pending frame observation. */
observeNow(): void {
this.cancelPending()
this.flush()
}
/** Drops a pending frame observation without running it. */
cancelPending(): void {
if (this.handle === null) return
this.scheduler.cancel(this.handle)
this.handle = null
}
}

View file

@ -5,7 +5,7 @@ import { flushFrameBatchedMounts } from "../lib/frame-batch-schedule"
import { attachScrollGestureRouting, findNestedScroller, getElementZoom, POINTER_CONTROL_SELECTOR, wheelDeltaUnit } from "../lib/scroll-gesture-routing"
import { remapVirtualMeasurements } from "./virtual-follow-measurements"
import { createVirtualReaderSettlement } from "./virtual-reader-settlement"
import { advanceBottomPinSettlement, AnchorRestoreStabilizer, canScrollInDirection, classifyVirtualItemKeyChange, describeKeyTarget, getBottomAnchoredViewportOffset, getFollowSnapshotState, getKeyboardScrollIntent, getPrimaryPointerDragDirection, isAtBottomForMode, isAutoFollowing, isMiddleButtonScrollIntent, isScrollRestoreMeasurementReady, resolveAutoPinHoldElement, restoreFollowModeFromSnapshot, SCROLL_INTENT_KEYS, USER_SCROLL_INTENT_WINDOW_MS, ScrollRestoreTokenGuard, selectTopViewportAnchor, shouldNavigateAtBoundary, VirtualScrollController, type BottomPinSettlementState, type FollowEffect, type FollowEvent, type FollowMode, type HoldTargetElementResolver, type ScrollControllerMetrics, type ScrollControllerResult } from "./virtual-follow-behavior.ts"
import { advanceBottomPinSettlement, AnchorRestoreStabilizer, canScrollInDirection, classifyVirtualItemKeyChange, describeKeyTarget, getBottomAnchoredViewportOffset, getFollowSnapshotState, getKeyboardScrollIntent, getPrimaryPointerDragDirection, isAtBottomForMode, isAutoFollowing, isMiddleButtonScrollIntent, isScrollRestoreMeasurementReady, resolveAutoPinHoldElement, restoreFollowModeFromSnapshot, SCROLL_INTENT_KEYS, ScrollObservationGate, USER_SCROLL_INTENT_WINDOW_MS, ScrollRestoreTokenGuard, selectTopViewportAnchor, shouldNavigateAtBoundary, VirtualScrollController, type BottomPinSettlementState, type FollowEffect, type FollowEvent, type FollowMode, type HoldTargetElementResolver, type ScrollControllerMetrics, type ScrollControllerResult } from "./virtual-follow-behavior.ts"
import { isScrollTraceEnabled, traceScroll, type ScrollReason, type ScrollTraceEntry, type ScrollTraceKind } from "./virtual-scroll-trace"
const DEFAULT_HOLD_TARGET_TOP_THRESHOLD_PX = 8
@ -170,6 +170,16 @@ export default function VirtualFollowList<T>(props: VirtualFollowListProps<T>) {
const scrollButtonsCount = createMemo(() => (showScrollTopButton() ? 1 : 0) + (showScrollBottomButton() ? 1 : 0))
const scrollController = new VirtualScrollController(initialAutoScroll())
// Scroll events observe the DOM at most once per animation frame: a
// settling list emits one per rendering update (every programmatic write,
// each of Virtua's measurement compensations, the follow pin), and each
// observation reads layout and can write again. Direct entries (a gesture
// at a clamped edge, content-rendered flushes, viewport resizes) keep their
// synchronous observation and consume the frame slot.
const scrollObservation = new ScrollObservationGate(() => updateScrollStateFromDom(), {
schedule: (callback) => requestAnimationFrame(callback),
cancel: (handle) => cancelAnimationFrame(handle),
})
// Virtua measures and compensates the header like any row. It is created
// once: a Virtua remount moves it into its new first row instead of
// recreating it (focus and its components' state survive).
@ -244,6 +254,7 @@ export default function VirtualFollowList<T>(props: VirtualFollowListProps<T>) {
readerSettlement.cancel()
invalidateScrollRestore()
endBottomPin("interrupted")
scrollObservation.cancelPending()
if (pendingContentRenderedFrame !== null) cancelAnimationFrame(pendingContentRenderedFrame)
pendingContentRenderedFrame = null
}
@ -321,7 +332,7 @@ export default function VirtualFollowList<T>(props: VirtualFollowListProps<T>) {
// No list positioning outlives this: see `writeScroll`.
// At a clamped edge a wheel/key produces no scroll event. The gesture
// itself must be able to request the next historical window.
if (direction) updateScrollStateFromDom()
if (direction) scrollObservation.observeNow()
}
function hasProgrammaticScrollIntent() {
@ -627,7 +638,7 @@ export default function VirtualFollowList<T>(props: VirtualFollowListProps<T>) {
function handleScroll() {
followRollAnchor()
updateScrollStateFromDom()
scrollObservation.request()
props.onScroll?.()
const handle = virtuaHandle()
@ -765,7 +776,7 @@ export default function VirtualFollowList<T>(props: VirtualFollowListProps<T>) {
else if (!bottomPin?.settle && !maybeEscapeForHoldTrigger()) {
dispatchFollowEvent({ type: "content-grew", canPinToBottom: autoScroll() && !externalSuspendAutoPinToBottom() })
}
updateScrollStateFromDom()
scrollObservation.observeNow()
}
function captureScrollSnapshot(): VirtualFollowScrollSnapshot | undefined {
@ -1020,7 +1031,7 @@ export default function VirtualFollowList<T>(props: VirtualFollowListProps<T>) {
lastPrimaryPointerY = null
if (wasDragging) {
programmaticScrollUntil = 0
updateScrollStateFromDom()
scrollObservation.observeNow()
}
}
let lastTouchY: number | null = null
@ -1355,7 +1366,7 @@ export default function VirtualFollowList<T>(props: VirtualFollowListProps<T>) {
// The rolled reader's place follows the bottom-anchored (and clamped) content.
if (rollReader) rollReader.offset -= element.scrollTop - before
}
updateScrollStateFromDom()
scrollObservation.observeNow()
})
// An inactive or restoring list only rebases. A held element re-aligns itself on its next frame.
const observer = new ResizeObserver(() => { viewportHeight.update(isActive() && !scrollController.snapshot().restoring) })

View file

@ -0,0 +1,72 @@
import assert from "node:assert/strict"
import { afterEach, test } from "node:test"
import { flushFrameBatchedMounts, scheduleFrameBatchedMount } from "./frame-batch-schedule"
const globalScope = globalThis as unknown as Record<string, unknown>
const armed: Array<() => void> = []
const cancelled: number[] = []
let originalRequest: unknown
let hadRequest = false
let originalCancel: unknown
let hadCancel = false
afterEach(() => {
armed.length = 0
cancelled.length = 0
// Node has no animation frames: restore the original state exactly,
// including absence, so later tests in this process pick their own path.
if (hadRequest) globalScope.requestAnimationFrame = originalRequest
else delete globalScope.requestAnimationFrame
if (hadCancel) globalScope.cancelAnimationFrame = originalCancel
else delete globalScope.cancelAnimationFrame
})
function installFrameScheduler() {
hadRequest = "requestAnimationFrame" in globalScope
originalRequest = globalScope.requestAnimationFrame
hadCancel = "cancelAnimationFrame" in globalScope
originalCancel = globalScope.cancelAnimationFrame
globalScope.requestAnimationFrame = (callback: () => void) => {
armed.push(callback)
return armed.length
}
globalScope.cancelAnimationFrame = (handle: number) => {
cancelled.push(handle)
}
}
test("a synchronous flush drains the queue and invalidates the armed frame", () => {
installFrameScheduler()
const mounted: number[] = []
scheduleFrameBatchedMount(() => mounted.push(1))
scheduleFrameBatchedMount(() => mounted.push(2))
scheduleFrameBatchedMount(() => mounted.push(3))
assert.equal(armed.length, 1, "the mounts share one armed frame")
flushFrameBatchedMounts()
assert.deepEqual(mounted, [1, 2, 3])
assert.deepEqual(cancelled, [1], "the flush invalidates the armed frame callback")
assert.equal(armed.length, 1, "the flush arms nothing")
// A mount scheduled after the flush arms a fresh frame.
scheduleFrameBatchedMount(() => mounted.push(4))
assert.equal(armed.length, 2)
armed.pop()!()
assert.deepEqual(mounted, [1, 2, 3, 4])
})
test("an ordinary frame batch mounts two queued items per frame", () => {
installFrameScheduler()
const mounted: number[] = []
scheduleFrameBatchedMount(() => mounted.push(1))
scheduleFrameBatchedMount(() => mounted.push(2))
scheduleFrameBatchedMount(() => mounted.push(3))
const frame = armed.pop()!
frame()
assert.deepEqual(mounted, [1, 2], "a frame batch joins two mounts")
frame()
assert.deepEqual(mounted, [1, 2, 3])
})

View file

@ -7,16 +7,16 @@
* even when the main thread never reports idle.
*
* Queued work owns its own validity: callbacks are fenced by their caller
* (a disposed check), so there is no cancellation API.
* (a disposed check), so there is no per-mount cancellation API.
*/
const MOUNTS_PER_FRAME = 2
const queue: Array<() => void> = []
let scheduled = false
let armed: number | null = null
function flush() {
scheduled = false
armed = null
let mounted = 0
while (queue.length > 0 && mounted < MOUNTS_PER_FRAME) {
queue.shift()!()
@ -26,10 +26,16 @@ function flush() {
}
function schedule() {
if (scheduled || queue.length === 0) return
scheduled = true
if (typeof requestAnimationFrame === "function") requestAnimationFrame(flush)
else setTimeout(flush, 0)
if (armed !== null || queue.length === 0) return
if (typeof requestAnimationFrame === "function") armed = requestAnimationFrame(flush)
else armed = setTimeout(flush, 0) as unknown as number
}
function disarm() {
if (armed === null) return
if (typeof requestAnimationFrame === "function") cancelAnimationFrame(armed)
else clearTimeout(armed as unknown as ReturnType<typeof setTimeout>)
armed = null
}
/** Runs `mount` in the next frame batch of at most `MOUNTS_PER_FRAME` items. */
@ -45,8 +51,6 @@ export function scheduleFrameBatchedMount(mount: () => void): void {
* target drifting for the reader.
*/
export function flushFrameBatchedMounts(): void {
// A pending frame callback finds an empty queue and stops; clearing the
// flag lets a later mount reschedule at once.
scheduled = false
disarm()
while (queue.length > 0) queue.shift()!()
}

View file

@ -1,11 +1,24 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { afterEach, test } from "node:test"
import { scheduleDeferredHighlight } from "./markdown-highlight-schedule"
const globalScope = globalThis as unknown as Record<string, unknown>
let hadIdle = false
let originalIdle: unknown
afterEach(() => {
// Node has no idle callbacks: restore the original state exactly,
// including absence, so later tests in this process pick their own path.
if (hadIdle) globalScope.requestIdleCallback = originalIdle
else delete globalScope.requestIdleCallback
})
/** Installs a capturing idle scheduler; returns the queued drains. */
function captureIdle(): { drains: Array<() => void> } {
const drains: Array<() => void> = []
;(globalThis as { requestIdleCallback?: unknown }).requestIdleCallback = (callback: () => void) => {
hadIdle = "requestIdleCallback" in globalScope
originalIdle = globalScope.requestIdleCallback
globalScope.requestIdleCallback = (callback: () => void) => {
drains.push(callback)
return drains.length
}

View file

@ -0,0 +1,59 @@
import assert from "node:assert/strict"
import test from "node:test"
import { SessionTranscriptMeasurementQueue } from "./session-transcript-measurement.ts"
test("reschedules the delayed measurement while pending, one walk after activity stops", async (context) => {
context.mock.timers.enable({ apis: ["setTimeout"] })
let measured = 0
const queue = new SessionTranscriptMeasurementQueue({
delayMs: 100,
measure: async () => {
measured += 1
return 10
},
account: () => {},
onError: () => {},
})
queue.schedule("instance", "session")
context.mock.timers.tick(80)
// Activity continues (a burst of cache commits): the quiet delay restarts
// instead of admitting a full retained-graph walk mid-burst.
queue.schedule("instance", "session")
context.mock.timers.tick(80)
await Promise.resolve()
assert.equal(measured, 0)
context.mock.timers.tick(20)
await Promise.resolve()
assert.equal(measured, 1)
})
test("aborts an in-flight measurement when scheduled again", async (context) => {
context.mock.timers.enable({ apis: ["setTimeout"] })
const aborted: boolean[] = []
let release: ((value: number) => void) | undefined
const queue = new SessionTranscriptMeasurementQueue({
delayMs: 1,
measure: (_instanceId, _sessionId, signal) =>
new Promise<number>((resolve, reject) => {
signal.addEventListener("abort", () => {
aborted.push(signal.aborted)
reject(signal.reason)
})
release = resolve
}),
account: () => {},
onError: () => {},
})
queue.schedule("instance", "session")
context.mock.timers.tick(1)
await Promise.resolve()
// A new schedule while the walk is running aborts it and re-arms the delay.
queue.schedule("instance", "session")
assert.deepEqual(aborted, [true])
release?.(6)
context.mock.timers.tick(1)
await Promise.resolve()
})

View file

@ -28,6 +28,15 @@ export class SessionTranscriptMeasurementQueue {
return
}
current.revision += 1
// The delay follows the last schedule: a burst of commits (store
// publishes, deferred-highlight cache writes) walks the retained graph
// once after it stops, instead of admitting a walk per quiet gap —
// one trailing follow-up per identity, like every other coalesced
// refresh in the codebase.
if (current.timer !== undefined) {
clearTimeout(current.timer)
this.arm(instanceId, sessionId, current)
}
return
}

View file

@ -37,7 +37,11 @@ const coordinator = new SessionTranscriptLru({
})
const measurements = new SessionTranscriptMeasurementQueue({
delayMs: 100,
// Deferred-highlight cache commits land every ~150-350ms while a mounted
// burst drains; a shorter quiet window would keep aborting and restarting
// the retained-graph walk mid-drain. The trailing debounce plus this
// window collapses a switch's measurement storm into one final walk.
delayMs: 500,
measure: async (instanceId, sessionId, signal) => {
return messageStoreBus.getInstance(instanceId)?.estimateSessionRetainedBytes(sessionId, signal) ?? 0
},

View file

@ -27,12 +27,20 @@ const THROTTLE_RATE = 4
*/
const FIRST_OPEN_LONGTASK_MS = 4_000
/**
* Timing backstop for switching between two long sessions (ms). Today's worst
* single longtask there measures 3.6-4.1s idle (store hydration, shell mount
* and scroll settling each still run as one task; follow-up work), up to
* about 7s on a busy host.
* Timing backstop for switching between two long sessions (ms), checked
* against that switch's own samples only. With scroll observations coalesced
* to one per animation frame and each deferred highlight render its own idle
* drain, the worst single longtask there measures about 1.5s at this throttle
* rate on a loaded host (about 2.8-3.4s before both). First opens keep their
* separate best-of-two policy and never feed this bound.
*/
const SUBSEQUENT_SWITCH_LONGTASK_MS = 9_000
const SUBSEQUENT_SWITCH_LONGTASK_MS = 3_000
/**
* Host-tolerant backstop over every sample of the plan: first opens are
* allowed one noisy sample under their own policy, so only a catastrophic
* regression on any switch should trip this, whatever the host is doing.
*/
const OVERALL_SWITCH_LONGTASK_MS = 9_000
/** A switch counts as settled once no longtask occurred for this long (ms). */
const QUIET_MS = 1_200
@ -104,8 +112,12 @@ test("a throttled switch to a 120-message session keeps every longtask bounded",
}
await cdp.send("Emulation.setCPUThrottlingRate", { rate: 1 })
const firstOpen = Math.min(...observations.filter(observation => observation.kind === "first-open").map(observation => observation.max))
// The long→long bound applies to that switch's own samples: first opens
// keep their separate best-of-two policy, and a noisy first-open sample
// must not fail the subsequent-switch ratchet.
const subsequentSwitch = Math.max(0, ...observations.filter(observation => observation.kind === "big-to-big").map(observation => observation.max))
const worst = Math.max(...observations.map(observation => observation.max))
console.log("mount-longtask", JSON.stringify({ throttle: THROTTLE_RATE, firstOpenBackstop: FIRST_OPEN_LONGTASK_MS, subsequentBackstop: SUBSEQUENT_SWITCH_LONGTASK_MS, firstOpen, worst, observations }))
console.log("mount-longtask", JSON.stringify({ throttle: THROTTLE_RATE, firstOpenBackstop: FIRST_OPEN_LONGTASK_MS, subsequentBackstop: SUBSEQUENT_SWITCH_LONGTASK_MS, overallBackstop: OVERALL_SWITCH_LONGTASK_MS, firstOpen, subsequentSwitch, worst, observations }))
assert.ok(
observations.every(observation => observation.count >= 1),
"each measured switch must have observed longtasks (observer wiring)",
@ -127,8 +139,10 @@ test("a throttled switch to a 120-message session keeps every longtask bounded",
}
assert.ok(firstOpen < FIRST_OPEN_LONGTASK_MS,
`opening a long session from a short one (${firstOpen}ms, better of two samples) must stay under the ${FIRST_OPEN_LONGTASK_MS}ms backstop at ${THROTTLE_RATE}x CPU throttle`)
assert.ok(worst < SUBSEQUENT_SWITCH_LONGTASK_MS,
`switching between long sessions (${worst}ms worst) must stay under the ${SUBSEQUENT_SWITCH_LONGTASK_MS}ms backstop at ${THROTTLE_RATE}x CPU throttle`)
assert.ok(subsequentSwitch < SUBSEQUENT_SWITCH_LONGTASK_MS,
`switching between long sessions (${subsequentSwitch}ms worst) must stay under the ${SUBSEQUENT_SWITCH_LONGTASK_MS}ms backstop at ${THROTTLE_RATE}x CPU throttle`)
assert.ok(worst < OVERALL_SWITCH_LONGTASK_MS,
`every measured switch (${worst}ms worst overall) must stay under the ${OVERALL_SWITCH_LONGTASK_MS}ms host-tolerant backstop at ${THROTTLE_RATE}x CPU throttle`)
assert.deepEqual(errors, [])
} finally {
await page.close()