@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,598 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Milestone 3 Verified Optimizer Test Suite (`k/ktvm/optimize/`).
|
|
3
|
+
*
|
|
4
|
+
* Verifies:
|
|
5
|
+
* 1. Howard's policy-improvement MWTR evaluator (`computeMWTR`) & global
|
|
6
|
+
* L1 budget allocator (`allocateTableBudgets`, default 64 KB).
|
|
7
|
+
* 2. Automatic CPS symbolic `proc -> kernel` fusion, TMC forward streaming,
|
|
8
|
+
* finite-enum register promotion (`reg c : enum(2)`), and `chunk_table`
|
|
9
|
+
* synthesis + always-on static bisimulation on `integer-streaming.k`
|
|
10
|
+
* (`lsb_add`, `lsb_sub`, `lsb_mul`) and `lib/integer.k` (`plus`, `minus`, `times`, `rev_bits`, `lsb_shl`)!
|
|
11
|
+
* 3. Automatic virtual LIFO bit-stack promotion (`stack s : bits`) +
|
|
12
|
+
* bisimulation-verified `stack_table` synthesis on `integer-streaming.k`
|
|
13
|
+
* `lsb_trim` AND `lib/generic.k` `rev_bits` / `trim_bits`!
|
|
14
|
+
* 4. Automatic SWAR don't-care bit compression (`compress: { mask }`) on
|
|
15
|
+
* `half_max_tally` / `lsb_shl` (halving effective key bits while passing
|
|
16
|
+
* exhaustive raw-window bisimulation verification!).
|
|
17
|
+
* 5. Graceful wide-alphabet fallback on `lib/djson.k` (`parse_json`, `get`)
|
|
18
|
+
* leaving wide `ascii[]`/`unicode[]` procs intact while honoring L1 budget!
|
|
19
|
+
* 6. Measurable step-count reduction & 100% bit-exact parity (`unopt kTVM`
|
|
20
|
+
* vs `opt kTVM` vs `k.compile`) + printable `.ktvm` round-trip!
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import assert from "node:assert/strict";
|
|
24
|
+
import fs from "node:fs";
|
|
25
|
+
import path from "node:path";
|
|
26
|
+
import { fileURLToPath } from "node:url";
|
|
27
|
+
|
|
28
|
+
import k from "../index.mjs";
|
|
29
|
+
import codes from "../codes.mjs";
|
|
30
|
+
import { Value } from "../Value.mjs";
|
|
31
|
+
import { compileLibrary, loadLibrary } from "../object.mjs";
|
|
32
|
+
import { encodeToWire, decodeWire } from "../codecs/runtime/prefix-codec.mjs";
|
|
33
|
+
import { parse as parseIntVal } from "../codecs/int.mjs";
|
|
34
|
+
import { patternFromFilter } from "../codecs/runtime/codec-sdk.mjs";
|
|
35
|
+
import { textToStringValue } from "../codecs/string-codec.mjs";
|
|
36
|
+
import { useSpecsFor } from "../tests/helpers/cli.mjs";
|
|
37
|
+
import { relationPatternPropertyList } from "../kir.mjs";
|
|
38
|
+
|
|
39
|
+
import {
|
|
40
|
+
DEFAULT_L1_BUDGET_BYTES,
|
|
41
|
+
allocateTableBudgets,
|
|
42
|
+
compileKIRToKTVM,
|
|
43
|
+
computeMWTR,
|
|
44
|
+
executeKTVMWire,
|
|
45
|
+
optimizeKTVM,
|
|
46
|
+
parseModule,
|
|
47
|
+
printModule,
|
|
48
|
+
validateModule
|
|
49
|
+
} from "./index.mjs";
|
|
50
|
+
|
|
51
|
+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
52
|
+
const readSrc = (rel) => fs.readFileSync(path.join(root, rel), "utf8");
|
|
53
|
+
const UNIT = Value.product({});
|
|
54
|
+
|
|
55
|
+
function bitsFromStr(str) {
|
|
56
|
+
let v = Value.variant("_", UNIT);
|
|
57
|
+
for (let i = str.length - 1; i >= 0; i--) v = Value.variant(str[i], v);
|
|
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",
|
|
68
|
+
libraries: [coreLib],
|
|
69
|
+
use: useSpecsFor("lib/generic.k")
|
|
70
|
+
}));
|
|
71
|
+
const integerLib = loadLibrary(compileLibrary(readSrc("lib/integer.k"), {
|
|
72
|
+
source: "lib/integer.k",
|
|
73
|
+
libraries: [coreLib],
|
|
74
|
+
use: useSpecsFor("lib/integer.k")
|
|
75
|
+
}));
|
|
76
|
+
const ieeeLib = loadLibrary(compileLibrary(readSrc("lib/ieee.k"), {
|
|
77
|
+
source: "lib/ieee.k",
|
|
78
|
+
libraries: [coreLib],
|
|
79
|
+
use: useSpecsFor("lib/ieee.k")
|
|
80
|
+
}));
|
|
81
|
+
const djsonLib = loadLibrary(compileLibrary(readSrc("lib/djson.k"), {
|
|
82
|
+
source: "lib/djson.k",
|
|
83
|
+
libraries: [coreLib, genericLib, ieeeLib],
|
|
84
|
+
use: useSpecsFor("lib/djson.k")
|
|
85
|
+
}));
|
|
86
|
+
const streamLib = loadLibrary(compileLibrary(readSrc("ktvm/fixtures/integer-streaming.k"), {
|
|
87
|
+
source: "ktvm/fixtures/integer-streaming.k",
|
|
88
|
+
libraries: [coreLib],
|
|
89
|
+
use: useSpecsFor("lib/integer.k")
|
|
90
|
+
}));
|
|
91
|
+
|
|
92
|
+
let passed = 0;
|
|
93
|
+
let failed = 0;
|
|
94
|
+
|
|
95
|
+
function test(name, fn) {
|
|
96
|
+
try {
|
|
97
|
+
fn();
|
|
98
|
+
passed++;
|
|
99
|
+
console.log(` PASS ${name}`);
|
|
100
|
+
} catch (err) {
|
|
101
|
+
failed++;
|
|
102
|
+
console.error(` FAIL ${name}`);
|
|
103
|
+
console.error(err);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// ============================================================================
|
|
108
|
+
console.log("\n=== 1. Howard MWTR Algorithm & Global L1 Budget Allocator ===");
|
|
109
|
+
// ============================================================================
|
|
110
|
+
|
|
111
|
+
test("Howard computeMWTR finds exact minimum cycle ratio and critical bottleneck cycle", () => {
|
|
112
|
+
// 2-state graph:
|
|
113
|
+
// 0 -> 0 (w=8, t=1 -> 8.0)
|
|
114
|
+
// 0 -> 1 (w=6, t=1)
|
|
115
|
+
// 1 -> 0 (w=4, t=1) -> 2-cycle ratio = (6+4)/2 = 5.0 (minimum!)
|
|
116
|
+
// 1 -> 1 (w=6, t=1 -> 6.0)
|
|
117
|
+
const res = computeMWTR(2, [
|
|
118
|
+
{ from: 0, to: 0, w: 8, t: 1 },
|
|
119
|
+
{ from: 0, to: 1, w: 6, t: 1 },
|
|
120
|
+
{ from: 1, to: 0, w: 4, t: 1 },
|
|
121
|
+
{ from: 1, to: 1, w: 6, t: 1 }
|
|
122
|
+
]);
|
|
123
|
+
assert.ok(Math.abs(res.rho - 5.0) < 1e-9, `expected rho=5.0, got ${res.rho}`);
|
|
124
|
+
assert.equal(res.cycleNodes.length, 2);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
test("Global L1 budget allocator maximizes MWTR within 64 KB budget and degrades cleanly on tight budget", () => {
|
|
128
|
+
const frontiers = [
|
|
129
|
+
{
|
|
130
|
+
kernelName: "@k_add",
|
|
131
|
+
candidates: [
|
|
132
|
+
{ bytes: 256, rho: 4.0 },
|
|
133
|
+
{ bytes: 4096, rho: 8.0 },
|
|
134
|
+
{ bytes: 65536, rho: 12.0 }
|
|
135
|
+
]
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
kernelName: "@k_trim",
|
|
139
|
+
candidates: [
|
|
140
|
+
{ bytes: 192, rho: 2.0 },
|
|
141
|
+
{ bytes: 768, rho: 4.0 }
|
|
142
|
+
]
|
|
143
|
+
}
|
|
144
|
+
];
|
|
145
|
+
|
|
146
|
+
// Under default 64 KB budget: picks k_add (4096B, rho=8) + k_trim (768B, rho=4) — fits in 4,864B!
|
|
147
|
+
const a1 = allocateTableBudgets(frontiers, { budgetBytes: DEFAULT_L1_BUDGET_BYTES });
|
|
148
|
+
assert.ok(a1.usedBytes <= DEFAULT_L1_BUDGET_BYTES);
|
|
149
|
+
assert.equal(a1.chosen.get("@k_add").rho, 8.0);
|
|
150
|
+
assert.equal(a1.chosen.get("@k_trim").rho, 4.0);
|
|
151
|
+
|
|
152
|
+
// Under ultra-tight 512 B budget: picks k_add (256B) + k_trim (192B) = 448B!
|
|
153
|
+
const a2 = allocateTableBudgets(frontiers, { budgetBytes: 512 });
|
|
154
|
+
assert.equal(a2.usedBytes, 448);
|
|
155
|
+
assert.equal(a2.chosen.get("@k_add").bytes, 256);
|
|
156
|
+
assert.equal(a2.chosen.get("@k_trim").bytes, 192);
|
|
157
|
+
|
|
158
|
+
// Under 0 B budget: graceful fallback to CFG-only (null)
|
|
159
|
+
const a0 = allocateTableBudgets(frontiers, { budgetBytes: 0 });
|
|
160
|
+
assert.equal(a0.usedBytes, 0);
|
|
161
|
+
assert.equal(a0.chosen.get("@k_add"), null);
|
|
162
|
+
assert.equal(a0.chosen.get("@k_trim"), null);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
// ============================================================================
|
|
166
|
+
console.log("\n=== 2. TMC Streaming Fusion, Register Promotion & Bisimulation-Verified Chunk Tables ===");
|
|
167
|
+
// ============================================================================
|
|
168
|
+
|
|
169
|
+
test("integer-streaming.k lsb_add: auto-fuses TMC kernel + reg carry + verified chunk_table, beats unopt steps", () => {
|
|
170
|
+
codes.load(streamLib.codes);
|
|
171
|
+
const inPat = relationPatternPropertyList(streamLib.rels[streamLib.relAlias.lsb_add], 0);
|
|
172
|
+
const compiled = compileKIRToKTVM(streamLib, "lsb_add", inPat);
|
|
173
|
+
const opt = optimizeKTVM(compiled.module, { budgetBytes: DEFAULT_L1_BUDGET_BYTES, verifyTables: true });
|
|
174
|
+
|
|
175
|
+
assert.ok(opt.stats.fuse.tmcLoops >= 1, `expected >= 1 TMC loop, got ${JSON.stringify(opt.stats.fuse)}`);
|
|
176
|
+
assert.ok(opt.stats.fuse.registerPromotions >= 1, "expected carry register promotion");
|
|
177
|
+
assert.ok(opt.stats.tables.tablesSynthesized >= 1, "expected bisimulation-verified chunk_table");
|
|
178
|
+
assert.ok(opt.stats.tables.totalTableBytes <= DEFAULT_L1_BUDGET_BYTES);
|
|
179
|
+
|
|
180
|
+
// Printable DSL round-trip + validator re-check!
|
|
181
|
+
const dsl = printModule(opt.module);
|
|
182
|
+
const reparsed = parseModule(dsl);
|
|
183
|
+
assert.equal(validateModule(reparsed, { verifyTables: true }).ok, true);
|
|
184
|
+
|
|
185
|
+
// Verify 100% bit-exact parity + dramatic step reduction on 64-bit and 128-bit addition!
|
|
186
|
+
const bigPairs = [
|
|
187
|
+
["0", "0"],
|
|
188
|
+
["255", "1"],
|
|
189
|
+
["12345678901234567890", "98765432109876543210"],
|
|
190
|
+
["340282366920938463463374607431768211455", "1"], // 2^128 - 1 + 1 carry chain!
|
|
191
|
+
["340282366920938463463374607431768211455", "340282366920938463463374607431768211455"] // 2x 128-bit hot chunk loop!
|
|
192
|
+
];
|
|
193
|
+
for (const [a, b] of bigPairs) {
|
|
194
|
+
const val = Value.product({ x: parseIntVal(a).value, y: parseIntVal(b).value });
|
|
195
|
+
const wire = encodeToWire(val, inPat);
|
|
196
|
+
const unoptRes = executeKTVMWire(compiled.module, wire, { entry: compiled.entry, validate: false });
|
|
197
|
+
const optRes = executeKTVMWire(opt.module, wire, { entry: compiled.entry, validate: false });
|
|
198
|
+
|
|
199
|
+
assert.equal(optRes.status, "OK");
|
|
200
|
+
assert.deepEqual(plainValue(optRes.value), plainValue(unoptRes.value), `lsb_add(${a},${b})`);
|
|
201
|
+
assert.deepEqual(
|
|
202
|
+
plainValue(decodeWire(optRes.wire, { eager: true }).value),
|
|
203
|
+
plainValue(unoptRes.value)
|
|
204
|
+
);
|
|
205
|
+
if (a.length >= 20 && b.length >= 20) {
|
|
206
|
+
assert.ok(optRes.telemetry.tableLookups >= 10, `table_step must fire on hot loop (got ${optRes.telemetry.tableLookups})`);
|
|
207
|
+
}
|
|
208
|
+
if (a.length >= 20) {
|
|
209
|
+
assert.ok(
|
|
210
|
+
optRes.telemetry.steps < unoptRes.telemetry.steps / 4,
|
|
211
|
+
`expected >=4x step reduction (unopt=${unoptRes.telemetry.steps}, opt=${optRes.telemetry.steps})`
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
test("integer-streaming.k lsb_trim: auto-promotes virtual LIFO BitStack + bisimulation-verified stack_table", () => {
|
|
218
|
+
codes.load(streamLib.codes);
|
|
219
|
+
const inPat = relationPatternPropertyList(streamLib.rels[streamLib.relAlias.lsb_trim], 0);
|
|
220
|
+
const compiled = compileKIRToKTVM(streamLib, "lsb_trim", inPat);
|
|
221
|
+
const opt = optimizeKTVM(compiled.module, { budgetBytes: DEFAULT_L1_BUDGET_BYTES, verifyTables: true });
|
|
222
|
+
|
|
223
|
+
assert.ok(opt.stats.fuse.stackKernels >= 1, `expected >= 1 virtual-stack kernel, got ${JSON.stringify(opt.stats.fuse)}`);
|
|
224
|
+
assert.ok(opt.stats.tables.tablesSynthesized >= 1, "expected verified stack_table");
|
|
225
|
+
assert.ok(opt.module.tables.some((t) => t.kind === "stack_table"), "must synthesize stack_table");
|
|
226
|
+
|
|
227
|
+
const cases = ["", "0", "00000", "1", "100000", "001001000", "0".repeat(200) + "1" + "0".repeat(300)];
|
|
228
|
+
for (const s of cases) {
|
|
229
|
+
const wire = encodeToWire(bitsFromStr(s), inPat);
|
|
230
|
+
const unoptRes = executeKTVMWire(compiled.module, wire, { entry: compiled.entry, validate: false });
|
|
231
|
+
const optRes = executeKTVMWire(opt.module, wire, { entry: compiled.entry, validate: false });
|
|
232
|
+
assert.equal(optRes.status, "OK");
|
|
233
|
+
assert.deepEqual(plainValue(optRes.value), plainValue(unoptRes.value), `lsb_trim(${s.slice(0, 16)})`);
|
|
234
|
+
if (s.length > 100) {
|
|
235
|
+
assert.ok(optRes.telemetry.tableLookups >= 10);
|
|
236
|
+
assert.ok(optRes.telemetry.steps < unoptRes.telemetry.steps / 4);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
test("SWAR don't-care bit compression automatically activates on half_max_tally and passes exhaustive bisimulation", () => {
|
|
242
|
+
codes.load(integerLib.codes);
|
|
243
|
+
const inPat = relationPatternPropertyList(integerLib.rels[integerLib.relAlias.half_max_tally], 0);
|
|
244
|
+
const compiled = compileKIRToKTVM(integerLib, "half_max_tally", inPat);
|
|
245
|
+
const opt = optimizeKTVM(compiled.module, { budgetBytes: DEFAULT_L1_BUDGET_BYTES, verifyTables: true });
|
|
246
|
+
|
|
247
|
+
const compressedTables = opt.module.tables.filter((t) =>
|
|
248
|
+
t.kind === "chunk_table" && (t.props.inputs || []).some((i) => i.compress && i.compress.ident !== "none")
|
|
249
|
+
);
|
|
250
|
+
assert.ok(
|
|
251
|
+
compressedTables.length >= 1,
|
|
252
|
+
`expected SWAR mask compression on half_max_tally, got tables=${JSON.stringify(opt.stats.tables.kernelReports)}`
|
|
253
|
+
);
|
|
254
|
+
|
|
255
|
+
// Verify parity across varied lengths
|
|
256
|
+
for (const [a, b] of [["0", "0"], ["101010", "11"], ["1".repeat(40), "0".repeat(25)]]) {
|
|
257
|
+
const val = Value.product({ x: bitsFromStr(a), y: bitsFromStr(b) });
|
|
258
|
+
const wire = encodeToWire(val, inPat);
|
|
259
|
+
const unoptRes = executeKTVMWire(compiled.module, wire, { entry: compiled.entry, validate: false });
|
|
260
|
+
const optRes = executeKTVMWire(opt.module, wire, { entry: compiled.entry, validate: false });
|
|
261
|
+
assert.equal(optRes.status, "OK");
|
|
262
|
+
assert.deepEqual(plainValue(optRes.value), plainValue(unoptRes.value));
|
|
263
|
+
assert.ok(optRes.telemetry.tableLookups >= 1);
|
|
264
|
+
}
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
// ============================================================================
|
|
268
|
+
console.log("\n=== 3. Full Stdlib Optimized Parity (integer.k, generic.k, ieee.k, djson.k) ===");
|
|
269
|
+
// ============================================================================
|
|
270
|
+
|
|
271
|
+
test("Optimized lib/integer.k (plus, minus, times, gcd, rev_bits) matches reference bit-for-bit within 64 KB L1", () => {
|
|
272
|
+
codes.load(integerLib.codes);
|
|
273
|
+
for (const [op, val] of [
|
|
274
|
+
["plus", Value.product({ x: parseIntVal("123456789"), y: parseIntVal("-987654321") })],
|
|
275
|
+
["minus", Value.product({ x: parseIntVal("100000"), y: parseIntVal("1") })],
|
|
276
|
+
["times", Value.product({ x: parseIntVal("65537"), y: parseIntVal("123456") })],
|
|
277
|
+
["gcd", Value.product({ x: parseIntVal("1071"), y: parseIntVal("462") })],
|
|
278
|
+
["rev_bits", bitsFromStr("1011001110001")]
|
|
279
|
+
]) {
|
|
280
|
+
const inPat = relationPatternPropertyList(integerLib.rels[integerLib.relAlias[op]], 0);
|
|
281
|
+
const compiled = compileKIRToKTVM(integerLib, op, inPat);
|
|
282
|
+
const opt = optimizeKTVM(compiled.module, { budgetBytes: DEFAULT_L1_BUDGET_BYTES, verifyTables: true });
|
|
283
|
+
assert.ok(opt.stats.tables.totalTableBytes <= DEFAULT_L1_BUDGET_BYTES);
|
|
284
|
+
|
|
285
|
+
const wire = encodeToWire(val, inPat);
|
|
286
|
+
const ref = k.compile(integerLib.relAlias[op], { libraries: [integerLib] })(val);
|
|
287
|
+
const optRes = executeKTVMWire(opt.module, wire, { entry: compiled.entry, validate: false });
|
|
288
|
+
assert.equal(optRes.status, "OK", `opt integer.${op} failed`);
|
|
289
|
+
assert.deepEqual(plainValue(optRes.value), plainValue(ref), `opt integer.${op} mismatch`);
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
test("Optimized lib/generic.k (trim_bits, inc_bits, rev_bits) and lib/ieee.k (bits_to_float64) match bit-for-bit", () => {
|
|
294
|
+
codes.load(genericLib.codes);
|
|
295
|
+
for (const op of ["trim_bits", "inc_bits", "rev_bits"]) {
|
|
296
|
+
const inPat = relationPatternPropertyList(genericLib.rels[genericLib.relAlias[op]], 0);
|
|
297
|
+
const compiled = compileKIRToKTVM(genericLib, op, inPat);
|
|
298
|
+
const opt = optimizeKTVM(compiled.module, { budgetBytes: DEFAULT_L1_BUDGET_BYTES, verifyTables: true });
|
|
299
|
+
const val = bitsFromStr("00101111");
|
|
300
|
+
const ref = k.compile(genericLib.relAlias[op], { libraries: [genericLib] })(val);
|
|
301
|
+
const optRes = executeKTVMWire(opt.module, encodeToWire(val, inPat), { entry: compiled.entry, validate: false });
|
|
302
|
+
assert.equal(optRes.status, "OK");
|
|
303
|
+
assert.deepEqual(plainValue(optRes.value), plainValue(ref), `opt generic.${op}`);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
codes.load(ieeeLib.codes);
|
|
307
|
+
const fPat = relationPatternPropertyList(ieeeLib.rels[ieeeLib.relAlias.bits_to_float64], 0);
|
|
308
|
+
const fComp = compileKIRToKTVM(ieeeLib, "bits_to_float64", fPat);
|
|
309
|
+
const fOpt = optimizeKTVM(fComp.module, { budgetBytes: DEFAULT_L1_BUDGET_BYTES, verifyTables: true });
|
|
310
|
+
assert.ok(fOpt.stats.tables.totalTableBytes <= DEFAULT_L1_BUDGET_BYTES);
|
|
311
|
+
const fVal = parseIntVal(String((1n << 53n) + 3n)).value;
|
|
312
|
+
const fRef = k.compile(ieeeLib.relAlias.bits_to_float64, { libraries: [ieeeLib] })(fVal);
|
|
313
|
+
const fRes = executeKTVMWire(fOpt.module, encodeToWire(fVal, fPat), { entry: fComp.entry, validate: false });
|
|
314
|
+
assert.equal(fRes.status, "OK");
|
|
315
|
+
assert.deepEqual(plainValue(fRes.value), plainValue(fRef));
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
test("Graceful wide-alphabet fallback on lib/djson.k parse_json stays strictly inside 64 KB L1 budget", () => {
|
|
319
|
+
codes.load(djsonLib.codes);
|
|
320
|
+
const inPat = relationPatternPropertyList(djsonLib.rels[djsonLib.relAlias.parse_json], 0);
|
|
321
|
+
const compiled = compileKIRToKTVM(djsonLib, "parse_json", inPat);
|
|
322
|
+
const opt = optimizeKTVM(compiled.module, { budgetBytes: DEFAULT_L1_BUDGET_BYTES, verifyTables: true });
|
|
323
|
+
assert.ok(opt.stats.tables.totalTableBytes <= DEFAULT_L1_BUDGET_BYTES);
|
|
324
|
+
|
|
325
|
+
for (const txt of ["{\"a\": [1, true, null], \"b\": \"ok\\n\"}", "{ broken"]) {
|
|
326
|
+
const val = textToStringValue(txt);
|
|
327
|
+
const ref = k.compile(djsonLib.relAlias.parse_json, { libraries: [djsonLib] })(val);
|
|
328
|
+
const optRes = executeKTVMWire(opt.module, encodeToWire(val, inPat), { entry: compiled.entry, validate: false });
|
|
329
|
+
if (ref === undefined) {
|
|
330
|
+
assert.equal(optRes.status, "FAILED");
|
|
331
|
+
} else {
|
|
332
|
+
assert.equal(optRes.status, "OK");
|
|
333
|
+
assert.deepEqual(plainValue(optRes.value), plainValue(ref));
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
test("simplifyProcs: helper inlining, O(N^2) tee->demux collapse, spec->switch, and loop-kernel extraction on lib/integer.k", () => {
|
|
339
|
+
codes.load(integerLib.codes);
|
|
340
|
+
const plusPat = relationPatternPropertyList(integerLib.rels[integerLib.relAlias.plus], 0);
|
|
341
|
+
const plusComp = compileKIRToKTVM(integerLib, "plus", plusPat);
|
|
342
|
+
const plusOpt = optimizeKTVM(plusComp.module, { budgetBytes: DEFAULT_L1_BUDGET_BYTES, verifyTables: true });
|
|
343
|
+
|
|
344
|
+
assert.ok(plusOpt.stats.simplify.inlinedCalls >= 1, "must inline small acyclic helpers");
|
|
345
|
+
assert.ok(plusOpt.stats.simplify.teeDemuxCollapses >= 2, "must collapse O(N^2) tee->demux projections");
|
|
346
|
+
assert.ok(plusOpt.stats.simplify.specsConverted >= 2, "must compile deterministic lsb_add/lsb_sub specs to switch");
|
|
347
|
+
assert.ok(plusOpt.stats.simplify.loopsExtracted >= 2, "must extract pure loop kernels for lsb_add/lsb_sub");
|
|
348
|
+
assert.ok(
|
|
349
|
+
plusOpt.module.tables.some((t) => t.kind === "chunk_table" && t.name.includes("lsb_add")),
|
|
350
|
+
"must synthesize bisimulation-verified chunk_table for lib/integer.k lsb_add_loop"
|
|
351
|
+
);
|
|
352
|
+
assert.ok(
|
|
353
|
+
plusOpt.module.tables.some((t) => t.kind === "chunk_table" && t.name.includes("lsb_sub")),
|
|
354
|
+
"must synthesize bisimulation-verified chunk_table for lib/integer.k lsb_sub_loop"
|
|
355
|
+
);
|
|
356
|
+
|
|
357
|
+
const bigAdd = Value.product({
|
|
358
|
+
x: parseIntVal(String((1n << 127n) - 37n)),
|
|
359
|
+
y: parseIntVal(String((1n << 127n) - 19n))
|
|
360
|
+
});
|
|
361
|
+
const wire = encodeToWire(bigAdd, plusPat);
|
|
362
|
+
const res = executeKTVMWire(plusOpt.module, wire, { entry: plusComp.entry, validate: false });
|
|
363
|
+
assert.equal(res.status, "OK");
|
|
364
|
+
assert.equal(res.telemetry.specRollbacks, 0, "integer.plus must execute with 0 speculative rollbacks");
|
|
365
|
+
assert.ok(res.telemetry.tableLookups >= 10, "extracted lsb_add_loop chunk_table must fire");
|
|
366
|
+
|
|
367
|
+
// Karatsuba `times`: nested spec on (_k_state -> /apply -> .stack /nil vs /cons) must split cleanly to switch!
|
|
368
|
+
const timesPat = relationPatternPropertyList(integerLib.rels[integerLib.relAlias.times], 0);
|
|
369
|
+
const timesComp = compileKIRToKTVM(integerLib, "times", timesPat);
|
|
370
|
+
const timesOpt = optimizeKTVM(timesComp.module, { budgetBytes: DEFAULT_L1_BUDGET_BYTES, verifyTables: true });
|
|
371
|
+
const bigMul = Value.product({
|
|
372
|
+
x: parseIntVal("98765432109876543210"),
|
|
373
|
+
y: parseIntVal("12345678901234567890")
|
|
374
|
+
});
|
|
375
|
+
const mulWire = encodeToWire(bigMul, timesPat);
|
|
376
|
+
const mulRes = executeKTVMWire(timesOpt.module, mulWire, { entry: timesComp.entry, validate: false });
|
|
377
|
+
assert.equal(mulRes.status, "OK");
|
|
378
|
+
assert.equal(mulRes.telemetry.specRollbacks, 0, "integer.times Karatsuba loop must execute with 0 speculative rollbacks");
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
test("simplifyProcs: strict accumulator forcing collapses lazy tail-loop chains to O(1) nodes without slowing reverse", () => {
|
|
382
|
+
const polySrc = readSrc("Examples/poly.k");
|
|
383
|
+
const polyDep = loadLibrary(compileLibrary(readSrc("lib/integer.k"), { source: "lib/integer.k" }));
|
|
384
|
+
const polyRaw = loadLibrary(compileLibrary(polySrc, {
|
|
385
|
+
source: "Examples/poly.k",
|
|
386
|
+
libraries: [polyDep],
|
|
387
|
+
use: ["int[] nat int pos? neg? zero? gt? inc dec"]
|
|
388
|
+
}));
|
|
389
|
+
const polyLib = {
|
|
390
|
+
format: "k-object",
|
|
391
|
+
codes: { ...polyDep.codes, ...polyRaw.codes },
|
|
392
|
+
rels: { ...polyDep.rels, ...polyRaw.rels },
|
|
393
|
+
relAlias: { ...polyRaw.relAlias },
|
|
394
|
+
meta: { ...polyDep.meta, ...polyRaw.meta }
|
|
395
|
+
};
|
|
396
|
+
codes.load(polyLib.codes);
|
|
397
|
+
const mkList = (n) => {
|
|
398
|
+
let cur = Value.variant("nil", UNIT);
|
|
399
|
+
for (let i = n; i >= 1; i--) cur = Value.variant("cons", Value.product({ car: parseIntVal(String(i)), cdr: cur }));
|
|
400
|
+
return cur;
|
|
401
|
+
};
|
|
402
|
+
const inferredPat = relationPatternPropertyList(polyLib.rels[polyLib.relAlias.length], 0);
|
|
403
|
+
const wire200 = encodeToWire(mkList(200), inferredPat);
|
|
404
|
+
const listPat = decodeWire(wire200).pattern;
|
|
405
|
+
|
|
406
|
+
// `length`: uninspected accumulator `acc` updated by `inc` -> must be forced via `after %tok`
|
|
407
|
+
const lenComp = compileKIRToKTVM(polyLib, "length", listPat);
|
|
408
|
+
const lenOpt = optimizeKTVM(lenComp.module, { budgetBytes: DEFAULT_L1_BUDGET_BYTES, verifyTables: true });
|
|
409
|
+
assert.ok(lenOpt.stats.simplify.strictAccumulatorsForced >= 1, "expected strict accumulator forcing on poly.length");
|
|
410
|
+
const len200 = executeKTVMWire(lenOpt.module, wire200, { entry: lenComp.entry, validate: false });
|
|
411
|
+
assert.equal(len200.status, "OK");
|
|
412
|
+
assert.equal(len200.telemetry.afterSettlements, 200);
|
|
413
|
+
assert.ok(len200.telemetry.peakActiveNodes <= 64, `expected O(1) peakActiveNodes <= 64 on length(200), got ${len200.telemetry.peakActiveNodes}`);
|
|
414
|
+
|
|
415
|
+
// `reverse`: structural `mux`+`wrap` accumulator must stay lazy (0 forced accumulators)
|
|
416
|
+
const revComp = compileKIRToKTVM(polyLib, "reverse", listPat);
|
|
417
|
+
const revOpt = optimizeKTVM(revComp.module, { budgetBytes: DEFAULT_L1_BUDGET_BYTES, verifyTables: true });
|
|
418
|
+
assert.equal(revOpt.stats.simplify.strictAccumulatorsForced, 0, "structural reverse accumulator must remain lazy");
|
|
419
|
+
});
|
|
420
|
+
|
|
421
|
+
test("simplifyProcs: interprocedural entry-guard analysis eliminates >99% of speculative rollbacks in djson.parse_json", () => {
|
|
422
|
+
codes.load(djsonLib.codes);
|
|
423
|
+
const inPat = relationPatternPropertyList(djsonLib.rels[djsonLib.relAlias.parse_json], 0);
|
|
424
|
+
const comp = compileKIRToKTVM(djsonLib, "parse_json", inPat);
|
|
425
|
+
const opt = optimizeKTVM(comp.module, { budgetBytes: DEFAULT_L1_BUDGET_BYTES, verifyTables: true });
|
|
426
|
+
|
|
427
|
+
// Interprocedural guards must eliminate all specs from `@dj_parse_atom` and `@dj_parse_expect_val`!
|
|
428
|
+
const expectValProc = opt.module.procs.find((p) => p.name.startsWith("@dj_parse_expect_val"));
|
|
429
|
+
const parseAtomProc = opt.module.procs.find((p) => p.name.startsWith("@dj_parse_atom"));
|
|
430
|
+
assert.ok(expectValProc, "expected @dj_parse_expect_val proc");
|
|
431
|
+
assert.ok(parseAtomProc, "expected @dj_parse_atom proc");
|
|
432
|
+
assert.equal(
|
|
433
|
+
JSON.stringify(expectValProc.body).includes('"op":"spec"'),
|
|
434
|
+
false,
|
|
435
|
+
"@dj_parse_expect_val must compile to deterministic switch (0 specs)"
|
|
436
|
+
);
|
|
437
|
+
assert.equal(
|
|
438
|
+
JSON.stringify(parseAtomProc.body).includes('"op":"spec"'),
|
|
439
|
+
false,
|
|
440
|
+
"@dj_parse_atom must compile to deterministic switch (0 specs)"
|
|
441
|
+
);
|
|
442
|
+
|
|
443
|
+
const items = [];
|
|
444
|
+
for (let i = 0; i < 10; i++) {
|
|
445
|
+
items.push(`{"id":${i},"ok":${i % 2 === 0},"val":${(i * -1.25).toFixed(2)},"nil":null,"tag":"item_${i}"}`);
|
|
446
|
+
}
|
|
447
|
+
const val = textToStringValue(`[${items.join(",")}]`);
|
|
448
|
+
const wire = encodeToWire(val, inPat);
|
|
449
|
+
const quota = { maxSteps: 1e8, maxNodes: 5e5, maxBitDequeBytes: 64 * 1024 * 1024 };
|
|
450
|
+
const unoptRes = executeKTVMWire(comp.module, wire, { entry: comp.entry, validate: false, quota });
|
|
451
|
+
const optRes = executeKTVMWire(opt.module, wire, { entry: comp.entry, validate: false, quota });
|
|
452
|
+
|
|
453
|
+
assert.equal(optRes.status, "OK");
|
|
454
|
+
assert.equal(
|
|
455
|
+
Buffer.compare(Buffer.from(unoptRes.wire), Buffer.from(optRes.wire)),
|
|
456
|
+
0,
|
|
457
|
+
"optimized djson wire must match unoptimized wire bit-for-bit"
|
|
458
|
+
);
|
|
459
|
+
assert.ok(
|
|
460
|
+
optRes.telemetry.specRollbacks <= 15,
|
|
461
|
+
`expected <= 15 rollbacks on 10 JSON objects (was 2,456), got ${optRes.telemetry.specRollbacks}`
|
|
462
|
+
);
|
|
463
|
+
assert.ok(
|
|
464
|
+
optRes.telemetry.steps < 450000,
|
|
465
|
+
`expected linear step budget < 450k on 10 JSON objects, got ${optRes.telemetry.steps}`
|
|
466
|
+
);
|
|
467
|
+
});
|
|
468
|
+
|
|
469
|
+
test("simplifyProcs: product-demux hoisting keeps poly.split_by strictly O(L) linear in steps and buffer bytes", () => {
|
|
470
|
+
const polyDep = loadLibrary(compileLibrary(readSrc("lib/integer.k"), { source: "lib/integer.k" }));
|
|
471
|
+
const polyRaw = loadLibrary(compileLibrary(readSrc("Examples/poly.k"), {
|
|
472
|
+
source: "Examples/poly.k",
|
|
473
|
+
libraries: [polyDep],
|
|
474
|
+
use: ["int[] nat int pos? neg? zero? gt? inc dec"]
|
|
475
|
+
}));
|
|
476
|
+
const polyLib = {
|
|
477
|
+
format: "k-object",
|
|
478
|
+
codes: { ...polyDep.codes, ...polyRaw.codes },
|
|
479
|
+
rels: { ...polyDep.rels, ...polyRaw.rels },
|
|
480
|
+
relAlias: { ...polyRaw.relAlias },
|
|
481
|
+
meta: { ...polyDep.meta, ...polyRaw.meta }
|
|
482
|
+
};
|
|
483
|
+
codes.load(polyLib.codes);
|
|
484
|
+
const mkList = (n) => {
|
|
485
|
+
let cur = Value.variant("nil", UNIT);
|
|
486
|
+
for (let i = n; i >= 1; i--) cur = Value.variant("cons", Value.product({ car: parseIntVal(String(i)), cdr: cur }));
|
|
487
|
+
return cur;
|
|
488
|
+
};
|
|
489
|
+
const splitPat = patternFromFilter(`
|
|
490
|
+
?{
|
|
491
|
+
< <bits 0, bits 1, {} _>=bits "+", bits "-" > n,
|
|
492
|
+
<
|
|
493
|
+
{} nil,
|
|
494
|
+
{
|
|
495
|
+
< <bits 0, bits 1, {} _>=bits "+", bits "-" > car,
|
|
496
|
+
list cdr
|
|
497
|
+
} cons
|
|
498
|
+
> = list xs
|
|
499
|
+
}
|
|
500
|
+
`);
|
|
501
|
+
const sampleVal = Value.product({ n: parseIntVal("20"), xs: mkList(40) });
|
|
502
|
+
const wire40 = encodeToWire(sampleVal, splitPat);
|
|
503
|
+
|
|
504
|
+
const comp = compileKIRToKTVM(polyLib, "split_by", splitPat);
|
|
505
|
+
const opt = optimizeKTVM(comp.module, { budgetBytes: DEFAULT_L1_BUDGET_BYTES, verifyTables: true });
|
|
506
|
+
|
|
507
|
+
const refFn = k.compile(polyLib.relAlias.split_by, { libraries: [polyLib] });
|
|
508
|
+
const val160 = Value.product({ n: parseIntVal("80"), xs: mkList(160) });
|
|
509
|
+
const wire160 = encodeToWire(val160, splitPat);
|
|
510
|
+
|
|
511
|
+
const r40 = executeKTVMWire(opt.module, wire40, { entry: comp.entry, validate: false });
|
|
512
|
+
const r160 = executeKTVMWire(opt.module, wire160, { entry: comp.entry, validate: false });
|
|
513
|
+
assert.equal(r40.status, "OK");
|
|
514
|
+
assert.equal(r160.status, "OK");
|
|
515
|
+
assert.deepEqual(plainValue(r40.value), plainValue(refFn(sampleVal)), "poly.split_by(40) mismatch");
|
|
516
|
+
assert.deepEqual(plainValue(r160.value), plainValue(refFn(val160)), "poly.split_by(160) mismatch");
|
|
517
|
+
|
|
518
|
+
const ratio = r160.telemetry.steps / r40.telemetry.steps;
|
|
519
|
+
assert.ok(
|
|
520
|
+
ratio < 5.5,
|
|
521
|
+
`expected O(L) linear scaling on 4x input (ratio < 5.5), got ${ratio.toFixed(2)} (${r40.telemetry.steps} -> ${r160.telemetry.steps})`
|
|
522
|
+
);
|
|
523
|
+
assert.ok(
|
|
524
|
+
r160.telemetry.peakBitDequeBytes < 16384,
|
|
525
|
+
`expected linear buffer bytes < 16 KiB on split_by(160), got ${r160.telemetry.peakBitDequeBytes}`
|
|
526
|
+
);
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
test("unfoldShortBitRecProcs & knownTag match/wrap peephole reduce spawns and steps with bit-exact parity", () => {
|
|
530
|
+
// 1. poly.reverse: 1-bit linear recursion (@rev_append) unfolds 3 rounds (4x unrolled)
|
|
531
|
+
const polyDep = loadLibrary(compileLibrary(readSrc("lib/integer.k"), { source: "lib/integer.k" }));
|
|
532
|
+
const polyRaw = loadLibrary(compileLibrary(readSrc("Examples/poly.k"), {
|
|
533
|
+
source: "Examples/poly.k",
|
|
534
|
+
libraries: [polyDep],
|
|
535
|
+
use: ["int[] nat int pos? neg? zero? gt? inc dec"]
|
|
536
|
+
}));
|
|
537
|
+
const polyLib = {
|
|
538
|
+
format: "k-object",
|
|
539
|
+
codes: { ...polyDep.codes, ...polyRaw.codes },
|
|
540
|
+
rels: { ...polyDep.rels, ...polyRaw.rels },
|
|
541
|
+
relAlias: { ...polyRaw.relAlias },
|
|
542
|
+
meta: { ...polyDep.meta, ...polyRaw.meta }
|
|
543
|
+
};
|
|
544
|
+
codes.load(polyLib.codes);
|
|
545
|
+
const listPat = patternFromFilter(`
|
|
546
|
+
?<
|
|
547
|
+
{} nil,
|
|
548
|
+
{
|
|
549
|
+
< <bits 0, bits 1, {} _>=bits "+", bits "-" > car,
|
|
550
|
+
list cdr
|
|
551
|
+
} cons
|
|
552
|
+
> = list
|
|
553
|
+
`);
|
|
554
|
+
let listVal = Value.variant("nil", UNIT);
|
|
555
|
+
for (let i = 200; i >= 1; i--) {
|
|
556
|
+
listVal = Value.variant("cons", Value.product({ car: parseIntVal(String(i)), cdr: listVal }));
|
|
557
|
+
}
|
|
558
|
+
const revWire = encodeToWire(listVal, listPat);
|
|
559
|
+
const revComp = compileKIRToKTVM(polyLib, "reverse", listPat);
|
|
560
|
+
const revNoUf = optimizeKTVM(revComp.module, { unfold: false });
|
|
561
|
+
const revUf = optimizeKTVM(revComp.module, { unfold: true });
|
|
562
|
+
assert.ok(revUf.stats.unfold.unfoldedProcs >= 1, "expected @rev_append to unfold");
|
|
563
|
+
assert.ok(revUf.stats.unfold.unfoldRounds >= 3, `expected >= 3 unfold rounds, got ${revUf.stats.unfold.unfoldRounds}`);
|
|
564
|
+
const r0 = executeKTVMWire(revNoUf.module, revWire, { entry: revComp.entry, validate: false });
|
|
565
|
+
const r1 = executeKTVMWire(revUf.module, revWire, { entry: revComp.entry, validate: false });
|
|
566
|
+
assert.equal(r1.status, "OK");
|
|
567
|
+
assert.equal(Buffer.compare(Buffer.from(r0.wire), Buffer.from(r1.wire)), 0, "unfolded reverse wire mismatch");
|
|
568
|
+
assert.ok(
|
|
569
|
+
r1.telemetry.steps < r0.telemetry.steps * 0.88,
|
|
570
|
+
`expected >=12% step reduction on reverse (noUf=${r0.telemetry.steps}, uf=${r1.telemetry.steps})`
|
|
571
|
+
);
|
|
572
|
+
|
|
573
|
+
// 2. integer.times: known-tag match/wrap peephole + bounded unfolding on @lsb_mul_small
|
|
574
|
+
codes.load(integerLib.codes);
|
|
575
|
+
const timesPat = relationPatternPropertyList(integerLib.rels[integerLib.relAlias.times], 0);
|
|
576
|
+
const tComp = compileKIRToKTVM(integerLib, "times", timesPat);
|
|
577
|
+
const tNoUf = optimizeKTVM(tComp.module, { unfold: false });
|
|
578
|
+
const tUf = optimizeKTVM(tComp.module, { unfold: true });
|
|
579
|
+
assert.ok(tUf.stats.simplify.knownMatchWrapFolds > 0, "expected knownMatchWrapFolds > 0 on integer.times");
|
|
580
|
+
assert.ok(tUf.stats.unfold.unfoldedProcs >= 1, "expected unfoldedProcs >= 1 on integer.times");
|
|
581
|
+
const mulVal = Value.product({
|
|
582
|
+
x: parseIntVal(String((1n << 127n) - 1234567n)),
|
|
583
|
+
y: parseIntVal(String((1n << 127n) - 7654321n))
|
|
584
|
+
});
|
|
585
|
+
const mulWire = encodeToWire(mulVal, timesPat);
|
|
586
|
+
const m0 = executeKTVMWire(tNoUf.module, mulWire, { entry: tComp.entry, validate: false });
|
|
587
|
+
const m1 = executeKTVMWire(tUf.module, mulWire, { entry: tComp.entry, validate: false });
|
|
588
|
+
assert.equal(m1.status, "OK");
|
|
589
|
+
assert.equal(Buffer.compare(Buffer.from(m0.wire), Buffer.from(m1.wire)), 0, "unfolded times wire mismatch");
|
|
590
|
+
assert.ok(
|
|
591
|
+
m1.telemetry.steps < m0.telemetry.steps,
|
|
592
|
+
`expected strictly fewer steps with unfolding (noUf=${m0.telemetry.steps}, uf=${m1.telemetry.steps})`
|
|
593
|
+
);
|
|
594
|
+
});
|
|
595
|
+
|
|
596
|
+
// --- Summary ---
|
|
597
|
+
console.log(`\nMilestone 3 Optimizer Results: ${passed} passed, ${failed} failed.`);
|
|
598
|
+
if (failed > 0) process.exit(1);
|