Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852/** * The load audit: what took how long, kept in a shape a flamegraph can draw. * * `trace.ts` answers "what is this load waiting on *right now*", which is the question a hung * track asks — one line per stage, printed as it happens, read by finding the line that did not * come. This answers the other question, the one a slow-but-successful load asks: **where did * the four seconds go?** That question is not answerable from a list of lines, because the * stages of a load are not a list. The cover's palette is fetched while the stream is still * arriving; the waveform fold runs between the decode and the first frame; the loop detector's * search sits on another thread for as long as the main one draws the row. Read as lines, that * is a timetable with the overlaps flattened away. Drawn on one axis, it is the picture: the * fetch is long, the decode is short, the fold is thirty small bars, and the detector is a block * that began before anything was pressed. * * So this module records **intervals, in a tree, on one clock**: a span per thing measured, each * carrying where it started relative to the load, how long it ran, what it was, and which kind * of machine it was waiting on. `:timeaudit` (components/TimeAuditModal.tsx) draws it; * `hackermusic.timeAudit()` prints the same tree as text for when nobody wants a modal. * * Three rules, each one there because of how the first version was wrong: * * - **Spans are attached by track id, not by call stack.** The accent is asked for by a * reactive effect that has never heard of the loader; the fold is driven by the store's own * pump; the search runs in a worker. None of them can be reached by threading a handle * through, and an ambient "current span" is a lie the moment two of them overlap — which they * do constantly, on purpose. So the caller names the *track*, and the recorder decides which * load that track is in. Nesting stays explicit: a child is opened from its parent's handle, * which is the only parentage that survives an `await`. * - **An open span is a record, not a promise.** A span closes when the code that opened it * says so — including "before the promise settles", which is how a first byte arriving at 2s * and a body finishing at 9s become two bars rather than one nine-second mystery. The graph * extends whatever is still open to the current tick, so opening the modal *during* a load * shows a load in progress instead of a frozen half-picture. * - **Off means off: nothing built, nothing stored.** The same bargain `trace.ts` strikes with * its reader. Switched down, every entry point hands back a shared inert handle and never * reads the clock, so the instrumentation left in the load path costs a boolean and a call on * a path about to spend 200ms in a codec. * * One thing deliberately not done: no `PerformanceObserver`, no long-task sampling, no * self-organising timeline of other people's work. `perf.ts` already watches that, and a flame * graph whose bars are guesses about attribution is a chart that argues with the code beside it. * Every bar here is an interval some function opened and closed around its own wait. */import { createRoot, createSignal, type Accessor } from "solid-js";import { count } from "./print";
/** * What kind of machine the time went to. Six of these answer a question somebody asks out loud * — is it the network, the disk, the codec, the algorithm — and the last two are the honest * leftovers: `wait` for an await this audit could not name, `main` for this thread doing its own * work. A bar nobody can classify is a bar that should be classified, and the palette in the * modal makes an unclassified stretch visible rather than invisible. */export type AuditCategory = | "network" | "disk" | "decode" | "audio" | "analysis" | "waveform" | "accent" | "wait" | "main";
/** What a span says about itself: numbers, words, and nothing that has to be held onto. */export type AuditDetail = Record<string, string | number | boolean | undefined>;
/** Why this timeline exists. The bar's reason for the wait and the graph's reason differ. */export type AuditReason = "play" | "prefetch" | "warm" | "resume" | "unasked";
/** A recorded interval, in milliseconds from its audit's own zero. */export interface AuditSpan { /** stable within one audit — the graph's key and the selection's identity */ readonly key: number; readonly parent: number | null; readonly name: string; readonly category: AuditCategory; readonly start: number; /** null while it is still open; the graph extends it to the current tick */ readonly end: number | null; readonly detail?: AuditDetail; /** which thread measured it, when that is not the page's */ readonly thread?: "main" | "worker";}
/** A zero-width event: the press, the arm, the first sample. */export interface AuditMark { readonly key: number; readonly name: string; readonly at: number; readonly detail?: AuditDetail;}
export interface LoadAudit { /** unique across the page; 0 is the first load measured in this page's life */ readonly seq: number; readonly trackId: string; readonly title: string; readonly artist: string; readonly album: string; readonly reason: AuditReason; /** `performance.now()` at this audit's zero — the axis the spans are measured from */ readonly began: number; /** the wall clock at that same zero, so a screenshot can be lined up with a server log */ readonly wall: number; /** Facts about the whole load rather than one span: container, bytes, cache tier, refusals. */ meta(): Readonly<AuditDetail>; /** * The spans, and the version they were read at. * * A version counter rather than a fresh array per mutation: a waveform fold publishes a couple * of hundred slices, and copying the whole span list per slice would make the act of watching * the load measurably change the load. Depend on `version()`, read `raw()` — which does that * read for you, so a graph can take the list and its dependency in one call. */ version(): number; raw(): readonly AuditSpan[]; marks(): readonly AuditMark[]; /** Spans open at the last record — the header's "still running", and the reason to re-tick. */ openCount(): number; /** True once a newer load for the same track has taken this one's place. */ superseded(): boolean;}
/** The handle instrumentation holds: close it, abandon it, or open something underneath it. *//** * How a span is opened. * * `at` is the unusual one: a span for work that happened *on another thread*, which knows its own * start and end and reports them only when the answer comes back — by which time this thread's * clock has moved several seconds past the work it is being told about. The instants are absolute * `performance.now()` values, so they still land against the load's own zero, and the handle comes * back inert: there is nothing left to close. */export interface SpanOptions { thread?: "main" | "worker"; /** * Facts the span owns from the moment it opens, rather than facts that arrive with its answer. * * The difference matters for exactly the bars worth reading: a model still thinking, or one whose * answer never came, has no close-time detail to carry, and so would be drawn with no context at * all — no GPU asked for, no isolation flag, nothing — in the one case where the reader most needs * to know what the machine was. A later `close` adds to this rather than replacing it. */ detail?: AuditDetail | (() => AuditDetail); at?: { start: number; end: number; detail?: AuditDetail | (() => AuditDetail) };}
export interface AuditHandle { readonly key: number; /** Record the detail and stop the clock. A second call is a no-op — one interval, one record. */ close(detail?: AuditDetail | (() => AuditDetail)): void; /** * Stop the clock and say the wait ended without an answer, so the bar is not read as success. * * `detail` is for the numbers that arrived *with* the refusal — the phases a thread got through * before its wait ran out, which runtime it was running on — since the case where an answer never * comes is exactly the case where what it managed to say on the way out is the finding. */ abandon(reason: string, detail?: AuditDetail): void; /** Open a span nested under this one — the parentage that survives an `await`. */ child(name: string, category: AuditCategory, opts?: SpanOptions): AuditHandle; /** The span's own audit, for a caller holding the handle but not the track id. */ audit(): LoadAudit | null;}
/** How many load timelines to keep for `:timeaudit` to walk back through. */const AUDIT_CAP = 16;
/** * Spans per timeline. The waveform fold is the only thing that gets near this — a long track * folded in fine slices is a few hundred bars — and a cap exists so a bug in the * instrumentation (a span opened inside a render loop, say) is a truncated graph rather than a * page that has eaten its own heap. The truncation is said out loud in `meta()`. */const SPAN_CAP = 4000;
const clock = (): number => typeof performance === "undefined" || !performance.now ? Date.now() : performance.now();
const round = (ms: number): number => Math.round(ms * 100) / 100;
/** * `null` = nobody has said, so the default (on) stands; a boolean = said, from the console or * from a test. Off, the module stores nothing and reads no clock — see the third rule above. */let enabled: boolean | null = null;
function enabledState(): boolean { return enabled === null ? true : enabled;}
/** The timeline each track id's spans land in — the newest one begun for it. */const current = new Map<string, LoadAuditRecord>();
/** * The bookkeeping a record keeps that its readers do not: the arrays, the counters, and the * three writes the instrumentation makes. Deliberately *not* on `LoadAudit` — a caller that can * close somebody else's span can also fabricate one, and the graph's whole claim is that it only * draws what the code said. */interface LoadAuditRecord extends LoadAudit { push(span: AuditSpan): boolean; patch(span: AuditSpan): void; mark(name: string, detail?: AuditDetail): void; setMeta(detail: AuditDetail): void; /** One open span more or less; the plain counter is the write path's, the signal is the graph's. */ countOpen(delta: 1 | -1): void; /** Stop accepting records: a newer load for this track owns the timeline now. */ supersede(): void; /** * Whether this timeline has been taken over, asked *without* subscribing to the answer. * * The write path needs this decision (`span` refuses to record into a dead timeline) and must * not take a dependency to make it: `span` is called from click handlers, from effect callbacks * and from promise continuations alike, and a probe that subscribes is a probe that reports * `STRICT_READ_UNTRACKED` from wherever it happens to be standing. The public `superseded()` * accessor is the subscribing one, for the graph. */ isDead(): boolean; /** The next span key, from this timeline's own counter. */ takeKey(): number;}
/** * A value beside a signal — the `field` idiom from `player/store.ts`, kept local because this * module has one use for it and none of its readers want the setter exposed. * * Solid commits a write at the end of the task, so a signal *read* in the task that wrote it * answers from before the write. Every reader here is in exactly that position: the graph asks * what a load looks like immediately after the recorder wrote a span into it, and the write path * asks whether a timeline is still alive before writing into it. So the plain value is the truth * and the signal is only the dependency that says a truth changed — which is what `get` pairs: * register the dependency, answer with the truth. */function mirror<T>(initial: T, name: string) { let current = initial; const [read, write] = createSignal<T>(initial as unknown as Exclude<T, Function>, { name }); return { /** As it is *now*, in this task, with no dependency taken: for the module's own decisions. */ value: (): T => current, /** As it is now, *and* reactive: what the graph reads. */ get(): T { read(); return current; }, set(next: T): void { current = next; write(next as unknown as Exclude<T, Function>); }, };}
/** * Build one timeline. Its signals live inside a root of the timeline's own. * * That is not tidiness: a timeline is begun from wherever a press lands — a click handler with no * owner, an effect during a session restore, a test's root — and a signal created in whichever * owner happens to be current is disposed with it. A timeline disposed under a still-playing track * would stop updating its graph while its spans kept being written: a bug whose only symptom is a * picture that has quietly stopped being true. Own root, own lifetime. */function build( seq: number, song: { id: string; title?: string; artist?: string; album?: string }, reason: AuditReason,): LoadAuditRecord { let record!: LoadAuditRecord; createRoot((dispose) => { // Retained on purpose: see the note in `beginAudit` — a timeline is never disposed while the // page lives, because a late span holds a handle into it, and a write to a dead signal is the // one failure mode worse than holding sixteen timelines alive. void dispose; const began = clock(); const spans: AuditSpan[] = []; const marksList: AuditMark[] = []; let key = 0; let dropped = 0; const version = mirror(0, `audit-${seq}-version`); const open = mirror(0, `audit-${seq}-open`); const dead = mirror(false, `audit-${seq}-superseded`); const meta = mirror<Readonly<AuditDetail>>({}, `audit-${seq}-meta`); const marks = mirror<readonly AuditMark[]>([], `audit-${seq}-marks`);
/** The one mutation primitive: change something, then say there is something new to draw. */ const bump = () => version.set(version.value() + 1);
record = { seq, trackId: song.id, title: song.title ?? "", artist: song.artist ?? "", album: song.album ?? "", reason, began, wall: Date.now(), meta: () => meta.get(), version: () => version.get(), raw: () => { // The dependency, taken here so that every reader of the list is also a reader of the // change that list makes. Without it `spans` is a plain array and the graph never wakes. version.get(); return spans; }, marks: () => marks.get(), openCount: () => open.get(), superseded: () => dead.get(), isDead: () => dead.value(), takeKey: () => ++key, push(span) { if (spans.length >= SPAN_CAP) { dropped += 1; if (dropped === 1 || dropped % 512 === 0) { meta.set({ ...meta.value(), "spans-dropped": dropped }); } return false; } spans.push(span); bump(); return true; }, patch(span) { for (let i = spans.length - 1; i >= 0; i--) { if (spans[i]!.key !== span.key) continue; spans[i] = span; bump(); return; } }, mark(name, detail) { marksList.push({ key: marksList.length, name, at: round(clock() - began), detail }); // A fresh array here, where the span list gets an in-place push: marks are few (a press, // an arm, a first sample) and a `<For>` wants a new value to iterate rather than a longer // array it has already been handed. marks.set([...marksList]); }, setMeta(detail) { meta.set({ ...meta.value(), ...detail }); }, countOpen(delta) { open.set(Math.max(0, open.value() + delta)); }, supersede() { if (dead.value()) return; dead.set(true); // Anything still open at this moment stopped being a measurement when the load was taken // over: it is not that the wait never ended, it is that nobody is waiting for that track // any more. Left open, the graph would grow a bar forever under a header saying the load // is over — the one thing this module must never draw. let changed = false; for (let i = 0; i < spans.length; i++) { const s = spans[i]!; if (s.end !== null) continue; spans[i] = { ...s, end: round(clock() - began), detail: { ...s.detail, abandoned: true }, }; changed = true; } open.set(0); if (changed) bump(); }, }; }); return record;}
/** The shared inert handle. * * One object rather than a new no-op per call: instrumentation that allocates while switched off * has not been switched off, it has been switched to a different cost. Exported so a caller whose * handle is optional (`media.ts`'s load log) can hold something that means "nowhere to write". */export const NO_SPAN: AuditHandle = { key: -1, close: () => undefined, abandon: () => undefined, child: () => NO_SPAN, audit: () => null,};
/** `k=v` pairs with `undefined` dropped — the shape the trace's lines already print. */function detailOf(detail?: AuditDetail | (() => AuditDetail)): AuditDetail | undefined { if (!detail) return undefined; const built = typeof detail === "function" ? detail() : detail; const out: AuditDetail = {}; for (const [k, v] of Object.entries(built)) if (v !== undefined) out[k] = v; return Object.keys(out).length ? out : undefined;}
let seq = 0;let list: LoadAuditRecord[] = [];const auditList = mirror<readonly LoadAuditRecord[]>([], "audit-list");
/** * Start the timeline for a track the listener (or the prefetcher) has just asked for. * * The previous timeline for that id is *superseded*, not thrown away: it stays in the list so * `:timeaudit` can walk back to the load that just got interrupted — usually the load whose * timing you wanted, since an interrupted load is a load whose shape changed. */export function beginAudit( song: { id: string; title?: string; artist?: string; album?: string }, reason: AuditReason = "play",): LoadAudit | null { // Switched off, a timeline would be a thing to build, keep, and draw nothing from — so the // answer to a disabled recorder is no timeline at all, and every caller already has to be able // to hold a null one (there is no timeline for a track nothing has asked for yet). if (!enabledState()) return null; const record = build(seq, song, reason); seq += 1; for (const older of list) if (older.trackId === song.id) older.supersede(); current.set(song.id, record); list = [record, ...list].slice(0, AUDIT_CAP); // Superseded records stay in the list — dropping them would take the walk-back away with them. // Nothing is disposed either: sixteen timelines are a few dozen signals, and disposing one // while a late span still holds a handle into it is a write to a dead signal for the sake of // bytes nobody will notice. auditList.set(list); return record;}
/** * The timeline a span about `trackId` belongs to, or null when there is nothing to write into. * * Null is the common case for the album warmer: it walks ahead of the clock, and an audit per * album track would spend the whole ring on records nobody asked about. The warmer's spans * therefore land inside a load that already exists, and are dropped where there is none. */export function auditFor(trackId: string | null | undefined): LoadAudit | null { if (!enabledState() || !trackId) return null; return current.get(trackId) ?? null;}
/** * Open a span. `trackId` decides *which load*; `parent` decides *where inside it*. * * With no parent the span is a top-level bar — which is what the accent's effect, the fold's * pump and the detector's worker should pass, because none of them sits inside the loader's * await chain, and a graph that pretends otherwise draws the cover's fetch underneath the codec. */export function span( trackId: string | null | undefined, name: string, category: AuditCategory, parent?: AuditHandle | null, opts?: SpanOptions,): AuditHandle { if (!enabledState()) return NO_SPAN; // Every `LoadAudit` this module hands out *is* a `LoadAuditRecord` — the interface is the // record's public face, not a second object — which is what makes this widening cast safe. const nested = parent && parent.key >= 0 ? parent.audit() : null; const record = (nested ?? auditFor(trackId)) as LoadAuditRecord | null; if (!record || record.isDead()) return NO_SPAN; const began = record.began; const key = record.takeKey(); if (opts?.at) { // Born closed, at instants somebody else measured. The worker's phases arrive in one reply // twenty seconds after the work they describe, and a span that claimed to have *started* on // arrival would draw the model's arithmetic as a bar at the end of the load rather than // spread across it — which is the opposite of what the graph is for. const born: AuditSpan = { key, parent: parent && parent.key >= 0 ? parent.key : null, name, category, start: round(opts.at.start - began), end: round(Math.max(opts.at.start, opts.at.end) - began), thread: opts.thread, detail: detailOf(opts.at.detail), }; record.push(born); return NO_SPAN; } const opened: AuditSpan = { key, parent: parent && parent.key >= 0 ? parent.key : null, name, category, start: round(clock() - began), end: null, thread: opts?.thread, ...(opts?.detail ? { detail: detailOf(opts.detail) } : {}), }; if (!record.push(opened)) return NO_SPAN; record.countOpen(1); // `live` is the handle's own, not the record's: `close` has to be idempotent against the `finally` // that arrives after a watchdog already closed the same wait, and an ambient boolean in this // closure is the smallest thing that can promise that. A close that arrives *after* the timeline // was superseded is allowed to land — the work really did finish, and its real end is a better // answer than the `abandoned` one the takeover wrote — and the open-count is floored at zero for // exactly that case, since supersede has already cleared it. let live = true; const handle: AuditHandle = { key, close(detail) { if (!live) return; live = false; // Merged, not replaced: what was true when the span opened is still true when it closes, and a // close that arrived with only its own two numbers would otherwise erase the machine behind it. record.patch({ ...opened, end: round(clock() - began), detail: { ...opened.detail, ...detailOf(detail) }, }); record.countOpen(-1); }, abandon(reason, detail) { if (!live) return; live = false; record.patch({ ...opened, end: round(clock() - began), detail: { ...opened.detail, ...detail, abandoned: reason }, }); record.countOpen(-1); }, child: (name2, category2, opts2) => span(trackId, name2, category2, handle, opts2), audit: () => record, }; return handle;}
/** * Mark a moment rather than a stretch: the press, the arm, the first sample. * * Marks are why the graph reads as a story instead of a pile. A four-second "network" bar means * one thing with the press mark at zero and quite another with it at 3.9s — the bytes were * already on their way — and only a mark says which. */export function mark( trackId: string | null | undefined, name: string, detail?: AuditDetail | (() => AuditDetail),): void { (auditFor(trackId) as LoadAuditRecord | null)?.mark(name, detailOf(detail));}
/** Facts about the load as a whole, shown in the graph's header rather than on one bar. */export function noteAudit( trackId: string | null | undefined, detail: AuditDetail | (() => AuditDetail),): void { const record = auditFor(trackId) as LoadAuditRecord | null; const built = detailOf(detail); if (record && built) record.setMeta(built);}
/** Every timeline kept, newest first. Reactive on the list, not on the spans inside it. */export const audits: Accessor<readonly LoadAudit[]> = () => auditList.get();
/** The newest timeline for one track. */export function latestAudit(trackId: string | null | undefined): LoadAudit | null { if (!trackId) return null; // A lookup, not a subscription: `audits()` is the reactive face of this list, and a helper that // subscribed as a side effect of finding one entry would report an untracked read from whatever // untracked place asked for it. return auditList.value().find((a) => a.trackId === trackId) ?? null;}
/** * Whether the recorder is running. * * On by default, in dev and in the built page alike: `trace.ts` may be a dev-only thing because * its reader is a console, but this one's reader is a keyboard shortcut on a phone over the * tailnet, and a diagnostic that exists only in the dev build cannot describe the build in use. */export function auditEnabled(): boolean { return enabledState();}
/** * Switch the recorder on or off — or back to "nobody has said" with `null`, which is what a test * does when it has finished being explicit and does not want to leave the page in its setting. * Off, the load path builds nothing at all. */export function setAuditEnabled(on: boolean | null): void { enabled = on;}
/** Forget every timeline — a test's reset, and the only way to get the ring buffer back empty. */export function clearAudits(): void { for (const record of current.values()) record.supersede(); current.clear(); list = []; seq = 0; auditList.set(list); shown.set(null);}
// ---------------------------------------------------------------------------------------------// The modal's hand. One signal, here rather than in the component, because the two things that// raise the graph — the `:timeaudit` verb and the console handle — both live on this side of the// import graph, and a command that had to reach into a component module to open a dialog would// drag the renderer into the command table.// ---------------------------------------------------------------------------------------------
const shown = mirror<LoadAudit | null>(null, "audit-modal");
/** The timeline the graph is showing, or null with no graph on screen. */export const auditModal: Accessor<LoadAudit | null> = () => shown.get();
/** Raise the graph. With no argument: the newest load measured, which is the one being asked about. */export function showAudit(audit?: LoadAudit | null): void { shown.set(audit ?? auditList.value()[0] ?? null);}
export function hideAudit(): void { shown.set(null);}
/** * Walk the graph to another recorded load: `-1` is the load *before* this one, `+1` the one after. * * The direction is about time, not about the index it is looked up by — the list is kept newest * first, so the two are opposite, and a caller should not have to know that to point an arrow key * at the right thing. Walking off either end stops rather than wrapping: a graph that cycles onto * a different track while you are looking for the one in front of you has changed the subject. */export function stepAudit(dir: -1 | 1): LoadAudit | null { const all = auditList.value(); if (!all.length) return null; const here = shown.value(); const at = here ? all.findIndex((a) => a.seq === here.seq) : -1; const to = at < 0 ? 0 : Math.min(all.length - 1, Math.max(0, at - dir)); const next = all[to] ?? null; shown.set(next); return next;}
// ---------------------------------------------------------------------------------------------// The same tree, as text, for `hackermusic.timeAudit()` and for anybody reading a pasted line.// ---------------------------------------------------------------------------------------------
/** Milliseconds, at the precision that matches their size: 2.4ms is not 0ms. */const ms = (v: number): string => (Math.abs(v) < 10 ? `${v.toFixed(2)}ms` : `${v.toFixed(0)}ms`);
/** * How long this timeline runs: the latest end any span reaches, with open spans taken to the * tick asked about (now, by default). It is the axis the graph is scaled to and the denominator * of every share printed beside a bar. */export function auditLength(audit: LoadAudit, at = clock()): number { let end = 0; for (const s of audit.raw()) end = Math.max(end, s.end ?? round(at - audit.began)); return Math.max(0, end);}
/** * The graph as an indented tree: one line per span, in the order the bars are drawn. * * The duration is printed twice on purpose — absolute, and as a share of the load — because they * are different questions ("the decode took 230ms", "the decode was a third of it") and the * second is the one that decides what to go and look at. */export function describeAudit(audit: LoadAudit, at = clock()): string { const spans = audit.raw(); const total = auditLength(audit, at); const lines: string[] = [ `${audit.trackId} · ${audit.title || "untitled"} · ${audit.reason} · ${ms(total)} · ${count(spans.length, "span")}${audit.superseded() ? " (superseded)" : ""}`, ]; const meta = Object.entries(audit.meta()) .filter(([, v]) => v !== undefined) .map(([k, v]) => `${k}=${v}`) .join(" "); if (meta) lines.push(` ${meta}`); const kids = new Map<number | null, AuditSpan[]>(); for (const s of spans) { const bucket = kids.get(s.parent) ?? []; bucket.push(s); kids.set(s.parent, bucket); } const walk = (parent: number | null, depth: number): void => { for (const s of (kids.get(parent) ?? []).slice().sort((a, b) => a.start - b.start)) { const end = s.end ?? round(at - audit.began); const dur = Math.max(0, end - s.start); const share = total > 0 ? Math.round((100 * dur) / total) : 0; const detail = Object.entries(s.detail ?? {}) .filter(([, v]) => v !== undefined) .map(([k, v]) => `${k}=${v}`) .join(" "); lines.push( ` ${ms(s.start).padStart(8)} ${ms(dur).padStart(8)} ${`${share}%`.padStart(4)} ${s.category.padEnd(9)} ${"│ ".repeat(depth)}${s.name}${detail ? ` (${detail})` : ""}`, ); walk(s.key, depth + 1); } }; walk(null, 0); for (const m of audit.marks()) { lines.push(` ${ms(m.at).padStart(8)} ${" "} ${"mark".padEnd(9)} ${m.name}`); } return lines.join("\n");}
/** * The console handle, installed the way `trace.ts` installs its own. * * hackermusic.timeAudit() // is it recording? * hackermusic.timeAudit(true) // start again * hackermusic.timeAudit(false) // stop; the load path builds nothing at all * hackermusic.timeAudit("show") // the last load, as a text flamegraph * hackermusic.timeAudit("all") // every recorded load that way, in one paste * hackermusic.timeAudit("clear") // forget them * * Installed by `installPlayerConsoleHandles` in `player/index.ts`, alongside the trace switches it * is the graphical sibling of — one door for the console, so that what is installed and what the * docs list cannot drift apart. */export interface TimeAuditHandle { (): boolean; (on: boolean): boolean; (what: "show" | "all" | "clear" | "json"): string;}
export const timeAuditHandle: TimeAuditHandle = (( ask?: boolean | "show" | "all" | "clear" | "json",) => { if (ask === true) { setAuditEnabled(true); return true; } if (ask === false) { setAuditEnabled(false); return false; } if (ask === "show") { const one = auditList.value()[0]; return one ? describeAudit(one) : "nothing measured yet"; } if (ask === "all") return auditList .value() .map((a) => describeAudit(a)) .join("\n\n"); if (ask === "json") return auditJSON({ app: { build: null } }); if (ask === "clear") { clearAudits(); return "forgotten"; } return auditEnabled();}) as TimeAuditHandle;
/** * The records themselves, as one string. * * `describeAudit` is a *rendering* — good for a glance at a console, lossy for anything else: it * rounds, truncates and drops whichever fields the text layout had no room for. This is the other * half, and the half that matters when the machine doing the reading is not the one that did the * waiting: every span this device measured, with its own instants and its own detail, beside the * context that makes them interpretable — how many cores, whether there was a GPU to ask for, * whether the page was isolated enough for threaded wasm. * * The spans go out as `raw()` has them, milliseconds relative to the load they belong to: the same * objects the graph lays out, so what somebody reads is what the bars said, and no rounding step * between the two gets to have an opinion. Open spans stay open (`end: null`) rather than being * stretched to the moment of export — `at` is recorded, so a reader can see how long ago that was. * * DOM-free on purpose: this is data, and it is asserted as data. */export interface AuditExportLoad { trackId: string; title: string; artist?: string; album?: string; reason: AuditReason; /** when the load began, on the same clock the spans' own `start`/`end` are relative to. */ began: number; length: number; open: number; superseded: boolean; meta: AuditDetail; spans: AuditSpan[];}
export interface AuditExport { format: "hackermusic.timeaudit/1"; /** the instant of the export, so an open span can be read as "still running, this long". */ at: number; app?: Record<string, string | number | boolean | null>; device: Record<string, string | number | boolean | undefined>; loads: AuditExportLoad[];}
/** * What kind of machine this was, as far as a page can tell without asking anything's permission. * * Half of the diagnoses a load audit ever receives will be "why is this twenty seconds on my phone * and three on the laptop", and the spans alone cannot answer that: the same nine inference windows * mean different things on a device with no GPU, on two cores, or on a page that was never * cross-origin-isolated so the wasm runtime had one thread to work with. These are the flags that * separate those, and they are cheap — every one is a `typeof` or a property nobody else reads. *//** * The same probe the export writes its `device` block from, exported because the *bars* want a few of * these facts at open time — see `SpanOptions.detail`. One place asks the device, and the graph and * the file cannot disagree about what it said. */export function auditEnvironment(): Record<string, string | number | boolean | undefined> { const g = globalThis as Record<string, unknown>; const nav = typeof navigator === "undefined" ? undefined : navigator; const gpu = (nav as { gpu?: unknown } | undefined)?.gpu; return { ua: nav?.userAgent, platform: (nav as { platform?: string } | undefined)?.platform, cores: (nav as { hardwareConcurrency?: number } | undefined)?.hardwareConcurrency, memory: (nav as { deviceMemory?: number } | undefined)?.deviceMemory, // *Available*, not *used*: whether the model actually got the GPU is on the model's own bar, // where the runtime's refusal is printed too. This only says whether asking was possible. gpu: gpu !== undefined && gpu !== null, worker: typeof Worker === "function", wasm: typeof WebAssembly === "object", secure: typeof isSecureContext === "boolean" ? isSecureContext : undefined, isolated: (g as { crossOriginIsolated?: boolean }).crossOriginIsolated === true, href: typeof location === "object" ? location.href : undefined, };}
export function auditJSON(opts?: { /** the last N loads rather than every one still in the buffer */ loads?: number; app?: Record<string, string | number | boolean | null>;}): string { const at = clock(); // `audits()` is newest first — the same order `timeAudit("all")` prints in — and the report keeps // it, so a file and a console say the loads in the same order. `loads` therefore takes from the // front: the most recent N, which is what a report is wanted for. let list = audits().slice(); if (opts?.loads !== undefined) list = list.slice(0, Math.max(0, opts.loads)); const loads: AuditExportLoad[] = list.map((audit) => ({ trackId: audit.trackId, title: audit.title, artist: audit.artist, album: audit.album, reason: audit.reason, began: audit.began, length: auditLength(audit, at), open: audit.openCount(), superseded: audit.superseded(), meta: audit.meta(), spans: audit.raw().map((span) => ({ ...span })), })); const out: AuditExport = { format: "hackermusic.timeaudit/1", at, app: opts?.app, device: auditEnvironment(), loads, }; return JSON.stringify(out);}