diff --git a/js/core/index.ts b/js/core/index.ts index 89db24b..cb228ff 100644 --- a/js/core/index.ts +++ b/js/core/index.ts @@ -29,7 +29,7 @@ export { checkJspi, checkSupport } from "./support.ts"; export type { SupportReport } from "./support.ts"; export { BootError, download, loadBytes, loadKernelModule } from "./load.ts"; export type { BootFailStage, BytesSource, DownloadProgress, KernelSource, LoadOptions } from "./load.ts"; -export { JitHost, jitFma, jitSimd } from "./jit.ts"; +export { JitHost, jitFma, jitSimd, jitTail } from "./jit.ts"; export { DEFAULT_DISPLAY_SIZE, DisplayHost, FOURCC_XRGB8888, frameToPpm, xrgbToRgba } from "./display.ts"; export type { DisplayFrame, DisplayHostOptions, DisplayMode, DisplayOption, DisplaySize, DisplayStats } from "./display.ts"; export { ABS_MAX, ABS_X, ABS_Y, BTN_LEFT, BTN_MIDDLE, BTN_RIGHT, DOM_CODE_TO_LINUX, EV_ABS, EV_KEY, EV_REL, EV_SYN, INPUT_KEYBOARD, INPUT_MOUSE, INPUT_TABLET, InputHost, REL_WHEEL, REL_X, REL_Y, domButtonToLinux, domCodeToLinux } from "./input.ts"; diff --git a/test/api.test.ts b/test/api.test.ts index c76742e..50945f0 100644 --- a/test/api.test.ts +++ b/test/api.test.ts @@ -72,10 +72,18 @@ const bundleInitrd = Buffer.from(bundledBoot(kernelModule).initrd ?? []); const noCaptureTools = !(bundleInitrd.includes("usr/bin/kwrec") && bundleInitrd.includes("usr/bin/kwcap")) && "the bundle's initramfs has no kwrec and kwcap (a release build)"; type BootOptions = NonNullable[0]>; +/** + * With UNKERNEL_TEST_CPUS > 1, the SMP kernel boot() boots on more than one CPU unless a test gives a kernel: derived + * from the bundle and compiled once here. Given the bundle, createKernel() derives it at every such boot on this + * thread (about 0.2 s of patching), and the suite's boots at once held this thread, where the inline kernels and the + * device sources run, for 3 s and more. sharedKernel() still boots the bundle. + */ +const smpTestKernel = (testCpus ?? 1) > 1 ? await compileTestKernel() : undefined; // A failed assertion must not leave a kernel running (it would keep the test process alive). // Each test stops its own kernels: a shared afterEach would stop the kernels of tests still running. const boot = async (t: { after(fn: () => unknown): void }, opts: BootOptions) => { - const vm = await createKernel({ kernel: testKernel, cpus: testCpus, ...opts }); + const kernel = smpTestKernel && (opts.cpus ?? testCpus ?? 1) > 1 ? smpTestKernel : testKernel; + const vm = await createKernel({ kernel, cpus: testCpus, ...opts }); t.after(() => vm.stop({ reason: "test cleanup" })); return vm; }; @@ -121,6 +129,17 @@ function screen(vm: Instance) { }; return { s, waitFor }; } +/** + * The value of a guest's background counter, a loop of `echo $i > FILE`; `read` gives `cat FILE`'s output. The echo + * truncates the file before it writes, so a read in between finds it empty: read again then (a fork per write instead, + * an atomic rename, would load the guest, and inline this thread, much more). + */ +async function readCounter(read: () => Promise): Promise { + for (let i = 0; ; i++) { + const v = (await read()).trim(); + if (v || i >= 50) return Number(v); + } +} /** Waits until a device callback has recorded `ev` (anywhere in `events`: a slow host's later events do not hide it). */ async function waitEvent(events: string[], ev: string, ms = 60000) { const end = Date.now() + ms; @@ -130,6 +149,16 @@ async function waitEvent(events: string[], ev: string, ms = 60000) { } } +/** + * Tests that `ownerThread()` defers to their own suite after the concurrent one, where they run alongside each other + * only: worker-mode capture from a source on this thread (sound in's read(), the camera's read()). The worker records + * silence or a black frame wherever this thread answers late, and with the whole suite at once it runs every inline + * kernel: there a source on it fell 200 ms or more behind (2026-12-01). + */ +const ownerThreadTests: Array<() => void> = []; +/** Registers `register`'s test now, or with a source on this thread (`onThread`) after the concurrent suite. */ +const ownerThread = (onThread: boolean, register: () => void) => (onThread ? void ownerThreadTests.push(register) : register()); + describe("api", { concurrency: CONCURRENCY }, () => { // Powering off with exit code 0 is checked by the display, data disk, jit and device tests. for (const { worker, shared, name, transport } of TRANSPORTS) describe(`createKernel() with no devices, one kernel (${spec}, ${name})`, { concurrency: 1 }, () => { @@ -537,7 +566,7 @@ describe("api", { concurrency: CONCURRENCY }, () => { const st = vm.stats().soundIn; // in a worker: its last report, at the exit assert.ok(st && st.opens === 2 && st.starts === 2 && st.frames >= 12000 + 4000, JSON.stringify(st)); }; - for (const { worker, shared, name } of TRANSPORTS) test(`sound in: a guest records the source's samples through ALSA hw:0,0 and /dev/dsp (read(), ${name})`, { skip: noCaptureTools }, async (t) => { + for (const { worker, shared, name } of TRANSPORTS) ownerThread(worker, () => test(`sound in: a guest records the source's samples through ALSA hw:0,0 and /dev/dsp (read(), ${name})`, { skip: noCaptureTools }, async (t) => { const events: string[] = []; let pos = 0; await captureRoundTrip(t, { @@ -553,7 +582,7 @@ describe("api", { concurrency: CONCURRENCY }, () => { }, }, }, events, !worker); - }); + })); for (const { worker, name } of MODES) test(`sound in: a producer on its own clock writes the capture ring (onRing, ${name})`, { skip: noCaptureTools }, async (t) => { const events: string[] = []; let producer: Worker | undefined, started: Promise | undefined; @@ -636,7 +665,7 @@ describe("api", { concurrency: CONCURRENCY }, () => { // ones skip, never rush), so only the first frame's lateness shortens the span, by less than an interval. assert.ok(frames.at(-1)!.ms >= (frames.at(-1)!.seq - frames[0]!.seq - 1) * 1000 / fps * 0.95, `${frames.at(-1)!.ms} ms for ${count} frames at ${fps} fps`); }; - for (const { worker, shared, name } of TRANSPORTS) test(`camera: a guest captures the source's frames through V4L2 /dev/video0, I420, NV12 and YUYV (${name})`, { skip: noCaptureTools }, async (t) => { + for (const { worker, shared, name } of TRANSPORTS) ownerThread(worker, () => test(`camera: a guest captures the source's frames through V4L2 /dev/video0, I420, NV12 and YUYV (${name})`, { skip: noCaptureTools }, async (t) => { const made = new Map(); const streams: string[] = []; const src = sdk.patternSource((n, frame) => made.set(fnv1a(frame), n)); @@ -666,7 +695,7 @@ describe("api", { concurrency: CONCURRENCY }, () => { const st = vm.stats().camera; assert.ok(st && st.starts === 4 && st.stops === 4 && st.frames >= 31 && (worker || st.blackFrames === 0), JSON.stringify(st)); assert.deepEqual(vm.camera, { format: null }); - }); + })); test("camera: without a picture the guest gets black frames at its rate; without the option no /dev/video0", { skip: noCaptureTools }, async (t) => { const vm = await boot(t, { log: () => {}, disks: [], camera: true }); const r = await vm.exec("sh", ["-c", "kwcap nv12 320 240 10 5"], { timeout: 120000 }); @@ -693,14 +722,20 @@ describe("api", { concurrency: CONCURRENCY }, () => { type Made = Map; const kwcapChunks = (out: string) => [...out.matchAll(/^frame (\d+) seq (\d+) bytes (\d+) fnv ([0-9a-f]{8}) ms ([\d.]+) key ([01])$/gm)] .map((m) => ({ seq: Number(m[2]), bytes: Number(m[3]), fnv: m[4]!, ms: Number(m[5]), key: m[6] === "1" })); - const h264Source = (made: Made, streams: string[], start = 0): import("../js/node.ts").CameraSource => { - const src = sdk.patternSource(undefined, { h264: true, start, onChunk: (n, c, key) => made.set(fnv1a(c), { n, key, bytes: c.length }) }); + /** `asked`: for each key frame asked of the source, the number of the chunk it makes next (that key frame). */ + const h264Source = (made: Made, streams: string[], start = 0, asked: number[] = []): import("../js/node.ts").CameraSource => { + let next = start; + const src = sdk.patternSource(undefined, { h264: true, start, onChunk: (n, c, key) => { next = n + 1; made.set(fnv1a(c), { n, key, bytes: c.length }); } }); return { ...src, onStream: (f, sink) => { streams.push(f ? `${f.pixelFormat} ${f.width}x${f.height} ${f.fps}${f.bitrate ? ` ${f.bitrate} ${f.keyInterval}` : ""}` : "stop"); src.onStream!(f, sink); }, + keyFrame: () => { + asked.push(next); + src.keyFrame!(); + }, }; }; /** @@ -734,8 +769,8 @@ describe("api", { concurrency: CONCURRENCY }, () => { return { ns, gaps, keys: cs.flatMap((c, i) => (c.key ? [i] : [])), cs }; }; for (const { worker, shared, name } of TRANSPORTS) test(`camera: H.264 the source encodes reaches the guest chunk for chunk, in order and once, key frames where the controls say; a guest that stops taking it loses chunks only up to a key frame (${name})`, { skip: noCaptureTools }, async (t) => { - const made: Made = new Map(), streams: string[] = []; - const vm = await boot(t, { log: () => {}, disks: [], worker, shared, camera: h264Source(made, streams) }); + const made: Made = new Map(), streams: string[] = [], asked: number[] = []; + const vm = await boot(t, { log: () => {}, disks: [], worker, shared, camera: h264Source(made, streams, 0, asked) }); const run = async (cmd: string) => { const r = await vm.exec("sh", ["-c", cmd], { timeout: 120000 }); assert.equal(r.exitCode, 0, r.stdout + r.stderr); @@ -747,12 +782,20 @@ describe("api", { concurrency: CONCURRENCY }, () => { assert.deepEqual(a.keys, [0, 30], "a key frame first and every second (the GOP size follows the rate)"); assert.match(await run("tail -1 /tmp/a.txt"), /format H264 320x240, 30 fps asked, expbuf ok, compressed, sizeimage 115200, frameioc refused/); assert.ok(a.cs.at(-1)!.ms >= 39 * 1000 / 30 * 0.8, `${a.cs.at(-1)!.ms} ms for 40 chunks at 30 fps`); - // the controls: a GOP of 12, a bitrate, a key frame forced after the 16th - const b = assertChunks(await run("kwcap h264 640 480 30 40 '' mmap '' gop=12 bitrate=300000 force=15"), made, 40); + // the controls: a GOP of 12, a bitrate, a key frame forced after the 16th. The source makes the forced key frame + // next, but the chunks it made before (the host's queue, the guest's filled buffers) come first: as many as + // the guest lags behind the source's clock, so the stream is long enough for the queue's 32 and 4 buffers. + const askedBefore = asked.length; + const b = assertChunks(await run("kwcap h264 640 480 30 60 '' mmap '' gop=12 bitrate=300000 force=15"), made, 60); assert.equal(b.gaps, 0); assert.deepEqual(b.keys.slice(0, 2), [0, 12]); - assert.ok(b.keys[2]! >= 16 && b.keys[2]! <= 22, `the forced key frame soon after the 16th chunk: ${b.keys}`); - if (b.keys[2]! + 12 < 40) assert.equal(b.keys[3], b.keys[2]! + 12, `the GOP counts from it: ${b.keys}`); + const forced = asked.slice(askedBefore).find((n) => n > b.ns[0]!); + assert.ok(forced !== undefined && forced > b.ns[15]!, `a key frame asked for after the guest took the 16th chunk (${b.ns[15]}): ${asked.slice(askedBefore)}`); + const fi = b.ns.indexOf(forced); + assert.ok(fi > 15 && b.keys.includes(fi), `the guest got the forced key frame (the source's ${forced}) as one: chunk ${fi}, keys ${b.keys}`); + assert.deepEqual(b.keys.filter((i) => i < fi), [0, 12, 24, 36, 48].filter((i) => i < fi), `only the GOP's key frames before it: ${b.keys}`); + if (fi + 12 < 60) assert.equal(b.keys[b.keys.indexOf(fi) + 1], fi + 12, `the GOP counts from it: ${b.keys}`); + t.diagnostic(`the forced key frame came as chunk ${fi} of 60`); // read(): one chunk a read const r = await run("kwcap h264 320 240 15 6 '' read"); const rf = [...r.matchAll(/^frame \d+ seq - bytes (\d+) fnv ([0-9a-f]{8})/gm)]; @@ -949,7 +992,10 @@ describe("api", { concurrency: CONCURRENCY }, () => { const logs: string[] = []; const host = new sdk.JitHost({ memory: () => memory, memory64: () => false, log: (m) => logs.push(m), retainedNudge: 2, retainedLimit: 4 }); host.attach({ __indirect_function_table: table }); - assert.equal(host.caps(), 3 | 16 | (sdk.jitSimd() ? 32 : 0)); // available, 32-bit memory, env.table, SIMD + // available, 32-bit memory, env.table, SIMD, fused multiply-adds, tail calls, module format v2 (KW_JIT_V2=1), chaining (KW_JIT_CHAIN=0: off) + const simd = sdk.jitSimd(), tail = sdk.jitTail(); + assert.equal(host.caps(), 3 | 16 | (simd ? 32 : 0) | (simd && sdk.jitFma() ? 64 : 0) | (tail ? 128 : 0) | + (process.env.KW_JIT_V2 === "1" ? 256 : 0) | (tail && process.env.KW_JIT_CHAIN !== "0" ? 512 : 0)); // Finalizers never run inside one synchronous loop, so nothing is collected here. const results: number[] = []; for (let i = 0; i < 6; i++) { @@ -1224,8 +1270,14 @@ describe("api", { concurrency: CONCURRENCY }, () => { const views = (big as import("../js/node.ts").InlineShmFile).views(100, BIG - 200); assert.ok(views.length >= 1 && views.every((v) => v.buffer === (vm as import("../js/node.ts").KernelInstance).kernel.memory.buffer), "views of the kernel's memory"); assert.equal(sha(Buffer.concat(views)), sha(content.subarray(100, BIG - 100)), "the views cover the range in order"); + } else if ((testCpus ?? 1) > 1) { + // An SMP kernel (UNKERNEL_TEST_CPUS): the worker shares its memory with this thread, which reads in place. + assert.equal(big.inPlace, true, "in place in worker mode with an SMP kernel"); + const views = big.views(100, BIG - 200); + assert.ok(views.length >= 1 && views.every((v) => v.buffer instanceof SharedArrayBuffer), "views of the shared memory"); + assert.equal(sha(Buffer.concat(views)), sha(content.subarray(100, BIG - 100)), "the views cover the range in order"); } else { - assert.throws(() => (big as unknown as { views(): unknown }).views(), (e: Error & { code?: string }) => e.code === "EOPNOTSUPP", "no views in worker mode"); + assert.throws(() => big.views(), (e: Error & { code?: string }) => e.code === "EOPNOTSUPP", "no views in worker mode with the UP kernel"); } // 2. The host writes into it (unaligned, across many pages); the guest sees the bytes. @@ -1465,26 +1517,34 @@ describe("api", { concurrency: CONCURRENCY }, () => { await sh(`rm -f /tmp/spin; for i in $(seq ${opts.cpus}); do (while :; do :; done) & echo $! >> /tmp/spin; done`); const id2 = await memfd(MFD, 7); const g = await shm.openId(id2); - const times: number[] = []; + // With each read, this thread's own longest delay meanwhile (zero timers, one after the other): with every + // test of the suite at once (inline kernels run on this thread) it alone can exceed a yield, and the read's + // answer waits for it too. The ring's reads are judged by those during which this thread stayed free. + const reads: Array<{ ms: number; lag: number }> = []; for (let i = 0; i < 25; i++) { + let reading = true, lag = 0; + const sampler = (async () => { + while (reading) { + const t1 = performance.now(); + await new Promise((res) => setTimeout(res, 0)); + lag = Math.max(lag, performance.now() - t1); + } + })(); const t0 = performance.now(); const b = await g.read(i * 65536, 524288); - times.push(performance.now() - t0); + const ms = performance.now() - t0; + reading = false; + await sampler; + reads.push({ ms, lag }); assert.equal(fnv32(b), fnv32(pattern.subarray(i * 65536, i * 65536 + 524288))); } - times.sort((x, y) => x - y); - const median = times[12]!; - // This thread's own delay (a zero timer): with every test of the suite at once it alone can exceed a yield. - const lags: number[] = []; - for (let i = 0; i < 9; i++) { - const t0 = performance.now(); - await new Promise((res) => setTimeout(res, 0)); - lags.push(performance.now() - t0); - } - const lag = lags.sort((x, y) => x - y)[4]!; - t.diagnostic(`${via}: reads of 512 KiB with the guest busy: median ${median.toFixed(2)} ms, longest ${times.at(-1)!.toFixed(1)} ms (this thread's timer delay ${lag.toFixed(2)} ms)`); + const mid = (xs: number[]) => xs.sort((x, y) => x - y)[xs.length >> 1]!; + const median = mid(reads.map((r) => r.ms)), free = reads.filter((r) => r.lag < 3).map((r) => r.ms); + const freeMedian = free.length ? mid(free) : NaN; + t.diagnostic(`${via}: reads of 512 KiB with the guest busy: median ${median.toFixed(2)} ms, longest ${Math.max(...reads.map((r) => r.ms)).toFixed(1)} ms; ` + + `${free.length} with this thread free (timer delays under 3 ms): median ${freeMedian.toFixed(2)} ms`); if (via === "in place") assert.ok(median < 2, `in place: median ${median} ms`); - if (via === "ring" && lag < 2) assert.ok(median < 8, `through the ring: median ${median} ms (a message waits for the kernel's 20 ms yield)`); + if (via === "ring" && free.length >= 3) assert.ok(freeMedian < 8, `through the ring, this thread free: median ${freeMedian} ms of ${free.length} reads (a message waits for the kernel's 20 ms yield)`); assert.equal(shm.stats.inPlaceReads > 0, inPlace, JSON.stringify(shm.stats)); if (inPlace) { @@ -2338,8 +2398,12 @@ describe("api", { concurrency: CONCURRENCY }, () => { const ev2: string[] = []; const vm2 = await boot(t, { ...opts(ev2), restore: snap }); const b = screen(vm2); - assert.deepEqual(ev2, ["open", "prepare", "start"], "replayed to the new source"); - assert.equal(vm2.soundIn?.capturing, true); + // The replay comes first, in boot(). The restored guest has what was left of its 3 s recording (a restore hides + // the stop from its clock): where the snapshot landed late in it (a busy host), its own stop and close can + // follow before boot() returns. + assert.deepEqual(ev2.slice(0, 3), ["open", "prepare", "start"], "replayed to the new source"); + assert.deepEqual(ev2.slice(3), ["stop", "close"].slice(0, ev2.length - 3), ev2.join(",")); + assert.equal(vm2.soundIn?.capturing, ev2.length === 3); await b.waitFor(/kwrec: 24000 frames, \d+ overrun\(s\)[\s\S]*recorded/); assert.equal(ev2.at(-1), "close", ev2.join(",")); vm2.write("poweroff\n"); @@ -2556,7 +2620,7 @@ describe("api", { concurrency: CONCURRENCY }, () => { assert.equal(p.sessionId, d.sessionId); const sp = termScreen(p); await sp.waitFor(/ready-2[\s\S]*still-6/); - const count = async () => Number((await vm2.exec("cat", ["/tmp/cnt"])).stdout); + const count = () => readCounter(async () => (await vm2.exec("cat", ["/tmp/cnt"])).stdout); const n1 = await count(); await p.write("echo got-$X-$$; stty size\n"); await sp.waitFor(new RegExp(`got-kept-${d.pid}\\r?\\n30 100\\r?\\n`)); @@ -2849,7 +2913,7 @@ describe("api", { concurrency: CONCURRENCY }, () => { const a = screen(vm), sh = shell(vm, a); await a.waitFor(PROMPT); await sh("X=kept; (i=0; while :; do i=$((i+1)); echo $i > /tmp/n; usleep 20000; done) & echo one > /data/one; sync"); - const counter = async () => Number((await sh("cat /tmp/n")).trim()); + const counter = () => readCounter(() => sh("cat /tmp/n")); const uptime = async () => Number((await sh("cut -d' ' -f1 /proc/uptime")).trim()); const runsOn = async (what: string) => { const n = await counter(); @@ -2897,9 +2961,10 @@ describe("api", { concurrency: CONCURRENCY }, () => { const vm2 = await boot(t, { worker, kernel: module, vsock: false, disks: [disk()], restore: sdk.decodeSnapshot(bytes!), log: () => {} } as BootOptions); const b = screen(vm2), sh2 = shell(vm2, b); assert.equal((await sh2("echo got-$X-$(cat /data/one)-$(cat /data/two)")).trim(), "got-kept-one-two"); - const n = Number((await sh2("cat /tmp/n")).trim()); + const counter2 = () => readCounter(() => sh2("cat /tmp/n")); + const n = await counter2(); await new Promise((r) => setTimeout(r, 300)); - assert.ok(Number((await sh2("cat /tmp/n")).trim()) > n, "the background task counts on after the restore"); + assert.ok(await counter2() > n, "the background task counts on after the restore"); await vm2.stop({ reason: "test" }); await assert.rejects(boot(t, { worker, kernel: module, vsock: false, disks: [disk()], restore: held!, log: () => {} } as BootOptions), /was written after the snapshot/); }); @@ -2937,7 +3002,7 @@ describe("api", { concurrency: CONCURRENCY }, () => { await d.write("Y=det; echo d-ready-$((2+2))\n"); await p.write("Z=plain; echo p-ready-$((3+3))\n"); await Promise.all([sd.waitFor(/d-ready-4/), sp.waitFor(/p-ready-6/)]); - const counter = async () => Number((await sh("cat /tmp/n")).trim()); + const counter = () => readCounter(() => sh("cat /tmp/n")); const alive = async (pid: number) => (await sh(`[ -d /proc/${pid} ] && echo yes || echo no`)).trim() === "yes"; // snapshot() refuses while vsock packets are in flight (kwtty's last output may still be); the guest goes on. const quietly = async (opts: NonNullable[0]>) => { @@ -3288,6 +3353,10 @@ describe("api", { concurrency: CONCURRENCY }, () => { }); +describe("api: worker-mode capture from a source on this thread, after the concurrent suite", { concurrency: CONCURRENCY }, () => { + for (const register of ownerThreadTests) register(); +}); + // Not with the others: it replaces WebAssembly.Memory, which every boot uses. test("SMP: the kernel's memory is allocated once, shared, at a boot and at a restore; memoryFallbackMiB applies where a shared memory cannot be had", { skip: !hasSmpPatch && "the kernel under test carries no SMP kernel" }, async (t) => {