@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.
- package/CHANGELOG.md +28 -0
- package/DOCS/ARCHITECTURE.md +5 -4
- package/DOCS/DICTIONARY.md +2 -2
- package/DOCS/FILE_FORMATS.md +11 -9
- package/DOCS/KIR_V1.md +5 -1
- package/DOCS/KTVM_SPEC.md +902 -0
- package/DOCS/KVM_EXECUTION_MODEL.md +3 -2
- package/DOCS/KVM_VS_KTVM_COMPARATIVE_STUDY.md +127 -0
- package/DOCS/PROFILING_AND_TRACING.md +6 -4
- package/DOCS/README.md +3 -2
- package/DOCS/REPL.md +16 -12
- package/README.md +132 -2
- package/backend-api.mjs +31 -16
- package/backends/llvm/README.md +4 -5
- package/backends/llvm/bin/k-llvm-build.mjs +7 -19
- package/backends/llvm/bin/k-llvm-compile.mjs +6 -18
- package/backends/llvm/bin/k-llvm.mjs +11 -33
- package/backends/llvm/src/cli.mjs +2 -12
- package/backends/llvm/src/executable.mjs +7 -95
- package/backends/llvm/src/kvm2llvm.mjs +1 -5
- package/backends/llvm/src/llvm.mjs +4 -111
- package/backends/llvm/tests/k-llvm-run.mjs +1 -6
- package/backends/llvm/tests/perf-support.mjs +3 -5
- package/backends/llvm/tests/test-llvm.mjs +0 -16
- package/backends/wasm/README.md +2 -3
- package/backends/wasm/bin/k-wasm-compile.mjs +4 -7
- package/backends/wasm/bin/k-wasm.mjs +4 -6
- package/backends/wasm/src/cli.mjs +8 -24
- package/backends/wasm/src/wasm.mjs +10 -56
- package/browser/repl-browser.mjs +9 -8
- package/browser/shims/buffer.mjs +31 -2
- package/browser/shims/child_process.mjs +26 -0
- package/browser/shims/fs.mjs +3 -1
- package/codecs/djson.mjs +2 -3
- package/codecs/int.mjs +66 -14
- package/conformance/run.mjs +17 -2
- package/harness/adapters/ktvm-llvm.mjs +118 -0
- package/harness/adapters/ktvm-wasm.mjs +104 -0
- package/harness/adapters/ktvm.mjs +133 -0
- package/harness/registry.mjs +9 -0
- package/ktvm/ast.mjs +218 -0
- package/ktvm/bit-deque.mjs +482 -0
- package/ktvm/fixtures/integer-streaming.k +477 -0
- package/ktvm/index.mjs +119 -0
- package/ktvm/llvm/index.mjs +202 -0
- package/ktvm/llvm/lower-c.mjs +1258 -0
- package/ktvm/llvm/runtime.h +3542 -0
- package/ktvm/llvm/test-llvm.mjs +476 -0
- package/ktvm/lower-kir.mjs +2221 -0
- package/ktvm/optimize/fuse-kernel.mjs +2111 -0
- package/ktvm/optimize/index.mjs +116 -0
- package/ktvm/optimize/mwtr.mjs +283 -0
- package/ktvm/optimize/simplify-procs.mjs +5250 -0
- package/ktvm/optimize/synthesize-tables.mjs +1105 -0
- package/ktvm/parser.mjs +1101 -0
- package/ktvm/printer.mjs +281 -0
- package/ktvm/schema.mjs +543 -0
- package/ktvm/specialize.mjs +538 -0
- package/ktvm/test-conformance.mjs +597 -0
- package/ktvm/test-ktvm.mjs +1376 -0
- package/ktvm/test-optimize.mjs +598 -0
- package/ktvm/validator.mjs +1280 -0
- package/ktvm/vm.mjs +2225 -0
- package/ktvm/wasm/index.mjs +331 -0
- package/ktvm/wasm/lower-wasm.mjs +1272 -0
- package/ktvm/wasm/runtime.wat +4413 -0
- package/ktvm/wasm/test-wasm.mjs +426 -0
- package/ktvm/wire.mjs +489 -0
- package/lib/djson.k +175 -173
- package/lib/generic.k +82 -97
- package/lib/ieee.k +110 -115
- package/lib/integer.k +25 -31
- package/package.json +1 -9
- package/repl.mjs +101 -20
- package/scripts/build-repl-html.mjs +40 -18
- package/scripts/perf-bigint-compare.mjs +275 -0
- package/scripts/perf-ieee.mjs +9 -229
- package/scripts/perf-int.mjs +14 -272
- package/scripts/perf-multiplication.mjs +8 -54
- package/scripts/perf-poly.mjs +9 -263
- package/scripts/run-tests.mjs +5 -2
- package/scripts/test-package.mjs +15 -3
- package/tests/README.md +3 -3
- package/tests/test-djson-methods.mjs +0 -1
- package/tests/test-djson.mjs +0 -1
- package/tests/test-generic.mjs +5 -7
- package/tests/test-repl-html.mjs +72 -15
- package/tests/test-repl.mjs +27 -20
- package/tests/test-structural-values.mjs +1 -1
- package/DOCS/POLYMORPHIC_IR.md +0 -86
- package/access-table.mjs +0 -343
- package/pkir.mjs +0 -772
- package/tests/test-access-table.mjs +0 -213
- package/tests/test-pkir.mjs +0 -530
|
@@ -0,0 +1,1376 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Comprehensive Milestone 1 test suite for standalone `kTVM` (`k/ktvm/`).
|
|
3
|
+
*
|
|
4
|
+
* Covers:
|
|
5
|
+
* 1. Parser, printer, and canonical JSON (`format: "k-tvm"`) round-trip on all
|
|
6
|
+
* 4 worked examples from DOCS/KTVM_SPEC.md §10.
|
|
7
|
+
* 2. Static validator positive & negative checks (SPSC linearity, local DAG
|
|
8
|
+
* acyclicity, mono schema strictness, dual-schema typing, and always-on
|
|
9
|
+
* static table-to-CFG bisimulation verification).
|
|
10
|
+
* 3. Polymorphism & boundary specialization (`reverse.ktvmp` on `list[int[]]`
|
|
11
|
+
* and `list[product{a:int[], b:bits[]}]`, opaque preservation, cache hits,
|
|
12
|
+
* `KTVMSchemaError` on incompatible envelopes, `project`, `guard`, dead
|
|
13
|
+
* `switch` arm pruning, Moore-equivalent `coerce -> splice`).
|
|
14
|
+
* 4. Operational semantics & zero-copy rewrites (O(1) tail-splice in `reverse`,
|
|
15
|
+
* same-scope `MUX -> DEMUX` bundle fusion, strict partiality `drain`/`barrier`/`gate`,
|
|
16
|
+
* `spec` local rollback + upstream-failure abort + tail-splice, `tee` fan-out,
|
|
17
|
+
* `after %tok` bounded-node sequential sibling settlement).
|
|
18
|
+
* 5. Compiled kernels (`_lsb_add` with bisimulation-verified `chunk_table` + O(1)
|
|
19
|
+
* tail splice, `_lsb_trim` with virtual LIFO `BitStack` + `stack_table`).
|
|
20
|
+
* 6. Hardening & quotas (`maxBitDequeBytes`, `maxNodes`, `maxSteps`, malformed
|
|
21
|
+
* `k-wire` envelopes, and 4,096-bit strictly iterative stress tests).
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import assert from "node:assert/strict";
|
|
25
|
+
import { Value } from "../Value.mjs";
|
|
26
|
+
import { encodeToWire, decodeWire, propertyListToPattern } from "../codecs/runtime/prefix-codec.mjs";
|
|
27
|
+
import {
|
|
28
|
+
KTVM_FORMAT,
|
|
29
|
+
KTVM_VERSION,
|
|
30
|
+
KTVMSyntaxError,
|
|
31
|
+
KTVMValidationError,
|
|
32
|
+
KTVMSchemaError,
|
|
33
|
+
KTVMQuotaError,
|
|
34
|
+
BitDeque,
|
|
35
|
+
BitStack,
|
|
36
|
+
parseModule,
|
|
37
|
+
printModule,
|
|
38
|
+
moduleToJSON,
|
|
39
|
+
moduleFromJSON,
|
|
40
|
+
packInt32Base64,
|
|
41
|
+
compileSchemaExprToPlist,
|
|
42
|
+
mooreKey,
|
|
43
|
+
schemasEquivalent,
|
|
44
|
+
validateModule,
|
|
45
|
+
specializeKTVM,
|
|
46
|
+
clearSpecializationCache,
|
|
47
|
+
executeKTVM,
|
|
48
|
+
executeKTVMWire,
|
|
49
|
+
splitEnvelopedWire,
|
|
50
|
+
encodePayloadToDeque,
|
|
51
|
+
decodeDequeToValue
|
|
52
|
+
} from "./index.mjs";
|
|
53
|
+
|
|
54
|
+
// --- Helpers to build K Values cleanly ---
|
|
55
|
+
|
|
56
|
+
const UNIT = Value.product({});
|
|
57
|
+
|
|
58
|
+
function bitsFromBigIntLSB(n) {
|
|
59
|
+
let v = BigInt(n);
|
|
60
|
+
const digits = [];
|
|
61
|
+
while (v > 0n) {
|
|
62
|
+
digits.push((v & 1n) === 1n ? "1" : "0");
|
|
63
|
+
v >>= 1n;
|
|
64
|
+
}
|
|
65
|
+
let cur = Value.variant("_", UNIT);
|
|
66
|
+
for (let i = digits.length - 1; i >= 0; i--) {
|
|
67
|
+
cur = Value.variant(digits[i], cur);
|
|
68
|
+
}
|
|
69
|
+
return cur;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function bitsToBigIntLSB(val) {
|
|
73
|
+
let acc = 0n;
|
|
74
|
+
let shift = 0n;
|
|
75
|
+
let cur = val;
|
|
76
|
+
while (cur.tag !== "_") {
|
|
77
|
+
if (cur.tag === "1") acc |= (1n << shift);
|
|
78
|
+
shift += 1n;
|
|
79
|
+
cur = cur.value;
|
|
80
|
+
}
|
|
81
|
+
return acc;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function bitsFromString(str) {
|
|
85
|
+
let cur = Value.variant("_", UNIT);
|
|
86
|
+
for (let i = str.length - 1; i >= 0; i--) {
|
|
87
|
+
cur = Value.variant(str[i], cur);
|
|
88
|
+
}
|
|
89
|
+
return cur;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function bitsToString(val) {
|
|
93
|
+
let s = "";
|
|
94
|
+
let cur = val;
|
|
95
|
+
while (cur.tag !== "_") {
|
|
96
|
+
s += cur.tag;
|
|
97
|
+
cur = cur.value;
|
|
98
|
+
}
|
|
99
|
+
return s;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function makeIntVal(n) {
|
|
103
|
+
const sign = n < 0 ? "-" : "+";
|
|
104
|
+
const mag = n < 0 ? -n : n;
|
|
105
|
+
return Value.variant(sign, bitsFromBigIntLSB(mag));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function intValToNumber(v) {
|
|
109
|
+
const mag = Number(bitsToBigIntLSB(v.value));
|
|
110
|
+
return v.tag === "-" ? -mag : mag;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function makeList(items) {
|
|
114
|
+
let cur = Value.variant("nil", UNIT);
|
|
115
|
+
for (let i = items.length - 1; i >= 0; i--) {
|
|
116
|
+
cur = Value.variant("cons", Value.product({ car: items[i], cdr: cur }));
|
|
117
|
+
}
|
|
118
|
+
return cur;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function listToArray(v) {
|
|
122
|
+
const out = [];
|
|
123
|
+
let cur = v;
|
|
124
|
+
while (cur.tag === "cons") {
|
|
125
|
+
out.push(cur.value.product.car);
|
|
126
|
+
cur = cur.value.product.cdr;
|
|
127
|
+
}
|
|
128
|
+
assert.equal(cur.tag, "nil");
|
|
129
|
+
return out;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// --- Test Harness ---
|
|
133
|
+
|
|
134
|
+
let passed = 0;
|
|
135
|
+
let failed = 0;
|
|
136
|
+
|
|
137
|
+
function test(name, fn) {
|
|
138
|
+
try {
|
|
139
|
+
fn();
|
|
140
|
+
passed++;
|
|
141
|
+
console.log(` PASS ${name}`);
|
|
142
|
+
} catch (err) {
|
|
143
|
+
failed++;
|
|
144
|
+
console.error(` FAIL ${name}`);
|
|
145
|
+
console.error(err);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// --- Reusable Worked-Example Modules ---
|
|
150
|
+
|
|
151
|
+
const REVERSE_KTVMP = `
|
|
152
|
+
ktvm 0.1 poly entry @reverse;
|
|
153
|
+
|
|
154
|
+
schema $list[$X] = union {
|
|
155
|
+
cons: product { car: $X, cdr: $list[$X] },
|
|
156
|
+
nil: unit
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
proc @reverse[$X](%in: $list[$X]) -> (%out: $list[$X]) {
|
|
160
|
+
chan %acc_u : unit;
|
|
161
|
+
chan %acc : $list[$X];
|
|
162
|
+
const_unit -> %acc_u;
|
|
163
|
+
wrap |nil %acc_u -> %acc;
|
|
164
|
+
spawn @_reverse[$X](%in, %acc) -> (%out);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
proc @_reverse[$X](%xs: $list[$X], %acc: $list[$X]) -> (%out: $list[$X]) {
|
|
168
|
+
switch (%xs) {
|
|
169
|
+
case (/nil): {
|
|
170
|
+
chan %u : unit;
|
|
171
|
+
barrier %b;
|
|
172
|
+
match /nil %xs -> %u;
|
|
173
|
+
drain %u : unit -> %b;
|
|
174
|
+
gate %b, %acc -> %out;
|
|
175
|
+
}
|
|
176
|
+
case (/cons): {
|
|
177
|
+
chan %cell : product { car: $X, cdr: $list[$X] };
|
|
178
|
+
chan %car : $X;
|
|
179
|
+
chan %cdr : $list[$X];
|
|
180
|
+
chan %newcell : product { car: $X, cdr: $list[$X] };
|
|
181
|
+
chan %newacc : $list[$X];
|
|
182
|
+
match /cons %xs -> %cell;
|
|
183
|
+
demux %cell : product { car: $X, cdr: $list[$X] } -> (car: %car, cdr: %cdr);
|
|
184
|
+
mux (car: %car, cdr: %acc) -> %newcell : product { car: $X, cdr: $list[$X] };
|
|
185
|
+
wrap |cons %newcell -> %newacc;
|
|
186
|
+
spawn @_reverse[$X](%cdr, %newacc) -> (%out);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
`;
|
|
191
|
+
|
|
192
|
+
// Build a real, exact 2-bit x 2-bit (1 tag per port, 32 entries) chunk_table for `_lsb_add`!
|
|
193
|
+
function buildLsbAdd2x2Entries() {
|
|
194
|
+
// Tag codes: 0 -> 0b00 (0), 1 -> 0b01 (1), _ -> 0b10 (2), 0b11 (3) = invalid
|
|
195
|
+
// Exits: 0 = exit_zero_done, 1 = exit_carry_done, 2 = exit_splice_y, 3 = exit_splice_x
|
|
196
|
+
const rows = [];
|
|
197
|
+
for (let c = 0; c < 2; c++) {
|
|
198
|
+
for (let tx = 0; tx < 4; tx++) {
|
|
199
|
+
for (let ty = 0; ty < 4; ty++) {
|
|
200
|
+
const idx = (c << 4) | (tx << 2) | ty;
|
|
201
|
+
if (tx === 3 || ty === 3) {
|
|
202
|
+
rows.push(`${idx} => { kind: FAIL };`);
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
if (tx === 2 && ty === 2) {
|
|
206
|
+
rows.push(`${idx} => { kind: EXIT, exit: ${c}, shift: [2, 2], emit_word: [0], emit_len: [0] };`);
|
|
207
|
+
} else if (tx === 2) {
|
|
208
|
+
if (c === 0) {
|
|
209
|
+
rows.push(`${idx} => { kind: EXIT, exit: 2, shift: [2, 0], emit_word: [0], emit_len: [0] };`);
|
|
210
|
+
} else {
|
|
211
|
+
const sum = ty + 1;
|
|
212
|
+
const outTag = sum & 1; // 0->0b00, 1->0b01
|
|
213
|
+
const nextC = sum >> 1;
|
|
214
|
+
rows.push(`${idx} => { kind: CONT, next_q: ${nextC}, shift: [0, 2], emit_word: [${outTag}], emit_len: [2] };`);
|
|
215
|
+
}
|
|
216
|
+
} else if (ty === 2) {
|
|
217
|
+
if (c === 0) {
|
|
218
|
+
rows.push(`${idx} => { kind: EXIT, exit: 3, shift: [0, 2], emit_word: [0], emit_len: [0] };`);
|
|
219
|
+
} else {
|
|
220
|
+
const sum = tx + 1;
|
|
221
|
+
const outTag = sum & 1;
|
|
222
|
+
const nextC = sum >> 1;
|
|
223
|
+
rows.push(`${idx} => { kind: CONT, next_q: ${nextC}, shift: [2, 0], emit_word: [${outTag}], emit_len: [2] };`);
|
|
224
|
+
}
|
|
225
|
+
} else {
|
|
226
|
+
const sum = tx + ty + c;
|
|
227
|
+
const outTag = sum & 1;
|
|
228
|
+
const nextC = sum >> 1;
|
|
229
|
+
rows.push(`${idx} => { kind: CONT, next_q: ${nextC}, shift: [2, 2], emit_word: [${outTag}], emit_len: [2] };`);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return rows.join("\n ");
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function makeLsbAddModule(tableEntriesStr) {
|
|
238
|
+
return `
|
|
239
|
+
ktvm 0.1 mono entry @lsb_add;
|
|
240
|
+
|
|
241
|
+
schema $bits = union { 0: $bits, 1: $bits, _: unit };
|
|
242
|
+
|
|
243
|
+
proc @lsb_add(%x: $bits, %y: $bits) -> (%out: $bits) total {
|
|
244
|
+
exec @_lsb_add_kernel(%x, %y) -> (%out);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
kernel @_lsb_add_kernel(%x: $bits, %y: $bits) -> (%out: $bits) total tmc {
|
|
248
|
+
reg c : enum(2) = 0;
|
|
249
|
+
|
|
250
|
+
entry:
|
|
251
|
+
yield %out, 64;
|
|
252
|
+
table_step &tab_lsb_add, c, (%x, %y), (%out) -> exits {
|
|
253
|
+
short: slow_step,
|
|
254
|
+
0: exit_zero_done,
|
|
255
|
+
1: exit_carry_done,
|
|
256
|
+
2: exit_splice_y,
|
|
257
|
+
3: exit_splice_x,
|
|
258
|
+
fail: err
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
slow_step:
|
|
262
|
+
%tx = peek_bits %x, @0, 2 else err;
|
|
263
|
+
%ty = peek_bits %y, @0, 2 else err;
|
|
264
|
+
switch_bits %tx {
|
|
265
|
+
case 0b10: goto x_end;
|
|
266
|
+
case 0b00: goto x_0;
|
|
267
|
+
case 0b01: goto x_1;
|
|
268
|
+
default: goto err;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
x_end:
|
|
272
|
+
switch_bits %ty {
|
|
273
|
+
case 0b10: goto both_end;
|
|
274
|
+
case 0b00: goto x_end_y_nz;
|
|
275
|
+
case 0b01: goto x_end_y_nz;
|
|
276
|
+
default: goto err;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
both_end:
|
|
280
|
+
shift_tag %x, 2 -> unit;
|
|
281
|
+
shift_tag %y, 2 -> unit;
|
|
282
|
+
drain_guard %x : unit;
|
|
283
|
+
drain_guard %y : unit;
|
|
284
|
+
switch_reg c {
|
|
285
|
+
case 0: goto exit_zero_done;
|
|
286
|
+
case 1: goto exit_carry_done;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
x_end_y_nz:
|
|
290
|
+
switch_reg c {
|
|
291
|
+
case 0: goto x_end_splice_y;
|
|
292
|
+
case 1: goto x_end_prop_carry;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
x_end_splice_y:
|
|
296
|
+
shift_tag %x, 2 -> unit;
|
|
297
|
+
drain_guard %x : unit;
|
|
298
|
+
goto exit_splice_y;
|
|
299
|
+
|
|
300
|
+
x_end_prop_carry:
|
|
301
|
+
shift_tag %y, 2 -> $bits;
|
|
302
|
+
switch_bits %ty {
|
|
303
|
+
case 0b00: goto emit_1_c0;
|
|
304
|
+
case 0b01: goto emit_0_c1;
|
|
305
|
+
default: goto err;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
x_0:
|
|
309
|
+
switch_bits %ty {
|
|
310
|
+
case 0b10: goto y_end_x0;
|
|
311
|
+
case 0b00: goto add_00;
|
|
312
|
+
case 0b01: goto add_01;
|
|
313
|
+
default: goto err;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
x_1:
|
|
317
|
+
switch_bits %ty {
|
|
318
|
+
case 0b10: goto y_end_x1;
|
|
319
|
+
case 0b00: goto add_01;
|
|
320
|
+
case 0b01: goto add_11;
|
|
321
|
+
default: goto err;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
y_end_x0:
|
|
325
|
+
switch_reg c {
|
|
326
|
+
case 0: goto y_end_splice_x;
|
|
327
|
+
case 1: goto y_end_x0_c1;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
y_end_x1:
|
|
331
|
+
switch_reg c {
|
|
332
|
+
case 0: goto y_end_splice_x;
|
|
333
|
+
case 1: goto y_end_x1_c1;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
y_end_splice_x:
|
|
337
|
+
shift_tag %y, 2 -> unit;
|
|
338
|
+
drain_guard %y : unit;
|
|
339
|
+
goto exit_splice_x;
|
|
340
|
+
|
|
341
|
+
y_end_x0_c1:
|
|
342
|
+
shift_tag %x, 2 -> $bits;
|
|
343
|
+
goto emit_1_c0;
|
|
344
|
+
|
|
345
|
+
y_end_x1_c1:
|
|
346
|
+
shift_tag %x, 2 -> $bits;
|
|
347
|
+
goto emit_0_c1;
|
|
348
|
+
|
|
349
|
+
add_00:
|
|
350
|
+
shift_tag %x, 2 -> $bits;
|
|
351
|
+
shift_tag %y, 2 -> $bits;
|
|
352
|
+
switch_reg c {
|
|
353
|
+
case 0: goto emit_0_c0;
|
|
354
|
+
case 1: goto emit_1_c0;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
add_01:
|
|
358
|
+
shift_tag %x, 2 -> $bits;
|
|
359
|
+
shift_tag %y, 2 -> $bits;
|
|
360
|
+
switch_reg c {
|
|
361
|
+
case 0: goto emit_1_c0;
|
|
362
|
+
case 1: goto emit_0_c1;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
add_11:
|
|
366
|
+
shift_tag %x, 2 -> $bits;
|
|
367
|
+
shift_tag %y, 2 -> $bits;
|
|
368
|
+
switch_reg c {
|
|
369
|
+
case 0: goto emit_0_c1;
|
|
370
|
+
case 1: goto emit_1_c1;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
emit_0_c0:
|
|
374
|
+
push_bits %out, 0b00, 2;
|
|
375
|
+
set_reg c, 0;
|
|
376
|
+
goto entry;
|
|
377
|
+
|
|
378
|
+
emit_1_c0:
|
|
379
|
+
push_bits %out, 0b01, 2;
|
|
380
|
+
set_reg c, 0;
|
|
381
|
+
goto entry;
|
|
382
|
+
|
|
383
|
+
emit_0_c1:
|
|
384
|
+
push_bits %out, 0b00, 2;
|
|
385
|
+
set_reg c, 1;
|
|
386
|
+
goto entry;
|
|
387
|
+
|
|
388
|
+
emit_1_c1:
|
|
389
|
+
push_bits %out, 0b01, 2;
|
|
390
|
+
set_reg c, 1;
|
|
391
|
+
goto entry;
|
|
392
|
+
|
|
393
|
+
exit_zero_done:
|
|
394
|
+
push_bits %out, 0b10, 2;
|
|
395
|
+
close %out;
|
|
396
|
+
retire;
|
|
397
|
+
|
|
398
|
+
exit_carry_done:
|
|
399
|
+
push_bits %out, 0b01, 2;
|
|
400
|
+
push_bits %out, 0b10, 2;
|
|
401
|
+
close %out;
|
|
402
|
+
retire;
|
|
403
|
+
|
|
404
|
+
exit_splice_y:
|
|
405
|
+
splice %y -> %out;
|
|
406
|
+
retire;
|
|
407
|
+
|
|
408
|
+
exit_splice_x:
|
|
409
|
+
splice %x -> %out;
|
|
410
|
+
retire;
|
|
411
|
+
|
|
412
|
+
err:
|
|
413
|
+
fail;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
table &tab_lsb_add chunk_table {
|
|
417
|
+
states: 2;
|
|
418
|
+
inputs: [
|
|
419
|
+
{ port: 0, raw_bits: 2, eff_bits: 2, compress: none },
|
|
420
|
+
{ port: 1, raw_bits: 2, eff_bits: 2, compress: none }
|
|
421
|
+
];
|
|
422
|
+
outputs: [ { port: 0, mode: push, max_emit_bits: 2 } ];
|
|
423
|
+
verified_against: @_lsb_add_kernel;
|
|
424
|
+
mwtr: { rho: 4.0, bytes: 128, budget_class: "L1" };
|
|
425
|
+
entries {
|
|
426
|
+
${tableEntriesStr}
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
`;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// Online virtual-stack `_lsb_trim` kernel with real `stack_table` (W_s = 2, W_k = 1, depth_only)
|
|
433
|
+
function buildLsbTrimStackTableEntries() {
|
|
434
|
+
// mode: 0 = scan, 1 = flush
|
|
435
|
+
// sBits (2b): 0=0b00 ('0'), 1=0b01 ('1'), 2=0b10 ('_'), 3=0b11 (invalid)
|
|
436
|
+
// depth_only (W_k = 1, stride = 2): d=0 (empty), d=1 (non-empty)
|
|
437
|
+
const rows = [];
|
|
438
|
+
for (let mode = 0; mode < 2; mode++) {
|
|
439
|
+
for (let sBits = 0; sBits < 4; sBits++) {
|
|
440
|
+
for (let d = 0; d < 2; d++) {
|
|
441
|
+
const idx = (((mode << 2) | sBits) * 2) + d;
|
|
442
|
+
if (mode === 1) {
|
|
443
|
+
// flush deferred '0's from stack before reading next input!
|
|
444
|
+
if (d === 1) {
|
|
445
|
+
rows.push(`${idx} => { kind: CONT, next_q: 1, shift_stream: 0, pop_stack: 1, push_stack_word: 0, push_stack_len: 0, emit_word: 0, emit_len: 2 };`);
|
|
446
|
+
} else {
|
|
447
|
+
// stack empty -> emit deferred '1', back to scan!
|
|
448
|
+
rows.push(`${idx} => { kind: CONT, next_q: 0, shift_stream: 0, pop_stack: 0, push_stack_word: 0, push_stack_len: 0, emit_word: 1, emit_len: 2 };`);
|
|
449
|
+
}
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
// mode === 0 (scan)
|
|
453
|
+
if (sBits === 3) {
|
|
454
|
+
rows.push(`${idx} => { kind: FAIL };`);
|
|
455
|
+
} else if (sBits === 2) {
|
|
456
|
+
// '_': exit to scan_eof (clears stack and emits '_')
|
|
457
|
+
rows.push(`${idx} => { kind: EXIT, exit: 0, shift_stream: 2, pop_stack: 0, push_stack_word: 0, push_stack_len: 0, emit_word: 0, emit_len: 0 };`);
|
|
458
|
+
} else if (sBits === 0) {
|
|
459
|
+
// '0': defer onto stack z
|
|
460
|
+
rows.push(`${idx} => { kind: CONT, next_q: 0, shift_stream: 2, pop_stack: 0, push_stack_word: 0, push_stack_len: 1, emit_word: 0, emit_len: 0 };`);
|
|
461
|
+
} else {
|
|
462
|
+
// '1': if stack empty emit '1' immediately; else pop 1 zero, emit '0', switch to flush!
|
|
463
|
+
if (d === 0) {
|
|
464
|
+
rows.push(`${idx} => { kind: CONT, next_q: 0, shift_stream: 2, pop_stack: 0, push_stack_word: 0, push_stack_len: 0, emit_word: 1, emit_len: 2 };`);
|
|
465
|
+
} else {
|
|
466
|
+
rows.push(`${idx} => { kind: CONT, next_q: 1, shift_stream: 2, pop_stack: 1, push_stack_word: 0, push_stack_len: 0, emit_word: 0, emit_len: 2 };`);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
return rows.join("\n ");
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
const LSB_TRIM_KTVM = `
|
|
476
|
+
ktvm 0.1 mono entry @lsb_trim;
|
|
477
|
+
|
|
478
|
+
schema $bits = union { 0: $bits, 1: $bits, _: unit };
|
|
479
|
+
|
|
480
|
+
proc @lsb_trim(%in: $bits) -> (%out: $bits) total {
|
|
481
|
+
exec @_lsb_trim_kernel(%in) -> (%out);
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
kernel @_lsb_trim_kernel(%in: $bits) -> (%out: $bits) total tmc {
|
|
485
|
+
reg mode : enum(2) = 0;
|
|
486
|
+
stack z : bits;
|
|
487
|
+
|
|
488
|
+
entry:
|
|
489
|
+
yield %out, 64;
|
|
490
|
+
stack_table_step &tab_lsb_trim, mode, %in, z, %out -> exits {
|
|
491
|
+
short: slow_step,
|
|
492
|
+
0: exit_eof_after_shift,
|
|
493
|
+
fail: err
|
|
494
|
+
};
|
|
495
|
+
|
|
496
|
+
slow_step:
|
|
497
|
+
switch_reg mode {
|
|
498
|
+
case 0: goto scan;
|
|
499
|
+
case 1: goto flush;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
scan:
|
|
503
|
+
%t = peek_bits %in, @0, 2 else err;
|
|
504
|
+
switch_bits %t {
|
|
505
|
+
case 0b10: goto scan_eof;
|
|
506
|
+
case 0b00: goto scan_zero;
|
|
507
|
+
case 0b01: goto scan_one;
|
|
508
|
+
default: goto err;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
scan_eof:
|
|
512
|
+
shift_tag %in, 2 -> unit;
|
|
513
|
+
goto exit_eof_after_shift;
|
|
514
|
+
|
|
515
|
+
exit_eof_after_shift:
|
|
516
|
+
drain_guard %in : unit;
|
|
517
|
+
stack_clear z;
|
|
518
|
+
push_bits %out, 0b10, 2;
|
|
519
|
+
close %out;
|
|
520
|
+
retire;
|
|
521
|
+
|
|
522
|
+
scan_zero:
|
|
523
|
+
shift_tag %in, 2 -> $bits;
|
|
524
|
+
stack_push z, 0b0, 1;
|
|
525
|
+
goto entry;
|
|
526
|
+
|
|
527
|
+
scan_one:
|
|
528
|
+
shift_tag %in, 2 -> $bits;
|
|
529
|
+
%_top = stack_pop z, 1 else emit_one_scan;
|
|
530
|
+
push_bits %out, 0b00, 2;
|
|
531
|
+
set_reg mode, 1;
|
|
532
|
+
goto entry;
|
|
533
|
+
|
|
534
|
+
flush:
|
|
535
|
+
%_top = stack_pop z, 1 else emit_one_scan;
|
|
536
|
+
push_bits %out, 0b00, 2;
|
|
537
|
+
goto entry;
|
|
538
|
+
|
|
539
|
+
emit_one_scan:
|
|
540
|
+
push_bits %out, 0b01, 2;
|
|
541
|
+
set_reg mode, 0;
|
|
542
|
+
goto entry;
|
|
543
|
+
|
|
544
|
+
err:
|
|
545
|
+
fail;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
table &tab_lsb_trim stack_table {
|
|
549
|
+
states: 2;
|
|
550
|
+
stream_bits: 2;
|
|
551
|
+
stack_bits: 1;
|
|
552
|
+
stack_encoding: depth_only;
|
|
553
|
+
output_mode: push;
|
|
554
|
+
mwtr: { rho: 2.0, bytes: 128, budget_class: "L1" };
|
|
555
|
+
entries {
|
|
556
|
+
${buildLsbTrimStackTableEntries()}
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
`;
|
|
560
|
+
|
|
561
|
+
// ============================================================================
|
|
562
|
+
console.log("\n=== 1. Parser, Printer, JSON Artifact & BitDeque/BitStack ADT ===");
|
|
563
|
+
// ============================================================================
|
|
564
|
+
|
|
565
|
+
test("BitDeque push/unshift/peek/shift/wrap-around/adopt across 32-bit boundaries", () => {
|
|
566
|
+
const dq = new BitDeque(1, { initialWords: 2 }); // 64-bit initial ring
|
|
567
|
+
dq.pushBits(0b10110, 5);
|
|
568
|
+
dq.unshiftBits(0b110, 3);
|
|
569
|
+
assert.equal(dq.toBitString(), "11010110");
|
|
570
|
+
assert.equal(dq.peekBits(8), 0b11010110);
|
|
571
|
+
assert.equal(dq.peekBitsAt(3, 5), 0b10110);
|
|
572
|
+
|
|
573
|
+
// Force ring wrap & growth past 64 bits
|
|
574
|
+
for (let i = 0; i < 20; i++) {
|
|
575
|
+
dq.pushBits(0xdeadbeef >>> 0, 32);
|
|
576
|
+
assert.equal(dq.shiftBits(8), i === 0 ? 0b11010110 : 0xef);
|
|
577
|
+
// keep shifting to exercise wrap-around
|
|
578
|
+
if (i === 0) {
|
|
579
|
+
assert.equal(dq.shiftBits(24), 0xdeadbe);
|
|
580
|
+
} else {
|
|
581
|
+
assert.equal(dq.shiftBits(24), 0xdeadbe);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
assert.equal(dq.shiftBits(8), 0xef);
|
|
585
|
+
assert.equal(dq.length, 0);
|
|
586
|
+
|
|
587
|
+
// Test unshiftFromDeque + adoptBufferFrom
|
|
588
|
+
const a = new BitDeque(2);
|
|
589
|
+
const b = new BitDeque(3);
|
|
590
|
+
a.pushBits(0b101011, 6);
|
|
591
|
+
b.pushBits(0b11001, 5);
|
|
592
|
+
b.unshiftFromDeque(a);
|
|
593
|
+
assert.equal(a.length, 0);
|
|
594
|
+
assert.equal(b.toBitString(), "10101111001");
|
|
595
|
+
a.adoptBufferFrom(b);
|
|
596
|
+
assert.equal(b.length, 0);
|
|
597
|
+
assert.equal(a.toBitString(), "10101111001");
|
|
598
|
+
a.release();
|
|
599
|
+
b.release();
|
|
600
|
+
dq.release();
|
|
601
|
+
});
|
|
602
|
+
|
|
603
|
+
test("BitStack push/peekTop/pop/grow/clear LIFO fidelity", () => {
|
|
604
|
+
const st = new BitStack(null, 1);
|
|
605
|
+
st.push(0b10, 2);
|
|
606
|
+
assert.equal(st.peekTop(2), 0b10);
|
|
607
|
+
st.push(1, 1);
|
|
608
|
+
assert.equal(st.pop(1), 1);
|
|
609
|
+
assert.equal(st.pop(2), 0b10);
|
|
610
|
+
assert.equal(st.length, 0);
|
|
611
|
+
// Push > 200 bits to force growth
|
|
612
|
+
for (let i = 0; i < 200; i++) st.push(i & 1, 1);
|
|
613
|
+
for (let i = 199; i >= 0; i--) assert.equal(st.pop(1), i & 1);
|
|
614
|
+
st.release();
|
|
615
|
+
});
|
|
616
|
+
|
|
617
|
+
test("Round-trip parse -> print -> re-parse -> JSON export/import on all worked examples", () => {
|
|
618
|
+
const sources = [
|
|
619
|
+
REVERSE_KTVMP,
|
|
620
|
+
makeLsbAddModule(buildLsbAdd2x2Entries()),
|
|
621
|
+
LSB_TRIM_KTVM,
|
|
622
|
+
`
|
|
623
|
+
ktvm 0.1 mono entry @branch_demo;
|
|
624
|
+
schema $bits = union { 0: $bits, 1: $bits, _: unit };
|
|
625
|
+
proc @id(%x: $bits) -> (%o: $bits) total { splice %x -> %o; }
|
|
626
|
+
proc @branch_demo(%x: $bits) -> (%o: $bits) branching {
|
|
627
|
+
chan %x0 : $bits; chan %x1 : $bits;
|
|
628
|
+
chan %a : $bits; chan %b : $bits;
|
|
629
|
+
barrier %bar;
|
|
630
|
+
tee %x -> (%x0, %x1);
|
|
631
|
+
spawn @id(%x0) -> (%a) as %t0;
|
|
632
|
+
spawn @id(%x1) -> (%b) after %t0;
|
|
633
|
+
drain %a : $bits -> %bar;
|
|
634
|
+
gate %bar, %b -> %o;
|
|
635
|
+
}
|
|
636
|
+
`
|
|
637
|
+
];
|
|
638
|
+
for (const src of sources) {
|
|
639
|
+
const ast1 = parseModule(src);
|
|
640
|
+
const printed1 = printModule(ast1);
|
|
641
|
+
const ast2 = parseModule(printed1);
|
|
642
|
+
const printed2 = printModule(ast2);
|
|
643
|
+
assert.equal(printed1, printed2, "printer must be idempotent");
|
|
644
|
+
|
|
645
|
+
const json = moduleToJSON(ast1);
|
|
646
|
+
assert.equal(json.format, KTVM_FORMAT);
|
|
647
|
+
assert.equal(json.formatVersion, KTVM_VERSION);
|
|
648
|
+
const hydrated = moduleFromJSON(JSON.parse(JSON.stringify(json)));
|
|
649
|
+
assert.equal(printModule(hydrated), printed1, "JSON artifact round-trip must be lossless");
|
|
650
|
+
}
|
|
651
|
+
});
|
|
652
|
+
|
|
653
|
+
test("Parser rejects malformed syntax with KTVMSyntaxError", () => {
|
|
654
|
+
assert.throws(() => parseModule("ktvm 0.1 bogus;"), KTVMSyntaxError);
|
|
655
|
+
assert.throws(() => parseModule("ktvm 0.1 mono; proc bad() -> () {}"), KTVMSyntaxError);
|
|
656
|
+
});
|
|
657
|
+
|
|
658
|
+
// ============================================================================
|
|
659
|
+
console.log("\n=== 2. Static Validator & Always-On Table-to-CFG Bisimulation ===");
|
|
660
|
+
// ============================================================================
|
|
661
|
+
|
|
662
|
+
test("Validator accepts valid poly and mono modules (including verified _lsb_add chunk_table)", () => {
|
|
663
|
+
assert.equal(validateModule(parseModule(REVERSE_KTVMP)).ok, true);
|
|
664
|
+
assert.equal(validateModule(parseModule(makeLsbAddModule(buildLsbAdd2x2Entries()))).ok, true);
|
|
665
|
+
assert.equal(validateModule(parseModule(LSB_TRIM_KTVM)).ok, true);
|
|
666
|
+
});
|
|
667
|
+
|
|
668
|
+
test("Validator catches SPSC linearity violations (double-consume, unproduced, unused)", () => {
|
|
669
|
+
assert.throws(
|
|
670
|
+
() => validateModule(parseModule(`
|
|
671
|
+
ktvm 0.1 mono entry @bad;
|
|
672
|
+
schema $b = union { _: unit };
|
|
673
|
+
proc @bad(%x: $b) -> (%o: $b) {
|
|
674
|
+
chan %d : $b;
|
|
675
|
+
splice %x -> %o;
|
|
676
|
+
splice %x -> %d;
|
|
677
|
+
drain %d : $b;
|
|
678
|
+
}
|
|
679
|
+
`)),
|
|
680
|
+
KTVMValidationError
|
|
681
|
+
);
|
|
682
|
+
assert.throws(
|
|
683
|
+
() => validateModule(parseModule(`
|
|
684
|
+
ktvm 0.1 mono entry @bad;
|
|
685
|
+
schema $b = union { _: unit };
|
|
686
|
+
proc @bad(%x: $b) -> (%o: $b) {
|
|
687
|
+
drain %x : $b;
|
|
688
|
+
}
|
|
689
|
+
`)),
|
|
690
|
+
KTVMValidationError
|
|
691
|
+
);
|
|
692
|
+
});
|
|
693
|
+
|
|
694
|
+
test("Validator catches local channel DAG cycle", () => {
|
|
695
|
+
assert.throws(
|
|
696
|
+
() => validateModule(parseModule(`
|
|
697
|
+
ktvm 0.1 mono entry @cyc;
|
|
698
|
+
schema $b = union { _: unit };
|
|
699
|
+
proc @cyc(%x: $b) -> (%o: $b) {
|
|
700
|
+
chan %a : $b;
|
|
701
|
+
chan %b : $b;
|
|
702
|
+
splice %a -> %b;
|
|
703
|
+
splice %b -> %a;
|
|
704
|
+
splice %x -> %o;
|
|
705
|
+
}
|
|
706
|
+
`)),
|
|
707
|
+
KTVMValidationError
|
|
708
|
+
);
|
|
709
|
+
});
|
|
710
|
+
|
|
711
|
+
test("Validator rejects open/any schemas and polymorphic ops in mono modules", () => {
|
|
712
|
+
assert.throws(
|
|
713
|
+
() => validateModule(parseModule(`
|
|
714
|
+
ktvm 0.1 mono entry @p;
|
|
715
|
+
schema $open = open_product { a: unit ... };
|
|
716
|
+
proc @p(%x: $open) -> (%o: $open) { splice %x -> %o; }
|
|
717
|
+
`)),
|
|
718
|
+
KTVMValidationError
|
|
719
|
+
);
|
|
720
|
+
});
|
|
721
|
+
|
|
722
|
+
test("Validator rejects schema mismatch in mono splice", () => {
|
|
723
|
+
assert.throws(
|
|
724
|
+
() => validateModule(parseModule(`
|
|
725
|
+
ktvm 0.1 mono entry @bad;
|
|
726
|
+
schema $a = union { x: unit, y: unit };
|
|
727
|
+
schema $b = union { x: unit, z: unit };
|
|
728
|
+
proc @bad(%in: $a) -> (%out: $b) { splice %in -> %out; }
|
|
729
|
+
`)),
|
|
730
|
+
KTVMValidationError
|
|
731
|
+
);
|
|
732
|
+
});
|
|
733
|
+
|
|
734
|
+
test("Static table-to-CFG bisimulation catches an intentionally corrupted chunk_table entry!", () => {
|
|
735
|
+
const goodEntries = buildLsbAdd2x2Entries();
|
|
736
|
+
// Corrupt entry 0 (c=0, tx=0, ty=0): change emit_word from [0] to [1]!
|
|
737
|
+
const badEntries = goodEntries.replace(
|
|
738
|
+
"0 => { kind: CONT, next_q: 0, shift: [2, 2], emit_word: [0], emit_len: [2] };",
|
|
739
|
+
"0 => { kind: CONT, next_q: 0, shift: [2, 2], emit_word: [1], emit_len: [2] };"
|
|
740
|
+
);
|
|
741
|
+
const badMod = parseModule(makeLsbAddModule(badEntries));
|
|
742
|
+
assert.throws(
|
|
743
|
+
() => validateModule(badMod, { verifyTables: true }),
|
|
744
|
+
(err) => err instanceof KTVMValidationError && /bisimulation/i.test(err.message)
|
|
745
|
+
);
|
|
746
|
+
// Opt-out flag skips bisimulation check
|
|
747
|
+
assert.equal(validateModule(badMod, { verifyTables: false }).ok, true);
|
|
748
|
+
});
|
|
749
|
+
|
|
750
|
+
// ============================================================================
|
|
751
|
+
console.log("\n=== 3. Polymorphism, Boundary Specialization & Opaque Payloads ===");
|
|
752
|
+
// ============================================================================
|
|
753
|
+
|
|
754
|
+
test("Specialize reverse.ktvmp for list[int[]], execute enveloped k-wire, verify bit-exactness & O(1) tail-splice", () => {
|
|
755
|
+
clearSpecializationCache();
|
|
756
|
+
const listIntSchemaMod = parseModule(`
|
|
757
|
+
ktvm 0.1 mono;
|
|
758
|
+
schema $bits = union { 0: $bits, 1: $bits, _: unit };
|
|
759
|
+
schema $int = union { "+": $bits, "-": $bits };
|
|
760
|
+
schema $list_int = union { cons: product { car: $int, cdr: $list_int }, nil: unit };
|
|
761
|
+
`);
|
|
762
|
+
const listIntPlist = compileSchemaExprToPlist(
|
|
763
|
+
{ kind: "ref", name: "$list_int", args: [] },
|
|
764
|
+
listIntSchemaMod.schemas
|
|
765
|
+
);
|
|
766
|
+
|
|
767
|
+
const inputNums = [1, -2, 3, 0, 42, -1023, 7, 15, -99, 256];
|
|
768
|
+
const inputVal = makeList(inputNums.map(makeIntVal));
|
|
769
|
+
const inWire = encodeToWire(inputVal, listIntPlist);
|
|
770
|
+
|
|
771
|
+
const r1 = executeKTVMWire(REVERSE_KTVMP, inWire);
|
|
772
|
+
assert.equal(r1.status, "OK");
|
|
773
|
+
assert.equal(r1.specialized.cached, false);
|
|
774
|
+
const outNums = listToArray(r1.value).map(intValToNumber);
|
|
775
|
+
assert.deepEqual(outNums, [...inputNums].reverse());
|
|
776
|
+
|
|
777
|
+
// Verify output wire decodes identically via K's canonical `decodeWire`!
|
|
778
|
+
const decodedByK = decodeWire(r1.wire, { eager: true }).value;
|
|
779
|
+
assert.deepEqual(listToArray(decodedByK).map(intValToNumber), [...inputNums].reverse());
|
|
780
|
+
|
|
781
|
+
// Second call hits specialization cache!
|
|
782
|
+
const r2 = executeKTVMWire(REVERSE_KTVMP, inWire);
|
|
783
|
+
assert.equal(r2.status, "OK");
|
|
784
|
+
assert.equal(r2.specialized.cached, true);
|
|
785
|
+
assert.deepEqual(r2.wire, r1.wire);
|
|
786
|
+
|
|
787
|
+
// Verify O(1) tail-splice behavior: total spliceBitsCopied scales O(total input bits), NOT O(n^2)!
|
|
788
|
+
const longNums = Array.from({ length: 80 }, (_, i) => i + 1);
|
|
789
|
+
const longWire = encodeToWire(makeList(longNums.map(makeIntVal)), listIntPlist);
|
|
790
|
+
const rLong = executeKTVMWire(REVERSE_KTVMP, longWire);
|
|
791
|
+
assert.equal(rLong.status, "OK");
|
|
792
|
+
assert.deepEqual(listToArray(rLong.value).map(intValToNumber), [...longNums].reverse());
|
|
793
|
+
// For 80 ints (~16 bits each -> ~1,400 bits total), O(n^2) would copy > 50,000 bits;
|
|
794
|
+
// O(1) tail-splice copies ONLY the prepended car + 1-bit cons tag (~1,600 bits)!
|
|
795
|
+
assert.ok(
|
|
796
|
+
rLong.telemetry.spliceBitsCopied < 4000,
|
|
797
|
+
`Expected O(n) splice bits copied, got ${rLong.telemetry.spliceBitsCopied}`
|
|
798
|
+
);
|
|
799
|
+
});
|
|
800
|
+
|
|
801
|
+
test("Specialize reverse.ktvmp on list[product { a: int[], b: bits[] }] preserving opaque product payload", () => {
|
|
802
|
+
const schemaMod = parseModule(`
|
|
803
|
+
ktvm 0.1 mono;
|
|
804
|
+
schema $bits = union { 0: $bits, 1: $bits, _: unit };
|
|
805
|
+
schema $int = union { "+": $bits, "-": $bits };
|
|
806
|
+
schema $pair = product { a: $int, b: $bits };
|
|
807
|
+
schema $list_pair = union { cons: product { car: $pair, cdr: $list_pair }, nil: unit };
|
|
808
|
+
`);
|
|
809
|
+
const listPairPlist = compileSchemaExprToPlist(
|
|
810
|
+
{ kind: "ref", name: "$list_pair", args: [] },
|
|
811
|
+
schemaMod.schemas
|
|
812
|
+
);
|
|
813
|
+
|
|
814
|
+
const items = [
|
|
815
|
+
Value.product({ a: makeIntVal(5), b: bitsFromString("101") }),
|
|
816
|
+
Value.product({ a: makeIntVal(-12), b: bitsFromString("00110") }),
|
|
817
|
+
Value.product({ a: makeIntVal(0), b: bitsFromString("") })
|
|
818
|
+
];
|
|
819
|
+
const inWire = encodeToWire(makeList(items), listPairPlist);
|
|
820
|
+
|
|
821
|
+
const res = executeKTVMWire(REVERSE_KTVMP, inWire);
|
|
822
|
+
assert.equal(res.status, "OK");
|
|
823
|
+
// Check access profile recognized `$X` as an opaque product!
|
|
824
|
+
const profiles = Object.values(res.specialized.accessProfiles);
|
|
825
|
+
assert.ok(profiles.some((p) => p.opaqueParams.includes("$X")));
|
|
826
|
+
|
|
827
|
+
const outArr = listToArray(res.value);
|
|
828
|
+
assert.equal(outArr.length, 3);
|
|
829
|
+
assert.equal(intValToNumber(outArr[0].product.a), 0);
|
|
830
|
+
assert.equal(bitsToString(outArr[0].product.b), "");
|
|
831
|
+
assert.equal(intValToNumber(outArr[1].product.a), -12);
|
|
832
|
+
assert.equal(bitsToString(outArr[1].product.b), "00110");
|
|
833
|
+
assert.equal(intValToNumber(outArr[2].product.a), 5);
|
|
834
|
+
assert.equal(bitsToString(outArr[2].product.b), "101");
|
|
835
|
+
});
|
|
836
|
+
|
|
837
|
+
test("Boundary specialization rejects incompatible input envelope with KTVMSchemaError", () => {
|
|
838
|
+
const bitsSchemaMod = parseModule(`
|
|
839
|
+
ktvm 0.1 mono;
|
|
840
|
+
schema $bits = union { 0: $bits, 1: $bits, _: unit };
|
|
841
|
+
`);
|
|
842
|
+
const bitsPlist = compileSchemaExprToPlist(
|
|
843
|
+
{ kind: "ref", name: "$bits", args: [] },
|
|
844
|
+
bitsSchemaMod.schemas
|
|
845
|
+
);
|
|
846
|
+
const badWire = encodeToWire(bitsFromString("101"), bitsPlist);
|
|
847
|
+
assert.throws(() => executeKTVMWire(REVERSE_KTVMP, badWire), KTVMSchemaError);
|
|
848
|
+
});
|
|
849
|
+
|
|
850
|
+
test("Polymorphic project .f on open_product + guard ?$P + dead switch arm pruning + Moore coerce collapse", () => {
|
|
851
|
+
const polyMod = `
|
|
852
|
+
ktvm 0.1 poly entry @pick_a;
|
|
853
|
+
|
|
854
|
+
schema $bits = union { 0: $bits, 1: $bits, _: unit };
|
|
855
|
+
schema $bits_alias = union { 0: $bits_alias, 1: $bits_alias, _: unit };
|
|
856
|
+
schema $has_a = open_product { a: $bits ... };
|
|
857
|
+
|
|
858
|
+
proc @pick_a(%in: $has_a) -> (%out: $bits_alias) {
|
|
859
|
+
chan %a1 : $bits;
|
|
860
|
+
chan %a2 : $bits;
|
|
861
|
+
project .a %in : $has_a -> %a1 : $bits;
|
|
862
|
+
guard ?$bits %a1 -> %a2;
|
|
863
|
+
coerce %a2 : $bits -> %out : $bits_alias;
|
|
864
|
+
}
|
|
865
|
+
`;
|
|
866
|
+
|
|
867
|
+
const recSchemaMod = parseModule(`
|
|
868
|
+
ktvm 0.1 mono;
|
|
869
|
+
schema $bits = union { 0: $bits, 1: $bits, _: unit };
|
|
870
|
+
schema $rec = product { a: $bits, b: $bits, c: unit };
|
|
871
|
+
`);
|
|
872
|
+
const recPlist = compileSchemaExprToPlist({ kind: "ref", name: "$rec", args: [] }, recSchemaMod.schemas);
|
|
873
|
+
const val = Value.product({
|
|
874
|
+
a: bitsFromString("1101"),
|
|
875
|
+
b: bitsFromString("000"),
|
|
876
|
+
c: UNIT
|
|
877
|
+
});
|
|
878
|
+
const wire = encodeToWire(val, recPlist);
|
|
879
|
+
|
|
880
|
+
const res = executeKTVMWire(polyMod, wire);
|
|
881
|
+
assert.equal(res.status, "OK");
|
|
882
|
+
assert.equal(bitsToString(res.value), "1101");
|
|
883
|
+
|
|
884
|
+
// Confirm Moore-equivalent `coerce` collapsed into `splice` and `project` lowered to `demux`+`drain`+`gate`!
|
|
885
|
+
const specText = printModule(res.specialized.module);
|
|
886
|
+
assert.ok(!specText.includes("project"), "project must be eliminated in mono");
|
|
887
|
+
assert.ok(!specText.includes("guard"), "guard must be eliminated in mono");
|
|
888
|
+
assert.ok(!specText.includes("coerce"), "Moore-equivalent coerce must collapse to splice");
|
|
889
|
+
assert.ok(specText.includes("demux") && specText.includes("drain") && specText.includes("gate"));
|
|
890
|
+
});
|
|
891
|
+
|
|
892
|
+
// ============================================================================
|
|
893
|
+
console.log("\n=== 4. Operational Semantics, Rewrites, Partiality, Spec & After ===");
|
|
894
|
+
// ============================================================================
|
|
895
|
+
|
|
896
|
+
test("Same-scope MUX -> wrap |cons -> match /cons -> DEMUX performs O(1) zero-copy bundle fusion", () => {
|
|
897
|
+
const fusionMod = `
|
|
898
|
+
ktvm 0.1 mono entry @swap_via_cons;
|
|
899
|
+
|
|
900
|
+
schema $bits = union { 0: $bits, 1: $bits, _: unit };
|
|
901
|
+
schema $pair = product { a: $bits, b: $bits };
|
|
902
|
+
schema $box = union { box: $pair, empty: unit };
|
|
903
|
+
|
|
904
|
+
proc @swap_via_cons(%x: $bits, %y: $bits) -> (%out: $pair) {
|
|
905
|
+
chan %p1 : $pair;
|
|
906
|
+
chan %bx : $box;
|
|
907
|
+
chan %p2 : $pair;
|
|
908
|
+
chan %a : $bits;
|
|
909
|
+
chan %b : $bits;
|
|
910
|
+
|
|
911
|
+
mux (a: %x, b: %y) -> %p1 : $pair;
|
|
912
|
+
wrap |box %p1 -> %bx;
|
|
913
|
+
match /box %bx -> %p2;
|
|
914
|
+
demux %p2 : $pair -> (a: %a, b: %b);
|
|
915
|
+
mux (a: %b, b: %a) -> %out : $pair;
|
|
916
|
+
}
|
|
917
|
+
`;
|
|
918
|
+
|
|
919
|
+
const res = executeKTVM(fusionMod, [bitsFromString("101100"), bitsFromString("01")]);
|
|
920
|
+
assert.equal(res.status, "OK");
|
|
921
|
+
assert.equal(bitsToString(res.value.product.a), "01");
|
|
922
|
+
assert.equal(bitsToString(res.value.product.b), "101100");
|
|
923
|
+
assert.ok(
|
|
924
|
+
res.telemetry.muxDemuxFusions >= 1,
|
|
925
|
+
`Expected MUX->DEMUX fusion, got ${res.telemetry.muxDemuxFusions}`
|
|
926
|
+
);
|
|
927
|
+
});
|
|
928
|
+
|
|
929
|
+
test("Strict K partiality: failing discarded sibling fails gated output via drain/barrier/gate", () => {
|
|
930
|
+
const partialMod = `
|
|
931
|
+
ktvm 0.1 mono entry @keep_second_strict;
|
|
932
|
+
|
|
933
|
+
schema $ab = union { a: unit, b: unit };
|
|
934
|
+
schema $bits = union { 0: $bits, 1: $bits, _: unit };
|
|
935
|
+
|
|
936
|
+
proc @keep_second_strict(%flag: $ab, %val: $bits) -> (%out: $bits) {
|
|
937
|
+
chan %u : unit;
|
|
938
|
+
barrier %bar;
|
|
939
|
+
match /a %flag -> %u;
|
|
940
|
+
drain %u : unit -> %bar;
|
|
941
|
+
gate %bar, %val -> %out;
|
|
942
|
+
}
|
|
943
|
+
`;
|
|
944
|
+
|
|
945
|
+
const ok = executeKTVM(partialMod, [Value.variant("a", UNIT), bitsFromString("101")]);
|
|
946
|
+
assert.equal(ok.status, "OK");
|
|
947
|
+
assert.equal(bitsToString(ok.value), "101");
|
|
948
|
+
|
|
949
|
+
// When %flag is /b, match /a fails -> drain fails %bar -> gate fails %out!
|
|
950
|
+
const fail = executeKTVM(partialMod, [Value.variant("b", UNIT), bitsFromString("101")]);
|
|
951
|
+
assert.equal(fail.status, "FAILED");
|
|
952
|
+
});
|
|
953
|
+
|
|
954
|
+
test("spec: (a) local mismatch rolls back bit-exact replay; (b) upstream failure aborts skipping branch 1", () => {
|
|
955
|
+
const specMod = `
|
|
956
|
+
ktvm 0.1 mono entry @try_ab;
|
|
957
|
+
|
|
958
|
+
schema $tag = union { a: $bits, b: $bits, c: $bits };
|
|
959
|
+
schema $bits = union { 0: $bits, 1: $bits, _: unit };
|
|
960
|
+
|
|
961
|
+
proc @try_ab(%in: $tag) -> (%out: $bits) {
|
|
962
|
+
spec (%in) -> (%out) {
|
|
963
|
+
branch 0: {
|
|
964
|
+
// Only succeeds if /a AND leading bit is 1!
|
|
965
|
+
chan %p : $bits;
|
|
966
|
+
chan %rest : $bits;
|
|
967
|
+
match /a %in -> %p;
|
|
968
|
+
match /1 %p -> %rest;
|
|
969
|
+
wrap |0 %rest -> %out;
|
|
970
|
+
}
|
|
971
|
+
branch 1: {
|
|
972
|
+
// Fallback: if /a with leading bit 0, match it (proving exact rollback of BOTH /a AND bit 0!)
|
|
973
|
+
chan %p : $bits;
|
|
974
|
+
chan %rest : $bits;
|
|
975
|
+
match /a %in -> %p;
|
|
976
|
+
match /0 %p -> %rest;
|
|
977
|
+
wrap |1 %rest -> %out;
|
|
978
|
+
}
|
|
979
|
+
branch 2: {
|
|
980
|
+
// Last branch (tail-spliced!): match /b
|
|
981
|
+
match /b %in -> %out;
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
// Pipeline testing Rule 1 (Upstream Failure Abort): upstream match /a fails on /c,
|
|
987
|
+
// so downstream spec MUST abort immediately WITHOUT running branch 1!
|
|
988
|
+
proc @upstream_abort_test(%raw: $tag) -> (%out: $bits) {
|
|
989
|
+
chan %mid : $bits;
|
|
990
|
+
match /a %raw -> %mid;
|
|
991
|
+
spec (%mid) -> (%out) {
|
|
992
|
+
branch 0: {
|
|
993
|
+
match /1 %mid -> %out;
|
|
994
|
+
}
|
|
995
|
+
branch 1: {
|
|
996
|
+
// Would succeed if invoked on a non-failed input, or fail with a rollback counter
|
|
997
|
+
splice %mid -> %out;
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
`;
|
|
1002
|
+
|
|
1003
|
+
// Branch 0 commits directly
|
|
1004
|
+
const r0 = executeKTVM(specMod, [Value.variant("a", bitsFromString("101"))]);
|
|
1005
|
+
assert.equal(r0.status, "OK");
|
|
1006
|
+
assert.equal(bitsToString(r0.value), "001");
|
|
1007
|
+
assert.equal(r0.telemetry.specRollbacks, 0);
|
|
1008
|
+
|
|
1009
|
+
// Branch 0 fails after consuming /a AND inspecting '0' -> exact replay rollback -> branch 1 succeeds!
|
|
1010
|
+
const r1 = executeKTVM(specMod, [Value.variant("a", bitsFromString("011"))]);
|
|
1011
|
+
assert.equal(r1.status, "OK");
|
|
1012
|
+
assert.equal(bitsToString(r1.value), "111");
|
|
1013
|
+
assert.equal(r1.telemetry.specRollbacks, 1);
|
|
1014
|
+
|
|
1015
|
+
// Branches 0 & 1 fail -> branch 2 tail-splices cleanly!
|
|
1016
|
+
const r2 = executeKTVM(specMod, [Value.variant("b", bitsFromString("110"))]);
|
|
1017
|
+
assert.equal(r2.status, "OK");
|
|
1018
|
+
assert.equal(bitsToString(r2.value), "110");
|
|
1019
|
+
assert.equal(r2.telemetry.specRollbacks, 2);
|
|
1020
|
+
assert.equal(r2.telemetry.specTailSplices, 1);
|
|
1021
|
+
|
|
1022
|
+
// All branches fail -> FAILED
|
|
1023
|
+
const r3 = executeKTVM(specMod, [Value.variant("c", bitsFromString("1"))]);
|
|
1024
|
+
assert.equal(r3.status, "FAILED");
|
|
1025
|
+
|
|
1026
|
+
// Upstream failure abort: %mid fails upstream because %raw is /c -> spec MUST abort immediately!
|
|
1027
|
+
const rAbort = executeKTVM(specMod, [Value.variant("c", bitsFromString("1"))], {
|
|
1028
|
+
entry: "@upstream_abort_test"
|
|
1029
|
+
});
|
|
1030
|
+
assert.equal(rAbort.status, "FAILED");
|
|
1031
|
+
assert.equal(rAbort.telemetry.specUpstreamAborts, 1);
|
|
1032
|
+
assert.equal(rAbort.telemetry.specRollbacks, 0, "upstream failure must NOT roll back to branch 1");
|
|
1033
|
+
});
|
|
1034
|
+
|
|
1035
|
+
test("after %tok sequential sibling settlement bounds peak active nodes on binary tree recursion", () => {
|
|
1036
|
+
// Binary tree recursion of depth d (2^d leaves): without `after`, concurrent expansion
|
|
1037
|
+
// could live-materialize both subtrees simultaneously; WITH `after %t0`, left settles
|
|
1038
|
+
// completely before right expands -> O(d) peak nodes!
|
|
1039
|
+
const treeMod = `
|
|
1040
|
+
ktvm 0.1 mono entry @tree_eval;
|
|
1041
|
+
|
|
1042
|
+
schema $bits = union { 0: $bits, 1: $bits, _: unit };
|
|
1043
|
+
|
|
1044
|
+
proc @tree_eval(%d: $bits) -> (%out: $bits) branching {
|
|
1045
|
+
switch (%d) {
|
|
1046
|
+
case (/_): {
|
|
1047
|
+
chan %u : unit;
|
|
1048
|
+
barrier %b;
|
|
1049
|
+
chan %z : unit;
|
|
1050
|
+
match /_ %d -> %u;
|
|
1051
|
+
drain %u : unit -> %b;
|
|
1052
|
+
const_unit -> %z;
|
|
1053
|
+
chan %res : $bits;
|
|
1054
|
+
wrap |_ %z -> %res;
|
|
1055
|
+
gate %b, %res -> %out;
|
|
1056
|
+
}
|
|
1057
|
+
case (/0): {
|
|
1058
|
+
chan %rest : $bits;
|
|
1059
|
+
chan %r0 : $bits;
|
|
1060
|
+
chan %r1 : $bits;
|
|
1061
|
+
chan %a : $bits;
|
|
1062
|
+
chan %b : $bits;
|
|
1063
|
+
barrier %bar;
|
|
1064
|
+
match /0 %d -> %rest;
|
|
1065
|
+
tee %rest -> (%r0, %r1);
|
|
1066
|
+
spawn @tree_eval(%r0) -> (%a) as %t0;
|
|
1067
|
+
spawn @tree_eval(%r1) -> (%b) after %t0;
|
|
1068
|
+
drain %a : $bits -> %bar;
|
|
1069
|
+
gate %bar, %b -> %out;
|
|
1070
|
+
}
|
|
1071
|
+
case (/1): {
|
|
1072
|
+
chan %rest : $bits;
|
|
1073
|
+
match /1 %d -> %rest;
|
|
1074
|
+
spawn @tree_eval(%rest) -> (%out);
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
`;
|
|
1079
|
+
|
|
1080
|
+
// Depth 8 -> 2^8 = 256 recursive calls, but peak live nodes stays O(depth) (< 60)!
|
|
1081
|
+
const res = executeKTVM(treeMod, [bitsFromString("00000000")]);
|
|
1082
|
+
assert.equal(res.status, "OK");
|
|
1083
|
+
assert.equal(bitsToString(res.value), "");
|
|
1084
|
+
assert.ok(res.telemetry.afterSettlements >= 255, `expected >= 255 after settlements, got ${res.telemetry.afterSettlements}`);
|
|
1085
|
+
assert.ok(
|
|
1086
|
+
res.telemetry.peakActiveNodes < 80,
|
|
1087
|
+
`Expected O(depth) peak nodes (< 80) for 2^8 tree, got ${res.telemetry.peakActiveNodes}`
|
|
1088
|
+
);
|
|
1089
|
+
});
|
|
1090
|
+
|
|
1091
|
+
// ============================================================================
|
|
1092
|
+
console.log("\n=== 5. Accelerated Kernels: TMC _lsb_add & Virtual-Stack _lsb_trim ===");
|
|
1093
|
+
// ============================================================================
|
|
1094
|
+
|
|
1095
|
+
test("TMC _lsb_add kernel with bisimulation-verified chunk_table matches BigInt addition across edge cases", () => {
|
|
1096
|
+
const modSrc = makeLsbAddModule(buildLsbAdd2x2Entries());
|
|
1097
|
+
const pairs = [
|
|
1098
|
+
[0n, 0n],
|
|
1099
|
+
[0n, 1n],
|
|
1100
|
+
[1n, 0n],
|
|
1101
|
+
[1n, 1n],
|
|
1102
|
+
[7n, 1n],
|
|
1103
|
+
[255n, 1n],
|
|
1104
|
+
[123456n, 987654n],
|
|
1105
|
+
[(1n << 200n) - 1n, 1n], // 200-bit carry chain!
|
|
1106
|
+
[(1n << 256n) + 42n, 5n], // uneven lengths (triggers O(1) tail splice!)
|
|
1107
|
+
[3n, (1n << 300n) + 12345n] // symmetric uneven lengths (exit_splice_y)
|
|
1108
|
+
];
|
|
1109
|
+
|
|
1110
|
+
for (const [a, b] of pairs) {
|
|
1111
|
+
const res = executeKTVM(modSrc, [bitsFromBigIntLSB(a), bitsFromBigIntLSB(b)]);
|
|
1112
|
+
assert.equal(res.status, "OK");
|
|
1113
|
+
assert.equal(bitsToBigIntLSB(res.value), a + b, `${a} + ${b}`);
|
|
1114
|
+
assert.ok(res.telemetry.tableLookups >= 1, "chunk_table must be executed");
|
|
1115
|
+
}
|
|
1116
|
+
});
|
|
1117
|
+
|
|
1118
|
+
test("Virtual-stack _lsb_trim kernel with stack_table trims trailing zeros including 4,096-bit stream", () => {
|
|
1119
|
+
const cases = [
|
|
1120
|
+
["", ""],
|
|
1121
|
+
["0", ""],
|
|
1122
|
+
["00000000", ""],
|
|
1123
|
+
["1", "1"],
|
|
1124
|
+
["10000", "1"],
|
|
1125
|
+
["001001000", "001001"],
|
|
1126
|
+
["0101010000000", "010101"],
|
|
1127
|
+
["0".repeat(2000) + "1" + "0".repeat(2095), "0".repeat(2000) + "1"]
|
|
1128
|
+
];
|
|
1129
|
+
|
|
1130
|
+
for (const [inp, expected] of cases) {
|
|
1131
|
+
const res = executeKTVM(LSB_TRIM_KTVM, [bitsFromString(inp)]);
|
|
1132
|
+
assert.equal(res.status, "OK");
|
|
1133
|
+
assert.equal(bitsToString(res.value), expected, `trim(${inp.slice(0, 20)}...)`);
|
|
1134
|
+
assert.ok(res.telemetry.tableLookups >= 1, "stack_table must be executed");
|
|
1135
|
+
}
|
|
1136
|
+
});
|
|
1137
|
+
|
|
1138
|
+
// ============================================================================
|
|
1139
|
+
console.log("\n=== 6. Runtime Quotas, Malformed k-wire & Deep Iterative Stress ===");
|
|
1140
|
+
// ============================================================================
|
|
1141
|
+
|
|
1142
|
+
test("Runtime quotas enforce maxSteps, maxNodes, and maxBitDequeBytes with KTVMQuotaError", () => {
|
|
1143
|
+
const modSrc = makeLsbAddModule(buildLsbAdd2x2Entries());
|
|
1144
|
+
const bigA = bitsFromBigIntLSB((1n << 256n) - 1n);
|
|
1145
|
+
const bigB = bitsFromBigIntLSB(1n);
|
|
1146
|
+
|
|
1147
|
+
// Confirm single-kernel TMC executes in literally 1 live node!
|
|
1148
|
+
const okSingle = executeKTVM(modSrc, [bigA, bigB]);
|
|
1149
|
+
assert.equal(okSingle.telemetry.peakActiveNodes, 1);
|
|
1150
|
+
|
|
1151
|
+
assert.throws(
|
|
1152
|
+
() => executeKTVM(modSrc, [bigA, bigB], { quota: { maxSteps: 5 } }),
|
|
1153
|
+
(err) => err instanceof KTVMQuotaError && err.quotaKind === "maxSteps"
|
|
1154
|
+
);
|
|
1155
|
+
assert.throws(
|
|
1156
|
+
() => executeKTVM(modSrc, [bigA, bigB], { quota: { maxNodes: 0 } }),
|
|
1157
|
+
(err) => err instanceof KTVMQuotaError && err.quotaKind === "maxNodes"
|
|
1158
|
+
);
|
|
1159
|
+
assert.throws(
|
|
1160
|
+
() => executeKTVM(modSrc, [bigA, bigB], { quota: { maxBitDequeBytes: 32 } }),
|
|
1161
|
+
(err) => err instanceof KTVMQuotaError && err.quotaKind === "maxBitDequeBytes"
|
|
1162
|
+
);
|
|
1163
|
+
});
|
|
1164
|
+
|
|
1165
|
+
test("Malformed k-wire envelopes (truncated, invalid ordinal, nonzero padding) are cleanly rejected", () => {
|
|
1166
|
+
const bitsMod = parseModule(`
|
|
1167
|
+
ktvm 0.1 mono;
|
|
1168
|
+
schema $bits = union { 0: $bits, 1: $bits, _: unit };
|
|
1169
|
+
`);
|
|
1170
|
+
const bitsPlist = compileSchemaExprToPlist({ kind: "ref", name: "$bits", args: [] }, bitsMod.schemas);
|
|
1171
|
+
const validWire = encodeToWire(bitsFromString("101"), bitsPlist);
|
|
1172
|
+
|
|
1173
|
+
// 1. Truncated wire
|
|
1174
|
+
assert.throws(() => splitEnvelopedWire(validWire.slice(0, validWire.length - 1)));
|
|
1175
|
+
|
|
1176
|
+
// 2. Nonzero trailing byte padding (flip LSB of last byte if it's padding, or add an extra byte)
|
|
1177
|
+
const paddedBad = new Uint8Array(validWire.length + 1);
|
|
1178
|
+
paddedBad.set(validWire);
|
|
1179
|
+
paddedBad[paddedBad.length - 1] = 0x01;
|
|
1180
|
+
assert.throws(() => splitEnvelopedWire(paddedBad));
|
|
1181
|
+
|
|
1182
|
+
// 3. Invalid 0b11 ordinal directly in BitDeque passed to _lsb_trim
|
|
1183
|
+
const badDq = new BitDeque(999, { prodSchema: bitsPlist, consSchema: bitsPlist });
|
|
1184
|
+
badDq.pushBits(0b11, 2); // invalid 3rd ordinal on 3-tag union!
|
|
1185
|
+
badDq.close();
|
|
1186
|
+
const res = executeKTVM(LSB_TRIM_KTVM, [badDq]);
|
|
1187
|
+
assert.equal(res.status, "FAILED");
|
|
1188
|
+
});
|
|
1189
|
+
|
|
1190
|
+
test("Strictly iterative 4,096-bit k-wire encode + execute + decode with zero host stack overflow", () => {
|
|
1191
|
+
const bitsMod = parseModule(`
|
|
1192
|
+
ktvm 0.1 mono;
|
|
1193
|
+
schema $bits = union { 0: $bits, 1: $bits, _: unit };
|
|
1194
|
+
`);
|
|
1195
|
+
const bitsPlist = compileSchemaExprToPlist({ kind: "ref", name: "$bits", args: [] }, bitsMod.schemas);
|
|
1196
|
+
|
|
1197
|
+
const deepStr = "10".repeat(2048); // 4,096 nested union constructors!
|
|
1198
|
+
const deepVal = bitsFromString(deepStr);
|
|
1199
|
+
|
|
1200
|
+
// Strictly iterative payload encode & decode
|
|
1201
|
+
const dq = new BitDeque(500, { prodSchema: bitsPlist, consSchema: bitsPlist });
|
|
1202
|
+
encodePayloadToDeque(deepVal, bitsPlist, dq, 0);
|
|
1203
|
+
dq.close();
|
|
1204
|
+
assert.equal(dq.length, 4097 * 2);
|
|
1205
|
+
|
|
1206
|
+
// Run through `_lsb_add` (+ 1) strictly iteratively!
|
|
1207
|
+
const oneDq = new BitDeque(501, { prodSchema: bitsPlist, consSchema: bitsPlist });
|
|
1208
|
+
encodePayloadToDeque(bitsFromString("1"), bitsPlist, oneDq, 0);
|
|
1209
|
+
oneDq.close();
|
|
1210
|
+
|
|
1211
|
+
const res = executeKTVM(makeLsbAddModule(buildLsbAdd2x2Entries()), [dq, oneDq]);
|
|
1212
|
+
assert.equal(res.status, "OK");
|
|
1213
|
+
assert.equal(bitsToBigIntLSB(res.value), bitsToBigIntLSB(deepVal) + 1n);
|
|
1214
|
+
|
|
1215
|
+
// Verify iterative decode on output deque directly
|
|
1216
|
+
const outVal = decodeDequeToValue(res.outputDeques[0], bitsPlist, 0, { exact: true });
|
|
1217
|
+
assert.equal(bitsToBigIntLSB(outVal), bitsToBigIntLSB(deepVal) + 1n);
|
|
1218
|
+
});
|
|
1219
|
+
|
|
1220
|
+
test("Dead switch arm pruning on open_union + non-equivalent coerce (tag widening)", () => {
|
|
1221
|
+
const polyMod = `
|
|
1222
|
+
ktvm 0.1 poly entry @widen_ab;
|
|
1223
|
+
|
|
1224
|
+
schema $in_open = open_union { a: unit ... };
|
|
1225
|
+
schema $out_wide = union { a: unit, b: unit, c: unit, d: unit };
|
|
1226
|
+
|
|
1227
|
+
proc @widen_ab(%in: $in_open) -> (%out: $out_wide) {
|
|
1228
|
+
switch (%in) {
|
|
1229
|
+
case (/a): {
|
|
1230
|
+
coerce %in : $in_open -> %out : $out_wide;
|
|
1231
|
+
}
|
|
1232
|
+
case (/b): {
|
|
1233
|
+
coerce %in : $in_open -> %out : $out_wide;
|
|
1234
|
+
}
|
|
1235
|
+
case (/c): {
|
|
1236
|
+
coerce %in : $in_open -> %out : $out_wide;
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
`;
|
|
1241
|
+
|
|
1242
|
+
// Supply concrete closed union with ONLY { a, b } (1-bit tag!), missing /c!
|
|
1243
|
+
const abMod = parseModule(`
|
|
1244
|
+
ktvm 0.1 mono;
|
|
1245
|
+
schema $ab = union { a: unit, b: unit };
|
|
1246
|
+
`);
|
|
1247
|
+
const abPlist = compileSchemaExprToPlist({ kind: "ref", name: "$ab", args: [] }, abMod.schemas);
|
|
1248
|
+
|
|
1249
|
+
const rA = executeKTVMWire(polyMod, encodeToWire(Value.variant("a", UNIT), abPlist));
|
|
1250
|
+
assert.equal(rA.status, "OK");
|
|
1251
|
+
assert.equal(rA.value.tag, "a");
|
|
1252
|
+
// Verify dead `/c` arm was statically pruned in specialized mono module!
|
|
1253
|
+
const specText = printModule(rA.specialized.module);
|
|
1254
|
+
assert.ok(!specText.includes("case (/c)"), "unreachable /c switch arm must be pruned");
|
|
1255
|
+
// Verify output wire is 2-bit tag widened `{ a, b, c, d }` decoded cleanly by K's decodeWire
|
|
1256
|
+
assert.equal(decodeWire(rA.wire, { eager: true }).value.tag, "a");
|
|
1257
|
+
|
|
1258
|
+
const rB = executeKTVMWire(polyMod, encodeToWire(Value.variant("b", UNIT), abPlist));
|
|
1259
|
+
assert.equal(rB.status, "OK");
|
|
1260
|
+
assert.equal(decodeWire(rB.wire, { eager: true }).value.tag, "b");
|
|
1261
|
+
});
|
|
1262
|
+
|
|
1263
|
+
test("packed_base64 chunk_table + fsm_table_step + kernel handoff work end-to-end", () => {
|
|
1264
|
+
// Pack a tiny 4-entry fsm_table for flipping a single leading bit on $bits and handing off to @id!
|
|
1265
|
+
const fsmMod = `
|
|
1266
|
+
ktvm 0.1 mono entry @flip_first_bit;
|
|
1267
|
+
|
|
1268
|
+
schema $bits = union { 0: $bits, 1: $bits, _: unit };
|
|
1269
|
+
|
|
1270
|
+
proc @id_tail(%x: $bits) -> (%o: $bits) total {
|
|
1271
|
+
splice %x -> %o;
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
proc @flip_first_bit(%x: $bits) -> (%o: $bits) total {
|
|
1275
|
+
exec @_flip_head(%x) -> (%o);
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
kernel @_flip_head(%x: $bits) -> (%o: $bits) total {
|
|
1279
|
+
entry:
|
|
1280
|
+
fsm_table_step &tab_flip, %x, (%o) -> exits {
|
|
1281
|
+
short: err,
|
|
1282
|
+
0: handoff_tail,
|
|
1283
|
+
1: done_empty,
|
|
1284
|
+
fail: err
|
|
1285
|
+
};
|
|
1286
|
+
|
|
1287
|
+
handoff_tail:
|
|
1288
|
+
handoff @id_tail(%x) -> (%o);
|
|
1289
|
+
|
|
1290
|
+
done_empty:
|
|
1291
|
+
drain_guard %x : unit;
|
|
1292
|
+
push_bits %o, 0b10, 2;
|
|
1293
|
+
close %o;
|
|
1294
|
+
retire;
|
|
1295
|
+
|
|
1296
|
+
err:
|
|
1297
|
+
fail;
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
table &tab_flip fsm_table {
|
|
1301
|
+
input_bits: 2;
|
|
1302
|
+
output_modes: [ push ];
|
|
1303
|
+
entries {
|
|
1304
|
+
0 => { kind: EXIT, exit: 0, shift: [2], emit_word: [1], emit_len: [2] };
|
|
1305
|
+
1 => { kind: EXIT, exit: 0, shift: [2], emit_word: [0], emit_len: [2] };
|
|
1306
|
+
2 => { kind: EXIT, exit: 1, shift: [2], emit_word: [0], emit_len: [0] };
|
|
1307
|
+
3 => { kind: FAIL };
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
`;
|
|
1311
|
+
|
|
1312
|
+
const r0 = executeKTVM(fsmMod, [bitsFromString("0110")]);
|
|
1313
|
+
assert.equal(r0.status, "OK");
|
|
1314
|
+
assert.equal(bitsToString(r0.value), "1110");
|
|
1315
|
+
assert.equal(r0.telemetry.tableLookups, 1);
|
|
1316
|
+
|
|
1317
|
+
const r1 = executeKTVM(fsmMod, [bitsFromString("100")]);
|
|
1318
|
+
assert.equal(r1.status, "OK");
|
|
1319
|
+
assert.equal(bitsToString(r1.value), "000");
|
|
1320
|
+
|
|
1321
|
+
const rEmpty = executeKTVM(fsmMod, [bitsFromString("")]);
|
|
1322
|
+
assert.equal(rEmpty.status, "OK");
|
|
1323
|
+
assert.equal(bitsToString(rEmpty.value), "");
|
|
1324
|
+
|
|
1325
|
+
// Also verify packed_base64 Int32 encoding round-trip + execution on _lsb_add!
|
|
1326
|
+
// Stride = 7: [kindCode (0=CONT,1=EXIT,2=NEED_MORE,3=FAIL), next_q, exit, sh0, sh1, emitWord0, emitLen0]
|
|
1327
|
+
const packed = new Int32Array(32 * 7);
|
|
1328
|
+
for (let c = 0; c < 2; c++) {
|
|
1329
|
+
for (let tx = 0; tx < 4; tx++) {
|
|
1330
|
+
for (let ty = 0; ty < 4; ty++) {
|
|
1331
|
+
const idx = (c << 4) | (tx << 2) | ty;
|
|
1332
|
+
const b = idx * 7;
|
|
1333
|
+
if (tx === 3 || ty === 3) {
|
|
1334
|
+
packed[b] = 3; // FAIL
|
|
1335
|
+
} else if (tx === 2 && ty === 2) {
|
|
1336
|
+
packed[b] = 1; packed[b + 2] = c; packed[b + 3] = 2; packed[b + 4] = 2;
|
|
1337
|
+
} else if (tx === 2) {
|
|
1338
|
+
if (c === 0) {
|
|
1339
|
+
packed[b] = 1; packed[b + 2] = 2; packed[b + 3] = 2; packed[b + 4] = 0;
|
|
1340
|
+
} else {
|
|
1341
|
+
const sum = ty + 1;
|
|
1342
|
+
packed[b] = 0; packed[b + 1] = sum >> 1; packed[b + 3] = 0; packed[b + 4] = 2;
|
|
1343
|
+
packed[b + 5] = sum & 1; packed[b + 6] = 2;
|
|
1344
|
+
}
|
|
1345
|
+
} else if (ty === 2) {
|
|
1346
|
+
if (c === 0) {
|
|
1347
|
+
packed[b] = 1; packed[b + 2] = 3; packed[b + 3] = 0; packed[b + 4] = 2;
|
|
1348
|
+
} else {
|
|
1349
|
+
const sum = tx + 1;
|
|
1350
|
+
packed[b] = 0; packed[b + 1] = sum >> 1; packed[b + 3] = 2; packed[b + 4] = 0;
|
|
1351
|
+
packed[b + 5] = sum & 1; packed[b + 6] = 2;
|
|
1352
|
+
}
|
|
1353
|
+
} else {
|
|
1354
|
+
const sum = tx + ty + c;
|
|
1355
|
+
packed[b] = 0; packed[b + 1] = sum >> 1; packed[b + 3] = 2; packed[b + 4] = 2;
|
|
1356
|
+
packed[b + 5] = sum & 1; packed[b + 6] = 2;
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
const b64 = packInt32Base64(packed);
|
|
1362
|
+
const packedSrc = makeLsbAddModule("").replace(
|
|
1363
|
+
/entries \{[\s\S]*?\}/,
|
|
1364
|
+
`stride: 7;\n packed_base64 "${b64}";`
|
|
1365
|
+
);
|
|
1366
|
+
const parsedPacked = parseModule(packedSrc);
|
|
1367
|
+
assert.equal(printModule(parseModule(printModule(parsedPacked))), printModule(parsedPacked));
|
|
1368
|
+
const rPack = executeKTVM(parsedPacked, [bitsFromBigIntLSB(99999n), bitsFromBigIntLSB(12345n)]);
|
|
1369
|
+
assert.equal(rPack.status, "OK");
|
|
1370
|
+
assert.equal(bitsToBigIntLSB(rPack.value), 112344n);
|
|
1371
|
+
assert.ok(rPack.telemetry.tableLookups >= 10);
|
|
1372
|
+
});
|
|
1373
|
+
|
|
1374
|
+
// --- Summary ---
|
|
1375
|
+
console.log(`\nResults: ${passed} passed, ${failed} failed.`);
|
|
1376
|
+
if (failed > 0) process.exit(1);
|