| 1 | // Reference runner of the stress kit (packages/stress) on the web renderers: every widget of the manifest |
| 2 | // through the web dev app (apps/web), the real pipeline (QuickJS worker → validator → renderer), in headless |
| 3 | // Chromium; iframe and shadow (Shadow DOM, the web product renderer); the frozen blitz and litehtml prototypes |
| 4 | // only when named in --renderers and their wasm is built. Per widget: load it, warm up, then measure for `measureMs`: |
| // - client frames: requestAnimationFrame timestamps in the frame that hosts the renderer (the page for |
| 6 | // shadow, the sandboxed iframe for iframe), plus long tasks there: what the user sees; |
| 7 | // - renderer work per frame: the wasm renderers' paint time; null for iframe and shadow (a WebView-like |
| 8 | // renderer cannot time its style and paint from script, CLIENTS.md); |
| 9 | // - the host: JS CPU, layout queries, QuickJS heap from `onStats`, nodes, validated ops per second and the |
| 10 | // largest validated batch from the renderer's `send`; |
| 11 | // - the widget's own data-stress (its rAF rate as the sandbox sees it). |
| 12 | // It writes one run file per renderer (packages/stress/run.schema.json) to reports/stress/<pass>-<renderer>.json; |
| 13 | // packages/stress/tools/report.mjs turns run files (any client's) into the summary. |
| 14 | // |
| 15 | // Needs the dev server of this checkout: corepack pnpm dev --port 5178 |
| 16 | // corepack pnpm tsx scripts/stress/run-web.ts --origin http://127.0.0.1:5178 [--renderers iframe,shadow] |
| 17 | // [--only shadow-moving] [--warmup 2000] [--measure 10000] [--pass measure|production] [--width 390] |
| 18 | // [--theme light] [--device "MacBook Pro (M5 Max)"] |
| 19 | // `--pass measure` (default) is CLIENTS.md's measuring configuration (compat, the quotas out of the way); |
| 20 | // `--pass production` is the product's (strict, the default limits) and records where each ladder stops. |
| 21 |
| 22 | import { execSync } from 'node:child_process'; |
| 23 | import fs from 'node:fs'; |
| 24 | import os from 'node:os'; |
| 25 | import path from 'node:path'; |
| 26 | import { chromium, type Frame, type Page } from '@playwright/test'; |
| 27 | import { DEFAULT_RUN, MEASURE_PARAMS, ROOT, STRESS, loadWidget, openDevApp, published, readManifest, type Published } from './lib'; |
| 28 |
| 29 | const args = process.argv.slice(2); |
| 30 | const opt = (name: string, def?: string) => (args.includes('--' + name) ? args[args.indexOf('--' + name) + 1] : def); |
| 31 | const ORIGIN = opt('origin', `http://127.0.0.1:${process.env.TW_PORT ?? 5178}`)!; |
| 32 | const RENDERERS = opt('renderers', 'iframe,shadow')!.split(','); |
| 33 | const ONLY = opt('only'); |
| 34 | const WARMUP = Number(opt('warmup', String(DEFAULT_RUN.warmupMs))); |
| 35 | const MEASURE = Number(opt('measure', String(DEFAULT_RUN.measureMs))); |
| 36 | const PASS = opt('pass', 'measure') as 'measure' | 'production'; |
| 37 | const WIDTH = Number(opt('width', String(DEFAULT_RUN.width))); |
| 38 | const THEME = opt('theme', 'light')!; |
| 39 | const DEVICE = opt('device', `${os.cpus()[0]?.model ?? 'unknown CPU'} (${os.cpus().length} cores)`)!; |
| 40 | const DPR = 2; |
| 41 | const OUT = path.join(ROOT, 'reports', 'stress'); |
| 42 |
| 43 | const commit = () => { try { return execSync('git rev-parse --short HEAD', { cwd: ROOT }).toString().trim(); } catch { return ''; } }; |
| 44 | const ownRenderer = (r: string) => r === 'blitz' || r === 'litehtml'; |
| 45 | const pct = (a: number[], p: number) => (a.length ? [...a].sort((x, y) => x - y)[Math.min(a.length - 1, Math.floor(p * a.length))] : null); |
| 46 | const r1 = (x: number | null) => (x === null || !Number.isFinite(x) ? null : Math.round(x * 10) / 10); |
| 47 |
| 48 | /** rAF timestamps and long tasks in a frame; each call starts a new window; the renderer's paint times ride along. A string: tsx would wrap named functions in a helper the page does not have. */ |
| 49 | const SAMPLER = `(() => { |
| 50 | const w = window; |
| 51 | if (!w.__sf) { |
| 52 | const s = (w.__sf = { t: [], long: 0, paints: [], lastPaints: -1 }); |
| 53 | const f = (t) => { |
| 54 | s.t.push(t); |
| 55 | const r = w.__tw && (w.__tw.blitz || w.__tw.litehtml); |
| 56 | if (r && r.paints !== s.lastPaints) { if (s.lastPaints >= 0) s.paints.push(r.paintMs); s.lastPaints = r.paints; } |
| 57 | requestAnimationFrame(f); |
| 58 | }; |
| 59 | requestAnimationFrame(f); |
| 60 | try { new PerformanceObserver((l) => { for (const e of l.getEntries()) s.long += e.duration; }).observe({ type: 'longtask' }); } catch (e) {} |
| 61 | } |
| 62 | w.__sf.t = []; w.__sf.long = 0; w.__sf.paints = []; |
| 63 | })()`; |
| 64 | const SAMPLES = '({ t: window.__sf.t, long: window.__sf.long, paints: window.__sf.paints })'; |
| 65 |
| 66 | /** The frame the renderer draws in: the sandboxed iframe for the iframe renderer, the page otherwise. */ |
| 67 | async function rendererFrame(page: Page): Promise<Frame> { |
| 68 | const el = await page.$('iframe[data-stress-el], [data-stress-el] iframe'); |
| 69 | return (await el?.contentFrame()) ?? page.mainFrame(); |
| 70 | } |
| 71 |
| 72 | function frameStats(t: number[], vsync: number) { |
| 73 | const dts: number[] = []; |
| 74 | for (let i = 1; i < t.length; i++) dts.push(t[i] - t[i - 1]); |
| 75 | let slots = 0, missed = 0; |
| 76 | for (const d of dts) { const n = Math.max(1, Math.round(d / vsync)); slots += n; missed += n - 1; } |
| 77 | return { count: dts.length, p50: r1(pct(dts, 0.5)), p95: r1(pct(dts, 0.95)), max: r1(dts.length ? Math.max(...dts) : null), dropped: slots ? Math.round((missed / slots) * 1000) / 1000 : null }; |
| 78 | } |
| 79 |
| 80 | async function hostSnapshot(page: Page) { |
| 81 | return page.evaluate(() => { |
| 82 | const st = (window as any).__tw.state, x = (window as any).__stress; |
| 83 | return { stats: st.stats ? { ...st.stats } : null, ops: x.ops as number, maxBatch: x.maxBatch as number, dead: st.dead as string | null, loaded: !!st.loaded }; |
| 84 | }); |
| 85 | } |
| 86 |
| 87 | async function runWidget(page: Page, w: { id: string; file: string; load: string; value: number }, renderer: string, vsync: number) { |
| 88 | const html = fs.readFileSync(path.join(STRESS, w.file), 'utf8'); |
| 89 | const t0 = Date.now(); |
| 90 | await loadWidget(page, html, `stress/${w.id}.html`, WIDTH); |
| 91 | await page.waitForFunction(() => { const s = (window as any).__tw.state; return s.loaded || s.dead; }, null, { timeout: 60_000, polling: 'raf' }).catch(() => {}); |
| 92 | const bootMs = Date.now() - t0; |
| 93 | const frame = await rendererFrame(page); |
| 94 | await frame.evaluate(SAMPLER).catch(() => {}); |
| 95 | await page.waitForTimeout(WARMUP); |
| 96 | const a = await hostSnapshot(page), pa = await published(page); |
| 97 | await frame.evaluate(SAMPLER).catch(() => {}); |
| 98 | const m0 = Date.now(); |
| 99 | let maxGap = 0; |
| 100 | let diedAtMs: number | null = a.dead ? 0 : null; |
| 101 | while (Date.now() - m0 < MEASURE) { |
| 102 | await page.waitForTimeout(Math.min(500, MEASURE - (Date.now() - m0))); |
| 103 | const p = await published(page); |
| 104 | if (p && p.maxGap > maxGap) maxGap = p.maxGap; |
| 105 | if (diedAtMs === null && (await page.evaluate(() => !!(window as any).__tw.state.dead))) diedAtMs = Date.now() - t0; |
| 106 | } |
| 107 | const secs = (Date.now() - m0) / 1000; |
| 108 | const samples = (await frame.evaluate(SAMPLES).catch(() => ({ t: [], long: 0, paints: [] }))) as { t: number[]; long: number; paints: number[] }; |
| 109 | const b = await hostSnapshot(page), pb = await published(page); |
| 110 | const state = await page.evaluate(() => { const st = (window as any).__tw.state; return { logs: st.logs as { level: string; text: string }[], diags: Object.fromEntries(Object.entries(st.diags as Record<string, { count: number }>).map(([k, v]) => [k, v.count])) }; }); |
| 111 | const rate = (k: string) => (a.stats && b.stats ? r1((b.stats[k] - a.stats[k]) / secs) : null); |
| 112 | const widgetFps = (pa: Published | null, pb: Published | null) => (pa && pb && pb.t > pa.t ? r1(((pb.frames - pa.frames) * 1000) / (pb.t - pa.t)) : null); |
| 113 | return { |
| 114 | id: w.id, load: w.load, value: w.value, |
| 115 | loaded: a.loaded, bootMs, dead: b.dead, diedAtMs: b.dead ? (diedAtMs ?? bootMs) : null, |
| 116 | frames: { ...frameStats(samples.t, vsync), longTaskMs: r1(samples.long) }, |
| 117 | renderer: ownRenderer(renderer) ? { msPerFrame: r1(samples.paints.length ? samples.paints.reduce((s, x) => s + x, 0) / samples.paints.length : null), p95Ms: r1(pct(samples.paints, 0.95)) } : null, |
| 118 | host: { |
| 119 | jsMsPerSec: rate('jsMs'), opsPerSec: r1((b.ops - a.ops) / secs), queriesPerSec: rate('queries'), queryMsPerSec: rate('queryMs'), |
| 120 | nodes: b.stats?.nodes ?? null, memoryBytes: b.stats?.memoryBytes ?? null, throttledTasks: a.stats && b.stats ? b.stats.throttledTasks - a.stats.throttledTasks : null, maxBatchOps: b.maxBatch, |
| 121 | }, |
| 122 | widget: { fps: widgetFps(pa, pb), frames: pb && pa ? pb.frames - pa.frames : null, maxGap, jank: pa && pb ? pb.jank - pa.jank : null, last: pb }, |
| 123 | thermal: null, |
| 124 | errors: state.logs.filter((l) => l.level === 'error').map((l) => String(l.text).split('\n')[0].slice(0, 200)), |
| 125 | diags: state.diags, |
| 126 | }; |
| 127 | } |
| 128 |
| 129 | async function main() { |
| 130 | const manifest = readManifest(); |
| 131 | const widgets = manifest.widgets.filter((w) => !ONLY || ONLY.split(',').some((o) => w.id.startsWith(o))); |
| 132 | const params: Record<string, string> = PASS === 'measure' ? MEASURE_PARAMS : { policy: 'strict' }; |
| 133 | const browser = await chromium.launch(); |
| 134 | fs.mkdirSync(OUT, { recursive: true }); |
| 135 | for (const renderer of RENDERERS) { |
| 136 | const ctx = await browser.newContext({ viewport: { width: 1200, height: 1000 }, deviceScaleFactor: DPR }); |
| 137 | const page = await ctx.newPage(); |
| 138 | await openDevApp(page, ORIGIN, renderer, { ...params, theme: THEME }); |
| 139 | // The display's frame period, from the idle page. |
| 140 | await page.evaluate(SAMPLER); |
| 141 | await page.waitForTimeout(1500); |
| 142 | const idle = ((await page.evaluate(SAMPLES)) as { t: number[] }).t; |
| 143 | const dts = idle.slice(1).map((t, i) => t - idle[i]); |
| 144 | const vsync = pct(dts, 0.5) ?? 1000 / 60; |
| 145 | const refreshHz = Math.round(1000 / vsync); |
| 146 | console.log(`${renderer}: ${widgets.length} widgets, ${PASS} pass, ${refreshHz} Hz, warm-up ${WARMUP} ms, measure ${MEASURE} ms`); |
| 147 | const runs = []; |
| 148 | let applied: Record<string, unknown> = {}; |
| 149 | for (const w of widgets) { |
| 150 | try { |
| 151 | const run = await runWidget(page, w, renderer, vsync); |
| 152 | if (!Object.keys(applied).length) applied = await page.evaluate(() => { const o = (window as any).__tw.host?.opts ?? {}; const k = ['policy', 'cpuLimitMs', 'cpuQuotaMs', 'cpuQuotaWindowMs', 'mainThreadQuotaMs', 'maxTimers', 'memoryLimitBytes']; return Object.fromEntries(k.map((n) => [n, o[n] ?? null])); }); |
| 153 | runs.push(run); |
| 154 | const f = run.frames; |
| 155 | console.log(` ${w.id.padEnd(28)} p50 ${String(f.p50).padStart(5)} p95 ${String(f.p95).padStart(5)} drop ${String(f.dropped).padStart(5)} | widget ${String(run.widget.fps).padStart(5)} fps | js ${String(run.host.jsMsPerSec).padStart(6)} ms/s ops ${String(run.host.opsPerSec).padStart(7)}/s${run.renderer ? ` | render ${run.renderer.msPerFrame} ms` : ''}${run.dead ? ' | DEAD ' + run.dead.slice(0, 90) : ''}`); |
| 156 | } catch (e) { |
| 157 | console.log(` ${w.id}: runner error ${(e as Error).message.split('\n')[0]}`); |
| 158 | await openDevApp(page, ORIGIN, renderer, { ...params, theme: THEME }); |
| 159 | } |
| 160 | } |
| 161 | const file = { |
| 162 | kit: { version: manifest.version, commit: commit() }, |
| 163 | platform: 'web', client: 'widget-sandbox dev app (apps/web)', clientBuild: commit(), framework: commit(), |
| 164 | renderer, rendererKind: ownRenderer(renderer) ? 'own' : 'webview', |
| 165 | engine: `Chromium ${browser.version()} (headless, Playwright)`, |
| 166 | device: { model: DEVICE, os: `${os.type()} ${os.release()}`, class: 'desktop', refreshHz, dpr: DPR }, |
| 167 | pass: PASS, |
| 168 | config: { requested: { ...Object.fromEntries(Object.entries(params).map(([k, v]) => [k, k === 'policy' ? v : Number(v)])), width: WIDTH, theme: THEME, warmupMs: WARMUP, measureMs: MEASURE, features: ['webAnimations'] }, applied }, |
| 169 | date: new Date().toISOString(), |
| 170 | runs, |
| 171 | }; |
| 172 | fs.writeFileSync(path.join(OUT, `${PASS}-${renderer}.json`), JSON.stringify(file, null, 1)); |
| 173 | console.log(` → ${path.relative(ROOT, path.join(OUT, `${PASS}-${renderer}.json`))}`); |
| 174 | await ctx.close(); |
| 175 | } |
| 176 | await browser.close(); |
| 177 | } |
| 178 |
| 179 | main().catch((e) => { console.error(e); process.exit(1); }); |
| 180 |