'use strict'; // One app serves every route: `/` lists recent runs, `//` and `/main/` // draw one run. Runs are okami.mom's records, read at view time. A run page // fetches only its own result blob, and PDS answers are cached in the browser. (() => { const config = JSON.parse(document.getElementById('config').textContent); const { parse, resolve, pathKey, isMain, newestFirst, byCommitTime } = window.PerfRoutes; // The root has as many path segments as the directory app.js is served from: // "/" locally, "/okami.mom/albedo-perf/" on sites.wisp.place. const depth = new URL(document.currentScript.src).pathname.split('/').length - 2; const rootPath = location.pathname .split('/') .slice(0, depth + 1) .join('/') + '/'; const href = (key) => `${rootPath}${key}/`; const recordUrl = (collection, rkey) => `https://pdsls.dev/at://${config.did}/${collection}/${rkey}`; const $ = (id) => document.getElementById(id); const el = (tag, className, text) => { const node = document.createElement(tag); if (className) node.className = className; if (text != null) node.textContent = text; return node; }; let run = null; const TILES = [ ['boot_tree_uss', 'Memory at boot', "the empty daemon's private memory"], [ 'idle_session_tree_uss', 'Memory per idle session', 'what each extra idle session costs', ], [ 'retained_turn_beam', 'Memory kept per turn', 'BEAM memory each turn leaves after warm-up (leak gate)', ], [ 'turn_peak_daemon_uss', 'Peak during a turn', 'the most a single turn adds to the daemon while it runs', ], [ 'request_bytes_per_turn', 'Sent to the model per turn', 'average request size in the long conversation', ], [ 'attach_bytes', 'Sent to open a long session', 'what a client downloads to open the long conversation', ], [ 'kernel_rest_anon', 'Python kernel at rest', "an idle kernel's own anonymous memory (Pss_Anon)", ], [ 'kernel_forked_anon', 'Forked kernel', 'a kernel forked from the zygote (Pss_Anon)', ], [ 'kernel_cell_slope', 'Kept per cell', 'kernel memory each Python cell leaves behind', ], [ 'kernel_pool_pss', 'Kernel pool at rest', 'pre-started kernels waiting: zygote and spares', ], [ 'disk_written_per_turn', 'Written per turn', 'bytes the daemon and its kernels write to disk each long-conversation turn', ], [ 'disk_written_idle_hour', 'Written per idle hour', 'what a resting daemon with three sessions writes to disk in an hour', ], ]; const NAMES = Object.fromEntries([ ...TILES.map(([key, name]) => [key, name]), ['idle_session_beam', 'BEAM memory per idle session'], ['turn_peak_beam_blocks', 'BEAM allocator peak during a turn'], ['kernel_start_daemon_uss', 'Daemon peak while a kernel starts'], ['kernel_first_anon', 'First kernel with its pool'], ['retained_turn_tree_uss', 'Process memory per turn'], ['request_bytes_slope', 'Request growth per turn'], ['disk_written_boot', 'Written at boot'], ['disk_appended_per_turn', 'Appended per turn, without checkpoints'], ['disk_backfilled_per_turn', 'Copied into the database per turn'], ]); const SCENARIOS = { boot: ['Start the daemon', 'empty, then one idle session'], chat: ['Short chat', '5 turns in one session'], coding: ['Coding task', '8 turns that read, edit and test a small repo'], long: [ 'Long conversation', '20 warm-up turns, then 40 measured turns in one session', ], 'fan-out': [ '20 sessions side by side', '1, 5, then 20 sessions after one turn each', ], agents: [ 'A session with 3 helpers', 'spawns 3 agents that each answer once', ], kernel: ['Python kernel', 'one session running cells in its kernel'], pool: [ 'Kernel pool', "warm pool, then a session's first kernel and an adopted one", ], idle: [ 'Idle hour', '3 sessions, one holding a kernel, left alone for an hour of 60× timers', ], }; // Decimal units, three significant figures: 48.3 MB, 329 KB, 20.9 KB. const size = (value) => { if (value == null) return '–'; for (const [unit, scale] of [ ['GB', 1e9], ['MB', 1e6], ['KB', 1e3], ]) { if (Math.abs(value) >= scale) return `${parseFloat((value / scale).toPrecision(3))} ${unit}`; } return `${Math.round(value)} B`; }; // Axis ticks on a narrow range need a fourth significant figure to differ. const tick = (value) => { for (const [unit, scale] of [ ['GB', 1e9], ['MB', 1e6], ['KB', 1e3], ]) { if (Math.abs(value) >= scale) return `${parseFloat((value / scale).toPrecision(4))} ${unit}`; } return `${Math.round(value)} B`; }; const exact = (value) => `${Math.round(value).toLocaleString('en')} bytes`; const short = (sha) => sha.slice(0, 7); const branch = (ref) => ref.replace(/^refs\/heads\//, ''); const runName = (r) => isMain(r) ? `main@${short(r.commit)}` : `${short(r.commit)} (${branch(r.ref)})`; // A change counts when it clears three times the larger noise and 1%; // byte counts are exact (noise 0), so any change in them counts. // One sample has no noise estimate, so it needs a 5% move to count. const isSingle = (m) => Boolean(m?.singleSample || m?.single_sample); function change(key, mine, theirs) { if (!theirs || theirs.value == null) return null; const delta = mine.value - theirs.value; const pct = theirs.value ? delta / theirs.value : 0; const noise = 3 * Math.max(mine.noise ?? 0, theirs.noise ?? 0); const real = isSingle(mine) || isSingle(theirs) ? Math.abs(pct) >= 0.05 : noise === 0 ? delta !== 0 : Math.abs(delta) > noise && Math.abs(pct) >= 0.01; return { key, delta, pct, real, from: theirs.value, to: mine.value }; } const css = getComputedStyle(document.documentElement); const color = (name) => css.getPropertyValue(name).trim(); const dark = matchMedia('(prefers-color-scheme: dark)'); const theme = () => (dark.matches ? 'dark' : 'default'); const charts = new Set(); const chart = (node, option) => { const instance = echarts.init(node, theme(), { renderer: 'canvas' }); instance.setOption({ backgroundColor: 'transparent', animation: false, ...option, }); charts.add(instance); return instance; }; dark.addEventListener('change', () => charts.forEach((c) => c.setTheme(theme())), ); new ResizeObserver(() => charts.forEach((c) => c.resize())).observe( document.body, ); const state = { other: null, runs: [], main: [], }; function header() { const chip = $('chip'); chip.textContent = run.verdict === 'pass' ? 'Pass' : 'Fail'; chip.dataset.state = run.verdict; $('commit').textContent = short(run.commit); $('commit').title = run.commit; $('branch').textContent = branch(run.ref); if (run.createdAt) { const when = new Date(run.createdAt); $('when').textContent = when.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short', }); $('when').title = run.createdAt; } } function verdict() { const failing = Object.entries(run.gated).filter( ([, m]) => m.verdict === 'over_budget' || m.verdict === 'regressed', ); if (failing.length) { const [key, metric] = failing[0]; const base = metric.baseline; const rise = base ? ` went up ${Math.round((100 * (metric.value - base)) / base)}%` : ` is ${size(metric.value)}`; const why = metric.verdict === 'over_budget' ? 'over budget' : 'a regression'; const more = failing.length > 1 ? `, and ${failing.length - 1} more` : ''; return `${NAMES[key] ?? key}${rise} (${why})${more}.`; } if (!state.other) return state.runs.length > 1 ? 'No main run to compare with yet; choose a run above. Every number is within its budget.' : 'First recorded run: nothing to compare with yet. Every number is within its budget.'; const worse = moved().filter((c) => c.delta > 0); if (!worse.length) return `No regressions against ${runName(state.other)}.`; const top = worse[0]; return `${NAMES[top.key] ?? top.key} went up ${pct(top.pct)} against ${runName(state.other)}; still within budget.`; } const pct = (value) => `${Math.abs(100 * value) < 10 ? Math.abs(100 * value).toFixed(1) : Math.round(Math.abs(100 * value))}%`; function arrow(up) { const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttribute('viewBox', '0 0 10 10'); svg.setAttribute('aria-hidden', 'true'); const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); path.setAttribute('d', up ? 'M5 1.5 9 7.5H1z' : 'M5 8.5 1 2.5h8z'); svg.appendChild(path); return svg; } function delta(c) { const node = el('span', 'delta'); if (!c) { node.textContent = state.other ? 'not measured there' : 'first run'; return node; } if (!c.real) { node.textContent = 'no change'; node.title = `${exact(c.to)} vs ${exact(c.from)}, within noise`; return node; } const failing = ['regressed', 'over_budget'].includes( run.gated[c.key]?.verdict, ); node.dataset.dir = failing && c.delta > 0 ? 'worse' : 'moved'; node.append(arrow(c.delta > 0), `${pct(c.pct)}`); node.title = `${exact(c.to)} vs ${exact(c.from)} (${c.delta > 0 ? '+' : '−'}${exact(Math.abs(c.delta))})`; return node; } function otherMetric(key) { if (state.other) return state.other.summary.gated[key]; return null; } function tiles() { const root = $('tiles'); root.replaceChildren(); for (const [key, name, meaning] of TILES) { const metric = run.gated[key]; if (!metric) continue; const tile = el('article', 'tile'); const value = el('p', 'value', size(metric.value)); value.title = isSingle(metric) ? `${exact(metric.value)} · one run, no noise estimate` : `${exact(metric.value)} · noise ±${exact(metric.noise)}`; tile.append( el('h3', null, name), delta(change(key, metric, otherMetric(key))), value, el('p', 'meaning', meaning), ); if (isSingle(metric)) tile.append(el('p', 'secondary', 'one run, no noise estimate')); if (key === 'retained_turn_beam') { const notes = el('div', 'secondary'); const process = run.gated.retained_turn_tree_uss; if (process) { const line = el( 'p', null, `process memory ${size(process.value)} per turn`, ); line.title = `${exact(process.value)} per turn, includes SQLite cache warm-up`; notes.append(line); } if (run.warmup) { const warm = el( 'p', null, `+${size(run.warmup.memory)} one-time warm-up`, ); warm.title = `memory after the first ${run.warmup.turns} turns minus before the first: ${exact(run.warmup.memory)}, not gated`; notes.append(warm); } if (notes.childElementCount) tile.append(notes); } const appended = run.gated.disk_appended_per_turn; if (key === 'disk_written_per_turn' && appended) { const line = el( 'p', 'secondary', `${size(appended.value)} by write calls, without checkpoints`, ); line.title = `${exact(appended.value)} per turn to every file but the database, which checkpoints copy into on a timer`; tile.append(line); } const backfilled = run.gated.disk_backfilled_per_turn; if (key === 'disk_written_per_turn' && backfilled) { const line = el( 'p', 'secondary', `+${size(backfilled.value)} copied in by checkpoints`, ); line.title = `${exact(backfilled.value)} per turn that WAL checkpoints copy into the database, up to 30 s after the turn`; tile.append(line); } if (metric.budget) { const used = Math.min(1, metric.value / metric.budget); const bar = el('div', 'budget'); bar.title = `${Math.round(used * 100)}% of the ${size(metric.budget)} budget`; const fill = el('span'); fill.style.inlineSize = `${Math.max(used * 100, 1)}%`; if (used > 0.9) fill.dataset.near = ''; bar.append(fill); tile.append( bar, el( 'p', 'budget-label', `${Math.round(used * 100)}% of ${size(metric.budget)} budget`, ), ); } if (state.main.length >= 3) { const spark = el('div', 'spark'); tile.append(spark); const values = state.main.map( (r) => r.summary.gated[key]?.value ?? null, ); requestAnimationFrame(() => chart(spark, { grid: { left: 0, right: 0, top: 4, bottom: 4 }, xAxis: { type: 'category', show: false, boundaryGap: false, data: state.main.map((r) => short(r.commit)), }, yAxis: { type: 'value', show: false, scale: true }, tooltip: { trigger: 'axis', valueFormatter: size, confine: true }, series: [ { type: 'line', data: values, showSymbol: false, lineStyle: { width: 1.5, color: color('--accent') }, areaStyle: { opacity: 0.1, color: color('--accent') }, }, ], }), ); } root.append(tile); } } function moved() { if (!state.other) return []; return Object.entries(run.gated) .map(([key, metric]) => change(key, metric, state.other.summary.gated[key]), ) .filter((c) => c && c.real) .sort((a, b) => Math.abs(b.pct) - Math.abs(a.pct)); } function movedSection() { const body = $('moved-body'); body.replaceChildren(); if (!state.other) { body.append( el( 'p', 'calm', state.runs.length > 1 ? 'Choose a run to compare with in the header.' : 'Nothing to compare with yet. Changes appear here once another run is recorded.', ), ); return; } const changes = moved(); if (!changes.length) { body.append( el( 'p', 'calm', `Nothing moved beyond noise against ${runName(state.other)}.`, ), ); return; } const list = el('ul', 'moved'); for (const c of changes) { const row = el('li'); row.append( el('span', 'moved-name', NAMES[c.key] ?? c.key), el('span', 'moved-values', `${size(c.from)} → ${size(c.to)}`), delta(c), ); list.append(row); } body.append(list); } function checkpointLabel(name, point, index) { if (point.label === 'empty') return 'start'; if (point.label === 'final') return 'end'; if (point.label === 'created') return 'session'; if (point.label === 'turn') return `${point.count}`; if (point.label === 'sessions') return `${point.count} sess.`; if (point.label === 'family') return 'helpers'; if (point.label === 'idle') return 'idle session'; return point.label || `${index}`; } function memoryChart(card, scenario, title, name) { const memory = el('div', 'plot'); memory.setAttribute('role', 'img'); memory.setAttribute('aria-label', `${title}: memory after each step`); card.append( el( 'p', 'plot-title', 'Memory after each step, and the peak while it ran', ), memory, ); const points = scenario.checkpoints; const labels = points.map((p, i) => checkpointLabel(name, p, i)); // Each turn's peak floats from the step before it to the highest point. const before = points.map((p, i) => p.label === 'turn' && i > 0 ? points[i - 1].memory : null, ); const rise = points.map((p, i) => before[i] == null ? null : (scenario.peaks[String(p.count)] ?? null), ); requestAnimationFrame(() => chart(memory, { grid: { left: 4, right: 8, top: 12, bottom: 4, containLabel: true }, tooltip: { trigger: 'axis', formatter: (items) => { const i = items[0].dataIndex; const lines = [ `${labels[i]}`, `kept: ${size(points[i].memory)}`, ]; if (rise[i] != null) lines.push( `peak while running: ${size(before[i] + rise[i])} (+${size(rise[i])})`, ); return lines.join('
'); }, }, xAxis: { type: 'category', data: labels, axisTick: { show: false }, axisLabel: { hideOverlap: true }, }, yAxis: { type: 'value', scale: true, splitNumber: 3, axisLabel: { formatter: tick }, }, series: [ { type: 'bar', stack: 'peak', data: before, itemStyle: { color: 'transparent' }, barMaxWidth: 8, silent: true, }, { name: 'peak while running', type: 'bar', stack: 'peak', data: rise, barMaxWidth: 8, itemStyle: { color: color('--accent'), opacity: 0.22, borderRadius: 2, }, }, { name: 'kept after it settled', type: 'line', data: points.map((p) => p.memory), symbolSize: points.length > 12 ? 0 : 5, lineStyle: { color: color('--accent'), width: 2 }, itemStyle: { color: color('--accent') }, }, ], }), ); } function scenarios() { const root = $('scenarios'); root.replaceChildren(); for (const [name, scenario] of Object.entries(run.scenarios)) { const [title, about] = SCENARIOS[name] ?? [name, '']; const card = el('article', 'scenario'); const head = el('div', 'scenario-head'); const heading = el('div'); heading.append(el('h3', null, title), el('p', 'meaning', about)); if (scenario.runs === 1) heading.append(el('p', 'secondary', 'one run, no noise estimate')); const facts = el('dl', 'facts'); const factRows = []; const kept = scenario.checkpoints.at(-1)?.memory; if (kept != null) factRows.push(['memory at end', size(kept)]); const pool = scenario.pool; if (pool?.warmPss != null) factRows.push(['warm pool', size(pool.warmPss)]); for (const [key, label] of [ ['first_kernel', 'first kernel'], ['adopted_kernel', 'adopted kernel'], ]) { const k = pool?.[key]; if (k?.uss != null) factRows.push([ `${label}${k.kinds.length ? ` (${k.kinds.join(', ')})` : ''}`, size(k.uss), ]); } if (scenario.wire.provider_sent) factRows.push(['sent to model', size(scenario.wire.provider_sent)]); const writes = scenario.writes; if (writes?.written != null) factRows.push(['written to disk', size(writes.written)]); if (scenario.wallMs) factRows.push(['took', `${(scenario.wallMs / 1000).toFixed(1)} s`]); for (const [label, value] of factRows) facts.append(el('dt', null, label), el('dd', null, value)); head.append(heading, facts); card.append(head); if (scenario.checkpoints.length) memoryChart(card, scenario, title, name); if (scenario.requests.length) { const bytes = el('div', 'plot plot-short'); bytes.setAttribute('role', 'img'); bytes.setAttribute('aria-label', `${title}: bytes per model request`); const legend = el('p', 'plot-title'); legend.append( 'Bytes per model request ', el('span', 'swatch sent'), 'sent ', el('span', 'swatch received'), 'received', ); card.append(legend, bytes); requestAnimationFrame(() => chart(bytes, { grid: { left: 4, right: 8, top: 8, bottom: 4, containLabel: true }, tooltip: { trigger: 'axis', valueFormatter: (v) => `${size(v)} (${exact(v)})`, }, xAxis: { type: 'category', data: scenario.requests.map((_, i) => `${i + 1}`), axisTick: { show: false }, axisLabel: { hideOverlap: true }, }, yAxis: { type: 'value', splitNumber: 2, axisLabel: { formatter: tick }, }, series: [ { name: 'sent', type: 'bar', stack: 'b', data: scenario.requests.map((r) => r.sent), barMaxWidth: 14, itemStyle: { color: color('--accent') }, }, { name: 'received', type: 'bar', stack: 'b', data: scenario.requests.map((r) => r.received), barMaxWidth: 14, itemStyle: { color: color('--faint'), opacity: 0.6 }, }, ], }), ); } if (writes?.files.length) { const [label, count] = writes.from; const since = name === 'long' ? `after turn ${count}` : name === 'idle' ? 'over the hour' : label === 'empty' ? 'after boot' : `from ${label}`; card.append(el('p', 'plot-title', `Written to disk by file, ${since}`)); const files = el('table', 'files'); for (const [path, bytes] of writes.files) { const tr = files.insertRow(); tr.insertCell().textContent = path; const cell = tr.insertCell(); cell.textContent = size(bytes); cell.title = exact(bytes); } card.append(files); } const details = el('details'); details.append(el('summary', null, 'All numbers')); const table = el('table'); const rows = [ ...Object.entries(scenario.memory).map(([k, v]) => [ k.replaceAll('_', ' '), size(v), exact(v), ]), ...Object.entries(scenario.wire).map(([k, v]) => [ k.replaceAll('_', ' '), k.endsWith('requests') ? `${v}` : size(v), k.endsWith('requests') ? '' : exact(v), ]), ]; for (const cells of rows) { const tr = table.insertRow(); for (const cell of cells) tr.insertCell().textContent = cell; } details.append(table); card.append(details); root.append(card); } } function scenariosNote() { const note = $('scenarios-note'); note.textContent = 'Recorded bonsai answers, five runs each. This is what the gate checks.'; const recordings = Object.values(run.recordings); const stale = recordings.filter((r) => r.stale).length; if (stale) note.append( el( 'span', 'stale', ` ${stale} of ${recordings.length} recordings are older than albedo's current requests; re-record with test/perf/record_container.py.`, ), ); } let historyKey = TILES[0][0]; function history() { const tabs = $('history-tabs'); const root = $('history'); tabs.replaceChildren(); root.replaceChildren(); if (state.main.length < 2) { tabs.hidden = true; root.append(el('p', 'calm', 'Trends appear after the second main run.')); return; } tabs.hidden = false; for (const [key, name] of TILES.filter(([key]) => run.gated[key])) { const tab = el('button', null, name); tab.type = 'button'; tab.setAttribute('role', 'tab'); tab.setAttribute('aria-selected', String(key === historyKey)); tab.addEventListener('click', () => { historyKey = key; charts.forEach((c) => c.dispose()); charts.clear(); tiles(); scenarios(); history(); }); tabs.append(tab); } const metricOf = (r) => r.summary.gated[historyKey] ?? {}; const values = state.main.map((r) => metricOf(r).value ?? null); // The band is each run's own ±3×MAD: movement inside it is noise. const lower = state.main.map((r) => metricOf(r).value == null ? null : metricOf(r).value - 3 * (metricOf(r).noise ?? 0), ); const band = state.main.map((r) => metricOf(r).value == null ? null : 6 * (metricOf(r).noise ?? 0), ); const known = values.filter((v) => v != null); const lo = Math.min(...lower.filter((v) => v != null)); const hi = Math.max( ...values.map((v, i) => v == null ? -Infinity : v + 3 * (metricOf(state.main[i]).noise ?? 0), ), ); const middle = (lo + hi) / 2; // A tight band would still turn a 0.5% wiggle into a cliff; span at least ±2%. const span = Math.max(hi - lo, 0.04 * Math.abs(middle)) * 1.1; const budget = run.gated[historyKey]?.budget; const drawBudget = budget && budget <= Math.max(...known) * 1.5; if (budget && !drawBudget) root.append( el('p', 'note', `Budget ${size(budget)}, well above every run so far.`), ); const node = el('div', 'plot plot-tall'); root.append(node); const here = state.main.findIndex((r) => r.commit === run.commit); requestAnimationFrame(() => chart(node, { grid: { left: 4, right: 12, top: 24, bottom: 40, containLabel: true }, tooltip: { trigger: 'axis', formatter: (items) => { const i = items[0].dataIndex; const m = metricOf(state.main[i]); return `${short(state.main[i].commit)}
${size(m.value)} (${exact(m.value)})
noise ±${size(3 * (m.noise ?? 0))}`; }, }, xAxis: { type: 'category', boundaryGap: false, axisLabel: { alignMinLabel: 'left', alignMaxLabel: 'right' }, data: state.main.map((r) => short(r.commit)), }, yAxis: { type: 'value', min: middle - span / 2, max: drawBudget ? Math.max(middle + span / 2, budget * 1.02) : middle + span / 2, axisLabel: { formatter: tick }, }, dataZoom: [ { type: 'inside' }, { type: 'slider', height: 16, bottom: 6 }, ], series: [ { type: 'line', data: lower, stack: 'noise', symbol: 'none', lineStyle: { opacity: 0 }, silent: true, }, { name: 'noise', type: 'line', data: band, stack: 'noise', symbol: 'none', lineStyle: { opacity: 0 }, areaStyle: { color: color('--accent'), opacity: 0.12 }, silent: true, }, { type: 'line', data: values, symbolSize: 5, lineStyle: { color: color('--accent'), width: 2 }, itemStyle: { color: color('--accent') }, markLine: drawBudget ? { symbol: 'none', silent: true, lineStyle: { type: 'dashed', color: color('--danger') }, label: { position: 'insideEndTop', formatter: `budget ${size(budget)}`, }, data: [{ yAxis: budget }], } : undefined, markPoint: here < 0 ? undefined : { data: [{ coord: [here, values[here]], value: 'this run' }], symbolSize: 34, }, }, ], }), ); } function footer() { const root = $('footer'); root.replaceChildren(); const links = el('p'); const add = (url, text) => { const a = el('a', null, text); a.href = url; links.append(a, ' '); }; add(run.blob, 'Replay results (JSON)'); add(recordUrl(config.collection, run.rkey), 'Run record'); root.append( links, el( 'p', 'fine', 'Memory is the private memory (USS) of the daemon and its kernels, median of five fresh starts, so other programs on the machine do not shift it; bytes are counted on the wire. Comparisons and history load from the run records at view time.', ), ); } function picker() { const select = $('compare'); select.replaceChildren(); const others = state.runs.filter((r) => r.rkey !== run.rkey); if (!others.length) { select.append(new Option('nothing yet', '')); select.disabled = true; return; } select.append(new Option('choose a run', '')); for (const r of others) select.append( new Option(`${runName(r)} · ${r.createdAt.slice(0, 10)}`, r.rkey), ); select.value = state.other?.rkey ?? ''; select.disabled = false; select.onchange = () => { state.other = others.find((r) => r.rkey === select.value) ?? null; refresh(); }; } function refresh() { charts.forEach((c) => c.dispose()); charts.clear(); $('verdict').textContent = verdict(); const accepts = Object.values(run.gated).flatMap((m) => m.accept ?? []); $('accept').hidden = !accepts.length; $('accept-lines').textContent = accepts.join('\n'); tiles(); movedSection(); scenarios(); history(); } // Run records answer for a minute; result blobs are content-addressed and // kept until BLOBS_KEPT newer ones push them out. const RECORDS = 'albedo-perf-records'; const BLOBS = 'albedo-perf-blobs'; const RECORD_TTL = 60_000; const BLOBS_KEPT = 12; // listRecords pages by rkey (the commit sha), not by time, so the index // needs every page to sort; past this many it shows what it has. const MAX_PAGES = 20; const INDEX_ROWS = 40; async function cachedJson(url, cacheName, ttl) { const store = await globalThis.caches?.open(cacheName).catch(() => null); const hit = await store?.match(url); if (hit && Date.now() - Number(hit.headers.get('x-fetched-at')) < ttl) return hit.json(); // The PDS varies its CORS headers by Origin; a copy the HTTP cache kept // for another origin or a plain navigation fails CORS here, so skip it. const response = await fetch(url, { cache: 'no-store' }); let body = await response.text(); // getRecord answers a missing record with 400 RecordNotFound; keep it as null. if (response.status === 400 && body.includes('RecordNotFound')) body = 'null'; else if (!response.ok) { const method = new URL(url).pathname.split('/').pop(); throw new Error(`${method} answered ${response.status}`); } if (store) { await store.put( url, new Response(body, { headers: { 'content-type': 'application/json', 'x-fetched-at': String(Date.now()), }, }), ); if (cacheName === BLOBS) for (const key of (await store.keys()).slice(0, -BLOBS_KEPT)) await store.delete(key); } return JSON.parse(body); } const xrpc = (base, method, params) => { const url = new URL(`/xrpc/${method}`, base); url.search = new URLSearchParams(params); return url.href; }; async function endpoint() { if (config.pds) return config.pds; const doc = await cachedJson( `https://plc.directory/${config.did}`, RECORDS, 86_400_000, ); return doc.service.find((s) => s.id === '#atproto_pds').serviceEndpoint; } async function listRuns(base) { const runs = []; let cursor; let pages = 0; do { const page = await cachedJson( xrpc(base, 'com.atproto.repo.listRecords', { repo: config.did, collection: config.collection, limit: '100', ...(cursor ? { cursor } : {}), }), RECORDS, RECORD_TTL, ); for (const item of page.records) runs.push({ ...item.value, rkey: item.uri.split('/').pop(), summary: JSON.parse(item.value.summary), }); // A short page is the last; the PDS still sends a cursor with it. cursor = page.records.length === 100 ? page.cursor : undefined; } while (cursor && ++pages < MAX_PAGES); return { runs, truncated: Boolean(cursor) }; } // A replay that crashed left records without gated numbers; they are not runs. const complete = (r) => Object.keys(r.summary.gated ?? {}).length > 0; // What the page draws from a results.json blob. const privateMemory = (s) => s.tree_uss ?? s.tree_pss; const medianOf = (v) => (v && typeof v === 'object' ? v.median : v); function medianObservation(scenario) { const runs = (scenario.observations ?? []).filter( (o) => o.checkpoints?.length, ); if (!runs.length) return { checkpoints: [], turns: [] }; const final = (i) => privateMemory(runs[i].checkpoints.at(-1)) || 0; const order = runs.map((_, i) => i).sort((a, b) => final(a) - final(b)); return runs[order[Math.floor(order.length / 2)]]; } function poolReport(pool) { if (!pool) return null; const report = { warmPss: medianOf(pool.warm_pss) }; for (const name of ['first_kernel', 'adopted_kernel']) if (name in pool) report[name] = { kinds: [...new Set(pool[name].kinds ?? [])].sort(), uss: medianOf(pool[name].uss), pss: medianOf(pool[name].pss), }; return report; } const medians = (memory) => Object.fromEntries( Object.entries(memory ?? {}).map(([k, v]) => [k, v.median]), ); function timeline(scenario) { const observation = medianObservation(scenario); const peaks = {}; for (const t of observation.turns ?? []) { const peak = t.peak_daemon_uss ?? t.peak_tree_uss ?? t.peak_tree_pss; if (peak !== undefined) peaks[String(t.turn)] = peak; } return { checkpoints: observation.checkpoints.map((c) => ({ label: c.label, count: c.count, memory: privateMemory(c), })), peaks, requests: (scenario.requests ?? []).map((r) => ({ sent: r.sent, received: r.received, })), wire: scenario.wire ?? {}, memory: medians(scenario.memory), wallMs: scenario.wall_ms?.median, pool: poolReport(scenario.pool), runs: scenario.runs, }; } function fromResult(result) { const recordings = {}; for (const [name, s] of Object.entries(result.scenarios)) if (s.recordings) recordings[name] = { recordedAt: s.recordings.recorded_at, model: s.recordings.model, stale: Boolean(s.recordings.stale_turns?.length), }; const warm = result.scenarios.long?.warmup_retained; const warmMemory = warm && (warm.tree_uss || warm.tree_pss); return { commit: result.commit, baseCommit: result.base_commit, ref: result.ref, event: result.event, verdict: result.verdict, gated: Object.fromEntries( Object.entries(result.gated).map(([name, m]) => [ name, { value: m.value, noise: m.noise, baseline: m.baseline, budget: m.budget, verdict: m.verdict, accept: m.accept, singleSample: Boolean(m.single_sample), }, ]), ), scenarios: Object.fromEntries( Object.entries(result.scenarios).map(([n, s]) => [n, timeline(s)]), ), recordings, warmup: warmMemory ? { turns: warm.turns, memory: warmMemory.median } : null, }; } const RUN_PAGE = `
All runs

