import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, waitFor } from "@solidjs/testing-library";
import { Show, type VoidComponent } from "solid-js";
import { captureArtifact, expectNoDiagnostics } from "../test/diagnostics";
import { stubResizeObserver } from "../test/env";
import { FakeAudioContext, stubStreamFetch, type StreamFetchStub } from "../test/audio";
import { mediaFiles, navidromeFetch, type FakeMediaFile } from "../test/navidrome";
import App from "../App";
import { TimeAuditModal } from "./TimeAuditModal";
import { clearConnection, saveConnection } from "../lib/connection";
import { library } from "../lib/harvest";
import {
auditModal,
beginAudit,
clearAudits,
hideAudit,
latestAudit,
mark,
noteAudit,
setAuditEnabled,
showAudit,
span,
type LoadAudit,
} from "../lib/loadaudit";
import { player } from "../lib/player";
import { forgetMediaVerdicts } from "../lib/player/media";
/**
* The load flamegraph, drawn.
*
* The recorder has its own tests; these are about the *drawing*, and specifically the two things a
* flamegraph gets wrong more often than anything else.
*
* - **The lanes.** This load has spans that run *beside* each other rather than inside each other
* — the fetch, the cover's palette, the fold — and two of them in the same row of pixels at the
* same moment is one unreadable bar, which is very easy to miss in a screenshot and is exactly
* what the lane assignment exists to prevent.
* - **The axis.** The widths *are* the measurement, so counting bars proves nothing about what the
* picture is for. The synthetic load below is exactly 1000ms and the chart is the component's
* fallback 960px (jsdom lays nothing out, so the observer reports nothing), which makes
* pixels-per-millisecond 0.96 and every bar's width a number the test can state outright —
* better than the test a real browser would allow, where it is whatever the window happens to be.
*
* Every assertion about the DOM comes after a `waitFor`, and that is not ceremony: a signal written
* from a test body is committed at the end of the task, so a synchronous read straight after
* `showAudit()` is reading the screen from before the graph was asked to open.
*/
const WIDTH = 960;
/** Chart px per ms of the mark labels' font estimate: the same ruler the component packs with. */
const CHAR_PX = 6.05;
/** The synthetic load is 1000ms on a 960px chart, so this is the scale it draws at. */
const PX = WIDTH / 1000;
let now = 1000;
const advance = (ms: number): void => {
now += ms;
};
/** The modal mounted the way the app mounts it: nothing exists until the audit says to. */
const Host: VoidComponent = () => (
{(audit) => }
);
const bars = () => Array.from(document.querySelectorAll(".ta-bar"));
const rects = () => bars().map((g) => g.querySelector("rect")!);
const lanes = () => rects().map((r) => Number(r.getAttribute("y")));
const widths = () => rects().map((r) => Number(r.getAttribute("width")));
const live = () => document.querySelector(".ta-live")?.textContent ?? "";
const detail = () => document.querySelector(".ta-detail")?.textContent ?? "";
const strip = () => document.querySelector(".ta-foot")?.textContent ?? "";
/** By the span's own name, not by its label: a bar too narrow to print its name still has it. */
const barFor = (name: string): SVGGElement | undefined =>
document.querySelector(`.ta-bar[data-name="${name}"]`) ?? undefined;
const indexOf = (name: string): number => bars().indexOf(barFor(name)!);
const widthOf = (name: string): number => widths()[indexOf(name)]!;
const laneOf = (name: string): number => lanes()[indexOf(name)]!;
/**
* One load, drawn from known instants, and exactly one second long.
*
* The cover is deliberately a *sibling* of the fetch that overlaps it — which is what it is in the
* app, the accent being asked for by an effect that has never heard of the loader — because that is
* the arrangement the lane assignment has to survive.
*/
function synthetic(): LoadAudit {
const audit = beginAudit(
{ id: "s1", title: "Second Scrape", artist: "Autechre", album: "Amber" },
"play",
) as LoadAudit;
mark("s1", "press");
const stream = span("s1", "ask the original", "network");
advance(60);
const asking = stream.child("server response", "network");
advance(440);
asking.close({ status: 200 });
const cover = span("s1", "accent from the cover", "accent");
advance(200);
const body = stream.child("body", "network");
advance(180);
body.close({ bytes: 4182532 });
const pixels = cover.child("cover pixels", "network");
advance(20);
pixels.close({ swatches: 24, size: 300 });
stream.close({ cameFrom: "network" });
advance(10);
cover.close({ accent: "#865b3a" });
const decoding = span("s1", "browser decoder", "decode");
advance(70);
decoding.close({ channels: 2, seconds: 214 });
const folding = span("s1", "waveform fold", "waveform");
advance(20);
folding.close({ slices: 42, reports: 3 });
noteAudit("s1", { container: "flac" });
return audit;
}
/** Open the graph for a timeline and wait for the screen to have caught up with the signal. */
async function shown(audit?: LoadAudit): Promise {
showAudit(audit);
await waitFor(() => expect(document.querySelector(".ta-bar")).not.toBeNull());
}
beforeEach(() => {
now = 1000;
vi.spyOn(performance, "now").mockImplementation(() => now);
setAuditEnabled(true);
clearAudits();
stubResizeObserver();
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
vi.restoreAllMocks();
hideAudit();
clearAudits();
setAuditEnabled(null);
});
it("draws nothing until something asks for the graph", async () => {
synthetic();
const { container } = render(() => );
expect(container.querySelector(".audit-modal")).toBeNull();
await shown();
expect(container.querySelector(".audit-modal")).not.toBeNull();
});
it("draws one bar per span, and the load across the whole axis", async () => {
const audit = synthetic();
render(() => );
const { artifact } = await captureArtifact(async () => {
await shown(audit);
expect(bars()).toHaveLength(audit.raw().length);
// The 440ms wait for the headers is 422px of the picture. The widths are the measurement, so
// this is the assertion the graph exists for: a chart that got the scale wrong passes every
// other test in this file.
expect(widthOf("server response")).toBeCloseTo(440 * PX, 0);
expect(widthOf("body")).toBeCloseTo(180 * PX, 0);
expect(widthOf("browser decoder")).toBeCloseTo(70 * PX, 0);
expect(widthOf("waveform fold")).toBeCloseTo(20 * PX, 0);
});
expectNoDiagnostics(artifact);
});
it("gives two spans that overlap the same moment two lanes", async () => {
const audit = synthetic();
render(() => );
await shown(audit);
// The stream is at the top and its body is under it; the cover runs beside both, so it can share
// neither of their rows — and it is not *inside* either of them, which the flat lanes also say.
expect(laneOf("ask the original")).toBeLessThan(laneOf("body"));
expect(laneOf("accent from the cover")).not.toBe(laneOf("ask the original"));
expect(laneOf("accent from the cover")).not.toBe(laneOf("body"));
expect(new Set(lanes()).size).toBeGreaterThan(2);
});
it("folds a bar too thin to see, and says how much it folded", async () => {
const audit = beginAudit({ id: "s2", title: "Thin" }, "play") as LoadAudit;
const wide = span("s2", "the whole load", "wait");
advance(1000);
// Nine spans of a tenth of a millisecond each: beside a one-second load, on a chart about a
// pixel per millisecond wide, that is a hundredth of a pixel apiece. Not bars, and not drawn as
// bars — the alternative is a graph of the waveform fold that is nine hundred hairlines.
for (let i = 0; i < 9; i++) {
const slice = span("s2", `slice ${i}`, "main", wide);
advance(0.1);
slice.close();
}
advance(2);
wide.close({ slices: 9 });
render(() => );
await shown(audit);
expect(bars()).toHaveLength(1);
expect(document.querySelector(".ta-facts")?.textContent).toContain("folded");
// What left the picture was still work: the totals count the folded spans' own time, so the
// strip says `main 9ms` for ninety percent of the graph that no longer has bars.
expect(strip()).toContain("main");
});
it("draws an open span as far as the load has got, and no further", async () => {
// The axis is rounded up to a step, so an open bar stretched to the axis edge would overstate
// every still-running wait by whatever the rounding added. The frontier is the measurement; the
// axis is only the paper.
const audit = beginAudit({ id: "s4", title: "Growing" }, "play") as LoadAudit;
span("s4", "server response", "network");
advance(500);
span("s4", "waveform fold", "waveform").close(); // a version bump: the graph re-asks how far it is
advance(1600);
span("s4", "loop & tempo detection", "analysis").close(); // ...and the frontier is 2100ms now
render(() => );
await shown(audit);
// The load reached 2100ms and the axis snaps to 2500 — a fifth of the chart is rounding. The open
// bar ends at the load's own frontier, not at the ruler's edge, which is the difference between
// 806px and a wait that claims to have filled the whole picture.
expect(widthOf("server response")).toBeCloseTo(2100 * (WIDTH / 2500), 0);
});
it("names what is still running, and lets the axis grow for it", async () => {
const audit = beginAudit({ id: "s3", title: "Hanging" }, "play") as LoadAudit;
span("s3", "server response", "network");
advance(500);
render(() => );
await shown(audit);
expect(live()).toContain("server response");
// An open span is drawn as far as the load has reached, rather than not at all.
expect(widths()[0]!).toBeGreaterThan(300);
});
it("clicking a bar zooms the axis onto it, and z gives the whole load back", async () => {
const audit = synthetic();
render(() => );
await shown(audit);
const whole = widths();
const target = () => barFor("browser decoder")!;
const before = widthOf("browser decoder");
fireEvent.click(target());
// Seventy milliseconds of decode inside a window of about eighty-four: the same bar most of the
// way across the chart, everything else off the ends of it.
await waitFor(() => expect(widthOf("browser decoder")).toBeGreaterThan(before * 4));
// The fetch is off the end of a window that starts at 903ms: the graph drops what it cannot
// draw rather than drawing it squashed against the edge.
expect(barFor("server response")).toBeUndefined();
expect(document.querySelector(".ta-zoom")).not.toBeNull();
fireEvent.keyDown(window, { key: "z" });
await waitFor(() => expect(widths()).toEqual(whole));
});
it("redraws the bars on a zoom instead of rebuilding them", async () => {
// A relayout moves every bar, so this is where a chart rebuilds itself if it is going to: the
// bars must survive the zoom with their DOM intact (the `UNSTABLE_LIST_IDENTITY` diagnostic is
// what a fresh `Row` per span used to raise here).
const audit = synthetic();
render(() => );
await shown(audit);
const before = bars().map((g) => g.querySelector("rect"));
fireEvent.click(barFor("browser decoder")!);
await waitFor(() => expect(widthOf("browser decoder")).toBeGreaterThan(200));
const kept = before.filter((r) => r && document.contains(r));
expect(kept.length).toBeGreaterThan(2);
});
it("does not redraw the graph for a hover", async () => {
// The readout follows the pointer, and the readout is one small subtree. If hovering moved the
// axis — or rebuilt the chart — the overlay would be animating under the mouse all evening.
const audit = synthetic();
render(() => );
await shown(audit);
const rects = bars().map((g) => g.querySelector("rect")!);
const geometry = rects.map((r) => `${r.getAttribute("x")}:${r.getAttribute("width")}`);
fireEvent.mouseEnter(barFor("body")!);
await waitFor(() => expect(detail()).toContain("bytes"));
expect(
bars().map((g) => {
const r = g.querySelector("rect")!;
return `${r.getAttribute("x")}:${r.getAttribute("width")}`;
}),
).toEqual(geometry);
});
it("reads out the span the pointer is on, with the numbers beside it", async () => {
const audit = synthetic();
render(() => );
await shown(audit);
const target = barFor("body")!;
fireEvent.mouseEnter(target);
await waitFor(() => expect(detail()).toContain("bytes"));
expect(detail()).toContain("network");
expect(detail()).toContain("4182532");
fireEvent.mouseLeave(target);
await waitFor(() => expect(detail()).toContain("click a bar"));
});
it("totals each kind of wait by the time that was on its own", async () => {
const audit = synthetic();
render(() => );
await shown(audit);
expect(strip()).toContain("network");
expect(strip()).toContain("decode");
expect(strip()).toContain("waveform");
// `meta()` belongs to the load rather than to one span, so it is shown beside the totals: which
// container the bytes came in is the first thing anybody asks about a slow load.
expect(strip()).toContain("container");
});
it("walks the recorded loads with the arrows, and closes with escape", async () => {
const first = synthetic();
advance(10);
const second = beginAudit({ id: "s9", title: "Second Hand" }, "prefetch") as LoadAudit;
const warm = span("s9", "bytes from memory", "disk");
advance(4);
warm.close({ bytes: 8_000_000 });
render(() => );
await shown(second);
// `←` is the earlier load and `→` the later one, on the timeline rather than in the list the
// timelines happen to be kept in — which is newest-first, so the two are opposite, and the graph
// is not the place to make a reader work that out.
expect(document.querySelector(".ta-title")?.textContent).toBe("Second Hand");
fireEvent.keyDown(window, { key: "ArrowLeft" });
await waitFor(() =>
expect(document.querySelector(".ta-title")?.textContent).toBe("Second Scrape"),
);
expect(auditModal()?.seq).toBe(first.seq);
fireEvent.keyDown(window, { key: "ArrowRight" });
await waitFor(() => expect(document.querySelector(".ta-title")?.textContent).toBe("Second Hand"));
expect(auditModal()?.seq).toBe(second.seq);
fireEvent.keyDown(window, { key: "Escape" });
await waitFor(() => expect(document.querySelector(".audit-modal")).toBeNull());
});
it("takes the keyboard while it is up, and hands back the keys it does not use", async () => {
synthetic();
render(() => );
await shown();
// The library view binds `j`/`k`/`g` on the window in the *bubble* phase, and a capture listener
// on the same target runs first — which is how a key the graph uses cannot also move a cursor
// behind it. The proof is a bubble listener of our own: it must fire for the keys the graph
// declines, or the overlay has eaten the transport.
const seen: string[] = [];
const spy = (e: Event) => seen.push((e as KeyboardEvent).key);
window.addEventListener("keydown", spy);
fireEvent.keyDown(window, { key: "ArrowLeft" });
fireEvent.keyDown(window, { key: "Escape" });
fireEvent.keyDown(window, { key: "j" });
window.removeEventListener("keydown", spy);
expect(seen).toEqual(["j"]);
});
/** The label boxes as the packing left them: where they are drawn, and how far they reach. */
const markLabels = () =>
[...document.querySelectorAll(".ta-mark text")].map((t) => ({
name: t.textContent ?? "",
x: Number(t.getAttribute("x")),
y: Number(t.getAttribute("y")),
right: Number(t.getAttribute("x")) + (t.textContent ?? "").length * CHAR_PX,
}));
it("stacks mark labels that would otherwise be drawn on top of each other", async () => {
// The everyday case, not a corner: on a real load the press and the moment the bytes were asked
// for are one millisecond apart, so their labels land on the same pixels. Overstruck letters look
// like a bug in the drawing, and are worse than no labels at all.
const audit = beginAudit({ id: "s5", title: "Marks" }, "play") as LoadAudit;
mark("s5", "press");
advance(1);
mark("s5", "bytes asked for");
advance(1);
mark("s5", "first sample");
const first = span("s5", "server response", "network");
advance(428);
first.close({ status: 200 });
mark("s5", "accent worn"); // ...and one with the whole right hand of the chart to itself
render(() => );
await shown(audit);
const labels = markLabels();
expect(labels).toHaveLength(4);
// Three moments one millisecond apart, three rows: a stack rather than a smear. The fourth lands
// where there is room, back on the first row — the packing is by collision, not by count.
expect(new Set(labels.map((l) => l.y)).size).toBe(3);
const crowded = labels.filter((l) => l.name !== "accent worn");
expect(new Set(crowded.map((l) => l.y)).size).toBe(3);
expect(labels.find((l) => l.name === "accent worn")!.y).toBe(Math.min(...labels.map((l) => l.y)));
// The rule, stated where it belongs: labels that *do* share a row never overlap. Rows are handed
// out by collision, not by count, so marks far apart still sit together on the first row.
const rows = new Map();
for (const l of labels) rows.set(l.y, [...(rows.get(l.y) ?? []), l]);
for (const row of rows.values()) {
const by = [...row].sort((a, b) => a.x - b.x);
for (let i = 1; i < by.length; i++) expect(by[i]!.x).toBeGreaterThanOrEqual(by[i - 1]!.right);
}
// …and they are in the band under the lanes, because a caption drawn over the bars it captions is
// how the labels came to be unreadable in the first place.
const barsBottom = Math.max(
...rects().map((r) => Number(r.getAttribute("y")) + Number(r.getAttribute("height"))),
);
expect(Math.min(...labels.map((l) => l.y))).toBeGreaterThan(barsBottom);
});
it("keeps a mark's label inside the chart, and its line where the moment was", async () => {
// Near the right edge there is no room for a label to the right of its line. The label gives way;
// the line never does — the position is the measurement, the text is only its caption.
const audit = beginAudit({ id: "s6", title: "Edge" }, "play") as LoadAudit;
const fetch = span("s6", "ask the original", "network");
advance(995);
mark("s6", "accent worn");
advance(5);
fetch.close({ status: 200 });
render(() => );
await shown(audit);
const g = document.querySelector(".ta-mark[data-name='accent worn']")!;
const line = Number(g.querySelector("line")!.getAttribute("x1"));
const label = Number(g.querySelector("text")!.getAttribute("x"));
expect(line).toBeCloseTo(995 * PX, 0); // 955px: where the moment actually is
expect(label).toBeLessThan(line); // pushed back inside
expect(label + "accent worn".length * CHAR_PX).toBeLessThanOrEqual(WIDTH + 1);
});
it("repacks the mark labels when the axis changes", async () => {
// The packing is a fact about the axis, not about the load: the same two moments crowd at one
// scale and separate at another, and a label that had to queue would look stranded if it stayed
// queued after a zoom gave it the room it needed.
const audit = beginAudit({ id: "s7", title: "Rescaled" }, "play") as LoadAudit;
mark("s7", "press");
const waiting = span("s7", "wait for the bytes", "wait");
advance(40);
mark("s7", "bytes asked for");
advance(140);
const decoding = span("s7", "browser decoder", "decode");
advance(80);
decoding.close({ channels: 2 });
waiting.close({ cameFrom: "network" });
advance(4740);
span("s7", "waveform fold", "waveform").close({ slices: 4 }); // ...and the load is 5s, so 40ms is a tenth of a pixel apart
render(() => );
await shown(audit);
const rows = () =>
new Set([...document.querySelectorAll(".ta-mark text")].map((t) => t.getAttribute("y"))).size;
expect(rows()).toBe(2);
fireEvent.click(barFor("wait for the bytes")!);
await waitFor(() => expect(widthOf("wait for the bytes")).toBeGreaterThan(400));
await waitFor(() => expect(rows()).toBe(1));
});
it("marks the moments that have a time and no duration", async () => {
const audit = synthetic();
render(() => );
await shown(audit);
expect(document.querySelectorAll(".ta-mark").length).toBe(1);
expect(document.querySelector(".ta-mark text")?.textContent).toBe("press");
});
it("lists every recorded load, and shows which one is being drawn", async () => {
synthetic();
advance(10);
beginAudit({ id: "s8", title: "Amber" }, "prefetch");
const chip = span("s8", "bytes from memory", "disk");
advance(3);
chip.close({ bytes: 1024 });
render(() => );
await shown();
expect(document.querySelectorAll(".ta-load").length).toBe(2);
expect(document.querySelector(".ta-load[data-current='true'] .ta-load-name")?.textContent).toBe(
"Amber",
);
});
// ---------------------------------------------------------------------------------------------
// End to end: a real press, through the real load path, into the graph.
//
// Everything above hands the component spans it is told to draw. This plays a track the way the app
// plays one and asks whether the picture the instrumentation produced describes the load that
// actually happened — the only way to notice that a span was wired to the wrong track, or that the
// load path never reached the code being measured at all.
// ---------------------------------------------------------------------------------------------
const songs: FakeMediaFile[] = mediaFiles(
{ album: "Heavy Loop", albumArtist: "Autechre", albumId: "al-1" },
2,
);
const trackRows = () => [...document.querySelectorAll(".lib-scroll .lib-row--track")];
async function bootConnected() {
const index = navidromeFetch(songs);
const stream: StreamFetchStub = stubStreamFetch({ base: index });
vi.stubGlobal("fetch", stream.fetch);
vi.stubGlobal("AudioContext", FakeAudioContext);
saveConnection({ host: "https://nav.example.com", username: "admin", password: "wordpass" });
render(() => );
await waitFor(() => expect(library().status()).toBe("ready"), { timeout: 3000 });
await waitFor(() => expect(trackRows().length).toBeGreaterThan(0));
}
/**
* Open the command line, type a verb, and read the line it leaves beside the prompt.
*
* The `:` is pressed rather than typed: it is the key that *arms* command mode, and the field's
* value is the rest — feeding it the whole string would be asking the parser to dispatch a verb
* called `:timeaudit`, which is a fair way to fail to notice that the verb is not registered.
*/
async function runCommand(verb: string): Promise {
if (!document.querySelector(".cmd-line[data-mode='command']"))
fireEvent.keyDown(window, { key: ":" });
const field = document.querySelector(".lib-query-input")!;
fireEvent.input(field, { target: { value: verb.replace(/^:/, "") } });
fireEvent.keyDown(field, { key: "Enter" });
await waitFor(() => expect(document.querySelector(".lib-query-count")?.textContent).toBeTruthy());
return document.querySelector(".lib-query-count")?.textContent ?? "";
}
it("draws the load a real press caused", async () => {
localStorage.clear();
clearConnection();
library().reset();
player().stop();
forgetMediaVerdicts();
const { artifact } = await captureArtifact(async () => {
await bootConnected();
// The row's own click, not a call into the store: the press is what the timeline is measured
// from, and a test that entered through the back door would not prove the audit begins where
// the listener's hand does.
// A real clock for a real load: the stubbed one from `beforeEach` is frozen, and a load
// measured against a clock that does not move is a picture in which every bar is zero wide.
vi.restoreAllMocks();
fireEvent.click(trackRows()[0]!);
await waitFor(() => expect(player().peekState()).toBe("playing"), { timeout: 3000 });
render(() => );
await shown(latestAudit("al-1-s0") ?? undefined);
});
const audit = auditModal();
expect(audit?.trackId).toBe("al-1-s0");
expect(audit?.reason).toBe("play");
const names = (audit?.raw() ?? []).map((s) => s.name);
// The three things the graph exists to keep apart: the request, the codec, and the wait that
// covers the whole arrival — plus the press, which is a mark and not a bar.
expect(names).toContain("server response");
expect(names).toContain("browser decoder");
expect(names.some((n) => n.startsWith("wait for the bytes"))).toBe(true);
expect(audit?.marks().map((m) => m.name)).toContain("press");
expect(document.querySelector(".ta-title")?.textContent).toBe("Track 1");
// At least the request, the decode and the wait, drawn at their real widths: what the whole load
// took here is a few milliseconds of jsdom, so some of the fifteen spans are legitimately too
// thin to be bars — which the header says out loud rather than hiding.
expect(bars().length).toBeGreaterThanOrEqual(3);
expect(names.length).toBeGreaterThanOrEqual(8);
expectNoDiagnostics(artifact);
});
it("answers `:timeaudit` with the track on the bar, not the newest timeline", async () => {
// Which is the same thing as: not the prefetch of the *next* track, which is always the newest
// timeline there is. A verb that opened the newest would answer a question nobody asked, and
// would look exactly like the one that answers the right one.
localStorage.clear();
clearConnection();
library().reset();
player().stop();
forgetMediaVerdicts();
const { artifact } = await captureArtifact(async () => {
await bootConnected();
vi.restoreAllMocks();
fireEvent.click(trackRows()[0]!);
await waitFor(() => expect(player().peekState()).toBe("playing"), { timeout: 3000 });
const played = latestAudit("al-1-s0") as LoadAudit;
// The warmer getting ahead of the clock, which is what makes this a real ordering problem.
beginAudit({ id: "al-1-s1", title: "Track 2" }, "prefetch");
const line = await runCommand(":timeaudit");
expect(line).toContain("Track 1");
expect(auditModal()?.seq).toBe(played.seq);
expect(await runCommand(":timeaudit 40")).toContain("recorded");
});
expectNoDiagnostics(artifact);
});