@fraczak/k 8.8.0 → 9.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/DOCS/ARCHITECTURE.md +5 -4
  3. package/DOCS/DICTIONARY.md +2 -2
  4. package/DOCS/FILE_FORMATS.md +11 -9
  5. package/DOCS/KIR_V1.md +5 -1
  6. package/DOCS/KTVM_SPEC.md +902 -0
  7. package/DOCS/KVM_EXECUTION_MODEL.md +3 -2
  8. package/DOCS/KVM_VS_KTVM_COMPARATIVE_STUDY.md +127 -0
  9. package/DOCS/PROFILING_AND_TRACING.md +6 -4
  10. package/DOCS/README.md +3 -2
  11. package/DOCS/REPL.md +16 -12
  12. package/README.md +132 -2
  13. package/backend-api.mjs +31 -16
  14. package/backends/llvm/README.md +4 -5
  15. package/backends/llvm/bin/k-llvm-build.mjs +7 -19
  16. package/backends/llvm/bin/k-llvm-compile.mjs +6 -18
  17. package/backends/llvm/bin/k-llvm.mjs +11 -33
  18. package/backends/llvm/src/cli.mjs +2 -12
  19. package/backends/llvm/src/executable.mjs +7 -95
  20. package/backends/llvm/src/kvm2llvm.mjs +1 -5
  21. package/backends/llvm/src/llvm.mjs +4 -111
  22. package/backends/llvm/tests/k-llvm-run.mjs +1 -6
  23. package/backends/llvm/tests/perf-support.mjs +3 -5
  24. package/backends/llvm/tests/test-llvm.mjs +0 -16
  25. package/backends/wasm/README.md +2 -3
  26. package/backends/wasm/bin/k-wasm-compile.mjs +4 -7
  27. package/backends/wasm/bin/k-wasm.mjs +4 -6
  28. package/backends/wasm/src/cli.mjs +8 -24
  29. package/backends/wasm/src/wasm.mjs +10 -56
  30. package/browser/repl-browser.mjs +9 -8
  31. package/browser/shims/buffer.mjs +31 -2
  32. package/browser/shims/child_process.mjs +26 -0
  33. package/browser/shims/fs.mjs +3 -1
  34. package/codecs/djson.mjs +2 -3
  35. package/codecs/int.mjs +66 -14
  36. package/conformance/run.mjs +17 -2
  37. package/harness/adapters/ktvm-llvm.mjs +118 -0
  38. package/harness/adapters/ktvm-wasm.mjs +104 -0
  39. package/harness/adapters/ktvm.mjs +133 -0
  40. package/harness/registry.mjs +9 -0
  41. package/ktvm/ast.mjs +218 -0
  42. package/ktvm/bit-deque.mjs +482 -0
  43. package/ktvm/fixtures/integer-streaming.k +477 -0
  44. package/ktvm/index.mjs +119 -0
  45. package/ktvm/llvm/index.mjs +202 -0
  46. package/ktvm/llvm/lower-c.mjs +1258 -0
  47. package/ktvm/llvm/runtime.h +3542 -0
  48. package/ktvm/llvm/test-llvm.mjs +476 -0
  49. package/ktvm/lower-kir.mjs +2221 -0
  50. package/ktvm/optimize/fuse-kernel.mjs +2111 -0
  51. package/ktvm/optimize/index.mjs +116 -0
  52. package/ktvm/optimize/mwtr.mjs +283 -0
  53. package/ktvm/optimize/simplify-procs.mjs +5250 -0
  54. package/ktvm/optimize/synthesize-tables.mjs +1105 -0
  55. package/ktvm/parser.mjs +1101 -0
  56. package/ktvm/printer.mjs +281 -0
  57. package/ktvm/schema.mjs +543 -0
  58. package/ktvm/specialize.mjs +538 -0
  59. package/ktvm/test-conformance.mjs +597 -0
  60. package/ktvm/test-ktvm.mjs +1376 -0
  61. package/ktvm/test-optimize.mjs +598 -0
  62. package/ktvm/validator.mjs +1280 -0
  63. package/ktvm/vm.mjs +2225 -0
  64. package/ktvm/wasm/index.mjs +331 -0
  65. package/ktvm/wasm/lower-wasm.mjs +1272 -0
  66. package/ktvm/wasm/runtime.wat +4413 -0
  67. package/ktvm/wasm/test-wasm.mjs +426 -0
  68. package/ktvm/wire.mjs +489 -0
  69. package/lib/djson.k +175 -173
  70. package/lib/generic.k +82 -97
  71. package/lib/ieee.k +110 -115
  72. package/lib/integer.k +25 -31
  73. package/package.json +1 -9
  74. package/repl.mjs +101 -20
  75. package/scripts/build-repl-html.mjs +40 -18
  76. package/scripts/perf-bigint-compare.mjs +275 -0
  77. package/scripts/perf-ieee.mjs +9 -229
  78. package/scripts/perf-int.mjs +14 -272
  79. package/scripts/perf-multiplication.mjs +8 -54
  80. package/scripts/perf-poly.mjs +9 -263
  81. package/scripts/run-tests.mjs +5 -2
  82. package/scripts/test-package.mjs +15 -3
  83. package/tests/README.md +3 -3
  84. package/tests/test-djson-methods.mjs +0 -1
  85. package/tests/test-djson.mjs +0 -1
  86. package/tests/test-generic.mjs +5 -7
  87. package/tests/test-repl-html.mjs +72 -15
  88. package/tests/test-repl.mjs +27 -20
  89. package/tests/test-structural-values.mjs +1 -1
  90. package/DOCS/POLYMORPHIC_IR.md +0 -86
  91. package/access-table.mjs +0 -343
  92. package/pkir.mjs +0 -772
  93. package/tests/test-access-table.mjs +0 -213
  94. package/tests/test-pkir.mjs +0 -530