Loading.

What moved

Scenarios

History on main

`; const app = $('app'); function message(title, text, runs = []) { document.title = `${title} · albedo perf`; app.innerHTML = `
All runs

    `; $('title').textContent = title; $('text').textContent = text; for (const r of runs) $('runs').append(indexRow(r)); } async function showRun(record, runs, base, latestMain) { const blob = xrpc(base, 'com.atproto.sync.getBlob', { did: config.did, cid: record.result.ref.$link, }); run = { ...fromResult(await cachedJson(blob, BLOBS, Infinity)), rkey: record.rkey, createdAt: record.createdAt, blob, }; document.title = `${short(run.commit)} · ${branch(run.ref)} · albedo perf`; app.innerHTML = RUN_PAGE; state.runs = newestFirst(runs); state.main = runs.filter(isMain).sort(byCommitTime); state.other = state.runs.find( (r) => r.rkey !== run.rkey && isMain(r) && r.commit === run.baseCommit, ) ?? null; header(); if (latestMain) $('branch').textContent = 'latest main'; picker(); scenariosNote(); footer(); refresh(); } const day = (iso) => new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short', }); function indexRow(r) { const row = el('li', 'run-row'); const link = el('a', 'run-link'); link.href = href(pathKey(r.rkey)); const chip = el('span', 'chip', r.verdict === 'pass' ? 'Pass' : 'Fail'); chip.dataset.state = r.verdict; link.append(chip, el('span', 'hash', pathKey(r.rkey))); if (isMain(r)) link.append(el('span', 'tag', 'main')); else link.append(el('span', 'run-ref', `${branch(r.ref)} · ${r.event}`)); const gated = r.summary.gated ?? {}; const facts = [ ['boot_tree_uss', 'at boot'], ['idle_session_tree_uss', 'per session'], ['request_bytes_per_turn', 'sent per turn'], ] .filter(([key]) => gated[key]) .map(([key, label]) => `${size(gated[key].value)} ${label}`); const when = el('time', 'run-when', day(r.createdAt)); when.dateTime = r.createdAt; const record = el('a', 'run-record', 'record'); record.href = recordUrl(config.collection, r.rkey); record.title = `at://${config.did}/${config.collection}/${r.rkey}`; row.append(link, el('span', 'run-facts', facts.join(' · ')), when, record); return row; } function showIndex(runs, truncated) { document.title = 'albedo perf'; app.innerHTML = `

    albedo perf

    Latest main run

    Recent runs

      `; const sorted = newestFirst(runs); $('count').textContent = `${sorted.length} runs, ${sorted.filter(isMain).length} on main. Memory, wire bytes, and disk writes from fetched gated runs.`; if (truncated) $('index-note').textContent = `Showing the first ${MAX_PAGES * 100} records the PDS lists. Runs outside this set are unavailable here, including by direct address.`; let shown = 0; const more = $('more'); const reveal = () => { for (const r of sorted.slice(shown, shown + INDEX_ROWS)) $('runs').append(indexRow(r)); shown = Math.min(sorted.length, shown + INDEX_ROWS); more.hidden = shown >= sorted.length; more.textContent = `Show ${Math.min(INDEX_ROWS, sorted.length - shown)} more`; }; more.addEventListener('click', reveal); if (!sorted.length) $('runs').replaceWith(el('p', 'calm', 'No runs recorded yet.')); else reveal(); } async function route() { const path = parse(location.pathname.slice(rootPath.length)); if (path.page === 'missing') return message( 'No such page', `"${path.key}" is not a run. Runs live at //, and the latest main run at /main/.`, ); const base = await endpoint(); const { runs, truncated } = await listRuns(base); if (path.page === 'index') return showIndex(runs.filter(complete), truncated); const found = resolve( path, path.page === 'main' ? runs.filter(complete) : runs, ); if (found.ambiguous) return message( `Several runs match ${path.key}`, 'Add more of the commit to the address, or pick one:', found.ambiguous, ); if (!found.run) return message( path.page === 'main' ? 'No main run yet' : `No run ${path.key}`, 'No recorded run matches this address yet. A run appears here once its record is written.', ); if (!complete(found.run)) return message( `Run ${path.key} has no gated numbers`, 'Its replay stopped before every scenario finished, so the gate never ran.', ); await showRun(found.run, runs.filter(complete), base, path.page === 'main'); } app.innerHTML = `

      Loading runs.

      `; route().catch((error) => message( 'Could not load runs', `The record store did not answer: ${error.message}`, ), ); })();