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: keep the streaming render harness the perf PRs kept rebuilding (#8969)
Daniel Han1f09a17868e6
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.ymlindex bfa140e3d2d..e3fcb8051c4 100644--- a/.github/workflows/studio-frontend-ci.yml+++ b/.github/workflows/studio-frontend-ci.yml@@ -21,6 +21,7 @@ on:- 'tests/studio/playwright_strip_ansi_smoke.py'- 'tests/studio/playwright_chat_autoscroll.py'- 'tests/studio/playwright_research_freeze.py'+ - 'tests/studio/playwright_stream_pacing.py'# Shared lifecycle helpers, and the contract test that keeps verdicts from going unread.- 'tests/studio/_playwright_robust.py'- 'tests/studio/test_autoscroll_harness_contract.py'@@ -186,6 +187,16 @@ jobs:working-directory: ${{ github.workspace }}run: python3 tests/studio/playwright_research_freeze.py+ # Reports, does not gate, for now. The budgets inside are calibrated on a+ # developer machine, and this measures a CPU-bound render on a shared runner+ # under 6x throttling, so a budget set from one box is a flake waiting to+ # happen. Tighten it from observed runs here and drop continue-on-error, the+ # way the startup profile did.+ - name: Browser smoke for chat stream pacing+ working-directory: ${{ github.workspace }}+ continue-on-error: true+ run: python3 tests/studio/playwright_stream_pacing.py+- name: Buildrun: npm run builddiff --git a/studio/frontend/smoke-stream-pacing-main.tsx b/studio/frontend/smoke-stream-pacing-main.tsxnew file mode 100644index 00000000000..e94eea6d4b4--- /dev/null+++ b/studio/frontend/smoke-stream-pacing-main.tsx@@ -0,0 +1,319 @@+// 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 for tests/studio/playwright_stream_pacing.py: the real MarkdownText inside a real+// assistant-ui runtime, fed a fixed reply at a fixed rate, so the measured main-thread cost+// is the chat renderer's own. Same shape as smoke-autoscroll.html and smoke-research.html:+// a vite entry, no backend, no auth, no model.+//+// Four merged PRs moved this path (#7892 transition starvation, #8750 incremental Markdown,+// #8845 publish coalescing, #8935 incremental fence tokenization) and each rebuilt a+// throwaway harness to prove it. The number they all reported is `longestStallMs`: the+// longest the bubble stops growing while text is still arriving.+//+// A local runtime rather than a bare component: MarkdownText reads its message part from+// assistant-ui context and its BlockComponent reads `useAuiState`, so mounting it outside a+// provider throws. The real runtime also puts assistant-ui's own update scheduling inside+// the measurement, which is where #7892's starvation lived.+//+// The reply is a fixed string, not a model's output. #8845's first measurement attempts+// failed because free-form sampling gave the two sides different essays, and the renderer's+// cost is superlinear in length, so comparing across different text says nothing.++/* eslint-disable no-restricted-imports -- a measurement entry point, not app code. */+// This store first, deliberately. MarkdownText's import graph reaches the chat barrel and the+// settings General tab reaches back for SIDEBAR_ORGANIZATION_STORAGE_KEY, so entering that+// cycle from the renderer leaves the constant in its temporal dead zone and the harness+// renders nothing. Evaluating the store first breaks the tie, as the app's entry order does.+import "@/features/chat/stores/sidebar-organization-store";+// And the chat barrel before MarkdownText, as the app's entry does. thread.tsx builds+// ASSISTANT_PART_COMPONENTS at module scope with `Text: MarkdownText`, so entering the+// markdown-text -> features/chat -> chat-page -> thread cycle from markdown-text runs that+// object literal while the MarkdownText binding is still in its temporal dead zone and the+// page dies with "Cannot access 'MarkdownText' before initialization".+import "@/features/chat";+/* eslint-enable no-restricted-imports */++import { MarkdownText } from "@/components/assistant-ui/markdown-text";+import {+ AssistantRuntimeProvider,+ type ChatModelAdapter,+ MessagePrimitive,+ ThreadPrimitive,+ useAui,+ useLocalRuntime,+} from "@assistant-ui/react";+import { type ReactElement, useEffect } from "react";+import { createRoot } from "react-dom/client";+import { stallInProgress } from "./smoke-stream-pacing-stall.ts";+import "./src/index.css";++/**+ * Deterministic, and shaped like what the renderer is slow on: prose to lay out, a fenced+ * block for Shiki, display math for KaTeX. Repeated so length is a knob, not a new fixture.+ */+export function buildReply(totalChars: number): string {+ const units = [+ "The printing press did not arrive as a single invention so much as a " ++ "convergence: movable type, a workable oil-based ink, and a screw press " ++ "already used for wine and olives. Each existed before Mainz; what changed " ++ "was that one workshop held all three at once.\n\n",+ "```ts\nfunction paginate(sheets: number, perSheet: number): number[] {\n" ++ " const out: number[] = [];\n for (let i = 0; i < sheets; i += 1) {\n" ++ " out.push(i * perSheet);\n }\n return out;\n}\n```\n\n",+ "Setting a single page took a compositor the better part of a day, so the " ++ "economics only worked above a threshold print run. That threshold is what " ++ "the arithmetic below expresses.\n\n",+ "$$\nc_{\\text{unit}} = \\frac{F + vn}{n} = v + \\frac{F}{n}\n$$\n\n",+ "- Fixed cost dominates at small runs\n- Variable cost dominates at large ones\n" ++ "- The crossover moved with paper prices, not with the press\n\n",+ ];+ let text = "";+ let index = 0;+ while (text.length < totalChars) {+ text += units[index % units.length];+ index += 1;+ }+ return text.slice(0, totalChars);+}++type Results = {+ startedAt: number;+ arrivals: number;+ sentChars: number;+ paintedChars: number;+ longestStallMs: number;+ timeToFullyPaintedMs: number | null;+ streamEndedAtMs: number | null;+ longTaskMs: number;+ longTasks: number;+ longTaskSupported: boolean;+ framesOver33ms: number;+ settledChars: number;+ done: boolean;+};++type RunOptions = { totalChars?: number; chunkChars?: number; gapMs?: number };++declare global {+ interface Window {+ __stream: {+ ready: boolean;+ run(options?: RunOptions): void;+ results(): Results;+ };+ }+}++const state: Results = {+ startedAt: 0,+ arrivals: 0,+ sentChars: 0,+ paintedChars: 0,+ longestStallMs: 0,+ timeToFullyPaintedMs: null,+ streamEndedAtMs: null,+ longTaskMs: 0,+ longTasks: 0,+ longTaskSupported: false,+ framesOver33ms: 0,+ settledChars: 0,+ done: false,+};++/** Consecutive frames without growth that count as settled. */+const SETTLED_FRAMES = 30;++let config: Required<RunOptions> = {+ totalChars: 24_000,+ chunkChars: 24,+ gapMs: 2,+};++const sleep = (ms: number) =>+ new Promise((resolve) => {+ setTimeout(resolve, ms);+ });++// Stands in for the network, not the renderer: the same growing cumulative text the chat+// adapter yields, at a fixed rate.+const adapter: ChatModelAdapter = {+ async *run() {+ const reply = buildReply(config.totalChars);+ let cursor = 0;+ state.startedAt = performance.now();+ while (cursor < reply.length) {+ cursor = Math.min(reply.length, cursor + config.chunkChars);+ state.arrivals += 1;+ state.sentChars = cursor;+ yield {+ content: [{ type: "text" as const, text: reply.slice(0, cursor) }],+ };+ await sleep(config.gapMs);+ }+ state.streamEndedAtMs = performance.now() - state.startedAt;+ },+};++function AssistantMessage(): ReactElement {+ return (+ <div className="min-w-0 max-w-full">+ <MessagePrimitive.Parts components={{ Text: MarkdownText }} />+ </div>+ );+}++function NoUserMessage(): null {+ return null;+}++function Harness(): ReactElement {+ const runtime = useLocalRuntime(adapter);+ const aui = useAui({});++ useEffect(() => {+ // Painted, not published: "the bubble stopped growing" is the complaint, and a store+ // update that never reaches paint does not answer it. So read the DOM.+ const paintedChars = (): number => {+ const node = document.querySelector("[data-status]");+ return node ? (node.textContent ?? "").length : 0;+ };++ let lastGrowthAt = 0;+ let lastFrameAt = 0;+ let settledChars = 0;+ let quietFrames = 0;+ let handle = requestAnimationFrame(function watch(now: number) {+ // Windowed like the long tasks: a frame dropped while loading is not the renderer's.+ // 0 of 286 here, but a slower box need not be 0 and the number must compare across both.+ if (now >= measureFrom && lastFrameAt && now - lastFrameAt > 33) {+ state.framesOver33ms += 1;+ }+ lastFrameAt = now;+ if (state.startedAt) {+ if (!lastGrowthAt) {+ lastGrowthAt = state.startedAt;+ }+ const painted = paintedChars();+ if (painted > state.paintedChars) {+ const stall = now - lastGrowthAt;+ if (stall > state.longestStallMs) {+ state.longestStallMs = stall;+ }+ state.paintedChars = painted;+ lastGrowthAt = now;+ } else {+ // Measure the stall in progress: a stall closed only by a LATER paint misses a+ // freeze that runs to the end of the stream, whose lost tail can hide inside the+ // 90% floor. stallInProgress caps it at stream end, so a freeze spanning that+ // moment is still recorded in full while the settle check's own quiet frames are+ // not counted as one.+ const stall = stallInProgress(+ lastGrowthAt,+ now,+ state.startedAt,+ state.streamEndedAtMs,+ );+ if (stall > state.longestStallMs) {+ state.longestStallMs = stall;+ }+ }+ // Settled is counted in FRAMES without growth, not wall clock: #8845's last+ // failed attempt used a 1.5s quiet window and called a reply finished mid+ // freeze. A freeze blocks the frame loop too, so a frame counter cannot tick+ // through one. Rendered length is compared against itself, not the bytes sent,+ // because Markdown syntax (fences, list markers, math delimiters) never+ // reaches textContent.+ if (state.streamEndedAtMs !== null && state.timeToFullyPaintedMs === null) {+ if (painted > settledChars) {+ settledChars = painted;+ quietFrames = 0;+ } else {+ quietFrames += 1;+ if (quietFrames >= SETTLED_FRAMES) {+ // On screen at settlement, not the peak: paintedChars only climbs, so a+ // completion render that truncates the bubble would still pass the workload+ // floor. This is the length the driver checks. Equal to the peak (24,033+ // both) today, so it is a guard, not a live discrepancy.+ state.settledChars = painted;+ state.timeToFullyPaintedMs = now - state.startedAt;+ state.done = true;+ }+ }+ }+ }+ handle = requestAnimationFrame(watch);+ });++ // `observe({type})` aborts silently on an unsupported entry type instead of throwing,+ // so a try/catch never fires and the long-task total stays 0, a perfect score on the+ // budget that matters most. Only supportedEntryTypes answers the question, and the+ // answer is recorded so the driver can fail the run instead of reporting the zero.+ // Chromium alone ships longtask (Gecko bug 1348405 open, WebKit never shipped it).+ // run() moves measureFrom to the moment the stream is asked for, so nothing the page+ // did while loading lands in the budget.+ let measureFrom = Number.POSITIVE_INFINITY;+ let observer: PerformanceObserver | null = null;+ state.longTaskSupported =+ typeof PerformanceObserver !== "undefined" &&+ (PerformanceObserver.supportedEntryTypes ?? []).includes("longtask");+ if (state.longTaskSupported) {+ observer = new PerformanceObserver((list) => {+ for (const entry of list.getEntries()) {+ // Only tasks belonging to the stream. `buffered: true` replays what the timeline+ // already held, on a dev server module evaluation and the first React render:+ // ~140ms in one entry, ~2.6% of the total, and larger on a cold or loaded runner.+ // That is page startup, and budgeting it makes a cold run look like a slow renderer.+ if (entry.startTime < measureFrom) continue;+ state.longTasks += 1;+ state.longTaskMs += entry.duration;+ }+ });+ observer.observe({ type: "longtask", buffered: true });+ }++ window.__stream = {+ ready: true,+ run(options: RunOptions = {}) {+ config = { ...config, ...options };+ // Open the window and drop what the buffered replay banked. A straddling entry is+ // discarded, not prorated: it began before the stream, so it is not the renderer's.+ measureFrom = performance.now();+ state.longTaskMs = 0;+ state.longTasks = 0;+ state.framesOver33ms = 0;+ // Append from a later task. In this same task, a long task is stamped with its+ // task's start, so runtime startup and the first publish would sort before+ // measureFrom and be dropped as page load. A fresh task starts after it.+ setTimeout(() => {+ void runtime.thread.append({+ role: "user",+ content: [{ type: "text", text: "stream the fixture" }],+ });+ }, 0);+ },+ results: () => ({ ...state }),+ };++ return () => {+ cancelAnimationFrame(handle);+ observer?.disconnect();+ };+ }, [runtime]);++ return (+ <AssistantRuntimeProvider runtime={runtime} aui={aui}>+ <ThreadPrimitive.Root+ style={{ width: 900, margin: "0 auto", padding: 16 }}+ >+ <ThreadPrimitive.Viewport>+ <ThreadPrimitive.Messages+ components={{ AssistantMessage, UserMessage: NoUserMessage }}+ />+ </ThreadPrimitive.Viewport>+ </ThreadPrimitive.Root>+ </AssistantRuntimeProvider>+ );+}++createRoot(document.getElementById("root") as HTMLElement).render(<Harness />);diff --git a/studio/frontend/smoke-stream-pacing-stall.ts b/studio/frontend/smoke-stream-pacing-stall.tsnew file mode 100644index 00000000000..42a30c2b59b--- /dev/null+++ b/studio/frontend/smoke-stream-pacing-stall.ts@@ -0,0 +1,35 @@+// 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 stall rule for smoke-stream-pacing-main.tsx, kept here so it can be tested without+// importing the harness entry, which mounts React into the DOM on import.++/**+ * How long the bubble has gone without growing, for a stall that no later paint has closed.+ *+ * The subtlety is what the interval is measured UP TO. While text is still arriving that is+ * simply `now`. Once the stream has ended it is the moment it ended, for two opposite reasons+ * that both point the same way:+ *+ * - a freeze that spans the end of the stream blocks the frame loop across it, so the first+ * frame afterwards already observes an ended stream. Refusing to measure once the stream has+ * ended would skip that whole interval and report no freeze at all, which is the one shape+ * this number exists to catch. The lost tail can hide inside the 90% workload floor.+ * - measuring up to `now` after the stream has ended would count the quiet frames the settle+ * check itself needs, so every healthy run would report a stall the length of the settle+ * window.+ *+ * Capping at stream end satisfies both: the frozen interval is recorded in full, and it stops+ * growing once there is no more text to be waiting for. Repeat calls return the same value, so+ * calling this on every frame after the stream ends is idempotent.+ */+export function stallInProgress(+ lastGrowthAt: number,+ now: number,+ startedAt: number,+ streamEndedAtMs: number | null,+): number {+ const until = streamEndedAtMs === null ? now : startedAt + streamEndedAtMs;+ const stall = until - lastGrowthAt;+ return stall > 0 ? stall : 0;+}diff --git a/studio/frontend/smoke-stream-pacing.html b/studio/frontend/smoke-stream-pacing.htmlnew file mode 100644index 00000000000..7bb649b0575--- /dev/null+++ b/studio/frontend/smoke-stream-pacing.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <script src="/crypto-boot.js"></script>+ <title>chat stream pacing smoke</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/smoke-stream-pacing-main.tsx"></script>+ </body>+</html>diff --git a/studio/frontend/tests/stream-pacing-stall.test.ts b/studio/frontend/tests/stream-pacing-stall.test.tsnew file mode 100644index 00000000000..2b072e49023--- /dev/null+++ b/studio/frontend/tests/stream-pacing-stall.test.ts@@ -0,0 +1,49 @@+// 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 stall rule behind the stream-pacing smoke's longestStallMs, which is the budget that+// catches the freeze class #7892 and #8845 fixed. A stall the harness fails to record is a+// harness that passes on a frozen renderer, so the interesting cases here are the ones where+// no later paint ever arrives to close the stall.++import assert from "node:assert/strict";+import test from "node:test";++import { stallInProgress } from "../smoke-stream-pacing-stall.ts";++const STARTED_AT = 1_000;++test("while text is still arriving, the stall runs to now", () => {+ assert.equal(stallInProgress(2_000, 3_500, STARTED_AT, null), 1_500);+});++test("a freeze spanning the end of the stream is still recorded in full", () => {+ // The regression this exists for. The frame loop is blocked across the moment the stream+ // ends, so the first frame afterwards (now = 9_000) already sees a non-null streamEndedAtMs.+ // Measuring only while the stream is live would skip the whole interval and report nothing,+ // and the missing tail can hide inside the harness's 90% workload floor.+ const streamEndedAtMs = 4_000; // absolute 5_000+ assert.equal(stallInProgress(1_500, 9_000, STARTED_AT, streamEndedAtMs), 3_500);+});++test("after the stream ends the stall stops growing with the settle window", () => {+ // The settle check needs 30 quiet frames by design. Measuring to now would count them, so+ // every healthy run would report a stall the length of its own settle window.+ const streamEndedAtMs = 4_000; // absolute 5_000+ const atEnd = stallInProgress(4_800, 5_000, STARTED_AT, streamEndedAtMs);+ const muchLater = stallInProgress(4_800, 60_000, STARTED_AT, streamEndedAtMs);+ assert.equal(atEnd, 200);+ assert.equal(muchLater, 200, "quiet frames after the stream ended are not a stall");+});++test("it is idempotent once the stream has ended", () => {+ const first = stallInProgress(2_000, 6_000, STARTED_AT, 4_000);+ const second = stallInProgress(2_000, 30_000, STARTED_AT, 4_000);+ assert.equal(first, second);+});++test("growth after the stream ended is not a negative stall", () => {+ // lastGrowthAt can sit past the stream end when the tail paints late, which would make the+ // capped interval negative. Report no stall rather than a negative one.+ assert.equal(stallInProgress(8_000, 9_000, STARTED_AT, 4_000), 0);+});diff --git a/studio/frontend/tsconfig.app.json b/studio/frontend/tsconfig.app.jsonindex beb31bd09d9..8e7ff07fd60 100644--- a/studio/frontend/tsconfig.app.json+++ b/studio/frontend/tsconfig.app.json@@ -32,6 +32,7 @@"src","smoke-ansi-main.tsx","smoke-autoscroll-main.tsx",- "smoke-research-main.tsx"+ "smoke-research-main.tsx",+ "smoke-stream-pacing-main.tsx"]}diff --git a/tests/studio/playwright_stream_pacing.py b/tests/studio/playwright_stream_pacing.pynew file mode 100644index 00000000000..87324e134ef--- /dev/null+++ b/tests/studio/playwright_stream_pacing.py@@ -0,0 +1,255 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Main-thread cost of a fast streaming reply in the chat renderer.++Four merged PRs moved this path and each rebuilt a throwaway harness to prove it:++ #7892 Streamdown's transition starvation 9.86s -> 0.34s longest freeze+ #8750 incremental Markdown parsing O(n) per update -> tail only+ #8845 publish coalescing 4.01s -> 0.62s longest stall+ #8935 incremental fence tokenization 21x fewer characters to Shiki++None of them left anything behind that would notice the next regression, and each had to+rediscover the same methodology. This is that harness, kept.++It drives smoke-stream-pacing.html, which mounts the real MarkdownText inside a real+assistant-ui local runtime, so nothing is a mock of the code under test and assistant-ui's+own update scheduling is inside the measurement. Runs against a vite dev server; no+backend, no auth, no GPU, no model.++The reply is a fixed string. #8845's first measurement attempts failed because a real+model gave the two sides different essays and the renderer's cost is superlinear in+length, so a comparison across different text says nothing.++CPU throttling is not decoration: on a developer machine the renderer keeps up with any+rate this can feed, so an unthrottled run measures nothing on either side.++Chromium only, deliberately. Both things that make this a measurement are Chromium-only:+`Emulation.setCPUThrottlingRate` is reached over CDP, which Playwright exposes for Chromium+alone, and `longtask` PerformanceObserver entries exist in no other engine (Gecko bug+1348405 is open; WebKit has never shipped them). Neither fails loudly on firefox or webkit,+since `observe({type: "longtask"})` is specified to abort silently on an unsupported type+rather than throw, so the budgets would read a perfect zero instead of an error. The verdict+below therefore refuses a run that saw no long tasks, and the harness records whether the+engine supported them.++Run:+ python tests/studio/playwright_stream_pacing.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.+"""++from __future__ import annotations++import json+import os+import sys+import time+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", "5186"))+# Unset: start and stop our own server. Set: drive that one and leave it running.+# Exported-but-empty counts as unset, else we skip the server and drive "" as the URL.+_EXTERNAL = os.environ.get("SMOKE_BASE_URL", "").strip()+BASE = _EXTERNAL or f"http://127.0.0.1:{PORT}"+OWNS_SERVER = not _EXTERNAL+# Under logs/ like every sibling harness. A default of "." would drop an untracked+# stream-pacing.json in the repo root every run; logs/ is gitignored, so the tree stays clean.+OUT = Path(os.environ.get("PW_ART_DIR", "logs/playwright-stream-pacing"))+LABEL = "stream-pacing"++# The reply and the rate it arrives at. Length is what the renderer's cost is superlinear+# in, so it is the knob that matters; the arrival count stays modest because throttling+# slows the feed's own timers too, and 1,000 arrivals at 6x stretched a one-second stream+# to 43s of wall clock for no extra signal.+TOTAL_CHARS = int(os.environ.get("SMOKE_STREAM_CHARS", "24000"))+CHUNK_CHARS = int(os.environ.get("SMOKE_STREAM_CHUNK", "96"))+GAP_MS = int(os.environ.get("SMOKE_STREAM_GAP_MS", "2"))+THROTTLE = int(os.environ.get("SMOKE_STREAM_THROTTLE", "6"))++# Budgets, not targets, chosen against real regressions rather than by feel. Two merged+# fixes were reverted in this harness, on two machines, and they move the two numbers in+# opposite directions, which is why there are two budgets and not one headline metric.+#+# main #8750 reverted #7892 reverted+# long tasks 5.0-8.0s 13.1s/74.4s 6.7-7.9s+# long task count 49-71 144/598 14-23+# longest stall 1.05-1.23s 0.97-1.40s 5.03-6.35s+#+# Reverting #8750 (incremental Markdown parsing) blows up the long-task total and leaves+# the longest stall alone. Reverting #7892 (Streamdown's `animated` config, which keeps+# block updates out of an interruptible transition) does the opposite: the stall goes 4-5x+# while the long-task total stays in the clean range. A single headline metric would have+# missed one of the two outright.+#+# Machine spread: the "main" column above is 5,029/5,901ms on one machine and 6,687-8,003ms+# on another, so clean readings vary ~60% ACROSS boxes even though a single box repeats to+# within ~15%. That is what keeps the CI step non-gating. The 10,000ms budget is NOT raised+# for that headroom, because the same two machines read the #8750 revert as 13,059ms and+# 74,353ms: a budget loose enough for the slower box would stop catching that regression on+# the faster one. Retune from observed runner numbers, not from one machine.+MAX_LONGEST_STALL_MS = int(os.environ.get("SMOKE_STREAM_STALL_BUDGET_MS", "2500"))+MAX_LONG_TASK_MS = int(os.environ.get("SMOKE_STREAM_LONG_TASK_BUDGET_MS", "10000"))+++def info(msg: str) -> None:+ print(f"[{LABEL}] {msg}", flush = True)+++def run() -> dict:+ headless = os.environ.get("SMOKE_HEADFUL") != "1"+ with sync_playwright() as p:+ browser = p.chromium.launch(headless = headless, args = chromium_launch_args())+ context = browser.new_context(viewport = {"width": 1200, "height": 900})+ page = context.new_page()+ errors: list[str] = []+ page.on("pageerror", lambda e: errors.append(str(e)))+ try:+ page.goto(f"{BASE}/smoke-stream-pacing.html", wait_until = "load", timeout = 60_000)+ page.wait_for_function("() => window.__stream && window.__stream.ready", timeout = 60_000)++ cdp = context.new_cdp_session(page)+ # After load so the harness bundle is not itself throttled in, and recorded+ # below so a difference can never be an artefact of uneven throttling.+ if THROTTLE > 1:+ cdp.send("Emulation.setCPUThrottlingRate", {"rate": THROTTLE})++ page.evaluate(+ "(o) => window.__stream.run(o)",+ {"totalChars": TOTAL_CHARS, "chunkChars": CHUNK_CHARS, "gapMs": GAP_MS},+ )++ # Poll the harness's own verdict rather than deciding out here: every round+ # trip is slowed by the throttling, so an outside "has it finished" arrives+ # late enough to hide the effect.+ deadline = time.monotonic() + 300+ results: dict = {}+ while time.monotonic() < deadline:+ results = page.evaluate("() => window.__stream.results()")+ if results.get("done"):+ break+ time.sleep(0.25)+ if not results.get("done"):+ raise RuntimeError(+ f"the reply never finished painting within 300s: {json.dumps(results)}"+ )+ finally:+ context.close()+ browser.close()++ results["page_errors"] = errors+ results["cpu_throttle"] = THROTTLE+ results["total_chars"] = TOTAL_CHARS+ results["chunk_chars"] = CHUNK_CHARS+ results["gap_ms"] = GAP_MS+ return results+++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-stream-pacing.html",+ "smoke-stream-pacing-main.tsx",+ proc = vite,+ info = info,+ )+ results = run()+ finally:+ if vite is not None:+ stop_process(vite)+ info("vite stopped")++ out = OUT / f"{LABEL}.json"+ out.parent.mkdir(parents = True, exist_ok = True)+ out.write_text(json.dumps(results, indent = 2), encoding = "utf-8")+ info(json.dumps(results, indent = 2))+ info(f"wrote {out}")++ failures: list[str] = []+ # A page that painted nothing scores a perfect zero on every budget below, so assert+ # the workload first. Not an equality: Markdown syntax (fences, list markers, math+ # delimiters) never reaches textContent, so rendered length is a few per cent under the+ # bytes sent. 90% is above that and far below "the render died early".+ floor = int(TOTAL_CHARS * 0.9)+ if results["paintedChars"] < floor:+ failures.append(+ f"only {results['paintedChars']} characters painted of {TOTAL_CHARS} sent "+ f"(floor {floor}); the budgets below measured no workload"+ )+ # paintedChars is a high-water mark and survives a completion render that truncates the+ # bubble. settledChars is the DOM a reader is actually left looking at.+ if results["settledChars"] < floor:+ failures.append(+ f"the reply settled at {results['settledChars']} characters of {TOTAL_CHARS} "+ f"sent (floor {floor}); it peaked at {results['paintedChars']} and then lost "+ "content, so the final render is incomplete"+ )+ if results["arrivals"] < TOTAL_CHARS // CHUNK_CHARS:+ failures.append(+ f"only {results['arrivals']} arrivals for {TOTAL_CHARS} characters; "+ "the stream did not run at the rate this claims to measure"+ )+ if results["longestStallMs"] > MAX_LONGEST_STALL_MS:+ failures.append(+ f"longest stall {results['longestStallMs']:.0f}ms exceeds "+ f"{MAX_LONGEST_STALL_MS}ms (the bubble stopped growing while text arrived)"+ )+ # The long-task total is the sensitive metric and the one that goes false-green most+ # quietly: an engine without the longtask entry type, or an observer that stopped+ # delivering, reports 0ms and sails under the budget without raising. Same reasoning as+ # the painted-characters floor above.+ if not results.get("longTaskSupported"):+ failures.append(+ "this engine reports no longtask entries, so the long-task budget measured "+ "nothing; run under Chromium"+ )+ elif results["longTasks"] <= 0:+ failures.append(+ "no long tasks were observed at all; the observer measured nothing, so the "+ f"{MAX_LONG_TASK_MS}ms budget below would pass on any tree"+ )+ if results["cpu_throttle"] <= 1:+ failures.append(+ f"CPU throttling was {results['cpu_throttle']}x; unthrottled, the renderer keeps "+ "up with any rate this can feed and the budgets measure nothing"+ )+ if results["longTaskMs"] > MAX_LONG_TASK_MS:+ failures.append(+ f"long tasks totalled {results['longTaskMs']:.0f}ms, over the "+ f"{MAX_LONG_TASK_MS}ms budget (the main thread is saturated by the render)"+ )+ if results["page_errors"]:+ failures.append(f"page errors: {results['page_errors']}")++ if failures:+ for f in failures:+ info(f"FAIL: {f}")+ return 1+ info(+ f"OK: longest stall {results['longestStallMs']:.0f}ms, "+ f"long tasks {results['longTaskMs']:.0f}ms, "+ f"{results['framesOver33ms']} frames over 33ms, fully painted at "+ f"{results['timeToFullyPaintedMs']:.0f}ms, {results['settledChars']} chars, "+ f"{THROTTLE}x throttle"+ )+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/studio/test_autoscroll_harness_contract.py b/tests/studio/test_autoscroll_harness_contract.pyindex 96637b980a0..f897242f433 100644--- a/tests/studio/test_autoscroll_harness_contract.py+++ b/tests/studio/test_autoscroll_harness_contract.py@@ -72,6 +72,30 @@ def test_research_freeze_keeps_a_hit_tested_click_in_the_report_phase() -> None:assert 'results["report"]["clicks_registered"]' in main+def test_stream_pacing_asserts_its_long_task_probe_measured_something() -> None:+ # longTaskMs is the metric the budgets turn on, and it is 0 both when the render is free+ # and when the observer never ran: `observe({type: "longtask"})` aborts silently on an+ # engine without the entry type. Without these, a firefox or webkit run, or a broken+ # observer, scores a perfect zero and exits 0.+ main = verdict("playwright_stream_pacing.py")+ assert 'results.get("longTaskSupported")' in main+ assert 'results["longTasks"] <= 0' in main+ # Same for an unthrottled run: the renderer keeps up with any rate this can feed, so+ # every budget passes on any tree.+ assert 'results["cpu_throttle"] <= 1' in main+++def test_stream_pacing_asserts_the_reply_was_actually_painted() -> None:+ # A page that rendered nothing scores a perfect zero on every budget, so the workload+ # has to be asserted before the numbers mean anything.+ main = verdict("playwright_stream_pacing.py")+ assert 'results["paintedChars"] < floor' in main+ assert 'results["arrivals"]' in main+ # paintedChars only climbs, so the length at settlement must be checked too, or an empty+ # final DOM passes on the peak it reached earlier.+ assert 'results["settledChars"] < floor' in main++def test_harnesses_own_their_dev_server() -> None:# A server started beside the harness leaves the node child alive when the wrapper is# killed, stranding the port and the step's stdout. Each harness owns its own instead.@@ -79,6 +103,7 @@ def test_harnesses_own_their_dev_server() -> None:"playwright_chat_autoscroll.py","playwright_research_freeze.py","playwright_strip_ansi_smoke.py",+ "playwright_stream_pacing.py",):text = source(name)assert "start_vite" in text, f"{name} does not start its own server"diff --git a/tests/studio/test_playwright_server_lifecycle.py b/tests/studio/test_playwright_server_lifecycle.pyindex 0993837392b..62293eaa992 100644--- a/tests/studio/test_playwright_server_lifecycle.py+++ b/tests/studio/test_playwright_server_lifecycle.py@@ -29,6 +29,7 @@ HARNESSES = ("playwright_chat_autoscroll","playwright_research_freeze","playwright_strip_ansi_smoke",+ "playwright_stream_pacing",)