Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321import { expect, it, vi } from "vitest";import { readFileSync } from "node:fs";
import { LogMel, splitStarts } from "./beattrack";import { answer, DROPPED, modelTurn, trackWith, verdictOf, type BeatModelPhase, type BeatTrackRequest, type Runner,} from "./beatmodel.worker";
/** * The beat thread's own accounting. * * `beatmodel.test.ts` is about the seam — what the store is promised when the model cannot answer. * This is about the other half of why the model exists as a separate module at all: the wait for a * grid is the longest bar in a load, and until it can say *what* it waited for — a runtime import, * eleven megabytes, a graph optimisation, or nine windows of arithmetic that every track pays — "the * detector is slow" is a guess rather than a finding. * * The runtime here is a stub that takes a measurable time, because the promise under test is the * bookkeeping, not the arithmetic: the real ONNX is `beattrack.test.ts`'s, and its numbers are that * file's to assert. */
const melMatrix = new Float32Array( readFileSync(`${process.cwd()}/public/models/mel-filterbank.f32`).buffer.slice(0),);
/** A track long enough to have a tempo (two seconds is the floor) and short enough to be one window. */function audio(seconds: number, sampleRate = 44100): Float32Array { const n = Math.round(seconds * sampleRate); const x = new Float32Array(n); const period = (60 / 120) * sampleRate; for (let i = 0; i < n; i++) { const p = i % period; x[i] = p < 0.01 * sampleRate ? Math.sin((2 * Math.PI * 900 * p) / sampleRate) : 0; } return x;}
/** * A session that spends a known few milliseconds per window and answers with a pulse. * * The activations are a spike train rather than noise on purpose: the pipeline's own answer is * `null` when it cannot find eight beats in what it is handed ("two bars of pulse before a grid is * a grid"), and a stub that never gets that far would be testing the timing code's arithmetic * without ever running the pipeline the timings are taken around. */function slowRunner(delayMs: number, every = 20): Runner { return { async run() { const until = performance.now() + delayMs; while (performance.now() < until) await new Promise((r) => setTimeout(r, 0)); const beat = new Float32Array(1500).fill(-10); for (let i = 0; i < beat.length; i += every) beat[i] = 4; const downbeat = new Float32Array(1500).fill(-10); return { beat: { data: beat }, downbeat: { data: downbeat } }; }, tensor: (data: Float32Array, dims: number[]) => ({ data, dims }), };}
const names = (phases: BeatModelPhase[]) => phases.map((p) => p.name);
it("says what the wait was made of, in the order it happened", async () => { const phases: BeatModelPhase[] = []; const grid = await trackWith(slowRunner(8), melMatrix, audio(4), 44100, phases, 0); expect(grid).not.toBeNull(); // Every stage of the pipeline, named: what a reader needs in order to say "that one is the // problem" without reading this file. expect(names(phases)).toEqual(["resample", "log-mel", "infer window", "aggregate + snap"]); // Sequential work laid out in the order it ran, from the arrival of the request — which is all // the caller has to go on, and enough to place each one inside its own wait. for (let i = 1; i < phases.length; i++) expect(phases[i]!.from).toBeGreaterThanOrEqual(phases[i - 1]!.from); // Measured, not asserted away: a phase that reports zero for a runner that was made to sleep is // a phase that is not timing anything. expect(phases.find((p) => p.name === "infer window")!.ms).toBeGreaterThanOrEqual(6);});
it("names each window of the arithmetic, and how many there were", async () => { // Nine of these at two seconds apiece is the twenty seconds people mean when they say the // detector is slow. One bar for all nine is exactly why nobody could show them that. const phases: BeatModelPhase[] = []; const long = audio(4); const frames = new LogMel(melMatrix).frames(Math.round(4 * 22050)); await trackWith(slowRunner(0), melMatrix, long, 44100, phases, 0); const windows = phases.filter((p) => p.name === "infer window"); expect(windows).toHaveLength(splitStarts(frames).length); expect(windows.map((w) => w.detail?.window)).toEqual( windows.map((_, i) => `${i + 1}/${windows.length}`), );});
it("still accounts for a track too short to have a tempo", async () => { // A refusal is an answer, and it still cost the resample and the spectrogram that found out. const phases: BeatModelPhase[] = []; // Half a second: 26 frames, under the fifty the pipeline needs before it will claim a tempo. expect(await trackWith(slowRunner(0), melMatrix, audio(0.5), 44100, phases, 0)).toBeNull(); expect(names(phases)).toEqual(["resample", "log-mel"]);});
it("hands the session to one run at a time", async () => { // The regression, named by the error it prevents: the wasm runtime keeps one in-flight run per // session and throws `Session already started` at the second `run()`. Play a track and the prefetch // of the next one arrives a second later, so the second track used to die on that guard while the // dynamic program answered anyway — a failure with nothing to show for it but a bar. expect(await modelTurn.acquire("", 1000)).toBe(0); // the session was free: no wait at all let second: number | "waiting" = "waiting"; const secondTurn = modelTurn.acquire("", 1000).then((ms) => (second = ms)); await Promise.resolve(); expect(second).toBe("waiting"); // it cannot have the session while the first holds it expect(modelTurn.queued()).toBe(1); modelTurn.release(); const waited = await secondTurn; expect(waited).toBeGreaterThanOrEqual(0); // and it is told how long it stood there expect(modelTurn.queued()).toBe(0); modelTurn.release();});
it("lets a run waiting behind another track give up", async () => { // Bounded so that a stuck session cannot hold a track forever — but per *run*, which is ~190ms of // real work, so the bound only catches something genuinely wedged rather than merely busy. That is // the whole difference from the first version of this, whose per-track bound refused a prefetched // track a second of work it was perfectly able to do. expect(await modelTurn.acquire("", 1000)).toBe(0); expect(await modelTurn.acquire("", 5)).toBe(-1); // gave up expect(modelTurn.queued()).toBe(0); // and left the queue rather than lurking in it modelTurn.release(); expect(await modelTurn.acquire("", 5)).toBe(0); // handed out again, unharmed modelTurn.release();});
it("gives the turn to whoever asked first", async () => { const order: string[] = []; expect(await modelTurn.acquire("", 1000)).toBe(0); const b = modelTurn.acquire("", 1000).then(() => order.push("b")); await Promise.resolve(); const c = modelTurn.acquire("", 1000).then(() => order.push("c")); await Promise.resolve(); expect(modelTurn.queued()).toBe(2); modelTurn.release(); modelTurn.release(); await Promise.all([b, c]); expect(order).toEqual(["b", "c"]); modelTurn.release();});
it("says how much of the track it was handed, and how long the track was", async () => { // The caller caps what the model is asked about, and a bar reading `seconds=180` under a // five-minute track looks like a bug unless the other number travels with it. const phases: BeatModelPhase[] = []; await trackWith(slowRunner(1), melMatrix, audio(4), 44100, phases, 0, 338); const resample = phases.find((p) => p.name === "resample")!; expect(resample.detail).toEqual({ seconds: 4, of: 338 });});
it("serves the track being heard before the one merely coming up", async () => { // Six loads in fifteen seconds is what moving through a library looks like, and every one of // them asked the model. Per-run turns made that fair, and fairness is the wrong rule: a report // had the track the listener was *hearing* wait 1.4–2.5 s per window behind four prefetches, its // grid landing at 17 s. The thread holds samples, not songs — the page has to say which one is // playing, and this is where that order is kept. modelTurn.prioritize(["now", "next"]); try { expect(await modelTurn.acquire("next", 1000)).toBe(0); // the session was free const served: string[] = []; const n = modelTurn.acquire("next", 1000).then((ms) => served.push(`next=${ms}`)); await Promise.resolve(); const w = modelTurn.acquire("now", 1000).then((ms) => served.push(`now=${ms}`)); await Promise.resolve(); expect(modelTurn.queued()).toBe(2); // A track that is not on the list does not queue at all: it is refused where it stands. expect(await modelTurn.acquire("skipped-past", 1000)).toBe(DROPPED); expect(modelTurn.queued()).toBe(2); modelTurn.release(); modelTurn.release(); modelTurn.release(); await Promise.all([n, w]); // Order is the assertion; the milliseconds each stood there are the caller's own business. expect(served.map((entry) => entry.split("=")[0])).toEqual(["now", "next"]); } finally { modelTurn.prioritize(null); modelTurn.release(); // whoever holds it at the end of this test, hand it back }});
it("stops working on a track the page stopped waiting for", async () => { // The other half of the same message: what is not named is not slow, it is unwanted, and it stops // at the next boundary instead of spending seven windows on an answer that will land for a track // nobody is looking at. `dropped` is not a failure, and not a strike against the model. modelTurn.prioritize(["now"]); try { expect(await modelTurn.acquire("now", 1000)).toBe(0); const dropped = await modelTurn.acquire("skipped-past", 1000); expect(dropped).toBe(DROPPED); // refused at once: no waiting for a budget to run out expect(modelTurn.queued()).toBe(0); modelTurn.release(); } finally { modelTurn.prioritize(null); }});
it("reports a track the listener skipped as a drop, not as a broken model", async () => { // The other half of the two tests above, and the half that was missing. The thread throws // `ModelDropped` when the page stops wanting an answer; what goes back has to say *dropped*, // because the page counts an `error` reply toward the two strikes that retire the model — and // retired it, in the field, over two skipped tracks, on a browser that had produced a grid in // 6.2 s the day before. `beatmodel.test.ts` has always asserted the page excuses a drop; this is // the promise the thread was never keeping, tested from the side that kept it. modelTurn.prioritize(["the track being heard"]); try { const thrown = await trackWith( slowRunner(0), melMatrix, audio(4), 44100, [], performance.now(), 4, "skipped-past", ).then( () => null, (e: unknown) => e, ); expect(thrown).toBeInstanceOf(Error); expect(verdictOf(thrown)).toEqual({ dropped: true }); // And what it must not be mistaken for: a runtime that refused, a session that would not start, // a fetch that 404s — those are the failures the strikes exist to stop paying for. expect(verdictOf(new Error("Session already started"))).toEqual({ error: "Session already started", }); } finally { modelTurn.prioritize(null); }});
it("drops what the queue was already holding when the listener moved on", async () => { // A question in the queue at the moment the page changes its mind: it has already given up its // turn once, and it should not get to keep a place in line for an answer nobody wants. modelTurn.prioritize(["a", "b"]); // b was somebody's successor a moment ago expect(await modelTurn.acquire("a", 1000)).toBe(0); let b: number | "waiting" = "waiting"; const waitingB = modelTurn.acquire("b", 1000).then((ms) => (b = ms)); await Promise.resolve(); expect(b).toBe("waiting"); // it had a place in line, and a budget to wait on modelTurn.prioritize(["a"]); // the listener moved; b is nobody's successor now await waitingB; expect(b).toBe(DROPPED); modelTurn.prioritize(null); modelTurn.release();});
it("infers two tracks at once without colliding in the session", async () => { // The guard the runtime has, reimplemented here rather than stubbed away, because the bug was that // nothing in this module enforced what a real session enforces — and a report from a real device // found it two loads in, on the ordinary case of a play and the prefetch behind it. Two `trackWith` // calls in flight: without the turn, one of them throws and this rejects. let inFlight = 0; const base = slowRunner(3); const guard: Runner = { async run(feeds) { if (inFlight > 0) throw new Error("Session already started"); inFlight++; try { return await base.run(feeds); } finally { inFlight--; } }, tensor: base.tensor, }; const [a, b] = await Promise.all([ trackWith(guard, melMatrix, audio(4), 44100), trackWith(guard, melMatrix, audio(4), 44100), ]); expect(a).not.toBeNull(); // both tracks got a grid expect(b).not.toBeNull(); expect(modelTurn.queued()).toBe(0); // and the queue is empty when they are done});
it("sends the bill back with a failure, not just with an answer", async () => { // The bug a real report caught: a model that failed after three seconds arrived with `phases=0` and // no runtime at all, because the error path threw away everything that could have explained the // failure. The verdict and the measurement of the verdict are both wanted. const fetch = vi.fn(async () => { throw new Error("offline"); }); vi.stubGlobal("fetch", fetch); const request: BeatTrackRequest = { token: 1, samples: audio(4), sampleRate: 44100, modelUrl: "http://models/beat.onnx", melUrl: "http://models/mel.f32", }; const reply = await answer(request); expect(reply.error).toContain("offline"); expect(reply.grid).toBeNull(); // It says how far it got before the failure, and what the machine was — the flags are written // before the session is built, precisely so that a session that never came to be can still report // them: "no GPU here" is worth most on the track that failed to get one. expect((reply.phases ?? []).map((p) => p.name)).toContain("load the runtime"); expect(reply.runtime).toMatchObject({ gpu: expect.any(Boolean), isolated: false }); // And the failure did not leave the session held: the next question can have it. expect(await modelTurn.acquire("", 5)).toBe(0); modelTurn.release(); vi.unstubAllGlobals();});
it("accounts without being asked, so a caller who does not care costs nothing", async () => { // `phases` is optional at the seam for that reason: the analyzer's own path must not have to // carry a collector to keep working. await expect(trackWith(slowRunner(0), melMatrix, audio(4), 44100)).resolves.not.toBeNull();});