@fraczak/k 9.0.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 CHANGED
@@ -5,6 +5,17 @@ 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
+ ## [9.1.0] — 2026-11-29 — Runtime Improvements and Published kTVM Paper
9
+
10
+ - Reuse LLVM arena blocks after same-block rollback in kVM, reducing repeated allocation.
11
+ - Forward validated wire for proven kVM WebAssembly identities and validate kTVM
12
+ WebAssembly input in its existing channel buffer.
13
+ - Document the current kTVM implementation, schema derivatives, prime decomposition,
14
+ specialization paths, and backend trade-offs in the reviewed compiler paper.
15
+ - Publish [kTVM: A Packed-Wire Execution Model and Compiler for K](https://zenodo.org/records/24653605)
16
+ and link the preprint, PDF, and LaTeX source from the README.
17
+ - Add reproducible compiler performance baselines and update profiling tools and documentation.
18
+
8
19
  ## [9.0.0] — 2026-11-26 — kTVM Packed-Wire Transducer VM, Wasm & LLVM Backends, and PKIR Removal
9
20
 
10
21
  - **Breaking Changes (PKIR Removal)**:
package/DOCS/KTVM_SPEC.md CHANGED
@@ -21,7 +21,7 @@ Its design rests on five core principles:
21
21
  2. **Two-Layer Polymorphism (`kTVM-P` → `kTVM`):** Mirrors K's `KIR-P`/`KVM-P` layering. A polymorphic `kTVM-P` module declares schema parameters and open pattern constraints. When a concrete enveloped `k-wire` input arrives at the execution boundary, **input-schema compatibility checking** is unified with **shape refinement**, binding schema parameters, splitting accessed product channels, resolving tag bit-widths, pruning dead branches, and specializing procedures into a concrete monomorphic `kTVM` module.
22
22
  3. **Two-Tier Execution ISA (Network + Kernel):**
23
23
  - The **Network Layer** dynamically instantiates finite transducer DAGs over bit-addressable `BitDeque` channels, supporting lazy demand-driven recursion (`spawn`), bounded-topology branching recursion (`spawn_seq` / `after`), deterministic multi-port switching (`switch`), bit-exact speculative backtracking (`spec`), strict partiality draining (`drain`/`barrier`/`gate`), and $O(1)$ zero-copy graph rewrites (`splice`, `wrap`/`match`, `mux`/`demux` fusion).
24
- - The **Kernel Layer** executes compiled single-node deterministic state machines, tail-modulo-constructor (TMC) streaming loops, local-register/local-stack automata, and static **variable-width bit-chunk tables** selected under Howard's Minimum Weight-to-Time Ratio (MWTR) criterion.
24
+ - The **Kernel Layer** executes compiled single-node deterministic state machines, tail-modulo-constructor (TMC) streaming loops, local-register/local-stack automata, and static **variable-width bit-chunk tables** selected under the Minimum Weight-to-Time Ratio (MWTR) criterion ([speed-eval.pdf](speed-eval.pdf)).
25
25
  4. **Formal Soundness by Construction:** Every operational invariant (dual producer/consumer channel schemas, exact value-boundary alignment, upstream-failure vs. local-mismatch separation, strict discarded-input draining, iterative non-recursive pushdown traversal) is encoded directly into the machine state and static validation rules.
26
26
  5. **Backend & Storage Independence:** The textual DSL (`.ktvmp` / `.ktvm`) is both human-readable and machine-verifiable, serving as the single contract between the K front-end/optimizers and multiple execution targets (JS reference VM, C/LLVM, WebAssembly). The `BitDeque` channel model is encapsulated behind an abstract ADT interface so alternative backing representations can be explored without altering VM semantics.
27
27
 
@@ -32,7 +32,7 @@ flowchart LR
32
32
  KTVMP --> SPEC
33
33
  SPEC -->|"Schema Contradiction"| ERR["Static Schema Error"]
34
34
  SPEC -->|"Compatible: (S_in -> S_out)"| KTVM["Concrete kTVM Module (.ktvm)<br/>Closed schemas, split ports, exact widths"]
35
- KTVM --> OPT["kTVM -> kTVM Passes<br/>CPS TMC Fusion, Bit-Chunk & Howard MWTR"]
35
+ KTVM --> OPT["kTVM -> kTVM Passes<br/>CPS TMC Fusion, Bit-Chunk & MWTR"]
36
36
  OPT --> EXEC["Backends<br/>Ref VM / C / LLVM / Wasm"]
37
37
  EXEC --> OUT["k-wire Output Envelope<br/>(S_out, payload bits)"]
38
38
  ```
@@ -60,24 +60,27 @@ A schema expression $\sigma$ is formed over a finite set of named recursive sche
60
60
 
61
61
  **Canonical Label Order:** Within any `product` or `union`, labels are unique and sorted strictly in canonical K Unicode code-point order (matching `prefix-codec.mjs`). An empty union `union {}` has no valid values ($\mathcal{L}(\texttt{union \{\}}) = \emptyset$).
62
62
 
63
- ### 2.2 Regular-Tree Equivalence (Moore Quotient)
63
+ ### 2.2 Structural Wire Equivalence and Bit-Level $s$-Language Equivalence
64
64
 
65
- Every closed schema $\sigma$ denotes a finite deterministic tree automaton (property-list graph) $G(\sigma) = (V, E, v_0)$. Two closed schemas $\sigma_1, \sigma_2$ are **wire-equivalent** (written $\sigma_1 \equiv \sigma_2$) iff their **Moore minimal bisimulation quotients** are isomorphic:
66
- - Same node kind (`closed-product` or `closed-union`) at every reachable state pair;
67
- - Identical ordered edge label lists at every reachable state pair;
68
- - Equivalent child target states for every edge.
65
+ Every closed schema $\sigma$ denotes a finite deterministic tree automaton (property-list graph) $G(\sigma) = (V, E, v_0)$. Two closed schemas $\sigma_1, \sigma_2$ are **structurally wire-equivalent** (written $\sigma_1 \equiv \sigma_2$) iff their rooted labeled graphs are bisimilar (equivalently, their minimal quotients under bisimulation, computed by `mooreMinimize` / `schemasEquivalent`, are isomorphic):
66
+ - Same node kind (`closed-product` or `closed-union`) at every related vertex pair;
67
+ - Identical ordered edge label lists at every related vertex pair;
68
+ - Related target vertices for every edge.
69
69
 
70
- Because `k-wire` serialization depends *solely* on node kinds and canonical ordered edge lists, $\sigma_1 \equiv \sigma_2 \implies \mathcal{L}(\sigma_1) = \mathcal{L}(\sigma_2)$ bit-for-bit. Consequently, zero-copy `splice` is sound between any two wire-equivalent schemas without inspecting a single payload bit.
70
+ Because `k-wire` serialization depends *solely* on node kinds and canonical ordered edge lists, $\sigma_1 \equiv \sigma_2 \implies \mathcal{L}(\sigma_1) = \mathcal{L}(\sigma_2)$ bit-for-bit. Consequently, zero-copy `splice` is sound between any two wire-equivalent schemas without inspecting a single payload bit, while preserving K label identity for `coerce`, `mux`/`demux` fusion, and `kTVM-P` contract unification.
71
71
 
72
- ### 2.3 Prefix Derivative ($\partial_w \sigma$)
72
+ At the raw bit-language level ($\mathcal{L}(\sigma) \subseteq \{0,1\}^*$), `schema.mjs` additionally provides a strictly coarser label-erased equivalence (`wireLanguageKey` / `wireLanguagesEqual`) that flattens associative product nesting, eliminates empty units and $1$-tag ($0$-bit) unions, prunes empty branches, expands multi-bit tags into binary $\{0,1\}$ decision tries, and applies sound right-suffix factoring before minimization.
73
73
 
74
- For a closed schema $\sigma$ and a valid bit prefix $w \in \{0,1\}^*$, the **schema derivative** tracks the remaining suffix obligation after emitting $w$:
75
- - For $\sigma = \texttt{union \{ } t_0:\sigma_0, \dots, t_{n-1}:\sigma_{n-1} \texttt{ \}}$ with $w = \mathrm{bits}_{\lceil\log_2 n\rceil}(i)$:
76
- $$\sigma \xrightarrow{|t_i} \sigma_i$$
77
- - For $\sigma = \texttt{product \{ } f_0:\sigma_0, \dots, f_{m-1}:\sigma_{m-1} \texttt{ \}}$ after emitting complete valid values for fields $f_0 \dots f_{k-1}$:
78
- $$\sigma \xrightarrow{f_0 \cdots f_{k-1}} \texttt{product \{ } f_k:\sigma_k, \dots, f_{m-1}:\sigma_{m-1} \texttt{ \}}$$
79
- and specifically after $f_0 \dots f_{m-2}$, the remaining suffix obligation is simply $\sigma_{m-1}$.
80
- - For $\sigma = \texttt{unit}$: emitting $\varepsilon$ completes the value ($\sigma \xrightarrow{\varepsilon} \bot_{\text{done}}$).
74
+ ### 2.3 Prefix Derivatives as Node Lists
75
+
76
+ Every closed `k-wire` payload language $\mathcal{L}(\sigma) \subseteq \{0,1\}^*$ is a simple language ($s$-language); by the characterization of $s$-languages via finite prime generators in Fraczak & Podolak (*Inf. Process. Lett.* 89(2), 2004) and Bastien–Czyzowicz–Fraczak–Rytter (*TCS* 363(2), 2006), every left quotient $w^{-1}\mathcal{L}(\sigma)$ factors as a finite concatenation of sub-languages. Directly on $G(\sigma) = (V, E, v_0)$, writing $\mathcal{L}([v_1, \dots, v_k]) = \mathcal{L}(v_1)\cdots\mathcal{L}(v_k)$ (with $\mathcal{L}([]) = \{\varepsilon\}$), the residual pattern at any *aligned* offset (after complete union tags or sub-values, without stopping mid-tag) is represented by a finite list of graph nodes $[v_1, \dots, v_k] \in V^*$: $v_1$ is the schema of the sub-value starting at that offset and $[v_2, \dots, v_k]$ is the continuation of remaining sibling and ancestor sub-patterns.
77
+ - **Head-Rewriting Prefix Derivative Rules (`normalizeNodeList`, `stepNodeListTag`, `stepNodeListLabel`, `scanBufferAlignedOffset`):**
78
+ 1. **Unit elimination ($\varepsilon$):** $[v_{\{\}},\, \vec{u}] \equiv \vec{u}$.
79
+ 2. **Product expansion:** $[v_{\{u_0\,f_0, \dots, u_{m-1}\,f_{m-1}\}},\, \vec{u}] \equiv [u_0, \dots, u_{m-1},\, \vec{u}]$.
80
+ 3. **Tag step:** $[v_{\langle u_0\,t_0, \dots, u_{n-1}\,t_{n-1}\rangle},\, \vec{u}] \xrightarrow{|t_i} [u_i,\, \vec{u}]$ ($0 \le i < n$, consuming $\mathrm{bits}_{\lceil\log_2 n\rceil}(i)$).
81
+ 4. **Complete sub-value step:** $[v_1,\, \vec{u}] \xrightarrow{d \in \mathcal{L}(v_1)} \vec{u}$.
82
+
83
+ Reaching the empty list $[]$ completes the encoding with residual language $\{\varepsilon\}$. In particular, emitting a union tag $|t_i$ reduces $[v_{\langle\dots\rangle}]$ to the singleton $[u_i]$, and emitting fields $f_0 \dots f_{m-2}$ of an $m$-field product reduces $[v_{\{u_0\dots u_{m-1}\}}]$ to the singleton $[u_{m-1}]$.
81
84
 
82
85
  ---
83
86
 
@@ -85,18 +88,20 @@ For a closed schema $\sigma$ and a valid bit prefix $w \in \{0,1\}^*$, the **sch
85
88
 
86
89
  ### 3.1 Abstract Channel ADT (`BitDeque`)
87
90
 
88
- The uniform communication primitive in `kTVM` is a **Single-Producer, Single-Consumer (SPSC)** bit-addressable double-ended queue (`BitDeque`). Each live channel $c$ has abstract state:
91
+ The uniform communication primitive in `kTVM` is a **Single-Producer, Single-Consumer (SPSC)** bit-addressable double-ended queue (`BitDeque`). Each live channel $c$ has abstract 8-tuple state:
89
92
 
90
93
  $$c = \langle \text{buf} \in \{0,1\}^*,\; \text{status} \in \{\mathsf{OPEN}, \mathsf{CLOSED}, \mathsf{FAILED}\},\; \sigma_{\text{prod}},\; \sigma_{\text{cons}},\; \text{aligned} \in \mathbb{B},\; \text{prod},\; \text{cons},\; \text{scope} \rangle$$
91
94
 
92
95
  Where:
93
- - `buf`: Unread bit sequence. Producers append at the back (`push_bits`); consumers read/remove from the front (`peek_bits`, `shift_bits`). Prefix constructors, tail-splicers, and speculative rollbacks prepend at the front (`unshift_bits`, `unshift_deque`).
94
- - `status`: Strictly monotone lifecycle:
96
+ - `buf` $\in \{0,1\}^*$: Unread bit sequence. Producers append at the back (`push_bits`); consumers read/remove from the front (`peek_bits`, `shift_bits`). Prefix constructors, tail-splicers, and speculative rollbacks prepend at the front (`unshift_bits`, `unshift_deque`).
97
+ - `status` $\in \{\mathsf{OPEN}, \mathsf{CLOSED}, \mathsf{FAILED}\}$: Strictly monotone lifecycle:
95
98
  $$\mathsf{OPEN} \longrightarrow \mathsf{CLOSED} \qquad \text{or} \qquad \mathsf{OPEN} \longrightarrow \mathsf{FAILED}$$
96
- Once `CLOSED` or `FAILED`, `status` is immutable and no further producer writes occur.
97
- - `aligned`: `true` iff the consumer has not partially consumed a value from the current $\sigma_{\text{cons}}$ boundary (i.e., `buf` followed by the producer's remaining stream forms a complete value of $\sigma_{\text{cons}}$).
98
- - `prod`, `cons`: Unique owning producer node ID (or `EXT_IN` / `NONE` once closed) and unique owning consumer node ID (or `EXT_OUT`).
99
- - `scope`: Enclosing speculation scope ID (root scope is `0`).
99
+ Once `CLOSED` or `FAILED`, `status` is immutable, `prod = NONE`, and no further producer writes occur (a `CLOSED` channel may still hold unread bits in `buf`).
100
+ - $\sigma_{\text{prod}}, \sigma_{\text{cons}} \in \mathcal{S}_{\text{closed}}$: Closed schema states in the module's pattern graphs. $\sigma_{\text{cons}}$ is the full schema expected by the consumer starting at its last value boundary; $\sigma_{\text{prod}}$ is the suffix schema still owed by the producer at the back of `buf` at producer value boundaries (initially $\sigma_{\text{prod}} = \sigma_{\text{cons}}$).
101
+ - `aligned` $\in \mathbb{B} = \{\mathrm{true}, \mathrm{false}\}$: `true` iff the consumer has not partially consumed bits from the current $\sigma_{\text{cons}}$ boundary (so bit $0$ of `buf` starts a complete $\sigma_{\text{cons}}$ encoding). Shifting raw bits mid-value sets `aligned := false`; advancing $\sigma_{\text{cons}}$ along a prefix derivative to a clean sub-value boundary (`match /tag`, final-field `demux`, `shift_tag`) restores `aligned := true`.
102
+ - `prod` $\in \mathrm{NodeId} \cup \{\mathsf{EXT\_IN}, \mathsf{NONE}\}$: Unique owning producer handle—an active transducer node ID in $N$, the external wire input `EXT_IN`, or `NONE` once closed, failed, or retired.
103
+ - `cons` $\in \mathrm{NodeId} \cup \{\mathsf{EXT\_OUT}, \mathsf{NONE}\}$: Unique owning consumer handle—an active transducer node ID in $N$, the external wire output `EXT_OUT`, or `NONE` when detached or retired.
104
+ - `scope` $\in \mathbb{N}$: Enclosing speculation scope ID in the rooted scope tree $S$ (root scope is `0`).
100
105
 
101
106
  **Required ADT Operations (Complexity Targets):**
102
107
 
@@ -110,16 +115,16 @@ Where:
110
115
  | `push_deque(dst, src)` | $c, c'$ | Append all bits of `src.buf` to back of `dst.buf`; empty `src` | $O(|\text{src}| / 32)$ |
111
116
  | `close(c)` / `fail(c)` | $c$ | Transition `OPEN` → `CLOSED` or `FAILED`; clear `c.prod := NONE` | $O(1)$ |
112
117
 
113
- > **Abstraction Boundary & Production Backing Stores:** Nothing in the operational semantics depends on `BitDeque`'s internal layout. The JS reference VM uses a power-of-2 word ring buffer for simplicity, while the WebAssembly and C/LLVM backends use **segmented fixed-size slabs with a `<= 128b` inline buffer** (zero slab allocation on short-lived streaming FIFOs, zero linear-memory fragmentation, $O(1)$ free-list alloc/rollback, and exact global byte-quota enforcement).
118
+ > **Abstraction Boundary & Production Backing Stores:** Nothing in the operational semantics depends on `BitDeque`'s internal layout. The JS reference VM uses a growable power-of-2 word ring buffer, while the WebAssembly and C/LLVM backends pair a **`<= 128b` inline ring buffer with growable power-of-2 ring buffers** (backed by a fast bump arena and, in C/LLVM, a power-of-2 buffer free list), giving zero heap allocation on short-lived streaming FIFOs, $O(1)$ buffer adoption on `splice`, and exact global byte-quota enforcement.
114
119
 
115
120
  ### 3.2 Dual-Schema Suffix Invariant $\mathcal{I}(c)$
116
121
 
117
122
  Separating producer suffix schema $\sigma_{\text{prod}}(c)$ from consumer schema $\sigma_{\text{cons}}(c)$ is essential whenever a prefix constructor (`wrap |tag`) or partial product emitter (`mux`) emits prefix bits ahead of an upstream producer.
118
123
 
119
- Let $w_{\text{read}}(c) \in \{0,1\}^*$ denote the ghost history of bits already shifted by `c.cons` since the last aligned boundary ($w_{\text{read}}(c) = \varepsilon$ whenever `c.aligned = true`). Every well-formed channel $c$ maintains:
124
+ Let $w_{\text{read}}(c) \in \{0,1\}^*$ denote the ghost history of bits already shifted by `c.cons` since the last aligned boundary ($w_{\text{read}}(c) = \varepsilon$ whenever `c.aligned = true`), and let $R_c \subseteq \{0,1\}^*$ denote the residual language of suffixes still owed by the producer. By Section 2.3, at any aligned producer position $R_c = \mathcal{L}(\vec{p}_c) = \mathcal{L}(p_1)\cdots\mathcal{L}(p_k)$ for a finite list of schema nodes $\vec{p}_c = [p_1, \dots, p_k] \in V^*$ maintained by the producer's control or DPDA cursor; at a producer value boundary, $\vec{p}_c = [\sigma_{\text{prod}}(c)]$ is a singleton, so $R_c = \mathcal{L}(\sigma_{\text{prod}}(c))$. Every well-formed channel $c$ maintains:
120
125
 
121
126
  $$\mathcal{I}(c) :\quad \begin{cases}
122
- \forall w_{\text{rem}} \in \mathcal{L}(\sigma_{\text{prod}}(c)).\; w_{\text{read}}(c) \cdot c.\text{buf} \cdot w_{\text{rem}} \in \mathcal{L}(\sigma_{\text{cons}}(c)) & \text{if } c.\text{status} = \mathsf{OPEN} \\
127
+ \forall w_{\text{rem}} \in R_c.\; w_{\text{read}}(c) \cdot c.\text{buf} \cdot w_{\text{rem}} \in \mathcal{L}(\sigma_{\text{cons}}(c)) & \text{if } c.\text{status} = \mathsf{OPEN} \\
123
128
  w_{\text{read}}(c) \cdot c.\text{buf} \in \mathcal{L}(\sigma_{\text{cons}}(c)) & \text{if } c.\text{status} = \mathsf{CLOSED}
124
129
  \end{cases}$$
125
130
 
@@ -130,8 +135,8 @@ w_{\text{read}}(c) \cdot c.\text{buf} \in \mathcal{L}(\sigma_{\text{cons}}(c)) &
130
135
  All zero-copy forwarding (`ID`), matched variant stripping (`DIV`), prepend-splicing (`VID`), last-field `MUX` tail-splicing, last-branch `spec` retirement, and compiled-kernel `handoff` reduce to a **single algebraic operation** `splice(src -> dst)`:
131
136
 
132
137
  **Preconditions:**
133
- 1. `src.aligned = true` (the consumer side of `src` is at a fresh value boundary of $\sigma_{\text{cons}}(\text{src})$).
134
- 2. $\sigma_{\text{cons}}(\text{src}) \equiv \sigma_{\text{prod}}(\text{dst})$ (the full value produced by `src` matches the remaining suffix obligation of `dst`).
138
+ 1. `src.aligned = true` (the consumer side of `src` is at a fresh value boundary of $\sigma_{\text{cons}}(\text{src})$, so $w_{\text{read}}(\text{src}) = \varepsilon$).
139
+ 2. `dst` is at a producer value boundary ($R_{\text{dst}} = \mathcal{L}(\sigma_{\text{prod}}(\text{dst}))$) with $\sigma_{\text{cons}}(\text{src}) \equiv \sigma_{\text{prod}}(\text{dst})$ (the full value produced by `src` matches the remaining suffix obligation of `dst`).
135
140
  3. `src` and `dst` are in compatible scopes (either same scope, or committing an outer `spec` staging buffer).
136
141
 
137
142
  **Operational Effect of `splice(src -> dst)`:**
@@ -142,15 +147,15 @@ All zero-copy forwarding (`ID`), matched variant stripping (`DIV`), prepend-spli
142
147
  - Else: execute `push_deque(dst, src)` ($O(|\text{src.buf}|)$ bits moved).
143
148
  2. **Metadata & Ownership Transfer:**
144
149
  - `dst.consSchema` and `dst.aligned` remain **unchanged**!
145
- - `dst.prodSchema := src.prodSchema` (if `src` is `OPEN`).
150
+ - `dst.prodSchema := src.prodSchema` (if `src` is `OPEN`), transferring $R_{\text{dst}}' := R_{\text{src}}$.
146
151
  - `dst.status := src.status`.
147
152
  - `dst.prod := src.prod` (and if `src.prod != NONE`, rebind that producer's output port handle from `src` to `dst`).
148
153
  - Retire channel `src`.
149
154
 
150
155
  **Corollary (Inductive Preservation of $\mathcal{I}$):**
151
- Since `src` satisfies $\forall w_{\text{rem}} \in \mathcal{L}(\sigma_{\text{prod}}(\text{src})).\; \text{src.buf} \cdot w_{\text{rem}} \in \mathcal{L}(\sigma_{\text{cons}}(\text{src}))$, and $\sigma_{\text{cons}}(\text{src}) \equiv \sigma_{\text{prod}}(\text{dst})$, substituting $\text{src.buf} \cdot w_{\text{rem}}$ into $\mathcal{I}(\text{dst})$ yields:
156
+ Since `src.aligned = true`, $\mathcal{I}(\text{src})$ gives $\forall w_{\text{rem}} \in R_{\text{src}}.\; \text{src.buf} \cdot w_{\text{rem}} \in \mathcal{L}(\sigma_{\text{cons}}(\text{src}))$ (or $\text{src.buf} \in \mathcal{L}(\sigma_{\text{cons}}(\text{src}))$ when `CLOSED`). Because $R_{\text{dst}} = \mathcal{L}(\sigma_{\text{prod}}(\text{dst})) = \mathcal{L}(\sigma_{\text{cons}}(\text{src}))$, substituting $\text{src.buf} \cdot w_{\text{rem}}$ into $\mathcal{I}(\text{dst})$ yields:
152
157
  $$w_{\text{read}}(\text{dst}) \cdot (\text{dst.buf} \cdot \text{src.buf}) \cdot w_{\text{rem}} \in \mathcal{L}(\sigma_{\text{cons}}(\text{dst}))$$
153
- Thus $\mathcal{I}(\text{dst})$ is preserved unconditionally—whether `dst` had a prepended tag (`|+`), a serialized `car` field (`|cons · car`), or a consumer already mid-stream (`aligned = false`).
158
+ Thus $\mathcal{I}(\text{dst})$ is preserved unconditionally—whether `dst` had a prepended tag (`|+`), a serialized `car` field (`|cons · car`), a mid-value producer on `src`, or a consumer already mid-stream (`aligned = false`).
154
159
 
155
160
  ---
156
161
 
@@ -198,7 +203,7 @@ This pass combines **compatibility verification** and **structural shape refinem
198
203
  - Lower `project .f` on split ports into direct channel wiring + `drain` on unused siblings, or on unsplit channels into `demux` + `drain` (or sequential `dpda_skip` + `splice`/`dpda_copy`).
199
204
 
200
205
  5. **Post-Specialization Kernel & Bit-Chunk Optimization (Optional `kTVM` → `kTVM`):**
201
- - With all schemas closed and bit-widths exact, the compiler may optionally fuse acyclic subgraphs and self-tail/TMC loops into `kernel` blocks and synthesize `chunk_table`/`stack_table`/`fsm_table` blocks via Howard's MWTR optimizer.
206
+ - With all schemas closed and bit-widths exact, the compiler may optionally fuse acyclic subgraphs and self-tail/TMC loops into `kernel` blocks and synthesize `chunk_table`/`stack_table`/`fsm_table` blocks via the MWTR optimizer.
202
207
 
203
208
  > **Caching & Amortized Cost:** The specialized module `M` is keyed purely by `(moduleHash, entry, MooreKey(S_in))`. Repeated invocations with the same input envelope schema reuse the cached specialized `kTVM` directly with zero re-specialization overhead.
204
209
 
@@ -315,7 +320,7 @@ A `kernel` is a single transducer node compiled from an acyclic subgraph, a self
315
320
 
316
321
  ---
317
322
 
318
- ## 6. Static Bit-Chunk Tables and Howard MWTR Contract
323
+ ## 6. Static Bit-Chunk Tables and MWTR Contract
319
324
 
320
325
  To achieve multi-bit-per-lookup native speed directly over `k-wire`, `kTVM` makes static read-only transition tables first-class module declarations.
321
326
 
@@ -349,7 +354,7 @@ A `kTVM` module may declare three kinds of immutable tables (`table &name ...`):
349
354
 
350
355
  Every `table` declaration may carry optional metadata:
351
356
  - `verified_against: @kernel_name` — asserts that the table is **bisimulation-equivalent** to the reference un-chunked `kernel` CFG over all valid `k-wire` inputs. In production compilation, static bisimulation verification is **enabled by default** (with an explicit opt-out flag for oversized tables), catching optimizer defects before code generation.
352
- - `mwtr: { rho: <float>, bytes: <int>, budget_class: "L1" | "L2" | ... }` — records the worst-case asymptotic bits-per-lookup ratio $\rho^*$ computed by **Howard's policy-improvement algorithm** ([speed-eval.pdf](speed-eval.pdf)) over the table's strongly connected transition graph (with cycle weight = bits shifted, cycle time = lookups, accounting for amortized stack pops in `stack_table`), together with its static byte footprint. Default global budget is **`64 KB` (L1-resident)**, configurable via CLI/API, with graceful fallback to un-chunked `kernel` CFG on wide alphabets (`ascii[]`/`unicode[]` in `lib/djson.k`).
357
+ - `mwtr: { rho: <float>, bytes: <int>, budget_class: "L1" | "L2" | ... }` — records the worst-case asymptotic bits-per-lookup ratio $\rho^*$ computed by max-plus policy-improvement cycle-ratio computation (Cochet-Terrasson et al., 1998; [speed-eval.pdf](speed-eval.pdf)) over the table's strongly connected transition graph (with cycle weight = bits shifted, cycle time = lookups, accounting for amortized stack pops in `stack_table`), together with its static byte footprint. Default global budget is **`64 KB` (L1-resident)**, configurable via CLI/API, with graceful fallback to un-chunked `kernel` CFG on wide alphabets (`ascii[]`/`unicode[]` in `lib/djson.k`).
353
358
 
354
359
  ---
355
360
 
@@ -876,11 +881,11 @@ proc @lsb_mul_karatsuba(%x: $bits, %y: $bits) -> (%out: $bits) branching total {
876
881
 
877
882
  1. **Core IR, Validator, Specializer & Reference VM (`ktvm/`):**
878
883
  - `ast.mjs`, `parser.mjs`, `printer.mjs`, `json.mjs`: round-trip `.ktvmp`/`.ktvm` DSL + `format: "k-tvm"` JSON export.
879
- - `schema.mjs`: Moore quotient minimization, prefix derivatives, and bridge to K's `intersectPropertyListPatterns`.
884
+ - `schema.mjs`: Moore quotient minimization (`mooreKey`, `schemasEquivalent`), node-list prefix derivatives (`normalizeNodeList`, `nodeListComplete`, `stepNodeListTag`, `stepNodeListLabel`), bit-level $s$-language wire equivalence (`wireLanguageKey`, `wireLanguagesEqual`), and bridge to K's `intersectPropertyListPatterns`.
880
885
  - `validator.mjs`: enforces all 6 static validation rules (Section 8)—including SPSC linearity, `(prodSchema, consSchema)` checking, DAG acyclicity, and always-on table-to-`CFG` bisimulation verification.
881
- - `bit-deque.mjs`: power-of-2 ring-buffer `BitDeque` ADT with configurable byte quotas (`maxBitDequeBytes`).
886
+ - `bit-deque.mjs`: power-of-2 ring-buffer `BitDeque` ADT (full 8-tuple channel state + `prodNodeList`/`consNodeList` helpers) with configurable byte quotas (`maxBitDequeBytes`).
882
887
  - `specialize.mjs`: standalone `specializeKTVM(ktvmp, entry, S_in)` → `SchemaError` or concrete envelope-free `.ktvm` + `S_out`.
883
- - `vm.mjs` & `wire.mjs`: strictly iterative small-step reference interpreter + iterative `k-wire` boundary codec + runtime quotas (`maxBitDequeBytes`, `maxNodes`, `maxSteps`).
888
+ - `vm.mjs` & `wire.mjs`: strictly iterative small-step reference interpreter, unified 1-state DPDA `SchemaCursor`, aligned-offset raw-buffer scanner (`scanBufferAlignedOffset`), iterative `k-wire` boundary codec, and runtime quotas (`maxBitDequeBytes`, `maxNodes`, `maxSteps`).
884
889
  - Verified by `ktvm/test-ktvm.mjs`.
885
890
  2. **`KIR-P → kTVM-P` Lowering & Full Standard-Library Parity (`ktvm/lower-kir.mjs`):**
886
891
  - Lowers all `KIR-P` opcodes (`usedPaths`, deterministic `switch` vs. `spec`, `isBranchingRecursive` `after %tok`, optional `retypeObjectRelationForBackend` fallback).
@@ -888,15 +893,15 @@ proc @lsb_mul_karatsuba(%x: $bits, %y: $bits) -> (%out: $bits) branching total {
888
893
  - Verified by `ktvm/test-conformance.mjs` against `conformance/`, `lib/generic.k`, `lib/integer.k`, `lib/ieee.k`, `lib/djson.k`, `ktvm/fixtures/integer-streaming.k`, and differential fuzzing.
889
894
  3. **Verified `kTVM → kTVM` Optimization Passes (`ktvm/optimize/`):**
890
895
  - CPS symbolic `kernel` fusion, bounded short-bit unfolding, entry-guard `spec → switch` compilation, and TMC forward streaming (register & local LIFO `stack` promotion).
891
- - Bit-chunk / stack-chunk / heterogeneous FSM table synthesis (`SWAR` compression, `64 KB` default L1 Howard `MWTR` budget, graceful wide-alphabet `CFG` fallback, always-on bisimulation verification).
896
+ - Bit-chunk / stack-chunk / heterogeneous FSM table synthesis (`SWAR` compression, `64 KB` default L1 `MWTR` budget, graceful wide-alphabet `CFG` fallback, always-on bisimulation verification).
892
897
  - Verified by `ktvm/test-optimize.mjs`.
893
898
  4. **WebAssembly & Native C/LLVM Backends (`ktvm/wasm/`, `ktvm/llvm/`):**
894
- - `ktvm/wasm/` lowers concrete `.ktvm` to WAT/Wasm via `wabt` with a flat active-node slab pool, `<= 128b`-inline + segmented-slab `BitDeque`s with global quota, static data segments for chunk tables, and an iterative worklist pull scheduler. Integrated directly into the terminal and browser REPLs (`:engine ktvm` / `--ktvm`) and verified by `ktvm/wasm/test-wasm.mjs`.
899
+ - `ktvm/wasm/` lowers concrete `.ktvm` to WAT/Wasm via `wabt` with a bump arena, `<= 128b`-inline + growable power-of-2 ring-buffer `BitDeque`s with global quota, static data segments for chunk tables, and an iterative worklist pull scheduler. Integrated directly into the terminal and browser REPLs (`:engine ktvm` / `--ktvm`) and verified by `ktvm/wasm/test-wasm.mjs`.
895
900
  - `ktvm/llvm/` lowers concrete `.ktvm` to C/LLVM IR linked against `ktvm/llvm/runtime.h`, verified by `ktvm/llvm/test-llvm.mjs` and benchmarked head-to-head against kVM in [KVM_VS_KTVM_COMPARATIVE_STUDY.md](KVM_VS_KTVM_COMPARATIVE_STUDY.md).
896
901
 
897
902
  ### 11.2 Intentionally Isolated Evolution Hooks
898
903
 
899
904
  To keep `kTVM` adaptable as empirical results arrive:
900
- - **Channel Storage:** Encapsulated behind the `BitDeque` ADT (Section 3.1); ring buffer in JS ref VM and `<= 128b`-inline + segmented fixed-size slabs in Wasm/C share the exact same operational semantics.
905
+ - **Channel Storage:** Encapsulated behind the `BitDeque` ADT (Section 3.1); growable power-of-2 ring buffers in the JS ref VM and `<= 128b`-inline + growable power-of-2 ring buffers in Wasm/C (with bump arena and power-of-2 free list in C) share the exact same operational semantics.
901
906
  - **Port-Splitting Policy:** Controlled purely inside `specialize.mjs` (Section 4.2 Step 3); changing between access-profile splitting, full product splitting, or unsplit single-channel execution changes only the refined `kTVM` shape, not the VM ISA.
902
907
  - **Scheduling Policy:** Demand-driven pull + `after %tok` is the baseline; future backends may explore work-stealing or bounded-buffer scheduling over the same acyclic DAG semantics.
@@ -13,6 +13,7 @@ Run commands from the repository root; LLVM lanes need Clang.
13
13
  | `npm run perf:int` | Integer arithmetic |
14
14
  | `npm run perf:ieee` | Binary64 arithmetic |
15
15
  | `npm run perf:mult` | Multiplication algorithm comparison |
16
+ | `node harness/experiments/bottlenecks.mjs > results.json` | Paired kTVM compiler-pass, wire, arithmetic, JSON and native build experiments |
16
17
  | `npm run benchmark` | End-to-end artifact/execution measurements |
17
18
  | `npm run benchmark:html` | Render generated benchmark-results.json |
18
19
 
@@ -70,3 +71,9 @@ or performance guarantees. For an in-depth architectural comparison of kVM and
70
71
  kTVM across arithmetic, list, IEEE 754, and JSON workloads, see the
71
72
  [kVM vs. kTVM comparative study](KVM_VS_KTVM_COMPARATIVE_STUDY.md). Use the
72
73
  [test suites](../tests/README.md) for regression verification.
74
+
75
+ The kTVM experiments include two ARM64 baseline runs, per-phase timings and
76
+ an ordered list of candidate compiler improvements. To compare a new revision,
77
+ run the same fixtures and print medians and interquartile ranges with
78
+ `node harness/experiments/summarize.mjs results.json`.
79
+ See the [experiment design and baseline](../harness/experiments/README.md).
package/README.md CHANGED
@@ -13,6 +13,12 @@ The [paper on Zenodo](https://zenodo.org/records/23652382) introduces the langua
13
13
  Its [LaTeX source](paper/k-paper.tex) and [PDF](paper/k-paper.pdf) are in this
14
14
  repository.
15
15
 
16
+ The sequel, [kTVM: A Packed-Wire Execution Model and Compiler for K](https://zenodo.org/records/24653605)
17
+ (DOI: [10.5281/zenodo.24653605](https://doi.org/10.5281/zenodo.24653605)),
18
+ describes the packed-wire execution model and compiler. Its
19
+ [LaTeX source](paper/k-transducer-compiler.tex) and
20
+ [PDF](paper/k-transducer-compiler.pdf) are also in this repository.
21
+
16
22
  ## A small example
17
23
 
18
24
  This relation swaps two fields:
@@ -27,7 +27,6 @@ const K_RT_BLOCKS_OFFSET = 0;
27
27
  const K_RT_UNIT_CACHE_OFFSET = 8;
28
28
  const K_RT_BIT0_CACHE_OFFSET = 16;
29
29
  const K_RT_BIT1_CACHE_OFFSET = 24;
30
- const K_RT_HAS_REUSABLE_BLOCKS_OFFSET = 32;
31
30
  const K_ARENA_BLOCK_USED_OFFSET = 8;
32
31
 
33
32
  function alignArenaSize(size) {
@@ -303,7 +302,6 @@ function lowerRtRewind(ctx, mark) {
303
302
  storePtrAt(ctx, "%rt", K_RT_UNIT_CACHE_OFFSET, "null");
304
303
  storePtrAt(ctx, "%rt", K_RT_BIT0_CACHE_OFFSET, "null");
305
304
  storePtrAt(ctx, "%rt", K_RT_BIT1_CACHE_OFFSET, "null");
306
- storeI32At(ctx, "%rt", K_RT_HAS_REUSABLE_BLOCKS_OFFSET, 0);
307
305
  ctx.lines.push(` br label %${doneBlock}`);
308
306
 
309
307
  ctx.lines.push(`${slowBlock}:`);
@@ -35,7 +35,6 @@ const K_RT_BLOCKS_OFFSET = 0;
35
35
  const K_RT_UNIT_CACHE_OFFSET = 8;
36
36
  const K_RT_BIT0_CACHE_OFFSET = 16;
37
37
  const K_RT_BIT1_CACHE_OFFSET = 24;
38
- const K_RT_HAS_REUSABLE_BLOCKS_OFFSET = 32;
39
38
  const K_ARENA_BLOCK_USED_OFFSET = 8;
40
39
  const K_ARENA_BLOCK_CAPACITY_OFFSET = 16;
41
40
  const K_ARENA_BLOCK_DATA_OFFSET = 24;
@@ -414,7 +413,6 @@ function lowerRtRewind(ctx, mark) {
414
413
  storePtrAt(ctx, "%rt", K_RT_UNIT_CACHE_OFFSET, "null");
415
414
  storePtrAt(ctx, "%rt", K_RT_BIT0_CACHE_OFFSET, "null");
416
415
  storePtrAt(ctx, "%rt", K_RT_BIT1_CACHE_OFFSET, "null");
417
- storeI32At(ctx, "%rt", K_RT_HAS_REUSABLE_BLOCKS_OFFSET, 0);
418
416
  ctx.lines.push(` br label %${doneBlock}`);
419
417
 
420
418
  ctx.lines.push(`${slowBlock}:`);
@@ -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");
@@ -550,6 +550,71 @@ 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
620
  if ((bitOffset + width - 1) >> 3 >= buffer.length) {
@@ -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
  }