@fraczak/k 8.5.0 → 8.5.1

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 CHANGED
@@ -5,6 +5,21 @@ All notable changes to this project will be documented here.
5
5
  The format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
6
6
  This project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [8.5.1] — 2026-10-31 — Fix Union Tail-Call Optimization in Wasm and LLVM Backends
9
+
10
+ - **Restrict Union Tail-Call Optimization to Final Branch (#3)**:
11
+ - Fix unsound self-tail-call optimization on non-final union branches in
12
+ `backends/wasm/src/kvm2wasm.mjs`, `backends/llvm/src/kvm2llvm.mjs`, and
13
+ `backends/llvm/src/llvm.mjs`. Only the final branch (`i === N - 1`) of a
14
+ union is in tail position; earlier branches must execute regular calls so
15
+ that failure of a recursive call properly backtracks to subsequent branches
16
+ with the original union input.
17
+ - Extend `feedsSelfTailCall` (`tailCallInputTargets`) in
18
+ `backends/wasm/src/kvm2wasm.mjs` so factored tail-recursive unions
19
+ (`< { ... }, { ... } > self` in tail position) continue to forward product
20
+ fields directly into `$tail_in_*` locals and jump to `$tail_loop` without
21
+ intermediate arena allocation.
22
+
8
23
  ## [8.5.0] — 2026-10-28 — Documentation and Test Cleanup
9
24
 
10
25
  - Replace the obsolete book, duplicated paper rendering, design plans, and
@@ -441,10 +441,11 @@ function hasSelfTailCall(insts, funcName, isTail = true) {
441
441
  for (let i = 0; i < insts.length; i++) {
442
442
  const inst = insts[i];
443
443
  if (isTail && isSelfTailCall(insts, i, funcName)) return true;
444
- if (inst.op === "union" && inst.branches) {
444
+ if (inst.op === "union" && inst.branches && inst.branches.length > 0) {
445
445
  const unionIsTail = isTail && tailValueAfter(insts, i + 1, inst.dest);
446
- for (let bIdx = 0; bIdx < inst.branches.length; bIdx++) {
447
- if (hasSelfTailCall(inst.branches[bIdx].body, funcName, unionIsTail)) return true;
446
+ if (unionIsTail) {
447
+ const lastBranch = inst.branches[inst.branches.length - 1];
448
+ if (hasSelfTailCall(lastBranch.body, funcName, true)) return true;
448
449
  }
449
450
  }
450
451
  }
@@ -908,7 +909,7 @@ function lowerKVMFunction(kvmFunc, symbol, funcName, moduleCtx, linkage = "", op
908
909
  outputPattern: kvmFunc.outputPattern,
909
910
  body: branch.body
910
911
  };
911
- const armTailRef = tailValueAfter(insts, i + 1, inst.dest) ? tailRef : null;
912
+ const armTailRef = (isLast && tailValueAfter(insts, i + 1, inst.dest)) ? tailRef : null;
912
913
  const armBody = lowerKVMFunction(armFunc, armName, armFunc.name, moduleCtx, "internal", { ...options, tailRef: armTailRef });
913
914
  moduleCtx.syntheticFunctions.push(armBody);
914
915
 
@@ -505,7 +505,8 @@ function emitUnionFunctionBody(symbol, items, ctx, linkage = "", options = {}) {
505
505
  unsupported(ctx);
506
506
  } else {
507
507
  items.forEach((item, index) => {
508
- unionBranch(ctx, ctx.addSyntheticFunction(item, options.tail === true), "%input", index === items.length - 1);
508
+ const isLast = index === items.length - 1;
509
+ unionBranch(ctx, ctx.addSyntheticFunction(item, options.tail === true && isLast), "%input", isLast);
509
510
  });
510
511
  }
511
512
  const prefix = linkage ? `define ${linkage} %k_result` : "define %k_result";
@@ -134,6 +134,13 @@ printf '{"x":"left","y":"right"}' \
134
134
  | node ../../codecs/k-print.mjs \
135
135
  | grep -qx '"left"'
136
136
 
137
+ node ../../objects/compile.mjs 't[] = < {} a, T b > = T; f = ?t[] < /b f, /b {} |a > ?t[]; /b f' "$TMP_DIR/nonfinal-tail.ko"
138
+ printf '{"b":{"b":"a"}}\n' \
139
+ | node ../../codecs/k-parse.mjs --input-type '?< {} a, T b > = T' \
140
+ | node ./bin/k-llvm.mjs --cache-dir "$TMP_DIR/jit-cache" "$TMP_DIR/nonfinal-tail.ko" \
141
+ | node ../../codecs/k-print.mjs \
142
+ | grep -qx '"a"'
143
+
137
144
  node --input-type=module -e "import { stdout } from 'node:process'; import { encodeToWire } from '../../codecs/runtime/prefix-codec.mjs'; import { Value } from '../../Value.mjs'; const pattern = [[\"open-union\",[[\"left\",1],[\"right\",1]]],[\"closed-product\",[]]]; stdout.write(encodeToWire(Value.variant(\"left\", Value.product({}), pattern), pattern));" \
138
145
  | node ./bin/k-llvm.mjs --cache-dir "$TMP_DIR/jit-cache" "$TMP_DIR/id.ko" \
139
146
  | node --input-type=module -e "import { stdin } from 'node:process'; import { decodeWire } from '../../codecs/runtime/prefix-codec.mjs'; const chunks = []; stdin.on('data', (chunk) => chunks.push(chunk)); stdin.on('end', () => console.log(JSON.stringify(decodeWire(Buffer.concat(chunks)).pattern)));" \
@@ -264,6 +264,26 @@ const { llvm: productRecurseLLVM } = compileObjectToLLVM(productRecurseObject, {
264
264
  // Calls inside product fields must not return tail status (i32 2)
265
265
  assert.doesNotMatch(productRecurseLLVM, /insertvalue %k_result undef, i32 2, 0/);
266
266
 
267
+ const unionNonFinalRecurseObject = decodeObject(compileObjectBuffer(`
268
+ t[] = < {} a, { T x } b > = T;
269
+ f = ?t[] <
270
+ /b .x f,
271
+ /b {} |a
272
+ > ?t[];
273
+ f
274
+ `, { source: "llvm-union-nonfinal-recurse.k" }));
275
+ const { llvm: unionNonFinalRecurseLLVM } = compileObjectToLLVM(unionNonFinalRecurseObject, {
276
+ relation: "f",
277
+ inputPattern: [
278
+ ["closed-union", [["a", 1], ["b", 2]]],
279
+ ["closed-product", []],
280
+ ["closed-product", [["x", 0]]]
281
+ ]
282
+ });
283
+ // Self-calls in non-final union branches must not be lowered as tail calls (status 2 or tail_loop)
284
+ assert.doesNotMatch(unionNonFinalRecurseLLVM, /insertvalue %k_result undef, i32 2, 0/);
285
+ assert.doesNotMatch(unionNonFinalRecurseLLVM, /tail_loop:/);
286
+
267
287
  const kvmArtifact = objectToKVMArtifact(productObject, "__main__");
268
288
  assert.equal(kvmArtifact.format, "k-vm");
269
289
  const kvmLLVM = compileLLVMArtifactFromKVM(kvmArtifact, {
@@ -197,14 +197,34 @@ export function lowerToWasm(relDef, name, options = {}) {
197
197
  return tailValueAfter(insts, index + 1, dest, inputMap, returnTarget, tailReturnTargets);
198
198
  }
199
199
 
200
- function selfTailCallAfterProduct(insts, index, productDest, inputMap, returnTarget, tailReturnTargets) {
201
- if (options.trace || inputProductFields.length === 0) return null;
202
- const callInst = insts[index + 1];
203
- if (!callInst || callInst.op !== "call" || callInst.func !== name) return null;
204
- if (mapsToReg(callInst.src, inputMap) !== productDest) return null;
205
- const callDest = cleanReg(callInst.dest);
206
- if (!tailValueAfter(insts, index + 2, callDest, inputMap, returnTarget, tailReturnTargets)) return null;
207
- return callInst;
200
+ function feedsSelfTailCall(
201
+ insts,
202
+ startIndex,
203
+ valueReg,
204
+ inputMap,
205
+ returnTarget,
206
+ tailReturnTargets,
207
+ tailCallInputTargets
208
+ ) {
209
+ if (options.trace || inputProductFields.length === 0) return false;
210
+ let current = valueReg;
211
+ for (let i = startIndex; i < insts.length; i++) {
212
+ const inst = insts[i];
213
+ if (inst.op === "guard_pattern" || inst.op === "guard_code" || inst.op === "id") {
214
+ if (mapsToReg(inst.src, inputMap) !== current) return false;
215
+ current = cleanReg(inst.dest);
216
+ continue;
217
+ }
218
+ if (inst.op === "call" && inst.func === name && mapsToReg(inst.src, inputMap) === current) {
219
+ const callDest = cleanReg(inst.dest);
220
+ return tailValueAfter(insts, i + 1, callDest, inputMap, returnTarget, tailReturnTargets);
221
+ }
222
+ if (inst.op === "return" && mapsToReg(inst.src, inputMap) === current) {
223
+ return Boolean(returnTarget && tailCallInputTargets.has(returnTarget));
224
+ }
225
+ return false;
226
+ }
227
+ return false;
208
228
  }
209
229
 
210
230
  function initInputProductLocals() {
@@ -252,7 +272,8 @@ export function lowerToWasm(relDef, name, options = {}) {
252
272
  returnTarget = null,
253
273
  failTarget = null,
254
274
  tailReturnTargets = new Set(),
255
- inputAliases = new Set(["in"])
275
+ inputAliases = new Set(["in"]),
276
+ tailCallInputTargets = new Set()
256
277
  ) {
257
278
  const lines = [];
258
279
  for (let index = 0; index < insts.length; index++) {
@@ -354,7 +375,15 @@ export function lowerToWasm(relDef, name, options = {}) {
354
375
  const dest = cleanReg(inst.dest);
355
376
  const rawSrc = cleanReg(inst.src);
356
377
  const src = inputMap[rawSrc] || rawSrc;
357
- const tailCall = selfTailCallAfterProduct(insts, index, dest, inputMap, returnTarget, tailReturnTargets);
378
+ const tailCall = feedsSelfTailCall(
379
+ insts,
380
+ index + 1,
381
+ dest,
382
+ inputMap,
383
+ returnTarget,
384
+ tailReturnTargets,
385
+ tailCallInputTargets
386
+ );
358
387
  const sortedBranches = [...inst.branches].sort((a, b) => {
359
388
  if (a.label < b.label) return -1;
360
389
  if (a.label > b.label) return 1;
@@ -382,8 +411,9 @@ export function lowerToWasm(relDef, name, options = {}) {
382
411
  { ...inputMap, "in": src },
383
412
  fieldTmp,
384
413
  failTarget,
385
- tailReturnTargets,
386
- new Set(inputAliases)
414
+ new Set(),
415
+ new Set(inputAliases),
416
+ new Set()
387
417
  );
388
418
  lines.push(branchWat);
389
419
  }
@@ -430,8 +460,9 @@ export function lowerToWasm(relDef, name, options = {}) {
430
460
  { ...inputMap, "in": src },
431
461
  fieldTmp,
432
462
  failTarget,
433
- tailReturnTargets,
434
- new Set(inputAliases)
463
+ new Set(),
464
+ new Set(inputAliases),
465
+ new Set()
435
466
  );
436
467
  lines.push(branchWat);
437
468
  }
@@ -549,9 +580,16 @@ export function lowerToWasm(relDef, name, options = {}) {
549
580
  const rawSrc = cleanReg(inst.src);
550
581
  const src = inputMap[rawSrc] || rawSrc;
551
582
  const N = inst.branches.length;
552
- const branchTailReturnTargets = tailValueAfter(insts, index + 1, dest, inputMap, returnTarget, tailReturnTargets)
553
- ? new Set([...tailReturnTargets, dest])
554
- : tailReturnTargets;
583
+ const unionIsTail = tailValueAfter(insts, index + 1, dest, inputMap, returnTarget, tailReturnTargets);
584
+ const unionFeedsSelfTailCall = feedsSelfTailCall(
585
+ insts,
586
+ index + 1,
587
+ dest,
588
+ inputMap,
589
+ returnTarget,
590
+ tailReturnTargets,
591
+ tailCallInputTargets
592
+ );
555
593
 
556
594
  const unionId = nextUnionId++;
557
595
  const arenaMark = `union_mark_${unionId}`;
@@ -566,6 +604,13 @@ export function lowerToWasm(relDef, name, options = {}) {
566
604
 
567
605
  for (let i = 0; i < N; i++) {
568
606
  const branch = inst.branches[i];
607
+ const isLast = i === N - 1;
608
+ const branchTailReturnTargets = isLast && unionIsTail
609
+ ? new Set([...tailReturnTargets, dest])
610
+ : new Set();
611
+ const branchTailCallInputTargets = unionFeedsSelfTailCall
612
+ ? new Set([...tailCallInputTargets, dest])
613
+ : (isLast && unionIsTail ? tailCallInputTargets : new Set());
569
614
  lines.push(` global.get $arena_free`);
570
615
  lines.push(` local.set $${arenaMark}`);
571
616
  const branchWat = compileInstructions(
@@ -574,7 +619,8 @@ export function lowerToWasm(relDef, name, options = {}) {
574
619
  dest,
575
620
  `$b${i}_try_${unionId}`,
576
621
  branchTailReturnTargets,
577
- new Set(inputAliases)
622
+ new Set(inputAliases),
623
+ branchTailCallInputTargets
578
624
  );
579
625
  lines.push(branchWat);
580
626
  lines.push(` br $union_done_${unionId}`);
@@ -54,6 +54,11 @@ compare_json_envelope "projected JSON number" \
54
54
  compare_json_envelope "closed product filter" \
55
55
  '{"a":[1,2,"kupa"], "b": 123}' \
56
56
  '?{X a, Y b}'
57
+ printf '{"b":{"b":"a"}}\n' |
58
+ node "$K_ROOT/codecs/k-parse.mjs" --input-type '?< {} a, T b > = T' |
59
+ node ./bin/k-wasm.mjs 't[] = < {} a, T b > = T; f = ?t[] < /b f, /b {} |a > ?t[]; /b f' |
60
+ node "$K_ROOT/codecs/k-print.mjs" |
61
+ grep -qx '"a"'
57
62
  printf '{"a":[1,2,"kupa"], "b": 123}\n' |
58
63
  node "$K_ROOT/codecs/json.mjs" --parse |
59
64
  node ./bin/k-wasm.mjs '{ .a.2 word, .b number }' |
@@ -448,8 +448,8 @@ console.log("==> Running End-to-End Peano Addition & Serialization Tests");
448
448
  inc = | +1 nat?;
449
449
  dec = nat? / +1;
450
450
  add = ?{ nat? x, nat? y } = X <
451
- { . x dec x, . y inc y } ?X add,
452
- . y
451
+ { . x / 0 a, . y then } . then,
452
+ { . x dec x, . y inc y } ?X add
453
453
  >;
454
454
  ()
455
455
  `;
@@ -625,4 +625,88 @@ console.log("==> Running End-to-End Peano Addition & Serialization Tests");
625
625
  console.log("End-to-End Peano Addition & Serialization tests passed successfully!");
626
626
  }
627
627
 
628
+ console.log("==> Running Union Non-Final Branch Recursion & Factored Tail-Call Tests (Issue #3)");
629
+ {
630
+ const runtimeWat = fs.readFileSync("runtime.wat", "utf8");
631
+
632
+ // 1. Issue #3: Self-call in a non-final union branch must NOT be tail-call optimized,
633
+ // because failure of the recursive call must backtrack to subsequent union branches
634
+ // with the original input.
635
+ const backtrackDefs = annotate(`
636
+ t[] = < {} a, { T x } b > = T;
637
+ f = ?t[] <
638
+ /b .x f,
639
+ /b {} |a
640
+ > ?t[];
641
+ main = ?t[] /b .x f;
642
+ ()
643
+ `, { convergence: { strategy: "auto" } });
644
+
645
+ const fWat = lowerToWasm(backtrackDefs.rels.f, "f");
646
+ const mainWat = lowerToWasm(backtrackDefs.rels.main, "main");
647
+ assert.match(fWat, /\bcall \$f\b/, "Self-call in non-final union branch must emit a regular call");
648
+ assert.doesNotMatch(fWat, /\bbr \$tail_loop\b/, "Self-call in non-final union branch must not jump to $tail_loop");
649
+
650
+ const fullBacktrackWat = runtimeWat.trim().slice(0, -1) + "\n" + fWat + "\n" + mainWat + "\n)";
651
+ const binaryBacktrack = compileWat("union_backtrack.wat", fullBacktrackWat);
652
+ const exportsBacktrack = await instantiateWasm(binaryBacktrack);
653
+
654
+ function writeUnit(exports) {
655
+ const ptr = exports.alloc(8);
656
+ const view = new DataView(exports.memory.buffer);
657
+ view.setUint32(ptr, 8, true);
658
+ view.setUint32(ptr + 4, 0, true);
659
+ return ptr;
660
+ }
661
+
662
+ function writeVariant(exports, tag, payloadPtr) {
663
+ const ptr = exports.alloc(12);
664
+ const view = new DataView(exports.memory.buffer);
665
+ view.setUint32(ptr, 12, true);
666
+ view.setUint32(ptr + 4, getTagId(tag), true);
667
+ view.setUint32(ptr + 8, payloadPtr, true);
668
+ return ptr;
669
+ }
670
+
671
+ function writeSingleFieldProduct(exports, label, valPtr) {
672
+ const ptr = exports.alloc(16);
673
+ const view = new DataView(exports.memory.buffer);
674
+ view.setUint32(ptr, 16, true);
675
+ view.setUint32(ptr + 4, 1, true);
676
+ view.setUint32(ptr + 8, getTagId(label), true);
677
+ view.setUint32(ptr + 12, valPtr, true);
678
+ return ptr;
679
+ }
680
+
681
+ // Construct b(b(a)) = {{{} |a x} |b x} |b
682
+ const aPtr = writeVariant(exportsBacktrack, "a", writeUnit(exportsBacktrack));
683
+ const baPtr = writeVariant(exportsBacktrack, "b", writeSingleFieldProduct(exportsBacktrack, "x", aPtr));
684
+ const bbaPtr = writeVariant(exportsBacktrack, "b", writeSingleFieldProduct(exportsBacktrack, "x", baPtr));
685
+
686
+ const resBacktrack = exportsBacktrack.main(bbaPtr);
687
+ assert.equal(resBacktrack[1], 1, "main(b(b(a))) must succeed by backtracking to branch 2 of f(b(a))");
688
+ const viewBacktrack = new DataView(exportsBacktrack.memory.buffer);
689
+ assert.equal(viewBacktrack.getUint32(resBacktrack[0] + 4, true), getTagId("a"), "main(b(b(a))) must return variant |a");
690
+
691
+ // 2. Factored tail-recursive union `< { ... }, { ... } > self` in the final branch of a union
692
+ // must forward product fields directly into $tail_in_* locals without allocating a product.
693
+ const factoredDefs = annotate(`
694
+ bits[] = < {} _, B 0, B 1 > = B;
695
+ eat = ?{ bits[] x, bits[] y } <
696
+ { .x /_ a, .y then } .then,
697
+ <
698
+ { .x /0 x, .y |0 y },
699
+ { .x /1 x, .y |1 y }
700
+ > eat
701
+ > ?bits[];
702
+ ()
703
+ `, { convergence: { strategy: "auto" } });
704
+
705
+ const eatWat = lowerToWasm(factoredDefs.rels.eat, "eat");
706
+ assert.doesNotMatch(eatWat, /\bcall \$eat\b/, "Factored tail-recursive union must not emit a Wasm self-call");
707
+ assert.match(eatWat, /;; tail-call field x/, "Factored tail-recursive union branches must forward product fields directly to $tail_in_*");
708
+
709
+ console.log("Union Non-Final Branch Recursion & Factored Tail-Call tests passed successfully!");
710
+ }
711
+
628
712
  console.log("==> Harness ready.");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fraczak/k",
3
- "version": "8.5.0",
3
+ "version": "8.5.1",
4
4
  "description": "k — a language for content-addressable schemas and data transformations over algebraic data types (products and tagged unions); includes runtime, contract derivation, REPL, and codec toolchain",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -1,5 +1,6 @@
1
1
  import assert from "node:assert";
2
2
  import fs from "node:fs";
3
+ import os from "node:os";
3
4
  import path from "node:path";
4
5
  import { spawn, spawnSync } from "node:child_process";
5
6
  import { fileURLToPath } from "node:url";
@@ -50,25 +51,36 @@ const chromiumBin = ["google-chrome", "chromium-browser", "chromium"].find(bin =
50
51
 
51
52
  if (chromiumBin) {
52
53
  console.log(`3. Running browser verification with ${chromiumBin}...`);
53
- const tmpDir = `/tmp/chrome-test-${Date.now()}`;
54
- fs.mkdirSync(tmpDir, { recursive: true });
54
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "k-browser-test-"));
55
55
 
56
- const cdpPort = 9333 + Math.floor(Math.random() * 500);
57
56
  const chrome = spawn(chromiumBin, [
58
57
  "--headless=new",
59
58
  "--disable-gpu",
60
- `--remote-debugging-port=${cdpPort}`,
59
+ "--remote-debugging-port=0",
61
60
  "--no-sandbox",
62
61
  "--disable-extensions",
63
62
  `--user-data-dir=${tmpDir}`,
64
63
  `file://${replHtmlPath}`
65
- ]);
64
+ ], { stdio: ["ignore", "ignore", "pipe"] });
65
+ let launchError;
66
+ let diagnostics = "";
67
+ chrome.on("error", error => { launchError = error; });
68
+ chrome.stderr.setEncoding("utf8");
69
+ chrome.stderr.on("data", chunk => { diagnostics = (diagnostics + chunk).slice(-16384); });
66
70
 
67
71
  try {
68
72
  let wsUrl = null;
69
- for (let i = 0; i < 30; i++) {
73
+ const deadline = Date.now() + 30000;
74
+ while (Date.now() < deadline) {
75
+ if (launchError) throw launchError;
76
+ if (chrome.exitCode !== null || chrome.signalCode !== null) {
77
+ throw new Error(`Chrome exited before startup (${chrome.exitCode ?? chrome.signalCode})\n${diagnostics}`);
78
+ }
70
79
  try {
71
- const res = await fetch(`http://127.0.0.1:${cdpPort}/json/list`);
80
+ const cdpPort = fs.readFileSync(path.join(tmpDir, "DevToolsActivePort"), "utf8").split("\n")[0];
81
+ const res = await fetch(`http://127.0.0.1:${cdpPort}/json/list`, {
82
+ signal: AbortSignal.timeout(1000)
83
+ });
72
84
  const list = await res.json();
73
85
  const page = list.find(item => item.url && item.url.includes("repl.html"));
74
86
  if (page && page.webSocketDebuggerUrl) {
@@ -79,7 +91,7 @@ if (chromiumBin) {
79
91
  await new Promise(r => setTimeout(r, 200));
80
92
  }
81
93
 
82
- assert(wsUrl, `Could not connect to Chromium CDP on port ${cdpPort}`);
94
+ assert(wsUrl, `Chrome debugging connection was not ready within 30 seconds\n${diagnostics}`);
83
95
 
84
96
  const ws = new WebSocket(wsUrl);
85
97
  await new Promise(r => ws.onopen = r);