@fraczak/k 9.0.0 → 9.1.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.
@@ -9,6 +9,9 @@ command -v clang >/dev/null || {
9
9
  exit 1
10
10
  }
11
11
 
12
+ clang -Iruntime runtime/krt.c tests/compaction-driver.c -o "$TMP_DIR/compaction"
13
+ "$TMP_DIR/compaction"
14
+
12
15
  node ../../objects/compile.mjs '()' "$TMP_DIR/id.ko"
13
16
  node ./bin/k-llvm-compile.mjs "$TMP_DIR/id.ko" "$TMP_DIR/id.ll"
14
17
  grep -q '@k_llvm_metadata' "$TMP_DIR/id.ll"
@@ -129,6 +132,21 @@ printf '987654321' \
129
132
  | node ../../codecs/int.mjs --print \
130
133
  | grep -qx '975461057789971041'
131
134
 
135
+ input_pattern='[["closed-union",[["a",1],["b",1]]],["closed-product",[]]]'
136
+ printf '"b"\n' | node ../../codecs/k-parse.mjs --input-type '?<{} a, {} b>' > "$TMP_DIR/b.wire"
137
+ node ./bin/k-llvm-build.mjs --input-pattern "$input_pattern" -o "$TMP_DIR/require-a" '/a'
138
+ if "$TMP_DIR/require-a" < "$TMP_DIR/b.wire" > "$TMP_DIR/failed.wire" 2> "$TMP_DIR/failed.err"; then
139
+ exit 1
140
+ else
141
+ test "$?" -eq 3
142
+ fi
143
+ test ! -s "$TMP_DIR/failed.wire"
144
+ grep -Fq 'kVM: evaluation failed' "$TMP_DIR/failed.err"
145
+ if node ../../codecs/int.mjs --print < "$TMP_DIR/failed.wire" 2> "$TMP_DIR/failed.err"; then
146
+ exit 1
147
+ fi
148
+ grep -Fq 'No k-wire input received on stdin' "$TMP_DIR/failed.err"
149
+
132
150
  printf '{"x":"left","y":"right"}' \
133
151
  | node ../../codecs/k-parse.mjs \
134
152
  | node ./bin/k-llvm.mjs --cache-dir "$TMP_DIR/jit-cache" "$TMP_DIR/run.ko" \
@@ -228,6 +228,8 @@ assert.match(unionLLVM, /call %k_result @k_union_arm_1\(ptr %rt, ptr %input\)/);
228
228
  assert.match(unionLLVM, /load ptr, ptr %mark_block_slot\d+/);
229
229
  assert.match(unionLLVM, /%rewind_fast_ok\d+ = and i1 %rewind_has_mark\d+, %rewind_same_block\d+/);
230
230
  assert.match(unionLLVM, /call void @k_rt_rewind\(ptr %rt, %k_rt_mark %mark\d+\)/);
231
+ // A fast rewind keeps older free blocks available for subsequent allocations.
232
+ assert.doesNotMatch(unionLLVM, /getelementptr i8, ptr %rt, i64 32/);
231
233
 
232
234
  const nestedUnionObject = decodeObject(compileObjectBuffer("{ < /x |left, /y |right > z }", { source: "llvm-nested-union.k" }));
