|
| 1 | +// Codegen tests for the @daemon / @scheduled COLD exports (spec 03 sections 5.2 / |
| 2 | +// 5.6 / 5.7, Reconciliation Part 2: `daemon_start() -> i32`, |
| 3 | +// `scheduled_tick(i32 task_id) -> i64`). This is the THIRD increment: the cold |
| 4 | +// artifact exports synthesized by `injectDaemonHandler` and the daemon-side |
| 5 | +// front-end checks (9012 handler signature, 9008 no-scheduled-tasks warning). |
| 6 | +// |
| 7 | +// It compiles @daemon fixtures under --targetMode cold, asserts the emitted |
| 8 | +// module EXPORTS `daemon_start` + `scheduled_tick`, instantiates the wasm and |
| 9 | +// drives the exports to prove `scheduled_tick(task_id)` dispatches to the method |
| 10 | +// the `toildaemon.catalog` assigned that task_index to (the lockstep contract), |
| 11 | +// and asserts the 9012 / 9008 diagnostics fire. Mirrors the run.mjs / catalog.mjs |
| 12 | +// harness style (spawn the local toilscript bin, inspect status / output / wasm). |
| 13 | +import { mkdtempSync, writeFileSync, rmSync, readFileSync } from "node:fs"; |
| 14 | +import { tmpdir } from "node:os"; |
| 15 | +import { join, dirname } from "node:path"; |
| 16 | +import { fileURLToPath } from "node:url"; |
| 17 | +import { spawnSync } from "node:child_process"; |
| 18 | + |
| 19 | +const here = dirname(fileURLToPath(import.meta.url)); |
| 20 | +const root = join(here, "..", ".."); |
| 21 | +const bin = join(root, "bin", "toilscript.js"); |
| 22 | + |
| 23 | +let failures = 0; |
| 24 | +function check(name, cond, detail) { |
| 25 | + if (cond) { console.log(` ok ${name}`); } |
| 26 | + else { failures++; console.error(` FAIL ${name}${detail ? ": " + detail : ""}`); } |
| 27 | +} |
| 28 | + |
| 29 | +// Compile `source` under `mode`, return { status, output, wasm:Buffer|null, exports:string[] }. |
| 30 | +function compile(source, mode) { |
| 31 | + const tmp = mkdtempSync(join(tmpdir(), "daemoncg-")); |
| 32 | + const app = join(tmp, "app.ts"); |
| 33 | + const out = join(tmp, "out.wasm"); |
| 34 | + writeFileSync(app, source); |
| 35 | + const args = [bin, app, "-o", out, "--runtime", "stub"]; |
| 36 | + if (mode != null) args.push("--targetMode", mode); |
| 37 | + const r = spawnSync("node", args, { encoding: "utf8" }); |
| 38 | + let wasm = null; |
| 39 | + try { wasm = readFileSync(out); } catch { /* no output on failure */ } |
| 40 | + rmSync(tmp, { recursive: true, force: true }); |
| 41 | + return { status: r.status, output: (r.stdout || "") + (r.stderr || ""), wasm, exports: wasm ? wasmExports(wasm) : [] }; |
| 42 | +} |
| 43 | + |
| 44 | +// --- wasm export-section walker (the hostile-safe parser; mirrors the host) --- |
| 45 | +function leb(buf, pos) { |
| 46 | + let result = 0, shift = 0, p = pos; |
| 47 | + for (;;) { const b = buf[p++]; result |= (b & 0x7f) << shift; if ((b & 0x80) === 0) break; shift += 7; } |
| 48 | + return [result >>> 0, p]; |
| 49 | +} |
| 50 | +// Return the list of EXPORTED names (export section, id = 7). |
| 51 | +function wasmExports(buf) { |
| 52 | + let pos = 8; // past "\0asm" magic + version u32 |
| 53 | + const names = []; |
| 54 | + while (pos < buf.length) { |
| 55 | + const id = buf[pos++]; |
| 56 | + let size; [size, pos] = leb(buf, pos); |
| 57 | + const end = pos + size; |
| 58 | + if (id === 7) { // export section |
| 59 | + let count, p = pos; [count, p] = leb(buf, p); |
| 60 | + for (let i = 0; i < count; i++) { |
| 61 | + let nlen; [nlen, p] = leb(buf, p); |
| 62 | + names.push(buf.toString("utf8", p, p + nlen)); |
| 63 | + p += nlen; |
| 64 | + p += 1; // export kind byte |
| 65 | + let idx; [idx, p] = leb(buf, p); // export index |
| 66 | + } |
| 67 | + } |
| 68 | + pos = end; |
| 69 | + } |
| 70 | + return names; |
| 71 | +} |
| 72 | + |
| 73 | +// toildaemon.catalog reader (just enough to recover the task_index ordering). |
| 74 | +function findSection(buf, wanted) { |
| 75 | + let pos = 8; |
| 76 | + while (pos < buf.length) { |
| 77 | + const id = buf[pos++]; |
| 78 | + let size; [size, pos] = leb(buf, pos); |
| 79 | + const end = pos + size; |
| 80 | + if (id === 0) { |
| 81 | + let nl, np; [nl, np] = leb(buf, pos); |
| 82 | + if (buf.toString("latin1", np, np + nl) === wanted) return buf.subarray(np + nl, end); |
| 83 | + } |
| 84 | + pos = end; |
| 85 | + } |
| 86 | + return null; |
| 87 | +} |
| 88 | +function catalogTaskOrder(buf) { |
| 89 | + const sec = findSection(buf, "toildaemon.catalog"); |
| 90 | + if (!sec) return null; |
| 91 | + let pos = 0; |
| 92 | + const u16 = () => { const v = sec[pos] | (sec[pos + 1] << 8); pos += 2; return v; }; |
| 93 | + const u8 = () => sec[pos++]; |
| 94 | + const u32 = () => { pos += 4; }; |
| 95 | + const u64 = () => { pos += 8; }; |
| 96 | + const str = () => { const n = (sec[pos] | (sec[pos + 1] << 8) | (sec[pos + 2] << 16) | (sec[pos + 3] << 24)) >>> 0; pos += 4; const s = sec.toString("utf8", pos, pos + n); pos += n; return s; }; |
| 97 | + u16(); u8(); const n = u16(); |
| 98 | + const tasks = []; |
| 99 | + for (let i = 0; i < n; i++) { |
| 100 | + const name = str(); const idx = u16(); u8(); u64(); u64(); u32(); u32(); u16(); u8(); u8(); u8(); u64(); |
| 101 | + tasks.push({ name, idx }); |
| 102 | + } |
| 103 | + return tasks; |
| 104 | +} |
| 105 | + |
| 106 | +// Instantiate a stub-runtime cold module with a minimal `env`. |
| 107 | +function instantiate(wasm) { |
| 108 | + const imports = { env: { abort: () => { throw new Error("wasm abort"); }, trace: () => {}, seed: () => Date.now() } }; |
| 109 | + return new WebAssembly.Instance(new WebAssembly.Module(wasm), imports).exports; |
| 110 | +} |
| 111 | + |
| 112 | +console.log("daemon cold-export codegen (spec 03 sections 5.2/5.6/5.7):"); |
| 113 | + |
| 114 | +// =========================================================================== |
| 115 | +// 1. A @daemon with 2+ @scheduled tasks EXPORTS daemon_start + scheduled_tick. |
| 116 | +// =========================================================================== |
| 117 | +{ |
| 118 | + const src = ` |
| 119 | +@daemon |
| 120 | +class Jobs { |
| 121 | + onStart(): void {} |
| 122 | + @scheduled("30s") fast(): void {} |
| 123 | + @scheduled("0 */6 * * *") sixHourly(): void {} |
| 124 | +} |
| 125 | +export function probe(): i32 { return 1; } |
| 126 | +`; |
| 127 | + const r = compile(src, "cold"); |
| 128 | + check("cold @daemon (2 tasks) compiles", r.status === 0, `status ${r.status}\n${r.output}`); |
| 129 | + check("exports daemon_start", r.exports.includes("daemon_start"), r.exports.join(",")); |
| 130 | + check("exports scheduled_tick", r.exports.includes("scheduled_tick"), r.exports.join(",")); |
| 131 | + check("does NOT export a separate init (folded into daemon_start)", !r.exports.includes("init")); |
| 132 | +} |
| 133 | + |
| 134 | +// =========================================================================== |
| 135 | +// 2. scheduled_tick(task_id) dispatches to the method the catalog task_index |
| 136 | +// names, in source-declaration order (the lockstep contract). Verified by |
| 137 | +// actually invoking the emitted wasm. |
| 138 | +// =========================================================================== |
| 139 | +{ |
| 140 | + const src = ` |
| 141 | +let __log: i32 = 0; |
| 142 | +let __started: i32 = 0; |
| 143 | +export function logv(): i32 { return __log; } |
| 144 | +export function started(): i32 { return __started; } |
| 145 | +@daemon |
| 146 | +class Jobs { |
| 147 | + private seq: i32 = 100; |
| 148 | + onStart(): void { __started = __started + 1; this.seq = 200; } |
| 149 | + @scheduled("30s") alpha(): void { __log = this.seq + 0; } // task 0 |
| 150 | + @scheduled("5m") beta(): void { __log = this.seq + 1; } // task 1 |
| 151 | + @scheduled("0 0 * * *") gamma(): void { __log = this.seq + 2; } // task 2 |
| 152 | +} |
| 153 | +export function probe(): i32 { return 1; } |
| 154 | +`; |
| 155 | + const r = compile(src, "cold"); |
| 156 | + check("cold @daemon (3 tasks) compiles", r.status === 0, r.output); |
| 157 | + if (r.status === 0 && r.wasm) { |
| 158 | + const order = catalogTaskOrder(r.wasm); |
| 159 | + check("catalog task order = alpha,beta,gamma", |
| 160 | + !!order && order.map((t) => `${t.idx}:${t.name}`).join(",") === "0:alpha,1:beta,2:gamma", |
| 161 | + order ? order.map((t) => `${t.idx}:${t.name}`).join(",") : "no catalog"); |
| 162 | + const ex = instantiate(r.wasm); |
| 163 | + const startRc = ex.daemon_start(); // i32 -> JS Number; call ONCE |
| 164 | + check("daemon_start() returns 0", startRc === 0, `${startRc}`); |
| 165 | + check("onStart ran exactly once after daemon_start", ex.started() === 1, `${ex.started()}`); |
| 166 | + // Each tick reads instance.seq (200, set by onStart). If a fresh instance |
| 167 | + // were created per tick, seq would be the field initializer 100 since |
| 168 | + // onStart never re-runs. So 200+idx proves the single box-lifetime |
| 169 | + // instance is reused AND that task_id maps to the catalog's method. |
| 170 | + for (const t of order) { |
| 171 | + ex.scheduled_tick(t.idx); |
| 172 | + check(`scheduled_tick(${t.idx}) dispatches ${t.name} (log=${200 + t.idx})`, |
| 173 | + ex.logv() === 200 + t.idx, `log=${ex.logv()}`); |
| 174 | + } |
| 175 | + check("onStart still ran once (single instance across ticks)", ex.started() === 1, `${ex.started()}`); |
| 176 | + // Out-of-range task id is a safe no-op (no dispatch arm matches). |
| 177 | + const before = ex.logv(); |
| 178 | + ex.scheduled_tick(99); |
| 179 | + check("scheduled_tick(out-of-range) is a no-op", ex.logv() === before); |
| 180 | + } |
| 181 | +} |
| 182 | + |
| 183 | +// =========================================================================== |
| 184 | +// 3. 9012: a @scheduled handler must take no arguments and return void. |
| 185 | +// =========================================================================== |
| 186 | +{ |
| 187 | + const withArg = compile(` |
| 188 | +@daemon |
| 189 | +class Jobs { @scheduled("30s") bad(x: i32): void {} } |
| 190 | +export function probe(): i32 { return 1; } |
| 191 | +`, "cold"); |
| 192 | + check("9012: @scheduled with an argument rejected", |
| 193 | + withArg.status !== 0 && /must take no arguments and return void/.test(withArg.output), |
| 194 | + withArg.output.slice(0, 200)); |
| 195 | + |
| 196 | + const nonVoid = compile(` |
| 197 | +@daemon |
| 198 | +class Jobs { @scheduled("30s") bad(): i32 { return 1; } } |
| 199 | +export function probe(): i32 { return 1; } |
| 200 | +`, "cold"); |
| 201 | + check("9012: @scheduled with non-void return rejected", |
| 202 | + nonVoid.status !== 0 && /must take no arguments and return void/.test(nonVoid.output), |
| 203 | + nonVoid.output.slice(0, 200)); |
| 204 | + |
| 205 | + // A correct void/no-arg handler must NOT trip 9012. |
| 206 | + const good = compile(` |
| 207 | +@daemon |
| 208 | +class Jobs { @scheduled("30s") ok(): void {} } |
| 209 | +export function probe(): i32 { return 1; } |
| 210 | +`, "cold"); |
| 211 | + check("valid void/no-arg @scheduled does NOT trip 9012", |
| 212 | + good.status === 0 && !/must take no arguments and return void/.test(good.output), good.output.slice(0, 200)); |
| 213 | +} |
| 214 | + |
| 215 | +// =========================================================================== |
| 216 | +// 4. 9008: a @daemon with zero @scheduled tasks is a WARNING (compiles), and |
| 217 | +// still emits daemon_start + scheduled_tick (the daemon may run only onStart). |
| 218 | +// =========================================================================== |
| 219 | +{ |
| 220 | + const r = compile(` |
| 221 | +@daemon |
| 222 | +class Loop { |
| 223 | + onStart(): void {} |
| 224 | +} |
| 225 | +export function probe(): i32 { return 1; } |
| 226 | +`, "cold"); |
| 227 | + check("9008: zero-@scheduled @daemon WARNS but compiles", |
| 228 | + r.status === 0 && /declares no scheduled tasks/.test(r.output), `status ${r.status}\n${r.output}`); |
| 229 | + check("zero-task daemon still exports daemon_start", r.exports.includes("daemon_start")); |
| 230 | + check("zero-task daemon still exports scheduled_tick", r.exports.includes("scheduled_tick")); |
| 231 | +} |
| 232 | + |
| 233 | +if (failures) { |
| 234 | + console.error(`\ndaemon codegen: ${failures} failure(s)`); |
| 235 | + process.exit(1); |
| 236 | +} |
| 237 | +console.log("\ndaemon codegen: all cases passed"); |
0 commit comments