Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342/** * The beat model's seam: what the store is promised, and what it gets when the promise cannot * be kept. * * The contract under test is mostly about *not* answering: `track` resolves — always, with a * grid or with `null` — because every failure this feature can hit (no worker, a fetch that * 404s, a runtime the browser refused, an inference that is still thinking three songs later) * has the same correct outcome: ask the dynamic program. A rejection escaping here would be a * bug even where it is handled, because it would mean the store had to learn a distinction the * analyzer is deliberately kept unable to make. */import { beforeEach, describe, expect, it, vi } from "vitest";
import { createBeatModel, type BeatModelReport, type BeatModelWorkerLike } from "./beatmodel";import type { AudioBufferLike } from "./engine";import type { NeuralGrid } from "./beattrack";
/** The one question's worth of audio the client is allowed to see. */function buffer(seconds = 60, sampleRate = 44100): AudioBufferLike { const data = new Float32Array(Math.round(seconds * sampleRate)); for (let i = 0; i < data.length; i++) data[i] = Math.sin(i * 0.01); return { sampleRate, numberOfChannels: 1, length: data.length, duration: seconds, getChannelData: () => data, } as unknown as AudioBufferLike;}
class FakeModelWorker implements BeatModelWorkerLike { requests: Record<string, unknown>[] = []; transfers: Transferable[][] = []; auto = false; onmessage: | ((event: { data?: { token: number; grid: NeuralGrid | null; error?: string } }) => void) | null = null; onerror: ((event: unknown) => void) | null = null; terminated = false;
/** the page saying who it is waiting for — not a question, and not a request */ readonly priorities: string[][] = []; postMessage(message: unknown, transfer?: Transferable[]): void { if (message && typeof message === "object" && "priority" in message) { this.priorities.push((message as { priority: string[] }).priority); return; } this.requests.push(message as Record<string, unknown>); this.transfers.push(transfer ?? []); if (this.auto) this.replyLast({ token: this.requests.length, grid: null }); } replyLast(reply: { token: number; grid: NeuralGrid | null; error?: string; busy?: boolean; dropped?: boolean; phases?: unknown[]; runtime?: Record<string, unknown>; }): void { this.onmessage?.({ data: reply }); } die(): void { this.onerror?.({}); } terminate(): void { this.terminated = true; }}
const GRID: NeuralGrid = { beats: Float32Array.from({ length: 100 }, (_, i) => i * 0.5), downbeats: Float32Array.from({ length: 25 }, (_, i) => i * 2), bpm: 120, beatAt: 0, strength: 0.95,};
describe("the beat model seam", () => { let worker: FakeModelWorker; beforeEach(() => { worker = new FakeModelWorker(); }); const model = (over = {}) => createBeatModel({ createWorker: () => worker, timeoutMs: 50, ...over });
it("hands the grid back from the worker's answer", async () => { const pending = model().track(buffer()); expect(worker.requests).toHaveLength(1); const request = worker.requests[0]!; expect(request.modelUrl).toContain("beat-this-small0.onnx"); expect(request.melUrl).toContain("mel-filterbank.f32"); expect(request.sampleRate).toBe(44100); worker.replyLast({ token: request.token as number, grid: GRID }); expect(await pending).toEqual(GRID); });
it("transfers the samples rather than copying them", async () => { const pending = model().track(buffer()); const request = worker.requests[0]!; // The array that crosses is the one that detaches: a forty-seven-megabyte // structured-clone copy per track would tax the main thread the worker exists to spare. expect(worker.transfers[0]![0]).toBe((request.samples as Float32Array).buffer); expect((request.samples as Float32Array).byteLength).toBe(60 * 44100 * 4); worker.replyLast({ token: request.token as number, grid: null }); expect(await pending).toBeNull(); });
it("answers null — never a rejection — when there is no worker to ask", async () => { const silent = createBeatModel({ createWorker: () => null }); expect(await silent.track(buffer())).toBeNull(); });
it("hands back the bill for the wait, once, before the answer", async () => { // The grid is the answer; this is the reason the wait was long. It has to arrive with the // answer rather than after it, because the caller closes its bar on the strength of it. const bills: unknown[] = []; const pending = model().track(buffer(), (b) => bills.push(b)); const request = worker.requests[0]!; worker.replyLast({ token: request.token as number, grid: GRID, phases: [ { name: "load the runtime", from: 0, ms: 6 }, { name: "fetch the weights", from: 6, ms: 1400, detail: { mb: 11 } }, { name: "infer window", from: 2000, ms: 2400, detail: { window: "1/9" } }, ], runtime: { gpu: true, isolated: false, threads: 1, refused: "webgpu: backend not found" }, }); expect(await pending).toEqual(GRID); expect(bills).toHaveLength(1); expect(bills[0]).toMatchObject({ outcome: "answered", runtime: { refused: "webgpu: backend not found" }, }); const phases = (bills[0] as { phases: { name: string; ms: number }[] }).phases; expect(phases.map((p) => p.name)).toEqual([ "load the runtime", "fetch the weights", "infer window", ]); });
it("passes the page's name for the track down, and its preferences across", async () => { // The thread holds samples, not songs. Everything it knows about which question matters arrives // in these two places: the name on the request, and the list it is told afterwards. const m = model(); const asked = m.track(buffer(60, 8000), undefined, { key: "s1" }); expect(worker.requests[0]!.key).toBe("s1"); m.priority?.(["s1", "s2"]); expect(worker.priorities).toEqual([["s1", "s2"]]); worker.replyLast({ token: 1, grid: GRID }); expect(await asked).toEqual(GRID); // A name is optional, because not every caller has one to give. const anonymous = m.track(buffer(60, 8000)); expect(worker.requests[1]!.key).toBe(""); worker.replyLast({ token: 2, grid: null }); expect(await anonymous).toBeNull(); });
it("says what finished the model, instead of blaming the browser", async () => { // Two failures in a row do retire the thread, and deliberately: a browser whose runtime cannot // work should not pay ten seconds a track for the rest of the page. But `unavailable` on its own // reads as a verdict about the device, and it used to print "this browser cannot run the model" // for a browser that had answered in 6.2 s an hour earlier — because what fired was this page's // own two strikes. The bar is allowed to say the feature is gone; it has to say which thing is // gone, and that a reload brings it back. const m = model(); for (let i = 0; i < 2; i++) { const asked = m.track(buffer(60, 8000)); worker.replyLast({ token: worker.requests.length, grid: null, error: "WebGPU device lost" }); await asked; } expect(worker.terminated).toBe(true);
const bills: BeatModelReport[] = []; expect(await m.track(buffer(), (b) => bills.push(b))).toBeNull(); expect(bills[0]!.outcome).toBe("unavailable"); expect(bills[0]!.error).toContain("WebGPU device lost"); // what actually finished it expect(bills[0]!.error).toContain("reload"); // and what undoes it });
it("treats an answer nobody waited for as a refusal, not a strike", async () => { // The listener skipped past and the page said so; the thread stopped at a window boundary. That // is the queue working, and a model retired because two tracks got skipped would be a model // switched off by ordinary traffic — the same mistake `busy` exists to avoid. const m = model(); const bills: string[] = []; for (const key of ["s1", "s2", "s3"]) { const asked = m.track(buffer(60, 8000), (bill) => bills.push(bill.outcome), { key }); worker.replyLast({ token: worker.requests.length, grid: null, dropped: true }); expect(await asked).toBeNull(); } expect(bills).toEqual(["dropped", "dropped", "dropped"]); expect(worker.terminated).toBe(false); // still here, still asking const alive = m.track(buffer(60, 8000)); worker.replyLast({ token: worker.requests.length, grid: GRID }); expect(await alive).toEqual(GRID); });
it("asks the model about three minutes of a long track, not the whole of it", async () => { // Where a five-minute track's wait actually goes, per a real device: 44% of it was resampling // and the log-mel — arithmetic that scales with the length of the track and wants no GPU at all — // against 190ms for each inference window. A period and a phase are settled by three minutes of a // steady track, and the dynamic program still scores the whole of it. The cap goes on the channels // before the fold, so the fold does not pay for audio nobody will look at. const m = model(); const long = m.track(buffer(400.47, 8000)); const request = worker.requests[0]!; expect(request.sampleRate).toBe(8000); expect((request.samples as Float32Array).length).toBe(180 * 8000); expect(request.trackSeconds).toBe(400); // what the track is, beside what was sent, in whole seconds worker.replyLast({ token: 1, grid: GRID }); expect(await long).toEqual(GRID);
// A track shorter than the cap is not a track that got truncated — the common case, and the one // a reader of the graph would otherwise be told about by a `of=` they cannot interpret. const short = m.track(buffer(60, 8000)); const second = worker.requests[1]!; expect((second.samples as Float32Array).length).toBe(60 * 8000); expect(second.trackSeconds).toBe(60); worker.replyLast({ token: 2, grid: GRID }); expect(await short).toEqual(GRID); });
it("treats a busy thread as a refusal, not a failure", async () => { // Two loads a second apart is ordinary listening, and the second one used to die on the runtime's // concurrent-run guard. Now it is told the model is occupied — and that must not count against the // two strikes that retire the model, or a listener who queues three songs would lose the feature. const bills: unknown[] = []; const m = model(); const busy = m.track(buffer(), (b) => bills.push(b)); worker.replyLast({ token: 1, grid: null, busy: true, phases: [{ name: "queue for the model", from: 0, ms: 50 }], }); expect(await busy).toBeNull(); expect(bills[0]).toMatchObject({ outcome: "busy", phases: [{ name: "queue for the model" }] }); const next = m.track(buffer(), (b) => bills.push(b)); // the model is very much still in service worker.replyLast({ token: 2, grid: GRID }); expect(await next).toEqual(GRID); expect(bills[1]).toMatchObject({ outcome: "answered" }); });
it("remembers the runtime for the answer that never comes", async () => { // A timeout is the report that most needs to say what the device was running on, and the only // place that fact was ever stated is the answer of an *earlier* track — the same session, so the // same truth. A report with no runtime here is a report that cannot explain itself. const bills: unknown[] = []; const m = model(); const first = m.track(buffer(), (b) => bills.push(b)); worker.replyLast({ token: 1, grid: GRID, runtime: { gpu: false, isolated: false, threads: 1, refused: "webgpu: backend not found" }, }); expect(await first).toEqual(GRID); const second = m.track(buffer(), (b) => bills.push(b)); expect(await second).toBeNull(); // the 50ms wait ran out with nothing on the other side expect(bills[1]).toMatchObject({ outcome: "timed out", runtime: { refused: "webgpu: backend not found" }, }); });
it("still sends the bill when the answer never comes", async () => { // The timeout is exactly when the caller most needs to close its bar and be told why — and // when a slow device stops being a theory: the phases that did arrive say how far it got. const bills: unknown[] = []; const pending = model({ timeoutMs: 20 }).track(buffer(), (b) => bills.push(b)); expect(await pending).toBeNull(); expect(bills).toMatchObject([{ outcome: "timed out", phases: [] }]); });
it("sends a bill for a failure too, with the phases that led to it", async () => { const bills: unknown[] = []; const pending = model().track(buffer(), (b) => bills.push(b)); worker.replyLast({ token: 1, grid: null, error: "wasm refused", phases: [{ name: "optimise + instantiate", from: 100, ms: 300 }], }); expect(await pending).toBeNull(); expect(bills[0]).toMatchObject({ outcome: "failed", error: "wasm refused" }); expect((bills[0] as { phases: unknown[] }).phases).toHaveLength(1); });
it("closes every open bill when the thread is retired", async () => { const bills: unknown[] = []; const pending = model().track(buffer(), (b) => bills.push(b)); worker.die(); // no answer, ever: the bar must still come down expect(await pending).toBeNull(); expect(bills).toMatchObject([{ outcome: "retired" }]); });
it("asks nothing of a caller that does not want the bill", async () => { const pending = model().track(buffer()); worker.replyLast({ token: 1, grid: GRID }); expect(await pending).toEqual(GRID); // the seam worked before this channel existed, and still does });
it("stops asking after the worker fails twice", async () => { const m = model(); const a = m.track(buffer()); worker.replyLast({ token: 1, grid: null, error: "wasm refused" }); expect(await a).toBeNull(); const b = m.track(buffer()); worker.die(); // the second strike retires the worker for the session expect(await b).toBeNull(); const before = worker.requests.length; expect(await m.track(buffer())).toBeNull(); expect(worker.requests.length).toBe(before); // no third question was even asked expect(worker.terminated).toBe(true); });
it("gives up on an answer that is still thinking next song", async () => { const pending = model({ timeoutMs: 20 }).track(buffer()); await vi.waitFor(async () => { expect(await pending).toBeNull(); }); // ...and the late reply, when it finally arrives, goes to nobody without complaint. expect(() => worker.replyLast({ token: 1, grid: GRID })).not.toThrow(); });
it("counts a success after failures and keeps the worker", async () => { const m = model(); const a = m.track(buffer()); worker.replyLast({ token: 1, grid: null, error: "one bad day" }); expect(await a).toBeNull(); const b = m.track(buffer()); worker.replyLast({ token: 2, grid: GRID }); expect(await b).toEqual(GRID); const c = m.track(buffer()); expect(worker.requests).toHaveLength(3); // still in conversation worker.replyLast({ token: 3, grid: GRID }); expect(await c).toEqual(GRID); });});