@fraczak/k 8.9.0 → 9.1.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 +907 -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 +13 -4
- package/DOCS/README.md +3 -2
- package/DOCS/REPL.md +16 -12
- package/README.md +138 -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 -7
- package/backends/llvm/src/llvm.mjs +4 -113
- 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 +2 -16
- package/backends/wasm/README.md +7 -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 +60 -57
- package/backends/wasm/tests/test-wasm.mjs +41 -2
- 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/runtime/prefix-codec.mjs +67 -1
- 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 +497 -0
- package/ktvm/fixtures/integer-streaming.k +477 -0
- package/ktvm/index.mjs +130 -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 +1134 -0
- package/ktvm/specialize.mjs +538 -0
- package/ktvm/test-conformance.mjs +597 -0
- package/ktvm/test-ktvm.mjs +1805 -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 +4404 -0
- package/ktvm/wasm/test-wasm.mjs +429 -0
- package/ktvm/wire.mjs +679 -0
- package/package.json +1 -9
- package/paper/Makefile +8 -5
- package/paper/k-transducer-compiler.pdf +0 -0
- package/paper/k-transducer-compiler.tex +658 -0
- package/paper/replay-diagnostic.mjs +63 -0
- package/repl.mjs +101 -20
- package/scripts/build-repl-html.mjs +40 -18
- package/scripts/perf-bigint-compare.mjs +12 -16
- package/scripts/perf-ieee.mjs +14 -232
- package/scripts/perf-int.mjs +16 -274
- package/scripts/perf-multiplication.mjs +116 -121
- 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-repl-html.mjs +72 -15
- package/tests/test-repl.mjs +24 -17
- 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,476 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Native C99 / LLVM Backend Test Suite (`k/ktvm/llvm/test-llvm.mjs`).
|
|
3
|
+
*
|
|
4
|
+
* Verifies 100% bit-exact C99 + `clang -O3` native compilation & execution across:
|
|
5
|
+
* 1. Accelerated streaming kernels (`lsb_add` 512b, `lsb_trim` 4,096b, `half_max_tally` SWAR)
|
|
6
|
+
* 2. Polymorphic & opaque payload execution (`lib/generic.k` `reverse`)
|
|
7
|
+
* 3. Full stdlib parity (`lib/integer.k` incl. Karatsuba `times`/`div`/`gcd`,
|
|
8
|
+
* `lib/ieee.k` `bits_to_float64` & `ratio_to_float64`, `lib/djson.k` RFC 8259 `parse_json`)
|
|
9
|
+
* 4. Persistent `--server` protocol (`K_TRACE=1`), general non-canonical `k-wire` header
|
|
10
|
+
* verification (without preset hint), quotas, malformed wire rejection, and `spec` rollback /
|
|
11
|
+
* upstream abort / `after %tok`.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import assert from "node:assert/strict";
|
|
15
|
+
import fs from "node:fs";
|
|
16
|
+
import os from "node:os";
|
|
17
|
+
import path from "node:path";
|
|
18
|
+
import { fileURLToPath } from "node:url";
|
|
19
|
+
|
|
20
|
+
import k from "../../index.mjs";
|
|
21
|
+
import codes from "../../codes.mjs";
|
|
22
|
+
import { Value } from "../../Value.mjs";
|
|
23
|
+
import { compileLibrary, loadLibrary } from "../../object.mjs";
|
|
24
|
+
import { encodeToWire, decodeWire } from "../../codecs/runtime/prefix-codec.mjs";
|
|
25
|
+
import { parse as parseIntVal } from "../../codecs/int.mjs";
|
|
26
|
+
import { textToStringValue } from "../../codecs/string-codec.mjs";
|
|
27
|
+
import { useSpecsFor } from "../../tests/helpers/cli.mjs";
|
|
28
|
+
import { relationPatternPropertyList } from "../../kir.mjs";
|
|
29
|
+
import { PersistentExecutable } from "../../harness/persistent.mjs";
|
|
30
|
+
|
|
31
|
+
import {
|
|
32
|
+
compileKTVMToExecutable,
|
|
33
|
+
compileObjectToKTVMExecutable,
|
|
34
|
+
executeKTVMExecutable,
|
|
35
|
+
executeKTVMWire,
|
|
36
|
+
isClangAvailable,
|
|
37
|
+
parseModule
|
|
38
|
+
} from "../index.mjs";
|
|
39
|
+
|
|
40
|
+
if (!isClangAvailable("clang")) {
|
|
41
|
+
console.log("SKIP: clang not found in PATH; skipping kTVM C/LLVM native test suite.");
|
|
42
|
+
process.exit(0);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
|
|
46
|
+
const readSrc = (rel) => fs.readFileSync(path.join(root, rel), "utf8");
|
|
47
|
+
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "ktvm-llvm-test-"));
|
|
48
|
+
const UNIT = Value.product({});
|
|
49
|
+
|
|
50
|
+
function bitsFromStr(str) {
|
|
51
|
+
let v = Value.variant("_", UNIT);
|
|
52
|
+
for (let i = str.length - 1; i >= 0; i--) v = Value.variant(str[i], v);
|
|
53
|
+
return v;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function makeList(items) {
|
|
57
|
+
let v = Value.variant("nil", UNIT);
|
|
58
|
+
for (let i = items.length - 1; i >= 0; i--) {
|
|
59
|
+
v = Value.variant("cons", Value.product({ car: items[i], cdr: v }));
|
|
60
|
+
}
|
|
61
|
+
return v;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function plainValue(v) {
|
|
65
|
+
return v === undefined ? undefined : JSON.parse(JSON.stringify(v.toJSON()));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const coreLib = loadLibrary(compileLibrary(readSrc("core.k"), { source: "core.k" }));
|
|
69
|
+
const genericLib = loadLibrary(compileLibrary(readSrc("lib/generic.k"), {
|
|
70
|
+
source: "lib/generic.k", libraries: [coreLib], use: useSpecsFor("lib/generic.k")
|
|
71
|
+
}));
|
|
72
|
+
const integerLib = loadLibrary(compileLibrary(readSrc("lib/integer.k"), {
|
|
73
|
+
source: "lib/integer.k", libraries: [coreLib], use: useSpecsFor("lib/integer.k")
|
|
74
|
+
}));
|
|
75
|
+
const ieeeLib = loadLibrary(compileLibrary(readSrc("lib/ieee.k"), {
|
|
76
|
+
source: "lib/ieee.k", libraries: [coreLib], use: useSpecsFor("lib/ieee.k")
|
|
77
|
+
}));
|
|
78
|
+
const djsonLib = loadLibrary(compileLibrary(readSrc("lib/djson.k"), {
|
|
79
|
+
source: "lib/djson.k", libraries: [coreLib, genericLib, ieeeLib], use: useSpecsFor("lib/djson.k")
|
|
80
|
+
}));
|
|
81
|
+
const streamLib = loadLibrary(compileLibrary(readSrc("ktvm/fixtures/integer-streaming.k"), {
|
|
82
|
+
source: "ktvm/fixtures/integer-streaming.k", libraries: [coreLib], use: useSpecsFor("lib/integer.k")
|
|
83
|
+
}));
|
|
84
|
+
|
|
85
|
+
let passed = 0;
|
|
86
|
+
let failed = 0;
|
|
87
|
+
|
|
88
|
+
async function test(name, fn) {
|
|
89
|
+
try {
|
|
90
|
+
await fn();
|
|
91
|
+
passed++;
|
|
92
|
+
console.log(` PASS ${name}`);
|
|
93
|
+
} catch (err) {
|
|
94
|
+
failed++;
|
|
95
|
+
console.error(` FAIL ${name}`);
|
|
96
|
+
console.error(err);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
try {
|
|
101
|
+
console.log("\n=== 1. Accelerated Native C/LLVM Kernels (chunk_table, stack_table, SWAR) ===");
|
|
102
|
+
|
|
103
|
+
await test("Native lsb_add (512b carry chain + persistent --server + K_TRACE=1)", async () => {
|
|
104
|
+
codes.load(streamLib.codes);
|
|
105
|
+
const inPat = relationPatternPropertyList(streamLib.rels[streamLib.relAlias.lsb_add], 0);
|
|
106
|
+
const exe = path.join(tmpDir, "lsb_add.exe");
|
|
107
|
+
const art = compileObjectToKTVMExecutable(streamLib, "lsb_add", inPat, exe, { optimize: true });
|
|
108
|
+
|
|
109
|
+
const srv = new PersistentExecutable(exe);
|
|
110
|
+
try {
|
|
111
|
+
for (const [a, b] of [["0", "0"], ["255", "1"], [String((1n << 512n) - 1n), "1"]]) {
|
|
112
|
+
const val = Value.product({ x: parseIntVal(a).value, y: parseIntVal(b).value });
|
|
113
|
+
const wire = encodeToWire(val, inPat);
|
|
114
|
+
const jsRef = executeKTVMWire(art.ktvmModule, wire, { entry: art.entry, validate: false });
|
|
115
|
+
const { payload, trace } = await srv.requestWithTrace(wire);
|
|
116
|
+
assert.deepEqual(Buffer.from(payload), Buffer.from(jsRef.wire));
|
|
117
|
+
assert.ok(trace && trace.evalNs >= 0 && trace.totalNs >= 0);
|
|
118
|
+
}
|
|
119
|
+
} finally {
|
|
120
|
+
srv.close();
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Verify CLI telemetry reports chunk_table_step lookups
|
|
124
|
+
const bigWire = encodeToWire(Value.product({
|
|
125
|
+
x: parseIntVal(String((1n << 128n) - 1n)).value,
|
|
126
|
+
y: parseIntVal(String((1n << 128n) - 1n)).value
|
|
127
|
+
}), inPat);
|
|
128
|
+
const cli = executeKTVMExecutable(exe, bigWire, { telemetry: true });
|
|
129
|
+
assert.equal(cli.status, "OK");
|
|
130
|
+
assert.ok(cli.telemetry.tableLookups >= 10, "native chunk_table_step must fire");
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
await test("Native lsb_trim (virtual LIFO BitStack + stack_table on 4,096-bit stream)", async () => {
|
|
134
|
+
codes.load(streamLib.codes);
|
|
135
|
+
const inPat = relationPatternPropertyList(streamLib.rels[streamLib.relAlias.lsb_trim], 0);
|
|
136
|
+
const exe = path.join(tmpDir, "lsb_trim.exe");
|
|
137
|
+
const art = compileObjectToKTVMExecutable(streamLib, "lsb_trim", inPat, exe, { optimize: true });
|
|
138
|
+
|
|
139
|
+
for (const s of ["", "0", "00000", "1", "001001000", "0".repeat(2000) + "1" + "0".repeat(2095)]) {
|
|
140
|
+
const wire = encodeToWire(bitsFromStr(s), inPat);
|
|
141
|
+
const jsRef = executeKTVMWire(art.ktvmModule, wire, { entry: art.entry, validate: false, decodeValue: false });
|
|
142
|
+
const res = executeKTVMExecutable(exe, wire, { telemetry: s.length > 1000 });
|
|
143
|
+
assert.equal(res.status, "OK");
|
|
144
|
+
assert.deepEqual(Buffer.from(res.wire), Buffer.from(jsRef.wire));
|
|
145
|
+
if (s.length > 1000) assert.ok(res.telemetry.tableLookups >= 500);
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
await test("Native half_max_tally (SWAR compressed unshift chunk_table)", async () => {
|
|
150
|
+
codes.load(integerLib.codes);
|
|
151
|
+
const inPat = relationPatternPropertyList(integerLib.rels[integerLib.relAlias.half_max_tally], 0);
|
|
152
|
+
const exe = path.join(tmpDir, "half_max_tally.exe");
|
|
153
|
+
const art = compileObjectToKTVMExecutable(integerLib, "half_max_tally", inPat, exe, { optimize: true });
|
|
154
|
+
|
|
155
|
+
for (const [a, b] of [["0", "0"], ["101010", "11"], ["1".repeat(80), "0".repeat(55)]]) {
|
|
156
|
+
const wire = encodeToWire(Value.product({ x: bitsFromStr(a), y: bitsFromStr(b) }), inPat);
|
|
157
|
+
const jsRef = executeKTVMWire(art.ktvmModule, wire, { entry: art.entry, validate: false, decodeValue: false });
|
|
158
|
+
const res = executeKTVMExecutable(exe, wire, { telemetry: true });
|
|
159
|
+
assert.equal(res.status, "OK");
|
|
160
|
+
assert.deepEqual(Buffer.from(res.wire), Buffer.from(jsRef.wire));
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
console.log("\n=== 2. Full Stdlib Parity in Native C/LLVM (generic, integer, ieee, djson) ===");
|
|
165
|
+
|
|
166
|
+
await test("Native lib/generic.k: opaque product list reverse + unminimized open-union header check", async () => {
|
|
167
|
+
codes.load(genericLib.codes);
|
|
168
|
+
const prodList = makeList([
|
|
169
|
+
Value.product({ a: bitsFromStr("101010"), b: bitsFromStr("101") }),
|
|
170
|
+
Value.product({ a: bitsFromStr("111"), b: bitsFromStr("00") }),
|
|
171
|
+
Value.product({ a: bitsFromStr("0001"), b: bitsFromStr("1") })
|
|
172
|
+
]);
|
|
173
|
+
const prodListPat = [
|
|
174
|
+
["closed-union", [["cons", 1], ["nil", 4]]],
|
|
175
|
+
["closed-product", [["car", 2], ["cdr", 0]]],
|
|
176
|
+
["closed-product", [["a", 3], ["b", 3]]],
|
|
177
|
+
["closed-union", [["0", 3], ["1", 3], ["_", 4]]],
|
|
178
|
+
["closed-product", []]
|
|
179
|
+
];
|
|
180
|
+
// Compile executable WITHOUT passing the open-union unminimized header as a preset,
|
|
181
|
+
// proving the C runtime's general header parser & coinductive equivalence checker works!
|
|
182
|
+
const exe = path.join(tmpDir, "reverse.exe");
|
|
183
|
+
compileObjectToKTVMExecutable(genericLib, "reverse", prodListPat, exe, { optimize: true });
|
|
184
|
+
|
|
185
|
+
const nonMinPat = [
|
|
186
|
+
["open-union", [["cons", 1], ["nil", 5]]],
|
|
187
|
+
["open-product", [["car", 2], ["cdr", 0]]],
|
|
188
|
+
["open-product", [["a", 3], ["b", 4]]],
|
|
189
|
+
["open-union", [["0", 3], ["1", 3], ["_", 5]]],
|
|
190
|
+
["open-union", [["0", 4], ["1", 4], ["_", 5]]],
|
|
191
|
+
["closed-product", []]
|
|
192
|
+
];
|
|
193
|
+
const wire = encodeToWire(prodList, nonMinPat);
|
|
194
|
+
const res = executeKTVMExecutable(exe, wire);
|
|
195
|
+
const ref = k.compile(genericLib.relAlias.reverse, { libraries: [genericLib] })(prodList);
|
|
196
|
+
assert.equal(res.status, "OK");
|
|
197
|
+
assert.deepEqual(plainValue(decodeWire(res.wire, { eager: true }).value), plainValue(ref));
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
await test("Native lib/integer.k: plus, minus, times (Karatsuba), div, gcd, cmp", async () => {
|
|
201
|
+
codes.load(integerLib.codes);
|
|
202
|
+
for (const [op, val] of [
|
|
203
|
+
["plus", Value.product({ x: parseIntVal("123456789"), y: parseIntVal("-987654321") })],
|
|
204
|
+
["minus", Value.product({ x: parseIntVal("100000"), y: parseIntVal("1") })],
|
|
205
|
+
["times", Value.product({ x: parseIntVal("65537"), y: parseIntVal("123456") })],
|
|
206
|
+
["div", Value.product({ x: parseIntVal("987654321"), y: parseIntVal("12345") })],
|
|
207
|
+
["gcd", Value.product({ x: parseIntVal("1071"), y: parseIntVal("462") })],
|
|
208
|
+
["cmp", Value.product({ x: parseIntVal("-42"), y: parseIntVal("17") })]
|
|
209
|
+
]) {
|
|
210
|
+
const inPat = relationPatternPropertyList(integerLib.rels[integerLib.relAlias[op]], 0);
|
|
211
|
+
const exe = path.join(tmpDir, `int_${op}.exe`);
|
|
212
|
+
compileObjectToKTVMExecutable(integerLib, op, inPat, exe, { optimize: true });
|
|
213
|
+
const ref = k.compile(integerLib.relAlias[op], { libraries: [integerLib] })(val);
|
|
214
|
+
const res = executeKTVMExecutable(exe, encodeToWire(val, inPat));
|
|
215
|
+
assert.equal(res.status, "OK", `native integer.${op} failed: ${res.stderr}`);
|
|
216
|
+
assert.deepEqual(plainValue(decodeWire(res.wire, { eager: true }).value), plainValue(ref));
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
await test("Native lib/ieee.k: bits_to_float64 & ratio_to_float64", async () => {
|
|
221
|
+
codes.load(ieeeLib.codes);
|
|
222
|
+
const fPat = relationPatternPropertyList(ieeeLib.rels[ieeeLib.relAlias.bits_to_float64], 0);
|
|
223
|
+
const fExe = path.join(tmpDir, "ieee_f64.exe");
|
|
224
|
+
compileObjectToKTVMExecutable(ieeeLib, "bits_to_float64", fPat, fExe, { optimize: true });
|
|
225
|
+
const fVal = parseIntVal(String((1n << 53n) + 3n)).value;
|
|
226
|
+
const fRef = k.compile(ieeeLib.relAlias.bits_to_float64, { libraries: [ieeeLib] })(fVal);
|
|
227
|
+
const fRes = executeKTVMExecutable(fExe, encodeToWire(fVal, fPat));
|
|
228
|
+
assert.equal(fRes.status, "OK");
|
|
229
|
+
assert.deepEqual(plainValue(decodeWire(fRes.wire, { eager: true }).value), plainValue(fRef));
|
|
230
|
+
|
|
231
|
+
const rPat = [
|
|
232
|
+
["closed-product", [["den", 1], ["num", 1], ["sign", 2]]],
|
|
233
|
+
["closed-union", [["0", 1], ["1", 1], ["_", 3]]],
|
|
234
|
+
["closed-union", [["0", 3], ["1", 3]]],
|
|
235
|
+
["closed-product", []]
|
|
236
|
+
];
|
|
237
|
+
const rVal = Value.product({
|
|
238
|
+
sign: Value.variant("0", UNIT),
|
|
239
|
+
num: parseIntVal("355").value,
|
|
240
|
+
den: parseIntVal("113").value
|
|
241
|
+
});
|
|
242
|
+
const rExe = path.join(tmpDir, "ieee_ratio.exe");
|
|
243
|
+
compileObjectToKTVMExecutable(ieeeLib, "ratio_to_float64", rPat, rExe, { optimize: true });
|
|
244
|
+
const rRef = k.compile(ieeeLib.relAlias.ratio_to_float64, { libraries: [ieeeLib] })(rVal);
|
|
245
|
+
const rRes = executeKTVMExecutable(rExe, encodeToWire(rVal, rPat));
|
|
246
|
+
assert.equal(rRes.status, "OK");
|
|
247
|
+
assert.deepEqual(plainValue(decodeWire(rRes.wire, { eager: true }).value), plainValue(rRef));
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
await test("Native lib/djson.k: full RFC 8259 parse_json (valid JSON + invalid JSON rejection)", async () => {
|
|
251
|
+
codes.load(djsonLib.codes);
|
|
252
|
+
const inPat = relationPatternPropertyList(djsonLib.rels[djsonLib.relAlias.parse_json], 0);
|
|
253
|
+
const exe = path.join(tmpDir, "djson_parse.exe");
|
|
254
|
+
compileObjectToKTVMExecutable(djsonLib, "parse_json", inPat, exe, { optimize: true });
|
|
255
|
+
|
|
256
|
+
const srv = new PersistentExecutable(exe);
|
|
257
|
+
try {
|
|
258
|
+
for (const txt of ["{\"a\":[1,-3.5,true,null,\"hi\\n\"]}", "[10, 20]"]) {
|
|
259
|
+
const val = textToStringValue(txt);
|
|
260
|
+
const ref = k.compile(djsonLib.relAlias.parse_json, { libraries: [djsonLib] })(val);
|
|
261
|
+
const payload = await srv.request(encodeToWire(val, inPat));
|
|
262
|
+
assert.deepEqual(plainValue(decodeWire(payload, { eager: true }).value), plainValue(ref), `djson(${txt})`);
|
|
263
|
+
}
|
|
264
|
+
} finally {
|
|
265
|
+
srv.close();
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// Invalid JSON -> normal partial FAILED (exit 1, code -1)
|
|
269
|
+
const badRes = executeKTVMExecutable(exe, encodeToWire(textToStringValue("{ invalid"), inPat));
|
|
270
|
+
assert.equal(badRes.status, "FAILED");
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
console.log("\n=== 3. Quotas, Malformed Wire & Spec Semantics ===");
|
|
274
|
+
|
|
275
|
+
await test("Native enforces quotas and rejects malformed k-wire / incompatible schema", async () => {
|
|
276
|
+
codes.load(streamLib.codes);
|
|
277
|
+
const inPat = relationPatternPropertyList(streamLib.rels[streamLib.relAlias.lsb_trim], 0);
|
|
278
|
+
const exe = path.join(tmpDir, "lsb_trim_q.exe");
|
|
279
|
+
compileObjectToKTVMExecutable(streamLib, "lsb_trim", inPat, exe, { optimize: false });
|
|
280
|
+
|
|
281
|
+
const longWire = encodeToWire(bitsFromStr("0".repeat(200) + "1"), inPat);
|
|
282
|
+
const qStep = executeKTVMExecutable(exe, longWire, { quota: { maxSteps: 5 } });
|
|
283
|
+
assert.equal(qStep.status, "ERROR");
|
|
284
|
+
assert.equal(qStep.errorCode, -2);
|
|
285
|
+
|
|
286
|
+
// Incompatible schema -> KTVM_ERR_SCHEMA (-8)
|
|
287
|
+
const wrongPat = [["closed-union", [["a", 1], ["b", 1]]], ["closed-product", []]];
|
|
288
|
+
const wrongWire = encodeToWire(Value.variant("a", UNIT), wrongPat);
|
|
289
|
+
const sErr = executeKTVMExecutable(exe, wrongWire);
|
|
290
|
+
assert.equal(sErr.status, "ERROR");
|
|
291
|
+
assert.equal(sErr.errorCode, -8);
|
|
292
|
+
|
|
293
|
+
// Truncated wire -> KTVM_ERR_MALFORMED (-6)
|
|
294
|
+
const mErr = executeKTVMExecutable(exe, longWire.subarray(0, longWire.length - 5));
|
|
295
|
+
assert.equal(mErr.status, "ERROR");
|
|
296
|
+
assert.equal(mErr.errorCode, -6);
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
await test("Native spec: local rollback, upstream failure abort, and after %tok", async () => {
|
|
300
|
+
const src = `
|
|
301
|
+
ktvm 0.1 mono entry @main;
|
|
302
|
+
schema $bit = union { 0: unit, 1: unit };
|
|
303
|
+
schema $pair = product { a: $bit, b: $bit };
|
|
304
|
+
proc @fail_zero(%x: $bit) -> (%y: $bit) {
|
|
305
|
+
chan %u: unit;
|
|
306
|
+
match /1 %x -> %u;
|
|
307
|
+
wrap |1 %u -> %y;
|
|
308
|
+
}
|
|
309
|
+
proc @main(%in: $pair) -> (%out: $bit) {
|
|
310
|
+
chan %a: $bit; chan %b: $bit;
|
|
311
|
+
demux %in : $pair -> (a: %a, b: %b);
|
|
312
|
+
chan %a_ok: $bit;
|
|
313
|
+
spawn @fail_zero(%a) -> (%a_ok) as %tok1;
|
|
314
|
+
chan %b_pass: $bit;
|
|
315
|
+
spawn @id_b(%b) -> (%b_pass) after %tok1;
|
|
316
|
+
spec (%a_ok, %b_pass) -> (%out) {
|
|
317
|
+
branch 0: {
|
|
318
|
+
chan %u0: unit;
|
|
319
|
+
match /0 %b_pass -> %u0;
|
|
320
|
+
barrier %bar0;
|
|
321
|
+
drain %u0 : unit -> %bar0;
|
|
322
|
+
gate %bar0, %a_ok -> %out;
|
|
323
|
+
}
|
|
324
|
+
branch 1: {
|
|
325
|
+
chan %u1: unit;
|
|
326
|
+
match /1 %b_pass -> %u1;
|
|
327
|
+
barrier %bar1;
|
|
328
|
+
drain %u1 : unit -> %bar1;
|
|
329
|
+
gate %bar1, %a_ok -> %out;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
proc @id_b(%x: $bit) -> (%y: $bit) { splice %x -> %y; }
|
|
334
|
+
`;
|
|
335
|
+
const mod = parseModule(src);
|
|
336
|
+
const exe = path.join(tmpDir, "spec_test.exe");
|
|
337
|
+
compileKTVMToExecutable(mod, exe, { optimize: false });
|
|
338
|
+
|
|
339
|
+
const pat = [
|
|
340
|
+
["closed-product", [["a", 1], ["b", 1]]],
|
|
341
|
+
["closed-union", [["0", 2], ["1", 2]]],
|
|
342
|
+
["closed-product", []]
|
|
343
|
+
];
|
|
344
|
+
// (a=1, b=1): branch 0 fails locally -> rolls back & succeeds in branch 1!
|
|
345
|
+
const okWire = encodeToWire(Value.product({ a: Value.variant("1", UNIT), b: Value.variant("1", UNIT) }), pat);
|
|
346
|
+
const okRes = executeKTVMExecutable(exe, okWire, { telemetry: true });
|
|
347
|
+
assert.equal(okRes.status, "OK");
|
|
348
|
+
assert.equal(okRes.telemetry.specRollbacks, 1);
|
|
349
|
+
assert.equal(okRes.telemetry.afterSettlements, 1);
|
|
350
|
+
|
|
351
|
+
// (a=0, b=1): upstream %a_ok fails -> spec aborts immediately without rollback!
|
|
352
|
+
const upFailWire = encodeToWire(Value.product({ a: Value.variant("0", UNIT), b: Value.variant("1", UNIT) }), pat);
|
|
353
|
+
const failRes = executeKTVMExecutable(exe, upFailWire, { telemetry: true });
|
|
354
|
+
assert.equal(failRes.status, "FAILED");
|
|
355
|
+
assert.equal(failRes.telemetry.specUpstreamAborts, 1);
|
|
356
|
+
assert.equal(failRes.telemetry.specRollbacks, 0);
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
await test("Native slab allocator & strict mux->demux fusion bound nodes and buffers on Karatsuba & spec stress", async () => {
|
|
360
|
+
// 1. 10,000-bit recursive flip with 5,000 spec rollbacks
|
|
361
|
+
const flipSrc = `
|
|
362
|
+
ktvm 0.1 mono entry @flip;
|
|
363
|
+
schema $bits = union { 0: $bits, 1: $bits, _: unit };
|
|
364
|
+
proc @flip(%x: $bits) -> (%out: $bits) {
|
|
365
|
+
switch (%x) {
|
|
366
|
+
case (/0): {
|
|
367
|
+
chan %rest : $bits; chan %flipped : $bits;
|
|
368
|
+
spec (%x) -> (%rest) {
|
|
369
|
+
branch 0: { chan %bad : $bits; match /1 %x -> %bad; splice %bad -> %rest; }
|
|
370
|
+
branch 1: { match /0 %x -> %rest; }
|
|
371
|
+
}
|
|
372
|
+
spawn @flip(%rest) -> (%flipped);
|
|
373
|
+
wrap |1 %flipped -> %out;
|
|
374
|
+
}
|
|
375
|
+
case (/1): {
|
|
376
|
+
chan %rest : $bits; chan %flipped : $bits;
|
|
377
|
+
match /1 %x -> %rest;
|
|
378
|
+
spawn @flip(%rest) -> (%flipped);
|
|
379
|
+
wrap |0 %flipped -> %out;
|
|
380
|
+
}
|
|
381
|
+
case (/_): { splice %x -> %out; }
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
`;
|
|
385
|
+
const flipExe = path.join(tmpDir, "flip_slab.exe");
|
|
386
|
+
const flipMod = parseModule(flipSrc);
|
|
387
|
+
compileKTVMToExecutable(flipMod, flipExe, { optimize: false });
|
|
388
|
+
const bitsPat = [
|
|
389
|
+
["closed-union", [["0", 0], ["1", 0], ["_", 1]]],
|
|
390
|
+
["closed-product", []]
|
|
391
|
+
];
|
|
392
|
+
const flipWire = encodeToWire(bitsFromStr("01".repeat(5000)), bitsPat);
|
|
393
|
+
const flipRes = executeKTVMExecutable(flipExe, flipWire, { telemetry: true });
|
|
394
|
+
assert.equal(flipRes.status, "OK");
|
|
395
|
+
assert.equal(flipRes.telemetry.specRollbacks, 5000);
|
|
396
|
+
assert.ok(flipRes.telemetry.peakBytes <= 65536, `expected bounded buffers <= 64 KiB, got ${flipRes.telemetry.peakBytes}`);
|
|
397
|
+
|
|
398
|
+
// 2. Karatsuba 256b*256b: strict zero-copy mux->demux fusion keeps peak_nodes & peak_bytes tiny
|
|
399
|
+
codes.load(integerLib.codes);
|
|
400
|
+
const timesPat = relationPatternPropertyList(integerLib.rels[integerLib.relAlias.times], 0);
|
|
401
|
+
const mulExe = path.join(tmpDir, "times_slab.exe");
|
|
402
|
+
compileObjectToKTVMExecutable(integerLib, "times", timesPat, mulExe, { optimize: true });
|
|
403
|
+
const mulIn = Value.product({
|
|
404
|
+
x: parseIntVal(String((1n << 255n) - 987654321n)),
|
|
405
|
+
y: parseIntVal(String((1n << 255n) - 123456789n))
|
|
406
|
+
});
|
|
407
|
+
const mulRes = executeKTVMExecutable(mulExe, encodeToWire(mulIn, timesPat), { telemetry: true });
|
|
408
|
+
assert.equal(mulRes.status, "OK");
|
|
409
|
+
assert.ok(mulRes.telemetry.peakNodes <= 400, `expected bounded Karatsuba nodes <= 400, got ${mulRes.telemetry.peakNodes}`);
|
|
410
|
+
assert.ok(mulRes.telemetry.peakBytes <= 16384, `expected bounded Karatsuba buffers <= 16 KiB, got ${mulRes.telemetry.peakBytes}`);
|
|
411
|
+
});
|
|
412
|
+
|
|
413
|
+
await test("Native fixed-width DPDA skip/copy & eager const/wrap/splice parity on 4,096-bit fanout and fixed-width products", async () => {
|
|
414
|
+
const fwSrc = `
|
|
415
|
+
ktvm 0.1 mono entry @main;
|
|
416
|
+
schema $bit = union { 0: unit, 1: unit };
|
|
417
|
+
schema $byte = product { b0: $bit, b1: $bit, b2: $bit, b3: $bit, b4: $bit, b5: $bit, b6: $bit, b7: $bit };
|
|
418
|
+
schema $bytes = union { cons: product { car: $byte, cdr: $bytes }, nil: unit };
|
|
419
|
+
schema $pair = product { a: $bytes, b: $bytes };
|
|
420
|
+
proc @main(%in: $bytes) -> (%out: $pair) {
|
|
421
|
+
chan %t0: $bytes; chan %t1: $bytes; chan %t2: $bytes;
|
|
422
|
+
tee %in -> (%t0, %t1, %t2);
|
|
423
|
+
barrier %bar;
|
|
424
|
+
drain %t2 : $bytes -> %bar;
|
|
425
|
+
chan %packed: $pair;
|
|
426
|
+
mux (a: %t0, b: %t1) -> %packed : $pair;
|
|
427
|
+
chan %p0: $pair; chan %p1: $pair;
|
|
428
|
+
tee %packed -> (%p0, %p1);
|
|
429
|
+
drain %p1 : $pair -> %bar;
|
|
430
|
+
chan %da: $bytes; chan %db: $bytes;
|
|
431
|
+
demux %p0 : $pair -> (a: %da, b: %db);
|
|
432
|
+
chan %res: $pair;
|
|
433
|
+
mux (a: %da, b: %db) -> %res : $pair;
|
|
434
|
+
gate %bar, %res -> %out;
|
|
435
|
+
}
|
|
436
|
+
`;
|
|
437
|
+
const fwExe = path.join(tmpDir, "dpda_fixed_width.exe");
|
|
438
|
+
compileKTVMToExecutable(parseModule(fwSrc), fwExe, { optimize: false });
|
|
439
|
+
const bytesPat = [
|
|
440
|
+
["closed-union", [["cons", 1], ["nil", 4]]],
|
|
441
|
+
["closed-product", [["car", 2], ["cdr", 0]]],
|
|
442
|
+
["closed-product", [["b0", 3], ["b1", 3], ["b2", 3], ["b3", 3], ["b4", 3], ["b5", 3], ["b6", 3], ["b7", 3]]],
|
|
443
|
+
["closed-union", [["0", 4], ["1", 4]]],
|
|
444
|
+
["closed-product", []]
|
|
445
|
+
];
|
|
446
|
+
const pairPat = [
|
|
447
|
+
["closed-product", [["a", 1], ["b", 1]]],
|
|
448
|
+
["closed-union", [["cons", 2], ["nil", 5]]],
|
|
449
|
+
["closed-product", [["car", 3], ["cdr", 1]]],
|
|
450
|
+
["closed-product", [["b0", 4], ["b1", 4], ["b2", 4], ["b3", 4], ["b4", 4], ["b5", 4], ["b6", 4], ["b7", 4]]],
|
|
451
|
+
["closed-union", [["0", 5], ["1", 5]]],
|
|
452
|
+
["closed-product", []]
|
|
453
|
+
];
|
|
454
|
+
const mkByte = (n) => Value.product(
|
|
455
|
+
Object.fromEntries(Array.from({ length: 8 }, (_, b) => [`b${b}`, Value.variant(String((n >> b) & 1), UNIT)]))
|
|
456
|
+
);
|
|
457
|
+
let bs = Value.variant("nil", UNIT);
|
|
458
|
+
for (let i = 255; i >= 0; i--) {
|
|
459
|
+
bs = Value.variant("cons", Value.product({ car: mkByte(i), cdr: bs }));
|
|
460
|
+
}
|
|
461
|
+
const wire = encodeToWire(bs, bytesPat);
|
|
462
|
+
const res = executeKTVMExecutable(fwExe, wire, { telemetry: true });
|
|
463
|
+
assert.equal(res.status, "OK");
|
|
464
|
+
const expectedWire = encodeToWire(Value.product({ a: bs, b: bs }), pairPat);
|
|
465
|
+
assert.equal(
|
|
466
|
+
Buffer.compare(Buffer.from(res.wire), Buffer.from(expectedWire)),
|
|
467
|
+
0,
|
|
468
|
+
"Fixed-width DPDA skip/copy + demux/drain output wire mismatch"
|
|
469
|
+
);
|
|
470
|
+
});
|
|
471
|
+
} finally {
|
|
472
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
console.log(`\nNative C/LLVM Results: ${passed} passed, ${failed} failed.`);
|
|
476
|
+
if (failed > 0) process.exit(1);
|