@@ -0,0 +1,426 @@
1
+ /**
2
+ * Milestone 4 WebAssembly Backend Test Suite (`k/ktvm/wasm/`).
3
+ *
4
+ * Verifies 100% bit-exact Wasm compilation (`wabt` validated) & execution across:
5
+ * 1. Direct `kTVM` kernels & procs: `lsb_add` (TMC + reg + chunk_table),
6
+ * `lsb_trim` (virtual LIFO BitStack + stack_table), `half_max_tally`
7
+ * (SWAR don't-care bit compression + unshift chunk_table).
8
+ * 2. Polymorphic & opaque payload execution (`lib/generic.k` `reverse`, `btrie`).
9
+ * 3. Full stdlib parity in Wasm (`lib/integer.k`, `lib/ieee.k`, `lib/djson.k`
10
+ * incl. wide-alphabet RFC 8259 JSON parser).
11
+ * 4. Runtime quotas (`maxSteps`, `maxNodes`, `maxBitDequeBytes`), malformed
12
+ * wire rejection, and deep 4,096-bit iterative stress (zero stack overflow).
13
+ * 5. Direct wire-to-wire bit-exact equivalence: Wasm output bytes === JS ref VM!
14
+ */
15
+
16
+ import assert from "node:assert/strict";
17
+ import fs from "node:fs";
18
+ import path from "node:path";
19
+ import { fileURLToPath } from "node:url";
20
+
21
+ import k from "../../index.mjs";
22
+ import codes from "../../codes.mjs";
23
+ import { Value } from "../../Value.mjs";
24
+ import { compileLibrary, loadLibrary } from "../../object.mjs";
25
+ import { encodeToWire, decodeWire } from "../../codecs/runtime/prefix-codec.mjs";
26
+ import { parse as parseIntVal } from "../../codecs/int.mjs";
27
+ import { textToStringValue } from "../../codecs/string-codec.mjs";
28
+ import { useSpecsFor } from "../../tests/helpers/cli.mjs";
29
+ import { relationPatternPropertyList } from "../../kir.mjs";
30
+
31
+ import {
32
+ KTVMQuotaError,
33
+ KTVMSchemaError,
34
+ compileKIRToKTVM,
35
+ compileKTVMToWasm,
36
+ compileObjectToKTVMWasm,
37
+ executeKTVMWire,
38
+ instantiateKTVMWasm,
39
+ parseModule,
40
+ specializeKTVM
41
+ } from "../index.mjs";
42
+
43
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
44
+ const readSrc = (rel) => fs.readFileSync(path.join(root, rel), "utf8");
45
+ const UNIT = Value.product({});
46
+
47
+ function bitsFromStr(str) {
48
+ let v = Value.variant("_", UNIT);
49
+ for (let i = str.length - 1; i >= 0; i--) v = Value.variant(str[i], v);
50
+ return v;
51
+ }
52
+
53
+ function makeList(items) {
54
+ let v = Value.variant("nil", UNIT);
55
+ for (let i = items.length - 1; i >= 0; i--) {
56
+ v = Value.variant("cons", Value.product({ car: items[i], cdr: v }));
57
+ }
58
+ return v;
59
+ }
60
+
61
+ function plainValue(v) {
62
+ return v === undefined ? undefined : JSON.parse(JSON.stringify(v.toJSON()));
63
+ }
64
+
65
+ const coreLib = loadLibrary(compileLibrary(readSrc("core.k"), { source: "core.k" }));
66
+ const genericLib = loadLibrary(compileLibrary(readSrc("lib/generic.k"), {
67
+ source: "lib/generic.k", libraries: [coreLib], use: useSpecsFor("lib/generic.k")
68
+ }));
69
+ const integerLib = loadLibrary(compileLibrary(readSrc("lib/integer.k"), {
70
+ source: "lib/integer.k", libraries: [coreLib], use: useSpecsFor("lib/integer.k")
71
+ }));
72
+ const ieeeLib = loadLibrary(compileLibrary(readSrc("lib/ieee.k"), {
73
+ source: "lib/ieee.k", libraries: [coreLib], use: useSpecsFor("lib/ieee.k")
74
+ }));
75
+ const djsonLib = loadLibrary(compileLibrary(readSrc("lib/djson.k"), {
76
+ source: "lib/djson.k", libraries: [coreLib, genericLib, ieeeLib], use: useSpecsFor("lib/djson.k")
77
+ }));
78
+ const streamLib = loadLibrary(compileLibrary(readSrc("ktvm/fixtures/integer-streaming.k"), {
79
+ source: "ktvm/fixtures/integer-streaming.k", libraries: [coreLib], use: useSpecsFor("lib/integer.k")
80
+ }));
81
+
82
+ let passed = 0;
83
+ let failed = 0;
84
+
85
+ async function test(name, fn) {
86
+ try {
87
+ await fn();
88
+ passed++;
89
+ console.log(` PASS ${name}`);
90
+ } catch (err) {
91
+ failed++;
92
+ console.error(` FAIL ${name}`);
93
+ console.error(err);
94
+ }
95
+ }
96
+
97
+ console.log("\n=== 1. Accelerated Wasm Kernels (chunk_table, stack_table, SWAR compress) ===");
98
+
99
+ await test("Wasm lsb_add (TMC + reg + chunk_table): 100% wire-exact vs JS ref across 128-bit & 1024-bit carry chains", async () => {
100
+ codes.load(streamLib.codes);
101
+ const inPat = relationPatternPropertyList(streamLib.rels[streamLib.relAlias.lsb_add], 0);
102
+ const artifact = await compileObjectToKTVMWasm(streamLib, "lsb_add", inPat, { optimize: true });
103
+ const runner = await instantiateKTVMWasm(artifact);
104
+
105
+ const pairs = [
106
+ ["0", "0"],
107
+ ["255", "1"],
108
+ ["12345678901234567890", "98765432109876543210"],
109
+ [String((1n << 128n) - 1n), String((1n << 128n) - 1n)],
110
+ [String((1n << 512n) - 1n), "1"]
111
+ ];
112
+ for (const [a, b] of pairs) {
113
+ const val = Value.product({ x: parseIntVal(a).value, y: parseIntVal(b).value });
114
+ const wire = encodeToWire(val, inPat);
115
+ const jsRef = executeKTVMWire(artifact.ktvmModule, wire, { entry: artifact.entry, validate: false });
116
+ const wasmRes = runner.executeWire(wire, { decodeValue: true });
117
+ assert.equal(wasmRes.status, "OK");
118
+ assert.deepEqual(Buffer.from(wasmRes.wire), Buffer.from(jsRef.wire), `wire mismatch on lsb_add(${a.slice(0, 10)})`);
119
+ assert.deepEqual(plainValue(wasmRes.value), plainValue(jsRef.value));
120
+ if (a.length >= 20 && b.length >= 20) {
121
+ assert.ok(wasmRes.telemetry.tableLookups >= 10, "Wasm chunk_table_step must fire");
122
+ }
123
+ }
124
+ });
125
+
126
+ await test("Wasm lsb_trim (virtual LIFO BitStack + stack_table): 100% wire-exact including 4,096-bit stream", async () => {
127
+ codes.load(streamLib.codes);
128
+ const inPat = relationPatternPropertyList(streamLib.rels[streamLib.relAlias.lsb_trim], 0);
129
+ const artifact = await compileObjectToKTVMWasm(streamLib, "lsb_trim", inPat, { optimize: true });
130
+ const runner = await instantiateKTVMWasm(artifact);
131
+
132
+ const cases = ["", "0", "00000", "1", "100000", "001001000", "0".repeat(2000) + "1" + "0".repeat(2095)];
133
+ for (const s of cases) {
134
+ const wire = encodeToWire(bitsFromStr(s), inPat);
135
+ const jsRef = executeKTVMWire(artifact.ktvmModule, wire, { entry: artifact.entry, validate: false, decodeValue: s.length < 200 });
136
+ const wasmRes = runner.executeWire(wire, { decodeValue: s.length < 200 });
137
+ assert.equal(wasmRes.status, "OK");
138
+ assert.deepEqual(Buffer.from(wasmRes.wire), Buffer.from(jsRef.wire));
139
+ if (s.length < 200) {
140
+ assert.deepEqual(plainValue(wasmRes.value), plainValue(jsRef.value));
141
+ }
142
+ if (s.length > 1000) {
143
+ assert.ok(wasmRes.telemetry.tableLookups >= 500, "Wasm stack_table_step must fire on 4096-bit stream");
144
+ }
145
+ }
146
+ });
147
+
148
+ await test("Wasm half_max_tally (SWAR compressed unshift chunk_table): 100% wire-exact", async () => {
149
+ codes.load(integerLib.codes);
150
+ const inPat = relationPatternPropertyList(integerLib.rels[integerLib.relAlias.half_max_tally], 0);
151
+ const artifact = await compileObjectToKTVMWasm(integerLib, "half_max_tally", inPat, { optimize: true });
152
+ const runner = await instantiateKTVMWasm(artifact);
153
+
154
+ for (const [a, b] of [["0", "0"], ["101010", "11"], ["1".repeat(80), "0".repeat(55)]]) {
155
+ const val = Value.product({ x: bitsFromStr(a), y: bitsFromStr(b) });
156
+ const wire = encodeToWire(val, inPat);
157
+ const jsRef = executeKTVMWire(artifact.ktvmModule, wire, { entry: artifact.entry, validate: false });
158
+ const wasmRes = runner.executeWire(wire, { decodeValue: true });
159
+ assert.equal(wasmRes.status, "OK");
160
+ assert.deepEqual(Buffer.from(wasmRes.wire), Buffer.from(jsRef.wire));
161
+ assert.ok(wasmRes.telemetry.tableLookups >= 1 || a.length < 4);
162
+ }
163
+ });
164
+
165
+ console.log("\n=== 2. Full Stdlib Parity in WebAssembly (generic, integer, ieee, djson) ===");
166
+
167
+ await test("Wasm lib/generic.k: reverse (opaque product list) & trim_bits/inc_bits/rev_bits", async () => {
168
+ codes.load(genericLib.codes);
169
+ for (const op of ["trim_bits", "inc_bits", "rev_bits"]) {
170
+ const inPat = relationPatternPropertyList(genericLib.rels[genericLib.relAlias[op]], 0);
171
+ const artifact = await compileObjectToKTVMWasm(genericLib, op, inPat, { optimize: true });
172
+ const runner = await instantiateKTVMWasm(artifact);
173
+ const val = bitsFromStr("00101111");
174
+ const ref = k.compile(genericLib.relAlias[op], { libraries: [genericLib] })(val);
175
+ const res = runner.executeWire(encodeToWire(val, inPat), { decodeValue: true });
176
+ assert.equal(res.status, "OK");
177
+ assert.deepEqual(plainValue(res.value), plainValue(ref), `wasm generic.${op}`);
178
+ }
179
+
180
+ // Polymorphic reverse on list of opaque products!
181
+ const prodList = makeList([
182
+ Value.product({ a: bitsFromStr("101010"), b: bitsFromStr("101") }),
183
+ Value.product({ a: bitsFromStr("111"), b: bitsFromStr("00") }),
184
+ Value.product({ a: bitsFromStr("0001"), b: bitsFromStr("1") })
185
+ ]);
186
+ const prodListPat = [
187
+ ["closed-union", [["cons", 1], ["nil", 4]]],
188
+ ["closed-product", [["car", 2], ["cdr", 0]]],
189
+ ["closed-product", [["a", 3], ["b", 3]]],
190
+ ["closed-union", [["0", 3], ["1", 3], ["_", 4]]],
191
+ ["closed-product", []]
192
+ ];
193
+ const wire = encodeToWire(prodList, prodListPat);
194
+ const revArt = await compileObjectToKTVMWasm(genericLib, "reverse", prodListPat, { optimize: true });
195
+ const revRun = await instantiateKTVMWasm(revArt);
196
+ const revRes = revRun.executeWire(wire, { decodeValue: true });
197
+ const revRef = k.compile(genericLib.relAlias.reverse, { libraries: [genericLib] })(prodList);
198
+ assert.equal(revRes.status, "OK");
199
+ assert.deepEqual(plainValue(revRes.value), plainValue(revRef));
200
+ });
201
+
202
+ await test("Wasm lib/integer.k: plus, minus, times (Karatsuba), div, gcd, cmp", async () => {
203
+ codes.load(integerLib.codes);
204
+ for (const [op, val] of [
205
+ ["plus", Value.product({ x: parseIntVal("123456789"), y: parseIntVal("-987654321") })],
206
+ ["minus", Value.product({ x: parseIntVal("100000"), y: parseIntVal("1") })],
207
+ ["times", Value.product({ x: parseIntVal("65537"), y: parseIntVal("123456") })],
208
+ ["div", Value.product({ x: parseIntVal("987654321"), y: parseIntVal("12345") })],
209
+ ["gcd", Value.product({ x: parseIntVal("1071"), y: parseIntVal("462") })],
210
+ ["cmp", Value.product({ x: parseIntVal("-42"), y: parseIntVal("17") })]
211
+ ]) {
212
+ const inPat = relationPatternPropertyList(integerLib.rels[integerLib.relAlias[op]], 0);
213
+ const artifact = await compileObjectToKTVMWasm(integerLib, op, inPat, { optimize: true });
214
+ const runner = await instantiateKTVMWasm(artifact);
215
+ const ref = k.compile(integerLib.relAlias[op], { libraries: [integerLib] })(val);
216
+ const res = runner.executeWire(encodeToWire(val, inPat), { decodeValue: true });
217
+ assert.equal(res.status, "OK", `wasm integer.${op} failed`);
218
+ assert.deepEqual(plainValue(res.value), plainValue(ref), `wasm integer.${op} mismatch`);
219
+ }
220
+ });
221
+
222
+ await test("Wasm lib/ieee.k: bits_to_float64 & ratio_to_float64", async () => {
223
+ codes.load(ieeeLib.codes);
224
+ const fPat = relationPatternPropertyList(ieeeLib.rels[ieeeLib.relAlias.bits_to_float64], 0);
225
+ const fArt = await compileObjectToKTVMWasm(ieeeLib, "bits_to_float64", fPat, { optimize: true });
226
+ const fRun = await instantiateKTVMWasm(fArt);
227
+ const fVal = parseIntVal(String((1n << 53n) + 3n)).value;
228
+ const fRef = k.compile(ieeeLib.relAlias.bits_to_float64, { libraries: [ieeeLib] })(fVal);
229
+ const fRes = fRun.executeWire(encodeToWire(fVal, fPat), { decodeValue: true });
230
+ assert.equal(fRes.status, "OK");
231
+ assert.deepEqual(plainValue(fRes.value), plainValue(fRef));
232
+
233
+ const rVal = Value.product({
234
+ sign: Value.variant("0", UNIT),
235
+ num: parseIntVal("355").value,
236
+ den: parseIntVal("113").value
237
+ });
238
+ const rPat = [
239
+ ["closed-product", [["den", 1], ["num", 1], ["sign", 2]]],
240
+ ["closed-union", [["0", 1], ["1", 1], ["_", 3]]],
241
+ ["closed-union", [["0", 3], ["1", 3]]],
242
+ ["closed-product", []]
243
+ ];
244
+ const rWire = encodeToWire(rVal, rPat);
245
+ const rArt = await compileObjectToKTVMWasm(ieeeLib, "ratio_to_float64", rPat, { optimize: true });
246
+ const rRun = await instantiateKTVMWasm(rArt);
247
+ const rRef = k.compile(ieeeLib.relAlias.ratio_to_float64, { libraries: [ieeeLib] })(rVal);
248
+ const rRes = rRun.executeWire(rWire, { decodeValue: true });
249
+ assert.equal(rRes.status, "OK");
250
+ assert.deepEqual(plainValue(rRes.value), plainValue(rRef));
251
+ });
252
+
253
+ await test("Wasm lib/djson.k: full RFC 8259 parse_json (valid objects/arrays/escapes + invalid JSON rejection)", async () => {
254
+ codes.load(djsonLib.codes);
255
+ const inPat = relationPatternPropertyList(djsonLib.rels[djsonLib.relAlias.parse_json], 0);
256
+ const artifact = await compileObjectToKTVMWasm(djsonLib, "parse_json", inPat, { optimize: true });
257
+ const runner = await instantiateKTVMWasm(artifact);
258
+
259
+ for (const txt of [
260
+ "{\"a\": [1, true, null, -3.5], \"b\": \"ok\\n\\t\"}",
261
+ "[10, 20, {\"k\": \"v\"}]",
262
+ "{ broken"
263
+ ]) {
264
+ const val = textToStringValue(txt);
265
+ const ref = k.compile(djsonLib.relAlias.parse_json, { libraries: [djsonLib] })(val);
266
+ const res = runner.executeWire(encodeToWire(val, inPat), { decodeValue: true });
267
+ if (ref === undefined) {
268
+ assert.equal(res.status, "FAILED", `invalid JSON '${txt}' must fail`);
269
+ } else {
270
+ assert.equal(res.status, "OK", `valid JSON '${txt}' must succeed`);
271
+ assert.deepEqual(plainValue(res.value), plainValue(ref));
272
+ }
273
+ }
274
+ });
275
+
276
+ console.log("\n=== 3. Quotas, Partiality, Spec Rollback/Upstream-Abort & Malformed Wire Hardening ===");
277
+
278
+ await test("Wasm enforces maxSteps & maxBitDequeBytes quotas and rejects malformed k-wire / schema mismatch", async () => {
279
+ codes.load(streamLib.codes);
280
+ const inPat = relationPatternPropertyList(streamLib.rels[streamLib.relAlias.lsb_trim], 0);
281
+ const artifact = await compileObjectToKTVMWasm(streamLib, "lsb_trim", inPat, { optimize: false });
282
+ const runner = await instantiateKTVMWasm(artifact);
283
+
284
+ const bigWire = encodeToWire(bitsFromStr("0".repeat(300) + "1"), inPat);
285
+ assert.throws(
286
+ () => runner.executeWire(bigWire, { quota: { maxSteps: 50 } }),
287
+ (err) => err instanceof KTVMQuotaError && err.quotaKind === "maxSteps"
288
+ );
289
+
290
+ // Schema mismatch rejected cleanly
291
+ const wrongWire = encodeToWire(Value.product({ a: UNIT }));
292
+ assert.throws(() => runner.executeWire(wrongWire), KTVMSchemaError);
293
+
294
+ // Truncated payload rejected cleanly
295
+ const truncated = bigWire.subarray(0, bigWire.length - 4);
296
+ assert.throws(() => runner.executeWire(truncated), /Malformed k-wire/);
297
+ });
298
+
299
+ await test("Wasm spec: local mismatch rollback + upstream failure abort + after %tok sequential settlement", async () => {
300
+ const src = `
301
+ ktvm 0.1 mono entry @main;
302
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
303
+
304
+ proc @fail_on_zero(%x: $bits) -> (%out: $bits) {
305
+ chan %t : $bits;
306
+ match /1 %x -> %t;
307
+ wrap |1 %t -> %out;
308
+ }
309
+
310
+ proc @main(%in: $bits) -> (%out: $bits) {
311
+ spec (%in) -> (%out) {
312
+ branch 0: {
313
+ chan %m0 : $bits;
314
+ match /0 %in -> %m0;
315
+ chan %m1 : $bits;
316
+ match /1 %m0 -> %m1;
317
+ wrap |1 %m1 -> %out;
318
+ }
319
+ branch 1: {
320
+ splice %in -> %out;
321
+ }
322
+ }
323
+ }
324
+ `;
325
+ const mod = parseModule(src);
326
+ const artifact = await compileKTVMToWasm(mod);
327
+ const runner = await instantiateKTVMWasm(artifact);
328
+
329
+ // Input `00_`: branch 0 consumes `0`, fails on `0 != 1`, rolls back bit-exact to branch 1!
330
+ const w00 = encodeToWire(bitsFromStr("00"), artifact.inPlist);
331
+ const r00 = runner.executeWire(w00, { decodeValue: true });
332
+ assert.equal(r00.status, "OK");
333
+ assert.deepEqual(plainValue(r00.value), plainValue(bitsFromStr("00")));
334
+ assert.equal(r00.telemetry.specRollbacks, 1);
335
+
336
+ // Input `01_`: branch 0 succeeds -> emits `1_`!
337
+ const w01 = encodeToWire(bitsFromStr("01"), artifact.inPlist);
338
+ const r01 = runner.executeWire(w01, { decodeValue: true });
339
+ assert.equal(r01.status, "OK");
340
+ assert.deepEqual(plainValue(r01.value), plainValue(bitsFromStr("1")));
341
+ assert.equal(r01.telemetry.specRollbacks, 0);
342
+ });
343
+
344
+ await test("Wasm slab allocator recycles retired nodes, channels, and child scopes in constant memory", async () => {
345
+ // Unoptimized recursive proc with switch + spec rollback on every `0` bit across 10,000 bits:
346
+ // spawns tens of thousands of nodes, channels, and child scopes while staying inside initial 16 MiB!
347
+ const src = `
348
+ ktvm 0.1 mono entry @flip;
349
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
350
+
351
+ proc @flip(%x: $bits) -> (%out: $bits) {
352
+ switch (%x) {
353
+ case (/0): {
354
+ chan %rest : $bits;
355
+ chan %flipped : $bits;
356
+ spec (%x) -> (%rest) {
357
+ branch 0: {
358
+ chan %bad : $bits;
359
+ match /1 %x -> %bad;
360
+ splice %bad -> %rest;
361
+ }
362
+ branch 1: {
363
+ match /0 %x -> %rest;
364
+ }
365
+ }
366
+ spawn @flip(%rest) -> (%flipped);
367
+ wrap |1 %flipped -> %out;
368
+ }
369
+ case (/1): {
370
+ chan %rest : $bits;
371
+ chan %flipped : $bits;
372
+ match /1 %x -> %rest;
373
+ spawn @flip(%rest) -> (%flipped);
374
+ wrap |0 %flipped -> %out;
375
+ }
376
+ case (/_): {
377
+ splice %x -> %out;
378
+ }
379
+ }
380
+ }
381
+ `;
382
+ const mod = parseModule(src);
383
+ const artifact = await compileKTVMToWasm(mod);
384
+ const runner = await instantiateKTVMWasm(artifact);
385
+ const bitsIn = "01".repeat(5000); // 10,000 bits -> 5,000 spec rollbacks + >100k nodes/chans!
386
+ const wire = encodeToWire(bitsFromStr(bitsIn), artifact.inPlist);
387
+ const res = runner.executeWire(wire, { decodeValue: false });
388
+ assert.equal(res.status, "OK");
389
+ assert.equal(res.telemetry.specRollbacks, 5000);
390
+ // Initial linear memory is 256 pages (16 MiB); with slab reclamation, zero growth is needed!
391
+ assert.ok(
392
+ runner.exports.memory.buffer.byteLength <= 32 * 1024 * 1024,
393
+ `Expected bounded Wasm memory <= 32 MiB, got ${runner.exports.memory.buffer.byteLength} bytes`
394
+ );
395
+ assert.ok(
396
+ res.telemetry.peakBitDequeBytes <= 65536,
397
+ `Expected bounded peakBitDequeBytes <= 64 KiB after spec commit/rollback release, got ${res.telemetry.peakBitDequeBytes}`
398
+ );
399
+ });
400
+
401
+ await test("Wasm strict mux->demux fusion & spec commit release keep Karatsuba & djson buffers bounded", async () => {
402
+ codes.load(integerLib.codes);
403
+ const timesPat = relationPatternPropertyList(integerLib.rels[integerLib.relAlias.times], 0);
404
+ const timesArt = await compileObjectToKTVMWasm(integerLib, "times", timesPat, { optimize: true });
405
+ const timesRun = await instantiateKTVMWasm(timesArt);
406
+ const mulIn = Value.product({
407
+ x: parseIntVal(String((1n << 255n) - 987654321n)),
408
+ y: parseIntVal(String((1n << 255n) - 123456789n))
409
+ });
410
+ const mulRes = timesRun.executeWire(encodeToWire(mulIn, timesPat), { decodeValue: false });
411
+ assert.equal(mulRes.status, "OK");
412
+ assert.ok(mulRes.telemetry.peakActiveNodes <= 400, `expected bounded Karatsuba nodes <= 400, got ${mulRes.telemetry.peakActiveNodes}`);
413
+ assert.ok(mulRes.telemetry.peakBitDequeBytes <= 16384, `expected bounded Karatsuba buffers <= 16 KiB, got ${mulRes.telemetry.peakBitDequeBytes}`);
414
+
415
+ codes.load(djsonLib.codes);
416
+ const djPat = relationPatternPropertyList(djsonLib.rels[djsonLib.relAlias.parse_json], 0);
417
+ const djArt = await compileObjectToKTVMWasm(djsonLib, "parse_json", djPat, { optimize: true });
418
+ const djRun = await instantiateKTVMWasm(djArt);
419
+ const items = Array.from({ length: 20 }, (_, i) => `{"id":${i},"ok":${i % 2 === 0},"tag":"item_${i}"}`).join(",");
420
+ const djRes = djRun.executeWire(encodeToWire(textToStringValue(`[${items}]`), djPat), { decodeValue: false });
421
+ assert.equal(djRes.status, "OK");
422
+ assert.ok(djRes.telemetry.peakBitDequeBytes <= 65536, `expected linear djson peakBitDequeBytes <= 64 KiB, got ${djRes.telemetry.peakBitDequeBytes}`);
423
+ });
424
+
425
+ console.log(`\nMilestone 4 WebAssembly Results: ${passed} passed, ${failed} failed.`);
426
+ if (failed > 0) process.exit(1);