Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: measure where a heavy thread stalls, across engines and thread size (#9016)
Daniel Han58403dd00147
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.ymlindex 18ae46382a3..7f43e8b2225 100644--- a/.github/workflows/studio-frontend-ci.yml+++ b/.github/workflows/studio-frontend-ci.yml@@ -21,12 +21,15 @@ on:- 'tests/studio/playwright_strip_ansi_smoke.py'- 'tests/studio/playwright_chat_autoscroll.py'- 'tests/studio/playwright_research_freeze.py'+ - 'tests/studio/playwright_heavy_thread.py'- 'tests/studio/playwright_settings_tabs.py'-- 'tests/studio/playwright_stream_pacing.py'- # Shared lifecycle helpers, and the contract test that keeps verdicts from going unread.+ # Shared lifecycle helpers, and the contract tests that keep verdicts from going unread.- 'tests/studio/_playwright_robust.py'- 'tests/studio/test_autoscroll_harness_contract.py'+ - 'tests/studio/test_heavy_thread_harness_contract.py'+ - 'tests/studio/test_heavy_thread_gap_contract.py'+ - 'tests/studio/test_heavy_thread_measurement_integrity.py'- 'tests/studio/test_playwright_server_lifecycle.py'- 'scripts/sync_allow_scripts_pins.py'- 'tests/studio/test_sync_allow_scripts_pins.py'@@ -171,7 +174,10 @@ jobs:working-directory: ${{ github.workspace }}run: |python3 -m pytest tests/studio/test_playwright_server_lifecycle.py \- tests/studio/test_autoscroll_harness_contract.py -q+ tests/studio/test_autoscroll_harness_contract.py \+ tests/studio/test_heavy_thread_harness_contract.py \+ tests/studio/test_heavy_thread_measurement_integrity.py \+ tests/studio/test_heavy_thread_gap_contract.py -q- name: Browser smoke for ANSI tool outputworking-directory: ${{ github.workspace }}@@ -189,6 +195,19 @@ jobs:working-directory: ${{ github.workspace }}run: python3 tests/studio/playwright_research_freeze.py+ # Two small sizes and one repetition on Chromium: enough to prove the fixture still+ # renders every kind of content it claims to and that the curve still rises, which is all+ # a PR gate can afford. The measurement this harness exists for is the three-engine,+ # three-size, three-repetition run, which takes tens of minutes and belongs on a runner+ # asked for it deliberately, not on every frontend PR.+ - name: Browser smoke for heavy-thread interaction cost+ working-directory: ${{ github.workspace }}+ env:+ SMOKE_HEAVY_CHARS: '25000,100000'+ SMOKE_HEAVY_ENGINES: chromium+ SMOKE_HEAVY_REPEATS: '1'+ PW_ART_DIR: logs/playwright_heavy_thread+ run: python3 tests/studio/playwright_heavy_thread.py# The settings panels are fetched on first view, so only a browser can answer whether# every tab renders and deep-opens land (and abandoned ones do not come back).- name: Browser smoke for the settings tab panelsdiff --git a/studio/frontend/smoke-heavy-thread-main.tsx b/studio/frontend/smoke-heavy-thread-main.tsxnew file mode 100644index 00000000000..1277e68b60b--- /dev/null+++ b/studio/frontend/smoke-heavy-thread-main.tsx@@ -0,0 +1,880 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Harness page for tests/studio/playwright_heavy_thread.py: the real Thread holding a HEAVY+// thread, so the measured cost of typing, scrolling, opening a menu, deleting and re-opening is+// the app's own and grows the way a long session's does.+//+// The axis is CHARACTERS OF THREAD CONTENT, not messages. Users report the slowdown after "long+// generations with any code cells and/or text", which is a statement about volume, so a fixture+// of N short paragraphs would measure the wrong variable.+//+// The content mix is the one the report names, and every kind of it is present at every size+// because the fixture is built in whole CYCLES of one message per kind (~26K characters a+// cycle). Building "until the budget runs out" instead would give the smallest size only the+// first few kinds, and the curve would then be reporting a change of fixture, not of size.+//+// prose long multi-paragraph answers+// python fence a large highlighted code fence+// typescript fence a second language, so one grammar is not the whole Shiki story+// python tool call collapsible card with a code-execution result pane+// bash tool call code_execution card, the other result-pane shape+// html artifact a full ```html document, which Studio collapses into an artifact card+// render_html tool the HTML canvas artifact, as a tool part rather than a fence+// svg fence a highlighted fence that also renders an inline <img> preview+// image parts a raster PNG data URL and a unique SVG data URL, as image content parts+// json fence one very long line, the shape that behaves worst in a highlighter+//+// Two honest limits, both of which the harness's own docstring repeats:+//+// * The HTML artifact renders as an artifact CARD here, not as a live preview. The <iframe>+// lives in ArtifactSurface on the chat page, and it loads its content from the backend+// (/api/inference/artifact-preview-frame), so it cannot exist on a backend-free smoke page.+// What is measured is the in-thread cost of an artifact, which is what a scroll pays.+// * `python` results carry `images: []`. A non-empty list makes the card fetch each image from+// the backend, which would put a network round trip inside a timed region.+//+// Same shape as smoke-autoscroll.html and smoke-thread-weight.html: a vite entry, no backend, no+// auth. Thread itself and the message bodies are real on purpose; mocking either deletes the+// measurement. The runtime is synthetic -- a local runtime whose model adapter never runs,+// seeded through `thread.import`.+//+// useLocalRuntime rather than useExternalStoreRuntime: the delete path under measurement is+// `thread.export()` -> MessageRepository -> `thread.import()`, which only the local runtime backs.++import { Thread } from "@/components/assistant-ui/thread";+import { TooltipProvider } from "@/components/ui/tooltip";+import {+ AssistantRuntimeProvider,+ type ChatModelAdapter,+ ExportedMessageRepository,+ type ThreadMessageLike,+ useAui,+ useLocalRuntime,+} from "@assistant-ui/react";+import {+ RouterProvider,+ createMemoryHistory,+ createRootRoute,+ createRouter,+} from "@tanstack/react-router";+import { type ReactElement, useEffect, useRef, useState } from "react";+import { createRoot } from "react-dom/client";+import "./src/index.css";++// The local runtime's thread list item reports a synthetic `__LOCALID_...` remoteId, which is+// truthy, so the fork-count badge really does fire one GET per assistant message. Answering them+// here, before anything mounts, keeps that off the wire entirely; answering them from the+// Playwright side instead would put a round trip to another process inside a timed region, once+// per assistant message.+// An explicit allowlist, never a blanket `/api/` match. A blanket match resolves EVERY request the+// measured interactions make before Playwright emits it, so `stray_api_requests` stays at zero and+// the fan-out this harness exists to detect becomes invisible to it. Narrowing it is what made the+// two entries below visible in the first place.+//+// Each entry answers a request the harness itself provokes, with the body that endpoint really+// returns, so no round trip lands inside a timed region. Anything NOT listed here goes to the+// network and trips the stray counter, which is the point.+const STUBBED_API: ReadonlyArray<readonly [RegExp, string]> = [+ // One GET per assistant message: the synthetic `__LOCALID_...` remoteId is truthy, so the badge+ // really does ask. `{ count: 0 }`, not `{}`: getForkCount returns `data.count`, and+ // `undefined <= 0` is false, so an empty body renders a badge reading "undefined forks" on every+ // assistant message and adds DOM in proportion to thread size, the axis being measured.+ [/\/api\/chat\/threads\/[^/]+\/messages\/[^/]+\/forks$/, '{"count":0}'],+ // The delete action's own persistence. deleteThreadMessage syncs the exported repository+ // whenever remoteId is truthy, which the synthetic id always is, so this is the fixture+ // maintaining itself rather than app fan-out. Left on the wire it is 3 round trips inside the+ // delete measurement, and it fails the run's own stray check.+ [/\/api\/chat\/threads\/[^/]+\/messages$/, '{"messages":[]}'],+ [/\/api\/chat\/threads\/[^/]+$/, "{}"],+ // App fan-out, NOT fixture upkeep: re-opening a thread asks for the project list and the+ // knowledge bases. Stubbed so a dev-server round trip does not land inside the reopen window,+ // which would be measuring the network rather than the render. They are recorded in+ // `__stubbedApi` and printed as "stubbed api requests" rather than being silently swallowed,+ // because two whole-endpoint GETs per reopen is a real cost and should stay visible.+ [/\/api\/chat\/projects(\?|$)/, '{"projects":[]}'],+ [/\/api\/rag\/knowledge-bases(\?|$)/, '{"knowledge_bases":[]}'],+];++const stubbedApiCalls: string[] = [];+(window as unknown as { __stubbedApi: string[] }).__stubbedApi = stubbedApiCalls;++const realFetch = window.fetch.bind(window);+window.fetch = (input, init) => {+ const url =+ typeof input === "string" ? input : ((input as Request).url ?? String(input));+ for (const [pattern, body] of STUBBED_API) {+ if (pattern.test(url)) {+ // Recorded, not silently swallowed, so a run can still show what was answered locally.+ stubbedApiCalls.push(url);+ return Promise.resolve(+ new Response(body, {+ status: 200,+ headers: { "content-type": "application/json" },+ }),+ );+ }+ }+ return realFetch(input, init);+};++// ── content generators ──────────────────────────────────────────────+//+// Every generator takes the block index and produces content that is UNIQUE to it. That is not+// decoration: code-plugin.ts caches highlighted tokens keyed on the exact source string, so a+// fixture that repeats one fence would highlight it once and hand back the cached result for+// every other copy, and the Shiki cost would vanish from the curve.++const PROSE_SENTENCES = [+ "The reception of a long thread is decided by what the renderer does on every interaction, not by what it did once at load.",+ "A reply that arrives quickly can still leave a thread that answers a keystroke slowly, because the two costs are paid in different places.",+ "Anything that walks the whole message list on each frame turns a pleasant session into an unpleasant one somewhere around the twentieth long answer.",+ "The tell is that generation stays fast while the surrounding interface does not, which points at per-message renderer work rather than at the model.",+ "Layout that is not contained propagates upward, so a change inside one message can force the entire column to be measured again.",+ "None of this is visible on a short thread, which is why the fixture here is sized in characters rather than in messages.",+];++function prose(index: number, targetChars: number): string {+ const parts: string[] = [`Reply ${index}.`];+ let length = parts[0].length;+ let cursor = index;+ while (length < targetChars) {+ const sentence = PROSE_SENTENCES[cursor % PROSE_SENTENCES.length];+ parts.push(`${sentence} (paragraph ${cursor - index + 1} of reply ${index})`);+ length += parts[parts.length - 1].length + 2;+ cursor += 1;+ }+ return parts.join("\n\n");+}++function pythonFence(index: number, targetChars: number): string {+ const lines = [+ "```python",+ `# reply ${index}: a batch scorer, long enough that the highlighter has real work to do`,+ "from dataclasses import dataclass",+ "",+ "@dataclass",+ `class Row${index}:`,+ " weight: float",+ " count: int",+ " label: str",+ "",+ ];+ let step = 0;+ while (lines.join("\n").length < targetChars) {+ lines.push(+ `def score_${index}_${step}(rows: list[Row${index}]) -> float:`,+ ` """Step ${step} of reply ${index}: sum the weighted counts, skipping the empties."""`,+ " total = 0.0",+ " for row in rows:",+ ` if row.count == 0 or row.label == "skip-${step}":`,+ " continue",+ ` total += row.weight * row.count * {0}.{1}`.replace("{0}", String(step + 1)).replace("{1}", String((index * 7 + step) % 97)),+ " return total",+ "",+ );+ step += 1;+ }+ lines.push("```");+ return lines.join("\n");+}++function typescriptFence(index: number, targetChars: number): string {+ const lines = [+ "```typescript",+ `// reply ${index}: the client half, so the fixture is not one grammar repeated`,+ `export interface Row${index} {`,+ " readonly weight: number;",+ " readonly count: number;",+ " readonly label: string;",+ "}",+ "",+ ];+ let step = 0;+ while (lines.join("\n").length < targetChars) {+ lines.push(+ `export function score${index}_${step}(rows: readonly Row${index}[]): number {`,+ " let total = 0;",+ " for (const row of rows) {",+ ` if (row.count === 0 || row.label === "skip-${step}") continue;`,+ ` total += row.weight * row.count * ${step + 1}.${(index * 5 + step) % 89};`,+ " }",+ " return total;",+ "}",+ "",+ );+ step += 1;+ }+ lines.push("```");+ return lines.join("\n");+}++function jsonFence(index: number, targetChars: number): string {+ // One very long line on purpose. A single-line document is the shape that behaves worst in a+ // highlighter and in any code that scans for line boundaries.+ const entries: string[] = [];+ let step = 0;+ let body = "";+ while (body.length < targetChars) {+ entries.push(+ `{"id":"row-${index}-${step}","weight":${(step % 17) + 0.5},"count":${step * 3 + index},"label":"batch-${index}-${step}"}`,+ );+ body = `{"reply":${index},"rows":[${entries.join(",")}]}`;+ step += 1;+ }+ return ["```json", body, "```"].join("\n");+}++function htmlArtifact(index: number, targetChars: number): string {+ // A full document, which is what Studio treats as an artifact rather than as a code block,+ // and it draws on a <canvas> so the fixture carries the shape users call a canvas artifact.+ const head = [+ "<!doctype html>",+ "<html>",+ " <head>",+ ` <title>Reply ${index} canvas</title>`,+ " <style>",+ " body { margin: 0; font-family: system-ui, sans-serif; background: #101014; color: #f4f4f5; }",+ " canvas { display: block; width: 100%; height: 240px; }",+ " </style>",+ " </head>",+ " <body>",+ ` <canvas id="plot-${index}" width="640" height="240"></canvas>`,+ " <script>",+ ` const ctx = document.getElementById("plot-${index}").getContext("2d");`,+ ];+ const tail = [" </script>", " </body>", "</html>"];+ const body: string[] = [];+ let step = 0;+ while ([...head, ...body, ...tail].join("\n").length < targetChars) {+ body.push(+ ` ctx.fillStyle = "hsl(${(index * 31 + step * 7) % 360}, 70%, 55%)";`,+ ` ctx.fillRect(${step * 12}, ${(step * 5) % 200}, 10, ${20 + (step % 40)});`,+ );+ step += 1;+ }+ return ["```html", ...head, ...body, ...tail, "```"].join("\n");+}++function svgFence(index: number, targetChars: number): string {+ // Studio renders a highlighted fence AND an inline <img> preview for an svg fence, so this one+ // block buys both a Shiki pass and an image decode. No <script>, no on*= handlers, no+ // <foreignObject>: any of those make the preview refuse to render and the block silently+ // becomes an ordinary code fence.+ const open = [`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 160" width="320" height="160">`];+ const close = ["</svg>"];+ const body: string[] = [];+ let step = 0;+ while ([...open, ...body, ...close].join("\n").length < targetChars) {+ body.push(+ ` <rect x="${(step * 9) % 300}" y="${(step * 6) % 140}" width="14" height="${8 + (step % 40)}" fill="hsl(${(index * 23 + step * 11) % 360}, 65%, 55%)" />`,+ );+ step += 1;+ }+ return ["```svg", ...open, ...body, ...close, "```"].join("\n");+}++function pythonScript(index: number, targetChars: number): string {+ const lines = [`# tool script for block ${index}`, "import json", ""];+ let step = 0;+ while (lines.join("\n").length < targetChars) {+ lines.push(+ `rows_${step} = [{"weight": ${step + 1}, "count": ${index + step}}]`,+ `print(json.dumps({"step": ${step}, "total": sum(r["weight"] * r["count"] for r in rows_${step})}))`,+ );+ step += 1;+ }+ return lines.join("\n");+}++function toolOutput(index: number, targetChars: number): string {+ const lines: string[] = [];+ let step = 0;+ while (lines.join("\n").length < targetChars) {+ lines.push(+ `[block ${index}] step ${step}: processed ${step * 128 + index} rows, ${((step * 37) % 100) / 10} MB resident`,+ );+ step += 1;+ }+ return lines.join("\n");+}++function bashOutput(index: number, targetChars: number): string {+ const lines: string[] = [`total ${index * 4 + 12}`];+ let step = 0;+ while (lines.join("\n").length < targetChars) {+ lines.push(+ `-rw-r--r-- 1 unsloth staff ${step * 733 + index} Jan ${(step % 28) + 1} 09:${String((step * 7) % 60).padStart(2, "0")} shard-${index}-${step}.safetensors`,+ );+ step += 1;+ }+ return lines.join("\n");+}++// 64x64 RGB PNG, 288 bytes. A real raster decode rather than a 1x1 placeholder, and small enough+// that its data URL does not dominate the character budget it is counted against.+const PNG_DATA_URL =+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAA50lEQVR42u3PkVIlAABA0VcTBEEQBEGwECwEQRAEwUIQBAtBEARBEFwIgiAIgiAIFoIgCIIgWFi4EARBEARBEAQLQdBXBM3cmfMDZzDAERzFMRzHCZzEKZzGHziDP3EW53AeF3ARl/AXLuMKruJvXMN13MBN3MJt3EFwF/dwHw/wEI/wGE/wFP/gGZ7jBV7iFV7jDf7Ffyje4h3e4wM+4hM+4wu+4hv+x3f8wOHB8NC3VqBAgQIFChQoUKBAgQIFChQoUKBAgQIFChQoUKBAgQIFChQoUKBAgQIFChQoUKBAgQIFCny9T1mrnz8ZmAtoAAAAAElFTkSuQmCC";++const pngCache = new Map<number, string>();++/**+ * A PNG that is unique to this block, so each one is a separate decode rather than a cache hit+ * on the last.+ *+ * Drawn and exported here rather than embedded as a literal because assistant-ui only accepts+ * `data:image/(png|jpeg|jpg|gif|webp);base64,` for an image part and drops anything else with a+ * console warning -- an SVG data URL, which would have been the easy way to vary the bytes, is+ * silently discarded.+ */+function pngDataUrl(index: number): string {+ const cached = pngCache.get(index);+ if (cached !== undefined) return cached;+ let url = PNG_DATA_URL;+ try {+ const canvas = document.createElement("canvas");+ canvas.width = 96;+ canvas.height = 64;+ const ctx = canvas.getContext("2d");+ if (ctx) {+ ctx.fillStyle = `hsl(${(index * 47) % 360}, 60%, 40%)`;+ ctx.fillRect(0, 0, 96, 64);+ ctx.fillStyle = `hsl(${(index * 91) % 360}, 70%, 65%)`;+ ctx.beginPath();+ ctx.arc(24 + (index % 48), 34, 18, 0, Math.PI * 2);+ ctx.fill();+ ctx.fillStyle = "#ffffff";+ ctx.font = "12px sans-serif";+ ctx.fillText(`block ${index}`, 6, 16);+ url = canvas.toDataURL("image/png");+ }+ } catch {+ url = PNG_DATA_URL;+ }+ pngCache.set(index, url);+ return url;+}++// ── the cycle ───────────────────────────────────────────────────────++type Part = NonNullable<Exclude<ThreadMessageLike["content"], string>>[number];++/** One block: the user's prompt and the assistant messages it produced. */+type Block = { user: string; assistant: ThreadMessageLike[] };++function textPart(text: string): Part {+ return { type: "text", text };+}++const KIND_COUNT = 10;++function buildBlock(index: number): Block {+ const kind = index % KIND_COUNT;+ const ask = `Prompt ${index}. Walk me through step ${index} of the batch scorer, and show the code and the run.`;+ switch (kind) {+ case 0:+ return { user: ask, assistant: [{ role: "assistant", content: [textPart(prose(index, 2600))] }] };+ case 1:+ return {+ user: ask,+ assistant: [+ {+ role: "assistant",+ content: [+ textPart(+ `${prose(index, 300)}\n\n${pythonFence(index, 2900)}\n\nThat is the scoring half.`,+ ),+ ],+ },+ ],+ };+ case 2:+ return {+ user: ask,+ assistant: [+ {+ role: "assistant",+ content: [+ textPart(+ `${prose(index, 300)}\n\n${typescriptFence(index, 2900)}\n\nAnd the client half.`,+ ),+ ],+ },+ ],+ };+ case 3:+ // python is one of the two tools the renderer never folds into a tool GROUP, so its card+ // stays a top-level collapsible even when it sits next to other calls.+ return {+ user: ask,+ assistant: [+ {+ role: "assistant",+ content: [+ textPart(`Running it now for block ${index}.`),+ {+ type: "tool-call",+ toolCallId: `heavy-python-${index}`,+ toolName: "python",+ args: { code: pythonScript(index, 900) },+ // All three keys, or the card falls back to stringifying the whole object.+ // `images` stays empty: a non-empty list makes the card fetch each one from a+ // backend this page does not have.+ result: { text: toolOutput(index, 1400), images: [], sessionId: `heavy-${index}` },+ },+ ],+ },+ ],+ };+ case 4:+ // No text part in this message on purpose. CodeExecutionToolUI is a CONTROLLED collapsible+ // that force-closes itself as soon as its message carries text, so a card with prose beside+ // it cannot be held open for the measurement.+ return {+ user: ask,+ assistant: [+ {+ role: "assistant",+ content: [+ {+ type: "tool-call",+ toolCallId: `heavy-bash-${index}`,+ toolName: "code_execution",+ args: { kind: "bash", command: `ls -la /workspace/shards/block-${index}` },+ result: bashOutput(index, 1700),+ },+ ],+ },+ ],+ };+ case 5:+ return {+ user: ask,+ assistant: [+ {+ role: "assistant",+ content: [+ textPart(+ `Here is the preview for block ${index}.\n\n${htmlArtifact(index, 2400)}\n\nOpen it to see the plot.`,+ ),+ ],+ },+ ],+ };+ case 6:+ return {+ user: ask,+ assistant: [+ {+ role: "assistant",+ content: [+ textPart(`Rendering the canvas for block ${index}.`),+ {+ type: "tool-call",+ toolCallId: `heavy-canvas-${index}`,+ toolName: "render_html",+ args: {+ title: `Block ${index} canvas`,+ code: htmlArtifact(index, 2300).replace(/^```html\n/, "").replace(/\n```$/, ""),+ },+ result: `Rendered HTML canvas for block ${index}`,+ },+ ],+ },+ ],+ };+ case 7:+ return {+ user: ask,+ assistant: [+ {+ role: "assistant",+ content: [+ textPart(`A diagram for block ${index}.\n\n${svgFence(index, 1500)}`),+ ],+ },+ ],+ };+ case 8:+ return {+ user: ask,+ assistant: [+ {+ role: "assistant",+ content: [+ textPart(`Two attachments for block ${index}: a rendered plot and a chart.`),+ // One repeated attachment and one that is unique to this block: a thread has both,+ // and only the second is a fresh decode every time.+ { type: "image", image: PNG_DATA_URL },+ { type: "image", image: pngDataUrl(index) },+ textPart(prose(index, 400)),+ ],+ },+ ],+ };+ default:+ return {+ user: ask,+ assistant: [+ {+ role: "assistant",+ content: [+ textPart(`The raw rows for block ${index}.\n\n${jsonFence(index, 2700)}`),+ ],+ },+ ],+ };+ }+}++function partChars(part: Part): number {+ const anyPart = part as Record<string, unknown>;+ if (anyPart.type === "text") return String(anyPart.text ?? "").length;+ if (anyPart.type === "image") return String(anyPart.image ?? "").length;+ if (anyPart.type === "tool-call") {+ return (+ JSON.stringify(anyPart.args ?? {}).length ++ (typeof anyPart.result === "string"+ ? anyPart.result.length+ : JSON.stringify(anyPart.result ?? "").length)+ );+ }+ return 0;+}++function messageChars(message: ThreadMessageLike): number {+ if (typeof message.content === "string") return message.content.length;+ return message.content.reduce((total, part) => total + partChars(part as Part), 0);+}++type Plan = {+ chars: number;+ messages: number;+ blocks: number;+ cycles: number;+ kinds: number;+ cycleChars: number;+ expectedPerCycle: Record<string, number>;+};++/**+ * What one cycle must put on screen. The Python side multiplies these by the cycle count and+ * fails the run if the DOM holds fewer.+ *+ * This is not belt and braces. assistant-ui drops an image part whose data URL is not+ * `data:image/(png|jpeg|jpg|gif|webp);base64,` with nothing but a console.warn, and a fixture+ * that quietly loses its images still renders 300K characters of prose and code and still+ * produces a rising curve -- of the wrong thing.+ */+const EXPECTED_PER_CYCLE: Record<string, number> = {+ // Two image parts in the image block, plus the inline preview the svg fence renders.+ images: 3,+ // The python card and the code_execution card. render_html renders an artifact card instead.+ toolParts: 2,+ collapsibleOutputs: 2,+ codeExecutionPanes: 2,+ // The full ```html document and the render_html tool call.+ artifactCards: 2,+ // python, typescript, json, svg, the html document, and the two tool result panes.+ codeBlocks: 7,+ // Shiki is async and per block, so a <pre> exists long before it is highlighted. A floor under+ // the token count is what tells a finished thread apart from one still building itself; a+ // settled-looking count of 577 against the 3216 a whole cycle produces is a real measured+ // failure of the naive "it stopped moving" gate.+ highlightedTokens: 2500,+};++/**+ * Whole cycles of one block per kind until `targetChars` is reached, never fewer than one.+ *+ * Whole cycles, not "blocks until the budget runs out": a partial cycle would give the smallest+ * size only the first few kinds of content, so the curve across sizes would be reporting a change+ * of fixture as well as a change of size.+ */+function buildThread(targetChars: number): { messages: ThreadMessageLike[]; plan: Plan } {+ const messages: ThreadMessageLike[] = [];+ let chars = 0;+ let cycles = 0;+ let blocks = 0;+ let cycleChars = 0;+ do {+ const cycleStart = chars;+ for (let k = 0; k < KIND_COUNT; k += 1) {+ const block = buildBlock(blocks);+ const user: ThreadMessageLike = { role: "user", content: [textPart(block.user)] };+ messages.push(user, ...block.assistant);+ chars += messageChars(user);+ for (const message of block.assistant) chars += messageChars(message);+ blocks += 1;+ }+ cycles += 1;+ if (cycleChars === 0) cycleChars = chars - cycleStart;+ } while (chars < targetChars);+ return {+ messages,+ plan: {+ chars,+ messages: messages.length,+ blocks,+ cycles,+ kinds: KIND_COUNT,+ cycleChars,+ expectedPerCycle: EXPECTED_PER_CYCLE,+ },+ };+}++// A run would need a backend. Seeding goes through `thread.import`, which does not use this.+const NEVER_RUNS: ChatModelAdapter = {+ run: () => {+ throw new Error("smoke-heavy-thread does not run the model");+ },+};++function HeavyThreadApi({+ mounted,+ setMounted,+}: {+ mounted: boolean;+ setMounted: (value: boolean) => void;+}): null {+ const aui = useAui();+ // What seed() last built. The delete action removes a message from the REPOSITORY, so without+ // a way to put it back every repetition after the first measures a shorter thread than the one+ // the harness took its census of.+ const seeded = useRef<ThreadMessageLike[]>([]);++ useEffect(() => {+ const api = {+ /** Replace the thread with whole cycles of content until `targetChars` is reached. */+ seed(targetChars: number): Plan {+ const built = buildThread(targetChars);+ seeded.current = built.messages;+ aui.thread().import(ExportedMessageRepository.fromArray(built.messages));+ return built.plan;+ },+ /**+ * Like seed(), then N one-word messages after it. Used by the viewport-gap measurement in+ * #9058: the tail makes the first mount commit land entirely on compact rows, which is the+ * worst case for a fixed-size initial window.+ *+ * It REPLACES rather than appends, and the heavy part is the same buildThread() call seed()+ * makes, so every census count for `targetChars` is identical to seed(targetChars). The only+ * difference is the tail, which is text parts only: no fences, images or tool calls.+ */+ seedCompactTail(targetChars: number, tailMessages: number): Plan {+ const built = buildThread(targetChars);+ const messages = built.messages.slice();+ const SHORT = ["ok", "thanks", "yes", "got it", "sure", "nice"];+ for (let i = 0; i < tailMessages; i += 1) {+ messages.push({+ role: i % 2 === 0 ? "user" : "assistant",+ content: [textPart(SHORT[i % SHORT.length])],+ });+ }+ seeded.current = messages;+ aui.thread().import(ExportedMessageRepository.fromArray(messages));+ return { ...built.plan, messages: messages.length };+ },+ /**+ * The empty band below the last mounted row, in px.+ *+ * gapBottom is measured against the viewport's BOTTOM EDGE, not against scrollHeight, so the+ * viewport's own bottom spacer counts as the gap it always was and the caller subtracts+ * spacerHeight to get the part the mount window is responsible for. Computed any other way+ * the numbers stop being comparable across sizes.+ */+ gapMetrics(): Record<string, number> {+ const element = api.viewport();+ if (!element) return { ok: 0 };+ const clientHeight = element.clientHeight;+ const rows = Array.from(element.querySelectorAll<HTMLElement>("[data-role]"));+ if (rows.length === 0) return { ok: 0, mountedRows: 0, clientHeight };+ const box = element.getBoundingClientRect();+ const first = rows[0].getBoundingClientRect();+ const last = rows[rows.length - 1].getBoundingClientRect();+ const spacer = element.querySelector<HTMLElement>(+ ':scope > [aria-hidden="true"].shrink-0',+ );+ const scrollHeight = element.scrollHeight;+ return {+ ok: 1,+ mountedRows: rows.length,+ clientHeight,+ scrollHeight,+ scrollTop: Math.round(element.scrollTop),+ maxScrollTop: Math.round(scrollHeight - clientHeight),+ mountedHeight: Math.round(last.bottom - first.top),+ gapTop: Math.round(first.top - box.top),+ gapBottom: Math.round(box.bottom - last.bottom),+ spacerHeight: spacer ? Math.round(spacer.getBoundingClientRect().height) : 0,+ };+ },+ /**+ * Put the seeded thread back, and answer with how many messages that is.+ *+ * Deleting a message is destructive to the repository, not to the view, so re-opening does+ * not undo it. Restoring is the same import seed() does: cheap on the harness side, and it+ * is untimed, but every timed repetition then runs on the same fixture rather than on a+ * thread that is one message shorter each time round.+ */+ restore(): number {+ aui.thread().import(ExportedMessageRepository.fromArray(seeded.current));+ return seeded.current.length;+ },+ /**+ * Open every tool card. Radix unmounts collapsed content, so a thread of closed cards+ * carries no result panes at all and the "tool calls with collapsible output" half of the+ * fixture would be a row of buttons. A user who has just watched those tools run is+ * looking at them open, which is the state worth measuring.+ */+ expandTools(): number {+ const triggers = Array.from(+ document.querySelectorAll<HTMLElement>('[data-slot="tool-fallback-trigger"]'),+ );+ for (const trigger of triggers) {+ if (trigger.getAttribute("data-state") !== "open") trigger.click();+ }+ return triggers.length;+ },+ /** Leave the thread. The runtime keeps the messages; the view is torn down. */+ closeThread(): void {+ setMounted(false);+ },+ /** Come back to it, which rebuilds every message from nothing. */+ openThread(): void {+ setMounted(true);+ },+ isOpen(): boolean {+ return mounted;+ },+ /**+ * One selector pass. Polling for a deletion has to read this, not counts(): counts() is a+ * dozen document-wide queries including a walk of every element, so at 300K characters a+ * poll loop built on it would spend more time measuring than the delete itself takes.+ */+ messageCount(): number {+ return document.querySelectorAll("[data-role]").length;+ },+ /** Highlighted tokens. Shiki runs after the <pre> exists, so counting <pre> gates nothing. */+ highlightedTokenCount(): number {+ return document.querySelectorAll("pre code span").length;+ },+ /**+ * Everything a caller might use to prove the fixture landed. A harness that asks for 300K+ * characters of mixed content and silently renders 200K of prose measures the wrong thing,+ * so the Python side prints every one of these and fails on any that is zero.+ */+ counts(): Record<string, number> {+ return {+ messages: document.querySelectorAll("[data-role]").length,+ assistantMessages: document.querySelectorAll('[data-role="assistant"]').length,+ userMessages: document.querySelectorAll('[data-role="user"]').length,+ domNodes: document.getElementsByTagName("*").length,+ codeBlocks: document.querySelectorAll("pre").length,+ highlightedTokens: document.querySelectorAll("pre code span").length,+ toolParts: document.querySelectorAll(".aui-tool-fallback-root").length,+ // The collapsible CONTENT ELEMENT, which Radix keeps in the tree for its collapse+ // animation. It is present whether the card is open or shut, so it counts cards, not+ // visible panes: measured at 25000 chars it reads 2 with every card closed and 2 again+ // after expandTools(). Do NOT gate a wait on this; such a gate is satisfied by a thread+ // of closed cards and cannot fail. Use codeExecutionPanes, which is 0 then 2.+ collapsibleOutputs: document.querySelectorAll(+ '[data-slot="tool-fallback-content"]',+ ).length,+ codeExecutionPanes: document.querySelectorAll(+ '[data-slot="tool-fallback-content"] pre',+ ).length,+ // ArtifactCard carries no class of its own; the accessible name is its stable handle.+ artifactCards: document.querySelectorAll('button[aria-label^="Open "]').length,+ images: document.querySelectorAll("img").length,+ katexNodes: document.querySelectorAll(".katex").length,+ actionBars: document.querySelectorAll(".aui-assistant-action-bar-root").length,+ tooltipTriggers: document.querySelectorAll('[data-slot="tooltip-trigger"]').length,+ };+ },+ viewportMetrics(): { scrollHeight: number; scrollTop: number; clientHeight: number } {+ const element = api.viewport();+ if (!element) return { scrollHeight: -1, scrollTop: -1, clientHeight: -1 };+ return {+ scrollHeight: element.scrollHeight,+ scrollTop: element.scrollTop,+ clientHeight: element.clientHeight,+ };+ },+ viewport(): HTMLElement | null {+ return document.querySelector<HTMLElement>(".aui-thread-viewport");+ },+ composer(): HTMLTextAreaElement | null {+ return document.querySelector<HTMLTextAreaElement>(".aui-composer-input");+ },+ /**+ * What the RUNTIME thinks the composer holds. Reading the textarea back instead would only+ * echo the value the caller just wrote, so a keystroke that never reached React would still+ * look like it landed.+ */+ composerText(): string {+ return aui.composer().getState().text;+ },+ /** Items in the open action menu. An empty popover satisfies "the menu opened". */+ openMenuItemCount(): number {+ return document.querySelectorAll(".aui-action-bar-more-item").length;+ },+ lastAssistantMessage(): HTMLElement | null {+ const messages = document.querySelectorAll<HTMLElement>('[data-role="assistant"]');+ return messages[messages.length - 1] ?? null;+ },+ /**+ * The last assistant message's action-bar button with accessible name `label`.+ * TooltipIconButton puts that name in an `sr-only` span rather than an aria-label, so this+ * matches on text and stays correct if the styling classes are renamed.+ */+ actionButton(label: string): HTMLButtonElement | null {+ const last = api.lastAssistantMessage();+ if (!last) return null;+ const buttons = Array.from(last.querySelectorAll("button"));+ return buttons.find((button) => (button.textContent ?? "").trim() === label) ?? null;+ },+ };+ (window as unknown as { __heavyThread: typeof api }).__heavyThread = api;+ }, [aui, mounted, setMounted]);++ return null;+}++function Harness(): ReactElement {+ const runtime = useLocalRuntime(NEVER_RUNS);+ // The runtime lives outside this flag, so unmounting Thread leaves the messages intact. That is+ // what re-opening a thread costs: the view is rebuilt, the data is not re-fetched.+ const [mounted, setMounted] = useState(true);+ return (+ <TooltipProvider>+ <AssistantRuntimeProvider runtime={runtime}>+ <HeavyThreadApi mounted={mounted} setMounted={setMounted} />+ {/* Thread is flex-1 basis-0 min-h-0, so it needs a bounded flex parent to scroll. */}+ <div+ data-smoke="heavy-thread"+ style={{ display: "flex", flexDirection: "column", height: "100vh" }}+ >+ {mounted ? <Thread hideWelcome={true} /> : null}+ </div>+ </AssistantRuntimeProvider>+ </TooltipProvider>+ );+}++// Thread reaches useNavigate (the fork action, the composer tools menu). Without a router in+// context tanstack's useRouter still works, but console.warns on every render of every action+// bar, which scales with the thread and is serialised over the debugging channel. A memory router+// with one route removes that without pulling in the app shell.+const rootRoute = createRootRoute({ component: Harness });+const router = createRouter({+ routeTree: rootRoute,+ history: createMemoryHistory({ initialEntries: ["/"] }),+});++const root = document.getElementById("root");+if (!root) {+ throw new Error("missing #root");+}+createRoot(root).render(<RouterProvider router={router as unknown as never} />);diff --git a/studio/frontend/smoke-heavy-thread.html b/studio/frontend/smoke-heavy-thread.htmlnew file mode 100644index 00000000000..86c1642dc5e--- /dev/null+++ b/studio/frontend/smoke-heavy-thread.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <script src="/crypto-boot.js"></script>+ <title>heavy thread smoke</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/smoke-heavy-thread-main.tsx"></script>+ </body>+</html>diff --git a/studio/frontend/tsconfig.app.json b/studio/frontend/tsconfig.app.jsonindex 7bec599ac3b..b9521f0efe5 100644--- a/studio/frontend/tsconfig.app.json+++ b/studio/frontend/tsconfig.app.json@@ -33,6 +33,7 @@"smoke-ansi-main.tsx","smoke-autoscroll-main.tsx","smoke-research-main.tsx",+ "smoke-heavy-thread-main.tsx","smoke-settings-main.tsx","smoke-stream-pacing-main.tsx"]diff --git a/tests/studio/playwright_heavy_thread.py b/tests/studio/playwright_heavy_thread.pynew file mode 100644index 00000000000..3fe72d3758b--- /dev/null+++ b/tests/studio/playwright_heavy_thread.py@@ -0,0 +1,1863 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Where a HEAVY thread stalls, as a curve over how much content the thread holds.++Users report Studio and Desktop going sluggish "after long generations with any code cells+and/or text": typing, scrolling, opening a message menu, deleting and re-opening the thread all+lag once a session has accumulated a few very long replies. That report is about CONTENT VOLUME,+not message count, so the axis here is characters of thread content, not messages, and the+fixture is the mix the report names rather than one paragraph repeated:++ long prose, several large code fences, tool calls with collapsible output, an HTML artifact,+ a code-execution result pane, an HTML canvas artifact and inline images.++studio/frontend/smoke-heavy-thread.html mounts the REAL Thread with that content, so what is+timed is the app's own renderer.++WHAT IS MEASURED, AND WHY THESE METRICS++Every primary number here is DOM-observable and wall-clock, because the interesting engines are+not Chromium. Unsloth Desktop is Tauri: WebView2 on Windows, WKWebView on macOS, WebKitGTK on+Linux. The Long Tasks API does not exist on JavaScriptCore, so a `longtask` PerformanceObserver+silently reports NOTHING on Desktop macOS and Desktop Linux. Measured here: on WebKit 26.5 and+Firefox 153 the `observe({ type: "longtask" })` call does not even throw. It is accepted and then+never fires, which reads as "no jank" instead of "no measurement", so support is read from+`PerformanceObserver.supportedEntryTypes` instead. `Performance.getMetrics` and+`Emulation.setCPUThrottlingRate` are CDP, so they do not exist off Chromium either.++So the primary four, all portable:++ longest stall ms the largest gap between consecutive ticks of a 1ms setTimeout loop. This+ is the portable stand-in for a long task: the main thread cannot answer+ the timer while it is busy, so the gap IS the block. Accurate to the+ timer clamp (~4ms), which is far below anything a user notices.+ worst frame ms the largest gap between consecutive requestAnimationFrame callbacks.+ frames over 33ms how many frames in the action missed two vsyncs at 60Hz. A single worst+ frame can be an outlier; a count says how much of the gesture was rough.+ wall ms how long the action took end to end, and for the gestures that keep+ working after the input stops, a separate settle time.++A MessageChannel ping-pong is the usual way to build the stall detector and it was measured and+rejected here: it spins ~150k times a second, and on Firefox that HALVED the frame rate of the+page under test (38 frames -> 14, median frame 17ms -> 34ms) before any Studio code ran. The+1ms setTimeout loop ticks ~150 times a second, costs nothing measurable on any of the three+engines, and reported the same 120ms synthetic stall on all three.++CDP counters (LayoutCount, RecalcStyleCount, LayoutDuration, RecalcStyleDuration, TaskDuration)+and the longtask observer are ALSO recorded, and every one of them is labelled CHROMIUM-ONLY in+the table. They attribute cost to layout versus script, which nothing portable does. They are+never the headline.++ENGINES++ chromium proxy for WebView2, i.e. Unsloth Desktop on Windows.+ webkit proxy for WKWebView and WebKitGTK, i.e. Unsloth Desktop on macOS and Linux.+ firefox control. Not shipped by anything here; it is in the table so that a number which+ moves on one engine only can be told apart from a number that moves everywhere.++Playwright's WebKit is a PROXY, not the webview Desktop embeds. It is Apple's WebKit built for+Playwright, driven headless, with no Tauri IPC layer and no WebKitGTK compositor. Read it as+"JavaScriptCore plus WebKit layout", not as "Unsloth Desktop on macOS".++Desktop Linux under Wayland is WORSE than any number this file can produce, and not by a little:+studio/src-tauri/src/linux_webkit.rs sets WEBKIT_DMABUF_RENDERER_FORCE_SHM=1, which forces the+software rendering transport. Everything below runs on a normal compositor path.++THIS HARNESS MEASURES, IT DOES NOT GATE. It prints the table and exits 0 on any timing. It exits+non-zero only when the harness itself is broken: the seed did not land, an element it drives went+missing, or the curve did not rise with content -- which would mean it is measuring nothing.+Budgets belong in a later change, set from numbers taken on real hardware.++Run:+ python tests/studio/playwright_heavy_thread.py+ SMOKE_HEAVY_CHARS=100000,300000 SMOKE_HEAVY_ENGINES=chromium python tests/studio/playwright_heavy_thread.py++It starts and stops its own vite dev server. Point it at one you already have with+SMOKE_BASE_URL, or move the port it picks with SMOKE_PORT.++RUN ONE ENGINE PER INVOCATION IN CI, UNDER AN EXTERNAL TIMEOUT. Measured on a macos-14 runner:+Chromium finished all three sizes in 90 seconds, and then Playwright's WebKit wedged at the+smallest size and never came back. `page.evaluate` and `browser.new_page` have no timeout of+their own, and a SIGALRM does not help, because Playwright's sync API blocks the main thread+inside a greenlet and the exception lands in the driver rather than in the caller. The only+bound that works is the process one, so drive the engines as separate invocations:++ bounded() { # not `timeout`: macOS runners do not ship coreutils, and+ local secs=$1; shift # `timeout: command not found` fails the step instantly+ "$@" & local pid=$!+ ( sleep "$secs"; kill -TERM $pid 2>/dev/null; sleep 15; kill -KILL $pid 2>/dev/null ) &+ local watcher=$!+ wait $pid; local rc=$?+ kill -TERM $watcher 2>/dev/null+ return $rc+ }+ port=5215+ for engine in chromium webkit firefox; do+ SMOKE_HEAVY_ENGINES=$engine SMOKE_PORT=$port SMOKE_LABEL=run-$engine \\+ bounded 1800 python -u tests/studio/playwright_heavy_thread.py \\+ || echo "$engine did not finish"+ port=$((port + 1))+ done++One wedged engine then costs one engine's column instead of the whole matrix. Each invocation+needs its own port: a killed run can leave its vite dev server holding the previous one.++The dev server is deliberate and is a limitation to read the numbers against: React runs in+development mode, nothing is minified, and vite serves unbundled modules. Absolute milliseconds+are therefore higher than a packaged Studio's. The curve across sizes and the ranking across+actions are what this file is for.+"""++from __future__ import annotations++import json+import os+import re+import sys+from pathlib import Path++from playwright.sync_api import sync_playwright++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _playwright_robust import ( # noqa: E402+ chromium_launch_args,+ start_vite,+ stop_process,+ wait_for_smoke_page,+)++PORT = int(os.environ.get("SMOKE_PORT", "5215"))+# Exported-but-empty counts as unset, else we skip the server and drive "" as the URL.+# rstrip("/"): a trailing slash makes the anchored /api/ route regex below never match, silently+# turning the stubbed fan-out back into live HTTP.+_EXTERNAL = os.environ.get("SMOKE_BASE_URL", "").strip().rstrip("/")+BASE = _EXTERNAL or f"http://127.0.0.1:{PORT}"+OWNS_SERVER = not _EXTERNAL+LABEL = os.environ.get("SMOKE_LABEL", "tree")+OUT = Path(os.environ.get("PW_ART_DIR", "logs/playwright-heavy-thread"))+OUT.mkdir(parents = True, exist_ok = True)++# Characters of thread content, not messages. Sorted: the growth check reads the first and last+# entries as smallest and largest, so an unsorted override would invert every ratio and report a+# good run as measuring nothing.+SIZES = sorted(+ int(n) for n in os.environ.get("SMOKE_HEAVY_CHARS", "25000,100000,300000").split(",")+)+ENGINES = [+ e.strip()+ for e in os.environ.get("SMOKE_HEAVY_ENGINES", "chromium,webkit,firefox").split(",")+ if e.strip()+]+# Every action set is run this many times on the seeded page and the table reports the MEDIAN.+# The first repetition is systematically the slowest (cold Shiki cache, cold layout), which is+# exactly why the headline is a median rather than a mean or a single shot.+REPEATS = int(os.environ.get("SMOKE_HEAVY_REPEATS", "3"))+# Chromium only, and off by default. Throttling is a CDP feature, so switching it on makes the+# chromium column incomparable with the other two.+CPU_THROTTLE_RATE = float(os.environ.get("SMOKE_CPU_THROTTLE", "1"))++KEYSTROKES = int(os.environ.get("SMOKE_KEYSTROKES", "5"))+SCROLL_STEPS = int(os.environ.get("SMOKE_SCROLL_STEPS", "20"))+SCROLL_STEP_PX = int(os.environ.get("SMOKE_SCROLL_STEP_PX", "400"))+SEED_TIMEOUT_MS = int(os.environ.get("SMOKE_SEED_TIMEOUT_MS", "300000"))+ACTION_TIMEOUT_MS = int(os.environ.get("SMOKE_ACTION_TIMEOUT_MS", "120000"))+# How long an in-page action waits for the DOM to reach the state it asked for. This bounds an+# action that never happened and nothing else, so it has to stay well above the slowest honest+# measurement or a very slow open is reported as "never opened".+SETTLE_TIMEOUT_MS = int(os.environ.get("SMOKE_SETTLE_TIMEOUT_MS", "120000"))+# How long the highlighter has to stay still before a re-open counts as finished. Four polls of+# the 250ms interval wait_for_highlighting_settled() uses, because that is what was MEASURED to be+# needed: a gate that released after one 250ms lull released mid-rebuild. The grace is not charged+# to the action -- quietUntilIdle() reports the time of the last activity, not of the timeout.+HIGHLIGHT_GRACE_MS = int(os.environ.get("SMOKE_HIGHLIGHT_GRACE_MS", "1000"))+# How often the settle loop is allowed to count highlighted tokens. It is a document-wide query,+# so per frame it would be an O(nodes) cost inside the region being timed, growing with the thread.+HIGHLIGHT_PROBE_MS = int(os.environ.get("SMOKE_HIGHLIGHT_PROBE_MS", "100"))+ACTIONS = ("keystroke", "scroll", "jump", "menu", "delete", "reopen")++# Installed into every page before anything else runs.+#+# The rAF wrapper COUNTS, it does not pump. Replacing rAF with a fixed timer -- which+# playwright_chat_autoscroll.py does on purpose, because it counts frames -- would destroy every+# time-to-paint number this file exists to read. The harness's own waits use the unwrapped+# reference, so __rafCount stays a count of the page's frames rather than of this file's.+RECORDER_INIT = """+(() => {+ const nativeRaf = window.requestAnimationFrame.bind(window);+ window.__nativeRaf = nativeRaf;+ window.__rafCount = 0;+ window.requestAnimationFrame = (cb) =>+ nativeRaf((t) => {+ window.__rafCount += 1;+ cb(t);+ });+ // Counted, because every one of these is a double rAF and therefore a ~33ms vsync floor inside+ // whatever is being timed across it. GROWTH_AXES used to declare that count by hand per axis+ // and defaulted it to 0 for every generated axis, which left the floor in both ends of those+ // ratios. begin() zeroes this and end() reports it, so a window's floor is measured rather+ // than asserted, and waits taken OUTSIDE a recorder window (ACTION_SETUPS, for one) are+ // excluded by construction rather than by remembering to exclude them.+ window.__paintWaits = 0;+ window.__nextPaint = () => {+ window.__paintWaits += 1;+ return new Promise((resolve) => nativeRaf(() => nativeRaf(() => resolve())));+ };++ // Chromium-only, recorded as a cross-check on the portable stall number and never as the+ // headline.+ //+ // Support is read from supportedEntryTypes, NOT from whether observe() throws. Measured on+ // this tree: PerformanceObserver.observe({ type: "longtask" }) throws on neither WebKit 26.5+ // nor Firefox 153 -- it is accepted and then never fires. A try/catch therefore reports both+ // as supported and both then report zero long tasks, which reads as "no jank on the engine+ // Unsloth Desktop ships on macOS and Linux" rather than as "this API does not exist there".+ // supportedEntryTypes lists `longtask` on Chromium alone.+ window.__longTasks = [];+ window.__longTaskSupported = Boolean(+ (PerformanceObserver.supportedEntryTypes || []).includes("longtask"),+ );+ if (window.__longTaskSupported) {+ try {+ new PerformanceObserver((list) => {+ for (const entry of list.getEntries()) {+ window.__longTasks.push({ start: entry.startTime, duration: entry.duration });+ }+ }).observe({ type: "longtask", buffered: true });+ } catch (e) {+ window.__longTaskSupported = false;+ }+ }++ const recorder = {+ running: false,+ // Which begin() a scheduled callback belongs to. `running` alone cannot answer that: when the+ // next action starts before the previous action's already-scheduled rAF has fired -- and it+ // does, because the actions are issued back to back over a CDP round trip that is shorter+ // than one frame -- that stale callback wakes to `running === true`, pushes the whole+ // between-action gap into the NEW arrays as if it were a frame, and schedules a second+ // recursive loop that then runs alongside the real one for the rest of the run. Measured on+ // the node harness in test_heavy_thread_measurement_integrity.py: without this token the+ // second action records the inter-action gap as its worst frame and counts double the frames.+ generation: 0,+ frames: [],+ stalls: [],+ // When each sample was taken, so end() can close the window at an earlier instant than the+ // one it was called at without the samples from after that instant still being in the arrays.+ frameAt: [],+ stallAt: [],+ startedAt: 0,+ begin() {+ this.running = true;+ this.generation += 1;+ const generation = this.generation;+ this.frames = [];+ this.stalls = [];+ this.frameAt = [];+ this.stallAt = [];+ this.startedAt = performance.now();+ window.__paintWaits = 0;+ let lastFrame = performance.now();+ const frame = () => {+ if (generation !== this.generation) return;+ const now = performance.now();+ this.frames.push(now - lastFrame);+ this.frameAt.push(now);+ lastFrame = now;+ if (this.running) nativeRaf(frame);+ };+ nativeRaf(frame);+ // 1ms setTimeout, not a MessageChannel ping-pong. Measured: the MessageChannel version+ // ticks ~150k/s and halves Firefox's frame rate before any app code runs; this one ticks+ // ~150/s and costs nothing on any engine. The clamp puts a ~4ms floor under the+ // resolution, which is far below any stall a user can feel.+ let lastStall = performance.now();+ const stall = () => {+ if (generation !== this.generation) return;+ const now = performance.now();+ this.stalls.push(now - lastStall);+ this.stallAt.push(now);+ lastStall = now;+ if (this.running) setTimeout(stall, 1);+ };+ setTimeout(stall, 1);+ },+ /**+ * Close the window. `untilMs` closes it at an earlier instant than "now" -- used by the+ * settle loops, which have to keep watching for a while after the page went quiet in order+ * to know that it stayed quiet, and must not charge that watching to the action.+ */+ end(untilMs) {+ this.running = false;+ // Retire this generation as well as stopping it, so the one callback already in flight+ // cannot append to the array a later begin() is about to hand out.+ this.generation += 1;+ const cutoff = untilMs === undefined ? Infinity : untilMs;+ const wallMs = (untilMs === undefined ? performance.now() : untilMs) - this.startedAt;+ // Trimmed, not just clocked: a settle loop that watches an idle page for another second+ // would otherwise add sixty fast frames to the count and drag median_frame_ms down with+ // them, at every size equally, which is the same constant-offset trap as the wall clock.+ const frames = this.frames.filter((_, i) => this.frameAt[i] <= cutoff);+ const stalls = this.stalls.filter((_, i) => this.stallAt[i] <= cutoff);+ const sorted = frames.slice().sort((a, b) => a - b);+ return {+ wall_ms: Math.round(wallMs * 10) / 10,+ // How many double-rAF waits this window was clocked across. Not trimmed to `cutoff`:+ // a wait after the cutoff still happened inside the window that produced wall_ms, and+ // wall_ms is the number this count is subtracted from.+ paint_waits: window.__paintWaits,+ frames: frames.length,+ // The first entry spans begin() to the first callback, so it is the wait for the next+ // vsync as much as a rendered frame. Kept: at these timescales it is ~16ms, well under+ // the 33ms threshold, and dropping it would also drop a genuine stall that landed there.+ worst_frame_ms: Math.round(Math.max(0, ...frames) * 10) / 10,+ median_frame_ms:+ sorted.length === 0 ? 0 : Math.round(sorted[Math.floor(sorted.length / 2)] * 10) / 10,+ frames_over_33: frames.filter((ms) => ms > 33).length,+ stall_ticks: stalls.length,+ longest_stall_ms: Math.round(Math.max(0, ...stalls) * 10) / 10,+ stalls_over_33: stalls.filter((ms) => ms > 33).length,+ };+ },+ /**+ * Time to settle, measured from the START of the action, not from the end of the input.+ *+ * Measured from the end of the gesture it reads ~50ms at every size on every engine, because+ * the answer is then "three frames", which is the minimum this loop can return. From the+ * start of the action it is what a user actually waits: the input, plus everything the page+ * does afterwards before it is calm again.+ */+ async quiet(timeoutMs) {+ const started = performance.now();+ let calm = 0;+ let last = performance.now();+ while (performance.now() - started < timeoutMs) {+ await new Promise((resolve) => nativeRaf(() => resolve()));+ const now = performance.now();+ calm = now - last > 33 ? 0 : calm + 1;+ last = now;+ if (calm >= 3) return performance.now() - this.startedAt;+ }+ return null;+ },+ /**+ * Settle for an action that also restarts the SYNTAX HIGHLIGHTER, which quiet() cannot see.+ *+ * quiet() declares an action settled after three sub-33ms frames. Shiki highlights each fence+ * on its own task, and the lull between two of those batches is longer than that -- the same+ * lull wait_for_highlighting_settled() exists for, where a two-read gate released at 577+ * highlighted tokens out of the 3216 a finished thread holds. So on re-open, which rebuilds+ * every fence from nothing, quiet() stops the clock partway through the rebuild.+ *+ * Settled here means: no frame over 33ms AND no new highlighted token, for graceMs.+ *+ * The returned time is the time of the LAST activity, not the time the grace window expired.+ * graceMs is a fixed cost that every size would pay equally, and a constant added to both+ * ends of a ratio drags it towards 1 -- the same trap the paint floor is subtracted for.+ *+ * `probe` counts highlighted tokens, which is a document-wide query, so it runs on an+ * INTERVAL and not once per frame. An O(nodes) query inside the window being timed would cost+ * more the bigger the thread is, which is to say it would grow like the signal -- the same+ * reason DELETE_JS polls isConnected on a captured node instead of re-counting [data-role].+ * The price is that the returned time is quantised to probeEveryMs, which is far below the+ * differences this axis exists to show.+ */+ async quietUntilIdle(timeoutMs, graceMs, probe, probeEveryMs) {+ const started = performance.now();+ let lastActivity = performance.now();+ let lastCount = probe();+ let lastProbeAt = performance.now();+ let last = performance.now();+ while (performance.now() - started < timeoutMs) {+ await new Promise((resolve) => nativeRaf(() => resolve()));+ const now = performance.now();+ let changed = false;+ if (now - lastProbeAt >= probeEveryMs) {+ const count = probe();+ changed = count !== lastCount;+ lastCount = count;+ lastProbeAt = now;+ }+ if (now - last > 33 || changed) lastActivity = now;+ last = now;+ if (now - lastActivity >= graceMs) {+ return { settleMs: lastActivity - this.startedAt, at: lastActivity };+ }+ }+ return { settleMs: null, at: performance.now() };+ },+ };+ window.__hv = recorder;+})();+"""+++def info(message: str) -> None:+ print(f"[heavy-thread] {message}", flush = True)+++# ── in-page actions ───────────────────────────────────────────────────+#+# Each one brackets itself with __hv.begin()/__hv.end(), so the recorder window is exactly the+# action rather than the action plus a CDP round trip.++# One character through the native value setter plus an input event: what the browser leaves+# behind after a real keypress, and what React's controlled textarea reacts to. Resolved on the+# second rAF, which is the frame that has painted it.+KEYSTROKE_JS = """+async (count) => {+ const api = window.__heavyThread;+ const input = api.composer();+ if (!input) return null;+ input.focus();+ const setValue = Object.getOwnPropertyDescriptor(+ HTMLTextAreaElement.prototype, "value",+ ).set;+ const samples = [];+ window.__hv.begin();+ for (let i = 0; i < count; i += 1) {+ await window.__nextPaint();+ const started = performance.now();+ setValue.call(input, input.value + "a");+ input.dispatchEvent(new Event("input", { bubbles: true }));+ await window.__nextPaint();+ samples.push(performance.now() - started);+ }+ const metrics = window.__hv.end();+ const sorted = samples.slice().sort((a, b) => a - b);+ // domText is what the harness itself wrote; runtimeText is what the runtime received. Only+ // the second can show the keystroke reached React rather than just the DOM node.+ return {+ samples: samples.map((s) => Math.round(s * 10) / 10),+ // The first sample is systematically a cold outlier, which is why the headline is a median.+ median_sample_ms: Math.round(sorted[Math.floor(sorted.length / 2)] * 10) / 10,+ worst_sample_ms: Math.round(sorted[sorted.length - 1] * 10) / 10,+ domText: input.value,+ runtimeText: api.composerText(),+ metrics,+ };+}+"""++SCROLL_JS = """+async ([steps, stepPx, settleMs]) => {+ const api = window.__heavyThread;+ const viewport = api.viewport();+ if (!viewport) return null;+ // The viewport carries `scroll-smooth`, so each scrollTop write starts an animation and the+ // next read lands mid-flight. Stepping from a tracked target with an explicit instant+ // behaviour is what a wheel gesture actually does, and it is the only way the gesture moves+ // the distance it asks for.+ const bottom = viewport.scrollHeight - viewport.clientHeight;+ viewport.scrollTo({ top: bottom, behavior: "instant" });+ await window.__nextPaint();+ let target = viewport.scrollTop;+ // Reverse at either end rather than stopping. A small thread runs out of travel long before a+ // large one does, and a gesture that covers 2600px at 25K chars and 8000px at 300K is not the+ // same gesture, so the two columns would not be comparable.+ let direction = -1;+ let travelled = 0;+ window.__hv.begin();+ for (let i = 0; i < steps; i += 1) {+ if (direction < 0 && target <= 0) direction = 1;+ else if (direction > 0 && target >= bottom) direction = -1;+ const next = Math.min(bottom, Math.max(0, target + direction * stepPx));+ // The wheel event is what the app's own scroll listeners key off; the scrollTo is what+ // moves the viewport in a headless run with no compositor input.+ viewport.dispatchEvent(+ new WheelEvent("wheel", { deltaY: direction * stepPx, bubbles: true, cancelable: true }),+ );+ viewport.scrollTo({ top: next, behavior: "instant" });+ await window.__nextPaint();+ travelled += Math.abs(next - target);+ target = next;+ }+ const gestureMs = performance.now() - window.__hv.startedAt;+ const settleMsTaken = await window.__hv.quiet(settleMs);+ const metrics = window.__hv.end();+ return {+ scrolledPx: travelled,+ gestureMs: Math.round(gestureMs * 10) / 10,+ settleMs: settleMsTaken === null ? null : Math.round(settleMsTaken * 10) / 10,+ metrics,+ };+}+"""++# A wheel gesture of fixed length traverses a fixed number of pixels, so it is comparable across+# sizes -- and, measured, it turns out to be nearly free at any size, because the layout was+# already done at mount. That is a real answer, but it is only half of "scrolling". The other half+# is the jump: dragging the scrollbar or hitting Home moves the viewport to a region the compositor+# has nothing for, which is what a user does when they go looking for an earlier answer.+JUMP_JS = """+async (settleMs) => {+ const api = window.__heavyThread;+ const viewport = api.viewport();+ if (!viewport) return null;+ const bottom = viewport.scrollHeight - viewport.clientHeight;+ viewport.scrollTo({ top: bottom, behavior: "instant" });+ await window.__nextPaint();+ window.__hv.begin();+ const started = performance.now();+ // The wheel event first, and it is load-bearing. Studio replaces assistant-ui's autoscroll+ // with an intent-aware one, and a bare scrollTo from the bottom is read as programmatic and+ // snapped straight back: measured, the jump landed at the bottom it started from and the whole+ // column timed nothing. A wheel is what says a person did this.+ viewport.dispatchEvent(+ new WheelEvent("wheel", { deltaY: -bottom, bubbles: true, cancelable: true }),+ );+ viewport.scrollTo({ top: 0, behavior: "instant" });+ await window.__nextPaint();+ const paintedMs = performance.now() - started;+ const settleMsTaken = await window.__hv.quiet(settleMs);+ const metrics = window.__hv.end();+ const landedAt = viewport.scrollTop;+ viewport.scrollTo({ top: bottom, behavior: "instant" });+ await window.__nextPaint();+ return {+ paintedMs: Math.round(paintedMs * 10) / 10,+ settleMs: settleMsTaken === null ? null : Math.round(settleMsTaken * 10) / 10,+ travelledPx: bottom,+ landedAt,+ metrics,+ };+}+"""++# Radix portals the menu to document.body and puts the body on the modal layer, which is the+# fan-out under suspicion. bodyPointerEvents proves the open really took that path.+#+# The trigger opens on `pointerdown`, not on `click`: an element.click() leaves the menu shut and+# the whole measurement silently reads zero. Hence the pointer pair.+#+# Everything this window scans, it scans a FIXED number of times: two observer queries, one per+# portal mutation, and the two censuses below, once each. Measured on Chromium at 300K that is+# 2.7ms of a 3208ms open+close, against 0.3ms of 375ms at 25K -- 0.08% of the number at both+# ends, so the share does not grow with the axis. Removing them entirely was measured too, on one+# page, alternating with the version above: 3389ms against 3394ms at 300K.+MENU_JS = """+async (timeoutMs) => {+ const api = window.__heavyThread;+ const trigger = api.actionButton("More");+ if (!trigger) return null;+ // A MutationObserver flag, not a querySelector per frame. The menu content is portaled to the+ // end of document.body, so polling for it walks the whole message list and finds nothing for+ // the entire open latency -- a cost that grows like the signal being measured.+ let open = Boolean(document.querySelector(".aui-action-bar-more-content"));+ const watcher = new MutationObserver(() => {+ open = Boolean(document.querySelector(".aui-action-bar-more-content"));+ });+ watcher.observe(document.body, { childList: true, subtree: false });+ const settle = async (want) => {+ const started = performance.now();+ while (performance.now() - started < timeoutMs) {+ if (open === want) return performance.now() - started;+ await window.__nextPaint();+ }+ return null;+ };+ const pointer = {+ bubbles: true, cancelable: true, composed: true,+ button: 0, pointerId: 1, pointerType: "mouse", isPrimary: true,+ };+ window.__hv.begin();+ const openStarted = performance.now();+ trigger.dispatchEvent(new PointerEvent("pointerdown", { ...pointer, buttons: 1 }));+ trigger.dispatchEvent(new PointerEvent("pointerup", { ...pointer, buttons: 0 }));+ const opened = await settle(true);+ const openMs = opened === null ? null : performance.now() - openStarted;+ const bodyPointerEvents = getComputedStyle(document.body).pointerEvents;+ const itemsWhileOpen = api.openMenuItemCount();+ // Counted here, under the pointer, not in the resting-state census. An autohidden bar is+ // absent at rest by design; one that never mounts at all is a broken page, and only a hovered+ // count tells the two apart.+ const triggersWhileHovered = document.querySelectorAll('[data-slot="tooltip-trigger"]').length;+ // The clock starts BEFORE the dispatch. Radix dismisses synchronously inside it -- layer+ // teardown, focus restore, the body coming off the modal layer and the re-render that follows+ // -- which is the fan-out being measured. Starting it after the dispatch excluded exactly the+ // part worth timing.+ const closeStarted = performance.now();+ document.dispatchEvent(+ new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }),+ );+ const closed = await settle(false);+ const metrics = window.__hv.end();+ watcher.disconnect();+ const closeMs = closed === null ? null : performance.now() - closeStarted;+ return {+ openMs: openMs === null ? null : Math.round(openMs * 10) / 10,+ closeMs: closeMs === null ? null : Math.round(closeMs * 10) / 10,+ open_close_ms:+ openMs === null || closeMs === null ? null : Math.round((openMs + closeMs) * 10) / 10,+ bodyPointerEvents,+ bodyPointerEventsAfterClose: getComputedStyle(document.body).pointerEvents,+ itemsWhileOpen,+ triggersWhileHovered,+ metrics,+ };+}+"""++DELETE_JS = """+async (timeoutMs) => {+ const api = window.__heavyThread;+ const button = api.actionButton("Delete message");+ if (!button) return null;+ // The last assistant message. That is the cheapest delete on the React side -- one subtree+ // unmounts -- so this column under-measures reconciliation, though the export/rebuild/import+ // half is O(messages) wherever the target sits.+ const target = api.lastAssistantMessage();+ const before = api.messageCount();+ window.__hv.begin();+ const started = performance.now();+ button.click();+ let ms = null;+ // isConnected on the captured node is O(1). Re-counting [data-role] every frame would put an+ // O(messages) query inside the window being timed, growing like the signal.+ while (performance.now() - started < timeoutMs) {+ if (target === null || !target.isConnected) {+ ms = performance.now() - started;+ break;+ }+ await window.__nextPaint();+ }+ const metrics = window.__hv.end();+ return { ms, before, after: api.messageCount(), metrics };+}+"""++# Leaving a thread and coming back. The runtime keeps the messages; the Thread subtree is torn+# down and rebuilt, which is every markdown block, every Shiki fence and every action bar mounted+# again from nothing. This is the action users describe as "it hangs when I click back into the+# conversation", and it is the one that has no incremental path at all.+#+# What comes back is the thread with its COMPLETED TOOL CARDS SHUT, because that is what the app+# does: tool-ui-python.tsx mounts with `defaultOpen={isRunning}` and tool-ui-code-execution.tsx+# initialises its `open` state from the same false flag, so a finished card remounts collapsed.+# The panes are therefore in the census this cell prints and not in the rebuild it times, and the+# gap was measured rather than assumed: 3999 DOM nodes expanded against 3981 rebuilt at 25K, and+# 42873 against 42675 at 300K. That is 0.45% and 0.46% of the tree, the same fraction at both+# ends, so it moves the ratio by nothing. Highlighted tokens are IDENTICAL in the two states+# (3216 and 35086), because the Shiki-highlighted cell renders outside the collapsible by design+# (#7165) and what is inside it is a plain <pre>: the settle probe below sees the same signal+# either way. Expanding them inside the window would mean a document-wide querySelectorAll for+# the triggers plus one synthetic click per card, 22 of them at 300K -- harness work that grows+# with the axis, to time a state the app never rebuilds into.+#+# The two messageCount() calls this makes inside the window are the harness's whole footprint in+# the number: measured on Chromium at 300K, 0.4ms of a 2292ms re-open, and 0.0ms of 363ms at 25K.+# The loop cannot poll more often than that because the rebuild is one blocking commit, so the+# rAF the loop waits on does not fire during it.+REOPEN_JS = """+async ([timeoutMs, settleMs, graceMs, probeEveryMs]) => {+ const api = window.__heavyThread;+ const before = api.messageCount();+ if (!before) return null;+ window.__hv.begin();+ const started = performance.now();+ api.closeThread();+ // Unmount first, or "already back" is indistinguishable from "never left".+ // Counted, not assumed. `growth()` subtracts one paint floor per double-rAF wait a metric is+ // clocked across, and that count was hand-declared per axis in GROWTH_AXES. Reopening is+ // driven by a React state update, so the count check immediately after openThread() always+ // still sees the unmounted tree and the loop always pays at least one __nextPaint() before it+ // can observe the rebuilt messages -- the same floor already subtracted from jump and delete.+ // Reporting it lets the harness check its own declared constant instead of trusting it.+ let closedMs = null;+ let closePaintWaits = 0;+ while (performance.now() - started < timeoutMs) {+ if (api.messageCount() === 0) { closedMs = performance.now() - started; break; }+ closePaintWaits += 1;+ await window.__nextPaint();+ }+ const reopenStarted = performance.now();+ api.openThread();+ let ms = null;+ let paintWaits = 0;+ while (performance.now() - reopenStarted < timeoutMs) {+ if (api.messageCount() >= before) { ms = performance.now() - reopenStarted; break; }+ paintWaits += 1;+ await window.__nextPaint();+ }+ // Not quiet(): re-open is the action whose whole cost is re-highlighting, and three calm frames+ // land inside the lull between two Shiki batches.+ const settled = await window.__hv.quietUntilIdle(+ settleMs,+ graceMs,+ () => api.highlightedTokenCount(),+ probeEveryMs,+ );+ const metrics = window.__hv.end(settled.at);+ return {+ ms,+ paintWaits,+ closePaintWaits,+ closedMs: closedMs === null ? null : Math.round(closedMs * 10) / 10,+ settleMs: settled.settleMs === null ? null : Math.round(settled.settleMs * 10) / 10,+ before,+ after: api.messageCount(),+ metrics,+ };+}+"""++# The floor under every timing clocked across a double rAF: two rAFs resolve no sooner than two+# vsync intervals. An action that never happened therefore still reports ~33ms, which reads as a+# plausible measurement rather than as a failure, so the floor is recorded per cell and+# subtracted before any growth ratio.+PAINT_FLOOR_JS = """+async (samples) => {+ const values = [];+ for (let i = 0; i < samples; i += 1) {+ await window.__nextPaint();+ const started = performance.now();+ await window.__nextPaint();+ values.push(performance.now() - started);+ }+ values.sort((a, b) => a - b);+ return values[Math.floor(values.length / 2)];+}+"""+++def median(values: list[float | None]) -> float | None:+ """Median across the repetitions, or None if any repetition did not produce a number.++ A None here is not a missing reading, it is a repetition in which the thing being timed never+ happened: the menu that never opened inside SETTLE_TIMEOUT_MS, the delete whose message never+ left the DOM, the action that never reached a settled state. Dropping those and taking the+ median of what is left changes the sample population and reports a partially broken action as+ a clean three-repetition measurement -- and it hides it from harness_failures(), whose+ `openMs is None` / `ms is None` checks then read the median of the repetitions that did work.+ So one bad repetition poisons the aggregate, and the run says so.+ """+ if not values or any(v is None for v in values):+ return None+ ordered = sorted(values)+ middle = len(ordered) // 2+ if len(ordered) % 2:+ return round(ordered[middle], 1)+ return round((ordered[middle - 1] + ordered[middle]) / 2, 1)+++def cdp_metrics(cdp) -> dict[str, float]:+ if cdp is None:+ return {}+ got = cdp.send("Performance.getMetrics")+ return {m["name"]: m["value"] for m in got["metrics"]}+++def cdp_counters(before: dict[str, float], after: dict[str, float]) -> dict[str, float | None]:+ """CHROMIUM-ONLY. Empty dicts off Chromium, and every consumer prints `-` for that."""+ if not before or not after:+ return {+ "layout_count": None,+ "recalc_style_count": None,+ "layout_ms": None,+ "recalc_style_ms": None,+ "task_ms": None,+ }++ def d(name: str) -> float:+ return after.get(name, 0.0) - before.get(name, 0.0)++ return {+ "layout_count": round(d("LayoutCount"), 1),+ "recalc_style_count": round(d("RecalcStyleCount"), 1),+ "layout_ms": round(d("LayoutDuration") * 1000, 1),+ "recalc_style_ms": round(d("RecalcStyleDuration") * 1000, 1),+ "task_ms": round(d("TaskDuration") * 1000, 1),+ }+++def long_task_summary(page) -> dict[str, float | None]:+ """CHROMIUM-ONLY. `supported` is the point: without it, an engine with no Long Tasks API+ reports zero jank in exactly the same shape as an engine that had none."""+ # PerformanceObserver callbacks are delivered on a later task, so the entry for the long task+ # at the tail of an action is not in the array yet. Yield once before reading, or the worst+ # entry is silently dropped -- flakily, and most often at large sizes where that tail task is+ # longest.+ got = page.evaluate(+ """async () => {+ await new Promise((r) => setTimeout(r, 0));+ return { supported: window.__longTaskSupported, tasks: window.__longTasks };+ }"""+ )+ if not got["supported"]:+ return {"long_tasks": None, "long_task_ms": None, "worst_long_task_ms": None}+ tasks = got["tasks"]+ return {+ "long_tasks": len(tasks),+ "long_task_ms": round(sum(t["duration"] for t in tasks), 1),+ "worst_long_task_ms": round(max((t["duration"] for t in tasks), default = 0.0), 1),+ }+++def reset_long_tasks(page) -> None:+ page.evaluate("window.__longTasks.length = 0")+++def wait_for_highlighting_settled(page, timeout_ms: int) -> None:+ """Block until Shiki has stopped adding tokens.++ FIVE stable reads a quarter of a second apart, not two consecutive ones. Two adjacent+ rAF-polled reads land inside the lull between two async highlight batches all the time:+ measured on WebKit, a two-read version released the gate at 577 highlighted tokens where the+ finished thread has 3216, so the whole engine column was measured against a thread that was+ still building itself.+ """+ page.evaluate("() => { window.__hvTokens = undefined; }")+ page.wait_for_function(+ """() => {+ const n = window.__heavyThread.highlightedTokenCount();+ const state = window.__hvTokens || { value: -1, stable: 0 };+ if (n === state.value && n > 0) state.stable += 1;+ else { state.value = n; state.stable = 0; }+ window.__hvTokens = state;+ return state.stable >= 5;+ }""",+ polling = 250,+ timeout = timeout_ms,+ )+++def run_action(page, cdp, name: str, script: str, arg) -> dict:+ """One action, with the portable recorder inside it and the CDP counters bracketing it."""+ reset_long_tasks(page)+ before = cdp_metrics(cdp)+ raw = page.evaluate(script, arg)+ after = cdp_metrics(cdp)+ if raw is None:+ return {"name": name, "ran": False, **cdp_counters({}, {}), **long_task_summary(page)}+ out = {"name": name, "ran": True}+ out.update(raw.pop("metrics"))+ out.update(raw)+ out.update(cdp_counters(before, after))+ out.update(long_task_summary(page))+ return out+++# The gate that says expandTools() really mounted the result panes.+#+# It reads codeExecutionPanes, which is `[data-slot="tool-fallback-content"] pre`, and NOT+# collapsibleOutputs, which is the content element itself. Radix keeps that element in the tree+# for its collapse animation, so it is present while the card is shut: measured on this tree at+# 300K characters, immediately after seeding and BEFORE any expandTools() call, collapsibleOutputs+# was already 22 of the 22 expected while codeExecutionPanes was 0. A `collapsibleOutputs >= n`+# gate is therefore satisfied by a thread of closed cards -- it cannot fail, and it released the+# highlighter wait below before the fences it exists to sequence had mounted. The pane's <pre> is+# a child of that element, so it appears only once the card is really open: 0 collapsed, 22+# expanded, at both sizes on all three engines.+EXPANDED_PANES_GATE_JS = "(n) => window.__heavyThread.counts().codeExecutionPanes >= n"+++def build_fixture(page) -> None:+ """Bring the page back to the fixture every column claims to have been measured on, untimed.++ Order matters and it is the reason this is one function rather than three call sites. Radix+ unmounts collapsed content, so the tool result panes -- which are CODE, two of the seven fences+ a content cycle produces -- do not exist until expandTools() has run. Waiting for the+ highlighter BEFORE expanding therefore gates on the fences that were already there and then+ mounts a fresh batch of unhighlighted ones, whose Shiki work lands in whatever is timed next.+ Expand first, then wait for the highlighter, which is the order measure_cell() seeds in.+ """+ expanded = page.evaluate("() => window.__heavyThread.expandTools()")+ if expanded:+ page.wait_for_function(+ EXPANDED_PANES_GATE_JS,+ arg = expanded,+ timeout = ACTION_TIMEOUT_MS,+ )+ wait_for_highlighting_settled(page, ACTION_TIMEOUT_MS)+++def one_repetition(page, cdp) -> dict[str, dict]:+ """The five scripted actions, once, in the order a user meets them."""+ rep: dict[str, dict] = {}+ # The previous repetition ended by re-opening the thread, which throws away every highlighted+ # fence and starts Shiki again, and by deleting a message, which the restore below puts back.+ # Without this wait, repetitions 2 and 3 measure a thread that is still building itself:+ # measured on Chromium at 300K, the scroll gesture read 667ms on the first repetition and+ # 1100ms on the two that followed, and the difference was the re-highlighting, not the scroll.+ build_fixture(page)+ rep["keystroke"] = run_action(page, cdp, "keystroke", KEYSTROKE_JS, KEYSTROKES)+ rep["scroll"] = run_action(+ page,+ cdp,+ "scroll",+ SCROLL_JS,+ [SCROLL_STEPS, SCROLL_STEP_PX, SETTLE_TIMEOUT_MS],+ )+ rep["jump"] = run_action(page, cdp, "jump", JUMP_JS, SETTLE_TIMEOUT_MS)++ # The action bar is hover-revealed, so put the pointer on the message before reaching for it.+ # behavior: "instant" -- the viewport carries scroll-smooth, so the default animates and at+ # large sizes leaves that animation in flight inside the menu counters.+ page.evaluate(+ """() => { const m = window.__heavyThread.lastAssistantMessage();+ if (m) m.scrollIntoView({ block: "center", behavior: "instant" }); }"""+ )+ page.wait_for_function(+ """() => {+ const top = window.__heavyThread.viewportMetrics().scrollTop;+ const settled = window.__hvTop === top;+ window.__hvTop = top;+ return settled;+ }""",+ timeout = ACTION_TIMEOUT_MS,+ )+ page.locator('[data-role="assistant"]').last.hover(timeout = ACTION_TIMEOUT_MS)+ rep["menu"] = run_action(page, cdp, "menu", MENU_JS, SETTLE_TIMEOUT_MS)++ page.locator('[data-role="assistant"]').last.hover(timeout = ACTION_TIMEOUT_MS)+ rep["delete"] = run_action(page, cdp, "delete", DELETE_JS, SETTLE_TIMEOUT_MS)++ # The delete is PERMANENT: it removes a message from the runtime's repository, not from the+ # view. Left alone, repetition 2 re-opens and measures a thread one message shorter than the+ # one the census at the top of this cell asserted, and repetition 3 one shorter again. At the+ # smallest size the whole thread is a single ten-kind cycle, so those three deletions take the+ # json fence, then both inline images, then the svg -- the exact "the fixture quietly lost a+ # content kind" failure harness_failures() gates on, except that the gate reads a census taken+ # before any repetition ran and so never sees it. Restore, then rebuild, untimed.+ restored = page.evaluate("() => window.__heavyThread.restore()")+ page.wait_for_function(+ "(n) => window.__heavyThread.messageCount() >= n",+ arg = restored,+ timeout = ACTION_TIMEOUT_MS,+ )+ build_fixture(page)++ rep["reopen"] = run_action(+ page,+ cdp,+ "reopen",+ REOPEN_JS,+ [SETTLE_TIMEOUT_MS, SETTLE_TIMEOUT_MS, HIGHLIGHT_GRACE_MS, HIGHLIGHT_PROBE_MS],+ )+ return rep+++# Portable headline per action, plus the action's own DOM-observable duration. `floored` marks a+# value clocked across a double rAF, which carries the ~33ms vsync floor.+HEADLINE = {+ "keystroke": ("median_sample_ms", True),+ "scroll": ("gestureMs", False),+ "jump": ("paintedMs", True),+ "menu": ("open_close_ms", True),+ "delete": ("ms", True),+ "reopen": ("ms", False),+}+++def summarise(reps: list[dict[str, dict]]) -> dict[str, dict]:+ """Median across repetitions, per action, per metric. Medians because the first repetition is+ systematically the slowest and a mean would carry it into every cell."""+ out: dict[str, dict] = {}+ for action in ACTIONS:+ rows = [r[action] for r in reps if action in r]+ if not rows or not all(r.get("ran") for r in rows):+ out[action] = {"ran": False}+ continue+ merged: dict = {"ran": True, "repetitions": len(rows)}+ numeric_keys = set()+ for row in rows:+ for key, value in row.items():+ # `value is None` is deliberately a key too. A timing that came back null in every+ # repetition would otherwise be absent from the merged row entirely, and the+ # verdict's `menu["openMs"] is None` would raise KeyError instead of reporting the+ # menu that never opened. Present-and-None is the readable form of that.+ if value is None or (+ isinstance(value, (int, float)) and not isinstance(value, bool)+ ):+ numeric_keys.add(key)+ for key in sorted(numeric_keys):+ merged[key] = median([r.get(key) for r in rows])+ # Values that are not numbers are proofs the action really happened, not timings, so the+ # last repetition's is kept verbatim rather than aggregated.+ for key in ("domText", "runtimeText", "bodyPointerEvents", "bodyPointerEventsAfterClose"):+ if key in rows[-1]:+ merged[key] = rows[-1][key]+ # The headline value from each repetition, unaggregated, so a median can be checked+ # against the spread it came from rather than taken on trust.+ merged["per_repetition"] = [r.get(HEADLINE[action][0]) for r in rows]+ out[action] = merged+ return out+++def measure_cell(context, engine: str, size: int) -> dict:+ """Seed a fresh page to `size` characters of content and run the action set REPEATS times."""+ page = context.new_page()+ result: dict = {"chars_requested": size, "engine": engine}+ # A request that escapes to the server, or a warning storm, is work this harness would be+ # charging to the app once per message. Both are cleared after seeding, so what is asserted on+ # is the measured actions rather than page load.+ #+ # startswith, not `"/api/" in url`: vite serves the app's own source modules from paths like+ # /src/features/chat/api/chat-api.ts, and a substring match counts dozens of those as network+ # calls. Same trap the route regex is anchored to avoid.+ api_prefix = f"{BASE}/api/"+ stray_requests: list[str] = []+ console_warnings: list[str] = []+ # Severity kept SEPARATE from the warning list. The allowance below exists for Gecko's two+ # scroll-anchoring notices, which are the engine describing itself. An application exception+ # is not chatter: a single console.error or an uncaught pageerror inside a measured+ # interaction means the interaction did not do what the row says it did, and folding those+ # into the same list let one pass under a "> 4" threshold and exit 0.+ console_errors: list[str] = []+ page.on(+ "request",+ lambda r: stray_requests.append(r.url) if r.url.startswith(api_prefix) else None,+ )+ page.on(+ "console",+ lambda m: (+ console_errors.append(m.text[:200])+ if m.type == "error"+ else console_warnings.append(m.text[:200])+ if m.type == "warning"+ else None+ ),+ )+ page.on("pageerror", lambda e: console_errors.append(f"pageerror: {e}"[:200]))+ cdp = None+ try:+ page.goto(f"{BASE}/smoke-heavy-thread.html", wait_until = "domcontentloaded")+ page.wait_for_function("() => Boolean(window.__heavyThread)", timeout = 60_000)+ if engine == "chromium":+ cdp = context.new_cdp_session(page)+ cdp.send("Performance.enable")++ # Seeding unthrottled and untimed: this measures interaction cost at a thread size, not+ # the cost of building the thread.+ plan = page.evaluate("(n) => window.__heavyThread.seed(n)", size)+ result["plan"] = plan+ # Single-selector gates. counts() walks every element in the document, so polling it per+ # frame makes seeding superlinear in the thing being seeded.+ page.wait_for_function(+ "(n) => window.__heavyThread.messageCount() >= n",+ arg = plan["messages"],+ timeout = SEED_TIMEOUT_MS,+ )+ # Radix unmounts collapsed content, so a thread of closed tool cards carries no result+ # panes at all. Open them before the census: a user who has just watched those tools run+ # is looking at them open, and the closed thread is a different fixture.+ result["tool_triggers_expanded"] = page.evaluate("() => window.__heavyThread.expandTools()")+ page.wait_for_function(+ EXPANDED_PANES_GATE_JS,+ arg = max(1, result["tool_triggers_expanded"]),+ timeout = SEED_TIMEOUT_MS,+ )+ # Shiki is async and per block, and a <pre> exists before it is highlighted, so counting+ # code blocks gates nothing. Wait for the token count to stop moving instead: unfinished+ # highlighting would otherwise land in the keystroke window, the first action measured.+ wait_for_highlighting_settled(page, SEED_TIMEOUT_MS)+ result["counts"] = page.evaluate("window.__heavyThread.counts()")+ result["viewport"] = page.evaluate("window.__heavyThread.viewportMetrics()")+ result["seed_api_requests"] = len(stray_requests)+ result["seed_console_warnings"] = len(console_warnings)+ result["first_seed_warning"] = console_warnings[0] if console_warnings else "-"+ result["seed_console_errors"] = len(console_errors)+ result["first_seed_error"] = console_errors[0] if console_errors else "-"+ stray_requests.clear()+ console_warnings.clear()+ console_errors.clear()++ result["cpu_throttle_rate"] = 1.0+ if cdp is not None and CPU_THROTTLE_RATE != 1.0:+ cdp.send("Emulation.setCPUThrottlingRate", {"rate": CPU_THROTTLE_RATE})+ result["cpu_throttle_rate"] = CPU_THROTTLE_RATE+ result["long_task_supported"] = page.evaluate("window.__longTaskSupported")+ result["paint_floor_ms"] = round(page.evaluate(PAINT_FLOOR_JS, 9), 2)++ reps = []+ for index in range(REPEATS):+ info(f" {engine} {size} chars: repetition {index + 1}/{REPEATS}")+ reps.append(one_repetition(page, cdp))+ result["repetitions"] = REPEATS+ result["actions"] = summarise(reps)+ result["raw_repetitions"] = reps++ if cdp is not None and CPU_THROTTLE_RATE != 1.0:+ cdp.send("Emulation.setCPUThrottlingRate", {"rate": 1})+ # Cumulative over seeding and every action: a liveness check, not attributable to any one.+ result["raf_callbacks"] = page.evaluate("window.__rafCount")+ result["stray_api_requests"] = len(stray_requests)+ # Answered inside the page by the smoke entry's allowlist. Reported rather than hidden:+ # these cost no round trip, but they are real requests the app makes and the number+ # should not vanish just because the harness declines to pay for them.+ result["stubbed_api_requests"] = len(page.evaluate("window.__stubbedApi || []"))+ result["console_warnings"] = len(console_warnings)+ result["first_console_warning"] = console_warnings[0] if console_warnings else "-"+ result["console_errors"] = len(console_errors)+ result["first_console_error"] = console_errors[0] if console_errors else "-"+ finally:+ page.close()+ return result+++def run() -> dict:+ results: dict = {+ "label": LABEL,+ "base": BASE,+ "sizes": SIZES,+ "engines": ENGINES,+ "repetitions": REPEATS,+ "cpu_throttle_rate_requested": CPU_THROTTLE_RATE,+ "by_engine": {},+ }+ with sync_playwright() as p:+ for engine in ENGINES:+ info(f"engine {engine}")+ launcher = getattr(p, engine)+ kwargs = {"headless": os.environ.get("SMOKE_HEADLESS", "1") == "1"}+ # Chromium-only flags. Passing them to Firefox or WebKit is not "ignored", it is a+ # launch failure, which would read as "this engine is unavailable".+ if engine == "chromium":+ kwargs["args"] = chromium_launch_args()+ browser = launcher.launch(**kwargs)+ results["by_engine"][engine] = {"version": browser.version, "by_size": {}}+ context = browser.new_context(viewport = {"width": 1440, "height": 900})+ context.add_init_script(RECORDER_INIT)+ # Anchored at the origin so it cannot swallow vite's own module URLs, which live+ # under src/features/**/api/ and would otherwise match a bare "/api/" pattern.+ context.route(+ re.compile(rf"^{re.escape(BASE)}/api/"),+ lambda route: route.fulfill(+ status = 200,+ content_type = "application/json",+ body = "{}",+ ),+ )+ for size in SIZES:+ info(f"measuring {engine} at {size} chars")+ # A renderer that dies mid-cell used to take the whole matrix with it: nine cells+ # of work thrown away because one WebKit page ran out of memory at 300K on a+ # loaded machine. The cell is recorded as crashed, the run continues, and+ # harness_failures reports it -- a crash is still a failure, it is just no longer+ # a failure that destroys the eight measurements that did work.+ try:+ cell = measure_cell(context, engine, size)+ except Exception as exc: # noqa: BLE001 - the message is the whole point+ info(f"CRASHED {engine} at {size} chars: {type(exc).__name__}: {exc}")+ cell = {+ "chars_requested": size,+ "engine": engine,+ "crashed": f"{type(exc).__name__}: {exc}"[:400],+ }+ results["by_engine"][engine]["by_size"][str(size)] = cell+ context.close()+ browser.close()+ return results+++# Every recorded metric appears here. That is the rule the harnesses in this directory are held+# to: a metric that is recorded and never read is how one goes false-green, and+# tests/studio/test_heavy_thread_harness_contract.py fails if anything recorded below is missing.+# CHROMIUM-ONLY rows are labelled in their own name, because off Chromium they print `-` and a+# `-` that means "not supported here" must not read as "zero".+def _action(action: str, key: str):+ return lambda r: r["actions"][action][key]+++def _floor_from(action: str, key: str):+ """A `floored` that is measured per row rather than declared once for every action."""+ return lambda r: (r.get("actions", {}).get(action) or {}).get(key) or 0+++TABLE_ROWS = (+ ("chars requested", lambda r: r["chars_requested"]),+ ("chars rendered", lambda r: r["plan"]["chars"]),+ ("messages seeded", lambda r: r["plan"]["messages"]),+ ("content cycles", lambda r: r["plan"]["cycles"]),+ ("chars per cycle", lambda r: r["plan"]["cycleChars"]),+ ("content kinds", lambda r: r["plan"]["kinds"]),+ ("tool cards expanded", lambda r: r["tool_triggers_expanded"]),+ ("repetitions", lambda r: r["repetitions"]),+ ("cpu throttle rate", lambda r: r["cpu_throttle_rate"]),+ ("paint floor ms", lambda r: r["paint_floor_ms"]),+ ("reopen paint waits", lambda r: (r.get("actions", {}).get("reopen") or {}).get("paintWaits")),+ ("longtask api supported", lambda r: r["long_task_supported"]),+ ("seed api requests", lambda r: r["seed_api_requests"]),+ ("seed console warnings", lambda r: r["seed_console_warnings"]),+ ("first seed warning", lambda r: r["first_seed_warning"]),+ ("action api requests", lambda r: r["stray_api_requests"]),+ ("stubbed api requests", lambda r: r.get("stubbed_api_requests", 0)),+ ("action console warnings", lambda r: r["console_warnings"]),+ ("seed console errors", lambda r: r.get("seed_console_errors", 0)),+ ("action console errors", lambda r: r.get("console_errors", 0)),+ ("first action error", lambda r: r.get("first_console_error", "-")),+ ("first action warning", lambda r: r["first_console_warning"]),+ ("messages rendered", lambda r: r["counts"]["messages"]),+ ("dom nodes", lambda r: r["counts"]["domNodes"]),+ ("code blocks", lambda r: r["counts"]["codeBlocks"]),+ ("highlighted tokens", lambda r: r["counts"]["highlightedTokens"]),+ ("tool parts", lambda r: r["counts"]["toolParts"]),+ ("collapsible tool outputs", lambda r: r["counts"]["collapsibleOutputs"]),+ ("code execution panes", lambda r: r["counts"]["codeExecutionPanes"]),+ ("artifact cards", lambda r: r["counts"]["artifactCards"]),+ ("images", lambda r: r["counts"]["images"]),+ ("action bars", lambda r: r["counts"]["actionBars"]),+ ("tooltip triggers", lambda r: r["counts"]["tooltipTriggers"]),+ ("viewport scrollHeight", lambda r: r["viewport"]["scrollHeight"]),+ ("viewport clientHeight", lambda r: r["viewport"]["clientHeight"]),+ ("rAF callbacks", lambda r: r["raf_callbacks"]),+)++for _name in ACTIONS:+ TABLE_ROWS = TABLE_ROWS + (+ (f"{_name} ran", _action(_name, "ran")),+ (f"{_name} wall ms", _action(_name, "wall_ms")),+ (f"{_name} longest stall ms", _action(_name, "longest_stall_ms")),+ (f"{_name} worst frame ms", _action(_name, "worst_frame_ms")),+ (f"{_name} median frame ms", _action(_name, "median_frame_ms")),+ (f"{_name} frames over 33ms", _action(_name, "frames_over_33")),+ (f"{_name} frames", _action(_name, "frames")),+ (f"{_name} stalls over 33ms", _action(_name, "stalls_over_33")),+ (f"{_name} stall ticks", _action(_name, "stall_ticks")),+ (f"{_name} layouts (chromium only)", _action(_name, "layout_count")),+ (f"{_name} layout ms (chromium only)", _action(_name, "layout_ms")),+ (f"{_name} recalcs (chromium only)", _action(_name, "recalc_style_count")),+ (f"{_name} recalc ms (chromium only)", _action(_name, "recalc_style_ms")),+ (f"{_name} task ms (chromium only)", _action(_name, "task_ms")),+ (f"{_name} longtasks (chromium only)", _action(_name, "long_tasks")),+ (f"{_name} longtask ms (chromium only)", _action(_name, "long_task_ms")),+ (f"{_name} worst longtask ms (chromium only)", _action(_name, "worst_long_task_ms")),+ )++TABLE_ROWS = TABLE_ROWS + (+ ("keystroke median ms", _action("keystroke", "median_sample_ms")),+ ("keystroke worst ms", _action("keystroke", "worst_sample_ms")),+ (+ "keystroke per repetition",+ lambda r: "/".join(str(v) for v in r["actions"]["keystroke"]["per_repetition"]),+ ),+ (+ "scroll per repetition",+ lambda r: "/".join(str(v) for v in r["actions"]["scroll"]["per_repetition"]),+ ),+ (+ "menu per repetition",+ lambda r: "/".join(str(v) for v in r["actions"]["menu"]["per_repetition"]),+ ),+ (+ "delete per repetition",+ lambda r: "/".join(str(v) for v in r["actions"]["delete"]["per_repetition"]),+ ),+ (+ "reopen per repetition",+ lambda r: "/".join(str(v) for v in r["actions"]["reopen"]["per_repetition"]),+ ),+ ("keystroke dom text", _action("keystroke", "domText")),+ ("keystroke runtime text", _action("keystroke", "runtimeText")),+ ("scroll gesture ms", _action("scroll", "gestureMs")),+ ("scroll settle ms", _action("scroll", "settleMs")),+ ("scroll px", _action("scroll", "scrolledPx")),+ ("jump painted ms", _action("jump", "paintedMs")),+ ("jump settle ms", _action("jump", "settleMs")),+ ("jump px", _action("jump", "travelledPx")),+ ("jump landed at", _action("jump", "landedAt")),+ ("menu open ms", _action("menu", "openMs")),+ ("menu close ms", _action("menu", "closeMs")),+ ("menu open+close ms", _action("menu", "open_close_ms")),+ ("menu items while open", _action("menu", "itemsWhileOpen")),+ ("menu body pe while open", _action("menu", "bodyPointerEvents")),+ ("menu body pe after close", _action("menu", "bodyPointerEventsAfterClose")),+ ("menu triggers hovered", _action("menu", "triggersWhileHovered")),+ ("delete ms", _action("delete", "ms")),+ ("delete messages before", _action("delete", "before")),+ ("delete messages after", _action("delete", "after")),+ ("reopen ms", _action("reopen", "ms")),+ ("reopen unmount ms", _action("reopen", "closedMs")),+ ("reopen settle ms", _action("reopen", "settleMs")),+ ("reopen messages before", _action("reopen", "before")),+ ("reopen messages after", _action("reopen", "after")),+)+++def print_table(results: dict) -> None:+ """Every recorded metric, printed, one column per (engine, size)."""+ columns = [(engine, str(size)) for engine in results["engines"] for size in results["sizes"]]+ rows = []+ for name, pick in TABLE_ROWS:+ cells = []+ for engine, size in columns:+ try:+ value = pick(results["by_engine"][engine]["by_size"][size])+ cells.append("-" if value is None else str(value))+ except (KeyError, TypeError):+ cells.append("-")+ rows.append((name, cells))+ label_width = max(len(name) for name, _ in rows) + 2+ # From the widest cell, not a constant: a fixed width silently runs the columns together on+ # the one row that overflows it, which is the row you were reading.+ headers = [f"{engine[:4]}/{int(size) // 1000}K" for engine, size in columns]+ cell_width = max([len(c) for _, cells in rows for c in cells] + [len(h) for h in headers]) + 2+ header = "".ljust(label_width) + "".join(h.rjust(cell_width) for h in headers)+ info(header)+ info("-" * len(header))+ for name, cells in rows:+ info(name.ljust(label_width) + "".join(cell.rjust(cell_width) for cell in cells))+++# Growth axes: the whole point of the harness is that these rise with content. The third field is+# HOW MANY double-rAF waits the metric is clocked across; each one carries its own ~33ms vsync+# floor, and left in, that floor compresses every ratio towards 1 and lets a real regression sit+# under the threshold. `menu open+close ms` is the sum of two independently floored timings, so it+# carries two.+GROWTH_AXES = tuple(+ [(f"{a} longest stall ms", _action(a, "longest_stall_ms"), 0) for a in ACTIONS]+ + [(f"{a} worst frame ms", _action(a, "worst_frame_ms"), 0) for a in ACTIONS]+ + [(f"{a} frames over 33ms", _action(a, "frames_over_33"), 0) for a in ACTIONS]+ # The floor is READ from the row, not declared: every one of these windows crosses a+ # different number of mandatory double-rAF waits, and declaring 0 for all of them left+ # roughly `paint_waits * paint_floor_ms` of constant baseline in both ends of the ratio.+ # MENU_JS is the clearest case: it opens the recorder before opening the menu and closes it+ # after closing it, so it crosses the same two waits `menu open+close ms` correctly declares,+ # and `menu wall ms` was declaring none of them.+ + [(f"{a} wall ms", _action(a, "wall_ms"), _floor_from(a, "paint_waits")) for a in ACTIONS]+ + [+ # The rule for the entries below: an axis measured from `__hv.startedAt` spans the WHOLE+ # recorder window, so it carries every double-rAF wait in it and takes the measured+ # `paint_waits`. An axis measured from a later mark carries only its own and keeps a+ # declared count. Both kinds are here on purpose and the difference is not cosmetic.+ #+ # gestureMs is `performance.now() - __hv.startedAt`, and BOTH settle figures come from+ # `quiet()` / `quietUntilIdle()`, which return `... - this.startedAt` rather than the time+ # they themselves took. All three therefore contained the scroll's twenty paint waits and+ # declared none of them, leaving ~20 vsync floors in both ends of those ratios, which+ # compresses them hard enough to report a real size-dependent regression as flat.+ #+ # Counted at runtime rather than written in: the twenty come from a LOOP, so the literal+ # `__nextPaint()` count in the source is one, and any hand-declared number here would have+ # been wrong in the same way the old zero was.+ ("keystroke median ms", _action("keystroke", "median_sample_ms"), 1),+ ("scroll gesture ms", _action("scroll", "gestureMs"), _floor_from("scroll", "paint_waits")),+ ("scroll settle ms", _action("scroll", "settleMs"), _floor_from("scroll", "paint_waits")),+ # NOT paint_waits: paintedMs starts at a mark taken after begin() and spans one wait,+ # while the jump's window holds two. Using the window count here would subtract a floor+ # the number never contained.+ ("jump painted ms", _action("jump", "paintedMs"), 1),+ ("jump settle ms", _action("jump", "settleMs"), _floor_from("jump", "paint_waits")),+ # Also NOT paint_waits: MENU_JS awaits no paint at all, and its two floors come from+ # settle() reading the pre-MutationObserver state on entry, once for open and once for+ # close. The window count is zero here and would remove a floor that is really there.+ ("menu open+close ms", _action("menu", "open_close_ms"), 2),+ ("delete ms", _action("delete", "ms"), 1),+ # 1, not 0: see paintWaits in REOPEN_JS. Leaving it at 0 left a full ~33ms vsync floor+ # of constant baseline in both ends of the ratio, which compresses it towards 1 and can+ # report a real reopen curve as flat when the smallest fixture rebuilds near the floor.+ ("reopen ms", _action("reopen", "ms"), 1),+ ]+)+# A ratio at or below this from the smallest size to the largest means the axis did not respond+# to twelve times the content. That is not a flat curve, it is an axis that is not measuring the+# thing being varied.+DISCRIMINATION_RATIO = float(os.environ.get("SMOKE_DISCRIMINATION_RATIO", "1.5"))+# What a counter that starts at zero has to REACH before its rise counts as an answer. A ratio+# cannot be formed against zero, so DISCRIMINATION_RATIO does not apply to these axes at all and+# something absolute has to. 5 because the counters this covers are dropped frames and long+# tasks: at twelve times the content a real curve produces them in quantity, while one or two is+# what an unloaded machine produces on its own, and the CI configuration runs a single repetition+# so there is no median to average that away.+ZERO_BASED_MIN_RISE = int(os.environ.get("SMOKE_ZERO_BASED_MIN_RISE", "5"))+# Which axes are COUNTS. Stated, not inferred. The zero branch below used to key on `floored`,+# which only identifies a timing that had a paint floor subtracted; an UNFLOORED timing such as+# `longest stall ms` or `worst frame ms` is zero at the smallest size whenever the action ends+# before the recorder produces a sample, and it was then treated as a dropped-frame counter, so a+# noisy 5ms at the largest size read as a rise of 5 and discriminated. `harness_failures` accepts+# any one discriminating axis, so that stray millisecond could carry the run.+#+# A count is a count of events. Only `frames over 33ms` is one; every other axis is milliseconds.+COUNTER_AXES = frozenset(f"{a} frames over 33ms" for a in ACTIONS)+# Engine chatter is tolerated up to this many warnings per size. Gecko's two scroll-anchoring+# notices are what this number exists for; anything the app emits per message would be two orders+# of magnitude above it at 220 messages.+CONSOLE_WARNING_ALLOWANCE = int(os.environ.get("SMOKE_CONSOLE_WARNING_ALLOWANCE", "4"))+++def resolve_floor(floored, row: dict) -> float:+ """The floor count for one row, as an INT.++ `floored` may be a callable, and the growth report is written to JSON at the end of the run.+ Putting the callable itself in the report made `json.dumps` raise `Object of type function is+ not JSON serializable`, which failed every complete run AFTER all the measurements were taken.+ Nothing in the unit tests caught it because none of them serialise the report.+ """+ # NOT int(). `summarise` takes a median across repetitions, so an even-repetition run whose+ # repetitions paid 1 and 2 waits reports 1.5, and truncating that to 1 left half a vsync floor+ # in the wall-clock axis and published a distorted ratio. The documented two-repetition+ # configurations are exactly the ones that produce halves. A float serialises fine.+ value = floored(row) if callable(floored) else floored+ return value if isinstance(value, (int, float)) else 0+++def growth(cells: dict, pick, floored, sizes: list[int]) -> tuple[float | None, float | None]:+ """`floored` is a COUNT of double-rAF waits inside the metric, not a flag.++ It may be an int, declared once for an axis, or a callable taking the row, for an axis whose+ window crosses a different number of waits per action. The generated `wall ms` axes are the+ second kind: they were declared 0 for every action, which left roughly `paint_waits *+ paint_floor_ms` in both ends of those ratios.++ Each `await __nextPaint()` a metric is clocked across contributes its own ~33ms vsync floor,+ and a metric that contains two of them carries two. `menu open+close ms` is the case: settle()+ reads the pre-MutationObserver state on entry, both times, so opening and closing each wait+ out a full double rAF before their first true comparison. Subtracting one floor from a sum of+ two left ~33ms of constant baseline in the number, which drags the ratio towards 1 in exactly+ the way the floor is subtracted to prevent.+ """+ try:+ rows = (cells[str(sizes[0])], cells[str(sizes[-1])])+ values = []+ for row in rows:+ value = pick(row)+ if value is None:+ return None, None+ count = resolve_floor(floored, row)+ if count:+ value -= count * row["paint_floor_ms"]+ values.append(round(value, 2))+ return values[0], values[1]+ except (KeyError, TypeError):+ return None, None+++def report_growth(results: dict) -> dict[str, dict[str, dict]]:+ """Per engine, per axis: the value at the smallest and largest size and their ratio."""+ report: dict[str, dict[str, dict]] = {}+ for engine in results["engines"]:+ cells = results["by_engine"][engine]["by_size"]+ per_axis: dict[str, dict] = {}+ for name, pick, floored in GROWTH_AXES:+ small, large = growth(cells, pick, floored, results["sizes"])+ # Resolved here, once, so what lands in the JSON is the count that was actually+ # subtracted at each end rather than the thing that computes it.+ floor_counts = [+ resolve_floor(floored, cells.get(str(size), {}))+ for size in (results["sizes"][0], results["sizes"][-1])+ ]+ if small is None or large is None:+ per_axis[name] = {+ "small": None,+ "large": None,+ "ratio": None,+ "discriminated": False,+ "reason": "not recorded",+ }+ continue+ if small <= 0:+ # A COUNT that is 0 at the smallest size and 4 at the largest has no ratio and has+ # still answered the question, so it counts as discriminating when it really rose.+ #+ # A TIMING does not get that credit. `floored` means the value had the ~33ms vsync+ # floor subtracted from it, so a zero or negative here says the action resolved at+ # or under one frame at the smallest size, which is a metric with no room to move+ # rather than a metric that grew from nothing.+ if floored:+ per_axis[name] = {+ "small": small,+ "large": large,+ "ratio": None,+ "discriminated": False,+ "reason": "at or under the paint floor at the smallest size",+ "floored": floor_counts,+ }+ continue+ # `large > small` is not enough. These are counts of missed frames and long+ # tasks, and in the one-repetition Chromium configuration the CI workflow runs+ # there is no median to smooth them: a single incidental dropped frame takes an+ # axis from 0 to 1, which was marked as discriminating no matter what+ # SMOKE_DISCRIMINATION_RATIO said, because a ratio was never computed for it.+ # `harness_failures` accepts any ONE discriminating axis, so that stray frame+ # could carry the whole verdict while every latency axis was flat or broken.+ if name not in COUNTER_AXES:+ # A timing that reads zero at the smallest size did not "grow from nothing",+ # it resolved below what the recorder can see. ZERO_BASED_MIN_RISE is a count+ # of events and means nothing applied to milliseconds.+ per_axis[name] = {+ "small": small,+ "large": large,+ "ratio": None,+ "discriminated": False,+ "reason": (+ "zero at the smallest size and this axis is a timing, not a count, "+ "so there is no rise to measure"+ ),+ "floored": floor_counts,+ }+ continue+ rose = large >= ZERO_BASED_MIN_RISE+ if rose:+ reason = f"rose from zero to {large}"+ elif large > small:+ reason = (+ f"rose from zero only to {large}, under the {ZERO_BASED_MIN_RISE} this "+ "counter needs to be distinguishable from noise"+ )+ else:+ reason = "zero at both ends"+ per_axis[name] = {+ "small": small,+ "large": large,+ "ratio": None,+ "discriminated": rose,+ "reason": reason,+ "floored": floor_counts,+ }+ continue+ ratio = round(large / small, 2)+ # The noise floor applies to a counter whatever its baseline. A dropped-frame count+ # going 1 -> 2 is a ratio of 2.0 and cleared DISCRIMINATION_RATIO, and since+ # harness_failures accepts any single discriminating axis, that one incidental frame+ # could carry the CI smoke while every latency axis was flat. A ratio is only+ # meaningful once there are enough events for the ratio to be about the content+ # rather than about one frame either way.+ noisy_counter = name in COUNTER_AXES and large < ZERO_BASED_MIN_RISE+ per_axis[name] = {+ "small": small,+ "large": large,+ "ratio": ratio,+ "discriminated": ratio > DISCRIMINATION_RATIO and not noisy_counter,+ "reason": (+ f"only {large} events at the largest size, under the "+ f"{ZERO_BASED_MIN_RISE} this counter needs to be distinguishable from noise"+ if noisy_counter+ else "-"+ ),+ "floored": floor_counts,+ }+ report[engine] = per_axis+ return report+++def print_growth(results: dict, report: dict) -> None:+ for engine, per_axis in report.items():+ info("")+ info(+ f"growth on {engine} ({results['sizes'][0]} -> {results['sizes'][-1]} chars, "+ f"median of {results['repetitions']} repetitions)"+ )+ for name, row in per_axis.items():+ if row["ratio"] is None:+ mark = "DISCRIMINATES" if row["discriminated"] else "flat"+ small = "-" if row["small"] is None else row["small"]+ large = "-" if row["large"] is None else row["large"]+ info(+ f" {name:<34} {small:>10} -> {large:>10} - " f"{mark} ({row['reason']})"+ )+ continue+ mark = "DISCRIMINATES" if row["discriminated"] else "flat"+ floor_note = " (paint floor removed)" if row.get("floored") else ""+ info(+ f" {name:<34} {row['small']:>10} -> {row['large']:>10} "+ f"{row['ratio']:>6.2f}x {mark}{floor_note}"+ )+++# The declared double-rAF count for each axis whose action reports how many it actually paid.+# GROWTH_AXES holds the declaration; the action holds the observation; a harness that declares a+# floor it does not pay, or pays one it does not declare, subtracts the wrong constant from both+# ends of every ratio it publishes. Only reopen reports its waits today, so only reopen is+# checkable here; the entry exists so adding a counter to another action wires it in by name.+# axis name in GROWTH_AXES -> (action, the field on that action reporting its own wait count)+FLOOR_COUNTERS = {"reopen ms": ("reopen", "paintWaits")}+++def declared_floor(axis_name: str) -> int | None:+ """The `floored` column of GROWTH_AXES for one axis, by exact name.++ Exact rather than prefix-matched: `reopen ms` and a later `reopen settle ms` would both match+ a prefix, and the check would silently compare one axis's waits against another's declaration.+ A name that is not an axis returns None, which the caller reports rather than skips.+ """+ for name, _pick, floored in GROWTH_AXES:+ if name == axis_name:+ return floored+ return None+++def floor_declaration_problems(results: dict) -> list[str]:+ """Axes whose subtracted paint floor does not match the waits the action actually paid."""+ problems: list[str] = []+ for engine in results["engines"]:+ for size in results["sizes"]:+ row = results["by_engine"][engine]["by_size"].get(str(size), {})+ if "crashed" in row:+ continue+ for axis_name, (action, counter) in FLOOR_COUNTERS.items():+ measured = row.get("actions", {}).get(action) or {}+ # An action that did not run is already reported by harness_failures, with the+ # reason. Reporting it again here as an unverified floor would be a second+ # failure for one cause, and would bury the real one.+ if not measured.get("ran", True):+ continue+ observed = measured.get(counter)+ if observed is None:+ problems.append(+ f"{engine} at {size} chars recorded no {counter} for {action}, so the "+ f"paint floor subtracted from '{axis_name}' is unverified"+ )+ continue+ declared = declared_floor(axis_name)+ if declared == observed:+ continue+ problems.append(+ f"{engine} at {size} chars paid {observed} paint wait(s) in {action} but "+ f"GROWTH_AXES subtracts {declared} from '{axis_name}'; the ratio is computed "+ "after removing the wrong constant from both ends"+ )+ return problems+++def harness_failures(results: dict, report: dict) -> list[str]:+ """Only the ways this harness can be measuring nothing. No performance budgets: see the+ module docstring."""+ failures: list[str] = list(floor_declaration_problems(results))+ for engine in results["engines"]:+ for size in results["sizes"]:+ row = results["by_engine"][engine]["by_size"][str(size)]+ where = f"{engine} at {size} chars"+ if "crashed" in row:+ failures.append(+ f"{where} crashed before it produced a measurement: {row['crashed']}"+ )+ continue+ counts = row["counts"]+ plan = row["plan"]+ # A request reaching the server is a round trip to another process inside a region+ # being timed, once per message. A warning storm is the same cost via the console+ # channel. Both scale with content, so both would forge the curve.+ if row["stray_api_requests"]:+ failures.append(+ f"{where} let {row['stray_api_requests']} /api/ requests reach the network "+ "during the measured actions; the timings include a round trip per request"+ )+ # Console output from inside a timed region is serialised over the debugging channel,+ # so a warning the app emits once per message would both cost time and grow like the+ # signal. The instrument for that is an ABSOLUTE cap, not a growth check: at 220+ # messages a per-message warning is in the hundreds, while what an engine says about+ # itself is a handful. Firefox 153 emits exactly two "Scroll anchoring was disabled+ # in a scroll container" notices once the container is large enough, which is zero at+ # 25K and two at both 100K and 300K -- a growth check fails on that and would leave+ # this harness unable to report a Gecko number at all. The count and the first+ # message are printed per size either way, so a reader can see what was tolerated.+ # NO allowance. The paragraph above is about engine chatter, which is the engine+ # describing itself; an application exception is not that. One console.error or one+ # uncaught pageerror inside a measured interaction means the interaction did not do+ # what the row says it did, so its timing is not a measurement of the labelled thing.+ # Sharing one list with the warnings let exactly one such error sit under the "> 4"+ # threshold and the run exit 0 with the timings published.+ for phase, count, first in (+ ("seeding", row.get("seed_console_errors", 0), row.get("first_seed_error", "-")),+ (+ "the measured actions",+ row.get("console_errors", 0),+ row.get("first_console_error", "-"),+ ),+ ):+ if count:+ failures.append(+ f"{where} logged {count} console error(s) or page error(s) during "+ f"{phase}, the first being {first!r}; an application exception is not "+ "engine chatter and the timings around it are not measurements"+ )+ if row["console_warnings"] > CONSOLE_WARNING_ALLOWANCE:+ failures.append(+ f"{where} logged {row['console_warnings']} console warnings during the "+ f"measured actions, the first being {row['first_console_warning']!r}; that is "+ f"more than the {CONSOLE_WARNING_ALLOWANCE} allowed for engine chatter, so "+ "the timings include work this harness is charging to the app"+ )+ if plan["chars"] < size * 0.9:+ failures.append(+ f"{where} only built {plan['chars']} characters of the {size} asked for"+ )+ if counts["messages"] < plan["messages"]:+ failures.append(+ f"{where} rendered {counts['messages']} of {plan['messages']} messages; the "+ "seed did not land"+ )+ # The fixture IS the measurement. A thread of plain paragraphs would be cheap for+ # reasons the app is not, so every kind the user report names has to be on screen,+ # in proportion, at every size.+ #+ # Counted against the page's own per-cycle expectation rather than against zero. The+ # renderer drops content silently in more than one place -- an image part whose data+ # URL is not base64 PNG/JPEG/GIF/WebP is discarded with a console.warn -- and a+ # fixture that has quietly lost a whole kind still produces a rising curve, of+ # something else.+ for key, per_cycle in plan["expectedPerCycle"].items():+ want = per_cycle * plan["cycles"]+ if counts.get(key, 0) < want:+ failures.append(+ f"{where} rendered {counts.get(key, 0)} {key}, short of the {want} its "+ f"{plan['cycles']} content cycles should produce; the fixture is not the "+ "heavy thread this harness claims to measure"+ )+ if counts.get("highlightedTokens", 0) <= 0:+ failures.append(f"{where} highlighted nothing; Shiki never ran")+ viewport = row["viewport"]+ if viewport["scrollHeight"] <= viewport["clientHeight"]:+ failures.append(+ f"{where} does not overflow its viewport; the scroll measures nothing"+ )++ actions = row["actions"]+ for name in ACTIONS:+ if not actions[name].get("ran"):+ failures.append(f"{where} could not run the {name} action at all")+ # A null settle time is the settle loop giving up: the page never produced a calm+ # window inside SETTLE_TIMEOUT_MS. It is NOT "this engine does not report that",+ # but it prints as the same `-`, and the axis it feeds merely becomes "not+ # recorded" -- so another axis can carry the discrimination check and the run exits+ # 0 having timed out without measuring settlement.+ for name in ("scroll", "jump", "reopen"):+ settling = actions[name]+ if settling.get("ran") and settling.get("settleMs") is None:+ failures.append(+ f"{where} ran the {name} action but it never reached a settled state "+ f"within {SETTLE_TIMEOUT_MS}ms, so its settle time and the frame counts "+ "beside it are the timeout rather than a measurement"+ )+ keystroke = actions["keystroke"]+ if keystroke.get("ran"):+ # The DOM value is what the harness itself wrote, so it proves nothing on its+ # own. Only the runtime's copy shows the keystroke reached React rather than just+ # the textarea, and a keystroke that reached nothing still reports the ~33ms+ # paint floor, which reads as a plausible timing.+ if keystroke["runtimeText"] != keystroke["domText"]:+ failures.append(+ f"{where} typed {keystroke['domText']!r} into the DOM but the runtime "+ f"holds {keystroke['runtimeText']!r}; the keystroke never reached the "+ "composer state"+ )+ # Sitting on the paint floor is NOT a harness failure here, and the reason is a+ # finding rather than an excuse: the character reaches the composer and paints on+ # the very next frame at every size, while the thread churns for another 180ms+ # afterwards. `runtimeText == domText` above is what proves the keystroke landed;+ # the floor comparison only says this particular axis has no room to move, which+ # the growth report states per axis.+ scroll = actions["scroll"]+ # Equal travel at every size or the columns are not the same gesture.+ if scroll.get("ran") and scroll["scrolledPx"] < SCROLL_STEPS * SCROLL_STEP_PX * 0.9:+ failures.append(+ f"{where} travelled only {scroll['scrolledPx']}px of the "+ f"{SCROLL_STEPS * SCROLL_STEP_PX}px gesture, so its scroll column is not "+ "comparable with the others"+ )+ jumped = actions["jump"]+ if jumped.get("ran"):+ # Unlike the gesture, the jump is DELIBERATELY not the same distance at every+ # size: it is bottom to top, which is the point. What has to hold is that it+ # arrived, or the column is timing a scroll that did not move.+ if jumped["landedAt"] > 1:+ failures.append(+ f"{where} jumped to the top of the thread and landed at "+ f"{jumped['landedAt']}px; the viewport did not move"+ )+ if jumped["travelledPx"] <= viewport["clientHeight"]:+ failures.append(+ f"{where} had only {jumped['travelledPx']}px to jump through, which is "+ "less than one viewport; nothing had to be painted"+ )+ menu = actions["menu"]+ if menu.get("ran"):+ if menu["openMs"] is None:+ failures.append(f"{where} never opened the message action menu")+ elif menu["closeMs"] is None:+ failures.append(f"{where} opened the action menu and it never closed")+ elif menu["bodyPointerEventsAfterClose"] == "none":+ failures.append(+ f"{where} left the body on the modal layer after closing the menu"+ )+ # An empty popover satisfies "the menu opened" and costs nothing to render.+ elif not menu["itemsWhileOpen"]:+ failures.append(f"{where} opened an action menu with no items in it")+ if not menu["triggersWhileHovered"] and counts["actionBars"] <= 0:+ failures.append(+ f"{where} mounted no action bar at rest and none under the pointer either"+ )+ deleted = actions["delete"]+ if deleted.get("ran"):+ if deleted["ms"] is None:+ failures.append(f"{where} never deleted a message")+ elif deleted["after"] >= deleted["before"]:+ failures.append(f"{where} clicked delete and the message count did not drop")+ reopened = actions["reopen"]+ if reopened.get("ran"):+ if reopened["ms"] is None:+ failures.append(f"{where} re-opened the thread and it never came back")+ elif reopened["closedMs"] is None:+ failures.append(+ f"{where} never saw the thread unmount, so its re-open time is the cost "+ "of a thread that never left"+ )++ # A modal menu puts the body on the modal layer and a non-modal one does not, and the two+ # cost wildly different amounts. Either is a legitimate tree, but a run that mixes them+ # across sizes is comparing columns measured on different mechanisms.+ layers = {+ results["by_engine"][engine]["by_size"][str(size)]+ .get("actions", {})+ .get("menu", {})+ .get("bodyPointerEvents")+ for size in results["sizes"]+ if "crashed" not in results["by_engine"][engine]["by_size"][str(size)]+ }+ if len(layers) > 1:+ failures.append(+ f"on {engine} the menu put the body on {sorted(str(x) for x in layers)} across "+ "sizes; the columns are not measuring the same mechanism"+ )++ # Discrimination. Not a budget: a harness where the largest thread costs what the smallest+ # does is not reporting a flat curve, it is reporting that it never drove the page.+ if len(results["sizes"]) >= 2:+ for engine, per_axis in report.items():+ if not any(row["discriminated"] for row in per_axis.values()):+ failures.append(+ f"on {engine} no measured axis rose by more than {DISCRIMINATION_RATIO}x "+ f"from {results['sizes'][0]} to {results['sizes'][-1]} characters. Either the "+ "page was never driven or every action is being measured somewhere it does "+ "not run; the numbers above cannot size any change."+ )+ return failures+++def main() -> int:+ vite = None+ if OWNS_SERVER:+ info(f"starting vite dev server on port {PORT}")+ vite = start_vite(PORT)+ try:+ wait_for_smoke_page(+ f"{BASE}/smoke-heavy-thread.html",+ "smoke-heavy-thread-main.tsx",+ proc = vite,+ info = info,+ )+ results = run()+ finally:+ if vite is not None:+ stop_process(vite)+ info("vite stopped")++ report = report_growth(results)+ results["growth"] = report+ out = OUT / f"{LABEL}.json"+ out.write_text(json.dumps(results, indent = 2), encoding = "utf-8")+ print_table(results)+ print_growth(results, report)+ info(f"wrote {out}")++ failures = harness_failures(results, report)+ for problem in failures:+ info(f"HARNESS-BROKEN {problem}")+ if failures:+ return 1+ info("measurement only: no budgets are asserted here, so this exits 0 on any timing.")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/studio/test_heavy_thread_gap_contract.py b/tests/studio/test_heavy_thread_gap_contract.pynew file mode 100644index 00000000000..1093de1d8f4--- /dev/null+++ b/tests/studio/test_heavy_thread_gap_contract.py@@ -0,0 +1,76 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The two methods the viewport-gap measurement in #9058 drives this harness through.++#9058 targets this page rather than duplicating the harness, and its committed+`probe_compact_tail_gap.py` preflights for these exact names and exits naming whichever is+missing. So renaming either one, or dropping a key out of `gapMetrics`, breaks a probe on+another branch rather than anything here, which is precisely the kind of break nothing local+would catch.+"""++import re+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+ENTRY = ROOT / "studio" / "frontend" / "smoke-heavy-thread-main.tsx"+++def entry() -> str:+ return ENTRY.read_text(encoding = "utf-8")+++def test_the_compact_tail_seed_keeps_its_name_and_arity() -> None:+ assert (+ "seedCompactTail(targetChars: number, tailMessages: number)" in entry()+ ), "#9058's probe calls seedCompactTail(chars, tailMessages) by name"+++def test_the_compact_tail_seed_reuses_the_ordinary_fixture_builder() -> None:+ # The census parity #9058 relies on comes from calling the same buildThread() seed() calls.+ # Measured: seedCompactTail(25000, 16) reports 36 messages against seed(25000)'s 20, a tail+ # of exactly 16, with every other count unchanged.+ body = entry()+ tail = body[body.index("seedCompactTail(") : body.index("gapMetrics()")]+ assert "buildThread(targetChars)" in tail, (+ "seedCompactTail must build the heavy part with buildThread(targetChars), or its counts "+ "stop matching seed(targetChars) and #9058's numbers stop being comparable"+ )+++def test_gap_metrics_keeps_every_key_the_probe_reads() -> None:+ body = entry()+ gap = body[body.index("gapMetrics()") :]+ gap = gap[: gap.index("\n },")]+ for key in (+ "ok",+ "mountedRows",+ "clientHeight",+ "scrollHeight",+ "scrollTop",+ "maxScrollTop",+ "mountedHeight",+ "gapTop",+ "gapBottom",+ "spacerHeight",+ ):+ # `key:` or the shorthand `key,` / `key\n`. Checking only for `key:` would have failed+ # on `clientHeight`, which is returned shorthand, so the guard would have been red+ # against correct code.+ assert re.search(+ rf"\b{key}\s*[:,\n]", gap+ ), f"gapMetrics no longer reports {key}, which #9058's probe reads"+++def test_the_gap_below_is_measured_against_the_viewport_edge() -> None:+ # Against the box bottom, not scrollHeight. The viewport's own bottom spacer then counts as+ # the gap it always was and the caller subtracts spacerHeight to get the part the mount+ # window owns. Measured with a 16 message tail: spacerHeight 165, gapBottom 199.+ body = entry()+ gap = body[body.index("gapMetrics()") :]+ gap = gap[: gap.index("\n },")]+ assert "box.bottom - last.bottom" in gap, (+ "gapBottom must be measured from the viewport's bottom edge, or #9058's numbers stop "+ "being comparable across sizes"+ )diff --git a/tests/studio/test_heavy_thread_harness_contract.py b/tests/studio/test_heavy_thread_harness_contract.pynew file mode 100644index 00000000000..3ce018e6afd--- /dev/null+++ b/tests/studio/test_heavy_thread_harness_contract.py@@ -0,0 +1,235 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The heavy-thread harness must read every guard it records, and must stay portable.++`tests/studio/playwright_heavy_thread.py` measures in a browser and then decides pass/fail in+`main()`. A metric that is recorded but never compared is how a harness goes false-green, which is+the rule already pinned for the #8483 harnesses in test_autoscroll_harness_contract.py.++This file adds the constraint that is specific to this harness: it is meant to run on WebKit and+Firefox as well as Chromium, because Unsloth Desktop is a Tauri webview and not Chromium. Every+CDP counter and the Long Tasks API are Chromium-only, and the failure mode is silent -- a+`longtask` PerformanceObserver on JavaScriptCore never fires, which reads as "no jank" rather than+as "no measurement". So no growth axis and no pass/fail decision may rest on one.+"""++from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+STUDIO_TESTS = ROOT / "tests" / "studio"+FRONTEND = ROOT / "studio" / "frontend"++HARNESS = "playwright_heavy_thread.py"+# Recorded by the harness, produced only by Chromium. None of these may decide anything.+CHROMIUM_ONLY = (+ "layout_count",+ "layout_ms",+ "recalc_style_count",+ "recalc_style_ms",+ "task_ms",+ "long_tasks",+ "long_task_ms",+ "worst_long_task_ms",+)+# The portable four the module docstring promises as the primary numbers.+PORTABLE_PRIMARY = ("longest_stall_ms", "worst_frame_ms", "frames_over_33", "wall_ms")+ACTIONS = ("keystroke", "scroll", "jump", "menu", "delete", "reopen")+++def source(name: str) -> str:+ return (STUDIO_TESTS / name).read_text(encoding = "utf-8")+++def section(text: str, start: str, end: str) -> str:+ head = text.index(start)+ return text[head : text.index(end, head)]+++def growth_axes() -> str:+ return section(source(HARNESS), "GROWTH_AXES = tuple(", "DISCRIMINATION_RATIO")+++def verdict() -> str:+ """Everything from `def harness_failures` on: the only place a metric turns into an exit+ code."""+ text = source(HARNESS)+ return text[text.index("def harness_failures") :]+++def test_every_measured_action_has_a_growth_axis() -> None:+ # An action that is driven but never checked for growth is an action whose column could be+ # constant at every size without anything failing. The axes are generated from ACTIONS, so+ # what has to hold is that ACTIONS is the generator and that it still lists all six.+ text = source(HARNESS)+ declared = section(text, "ACTIONS = (", ")")+ for action in ACTIONS:+ assert f'"{action}"' in declared, action+ axes = growth_axes()+ for metric in PORTABLE_PRIMARY:+ assert f"for a in ACTIONS" in axes and f'"{metric}"' in axes, metric+++def test_the_portable_primaries_are_the_growth_axes() -> None:+ axes = growth_axes()+ for metric in PORTABLE_PRIMARY:+ assert f'"{metric}"' in axes, metric+++def test_no_growth_axis_is_chromium_only() -> None:+ # The whole point of the portable metrics: a curve built on CDP counters is a curve that does+ # not exist on the engine Unsloth Desktop actually ships on macOS and Linux.+ axes = growth_axes()+ for metric in CHROMIUM_ONLY:+ assert f'"{metric}"' not in axes, metric+++def test_the_verdict_never_rests_on_a_chromium_only_metric() -> None:+ decision = verdict()+ for metric in CHROMIUM_ONLY:+ assert f'["{metric}"]' not in decision, metric+++def test_chromium_only_rows_say_so_in_their_own_label() -> None:+ # Off Chromium these print `-`, and a `-` that means "not supported here" must not be read as+ # a zero. The label is the only thing carrying that.+ text = source(HARNESS)+ table = section(text, "TABLE_ROWS = (", "def print_table")+ for metric in CHROMIUM_ONLY:+ for line in table.splitlines():+ if f'"{metric}"' in line:+ assert "chromium only" in line, line+++def test_the_longtask_api_is_recorded_as_supported_or_not() -> None:+ # Without this flag an engine with no Long Tasks API reports zero long tasks in exactly the+ # same shape as an engine that had none.+ text = source(HARNESS)+ assert "__longTaskSupported" in text+ assert '("longtask api supported", lambda r: r["long_task_supported"])' in text+++def test_the_stall_detector_is_a_timer_and_not_a_message_channel() -> None:+ # Measured, not preference: the MessageChannel ping-pong halves Firefox's frame rate before+ # any application code runs, so it changes the thing it is there to measure.+ text = source(HARNESS)+ assert "new MessageChannel(" not in text, "the recorder must not spin a port"+ assert "setTimeout(stall, 1)" in text+++def test_the_verdict_asserts_the_fixture_and_not_just_its_size() -> None:+ # 300K characters of prose would produce a rising curve too, and would be measuring something+ # nobody reported.+ decision = verdict()+ assert 'plan["expectedPerCycle"]' in decision+ assert 'counts.get("highlightedTokens", 0)' in decision+++def test_the_verdict_asserts_the_keystroke_reached_the_runtime() -> None:+ # The DOM value is what the harness itself wrote. A keystroke that reached nothing still+ # reports the ~33ms paint floor, which reads as a plausible timing.+ decision = verdict()+ assert 'keystroke["runtimeText"] != keystroke["domText"]' in decision+++def test_the_paint_floor_is_measured_and_subtracted() -> None:+ # Two rAFs resolve no sooner than two vsync intervals, so an action that never happened still+ # reports ~33ms. Left in a ratio, that floor compresses every axis towards 1 and lets a real+ # regression sit under the discrimination threshold.+ text = source(HARNESS)+ assert "PAINT_FLOOR_JS" in text+ # Once per double-rAF wait the metric is clocked across, not once per metric: `menu open+close+ # ms` is the sum of two independently floored timings and carries two floors.+ assert 'value -= count * row["paint_floor_ms"]' in section(+ text, "def growth(", "def report_growth"+ )+++def test_the_verdict_asserts_the_reopen_really_unmounted() -> None:+ # Without this, "re-open" is timing a thread that never left, which is free.+ decision = verdict()+ assert 'reopened["closedMs"] is None' in decision+++def test_the_verdict_asserts_discrimination() -> None:+ # A harness where the largest thread costs what the smallest does is not reporting a flat+ # curve, it is reporting that it never drove the page.+ decision = verdict()+ assert 'row["discriminated"]' in decision+ assert "DISCRIMINATION_RATIO" in decision+++def test_the_smoke_page_exposes_every_count_the_fixture_gate_needs() -> None:+ page = (FRONTEND / "smoke-heavy-thread-main.tsx").read_text(encoding = "utf-8")+ expected = section(page, "const EXPECTED_PER_CYCLE", "};")+ counts = section(page, "counts(): Record<string, number>", "viewportMetrics()")+ for line in expected.splitlines():+ key = line.strip().split(":")[0]+ if key.isidentifier():+ assert f"{key}:" in counts, key+++def test_the_smoke_page_is_served_and_owns_its_dev_server() -> None:+ text = source(HARNESS)+ assert (FRONTEND / "smoke-heavy-thread.html").exists()+ assert (FRONTEND / "smoke-heavy-thread-main.tsx").exists()+ assert "start_vite(PORT)" in text+ assert "stop_process(vite)" in text+++def test_the_fork_count_stub_answers_with_a_real_zero() -> None:+ # `getForkCount` returns `data.count`, and the badge's guard is `count <= 0`. `undefined <= 0`+ # is false, so a `{}` body renders a badge reading "undefined forks from this message" on every+ # assistant message. Measured at 25000 chars: 10 badges and 4031 DOM nodes with `{}`, 0 badges+ # and 3981 with `{"count":0}`. That is DOM in proportion to thread size, on the axis this+ # harness measures.+ page = (FRONTEND / "smoke-heavy-thread-main.tsx").read_text(encoding = "utf-8")+ # Pin the fork-count entry to its own body rather than scanning the whole file: other+ # endpoints in the allowlist legitimately answer "{}", so a bare file-wide check for it+ # would fail on them and tell us nothing about this one.+ forks = next(+ (line for line in page.splitlines() if "forks$/" in line),+ "",+ )+ assert forks, "the fork-count endpoint is no longer in the stub allowlist"+ assert '{"count":0}' in forks, (+ "the fork-count stub must answer with a numeric count; an empty object makes the parsed "+ f"count undefined and renders a badge on every assistant message. Got: {forks.strip()!r}"+ )+++def test_the_fetch_stub_only_intercepts_fork_counts() -> None:+ # A blanket `/api/` match resolves any other request a measured interaction makes before+ # Playwright emits it, so `measure_cell`'s listener never increments `stray_api_requests` and+ # the API fan-out this harness claims to detect cannot reach it.+ page = (FRONTEND / "smoke-heavy-thread-main.tsx").read_text(encoding = "utf-8")+ assert 'url.includes("/api/")' not in page, (+ "the fetch stub is matching every /api/ request again, which hides stray requests from "+ "the harness's own stray_api_requests counter"+ )+ assert (+ "forks$/" in page or "/forks" in page+ ), "the fetch stub must match the fork-count endpoint specifically"+++def test_the_api_stub_is_an_allowlist_not_a_blanket_match() -> None:+ # A blanket `/api/` match answers every request the measured interactions make before Playwright+ # emits it, so `stray_api_requests` stays at zero and the fan-out this harness exists to detect+ # is invisible to it. Narrowing it is what revealed the project-list and knowledge-base GETs on+ # reopen, and the delete's own three-request sync.+ page = (FRONTEND / "smoke-heavy-thread-main.tsx").read_text(encoding = "utf-8")+ assert (+ 'url.includes("/api/")' not in page+ ), "the fetch stub is matching every /api/ request again"+ assert "STUBBED_API" in page, "the fetch stub must answer from an explicit allowlist"+++def test_every_stubbed_endpoint_is_reported() -> None:+ # Answering a request inside the page removes its round trip from the timings, which is the+ # point, but it must not remove the request from the record. An endpoint that is answered and+ # not counted is one nobody can see the cost of later.+ page = (FRONTEND / "smoke-heavy-thread-main.tsx").read_text(encoding = "utf-8")+ assert "__stubbedApi" in page, "stubbed requests must be recorded on the page"+ harness = source("playwright_heavy_thread.py")+ assert "stubbed_api_requests" in harness, "the harness must read the stubbed-request record"+ assert '"stubbed api requests"' in harness, "the stubbed-request count must reach the table"diff --git a/tests/studio/test_heavy_thread_measurement_integrity.py b/tests/studio/test_heavy_thread_measurement_integrity.pynew file mode 100644index 00000000000..d9f2465b7e5--- /dev/null+++ b/tests/studio/test_heavy_thread_measurement_integrity.py@@ -0,0 +1,1297 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The heavy-thread harness must not report a number it did not measure.++`test_heavy_thread_harness_contract.py` pins the SHAPE of the harness: every recorded metric is+printed, no verdict rests on a Chromium-only counter. This file pins its ARITHMETIC and its+ORDERING, which is the other way a measurement harness goes false-green: it drives the page, it+prints a plausible table, and the numbers in it are of something else.++Five defects this file exists to keep out, each one previously live:++ * the frame recorder deciding which action a scheduled callback belongs to from a shared+ `running` flag, so an action that starts before the previous action's rAF has fired inherits+ that callback, charges the between-action gap to itself as a frame, and runs two recorder+ loops from then on;+ * `median()` dropping a null repetition instead of failing on it, which turns "the menu never+ opened once in three tries" into a clean three-repetition median;+ * a settle loop that timed out being indistinguishable, in the table and in the verdict, from a+ metric the engine does not support;+ * `menu open+close ms` being the sum of two independently double-rAF-floored timings while only+ one floor was subtracted from it;+ * the per-repetition fixture rebuild waiting for the syntax highlighter BEFORE mounting the tool+ result panes it has to highlight, and never restoring the message the delete action destroys.++The browser-side pieces run under node against the harness's own JS, sliced out of the Python+source verbatim, on a virtual clock: the frame pump is explicit, so "the next action began before+the previous action's callback fired" is a deterministic interleaving rather than a race someone+has to be lucky to catch.+"""++from __future__ import annotations++import copy+import json+import os+import sys+import types+from pathlib import Path++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _node_harness import require_node, run_harness # noqa: E402++WORKDIR = Path(__file__).resolve().parents[2]+TEMP_ROOT = WORKDIR / "logs" / "heavy-thread-node"+HARNESS_SOURCE = (Path(__file__).resolve().parent / "playwright_heavy_thread.py").read_text(+ encoding = "utf-8"+)+++def _load_harness():+ """Import the harness module without needing a browser.++ The module imports `playwright.sync_api` at the top for `sync_playwright`, which nothing in+ this file calls. Stubbing it keeps these tests runnable in the CPU test job, where the+ Playwright package is not installed, rather than skipping the arithmetic along with the+ browser.+ """+ os.environ.setdefault("PW_ART_DIR", str(TEMP_ROOT / "artifacts"))+ if "playwright.sync_api" not in sys.modules:+ try:+ import playwright.sync_api # noqa: F401+ except ImportError:+ package = types.ModuleType("playwright")+ module = types.ModuleType("playwright.sync_api")+ module.sync_playwright = None+ package.sync_api = module+ sys.modules["playwright"] = package+ sys.modules["playwright.sync_api"] = module+ import playwright_heavy_thread++ return playwright_heavy_thread+++HARNESS = _load_harness()+++# ── the node side: the harness's own JS on a virtual clock ────────────++# performance.now() is the fake clock, requestAnimationFrame is a queue this file pumps, and+# setTimeout is a queue too -- the recorder's stall loop reschedules itself forever, so a real+# timer would keep the process alive past the end of the test.+FAKE_ENV = """+let now = 0;+let rafs = [];+let timers = [];+globalThis.performance = { now: () => now };+class FakePerformanceObserver {+ constructor(cb) { this.cb = cb; }+ observe() {}+ disconnect() {}+}+FakePerformanceObserver.supportedEntryTypes = [];+globalThis.PerformanceObserver = FakePerformanceObserver;+globalThis.setTimeout = (fn, ms) => { timers.push({ fn, at: now + (ms || 0) }); return timers.length; };+const win = { requestAnimationFrame: (cb) => { rafs.push(cb); return rafs.length; } };+globalThis.window = win;++const drain = async () => {+ for (let i = 0; i < 40; i += 1) await new Promise((r) => setImmediate(r));+};+// One frame. Callbacks scheduled DURING the frame land in the next one, which is what the browser+// does and is the whole point: a callback scheduled by the previous action is still pending when+// the next action starts.+const tick = async (deltaMs) => {+ now += deltaMs;+ const dueTimers = timers.filter((t) => t.at <= now);+ timers = timers.filter((t) => t.at > now);+ for (const t of dueTimers) t.fn();+ const dueFrames = rafs;+ rafs = [];+ for (const cb of dueFrames) cb(now);+ await drain();+};+const idle = (ms) => { now += ms; };+const say = (value) => console.log(JSON.stringify(value));+"""+++def node_script(body: str, *, sources: dict[str, str]) -> str:+ """A runnable .mts: the fake environment, the sliced harness JS, then `body`."""+ declarations = "\n".join(+ f"const {name} = {json.dumps(text)};" for name, text in sources.items()+ )+ return f"{FAKE_ENV}\n{declarations}\n{body}\n"+++def run_node(body: str, sources: dict[str, str]) -> dict:+ require_node([])+ return run_harness(TEMP_ROOT, "export const unused = 0;\n", node_script(body, sources = sources))+++RECORDER_SOURCES = {"RECORDER_INIT": HARNESS.RECORDER_INIT}+++# ── the recorder must not leak a loop into the next action ────────────++LEAK_BODY = """+eval(RECORDER_INIT);+const hv = window.__hv;+hv.begin();+await tick(16);+await tick(16);+const first = hv.end();+// The gap between two actions: a CDP round trip and a page.evaluate, during which the page is+// busy finishing the previous action and paints nothing. The rAF the last frame callback+// scheduled is still pending when the next action begins.+idle(40);+hv.begin();+await tick(16);+await tick(16);+const second = hv.end();+say({ first_frames: first.frames, second_frames: second.frames,+ second_worst: second.worst_frame_ms });+"""+++def test_the_recorder_starts_the_next_action_with_one_loop() -> None:+ # Two frames pumped, two frames recorded. A stale callback that survived into this action+ # would be recording alongside the real one, so every frame is counted twice -- and it+ # compounds, because each begin() can leave another behind.+ got = run_node(LEAK_BODY, RECORDER_SOURCES)+ assert got["second_frames"] == 2, got+++def test_the_recorder_does_not_charge_the_between_action_gap_as_a_frame() -> None:+ # The stale callback's own `lastFrame` is from the PREVIOUS action, so the interval it pushes+ # spans the gap between the two actions. It lands in worst_frame_ms and, once the gap is over+ # 33ms, in frames_over_33 as well: both growth axes.+ got = run_node(LEAK_BODY, RECORDER_SOURCES)+ assert got["second_worst"] == 16, got+++# ── re-open must not stop the clock while Shiki is still running ──────++REOPEN_SOURCES = {"RECORDER_INIT": HARNESS.RECORDER_INIT, "REOPEN_JS": HARNESS.REOPEN_JS}++# A thread that remounts instantly and then highlights for 40 frames, which is the shape re-open+# actually has: the message roots are back long before the fences inside them are coloured.+REOPEN_BODY = """+eval(RECORDER_INIT);+let mounted = true;+let tokens = 3000;+let highlightFrames = 0;+window.__heavyThread = {+ messageCount: () => (mounted ? 20 : 0),+ closeThread: () => { mounted = false; tokens = 0; },+ openThread: () => { mounted = true; highlightFrames = 40; },+ highlightedTokenCount: () => tokens,+};+const reopen = eval("(" + REOPEN_JS + ")");+let done = null;+reopen([100000, 100000, 1000, 100]).then((r) => { done = r; });+let lastChangeAt = 0;+// A FIXED number of frames, not "until it resolves": the last-token-change time has to be the+// same reference whether the settle loop stopped early or not, or an early stop moves the+// reference it is being compared against and the comparison proves nothing.+for (let i = 0; i < 200; i += 1) {+ if (highlightFrames > 0) { tokens += 75; highlightFrames -= 1; lastChangeAt = now + 16; }+ await tick(16);+}+say({+ settleMs: done === null ? null : done.settleMs,+ lastChangeAt,+ wallMs: done === null ? null : done.metrics.wall_ms,+ frames: done === null ? null : done.metrics.frames,+ medianFrameMs: done === null ? null : done.metrics.median_frame_ms,+});+"""+++def test_reopen_keeps_the_clock_running_until_the_highlighter_stops() -> None:+ # quiet() settles on three sub-33ms frames, and the lull between two Shiki batches is longer+ # than three frames -- the same lull wait_for_highlighting_settled() needs five stable reads to+ # see through. Settling on frames alone stops the re-open clock partway through the rebuild.+ got = run_node(REOPEN_BODY, REOPEN_SOURCES)+ assert got["settleMs"] >= got["lastChangeAt"] - 20, got+++def test_reopen_does_not_charge_the_grace_window_to_the_action() -> None:+ # The grace is a fixed cost every size pays equally, and a constant on both ends of a ratio+ # drags it towards 1. The reported settle is the time of the LAST activity, so the 1000ms of+ # watching that confirmed it is not in the number.+ got = run_node(REOPEN_BODY, REOPEN_SOURCES)+ assert got["settleMs"] <= got["lastChangeAt"] + 120, got+++def test_reopen_counts_no_frames_from_the_grace_window() -> None:+ # The grace window watches an idle page, so every frame in it is a fast one. Left in the+ # arrays they inflate `frames`, drag `median_frame_ms` down towards the idle rate, and do it+ # by the same fixed amount at every size -- a constant offset on a growth axis.+ got = run_node(REOPEN_BODY, REOPEN_SOURCES)+ # 640ms of highlighting at 16ms a frame, and nothing past it.+ assert got["frames"] <= 45, got+++def test_reopen_closes_its_recorder_window_at_the_last_activity() -> None:+ # Same reason, for wall ms, which is a growth axis in its own right.+ got = run_node(REOPEN_BODY, REOPEN_SOURCES)+ assert got["wallMs"] <= got["lastChangeAt"] + 120, got+++# ── no-regression guards: what the timed windows may scan ─────────────+#+# GUARDS, not evidence for a finding. They pass on this tree and are here to keep it that way.+#+# Both timed windows are measured in the browser and the harness-owned DOM scans inside them are+# a rounding error today: on Chromium at 300000 characters the re-open window makes 2 selector+# passes costing 0.4ms of a 2292ms re-open (0.02%), and the menu window makes 2 observer queries+# and 2 censuses costing 2.7ms of a 3208ms open+close (0.08%). That holds because the count of+# scans is FIXED while their unit cost grows with the thread (messageCount 0.01ms at 25000 chars,+# 0.105ms at 300000). Swap one of them for the full census, or move any of them inside the poll+# loop, and the harness starts adding size-dependent work to the number it publishes. These pin+# the count.++SCAN_BUDGET_BODY = """+eval(RECORDER_INIT);+let mounted = true;+let tokens = 3000;+let highlightFrames = 0;+// The rebuild straddles this many frames, so the poll loop really does go round more than once.+let mountFrames = 4;+let scans = 0;+let censuses = 0;+let probes = 0;+window.__heavyThread = {+ messageCount: () => { scans += 1; return mounted && mountFrames <= 0 ? 20 : 0; },+ counts: () => { censuses += 1; return { messages: 20, domNodes: 4000 }; },+ closeThread: () => { mounted = false; tokens = 0; },+ openThread: () => { mounted = true; mountFrames = 4; highlightFrames = 40; },+ highlightedTokenCount: () => { probes += 1; return tokens; },+};+mountFrames = 0;+const reopen = eval("(" + REOPEN_JS + ")");+let done = null;+let doneAt = null;+const startedAt = now;+reopen([100000, 100000, 1000, 100]).then((r) => { done = r; doneAt = now; });+for (let i = 0; i < 200; i += 1) {+ if (mountFrames > 0) mountFrames -= 1;+ if (highlightFrames > 0) { tokens += 75; highlightFrames -= 1; }+ await tick(16);+}+say({+ scans, censuses, probes,+ mountFrames: 4,+ probeBudget: Math.ceil((doneAt - startedAt) / 100) + 2,+ ms: done === null ? null : done.ms,+});+"""+++def test_the_reopen_window_never_runs_the_document_census() -> None:+ # GUARD. counts() is a dozen document-wide queries including getElementsByTagName("*"), and it+ # is 25 times the cost of messageCount() at 25000 chars and 24 times at 300000 (measured+ # 0.15ms/0.01ms and 2.51ms/0.105ms on Chromium). One of those per frame inside the re-open+ # window is the harness measuring itself.+ got = run_node(SCAN_BUDGET_BODY, REOPEN_SOURCES)+ assert got["censuses"] == 0, got+++def test_the_reopen_window_scans_no_more_than_once_per_frame_of_the_rebuild() -> None:+ # GUARD. Six [data-role] passes for this rebuild on the virtual clock, and the six are+ # enumerable: `before` sizes the thread, one closes the unmount loop, three run the re-open+ # loop while the stub rebuild is still blocked, and `after` proves the thread came back. Only+ # the middle four are inside the recorder window and only one of them is inside the reported+ # `ms`. A second pass per iteration doubles the size-dependent work in the number, and at+ # 300000 characters each pass is 0.105ms against 0.01ms at 25000.+ got = run_node(SCAN_BUDGET_BODY, REOPEN_SOURCES)+ assert got["scans"] <= 6, got+++def test_the_highlight_probe_stays_on_its_interval_inside_the_settle_loop() -> None:+ # GUARD. quietUntilIdle()'s probe is `pre code span` over the whole document: 0.03ms at 25000+ # chars and 0.465ms at 300000 on Chromium, 2.05ms on Firefox. Per frame that is an O(nodes)+ # query inside the window being timed, growing like the signal; on the interval it is a few+ # milliseconds across the whole settle.+ got = run_node(SCAN_BUDGET_BODY, REOPEN_SOURCES)+ assert got["probes"] <= got["probeBudget"], got+++MENU_SCAN_BODY = """+eval(RECORDER_INIT);+let menuOpen = false;+let observer = null;+let notifications = 0;+let querySelectorCalls = 0;+let querySelectorAllCalls = 0;+class FakeMutationObserver {+ constructor(cb) { observer = cb; }+ observe() {}+ disconnect() { observer = null; }+}+globalThis.MutationObserver = FakeMutationObserver;+globalThis.PointerEvent = class { constructor(type) { this.type = type; } };+globalThis.KeyboardEvent = class { constructor(type) { this.type = type; } };+globalThis.getComputedStyle = () => ({ pointerEvents: menuOpen ? "none" : "auto" });+const notify = () => {+ queueMicrotask(() => { if (observer) { notifications += 1; observer([]); } });+};+const trigger = {+ dispatchEvent: (e) => { if (e.type === "pointerdown") { menuOpen = true; notify(); } },+};+globalThis.document = {+ body: {},+ querySelector: (sel) => {+ querySelectorCalls += 1;+ return sel === ".aui-action-bar-more-content" && menuOpen ? {} : null;+ },+ querySelectorAll: () => { querySelectorAllCalls += 1; return []; },+ dispatchEvent: (e) => { if (e.type === "keydown") { menuOpen = false; notify(); } },+};+window.__heavyThread = { actionButton: () => trigger, openMenuItemCount: () => 5 };+const menu = eval("(" + MENU_JS + ")");+let done = null;+menu(100000).then((r) => { done = r; });+for (let i = 0; i < 40 && done === null; i += 1) await tick(16);+say({ notifications, querySelectorCalls, querySelectorAllCalls, openMs: done.openMs });+"""+++def test_the_menu_reads_its_open_flag_from_the_mutation_and_not_from_a_scan() -> None:+ # GUARD. The menu content is portaled to the END of document.body, so a querySelector for it+ # walks the whole message list -- and for the entire open latency it walks it and finds+ # nothing. Measured on Chromium at 300000 chars that query is 0.25ms a call against 0.025ms at+ # 25000. One per mutation is 2 in the window; one per frame would be one per 16ms of the very+ # latency being measured, on a cost that grows with the thread.+ got = run_node(MENU_SCAN_BODY, MENU_SOURCES)+ assert got["querySelectorCalls"] <= got["notifications"] + 1, got+++def test_the_menu_window_takes_one_census_and_not_one_per_frame() -> None:+ # GUARD. The tooltip-trigger census is the only querySelectorAll the menu window runs+ # (measured 0.13ms at 300000 chars against 0.005ms at 25000). It is taken once, under the+ # pointer, because an action bar that never mounts and one that is autohidden at rest are+ # otherwise indistinguishable.+ got = run_node(MENU_SCAN_BODY, MENU_SOURCES)+ assert got["querySelectorAllCalls"] <= 1, got+++# ── the menu total carries two paint floors, not one ──────────────────++MENU_SOURCES = {"RECORDER_INIT": HARNESS.RECORDER_INIT, "MENU_JS": HARNESS.MENU_JS}++# A menu that opens and closes with NO work at all: the flag flips inside the dispatch. Whatever+# this reports is therefore pure floor.+MENU_BODY = """+eval(RECORDER_INIT);+let menuOpen = false;+let observer = null;+class FakeMutationObserver {+ constructor(cb) { observer = cb; }+ observe() {}+ disconnect() { observer = null; }+}+globalThis.MutationObserver = FakeMutationObserver;+globalThis.PointerEvent = class { constructor(type) { this.type = type; } };+globalThis.KeyboardEvent = class { constructor(type) { this.type = type; } };+globalThis.getComputedStyle = () => ({ pointerEvents: menuOpen ? "none" : "auto" });+// A MutationObserver callback is delivered as a MICROTASK ("queue a mutation observer microtask"+// in the DOM standard), never synchronously inside the mutation. That is what puts the floor+// under this metric: the settle loop's first comparison runs before the callback has updated the+// flag, so it always waits out one __nextPaint() even when the menu opened instantly.+const notify = () => { queueMicrotask(() => { if (observer) observer(); }); };+const trigger = { dispatchEvent: (e) => { if (e.type === "pointerdown") { menuOpen = true; notify(); } } };+globalThis.document = {+ body: {},+ querySelector: (sel) => (sel === ".aui-action-bar-more-content" && menuOpen ? {} : null),+ querySelectorAll: () => [],+ dispatchEvent: (e) => { if (e.type === "keydown") { menuOpen = false; notify(); } },+};+window.__heavyThread = {+ actionButton: () => trigger,+ openMenuItemCount: () => 5,+};+const menu = eval("(" + MENU_JS + ")");+let done = null;+menu(100000).then((r) => { done = r; });+for (let i = 0; i < 40 && done === null; i += 1) await tick(16);+say({ openMs: done.openMs, closeMs: done.closeMs, total: done.open_close_ms });+"""+++def test_opening_the_menu_costs_a_whole_double_raf_even_when_it_is_free() -> None:+ # settle() reads `open` before the MutationObserver callback that would have updated it has+ # been delivered, so its first true comparison is on the far side of an __nextPaint(). Nothing+ # is wrong with that -- it is what makes the number a wall-clock one -- but it means the metric+ # carries a floor, and the floor has to be subtracted before a ratio.+ got = run_node(MENU_BODY, MENU_SOURCES)+ assert got["openMs"] >= 32, got+++def test_closing_the_menu_costs_a_second_double_raf() -> None:+ # And this is the one the single-floor subtraction missed: closing waits out its own+ # __nextPaint() for exactly the same reason, independently of opening.+ got = run_node(MENU_BODY, MENU_SOURCES)+ assert got["closeMs"] >= 32, got+++def test_the_menu_growth_axis_subtracts_both_floors() -> None:+ name, pick, floors = next(a for a in HARNESS.GROWTH_AXES if a[0] == "menu open+close ms")+ assert floors == 2, f"{name} is clocked across two double rAFs, so it carries two floors"+++def test_the_menu_growth_value_has_both_floors_removed() -> None:+ _, pick, floors = next(a for a in HARNESS.GROWTH_AXES if a[0] == "menu open+close ms")+ cells = {+ "25000": {"paint_floor_ms": 30.0, "actions": {"menu": {"open_close_ms": 100.0}}},+ "300000": {"paint_floor_ms": 30.0, "actions": {"menu": {"open_close_ms": 1000.0}}},+ }+ small, large = HARNESS.growth(cells, pick, floors, [25000, 300000])+ assert (small, large) == (40.0, 940.0), (small, large)+++# ── a null repetition is a failure, not a sample to drop ──────────────+++def menu_repetition(open_ms: float | None) -> dict:+ close_ms = 40.0+ total = None if open_ms is None else open_ms + close_ms+ return {+ "menu": {+ "name": "menu",+ "ran": True,+ "openMs": open_ms,+ "closeMs": close_ms,+ "open_close_ms": total,+ "bodyPointerEvents": "none",+ "bodyPointerEventsAfterClose": "auto",+ "itemsWhileOpen": 5,+ "triggersWhileHovered": 3,+ }+ }+++def test_one_repetition_that_never_opened_the_menu_poisons_the_median() -> None:+ # Filtering the null out and taking the median of the rest silently changes the sample+ # population, and the verdict's `openMs is None` check then reads the median of the+ # repetitions that worked.+ summary = HARNESS.summarise(+ [menu_repetition(80.0), menu_repetition(None), menu_repetition(120.0)]+ )+ assert summary["menu"]["openMs"] is None, summary["menu"]+++def test_a_timing_that_was_null_in_every_repetition_is_still_reported() -> None:+ # Present-and-None, not absent: a key that is missing entirely makes the verdict raise+ # KeyError instead of naming the action that never happened.+ summary = HARNESS.summarise([menu_repetition(None), menu_repetition(None)])+ assert "openMs" in summary["menu"] and summary["menu"]["openMs"] is None, summary["menu"]+++def test_the_median_of_three_good_repetitions_is_unchanged() -> None:+ # The guard above must not cost the normal case its median.+ summary = HARNESS.summarise(+ [menu_repetition(80.0), menu_repetition(100.0), menu_repetition(120.0)]+ )+ assert summary["menu"]["openMs"] == 100.0, summary["menu"]+++# ── the verdict must reject an action that never settled ──────────────+++def clean_cell() -> dict:+ """One (engine, size) cell that harness_failures() has nothing to say about."""+ per_cycle = {"images": 3, "codeBlocks": 7}+ counts = {+ "messages": 20,+ "domNodes": 4000,+ "codeBlocks": 7,+ "highlightedTokens": 3000,+ "images": 3,+ "actionBars": 10,+ "tooltipTriggers": 30,+ "collapsibleOutputs": 2,+ }+ action = {"ran": True, "wall_ms": 100.0, "longest_stall_ms": 10.0, "worst_frame_ms": 20.0}+ return {+ "chars_requested": 25000,+ "engine": "chromium",+ "plan": {"chars": 26000, "messages": 20, "cycles": 1, "expectedPerCycle": per_cycle},+ "counts": counts,+ "viewport": {"scrollHeight": 20000, "clientHeight": 900, "scrollTop": 0},+ "paint_floor_ms": 30.0,+ "stray_api_requests": 0,+ "console_warnings": 0,+ "first_console_warning": "-",+ "actions": {+ "keystroke": {+ **action,+ "median_sample_ms": 40.0,+ "domText": "aaa",+ "runtimeText": "aaa",+ },+ "scroll": {**action, "gestureMs": 300.0, "settleMs": 400.0, "scrolledPx": 8000},+ "jump": {+ **action,+ "paintedMs": 90.0,+ "settleMs": 200.0,+ "travelledPx": 19100,+ "landedAt": 0,+ },+ "menu": {+ **action,+ "openMs": 100.0,+ "closeMs": 40.0,+ "open_close_ms": 140.0,+ "itemsWhileOpen": 5,+ "triggersWhileHovered": 3,+ "bodyPointerEvents": "none",+ "bodyPointerEventsAfterClose": "auto",+ },+ "delete": {**action, "ms": 100.0, "before": 20, "after": 19},+ "reopen": {+ **action,+ "ms": 400.0,+ # One double-rAF wait, the floor GROWTH_AXES subtracts from the `reopen ms` axis.+ "paintWaits": 1,+ "closePaintWaits": 1,+ "closedMs": 20.0,+ "settleMs": 900.0,+ "before": 20,+ "after": 20,+ },+ },+ }+++def results_with(cell: dict) -> dict:+ return {+ "engines": ["chromium"],+ "sizes": [25000],+ "repetitions": 3,+ "by_engine": {"chromium": {"by_size": {"25000": cell}}},+ }+++def discriminating_report() -> dict:+ return {"chromium": {"scroll wall ms": {"discriminated": True, "ratio": 4.0}}}+++def test_a_clean_cell_produces_no_harness_failure() -> None:+ # The guards below are only worth anything if they are silent on a good run.+ assert HARNESS.harness_failures(results_with(clean_cell()), discriminating_report()) == []+++def test_a_scroll_that_never_settled_is_a_harness_failure() -> None:+ cell = copy.deepcopy(clean_cell())+ cell["actions"]["scroll"]["settleMs"] = None+ failures = HARNESS.harness_failures(results_with(cell), discriminating_report())+ assert any(+ "scroll action but it never reached a settled state" in f for f in failures+ ), failures+++def test_a_reopen_that_never_settled_is_a_harness_failure() -> None:+ cell = copy.deepcopy(clean_cell())+ cell["actions"]["reopen"]["settleMs"] = None+ failures = HARNESS.harness_failures(results_with(cell), discriminating_report())+ assert any(+ "reopen action but it never reached a settled state" in f for f in failures+ ), failures+++def test_a_jump_that_never_settled_is_a_harness_failure() -> None:+ cell = copy.deepcopy(clean_cell())+ cell["actions"]["jump"]["settleMs"] = None+ failures = HARNESS.harness_failures(results_with(cell), discriminating_report())+ assert any("jump action but it never reached a settled state" in f for f in failures), failures+++# ── the per-repetition fixture ────────────────────────────────────────+++class StubLocator:+ def __init__(self, log: list, selector: str) -> None:+ self.log = log+ self.selector = selector++ @property+ def last(self):+ return self++ def hover(self, timeout = None) -> None:+ self.log.append(("hover", self.selector))+++class StubPage:+ """Records the order of the calls one_repetition() makes, and nothing else.++ The question this answers is an ORDERING one -- does the highlighter gate run after the panes+ it has to highlight are mounted, and is the destroyed message put back before the next action+ measures the thread -- so a call log is the whole instrument.+ """++ ACTION_METRICS = {+ "metrics": {"wall_ms": 1.0, "frames": 1, "worst_frame_ms": 1.0},+ "ms": 1.0,+ }++ def __init__(self) -> None:+ self.log: list = []++ def evaluate(+ self,+ script,+ arg = None,+ ):+ for name in ("KEYSTROKE_JS", "SCROLL_JS", "JUMP_JS", "MENU_JS", "DELETE_JS", "REOPEN_JS"):+ if script is getattr(HARNESS, name):+ self.log.append(("action", name))+ return dict(self.ACTION_METRICS)+ if "__longTaskSupported" in script:+ return {"supported": False, "tasks": []}+ if "__longTasks.length" in script:+ return None+ if "expandTools" in script:+ self.log.append(("evaluate", "expandTools"))+ return 2+ if "restore()" in script:+ self.log.append(("evaluate", "restore"))+ return 20+ if "__hvTokens = undefined" in script:+ return None+ self.log.append(("evaluate", "other"))+ return None++ def wait_for_function(+ self,+ script,+ arg = None,+ timeout = None,+ polling = None,+ ):+ if "highlightedTokenCount" in script:+ self.log.append(("wait", "highlighting"))+ elif "codeExecutionPanes" in script:+ self.log.append(("wait", "toolPanes"))+ elif "messageCount" in script:+ self.log.append(("wait", "messageCount"))+ else:+ self.log.append(("wait", "other"))++ def locator(self, selector: str) -> StubLocator:+ return StubLocator(self.log, selector)+++def repetition_log() -> list:+ page = StubPage()+ HARNESS.one_repetition(page, None)+ return page.log+++def test_the_highlighter_gate_runs_after_the_tool_panes_are_mounted() -> None:+ # The tool result panes ARE code -- two of the seven fences a content cycle produces -- and+ # Radix does not mount them until they are expanded. Gating on the highlighter first and+ # expanding second leaves a fresh batch of unhighlighted fences building inside the keystroke+ # measurement, which is the very next thing timed.+ log = repetition_log()+ expand = log.index(("evaluate", "expandTools"))+ highlight = log.index(("wait", "highlighting"))+ assert expand < highlight, log+++def test_the_highlighter_gate_runs_before_the_first_measured_action() -> None:+ log = repetition_log()+ highlight = log.index(("wait", "highlighting"))+ assert highlight < log.index(("action", "KEYSTROKE_JS")), log+++def test_the_deleted_message_is_restored_before_anything_else_is_measured() -> None:+ # The delete removes a message from the repository, permanently. At the smallest size the+ # whole thread is one ten-kind cycle, so three repetitions take the json fence, then both+ # inline images, then the svg -- and the fixture census that would have caught it was taken+ # before any repetition ran.+ log = repetition_log()+ assert ("evaluate", "restore") in log, log+ assert (+ log.index(("action", "DELETE_JS"))+ < log.index(("evaluate", "restore"))+ < log.index(("action", "REOPEN_JS"))+ ), log+++def test_the_restored_thread_is_re_expanded_and_re_highlighted_before_re_open() -> None:+ # Restoring re-imports the thread, which unmounts every tool card and throws away every+ # highlighted fence. Re-opening straight afterwards would time that rebuild as well as its own.+ log = repetition_log()+ restore = log.index(("evaluate", "restore"))+ reopen = log.index(("action", "REOPEN_JS"))+ assert any(entry == ("wait", "highlighting") for entry in log[restore:reopen]), log+ assert any(entry == ("evaluate", "expandTools") for entry in log[restore:reopen]), log+++def test_the_tool_expand_gate_is_not_satisfied_by_a_thread_of_closed_cards() -> None:+ # `collapsibleOutputs` is the CollapsibleContent element itself, and Radix keeps that element+ # in the tree for its collapse animation, so it is there while the card is shut. Measured on+ # this tree at 300000 characters, straight after seeding and before any expandTools() call:+ # collapsibleOutputs 22 of the 22 expected, codeExecutionPanes 0. A `collapsibleOutputs >= n`+ # gate is therefore satisfied by the closed thread, which is a wait that cannot fail -- and it+ # released the highlighter gate below it before the two fences per cycle it exists to sequence+ # had mounted. The pane's <pre> is a CHILD of that element: 0 collapsed, 22 expanded.+ gates = [line for line in HARNESS_SOURCE.splitlines() if "counts()." in line]+ assert gates, "the fixture no longer gates on a count at all"+ for line in gates:+ assert "codeExecutionPanes" in line, line+++def test_the_smoke_page_can_restore_the_thread_it_seeded() -> None:+ page = (WORKDIR / "studio" / "frontend" / "smoke-heavy-thread-main.tsx").read_text(+ encoding = "utf-8"+ )+ assert "restore(): number" in page+ assert "seeded.current = built.messages" in page+++# ── the declared paint floor ──────────────────────────────────────────+#+# `growth()` subtracts `floored` double-rAF vsync floors from both ends of every ratio, and+# `floored` was a hand-declared integer per axis. Declaring it too low leaves a ~33ms constant in+# both ends, which drags the ratio towards 1 and can report a real curve as flat; declaring it too+# high subtracts time the action never spent. REOPEN_JS now counts the waits it actually pays, so+# the constant is checked against the run rather than trusted.+++def floor_row(+ observed,+ engine = "chromium",+ size = 25000,+):+ cell = {"actions": {"reopen": {"ms": 120.0, "paintWaits": observed}}}+ return {+ "engines": [engine],+ "sizes": [size],+ "by_engine": {engine: {"by_size": {str(size): cell}}},+ }+++def test_reopen_declares_the_one_paint_floor_it_pays() -> None:+ """Reopen is driven by a React state update, so the count check straight after openThread()+ always still sees the unmounted tree and the loop always waits at least one paint."""+ assert HARNESS.declared_floor("reopen ms") == 1+++def test_a_matching_floor_declaration_is_accepted() -> None:+ """The control. Without it the checks below could be met by rejecting every run."""+ assert HARNESS.floor_declaration_problems(floor_row(1)) == []+++def test_a_floor_declared_below_the_waits_paid_is_rejected() -> None:+ problems = HARNESS.floor_declaration_problems(floor_row(2))+ assert len(problems) == 1 and "subtracts 1" in problems[0], problems+++def test_a_floor_declared_above_the_waits_paid_is_rejected() -> None:+ problems = HARNESS.floor_declaration_problems(floor_row(0))+ assert len(problems) == 1 and "paid 0 paint wait" in problems[0], problems+++def test_an_unreported_wait_count_is_a_failure_not_a_skip() -> None:+ """A cell that stopped reporting `paintWaits` leaves the subtraction unverified. Skipping it+ is how this check would quietly stop checking anything."""+ row = floor_row(1)+ del row["by_engine"]["chromium"]["by_size"]["25000"]["actions"]["reopen"]["paintWaits"]+ problems = HARNESS.floor_declaration_problems(row)+ assert len(problems) == 1 and "unverified" in problems[0], problems+++def test_a_crashed_cell_is_not_reported_twice() -> None:+ """`harness_failures` already reports the crash itself, with the reason."""+ row = floor_row(0)+ row["by_engine"]["chromium"]["by_size"]["25000"]["crashed"] = "boom"+ assert HARNESS.floor_declaration_problems(row) == []+++def test_the_floor_check_decides_the_exit_code() -> None:+ """Wiring, not logic: a checker whose result never reaches `harness_failures` passes its own+ unit tests forever while the harness goes on publishing ratios built on the wrong constant."""+ body = HARNESS_SOURCE.split("def harness_failures", 1)[1]+ assert (+ "floor_declaration_problems(results)" in body+ ), "harness_failures ignores the paint-floor check, so a mis-declared floor never fails"+++def test_reopen_counts_the_waits_it_pays() -> None:+ """Source-level half: the counter has to be incremented in the loop that clocks `ms`."""+ reopen = HARNESS.REOPEN_JS.split("api.openThread();", 1)[1]+ assert "paintWaits += 1;" in reopen, "the reopen timing loop no longer counts its paint waits"+ assert "paintWaits," in HARNESS.REOPEN_JS, "the count is never returned to the harness"+++def test_an_action_that_did_not_run_is_not_reported_twice() -> None:+ """`harness_failures` already reports the action itself, with the reason. A second failure+ here for the same cause buries the real one."""+ row = floor_row(1)+ reopen = row["by_engine"]["chromium"]["by_size"]["25000"]["actions"]["reopen"]+ reopen["ran"] = False+ del reopen["paintWaits"]+ assert HARNESS.floor_declaration_problems(row) == []+++def test_an_action_that_ran_without_a_count_is_still_reported() -> None:+ """The other side of the skip above, so it cannot be widened into a blanket exemption."""+ row = floor_row(1)+ reopen = row["by_engine"]["chromium"]["by_size"]["25000"]["actions"]["reopen"]+ reopen["ran"] = True+ del reopen["paintWaits"]+ problems = HARNESS.floor_declaration_problems(row)+ assert len(problems) == 1 and "unverified" in problems[0], problems+++# ── the wall axes carry the floor they actually paid ──────────────────+++def wall_cells(+ paint_waits: int,+ floor_ms: float = 33.0,+ wall_ms: float = 200.0,+) -> dict:+ return {+ str(size): {+ "paint_floor_ms": floor_ms,+ "actions": {"menu": {"wall_ms": wall_ms, "paint_waits": paint_waits}},+ }+ for size in (25000, 300000)+ }+++def wall_axis():+ for name, pick, floored in HARNESS.GROWTH_AXES:+ if name == "menu wall ms":+ return pick, floored+ raise AssertionError("menu wall ms is no longer an axis")+++def test_the_wall_axis_floor_is_read_from_the_row_not_declared() -> None:+ """`MENU_JS` opens the recorder before opening the menu and closes it after closing it, so it+ crosses the same two waits `menu open+close ms` declares. The generated wall axes declared 0+ for every action, leaving that floor in both ends of the ratio."""+ _pick, floored = wall_axis()+ assert callable(floored), "the wall axis floor is a hardcoded number again"+ row = {"actions": {"menu": {"paint_waits": 2}}}+ assert floored(row) == 2+++def test_the_measured_floor_is_actually_subtracted() -> None:+ pick, floored = wall_axis()+ small, large = HARNESS.growth(wall_cells(2), pick, floored, [25000, 300000])+ assert small == 200.0 - 2 * 33.0, small+ assert large == 200.0 - 2 * 33.0, large+++def test_an_axis_that_paid_no_waits_is_left_alone() -> None:+ """The control: the change must not subtract a floor from a window that never waited."""+ pick, floored = wall_axis()+ small, _large = HARNESS.growth(wall_cells(0), pick, floored, [25000, 300000])+ assert small == 200.0, small+++def test_a_missing_wait_count_subtracts_nothing_rather_than_crashing() -> None:+ """An older result file has no `paint_waits`. Subtracting an unknown count would be worse+ than subtracting none, and raising would drop the axis entirely."""+ _pick, floored = wall_axis()+ assert floored({"actions": {"menu": {}}}) == 0+ assert floored({}) == 0+++# ── an application exception is not engine chatter ────────────────────+++def error_cell(seed_errors = 0, action_errors = 0) -> dict:+ cell = copy.deepcopy(clean_cell())+ cell["seed_console_errors"] = seed_errors+ cell["first_seed_error"] = "boom" if seed_errors else "-"+ cell["console_errors"] = action_errors+ cell["first_console_error"] = "TypeError: x is not a function" if action_errors else "-"+ return cell+++def test_a_clean_cell_still_passes_with_the_error_counters_present() -> None:+ """The control, so the two checks below cannot be met by rejecting every run."""+ assert HARNESS.harness_failures(results_with(error_cell()), discriminating_report()) == []+++def test_one_console_error_during_the_actions_fails_the_run() -> None:+ """Previously this went into the same list as Gecko's two scroll-anchoring notices and passed+ under the `> 4` allowance, so a run could exit 0 with an application exception in it."""+ failures = HARNESS.harness_failures(+ results_with(error_cell(action_errors = 1)), discriminating_report()+ )+ assert any("console error" in f and "measured actions" in f for f in failures), failures+++def test_one_console_error_during_seeding_fails_the_run() -> None:+ failures = HARNESS.harness_failures(+ results_with(error_cell(seed_errors = 1)), discriminating_report()+ )+ assert any("console error" in f and "seeding" in f for f in failures), failures+++def test_the_warning_allowance_still_tolerates_engine_chatter() -> None:+ """Firefox emits two scroll-anchoring notices and the harness must still be able to report a+ Gecko number. Errors are rejected; warnings under the allowance are not."""+ cell = error_cell()+ cell["console_warnings"] = HARNESS.CONSOLE_WARNING_ALLOWANCE+ assert HARNESS.harness_failures(results_with(cell), discriminating_report()) == []+++def test_warnings_and_errors_are_captured_into_separate_lists() -> None:+ """Source-level: one list for both is how the severity was lost in the first place."""+ assert "console_errors: list[str] = []" in HARNESS_SOURCE+ assert 'page.on("pageerror", lambda e: console_errors.append' in HARNESS_SOURCE+ assert 'if m.type == "error"' in HARNESS_SOURCE, "errors are no longer routed by severity"+ assert 'if m.type == "warning"' in HARNESS_SOURCE, "warnings are no longer routed by severity"+ # Keyed on the predicate alone, not on the whole expression around it: the first version of+ # this assertion pinned an exact one-line form and stayed green when the predicate was put+ # back on a line of its own.+ assert 'm.type in ("warning", "error")' not in HARNESS_SOURCE, (+ "one predicate captures both severities again, so an application exception is filed as "+ "chatter and absorbed by the warning allowance"+ )+++def test_the_recorder_zeroes_its_wait_counter_at_the_start_of_each_window() -> None:+ """Without the reset the count is cumulative across every action in the page, so each window+ subtracts a larger floor than it paid and later actions go negative."""+ begin = HARNESS_SOURCE.split(" begin() {", 1)[1].split("},", 1)[0]+ assert "__paintWaits = 0" in begin, (+ "begin() no longer zeroes the paint-wait counter, so every window inherits the waits of "+ "the ones before it"+ )+++# ── a counter rising from zero has to say something ───────────────────+#+# No ratio can be formed against zero, so DISCRIMINATION_RATIO never applies to these axes and+# `large > small` was the whole test. The CI workflow runs one repetition on Chromium, so there is+# no median to smooth a stray dropped frame, and `harness_failures` accepts any ONE discriminating+# axis: 0 at 25K and 1 at 100K could carry the entire verdict while every latency axis was flat.+++def counter_cells(+ small,+ large,+ sizes = (25000, 300000),+) -> dict:+ return {+ "engines": ["chromium"],+ "sizes": list(sizes),+ "repetitions": 1,+ "by_engine": {+ "chromium": {+ "by_size": {+ str(sizes[0]): {+ "paint_floor_ms": 33.0,+ "actions": {"scroll": {"frames_over_33": small}},+ },+ str(sizes[1]): {+ "paint_floor_ms": 33.0,+ "actions": {"scroll": {"frames_over_33": large}},+ },+ }+ }+ },+ }+++def counter_axis(results):+ return HARNESS.report_growth(results)["chromium"]["scroll frames over 33ms"]+++def test_one_stray_frame_does_not_discriminate() -> None:+ """The reported case: 0 at the smallest size and 1 at the largest."""+ row = counter_axis(counter_cells(0, 1))+ assert row["discriminated"] is False, row+ assert "under the" in row["reason"], row+++def test_a_counter_that_really_rose_still_discriminates() -> None:+ """The control. Without it the check above could be met by rejecting every counter, which+ would leave the harness unable to report a live run at all."""+ row = counter_axis(counter_cells(0, HARNESS.ZERO_BASED_MIN_RISE))+ assert row["discriminated"] is True, row+ assert "rose from zero to" in row["reason"], row+++def test_a_counter_just_under_the_threshold_does_not_discriminate() -> None:+ """Pins the boundary, so widening the threshold is a visible edit rather than a quiet one."""+ row = counter_axis(counter_cells(0, HARNESS.ZERO_BASED_MIN_RISE - 1))+ assert row["discriminated"] is False, row+++def test_zero_at_both_ends_is_still_reported_as_flat() -> None:+ row = counter_axis(counter_cells(0, 0))+ assert row["discriminated"] is False and row["reason"] == "zero at both ends", row+++def test_the_threshold_is_absolute_because_no_ratio_exists() -> None:+ """`DISCRIMINATION_RATIO` is a ratio and there is nothing to divide by here, so a separate+ absolute constant is required rather than a reuse of that one."""+ assert HARNESS.ZERO_BASED_MIN_RISE == 5+ assert "large >= ZERO_BASED_MIN_RISE" in HARNESS_SOURCE, (+ "the zero-based branch is back to a bare `large > small`, so one incidental dropped "+ "frame can carry the liveness verdict"+ )+++# ── zero-based is not the same as counted ─────────────────────────────+#+# The zero branch keyed on `floored`, which only identifies a timing that had a paint floor+# subtracted. An UNFLOORED timing reads zero at the smallest size whenever the action resolves+# before the recorder produces a sample, and was then treated as a dropped-frame counter, so a+# noisy 5ms at the largest size read as a rise of 5 and discriminated.+++def timing_cells(+ small,+ large,+ sizes = (25000, 300000),+) -> dict:+ return {+ "engines": ["chromium"],+ "sizes": list(sizes),+ "repetitions": 1,+ "by_engine": {+ "chromium": {+ "by_size": {+ str(sizes[0]): {+ "paint_floor_ms": 33.0,+ "actions": {"scroll": {"longest_stall_ms": small}},+ },+ str(sizes[1]): {+ "paint_floor_ms": 33.0,+ "actions": {"scroll": {"longest_stall_ms": large}},+ },+ }+ }+ },+ }+++def test_an_unfloored_timing_at_zero_does_not_discriminate() -> None:+ """`scroll longest stall ms` carries no paint floor, so the old `floored` test did not catch+ it, and 0 -> 5 milliseconds read as a rise of 5 events."""+ row = HARNESS.report_growth(timing_cells(0, 5))["chromium"]["scroll longest stall ms"]+ assert row["discriminated"] is False, row+ assert "timing, not a count" in row["reason"], row+++def test_a_counter_is_still_judged_as_a_counter() -> None:+ """The control: the fix must not turn every zero-based axis into an automatic no."""+ row = HARNESS.report_growth(counter_cells(0, HARNESS.ZERO_BASED_MIN_RISE))["chromium"][+ "scroll frames over 33ms"+ ]+ assert row["discriminated"] is True, row+++def test_the_counter_set_is_stated_and_non_empty() -> None:+ """Inferring which axes are counts is what produced the defect. If a rename ever empties this+ set, every counter silently becomes a timing and the liveness verdict loses its only+ zero-based axis, so the set is pinned against the axis list itself."""+ assert HARNESS.COUNTER_AXES, "no axis is classified as a counter any more"+ names = {name for name, _pick, _floored in HARNESS.GROWTH_AXES}+ assert (+ HARNESS.COUNTER_AXES <= names+ ), f"COUNTER_AXES names axes that do not exist: {HARNESS.COUNTER_AXES - names}"+ # Stated exactly rather than pattern-matched. My first attempt keyed on the name not ending+ # in "ms", which is wrong: the counter axis is called "frames over 33ms" and legitimately+ # does. Naming the whole set is the point of classifying it explicitly in the first place.+ assert HARNESS.COUNTER_AXES == frozenset(+ f"{action} frames over 33ms" for action in HARNESS.ACTIONS+ ), HARNESS.COUNTER_AXES+ timings = names - HARNESS.COUNTER_AXES+ assert (+ "scroll longest stall ms" in timings and "menu wall ms" in timings+ ), f"a timing axis is classified as a count: {HARNESS.COUNTER_AXES}"+++# ── the report has to survive being written out ───────────────────────+#+# Making the wall floor a callable put the lambda itself into the growth report. main() attaches+# that report to `results` and json.dumps it, so every complete run raised "Object of type+# function is not JSON serializable" AFTER taking all its measurements. No unit test caught it+# because none of them serialised the report, which is the gap this section closes.+++def test_the_growth_report_is_json_serializable() -> None:+ report = HARNESS.report_growth(counter_cells(0, 9))+ json.dumps(report) # raises if any value is a function+++def test_the_report_is_serializable_for_a_callable_floor_axis() -> None:+ """The wall axes are the ones whose floor is a callable, so they are the case that broke."""+ report = HARNESS.report_growth(+ {+ "engines": ["chromium"],+ "sizes": [25000, 300000],+ "repetitions": 1,+ "by_engine": {+ "chromium": {+ "by_size": {+ size: {+ "paint_floor_ms": 33.0,+ "actions": {"menu": {"wall_ms": 200.0, "paint_waits": 2}},+ }+ for size in ("25000", "300000")+ }+ }+ },+ }+ )+ json.dumps(report)+ assert report["chromium"]["menu wall ms"]["floored"] == [2, 2], report["chromium"][+ "menu wall ms"+ ]+++def test_the_recorded_floor_is_the_count_that_was_subtracted() -> None:+ """A boolean would serialise too and say nothing. The report carries the actual count at each+ end of the ratio, so a reader can check the subtraction rather than trust it."""+ report = HARNESS.report_growth(wall_cells_for_report(2))+ assert report["chromium"]["menu wall ms"]["floored"] == [2, 2]+ report = HARNESS.report_growth(wall_cells_for_report(0))+ assert report["chromium"]["menu wall ms"]["floored"] == [0, 0]+++def wall_cells_for_report(paint_waits: int) -> dict:+ return {+ "engines": ["chromium"],+ "sizes": [25000, 300000],+ "repetitions": 1,+ "by_engine": {+ "chromium": {+ "by_size": {+ size: {+ "paint_floor_ms": 33.0,+ "actions": {"menu": {"wall_ms": 200.0, "paint_waits": paint_waits}},+ }+ for size in ("25000", "300000")+ }+ }+ },+ }+++# ── halves, and counters that never left the noise ────────────────────+++def test_a_fractional_median_wait_count_is_not_truncated() -> None:+ """`summarise` medians the wait count across repetitions, so an even-repetition run whose+ repetitions paid 1 and 2 reports 1.5. Truncating that to 1 left half a vsync floor in the+ wall axis, and the documented two-repetition configurations are the ones that produce it."""+ assert (+ HARNESS.resolve_floor(+ HARNESS._floor_from("menu", "paint_waits"), {"actions": {"menu": {"paint_waits": 1.5}}}+ )+ == 1.5+ )+++def test_the_fractional_floor_is_actually_subtracted() -> None:+ report = HARNESS.report_growth(wall_cells_for_report(1.5))+ row = report["chromium"]["menu wall ms"]+ assert row["floored"] == [1.5, 1.5], row+ assert row["small"] == round(200.0 - 1.5 * 33.0, 2), row+++def test_a_counter_with_a_nonzero_baseline_still_needs_the_noise_floor() -> None:+ """1 -> 2 dropped frames is a ratio of 2.0 and cleared DISCRIMINATION_RATIO, and one+ discriminating axis is enough for the whole run to pass."""+ row = HARNESS.report_growth(counter_cells(1, 2))["chromium"]["scroll frames over 33ms"]+ assert row["discriminated"] is False, row+ assert "distinguishable from noise" in row["reason"], row+++def test_a_counter_that_rose_well_past_the_noise_floor_still_discriminates() -> None:+ """The control, so the rule above cannot be met by rejecting every nonzero counter."""+ row = HARNESS.report_growth(counter_cells(2, 40))["chromium"]["scroll frames over 33ms"]+ assert row["discriminated"] is True, row+++def test_a_timing_with_a_small_nonzero_baseline_is_untouched() -> None:+ """The noise floor is a count of events. Applying it to milliseconds would silently reject+ real latency curves that happen to sit at low absolute values."""+ row = HARNESS.report_growth(timing_cells(1.0, 4.0))["chromium"]["scroll longest stall ms"]+ assert row["discriminated"] is True, row+++# ── whole-window axes carry the whole window's floors ─────────────────+#+# `quiet()` and `quietUntilIdle()` return `... - this.startedAt`, not the time they themselves+# took, and `gestureMs` is computed from `startedAt` too. All three therefore span the entire+# recorder window and contain every double-rAF wait in it. They declared zero, which left roughly+# twenty vsync floors in both ends of the scroll ratios.+++def axis_floor(name):+ for axis, _pick, floored in HARNESS.GROWTH_AXES:+ if axis == name:+ return floored+ raise AssertionError(f"{name} is not an axis")++[email protected]("name", ("scroll gesture ms", "scroll settle ms", "jump settle ms"))+def test_whole_window_axes_use_the_measured_floor(name) -> None:+ floored = axis_floor(name)+ assert callable(floored), f"{name} declares a fixed floor but spans the whole window"+ action = name.split(" ")[0]+ assert floored({"actions": {action: {"paint_waits": 20}}}) == 20++[email protected]("name", ("jump painted ms", "menu open+close ms", "reopen ms"))+def test_partial_window_axes_keep_their_declared_floor(name) -> None:+ """The other half of the rule, and it is not symmetry for its own sake.++ `paintedMs` starts at a mark taken after `begin()` and spans one wait while the jump's window+ holds two. `MENU_JS` awaits no paint at all, so the window count is zero while its two floors+ are real, coming from `settle()` reading the pre-MutationObserver state on entry. Applying the+ window count to either would subtract a floor the number never contained, or remove one that+ it did.+ """+ assert not callable(+ axis_floor(name)+ ), f"{name} was given the whole-window floor, which it does not carry"+++def test_the_scroll_ratio_is_not_compressed_by_the_gesture_floors() -> None:+ """End to end: twenty floors left in both ends is what flattens the curve."""+ cells = {+ "engines": ["chromium"],+ "sizes": [25000, 300000],+ "repetitions": 1,+ "by_engine": {+ "chromium": {+ "by_size": {+ "25000": {+ "paint_floor_ms": 33.0,+ "actions": {"scroll": {"gestureMs": 700.0, "paint_waits": 20}},+ },+ "300000": {+ "paint_floor_ms": 33.0,+ "actions": {"scroll": {"gestureMs": 1300.0, "paint_waits": 20}},+ },+ }+ }+ },+ }+ row = HARNESS.report_growth(cells)["chromium"]["scroll gesture ms"]+ # 700 - 660 = 40, 1300 - 660 = 640: a 16x curve that reads as 1.86x with the floors left in.+ assert row["small"] == 40.0 and row["large"] == 640.0, row+ assert row["ratio"] > 10 and row["discriminated"] is True, row+++if __name__ == "__main__":+ raise SystemExit(pytest.main([__file__, "-q"]))