lumbda/wasm/tests/integration.mjs
russell@unturf.com 1b7de2c9c6
wasm/playground: cancel button, asm state-leak fix, restyle to match homepage
User-visible changes
  - Cancel button — terminates the running worker. Pyodide's slow mandelbrot
    no longer freezes the UI; click cancel and the elapsed counter freezes
    at "(cancelled @ NNNN ms)".
  - Live ms counter ticks per animation frame while a tier is busy, so the
    Pyodide tier's ~5-15 s wait is visible instead of looking hung.
  - Restyled to match lumbda.com: chunkfive wordmark, --green: #227842
    (light) / #5ec07a (dark), lumbda-logo-green.png, lowercase "lumbda"
    everywhere. Pulls fonts/chunkfive locally so the playground stays
    self-contained.

Architecture
  - All tier evaluations now run inside a Web Worker (wasm/app/worker.mjs)
    so the main thread stays responsive. Cancel = worker.terminate(); next
    eval respawns a fresh worker.
  - Loaders use new URL("./...", import.meta.url) so paths resolve against
    the loader file's own location — works identically in window and
    worker contexts, no baseURL argument needed.
  - C tier Emscripten build flipped to EXPORT_ES6=1; loader uses dynamic
    `import()` of the factory module. Integration test updated accordingly.
  - Python loader uses `import("pyodide.mjs")` (ES module) instead of
    document.createElement, which doesn't exist in workers.

Bug fixes
  - Asm tier state leak: running the same demo twice on a cached WASM
    instance produced corrupted output (every other cell on row 2+ rendered
    as " " instead of the expected shade char). Root cause: top-level eval
    passed `global_env` as the env, so closures captured stale globals;
    fixed by passing NIL — env_lookup falls back to the CURRENT global_env
    via its existing two-pass walk. Multi-run regression added to the
    functional test suite.
  - fib-ack demo: (ack 3 4) was too heavy for Pyodide (minutes). Cut to
    (ack 3 3) + (fib 20) max so every tier finishes in seconds.

Test discipline
  - Root `make test-all` now includes `wasm-test`. Adding a language
    feature without exercising it on all six implementations is no longer
    possible by accident.
  - Functional suite: 11 assertions (was 10) — adds asm multi-run stability.
  - Integration + unit: still 20 + 8.
2026-06-14 12:13:20 -04:00

101 lines
3.9 KiB
JavaScript

// wasm/tests/integration.mjs
// Cross-tier integration — each demo runs on c-WASM and asm-WASM (Node
// hosts), output is compared to the canonical native Python lumbda run.
// Python tier (Pyodide) loads from a CDN inside a browser; covered in the
// functional/Playwright test suite.
import fs from "node:fs";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";
const here = path.dirname(fileURLToPath(import.meta.url));
const dist = path.resolve(here, "..", "dist");
const repoRoot = path.resolve(here, "..", "..");
const demosDir = path.join(here, "..", "app", "demos");
const DEMOS = ["mandelbrot", "fib-ack", "sieve", "self-interp"];
const state = { pass: 0, fail: 0, failures: [] };
function check(name, cond, detail) {
if (cond) { state.pass++; console.log(`${name}`); }
else { state.fail++; console.log(`${name}`); if (detail) { console.log(detail); } state.failures.push({ name, detail }); }
}
function nativePython(demoPath) {
return execFileSync("python3", [path.join(repoRoot, "lumbda.py"), "--fast", demoPath], {
encoding: "utf8", timeout: 120000,
});
}
async function runAsm(src) {
const wasmBytes = fs.readFileSync(path.join(dist, "asm", "lumbda-asm.wasm"));
const { instance } = await WebAssembly.instantiate(wasmBytes);
const exp = instance.exports;
exp.lumbda_init();
const bytes = new TextEncoder().encode(src);
new Uint8Array(exp.memory.buffer).set(bytes, exp.lumbda_source_ptr());
exp.lumbda_eval(bytes.length);
return new TextDecoder().decode(
new Uint8Array(exp.memory.buffer, exp.lumbda_output_ptr(), exp.lumbda_output_len()));
}
async function runC(src) {
const factoryURL = "file://" + path.join(dist, "c", "lumbda-c.js");
const createLumbdaC = (await import(factoryURL)).default;
let out = [];
const m = await createLumbdaC({
locateFile: (p) => path.join(dist, "c", p),
print: (line) => out.push(line),
printErr: (line) => out.push("ERR: " + line),
});
m.cwrap("lumbda_wasm_init", null, [])();
const r = m.cwrap("lumbda_wasm_eval", "number", ["string"])(src);
let errMsg = "";
if (r) errMsg = m.UTF8ToString(r);
return out.join("\n") + (errMsg ? "\n" + errMsg : "") + (out.length ? "\n" : "");
}
function diffSnippet(a, b) {
const aL = a.split("\n");
const bL = b.split("\n");
const n = Math.max(aL.length, bL.length);
const lines = [];
for (let i = 0; i < n; i++) {
if (aL[i] !== bL[i]) {
lines.push(` line ${i + 1}:`);
lines.push(` canonical: ${JSON.stringify(aL[i])}`);
lines.push(` got: ${JSON.stringify(bL[i])}`);
if (lines.length > 10) { lines.push(" ... (truncated)"); break; }
}
}
return lines.join("\n");
}
(async () => {
for (const demo of DEMOS) {
console.log(`── ${demo} ──`);
const demoPath = path.join(demosDir, demo + ".lsp");
const src = fs.readFileSync(demoPath, "utf8");
let canonical;
try { canonical = nativePython(demoPath); }
catch (e) { console.log(" ✗ canonical (native python lumbda) FAILED:", e.message.slice(0, 200)); state.fail++; continue; }
try {
const asmOut = await runAsm(src);
check(`${demo}: asm tier matches canonical`,
asmOut === canonical,
diffSnippet(canonical, asmOut));
} catch (e) { check(`${demo}: asm tier`, false, " threw: " + e.message); }
try {
const cOut = await runC(src);
check(`${demo}: c tier matches canonical`,
cOut === canonical,
diffSnippet(canonical, cOut));
} catch (e) { check(`${demo}: c tier`, false, " threw: " + e.message); }
}
console.log(`\n${state.pass} passed, ${state.fail} failed`);
process.exit(state.fail ? 1 : 0);
})();