233
235
  const { llvm: nestedUnionLLVM } = compileObjectToLLVM(nestedUnionObject, {
@@ -74,6 +74,7 @@ A module contains the reachable functions, the arena runtime from
74
74
  | `abi` | `"arena-v1"` |
75
75
  | `entry` | Exported function called by the runner |
76
76
  | `inputPattern` / `outputPattern` | Patterns used by the arena adapters |
77
+ | `wireIdentity` | Optional compiler proof that the entry returns its input under one closed contract |
77
78
  | `tags` | Statically known variant tags and their IDs |
78
79
 
79
80
  The entry ABI is `(input_pointer i32) -> (output_pointer i32, ok i32)`.
@@ -91,6 +92,10 @@ contract is needed.
91
92
 
92
93
  ## Limits and implementation
93
94
 
95
+ The wire runner can forward the bytes for a proven identity after validating
96
+ the complete payload and matching the canonical header. This path skips arena
97
+ conversion. Frames with other headers go through the normal adapter.
98
+
94
99
  A `.wasm` file still needs a host that understands the arena ABI and metadata.
95
100
  The CLI host is Node.js; the browser REPL bundles its own in-process adapter.
96
101
 
@@ -16,6 +16,7 @@ import {
16
16
  specializeKVM,
17
17
  specializeObjectRelations
18
18
  } from "@fraczak/k/backend-api.mjs";
19
+ import { makeWireValidator } from "@fraczak/k/codecs/runtime/prefix-codec.mjs";
19
20
  import { intersectPropertyListPatterns } from "@fraczak/k/codecs/runtime/codec.mjs";
20
21
  import { propertyListToFilter } from "@fraczak/k/codecs/runtime/show-value.mjs";
21
22
  import { parse } from "@fraczak/k/index.mjs";
@@ -288,6 +289,7 @@ function compileModule(mainRelName, defs) {
288
289
  const queue = [mainRelName];
289
290
  const wats = [];
290
291
  const nameMap = cleanFunctionNameMap(Object.keys(defs.rels));
292
+ let entryBody;
291
293
 
292
294
  while (queue.length > 0) {
293
295
  const name = queue.shift();
@@ -300,6 +302,7 @@ function compileModule(mainRelName, defs) {
300
302
  }
301
303
 
302
304
  const kvmFunc = lowerToKVM(relDef, name);
305
+ if (name === mainRelName) entryBody = kvmFunc.body;
303
306
  kvmFunc.typePatternGraph = relDef.typePatternGraph;
304
307
  scanCalls(kvmFunc.body, compiled, queue);
305
308
 
@@ -312,6 +315,7 @@ function compileModule(mainRelName, defs) {
312
315
  return {
313
316
  wat: wats.join("\n\n"),
314
317
  relationNames: [...compiled],
318
+ entryBody,
315
319
  entryName: nameMap.get(mainRelName) || cleanName(mainRelName)
316
320
  };
317
321
  }
@@ -413,6 +417,27 @@ function isMonomorphicPattern(pattern) {
413
417
  pattern.every(([kind]) => kind === "closed-product" || kind === "closed-union");
414
418
  }
415
419
 
420
+ function sameClosedPattern(inputPattern, outputPattern) {
421
+ return isMonomorphicPattern(inputPattern) &&
422
+ JSON.stringify(inputPattern) === JSON.stringify(outputPattern);
423
+ }
424
+
425
+ // Prove a straight-line return of the original input. Every guard must be
426
+ // implied by the contract that will be checked at the wire boundary.
427
+ function isWireIdentity(body, inputPattern, outputPattern) {
428
+ if (!sameClosedPattern(inputPattern, outputPattern) || !body?.length) return false;
429
+ const contract = JSON.stringify(inputPattern);
430
+ let input = "%in";
431
+ for (const inst of body.slice(0, -1)) {
432
+ if (inst.src !== input || !inst.dest) return false;
433
+ if (inst.op !== "id" &&
434
+ !(inst.op === "guard_pattern" && JSON.stringify(inst.pattern) === contract)) return false;
435
+ input = inst.dest;
436
+ }
437
+ const last = body[body.length - 1];
438
+ return last.op === "return" && last.src === input;
439
+ }
440
+
416
441
  function classifyTyping(inputPattern, outputPattern, status = "unknown", mode = "generic") {
417
442
  const input = isMonomorphicPattern(inputPattern) ? "monomorphic" : "polymorphic";
418
443
  const output = isMonomorphicPattern(outputPattern) ? "monomorphic" : "polymorphic";
@@ -481,7 +506,7 @@ async function compileWasmArtifactFromDefs(
481
506
  throw new Error(`No main relation (${mainRelName}) defined in script`);
482
507
  }
483
508
 
484
- const { wat: moduleWatBody, relationNames, entryName } = compileModule(
509
+ const { wat: moduleWatBody, relationNames, entryName, entryBody } = compileModule(
485
510
  mainRelName,
486
511
  defs
487
512
  );
@@ -497,6 +522,7 @@ async function compileWasmArtifactFromDefs(
497
522
  entry: entryName || cleanName(mainRelName),
498
523
  inputPattern,
499
524
  outputPattern,
525
+ ...(isWireIdentity(entryBody, inputPattern, outputPattern) && { wireIdentity: true }),
500
526
  typing: classifyTyping(
501
527
  inputPattern,
502
528
  outputPattern,
@@ -566,6 +592,7 @@ async function compileWasmArtifactFromKVM(kvmInput, options = {}) {
566
592
  relation,
567
593
  inputPattern: mainFunc.inputPattern,
568
594
  outputPattern: mainFunc.outputPattern,
595
+ ...(isWireIdentity(mainFunc.body, mainFunc.inputPattern, mainFunc.outputPattern) && { wireIdentity: true }),
569
596
  typing: classifyTyping(
570
597
  mainFunc.inputPattern,
571
598
  mainFunc.outputPattern,
@@ -957,9 +984,31 @@ async function instantiateWasmArtifact(wasmBuffer) {
957
984
  const tags = createTagRegistry(metadata.tags);
958
985
  const inputPattern = propertyListToPattern(metadata.inputPattern);
959
986
  const outputPattern = propertyListToPattern(metadata.outputPattern);
987
+ const validateIdentityWire = metadata.wireIdentity === true &&
988
+ sameClosedPattern(metadata.inputPattern, metadata.outputPattern)
989
+ ? makeWireValidator(metadata.outputPattern)
990
+ : null;
960
991
 
961
992
  function execute(inputBuffer, options = {}) {
962
993
  const t0 = process.hrtime.bigint();
994
+ if (validateIdentityWire?.(inputBuffer)) {
995
+ const validated = process.hrtime.bigint();
996
+ const outputWire = Buffer.from(inputBuffer);
997
+ if (!options.trace) return outputWire;
998
+ const done = process.hrtime.bigint();
999
+ return {
1000
+ outputWire,
1001
+ trace: {
1002
+ decodeNs: Number(validated - t0),
1003
+ flatInNs: 0,
1004
+ evalNs: 0,
1005
+ flatOutNs: 0,
1006
+ encodeNs: Number(done - validated),
1007
+ totalNs: Number(done - t0)
1008
+ }
1009
+ };
1010
+ }
1011
+
963
1012
  const { pattern: valuePattern, value } = decodeWire(inputBuffer);
964
1013
  if (!isMonomorphicPattern(metadata.inputPattern)) {
965
1014
  validateInputEnvelope(metadata.inputPattern, valuePattern);
@@ -141,9 +141,14 @@ console.log("==> Running Compiler Scaffolding Tests (id, fail, return)");
141
141
  console.log("Compiler Scaffolding tests passed successfully!");
142
142
  }
143
143
 
144
- import { annotate, objectToKVMArtifact } from "@fraczak/k/backend-api.mjs";
144
+ import { annotate, encodeToWire, objectToKVMArtifact } from "@fraczak/k/backend-api.mjs";
145
145
  import { compileObjectBuffer, decodeObject } from "@fraczak/k/object.mjs";
146
- import { compileWasmArtifactFromKVM, metadataFromModule } from "../src/wasm.mjs";
146
+ import {
147
+ compileWasmArtifact,
148
+ compileWasmArtifactFromKVM,
149
+ instantiateWasmArtifact,
150
+ metadataFromModule
151
+ } from "../src/wasm.mjs";
147
152
  import { getTagId } from "../src/kvm2wasm.mjs";
148
153
 
149
154
  console.log("==> Running Wrapped kVM Artifact Test");
@@ -160,6 +165,40 @@ console.log("==> Running Wrapped kVM Artifact Test");
160
165
  assert(!("instanceKey" in metadata));
161
166
  assert.deepEqual(metadata.inputPattern, artifact.inputPattern);
162
167
  assert.deepEqual(metadata.outputPattern, artifact.outputPattern);
168
+ assert.equal(metadata.wireIdentity, true);
169
+ }
170
+
171
+ console.log("==> Running Validated Wire Identity Tests");
172
+ {
173
+ const source = "?<{} a, {} b, {} c> ()";
174
+ const runner = await instantiateWasmArtifact(await compileWasmArtifact(source));
175
+ assert.equal(runner.metadata.wireIdentity, true);
176
+ const value = Value.variant("b", Value.product({}));
177
+ const frame = encodeToWire(value, runner.metadata.inputPattern);
178
+ const mark = runner.exports.arena_mark();
179
+ const { outputWire, trace } = runner.execute(frame, { trace: true });
180
+ assert.deepEqual(outputWire, frame);
181
+ assert.equal(trace.flatInNs, 0);
182
+ assert.equal(trace.evalNs, 0);
183
+ assert.equal(trace.flatOutNs, 0);
184
+ assert.equal(runner.exports.arena_mark(), mark);
185
+ assert.equal(runner.executeValue(value).tag, "b");
186
+
187
+ const differentHeader = encodeToWire(value);
188
+ assert.notDeepEqual(differentHeader, frame);
189
+ assert.deepEqual(runner.execute(differentHeader), frame);
190
+ assert.throws(() => runner.execute(Buffer.concat([frame, Buffer.alloc(1)])), /trailing bytes/);
191
+
192
+ const invalidChoice = Buffer.from(frame);
193
+ const otherTag = encodeToWire(Value.variant("c", Value.product({})), runner.metadata.inputPattern);
194
+ for (let i = 0; i < frame.length; i++) invalidChoice[i] |= otherTag[i];
195
+ assert.throws(() => runner.execute(invalidChoice), /Invalid choice/);
196
+
197
+ const changesValue = await instantiateWasmArtifact(
198
+ await compileWasmArtifact("?<{} a, {} b, {} c> < /a |b, /b |c, /c |a >")
199
+ );
200
+ assert.equal(changesValue.metadata.wireIdentity, undefined);
201
+ assert.notDeepEqual(changesValue.execute(frame), frame);
163
202
  }
164
203
 
165
204
  console.log("==> Running Product Operations Integration Tests");
@@ -84,6 +84,7 @@ function runCodecCLI(metaUrl, codec) {
84
84
  stdout.write(wire);
85
85
  } else {
86
86
  const buf = await readAll(stdin);
87
+ if (buf.length === 0) throw new Error("No k-wire input received on stdin");
87
88
  const { value } = decodeWire(buf);
88
89
  const output = codec.print(value);
89
90
  if (Buffer.isBuffer(output) || codec.addNewline === false) {
@@ -550,18 +550,83 @@ function encodeToWire(value, propertyList) {
550
550
  return writer.toBuffer();
551
551
  }
552
552
 
553
+ // Match the exact canonical header and validate the packed payload without
554
+ // constructing a K value. A different header needs the ordinary codec path.
555
+ function makeWireValidator(propertyList) {
556
+ const pattern = canonicalizePattern(propertyListToPattern(propertyList));
557
+ const writer = new BitWriter();
558
+ encodeNode(writer, patternToKValue(patternToPropertyList(pattern)), CORE_PATTERN_PATTERN, 0);
559
+ const { byteLength, bitCount } = writer;
560
+ const header = writer.toBuffer();
561
+ const mask = (0xff << (8 - bitCount)) & 0xff;
562
+
563
+ return (buffer) => {
564
+ if (!Buffer.isBuffer(buffer) || buffer.length < header.length) return false;
565
+ for (let i = 0; i < byteLength; i++) {
566
+ if (buffer[i] !== header[i]) return false;
567
+ }
568
+ if (bitCount && (buffer[byteLength] & mask) !== header[byteLength]) return false;
569
+
570
+ const reader = new BitReader(buffer);
571
+ reader.byteOffset = byteLength;
572
+ reader.bitOffset = bitCount;
573
+ validatePackedPayload(reader, pattern);
574
+ return true;
575
+ };
576
+ }
577
+
578
+ function validatePackedPayload(reader, pattern) {
579
+ // An active node can recur only after the scan has consumed input.
580
+ const activeAt = new Float64Array(pattern.nodes.length).fill(-1);
581
+ const stack = [];
582
+ let id = 0;
583
+ for (;;) {
584
+ const node = pattern.nodes[id];
585
+ const position = reader.byteOffset * 8 + reader.bitOffset;
586
+ const previous = activeAt[id];
587
+ if (previous === position) throw new Error("Non-consuming recursive wire pattern");
588
+ activeAt[id] = position;
589
+ const frame = { id, previous, next: 0 };
590
+ stack.push(frame);
591
+ if (node.kind === NODE_KIND.CLOSED_UNION) {
592
+ const ordinal = reader.readBits(node.choiceBits ?? choiceWidth(node.edges.length));
593
+ if (!node.edges[ordinal]) throw new Error(`Invalid choice ${ordinal} at pattern node ${id}`);
594
+ frame.next = node.edges.length;
595
+ id = node.edges[ordinal].target;
596
+ continue;
597
+ }
598
+ if (node.kind !== NODE_KIND.CLOSED_PRODUCT) throw new Error("Expected a closed wire pattern");
599
+
600
+ while (stack.length > 0) {
601
+ const top = stack[stack.length - 1];
602
+ const edges = pattern.nodes[top.id].edges;
603
+ if (top.next < edges.length) {
604
+ id = edges[top.next++].target;
605
+ break;
606
+ }
607
+ activeAt[top.id] = top.previous;
608
+ stack.pop();
609
+ }
610
+ if (stack.length === 0) break;
611
+ }
612
+ if ((reader.buffer.length - reader.byteOffset) * 8 - reader.bitOffset >= 8) {
613
+ throw new Error("Extra trailing bytes after wire payload");
614
+ }
615
+ reader.assertZeroPadding();
616
+ }
617
+
553
618
  function readBitsAt(buffer, bitOffset, width) {
554
619
  if (width === 0) return 0;
555
- if ((bitOffset + width - 1) >> 3 >= buffer.length) {
620
+ if (Math.floor((bitOffset + width - 1) / 8) >= buffer.length) {
556
621
  throw new Error("Unexpected end of bitstream");
557
622
  }
558
623
  if (width === 1) {
559
- return (buffer[bitOffset >> 3] >> (7 - (bitOffset & 7))) & 1;
624
+ return (buffer[Math.floor(bitOffset / 8)] >> (7 - (bitOffset & 7))) & 1;
560
625
  }
561
626
  let v = 0;
562
627
  for (let i = 0; i < width; i++) {
563
628
  const pos = bitOffset + i;
564
- v = (v << 1) | ((buffer[pos >> 3] >> (7 - (pos & 7))) & 1);
629
+ v = (v << 1) | ((buffer[Math.floor(pos / 8)] >> (7 - (pos & 7))) & 1);
565
630
  }
566
631
  return v;
567
632
  }
@@ -1005,7 +1070,8 @@ export {
1005
1070
  propertyListToPattern,
1006
1071
  patternToPropertyList,
1007
1072
  choiceWidth,
1008
- CORE_PATTERN_PROPERTY_LIST
1073
+ CORE_PATTERN_PROPERTY_LIST,
1074
+ makeWireValidator
1009
1075
  };
1010
1076
  export default {
1011
1077
  encodeToWire,
@@ -1,10 +1,15 @@
1
1
  /**
2
2
  * kTVM Channel ADT (`BitDeque`), Kernel-Local LIFO `BitStack`, and `QuotaTracker`.
3
3
  *
4
- * Implements DOCS/KTVM_SPEC.md §3:
5
- * - SPSC bit-addressable double-ended queue with power-of-2 Uint32Array ring buffer
6
- * - Dual schema state `(prodSchema, consSchema)` + `aligned` boundary flag
7
- * - Strictly monotone status lifecycle: `OPEN -> CLOSED | FAILED`
4
+ * Implements DOCS/KTVM_SPEC.md §3 and the 8-tuple channel state:
5
+ * c = <buf, st, prodSchema, consSchema, aligned, prod, cons, scope>
6
+ * - buf: unread bit sequence in a power-of-2 Uint32Array ring buffer
7
+ * - st (`status`): strictly monotone lifecycle `OPEN -> CLOSED | FAILED`
8
+ * - prodSchema / prodNodeId: suffix schema owed by producer at value boundaries
9
+ * - consSchema / consNodeId: full schema expected by consumer at value boundaries
10
+ * - aligned: consumer boundary-alignment flag (`true` iff no mid-value bits shifted)
11
+ * - prod, cons: unique owning producer / consumer handles (SPSC linearity)
12
+ * - scope: enclosing speculation scope ID (`0` = root scope)
8
13
  * - Global byte / node / step quota enforcement (`KTVMQuotaError`)
9
14
  */
10
15
 
@@ -131,6 +136,16 @@ export class BitDeque {
131
136
  return this.status === CHAN_STATUS.FAILED;
132
137
  }
133
138
 
139
+ /** Singleton residual node list `[prodNodeId]` at the producer's aligned boundary. */
140
+ get prodNodeList() {
141
+ return this.prodSchema ? [this.prodNodeId] : [];
142
+ }
143
+
144
+ /** Singleton residual node list `[consNodeId]` at the consumer's aligned boundary. */
145
+ get consNodeList() {
146
+ return this.consSchema ? [this.consNodeId] : [];
147
+ }
148
+
134
149
  hasBits(n = 1) {
135
150
  return this.lenBits >= n;
136
151
  }
package/ktvm/index.mjs CHANGED
@@ -32,6 +32,12 @@ export {
32
32
  mooreMinimize,
33
33
  mooreKey,
34
34
  schemasEquivalent,
35
+ normalizeNodeList,
36
+ nodeListComplete,
37
+ stepNodeListTag,
38
+ stepNodeListLabel,
39
+ wireLanguageKey,
40
+ wireLanguagesEqual,
35
41
  isUnitSchema,
36
42
  unionTagInfo,
37
43
  unionOrdinalInfo,
@@ -55,10 +61,15 @@ export {
55
61
  decodeDequeToValue,
56
62
  writeBytesToDeque,
57
63
  dequeToPaddedBytes,
64
+ splitWireHeaderOnly,
58
65
  splitEnvelopedWire,
59
66
  frameEnvelopedWire,
60
67
  encodeValueToEnvelopedWire,
61
68
  decodeEnvelopedWireToValue,
69
+ createSchemaCursor,
70
+ cursorNodeList,
71
+ stepSchemaCursor,
72
+ scanBufferAlignedOffset,
62
73
  createDpdaSkip,
63
74
  stepDpdaSkip,
64
75
  createDpdaCopy,