Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { auditEnabled, auditFor, auditJSON, auditLength, auditModal, audits, beginAudit, clearAudits, describeAudit, hideAudit, latestAudit, mark, noteAudit, setAuditEnabled, showAudit, span, stepAudit, timeAuditHandle, type LoadAudit,} from "./loadaudit";
/** * The recorder itself: what a span is, where it lands, and what the graph is allowed to believe. * * The clock is stubbed rather than slept through. Every number this module produces is a * difference of two `performance.now()` reads, and a test that asserted `>= 0` against a real * clock would assert nothing at all about the thing that actually breaks — a span measured from * the wrong zero, a child attached to the wrong parent, a load that never stops being open. */
let now = 1000;const advance = (ms: number): void => { now += ms;};
const song = (id: string): { id: string; title: string; artist: string; album: string } => ({ id, title: `Track ${id}`, artist: "Autechre", album: "Amber",});
beforeEach(() => { now = 1000; vi.spyOn(performance, "now").mockImplementation(() => now); setAuditEnabled(true); clearAudits();});
afterEach(() => { vi.restoreAllMocks(); hideAudit(); clearAudits(); setAuditEnabled(null);});
it("measures a span from the load's own zero, not from the page's", () => { advance(4000); // the page has been up a while; the load has not const audit = beginAudit(song("s1"), "play") as LoadAudit; const s = span("s1", "server response", "network"); advance(250); s.close({ status: 200, bytes: 4182532 });
const [recorded] = audit.raw(); expect(recorded).toMatchObject({ name: "server response", category: "network", start: 0, end: 250, detail: { status: 200, bytes: 4182532 }, }); expect(auditLength(audit)).toBe(250);});
it("keeps a child under the handle that opened it, and a stranger at the top", () => { const audit = beginAudit(song("s1"), "play") as LoadAudit; const fetch = span("s1", "stream", "network"); advance(10); // The body is inside the stream. The cover is not: it is asked for by an effect that has never // heard of the loader, and a graph that hung it under the codec would be a lie about the wait. const body = fetch.child("body", "network"); const cover = span("s1", "cover palette", "accent"); advance(40); body.close({ bytes: 12 }); cover.close(); fetch.close();
const spans = audit.raw(); const byName = Object.fromEntries(spans.map((s) => [s.name, s])); expect(byName.stream!.parent).toBeNull(); expect(byName.body!.parent).toBe(byName.stream!.key); expect(byName["cover palette"]!.parent).toBeNull(); expect(byName.body!.start).toBe(10);});
it("leaves a span open until the code that opened it says so", () => { const audit = beginAudit(song("s1"), "play") as LoadAudit; const s = span("s1", "decoder", "decode"); advance(300); expect(audit.raw()[0]!.end).toBeNull(); expect(audit.openCount()).toBe(1); // The graph's own answer for an open bar is "up to now", which is what makes watching a load // while it happens possible at all. expect(auditLength(audit)).toBe(300); s.close({ channels: 2 }); expect(audit.openCount()).toBe(0); expect(audit.raw()[0]!.end).toBe(300);});
it("closes a span once: a second close does not move the end", () => { const audit = beginAudit(song("s1"), "play") as LoadAudit; const s = span("s1", "wait for bytes", "wait"); advance(100); s.close(); advance(5000); // …the `finally` that closes it anyway, or the watchdog that closes it first. s.close({ late: true }); expect(audit.raw()[0]).toMatchObject({ end: 100 });});
it("closes what was still open when the load was superseded", () => { const first = beginAudit(song("s1"), "play") as LoadAudit; span("s1", "server response", "network"); advance(20); span("s1", "cover palette", "accent"); // never closed, on purpose beginAudit(song("s1"), "play"); // the listener pressed again
expect(first.superseded()).toBe(true); expect(first.openCount()).toBe(0); // A bar that grew forever under a header saying the load is over is the one thing this module // must never draw, so an abandoned wait is closed and says it was abandoned. expect(first.raw().every((s) => s.end !== null)).toBe(true); expect(first.raw().map((s) => s.detail?.abandoned)).toEqual([true, true]);});
it("drops spans for a track nobody has asked for, rather than inventing a timeline", () => { // The album warmer walks records the listener has not reached. A timeline per one of them // would spend the whole ring buffer on loads nobody asked to see. expect(auditFor("nowhere")).toBeNull(); const s = span("nowhere", "bytes", "network"); expect(s.key).toBe(-1); s.close(); expect(audits()).toHaveLength(0);});
it("says why a wait ended without an answer", () => { const audit = beginAudit(song("s1"), "play") as LoadAudit; span("s1", "body", "network").abandon("the listener moved on"); expect(audit.raw()[0]).toMatchObject({ end: 0, detail: { abandoned: "the listener moved on" } });});
it("records a failure in the span rather than leaving the bar growing", () => { // The shape the load path actually uses: open, `try`, and abandon from the `catch`. A bar that // keeps growing under a header saying the load is over is the one thing this module must never // draw, so the throw has to close it with the reason in its detail — which is also the only // reason `abandon` exists as distinct from `close`. const audit = beginAudit(song("s1"), "play") as LoadAudit; advance(5); const decoding = span("s1", "decode", "decode"); advance(80); try { throw new Error("no AudioContext"); } catch (e) { decoding.abandon(e instanceof Error ? e.message : String(e)); } expect(audit.raw()[0]).toMatchObject({ name: "decode", start: 5, end: 85, detail: { abandoned: "no AudioContext" }, }); expect(audit.openCount()).toBe(0);});
it("marks a moment, and notes a fact about the whole load", () => { const audit = beginAudit(song("s1"), "play") as LoadAudit; mark("s1", "press", { offset: 0 }); advance(30); noteAudit("s1", { container: "flac", "warm-from": "memory" }); expect(audit.marks()).toEqual([{ key: 0, name: "press", at: 0, detail: { offset: 0 } }]); expect(audit.meta()).toEqual({ container: "flac", "warm-from": "memory" });});
it("keeps the last sixteen loads, newest first", () => { for (let i = 0; i < 20; i++) beginAudit(song(`s${i}`), i % 2 ? "prefetch" : "play"); const all = audits(); expect(all).toHaveLength(16); expect(all[0]!.trackId).toBe("s19"); // The ring keeps the *recent* sixteen: the four oldest loads are gone, and nothing older than a // dozen tracks is ever being asked about anyway. expect(all[15]!.trackId).toBe("s4"); expect(latestAudit("s19")?.seq).toBe(all[0]!.seq); expect(latestAudit("nothing")).toBeNull();});
it("builds nothing at all while switched off", () => { setAuditEnabled(false); expect(auditEnabled()).toBe(false); expect(beginAudit(song("s1"), "play")).toBeNull(); const s = span("s1", "stream", "network"); expect(s.key).toBe(-1); s.child("body", "network").close(); mark("s1", "press"); noteAudit("s1", { bytes: 1 }); expect(audits()).toHaveLength(0);});
it("walks the recorded loads, and shows the newest one by default", () => { beginAudit(song("s1"), "play"); beginAudit(song("s2"), "prefetch"); showAudit(); // no argument: the newest load measured expect(auditModal()?.trackId).toBe("s2"); // `-1` is the load *before* this one, whatever order the list happens to be kept in. expect(stepAudit(-1)?.trackId).toBe("s1"); // Walking off the end stops rather than wrapping: a graph that cycles onto another track while // you are looking for the one in front of you has changed the subject. expect(stepAudit(-1)?.trackId).toBe("s1"); expect(stepAudit(1)?.trackId).toBe("s2"); hideAudit(); expect(auditModal()).toBeNull();});
it("lets a close that arrives after the takeover overwrite the abandonment it wrote", () => { const audit = beginAudit(song("s1"), "play") as LoadAudit; const s = span("s1", "body", "network"); beginAudit(song("s1"), "play"); // the takeover closes it and says so expect(audit.raw()[0]!.detail?.abandoned).toBe(true); advance(120); // …and then the bytes really do arrive. The work finished; its end is the truth, and a graph // still showing `abandoned` here would be the recorder defending its own earlier guess. s.close({ bytes: 9 }); expect(audit.raw()[0]).toMatchObject({ end: 120, detail: { bytes: 9 } }); expect(audit.openCount()).toBe(0); // floored, not driven negative by the late close});
it("exports the records, with the machine they were measured on", () => { // The text tree is a rendering; this is the data, and it has to survive being read by something // that was not here. Asserted as data: parse it back, and the spans must be the spans. const first = beginAudit(song("s1"), "play") as LoadAudit; const outer = span("s1", "ask the original", "network"); span("s1", "server response", "network", outer).close({ status: 200 }); advance(100); outer.close({ cameFrom: "network" }); const second = beginAudit(song("s2"), "prefetch") as LoadAudit; // still open, nothing has answered
const report = JSON.parse(auditJSON()) as { format: string; at: number; device: Record<string, unknown>; loads: { trackId: string; length: number; open: number; spans: Record<string, unknown>[] }[]; }; expect(report.format).toBe("hackermusic.timeaudit/1"); expect(report.at).toBeGreaterThanOrEqual(first.began); // The context that turns "22 seconds" into an answer: no GPU, two cores and an unisolated page are // three different explanations for one bar, and the spans alone cannot tell them apart. // The four flags that separate the diagnoses — a device with no GPU, with one core, with a page // that never got the isolation threaded wasm needs, in a browser that has no workers at all — plus // the two that identify the build and the page it was served from. for (const flag of ["cores", "gpu", "isolated", "worker", "wasm", "ua", "href"]) expect(report.device).toHaveProperty(flag); // And absent rather than guessed at: jsdom has no `deviceMemory`, and an export that filled one in // would be inventing a fact about a machine it is not standing on. expect("memory" in report.device).toBe(false); expect(report.loads.map((l) => l.trackId)).toEqual(["s2", "s1"]); // newest first, as `audits()` is const [newest, oldest] = report.loads; expect(oldest!.length).toBe(100); expect(oldest!.open).toBe(0); expect(oldest!.spans).toEqual(first.raw()); // verbatim, not a summary of it // An open load exports as it stands — `end: null` — and the report's own `at` is what dates it. expect(newest!.spans).toHaveLength(0); // a load that has not been measured at all yet expect(second.trackId).toBe("s2"); span("s2", "wait for the bytes", "wait"); expect(JSON.parse(auditJSON()).loads[0]!.spans[0]).toMatchObject({ name: "wait for the bytes", end: null, }); // Bounded when asked, from the newest. expect( JSON.parse(auditJSON({ loads: 1 })).loads.map((l: { trackId: string }) => l.trackId), ).toEqual(["s2"]);});
it("answers the console handle, and forgets when asked", () => { syntheticForHandle(); expect(timeAuditHandle()).toBe(true); expect(timeAuditHandle("show")).toContain("server response"); expect(timeAuditHandle("all")).toContain("server response"); expect(timeAuditHandle(false)).toBe(false); expect(beginAudit(song("s9"), "play")).toBeNull(); // off means off, from this moment expect(timeAuditHandle(true)).toBe(true); expect(timeAuditHandle("clear")).toBe("forgotten"); expect(audits()).toHaveLength(0); expect(auditModal()).toBeNull();});
function syntheticForHandle(): void { beginAudit(song("s1"), "play"); const s = span("s1", "server response", "network"); advance(250); s.close({ status: 200 });}
it("says what the machine was when the bar opened, not only when it closed", () => { // A bar whose answer never arrives has no close-time detail to carry — and that is the bar a reader // most needs the machine behind. So facts can be written when the span opens, and a later close // adds to them rather than wiping them out. const audit = beginAudit(song("s1"), "play") as LoadAudit; const model = span("s1", "beat model", "analysis", null, { thread: "worker", detail: { gpu: true, isolated: false, cores: 8 }, }); expect(audit.raw()[0]!.detail).toEqual({ gpu: true, isolated: false, cores: 8 }); model.close({ phases: 12, threads: 1 }); expect(audit.raw()[0]!.detail).toEqual({ gpu: true, isolated: false, cores: 8, phases: 12, threads: 1, }); // Abandon carries the same promise: the reason goes in, what was already said stays. const other = span("s1", "beat model", "analysis", null, { thread: "worker", detail: { gpu: false }, }); other.abandon("the wait ran out", { phases: 3 }); expect(audit.raw()[1]!.detail).toEqual({ gpu: false, phases: 3, abandoned: "the wait ran out" });});
it("takes the instants from the thread that did the work", () => { // A worker reports its phases when the answer comes back, seconds after they happened. A span // that 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 one thing the graph must not do. const audit = beginAudit(song("s1"), "play") as LoadAudit; advance(5000); // the whole load has moved on while the thread was thinking const zero = audit.began; const parent = span("s1", "beat model", "analysis", null, { thread: "worker" }); span("s1", "infer window", "analysis", parent, { thread: "worker", at: { start: zero + 1200, end: zero + 3600, detail: { window: "1/9" } }, }); const [beats] = audit.raw().filter((x) => x.name === "infer window"); expect(beats).toMatchObject({ start: 1200, end: 3600, thread: "worker", parent: audit.raw()[0]!.key, // under the model's bar, not beside it detail: { window: "1/9" }, }); // Born closed: nothing is left running, and the handle it returns cannot close it again. expect(audit.openCount()).toBe(1); // only the parent is open span("s1", "infer window", "analysis", parent, { thread: "worker", at: { start: zero + 3600, end: zero + 6000 }, }).close(); // inert, by construction expect(audit.raw().filter((x) => x.name === "infer window")[1]).toMatchObject({ start: 3600, end: 6000, }); expect(audit.openCount()).toBe(1);});
it("prints the same tree the graph draws", () => { const audit = beginAudit(song("s1"), "play") as LoadAudit; const stream = span("s1", "stream", "network"); advance(2000); stream.child("body", "network").close({ bytes: 4182532 }); advance(300); stream.close({ status: 200 }); mark("s1", "press"); const text = describeAudit(audit); expect(text).toContain("s1 · Track s1 · play · 2300ms · 2 spans"); expect(text).toContain("network"); expect(text).toContain("status=200"); // The child is indented under its parent, and the share of the load is printed beside the // absolute duration, because "how long" and "how much of it" are different questions. expect(text).toMatch(/stream[\s\S]*\n.*│ body/); expect(text).toContain("mark");});
it("says one span in the singular", () => { // The header line is quoted in bug reports, and "1 spans" is the kind of thing that gets // quoted back. Every other case here measures a load with several spans in it, which is // exactly why the singular is never seen until someone plays a file from warm cache. const audit = beginAudit(song("s1"), "play") as LoadAudit; span("s1", "stream", "network").close({ status: 200 }); expect(describeAudit(audit)).toContain("1 span");});