@fraczak/k 8.8.0 → 9.0.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.
Files changed (94) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/DOCS/ARCHITECTURE.md +5 -4
  3. package/DOCS/DICTIONARY.md +2 -2
  4. package/DOCS/FILE_FORMATS.md +11 -9
  5. package/DOCS/KIR_V1.md +5 -1
  6. package/DOCS/KTVM_SPEC.md +902 -0
  7. package/DOCS/KVM_EXECUTION_MODEL.md +3 -2
  8. package/DOCS/KVM_VS_KTVM_COMPARATIVE_STUDY.md +127 -0
  9. package/DOCS/PROFILING_AND_TRACING.md +6 -4
  10. package/DOCS/README.md +3 -2
  11. package/DOCS/REPL.md +16 -12
  12. package/README.md +132 -2
  13. package/backend-api.mjs +31 -16
  14. package/backends/llvm/README.md +4 -5
  15. package/backends/llvm/bin/k-llvm-build.mjs +7 -19
  16. package/backends/llvm/bin/k-llvm-compile.mjs +6 -18
  17. package/backends/llvm/bin/k-llvm.mjs +11 -33
  18. package/backends/llvm/src/cli.mjs +2 -12
  19. package/backends/llvm/src/executable.mjs +7 -95
  20. package/backends/llvm/src/kvm2llvm.mjs +1 -5
  21. package/backends/llvm/src/llvm.mjs +4 -111
  22. package/backends/llvm/tests/k-llvm-run.mjs +1 -6
  23. package/backends/llvm/tests/perf-support.mjs +3 -5
  24. package/backends/llvm/tests/test-llvm.mjs +0 -16
  25. package/backends/wasm/README.md +2 -3
  26. package/backends/wasm/bin/k-wasm-compile.mjs +4 -7
  27. package/backends/wasm/bin/k-wasm.mjs +4 -6
  28. package/backends/wasm/src/cli.mjs +8 -24
  29. package/backends/wasm/src/wasm.mjs +10 -56
  30. package/browser/repl-browser.mjs +9 -8
  31. package/browser/shims/buffer.mjs +31 -2
  32. package/browser/shims/child_process.mjs +26 -0
  33. package/browser/shims/fs.mjs +3 -1
  34. package/codecs/djson.mjs +2 -3
  35. package/codecs/int.mjs +66 -14
  36. package/conformance/run.mjs +17 -2
  37. package/harness/adapters/ktvm-llvm.mjs +118 -0
  38. package/harness/adapters/ktvm-wasm.mjs +104 -0
  39. package/harness/adapters/ktvm.mjs +133 -0
  40. package/harness/registry.mjs +9 -0
  41. package/ktvm/ast.mjs +218 -0
  42. package/ktvm/bit-deque.mjs +482 -0
  43. package/ktvm/fixtures/integer-streaming.k +477 -0
  44. package/ktvm/index.mjs +119 -0
  45. package/ktvm/llvm/index.mjs +202 -0
  46. package/ktvm/llvm/lower-c.mjs +1258 -0
  47. package/ktvm/llvm/runtime.h +3542 -0
  48. package/ktvm/llvm/test-llvm.mjs +476 -0
  49. package/ktvm/lower-kir.mjs +2221 -0
  50. package/ktvm/optimize/fuse-kernel.mjs +2111 -0
  51. package/ktvm/optimize/index.mjs +116 -0
  52. package/ktvm/optimize/mwtr.mjs +283 -0
  53. package/ktvm/optimize/simplify-procs.mjs +5250 -0
  54. package/ktvm/optimize/synthesize-tables.mjs +1105 -0
  55. package/ktvm/parser.mjs +1101 -0
  56. package/ktvm/printer.mjs +281 -0
  57. package/ktvm/schema.mjs +543 -0
  58. package/ktvm/specialize.mjs +538 -0
  59. package/ktvm/test-conformance.mjs +597 -0
  60. package/ktvm/test-ktvm.mjs +1376 -0
  61. package/ktvm/test-optimize.mjs +598 -0
  62. package/ktvm/validator.mjs +1280 -0
  63. package/ktvm/vm.mjs +2225 -0
  64. package/ktvm/wasm/index.mjs +331 -0
  65. package/ktvm/wasm/lower-wasm.mjs +1272 -0
  66. package/ktvm/wasm/runtime.wat +4413 -0
  67. package/ktvm/wasm/test-wasm.mjs +426 -0
  68. package/ktvm/wire.mjs +489 -0
  69. package/lib/djson.k +175 -173
  70. package/lib/generic.k +82 -97
  71. package/lib/ieee.k +110 -115
  72. package/lib/integer.k +25 -31
  73. package/package.json +1 -9
  74. package/repl.mjs +101 -20
  75. package/scripts/build-repl-html.mjs +40 -18
  76. package/scripts/perf-bigint-compare.mjs +275 -0
  77. package/scripts/perf-ieee.mjs +9 -229
  78. package/scripts/perf-int.mjs +14 -272
  79. package/scripts/perf-multiplication.mjs +8 -54
  80. package/scripts/perf-poly.mjs +9 -263
  81. package/scripts/run-tests.mjs +5 -2
  82. package/scripts/test-package.mjs +15 -3
  83. package/tests/README.md +3 -3
  84. package/tests/test-djson-methods.mjs +0 -1
  85. package/tests/test-djson.mjs +0 -1
  86. package/tests/test-generic.mjs +5 -7
  87. package/tests/test-repl-html.mjs +72 -15
  88. package/tests/test-repl.mjs +27 -20
  89. package/tests/test-structural-values.mjs +1 -1
  90. package/DOCS/POLYMORPHIC_IR.md +0 -86
  91. package/access-table.mjs +0 -343
  92. package/pkir.mjs +0 -772
  93. package/tests/test-access-table.mjs +0 -213
  94. package/tests/test-pkir.mjs +0 -530
@@ -0,0 +1,902 @@
1
+ # `kTVM`: Formal Specification and Textual DSL (v0.1)
2
+
3
+ **Status:** Implemented Formal Specification
4
+ **Scope:** Formal abstract machine model, operational semantics, polymorphic schema specialization (`kTVM-P` → `kTVM`), static bit-chunk acceleration contract, and textual DSL grammar for **kTVM** (the K Transducer Virtual Machine).
5
+ **Related Specifications:**
6
+ - Wire format contract: [WIRE_FORMAT.md](../codecs/WIRE_FORMAT.md), [prefix-codec.mjs](../codecs/runtime/prefix-codec.mjs)
7
+ - Patterns & relations: [PATTERNS.md](PATTERNS.md), [KIR_V1.md](KIR_V1.md)
8
+ - Register VM reference: [KVM_EXECUTION_MODEL.md](KVM_EXECUTION_MODEL.md)
9
+ - Empirical evaluation: [KVM_VS_KTVM_COMPARATIVE_STUDY.md](KVM_VS_KTVM_COMPARATIVE_STUDY.md)
10
+ - Throughput criterion (MWTR): [speed-eval.pdf](speed-eval.pdf)
11
+
12
+ ---
13
+
14
+ ## 1. Design Goals and Compilation Architecture
15
+
16
+ `kTVM` is a formal, target-independent **streaming pushdown transducer virtual machine** designed to execute K relations directly over unmodified, bit-packed `k-wire` bitstreams without materializing heap-allocated value trees.
17
+
18
+ Its design rests on five core principles:
19
+
20
+ 1. **Unmodified `k-wire` Boundary Contract:** External inputs and outputs strictly obey [WIRE_FORMAT.md](../codecs/WIRE_FORMAT.md) (`encode(pattern_value) encode(payload)`). Every internal channel carries valid bit-packed `k-wire` payloads with zero per-bit boxing or framing overhead.
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
+ 3. **Two-Tier Execution ISA (Network + Kernel):**
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.
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
+ 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
+
28
+ ```mermaid
29
+ flowchart LR
30
+ K["K Source / KIR-P"] --> KTVMP["kTVM-P Module (.ktvmp)<br/>Schema params, open schemas"]
31
+ ENV["k-wire Input Envelope<br/>(S_in, payload bits)"] --> SPEC{"Boundary Check &<br/>Shape Refinement"}
32
+ KTVMP --> SPEC
33
+ SPEC -->|"Schema Contradiction"| ERR["Static Schema Error"]
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"]
36
+ OPT --> EXEC["Backends<br/>Ref VM / C / LLVM / Wasm"]
37
+ EXEC --> OUT["k-wire Output Envelope<br/>(S_out, payload bits)"]
38
+ ```
39
+
40
+ ---
41
+
42
+ ## 2. Schema and Wire Type System
43
+
44
+ `kTVM` schemas correspond directly to K's regular pattern graphs ([WIRE_FORMAT.md](../codecs/WIRE_FORMAT.md), [PATTERNS.md](PATTERNS.md)), extended with explicit schema parameters for `kTVM-P`.
45
+
46
+ ### 2.1 Schema Algebra
47
+
48
+ A schema expression $\sigma$ is formed over a finite set of named recursive schema definitions (`schema $Name[$P1, ...] = body`) and schema parameters `$X`:
49
+
50
+ | Form | K Pattern Node | `k-wire` Bit Representation | Allowed Layer |
51
+ | --- | --- | --- | --- |
52
+ | `unit` | `closed-product []` | $0$ bits | `kTVM-P`, `kTVM` |
53
+ | `product { f1: S1, ..., fm: Sm }` | `closed-product` | Concatenation of `S1 .. Sm` in canonical label order ($0$ framing bits) | `kTVM-P`, `kTVM` |
54
+ | `union { t1: S1, ..., tn: Sn }` | `closed-union` | Tag ordinal $i \in [0, n-1]$ MSB-first in $w = \lceil \log_2 n \rceil$ bits ($0$ bits if $n \le 1$), followed by `S_i` | `kTVM-P`, `kTVM` |
55
+ | `open_product { f1: S1, ..., ... }` | `open-product` | Concrete layout resolved at specialization or via runtime schema descriptor | `kTVM-P` only |
56
+ | `open_union { t1: S1, ..., ... }` | `open-union` | Tag width/ordinal resolved at specialization or via runtime schema descriptor | `kTVM-P` only |
57
+ | `any` | `any` | Unconstrained; cannot encode bits without refinement | `kTVM-P` only |
58
+ | `$X` | Schema parameter | Instantiated at boundary specialization or passed as DPDA descriptor | `kTVM-P` (or opaque ref) |
59
+ | `$Name[A1, ...]` | Named / recursive schema | Regular tree graph (expanded lazily by Moore graph) | `kTVM-P`, `kTVM` |
60
+
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
+
63
+ ### 2.2 Regular-Tree Equivalence (Moore Quotient)
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.
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.
71
+
72
+ ### 2.3 Prefix Derivative ($\partial_w \sigma$)
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}}$).
81
+
82
+ ---
83
+
84
+ ## 3. Channel Model: `BitDeque` and Dual-Schema Invariant
85
+
86
+ ### 3.1 Abstract Channel ADT (`BitDeque`)
87
+
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:
89
+
90
+ $$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
+
92
+ 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:
95
+ $$\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`).
100
+
101
+ **Required ADT Operations (Complexity Targets):**
102
+
103
+ | Operation | Signature | Semantics | Target Cost |
104
+ | --- | --- | --- | --- |
105
+ | `push_bits(c, word, k)` | $k \in [0, 32]$ | Append $k$ LSBs of `word` (MSB-first) to back of `c.buf` | $O(1)$ amortized |
106
+ | `unshift_bits(c, word, k)` | $k \in [0, 32]$ | Prepend $k$ LSBs of `word` (MSB-first) to front of `c.buf` | $O(1)$ amortized |
107
+ | `peek_bits(c, off, k)` | $k \in [0, 32]$ | Read $k$ bits starting at bit offset `off` from front (non-destructive) | $O(1)$ |
108
+ | `shift_bits(c, k)` | $k \in [0, 32]$ | Discard $k$ bits from front of `c.buf` | $O(1)$ |
109
+ | `unshift_deque(dst, src)` | $c, c'$ | Prepend all bits of `src.buf` in front of `dst.buf`; empty `src` | $O(|\text{src}| / 32)$ |
110
+ | `push_deque(dst, src)` | $c, c'$ | Append all bits of `src.buf` to back of `dst.buf`; empty `src` | $O(|\text{src}| / 32)$ |
111
+ | `close(c)` / `fail(c)` | $c$ | Transition `OPEN` → `CLOSED` or `FAILED`; clear `c.prod := NONE` | $O(1)$ |
112
+
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).
114
+
115
+ ### 3.2 Dual-Schema Suffix Invariant $\mathcal{I}(c)$
116
+
117
+ 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
+
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:
120
+
121
+ $$\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} \\
123
+ w_{\text{read}}(c) \cdot c.\text{buf} \in \mathcal{L}(\sigma_{\text{cons}}(c)) & \text{if } c.\text{status} = \mathsf{CLOSED}
124
+ \end{cases}$$
125
+
126
+ *(Where if `c.status = CLOSED` and `c.buf` has not yet been fully consumed, `c.prod = NONE`.)*
127
+
128
+ ### 3.3 The Unified `splice(src -> dst)` Primitive
129
+
130
+ 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
+
132
+ **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`).
135
+ 3. `src` and `dst` are in compatible scopes (either same scope, or committing an outer `spec` staging buffer).
136
+
137
+ **Operational Effect of `splice(src -> dst)`:**
138
+ 1. **Buffer merge (preserving bit order `dst.buf · src.buf` with minimal copying):**
139
+ - If `|dst.buf| == 0`: `dst` takes ownership of `src.buf` in $O(1)$ (`0` bits copied).
140
+ - Else if `|src.buf| == 0`: keep `dst.buf` (`0` bits copied).
141
+ - Else if `|dst.buf| <= |src.buf|` (the common `wrap |tag` and tail-recursive `cons` case, where `dst` holds a tiny prefix and `src` holds a large tail): execute `unshift_deque(src, dst)` and transfer `src.buf` ownership to `dst` ($O(|\text{dst.buf}|)$ bits moved, **$0$ bits of `src` copied**).
142
+ - Else: execute `push_deque(dst, src)` ($O(|\text{src.buf}|)$ bits moved).
143
+ 2. **Metadata & Ownership Transfer:**
144
+ - `dst.consSchema` and `dst.aligned` remain **unchanged**!
145
+ - `dst.prodSchema := src.prodSchema` (if `src` is `OPEN`).
146
+ - `dst.status := src.status`.
147
+ - `dst.prod := src.prod` (and if `src.prod != NONE`, rebind that producer's output port handle from `src` to `dst`).
148
+ - Retire channel `src`.
149
+
150
+ **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:
152
+ $$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`).
154
+
155
+ ---
156
+
157
+ ## 4. Polymorphism and Boundary Envelope Specialization (`kTVM-P` → `kTVM`)
158
+
159
+ K supports parametric polymorphism (e.g., `reverse : list[X] -> list[X]`, `btrie_get : { bits[] key, btrie[V] trie } -> V`) and open structural patterns (`{ X a, ... }`, `< {} nil, ... >`). `kTVM` handles polymorphism in two coordinated stages:
160
+
161
+ ### 4.1 Polymorphic Modules (`kTVM-P`)
162
+
163
+ A `kTVM-P` module may contain:
164
+ - Parameterized schema templates: `schema $list[$X] = union { cons: product { car: $X, cdr: $list[$X] }, nil: unit }`.
165
+ - Parameterized procedures: `proc @reverse[$X](%in: $list[$X]) -> (%out: $list[$X])`.
166
+ - Open schema positions (`open_product`, `open_union`, `any`) and schema-symbolic instructions (`project .f`, `guard ?$P`, `dpda_copy $X`, `dpda_skip $X`, `dpda_coerce $X -> $Y`).
167
+
168
+ A `kTVM-P` module is a self-contained polymorphic template; execution always specializes at the input envelope boundary into a **100% closed, envelope-free concrete `kTVM` module** via `specializeKTVM` (backed by K's `intersectPropertyListPatterns`, with an optional `retypeObjectRelationForBackend` pre-pass for non-converged `.ko` relations). If a non-converged relation still cannot close statically, specialization rejects cleanly and the host falls back to `kVM` or the reference evaluator.
169
+
170
+ ### 4.2 Boundary Compatibility Checking and Shape Refinement
171
+
172
+ When an external `k-wire` input arrives, its header decodes to a closed concrete schema graph $S_{\text{in}}$ ([WIRE_FORMAT.md](../codecs/WIRE_FORMAT.md)). Before decoding payload bits, the boundary driver executes:
173
+
174
+ $$\mathrm{specialize}(M_P,\; @\text{entry},\; S_{\text{in}}) \;\longrightarrow\; \mathsf{Ok}(M,\; @\text{entry}',\; S_{\text{out}}) \;\mid\; \mathsf{SchemaError}(\text{reason})$$
175
+
176
+ This pass combines **compatibility verification** and **structural shape refinement** in five steps:
177
+
178
+ 1. **Contract Unification & Parameter Binding:**
179
+ - Unify $S_{\text{in}}$ against `@entry`'s declared input schema contract $C_{\text{in}}$ (using K's greatest-lower-bound / pattern intersection rules from [TYPE_DERIVATION.md](TYPE_DERIVATION.md)).
180
+ - Bind every schema parameter `$X` to a closed concrete sub-schema $S_X$ (checking Moore equivalence whenever `$X` appears multiple times, e.g. `?{ $X a, $X b }`).
181
+ - Refine every `open_product` and `open_union` node by intersecting with the concrete fields/tags present in $S_{\text{in}}$.
182
+ - **Error Semantics:** Any structural contradiction (wrong kind, missing required field, disjoint union tags, incompatible repeated `$X`) raises **`SchemaError`**, strictly distinct from runtime partial failure (`FAILED`).
183
+
184
+ 2. **Output Schema Derivation:**
185
+ - Propagate bound concrete schemas forward through `@entry` and reachable procedures to derive the concrete closed output schema $S_{\text{out}}$ required for the output `k-wire` envelope header.
186
+ - Because K schemas are finite regular graphs, memoizing instantiations by the canonical key `(procId, MooreKey(argSchemas))` is guaranteed to terminate (every encountered sub-schema is either a sub-node of $S_{\text{in}}$, a static pattern node in $M_P$, or a finite intersection thereof).
187
+
188
+ 3. **Access-Profile Port Splitting (Shape Refinement):**
189
+ - For each specialized procedure `@p'`, compute its **access profile** (which product fields are projected, constructed, or passed to callees that project them).
190
+ - **Rule:** If a procedure input or output port has refined to a concrete `product { f1: S1, ..., fm: Sm }` ($m \ge 1$) **and** at least one field of that product is accessed by `@p'` or a callee, split that port into $m$ parallel `BitDeque` channels `(%p.f1: S1, ..., %p.fm: Sm)` (inserting `demux`/`mux` only at union boundaries or the single-stream external `k-wire` boundary).
191
+ - **Opaque Preservation:** If a schema parameter `$X` refined to a concrete product (e.g., `$X := product { a: $int, b: $string }`) in `reverse[$X]`, and `reverse` **never** inspects inside `$X` (only forwards/copies it whole), keep `$X` as a **single `BitDeque`** with concrete schema descriptor `S_X`! This avoids redundant `demux`/`mux` splitting of opaque payloads while still compiling `dpda_copy(S_X)` / `dpda_skip(S_X)` into fast static integer DPDA tables.
192
+
193
+ 4. **Tag Width Resolution, Guard Folding, and Branch Pruning:**
194
+ - Every `open_union` and parameterized `union` now has a fixed canonical tag list, exact ordinal $i$, and exact bit-width $w = \lceil \log_2 n \rceil$.
195
+ - Erase `guard ?$P` instructions proven satisfied by the specialized schema into zero-copy `splice`.
196
+ - Statically prune `switch`/`spec` branches whose leading `match /tag` references a tag absent from the specialized input schema.
197
+ - Collapse `coerce $S1 -> $S2` into zero-copy `splice` whenever $S_1 \equiv S_2$ (Moore-equivalent).
198
+ - 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
+
200
+ 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.
202
+
203
+ > **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
+
205
+ ---
206
+
207
+ ## 5. Formal Abstract Machine and Operational Semantics
208
+
209
+ ### 5.1 Machine State $\Sigma$
210
+
211
+ At runtime, a `kTVM` instance operates over the abstract machine state:
212
+
213
+ $$\Sigma = \langle N,\; C,\; B,\; S,\; \mathcal{M},\; \text{root\_in},\; \text{root\_out} \rangle$$
214
+
215
+ Where:
216
+ - $\mathcal{M}$ is the immutable loaded `kTVM` module (schemas, DPDA tables, `proc` definitions, `kernel` definitions, static bit-chunk `table`s).
217
+ - $N$ is the finite map of active transducer nodes `nid -> NodeState`. Every node carries a `scope: sid`, `status ∈ {ACTIVE, RETIRED}`, and node-kind state.
218
+ - $C$ is the finite map of active `BitDeque` channels `cid -> ChannelState`.
219
+ - $B$ is the finite map of active partiality barriers `bid -> BarrierState`, where `BarrierState = { guards: Set<cid>, status: PENDING | PASSED | FAILED, waiters: Set<nid> }`.
220
+ - $S$ is the tree of active speculation scopes `sid -> ScopeState`, where scope `0` is the root scope, and each child scope `s > 0` records `{ parent: sid, owner: spec_nid, nodes: Set<nid>, chans: Set<cid>, bars: Set<bid>, taps: [(parent_cid, child_cid, replay_buf)], staged: [(child_out_cid, parent_out_cid)] }`.
221
+ - `root_in` is the external input `BitDeque` fed from the `k-wire` payload bitstream (`CLOSED` once EOF is reached); `root_out` is the external output `BitDeque` drained to the `k-wire` output bitstream.
222
+
223
+ ### 5.2 Demand-Driven Pull Scheduler & Sequential Settlement
224
+
225
+ Execution is **demand-driven** from `root_out` (and from the active staging outputs of any active `spec` scope):
226
+
227
+ 1. **Pull Step $\mathsf{pull}(c)$:** Given a channel $c$ whose consumer needs bits (or needs `c.status != OPEN`):
228
+ - If `c.status != OPEN` or `c.prod == NONE`: return immediately (channel is settled or failed).
229
+ - Otherwise, let $u = N[c.\text{prod}]$.
230
+ - **Pre-Expansion Settlement (`after` constraint):** If $u$ is an unexpanded `spawn_node` with an unresolved sequencing dependency `after(v)` where $v \in N$ is still `ACTIVE`, the scheduler first drives $v$ (pulling all of $v$'s output channels to completion/failure until $v$ retires) before expanding $u$.
231
+ - **Step $u$:** Execute one small-step transition of node $u$. If $u$ itself blocks waiting for bits on one of its input channels $c_{\text{in}}$, push $u$ onto the explicit iterative demand stack and call $\mathsf{pull}(c_{\text{in}})$.
232
+ - **Cooperative Yield:** When a streaming `kernel` executes `yield out_q, threshold` (because `|out_q.buf| >= threshold` and `out_q.cons != NONE`), stepping $u$ returns control to `out_q.cons` immediately so downstream drains `out_q` before $u$ resumes.
233
+ 2. **Termination:** Execution finishes when `root_out.status` becomes `CLOSED` (success: output payload is `root_out.buf`, framed with $S_{\text{out}}$) or `FAILED` (ordinary K partial failure: relation is undefined on this input).
234
+ 3. **Strict Iterativity:** The VM demand stack and all DPDA traversal stacks MUST be heap-allocated explicit stacks—never host call-stack recursion—so arbitrarily deep `k-wire` structures (e.g., 4,096-bit `bits[]` values) execute without host stack overflow.
235
+
236
+ ### 5.3 Network Layer Instructions & Small-Step Rules
237
+
238
+ Every `proc` body instantiates a finite acyclic local subgraph when expanded, replacing the `spawn` node in-place inside the same scope.
239
+
240
+ | Instruction | Signature / Syntax | Small-Step Operational Semantics |
241
+ | --- | --- | --- |
242
+ | **`chan`** | `chan %c : $S` | Allocate fresh `BitDeque` `%c` in current scope: `buf = ε`, `status = OPEN`, `prodSchema = consSchema = $S`, `aligned = true`. |
243
+ | **`barrier`** | `barrier %b` | Allocate barrier `%b` (`guards = ∅`, `status = PENDING`, `waiters = ∅`). |
244
+ | **`drain`** | `drain %c : $S [-> %b]` | Register `%c` in `%b.guards` (if `%b` given). Runs iterative `dpda_skip($S)` on `%c`. When `%c` reaches valid end-of-value and `CLOSED`: mark guard done; if all guards of `%b` done, set `%b.status := PASSED` and wake all `%b.waiters`. If `%c` fails or has invalid wire bits: set `%b.status := FAILED`, wake waiters, and retire. |
245
+ | **`gate`** | `gate %b, %in -> %out` | Wait until `%b.status != PENDING` (pulling `%b`'s pending guard drains first). If `PASSED`: execute `splice(%in -> %out)` and retire. If `FAILED`: `fail(%out)`, cancel `%in`, and retire. |
246
+ | **`splice`** | `splice %in -> %out` | Immediate $O(1)$ rewrite: execute `splice(%in -> %out)` (Section 3.3) and retire. Requires $\sigma_{\text{cons}}(\%in) \equiv \sigma_{\text{prod}}(\%out)$ and `%in.aligned = true`. |
247
+ | **`coerce`** | `coerce %in : $S1 -> %out : $S2` | If $S_1 \equiv S_2$, degrade to `splice(%in -> %out)`. Otherwise run iterative paired-stack `dpda_coerce($S1 -> $S2)`: read tag/fields under $S_1$, re-encode under $S_2$, close `%out` on completion (or fail `%out` on `%in` failure / incompatible tag). |
248
+ | **`const_unit`** | `const_unit -> %out` | Immediately execute `close(%out)` ($0$ bits written) and retire. Requires $\sigma_{\text{prod}}(\%out) \equiv \texttt{unit}$. |
249
+ | **`tee`** | `tee %in -> (%o0, ..., %ok)` | Pull chunks (up to 32 bits) from `%in` and `push_bits` to every non-cancelled `%oj`. On `%in.status == CLOSED` (and `|buf| == 0`): `close` all `%oj` and retire immediately. On `%in.status == FAILED`: `fail` all `%oj` and retire. *(Note: if all consumers fail/cancel except one, `tee` may degrade to `splice`.)* |
250
+ | **`wrap`** | `wrap \|tag %in -> %out` | Let `w = code(tag, prodSchema(%out))` of width $k$, with payload schema $\sigma_{\text{tag}}$. Push `w` onto `%out` (`push_bits(%out, w, k)`), narrow `prodSchema(%out) := σ_tag`. If `%in.consSchema ≡ σ_tag`, execute `splice(%in -> %out)` immediately and retire! Otherwise degrade to `coerce %in -> %out`. |
251
+ | **`match`** | `match /tag %in -> %out` | Pull until `|%in.buf| >= w` (where $w$ is tag width of `consSchema(%in)`). Peek $w$ bits: if invalid code or `!= code(tag)`, set `fail(%out)`, cancel `%in`, and retire. If equal: `shift_bits(%in, w)`, update `consSchema(%in) := σ_tag` keeping **`%in.aligned := true`** (exact value boundary!), then execute `splice(%in -> %out)` (or `coerce` if schemas differ) and retire! If `%in` is `FAILED` or `CLOSED` with $< w$ bits: `fail(%out)` and retire. |
252
+ | **`demux`** | `demux %in : $P -> (f0: %c0, ..., fm: %cm)` | **Fusion Rule:** If `%in.buf == ε`, `%in.aligned == true`, `%in.prod` is a `mux` in the **same scope** with matching product schema `$P` and fields `(f0: %a0, ..., fm: %am)`, then for all $i$: `splice(%ai -> %ci)` and retire both `mux` and `demux` in $O(1)$! **Streaming Rule:** Otherwise, for $i = 0 \dots m-2$ in canonical order, run `dpda_copy(S_i)` from `%in` to `%ci` (closing `%ci` at end of field $i$); after field $m-2$ finishes, `%in` stands at the fresh boundary of `S_{m-1}` (`consSchema := S_{m-1}`, `aligned := true`), so execute **`splice(%in -> %cm)`** (zero-copy final field!) and retire. If `%in` fails at any step, fail all remaining unclosed `%ci` and retire. |
253
+ | **`mux`** | `mux (f0: %c0, ..., fm: %cm) -> %out : $P` | **Fusion Rule:** See `demux` above. **Streaming + Tail-Splice Rule:** For $i = 0 \dots m-2$ in canonical order, stream `%ci` to `%out` (`push_bits` / `push_deque`) until `%ci.status == CLOSED` (failing `%out` if any `%ci` fails). Once fields $0 \dots m-2$ are all `CLOSED`, `prodSchema(%out)` has narrowed to `S_{m-1}`: execute **`splice(%cm -> %out)`** and retire! *(Because `splice` prepends small `out.buf` onto large `%cm.buf`, tail-recursive constructors like `{ car, cdr } \|cons` run in $O(|car|)$ with **$0$ bits of `cdr` copied**!)* |
254
+ | **`switch`** | `switch (%i0, ...) { case (t0, ...): { body } ... }` | Deterministic prefix-disjoint multi-port branch. Peeks the leading tag code(s) of `%i0, ...` (non-destructively; never shifts bits!). If any inspected `%ij` fails (or closes prematurely), fail all outputs and retire. Once sufficient peek bits exist: if a unique `case` matches, instantiate `body` directly on parent `(in, out)` channels in the current scope and retire `switch`; if none match (and no `default`), fail all outputs and retire. |
255
+ | **`spec`** | `spec (%i0, ...) -> (%o0, ...) { branch 0: { ... } ... branch k-1: { ... } }` | Ordered speculative backtracking choice (exact rules in Section 5.4). |
256
+ | **`spawn`** | `spawn @proc[$S...](%i...) -> (%o...) [after %tok] [as %tok]` | Allocate an unexpanded lazy stub node in the current scope owning `%o...` and consuming `%i...`. Expands into `@proc`'s body on first pull of any `%oj` (after any `after %tok` peer has retired). Before expanding a recursive `@proc`, the scheduler may settle finite/spliceable upstream chains on `%i...`. |
257
+ | **`exec`** | `exec @kernel(%i...) -> (%o...)` | Instantiate a single-node compiled `kernel` in the current scope with initial state `entry`, zeroed local registers, and empty local stacks (Section 5.5). |
258
+
259
+ **`kTVM-P`-Only Polymorphic Network Instructions** (eliminated during specialization, or executed via runtime schema descriptors):
260
+ - `project .f %in : $S -> %out : $Sf`: extracts field `.f` from an `open_product` (draining all other fields via `barrier`).
261
+ - `guard ?$P %in -> %out`: verifies/intersects runtime schema against `$P` (`SchemaError` on contradiction; `splice` when satisfied).
262
+
263
+ ### 5.4 Exact Operational Semantics of `spec` (Speculative Choice)
264
+
265
+ Let `spec (in_0, ..., in_{m-1}) -> (out_0, ..., out_{r-1})` have branches $B_0, \dots, B_{k-1}$ in scope $s_{\text{par}}$:
266
+
267
+ 1. **Empty Choice ($k = 0$):** Immediately `fail(out_l)` for all $l$, cancel inputs, and retire.
268
+ 2. **Last-Branch Tail Splice ($i = k - 1$):** Instantiate $B_{k-1}$ directly inside $s_{\text{par}}$ wired to the parent `(in_0..in_{m-1})` and `(out_0..out_{r-1})`, and **retire `spec` immediately**. No child scope, replay buffer, or staging buffer is allocated.
269
+ 3. **Speculative Branch ($i < k - 1$):**
270
+ - Create fresh child scope $s_i$ with `parent = s_par`.
271
+ - For each input $j \in [0, m-1]$, allocate tap channel `in'_j` in $s_i$ backed by a `TAP` producer that pulls from `in_j`, records every bit transferred into `replay_j`, and forwards to `in'_j`.
272
+ - For each output $l \in [0, r-1]$, allocate staging channel `out'_l` in $s_i$ (`prodSchema = consSchema = prodSchema(out_l)`).
273
+ - Instantiate $B_i$ inside $s_i$ connected to `(in'_0..in'_{m-1}) -> (out'_0..out'_{r-1})`.
274
+ - Drive $s_i$ by pulling `out'_0 .. out'_{r-1}` until either:
275
+ - **Case A (All `out'_l` are `CLOSED` — Commit):** Discard all `replay_j`, detach `TAP` nodes (splicing any remaining unread `in'_j` bits back if needed — note: valid K branches drain or consume their inputs cleanly; any still-unread bits in `in'_j` are unshifted back to `in_j` only if unconsumed, otherwise `in_j` advances to the post-branch position), `splice(out'_l -> out_l)` for all $l$, destroy child scope $s_i$, and retire `spec`.
276
+ - **Case B (Some `out'_l` is `FAILED` AND some parent `in_j.status == FAILED` — Upstream Failure Abort):** Destroy child scope $s_i$ (all nodes, channels, barriers in $s_i$), immediately `fail(out_l)` for all $l$, and retire `spec`. **Do NOT try branch $i+1$.**
277
+ - **Case C (Some `out'_l` is `FAILED` AND no parent `in_j` is `FAILED` — Local Mismatch Rollback):** Destroy child scope $s_i$. For every input $j \in [0, m-1]$, restore the parent channel bit-for-bit via `unshift_deque(in_j, replay_j)` (preserving `in_j.consSchema`, `in_j.aligned`, and `in_j.status`). Advance to branch $i + 1$.
278
+
279
+ *Notice:* If branch $B_i$ diverges (loops forever without closing or failing `out'_l`), Case A/B/C is never reached and $B_{i+1}$ is never tried—preserving exact K branch-order divergence semantics.
280
+
281
+ ### 5.5 Kernel Layer Instructions & Small-Step Rules
282
+
283
+ A `kernel` is a single transducer node compiled from an acyclic subgraph, a self-tail loop, or a TMC streaming loop. Its local state consists of:
284
+ - Input channel handles `%i0 .. %i{m-1}` and output channel handles `%o0 .. %o{r-1}`;
285
+ - Current basic-block label `pc` (starts at `entry`);
286
+ - Bounded finite-enum registers `reg r : enum(K)` (initialized to `0` or explicit init);
287
+ - Optional kernel-local LIFO bit-stacks `stack s : bits` (initially empty; used by virtual-stack kernels like `_lsb_trim`);
288
+ - Optional suspended-read state when an input `BitDeque` lacks enough buffered bits and must pull upstream before retrying the current instruction.
289
+
290
+ | Instruction | Syntax | Operational Semantics |
291
+ | --- | --- | --- |
292
+ | **`peek_bits`** | `%w = peek_bits %in, @off, k else on_eof` | Ensure `|%in.buf| >= off + k` (pulling `%in` if `OPEN`). If `%in.status == FAILED`, jump to `fail`. If `%in.status == CLOSED` and `|%in.buf| < off + k`, jump to `on_eof`. Else read `k` bits at offset `off` into `%w`. |
293
+ | **`shift_bits`** | `shift_bits %in, k` | Discard `k` bits from front of `%in.buf`; sets `%in.aligned := false` unless an explicit schema boundary reset occurs (`shift_tag`). |
294
+ | **`shift_tag`** | `shift_tag %in, k -> $S_next` | Discard `k` tag bits from aligned `%in`, updating `consSchema(%in) := $S_next` while keeping `%in.aligned := true`. |
295
+ | **`push_bits`** | `push_bits %out, 0b..., k` | Append `k` constant bits to back of `%out.buf`. |
296
+ | **`unshift_bits`** | `unshift_bits %out, 0b..., k` | Prepend `k` constant bits onto front of `%out.buf` (requires `%out.aligned == true`). |
297
+ | **`set_reg`** | `set_reg r, imm` | Assign integer constant `imm ∈ [0, K-1]` to local register `r`. |
298
+ | **`switch_bits`** | `switch_bits %w { case 0b..: goto L ... default: goto Ld }` | Deterministic dispatch on bit temporary `%w`. |
299
+ | **`switch_reg`** | `switch_reg r { case 0: goto L ... }` | Deterministic dispatch on finite-enum register `r`. |
300
+ | **`stack_push`** | `stack_push s, 0b..., k` | Push `k` bits onto top of local LIFO bit-stack `s`. |
301
+ | **`stack_pop`** | `%w = stack_pop s, k else on_empty` | Pop `k` bits from top of `s` into `%w` (or branch to `on_empty` if `|s| < k`). |
302
+ | **`stack_clear`** | `stack_clear s` | Discard all bits on local LIFO bit-stack `s` in $O(1)$. |
303
+ | **`drain_guard`** | `drain_guard %in : $S` | Run iterative `dpda_skip($S)` to verify `%in` completes cleanly to `CLOSED`; jump to `fail` if `%in` fails or is malformed. (Prevents silent drop of unit/discarded guard failures.) |
304
+ | **`dpda_copy`** | `dpda_copy %in -> %out : $S` | Iteratively copy one complete value of schema `$S` from `%in` to `%out`. |
305
+ | **`splice`** | `splice %in -> %out` | Transfer `%in` into `%out` via Section 3.3 (kernel relinquishes both handles). |
306
+ | **`close`** | `close %out` | Close `%out` (kernel relinquishes `%out`). |
307
+ | **`yield`** | `yield %out, N` | If `|%out.buf| >= N` and `%out.cons != NONE`, suspend this kernel and return control to the scheduler so downstream drains `%out`; resume at the next instruction on subsequent pull. |
308
+ | **`goto`** | `goto L` | In-place control transfer to basic block `L` ($O(1)$ stack, zero node allocation). |
309
+ | **`handoff`** | `handoff @target(%args...) -> (%outs...)` | Replace this kernel in-place with a fresh `spawn @target` (or `exec @target`) on the remaining channels and retire immediately. Valid only when `@target` is wired to remaining outputs. |
310
+ | **`retire`** | `retire` | Finish and retire this kernel (validator checks all outputs are closed/spliced/handed off and all inputs are consumed/drained/spliced). |
311
+ | **`fail`** | `fail` | Mark every still-owned output channel `FAILED`, cancel owned inputs, and retire. |
312
+ | **`table_step`** | `table_step &T, reg_state, (%i...), (%o...) -> exits { 0: L0, ... }` | Execute one or more accelerated multi-bit transitions from `chunk_table &T` (Section 6). |
313
+ | **`stack_table_step`** | `stack_table_step &T, reg_state, %in, s, %out -> exits { ... }` | Execute accelerated virtual-stack chunk transitions from `stack_table &T` (Section 6). |
314
+ | **`fsm_table_step`** | `fsm_table_step &T, %in, (%o...) -> exits { ... }` | Execute an acyclic multi-bit FSM table lookup from `fsm_table &T` (Section 6). |
315
+
316
+ ---
317
+
318
+ ## 6. Static Bit-Chunk Tables and Howard MWTR Contract
319
+
320
+ To achieve multi-bit-per-lookup native speed directly over `k-wire`, `kTVM` makes static read-only transition tables first-class module declarations.
321
+
322
+ ### 6.1 Table Kinds
323
+
324
+ A `kTVM` module may declare three kinds of immutable tables (`table &name ...`):
325
+
326
+ 1. **`chunk_table` (Multi-Port Streaming / TMC Loop Table):**
327
+ - **Header:**
328
+ - `states`: number of abstract FSM/register states $Q$ (mapped from a kernel's `reg_state : enum(Q)`).
329
+ - `inputs`: list of `(port_idx, raw_bits: W_raw, eff_bits: W_eff, compress: none | mask(M) | lut([...]))`.
330
+ - `compress` supports **automatic don't-care bit compression** (e.g., when only `0/1` vs `_` matters, collapsing `W_raw = 12` bits into `W_eff = 6` bits via SWAR `pext`/mask or a tiny LUT, shrinking table size from $2^{12}$ to $2^6$).
331
+ - `outputs`: list of `(port_idx, mode: push | unshift, max_emit_bits)`.
332
+ - `exits`: numbered exit handlers `0 .. E-1`.
333
+ - **Flat Address Space:** Entry index is packed as:
334
+ $$\text{idx} = \bigl(((q \ll W_{\text{eff},0}) \mid \text{compress}_0(\text{peek}_0)) \ll W_{\text{eff},1}\bigr) \mid \dots$$
335
+ (When any input port has $< W_{\text{raw}}$ bits buffered because it reached `CLOSED`, remaining high/low padding positions are filled with a canonical closed-EOF sentinel or routed to a compact fallback/short-buffer kernel path—guaranteeing exact behavior on the final $< W_{\text{raw}}$ bits of every stream without ever misreading padding!)
336
+ - **Entry Payload:** `(kind: CONT | EXIT(e) | FAIL | NEED_MORE, next_q, shift[0..m-1], emit_word[0..r-1], emit_len[0..r-1])`.
337
+ - **Hot Loop Semantics (`table_step`):** On each iteration, if any output has `|out.buf| >= yield_threshold` (with an active consumer), suspend cooperatively and resume at `table_step` on the next pull. Otherwise, for every input port with `< W_raw` bits buffered and `status == OPEN`, pull upstream to refill; if any input is `FAILED`, jump to `fail`; if any input is `CLOSED` with `< W_raw` bits (so a full `W_raw`-bit chunk cannot be formed without EOF padding), jump to `short` (the exact bit-level CFG fallback). Once all inputs hold $\ge W_{\text{raw}}$ bits, execute in-place: peek `W_raw` bits → compress → 1 array lookup → `shift_bits` → `push_bits`/`unshift_bits` → `q := next_q`. On `CONT`, continue the hot loop; on `EXIT(e)`, `NEED_MORE` (→ `short`), or `FAIL` (→ `fail`), transfer control to the mapped basic block!
338
+
339
+ 2. **`stack_table` (Virtual-Stack 1-Stream + 1-LIFO-Stack Loop Table):**
340
+ - Models single-pass streaming automata that maintain a local LIFO bit-stack (e.g., `_lsb_trim`'s deferred-zero tally `z`).
341
+ - **Header:** `states: Q`, `stream_bits: W_s`, `stack_bits: W_k`, `output_mode: push | unshift`, `exits: E`.
342
+ - **Address:** `(q, peek(stream, W_s), stack_top_encoding(s, W_k))` where `stack_top_encoding` encodes both the available stack depth $\min(|s|, W_k)$ and the top bits so empty-stack vs. non-empty-stack transitions are resolved in a single lookup.
343
+ - **Entry Payload:** `(kind, next_q, shift_stream, pop_stack, push_stack_word, push_stack_len, emit_word, emit_len)`.
344
+
345
+ 3. **`fsm_table` (Acyclic & Cross-Schema Finite Transducer Table):**
346
+ - Compiles acyclic multi-step helpers (including heterogeneous cross-schema transitions such as `int[] -> bits[]`, `_classify_bits`, `_drop16`) into 1 or a few lookups consuming up to `W_raw` bits at once, followed by `EXIT(e)` to emit/splice/handoff.
347
+
348
+ ### 6.2 Verification & MWTR Optimization Contract
349
+
350
+ Every `table` declaration may carry optional metadata:
351
+ - `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`).
353
+
354
+ ---
355
+
356
+ ## 7. Formal Soundness Properties
357
+
358
+ A valid `kTVM` module (Section 8) executed under Section 5 satisfies four structural guarantees:
359
+
360
+ 1. **SPSC Linearity & Dual-Schema Soundness:** Every channel has at most one producer and at most one consumer at all times, and every operational step preserves $\mathcal{I}(c)$ (Section 3.2). No producer ever writes invalid tag ordinals or clobbers an already-prepended consumer schema.
361
+ 2. **Dynamic DAG Acyclicity & Deadlock Freedom:**
362
+ - Every `proc` body is statically acyclic (checked by validator); recursion only extends the network forward through fresh `spawn` nodes.
363
+ - Every `after %tok` constraint connects only data-independent siblings within the same `proc` expansion (no channel path may exist from the `after` target's outputs back to the `after` predecessor's inputs).
364
+ - Because `BitDeque` buffers grow dynamically (no bounded-buffer write blocking on `tee` or `mux`), no cyclic wait can form between any set of active nodes. Every live network snapshot is a finite DAG, so the pull scheduler is **provably deadlock-free**.
365
+ 3. **Exact K Partiality & Branch-Order Fidelity:**
366
+ - Every unread input channel must be explicitly attached to a `drain` node linked to a `barrier` gating sibling outputs (checked by validator). Thus discarded computations cannot fail silently.
367
+ - `spec` evaluates branches sequentially in source order, aborts immediately on upstream input failure without rolling back, and never falls through past a diverging earlier branch.
368
+ 4. **Bit-Exact `k-wire` Equivalence:** For any closed `k-wire` input $(S_{\text{in}}, b_{\text{in}})$ compatible with `@entry`, `kTVM` produces $(S_{\text{out}}, b_{\text{out}})$ (or `FAILED`, or diverges) identically to K's reference operational semantics under `prefix-codec.mjs`.
369
+
370
+ ---
371
+
372
+ ## 8. Static Validation Rules
373
+
374
+ Before executing or lowering a `kTVM` (or `kTVM-P`) module, the validator verifies:
375
+
376
+ 1. **Schema Well-Formedness:** All schema references resolve; labels within each `product`/`union` are unique and in canonical order; no unguarded direct cycle `schema $A = $A`; concrete `kTVM` modules contain zero `open_product`, `open_union`, `any`, or unbound `$X` nodes.
377
+ 2. **SPSC Channel Linearity:** Within every `proc` body (and each branch of `switch`/`spec`), every local `chan` has exactly one producer and exactly one consumer; every input port is consumed exactly once (via instruction, `tee`, `splice`, `drain`, or `spawn`); every output port is produced exactly once.
378
+ 3. **Local Acyclicity:** The channel dependency graph + `after` scheduling edges within each `proc` body is a DAG.
379
+ 4. **Schema & Alignment Typing:** Every `splice`, `wrap`, `match`, `mux`, `demux`, `spawn`, and `exec` matches the declared schemas (up to Moore equivalence $\equiv$ in `kTVM`, or unify-compatible in `kTVM-P`).
380
+ 5. **Kernel Discipline:** Every path through a `kernel` terminates at `retire`, `handoff`, `fail`, or a `goto` cycle; `retire` is reachable only when all owned outputs have been closed/spliced and all owned inputs consumed/drained/spliced; `unshift_bits` occurs only on statically aligned outputs.
381
+ 6. **Optional Table Bisimulation Check:** For every `table` with `verified_against: @k`, symbolically simulate each table entry against `@k`'s CFG and confirm identical state transitions, shift counts, emitted bits, and exit labels.
382
+
383
+ ---
384
+
385
+ ## 9. Concrete Textual DSL Grammar (EBNF)
386
+
387
+ File extensions: `.ktvmp` (`kTVM-P` polymorphic template), `.ktvm` (`kTVM` specialized executable module). Comments follow K conventions (`-- ...`, `// ...`, `/* ... */`).
388
+
389
+ **Dual Canonical Format:** `kTVM` supports one shared AST with two lossless 1-to-1 serializations: (1) this human-readable textual DSL (using `packed_base64` for large static tables) as the primary authoring and testing format, and (2) a JSON artifact (`format: "k-tvm"`, `version: 1`) matching `KIR-P`/`kVM` conventions for `backend-api.mjs` and specialization caches.
390
+
391
+ ```ebnf
392
+ module ::= header decl* EOF ;
393
+
394
+ header ::= "ktvm" version layer_kind ("entry" PROC_ID)? ";" ;
395
+ version ::= INT "." INT ;
396
+ layer_kind ::= "poly" | "mono" ;
397
+
398
+ decl ::= schema_decl
399
+ | proc_decl
400
+ | kernel_decl
401
+ | table_decl ;
402
+
403
+ (* --- Schemas --- *)
404
+ schema_decl ::= "schema" SCHEMA_ID schema_params? "=" schema_expr ";" ;
405
+ schema_params ::= "[" SCHEMA_ID ("," SCHEMA_ID)* "]" ;
406
+
407
+ schema_expr ::= "unit"
408
+ | "any"
409
+ | "product" "{" field_spec_list? "}"
410
+ | "open_product" "{" field_spec_list? "..." "}"
411
+ | "union" "{" field_spec_list? "}"
412
+ | "open_union" "{" field_spec_list? "..." "}"
413
+ | SCHEMA_ID ("[" schema_expr ("," schema_expr)* "]")? ;
414
+
415
+ field_spec_list ::= label ":" schema_expr ("," label ":" schema_expr)* (",")? ;
416
+
417
+ (* --- Network Procedures --- *)
418
+ proc_decl ::= "proc" PROC_ID schema_params? "(" port_list? ")" "->" "(" port_list? ")"
419
+ proc_attr* "{" net_stmt* "}" ;
420
+ proc_attr ::= "acyclic" | "branching" | "total" ;
421
+ port_list ::= port_decl ("," port_decl)* ;
422
+ port_decl ::= VAR_ID ":" schema_expr ;
423
+
424
+ net_stmt ::= "chan" VAR_ID ":" schema_expr ";"
425
+ | "barrier" VAR_ID ";"
426
+ | "drain" VAR_ID ":" schema_expr ("->" VAR_ID)? ";"
427
+ | "gate" VAR_ID "," VAR_ID "->" VAR_ID ";"
428
+ | "splice" VAR_ID "->" VAR_ID ";"
429
+ | "coerce" VAR_ID ":" schema_expr "->" VAR_ID ":" schema_expr ";"
430
+ | "const_unit" "->" VAR_ID ";"
431
+ | "tee" VAR_ID "->" "(" var_list ")" ";"
432
+ | "wrap" "|" label VAR_ID "->" VAR_ID ";"
433
+ | "match" "/" label VAR_ID "->" VAR_ID ";"
434
+ | "demux" VAR_ID ":" schema_expr "->" "(" labeled_vars? ")" ";"
435
+ | "mux" "(" labeled_vars? ")" "->" VAR_ID ":" schema_expr ";"
436
+ | "project" "." label VAR_ID ":" schema_expr "->" VAR_ID ":" schema_expr ";"
437
+ | "guard" "?" schema_expr VAR_ID "->" VAR_ID ";"
438
+ | "spawn" PROC_ID schema_args? "(" var_list? ")" "->" "(" var_list? ")"
439
+ ("after" VAR_ID)? ("as" VAR_ID)? ";"
440
+ | "exec" PROC_ID "(" var_list? ")" "->" "(" var_list? ")" ";"
441
+ | switch_stmt
442
+ | spec_stmt ;
443
+
444
+ schema_args ::= "[" schema_expr ("," schema_expr)* "]" ;
445
+ var_list ::= VAR_ID ("," VAR_ID)* ;
446
+ labeled_vars ::= label ":" VAR_ID ("," label ":" VAR_ID)* ;
447
+
448
+ switch_stmt ::= "switch" "(" var_list ")" "{" switch_arm+ ("default" ":" "{" net_stmt* "}")? "}" ;
449
+ switch_arm ::= "case" "(" pat_tag ("," pat_tag)* ")" ":" "{" net_stmt* "}" ;
450
+ pat_tag ::= "/" label | "_" ;
451
+
452
+ spec_stmt ::= "spec" "(" var_list? ")" "->" "(" var_list? ")" "{" spec_branch* "}" ;
453
+ spec_branch ::= "branch" INT ":" "{" net_stmt* "}" ;
454
+
455
+ (* --- Compiled Kernels --- *)
456
+ kernel_decl ::= "kernel" PROC_ID "(" port_list? ")" "->" "(" port_list? ")"
457
+ kernel_attr* "{" kernel_res* kernel_block+ "}" ;
458
+ kernel_attr ::= "total" | "tmc" ;
459
+
460
+ kernel_res ::= "reg" IDENT ":" "enum" "(" INT ")" ("=" INT)? ";"
461
+ | "stack" IDENT ":" "bits" ";" ;
462
+
463
+ kernel_block ::= IDENT ":" kernel_stmt* kernel_term ;
464
+
465
+ kernel_stmt ::= VAR_ID "=" "peek_bits" VAR_ID "," "@" INT "," INT "else" IDENT ";"
466
+ | "shift_bits" VAR_ID "," INT ";"
467
+ | "shift_tag" VAR_ID "," INT "->" schema_expr ";"
468
+ | "push_bits" VAR_ID "," BITS_LIT "," INT ";"
469
+ | "unshift_bits" VAR_ID "," BITS_LIT "," INT ";"
470
+ | "set_reg" IDENT "," INT ";"
471
+ | "stack_push" IDENT "," BITS_LIT "," INT ";"
472
+ | VAR_ID "=" "stack_pop" IDENT "," INT "else" IDENT ";"
473
+ | "stack_clear" IDENT ";"
474
+ | "drain_guard" VAR_ID ":" schema_expr ";"
475
+ | "dpda_copy" VAR_ID "->" VAR_ID ":" schema_expr ";"
476
+ | "dpda_coerce" VAR_ID ":" schema_expr "->" VAR_ID ":" schema_expr ";"
477
+ | "splice" VAR_ID "->" VAR_ID ";"
478
+ | "close" VAR_ID ";"
479
+ | "yield" VAR_ID "," INT ";" ;
480
+
481
+ kernel_term ::= "goto" IDENT ";"
482
+ | "retire" ";"
483
+ | "fail" ";"
484
+ | "handoff" PROC_ID "(" var_list? ")" "->" "(" var_list? ")" ";"
485
+ | "switch_bits" VAR_ID "{" bit_case+ ("default" ":" "goto" IDENT ";")? "}"
486
+ | "switch_reg" IDENT "{" int_case+ "}"
487
+ | "table_step" TABLE_ID "," IDENT "," "(" var_list ")" "," "(" var_list? ")"
488
+ "->" "exits" "{" exit_map "}" ";"
489
+ | "stack_table_step" TABLE_ID "," IDENT "," VAR_ID "," IDENT "," VAR_ID
490
+ "->" "exits" "{" exit_map "}" ";"
491
+ | "fsm_table_step" TABLE_ID "," VAR_ID "," "(" var_list? ")"
492
+ "->" "exits" "{" exit_map "}" ";" ;
493
+
494
+ bit_case ::= "case" BITS_LIT ":" "goto" IDENT ";" ;
495
+ int_case ::= "case" INT ":" "goto" IDENT ";" ;
496
+ exit_map ::= exit_entry ("," exit_entry)* (",")? ;
497
+ exit_entry ::= (INT | "short" | "fail") ":" IDENT ;
498
+
499
+ (* --- Static Bit-Chunk Tables --- *)
500
+ table_decl ::= "table" TABLE_ID table_kind "{" table_prop* table_entries "}" ;
501
+ table_kind ::= "chunk_table" | "stack_table" | "fsm_table" ;
502
+ table_prop ::= IDENT ":" table_val ";" ;
503
+ table_val ::= INT | FLOAT | STRING | IDENT | PROC_ID
504
+ | "[" (table_val ("," table_val)*)? "]"
505
+ | "{" (IDENT ":" table_val ("," IDENT ":" table_val)*)? "}" ;
506
+ table_entries ::= "entries" "{" entry_row* "}"
507
+ | "packed_base64" STRING ";" ;
508
+ entry_row ::= INT "=>" table_val ";" ;
509
+
510
+ (* --- Lexical Tokens --- *)
511
+ SCHEMA_ID ::= "$" IDENT ;
512
+ PROC_ID ::= "@" IDENT ;
513
+ TABLE_ID ::= "&" IDENT ;
514
+ VAR_ID ::= "%" IDENT ;
515
+ BITS_LIT ::= "0b" ("0" | "1")+ ;
516
+ label ::= IDENT | INT | "+" | "-" | STRING ;
517
+ IDENT ::= [A-Za-z_] [A-Za-z0-9_?'-]* ;
518
+ INT ::= [0-9]+ ;
519
+ FLOAT ::= [0-9]+ "." [0-9]+ ;
520
+ STRING ::= "\"" ([^"\\] | "\\" .)* "\"" ;
521
+ ```
522
+
523
+ ---
524
+
525
+ ## 10. Worked End-to-End Examples
526
+
527
+ ### 10.1 Polymorphism & Boundary Specialization: `reverse` (`lib/generic.k`)
528
+
529
+ **Source K (`lib/generic.k`):**
530
+ ```k
531
+ list[X] = < {} nil, { X car, L cdr } cons > = L;
532
+ reverse = ?list[X] { () xs, {} |nil acc } _reverse ?list[X];
533
+ _reverse = ?{ list[X] xs, list[X] acc } <
534
+ { .xs /nil _, .acc acc } .acc,
535
+ { .xs /cons .cdr xs, { .xs /cons .car car, .acc cdr } |cons acc } _reverse
536
+ >;
537
+ ```
538
+
539
+ **Stage 1 — Polymorphic `kTVM-P` Module (`reverse.ktvmp`):**
540
+ ```ktvm
541
+ ktvm 0.1 poly entry @reverse;
542
+
543
+ schema $list[$X] = union {
544
+ cons: product { car: $X, cdr: $list[$X] },
545
+ nil: unit
546
+ };
547
+
548
+ proc @reverse[$X](%in: $list[$X]) -> (%out: $list[$X]) {
549
+ chan %acc_u : unit;
550
+ chan %acc : $list[$X];
551
+ const_unit -> %acc_u;
552
+ wrap |nil %acc_u -> %acc;
553
+ spawn @_reverse[$X](%in, %acc) -> (%out);
554
+ }
555
+
556
+ proc @_reverse[$X](%xs: $list[$X], %acc: $list[$X]) -> (%out: $list[$X]) {
557
+ switch (%xs) {
558
+ case (/nil): {
559
+ chan %u : unit;
560
+ barrier %b;
561
+ match /nil %xs -> %u;
562
+ drain %u : unit -> %b;
563
+ gate %b, %acc -> %out;
564
+ }
565
+ case (/cons): {
566
+ chan %cell : product { car: $X, cdr: $list[$X] };
567
+ chan %car : $X;
568
+ chan %cdr : $list[$X];
569
+ chan %newcell : product { car: $X, cdr: $list[$X] };
570
+ chan %newacc : $list[$X];
571
+ match /cons %xs -> %cell;
572
+ demux %cell : product { car: $X, cdr: $list[$X] } -> (car: %car, cdr: %cdr);
573
+ mux (car: %car, cdr: %acc) -> %newcell : product { car: $X, cdr: $list[$X] };
574
+ wrap |cons %newcell -> %newacc;
575
+ spawn @_reverse[$X](%cdr, %newacc) -> (%out);
576
+ }
577
+ }
578
+ }
579
+ ```
580
+
581
+ **Stage 2 — Boundary Specialization when an enveloped `list[int[]]` arrives (`reverse_int.ktvm`):**
582
+ Suppose the input envelope supplies `S_in = $list[$int]`. Boundary refinement checks compatibility against `$list[$X]`, binds `$X := $int`, derives `S_out = $list[$int]`, and notices:
583
+ - `cons` is accessed (`demux`/`mux`), so `cons` splits into `(%car: $int, %cdr: $list[$int])`.
584
+ - `$int` itself is **never** projected or matched inside `@reverse`, so `%car` stays a **single opaque `BitDeque`** of schema `$int`, and `demux` copies `car` with a compiled concrete `dpda_copy($int)` while `mux` tail-splices `%acc` in $O(1)$ (`0` bits of `%acc` copied per element)!
585
+ - Tag bit-widths resolve statically: `cons = 0b0` (1 bit), `nil = 0b1` (1 bit).
586
+
587
+ ```ktvm
588
+ ktvm 0.1 mono entry @reverse__int;
589
+
590
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
591
+ schema $int = union { "+": $bits, "-": $bits };
592
+ schema $list_int = union {
593
+ cons: product { car: $int, cdr: $list_int },
594
+ nil: unit
595
+ };
596
+
597
+ proc @reverse__int(%in: $list_int) -> (%out: $list_int) total {
598
+ chan %acc_u : unit;
599
+ chan %acc : $list_int;
600
+ const_unit -> %acc_u;
601
+ wrap |nil %acc_u -> %acc; // pushes 1 bit (0b1), closes %acc
602
+ spawn @_reverse__int(%in, %acc) -> (%out);
603
+ }
604
+
605
+ proc @_reverse__int(%xs: $list_int, %acc: $list_int) -> (%out: $list_int) total {
606
+ switch (%xs) { // 1-bit peek: 0 -> cons, 1 -> nil
607
+ case (/nil): {
608
+ chan %u : unit;
609
+ barrier %b;
610
+ match /nil %xs -> %u;
611
+ drain %u : unit -> %b;
612
+ gate %b, %acc -> %out; // O(1) splice of reversed %acc
613
+ }
614
+ case (/cons): {
615
+ chan %cell : product { car: $int, cdr: $list_int };
616
+ chan %car : $int; // stays opaque single BitDeque!
617
+ chan %cdr : $list_int;
618
+ chan %newcell : product { car: $int, cdr: $list_int };
619
+ chan %newacc : $list_int;
620
+ match /cons %xs -> %cell;
621
+ demux %cell : product { car: $int, cdr: $list_int } -> (car: %car, cdr: %cdr);
622
+ mux (car: %car, cdr: %acc) -> %newcell : product { car: $int, cdr: $list_int };
623
+ wrap |cons %newcell -> %newacc; // O(1) unshift of (0b0 + car) onto %acc
624
+ spawn @_reverse__int(%cdr, %newacc) -> (%out);
625
+ }
626
+ }
627
+ }
628
+ ```
629
+
630
+ ### 10.2 Guarded Streaming TMC Kernel + Bit-Chunk Table: `_lsb_add` (`ktvm/fixtures/integer-streaming.k`)
631
+
632
+ Demonstrates in-register carry promotion (`reg c : enum(2)`), forward streaming `push_bits`, cooperative `yield`, $O(1)$ zero-copy tail splicing on `carry == 0`, and accelerated `chunk_table` dispatch with short-tail fallback to the exact bit-level CFG:
633
+
634
+ ```ktvm
635
+ ktvm 0.1 mono entry @lsb_add;
636
+
637
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
638
+ // Canonical tag codes: 0 -> 0b00, 1 -> 0b01, _ -> 0b10 (0b11 invalid)
639
+
640
+ proc @lsb_add(%x: $bits, %y: $bits) -> (%out: $bits) total {
641
+ exec @_lsb_add_kernel(%x, %y) -> (%out);
642
+ }
643
+
644
+ kernel @_lsb_add_kernel(%x: $bits, %y: $bits) -> (%out: $bits) total tmc {
645
+ reg c : enum(2) = 0;
646
+
647
+ entry:
648
+ yield %out, 64;
649
+ table_step &tab_lsb_add, c, (%x, %y), (%out) -> exits {
650
+ short: slow_step,
651
+ 0: exit_zero_done,
652
+ 1: exit_carry_done,
653
+ 2: exit_splice_y,
654
+ 3: exit_splice_x,
655
+ fail: err
656
+ };
657
+
658
+ slow_step:
659
+ %tx = peek_bits %x, @0, 2 else err;
660
+ %ty = peek_bits %y, @0, 2 else err;
661
+ switch_bits %tx {
662
+ case 0b10: goto x_end;
663
+ case 0b00: goto x_0;
664
+ case 0b01: goto x_1;
665
+ default: goto err;
666
+ }
667
+
668
+ x_end:
669
+ switch_bits %ty {
670
+ case 0b10: goto both_end;
671
+ case 0b00: goto x_end_y_nz;
672
+ case 0b01: goto x_end_y_nz;
673
+ default: goto err;
674
+ }
675
+
676
+ both_end:
677
+ shift_tag %x, 2 -> unit;
678
+ shift_tag %y, 2 -> unit;
679
+ drain_guard %x : unit;
680
+ drain_guard %y : unit;
681
+ switch_reg c {
682
+ case 0: goto exit_zero_done;
683
+ case 1: goto exit_carry_done;
684
+ }
685
+
686
+ x_end_y_nz:
687
+ switch_reg c {
688
+ case 0: goto x_end_splice_y;
689
+ case 1: goto x_end_prop_carry;
690
+ }
691
+
692
+ x_end_splice_y:
693
+ shift_tag %x, 2 -> unit;
694
+ drain_guard %x : unit;
695
+ goto exit_splice_y;
696
+
697
+ x_end_prop_carry:
698
+ // y_bit + carry=1: 0+1 -> emit 1, c=0; 1+1 -> emit 0, c=1
699
+ shift_tag %y, 2 -> $bits;
700
+ switch_bits %ty {
701
+ case 0b00: goto emit_1_c0;
702
+ case 0b01: goto emit_0_c1;
703
+ default: goto err;
704
+ }
705
+
706
+ // (x_0, x_1 symmetric full-adder states omitted for brevity;
707
+ // each shifts consumed tags, pushes sum tag to %out, updates c, goto entry)
708
+ x_0:
709
+ goto err;
710
+ x_1:
711
+ goto err;
712
+
713
+ emit_1_c0:
714
+ push_bits %out, 0b01, 2;
715
+ set_reg c, 0;
716
+ goto entry;
717
+
718
+ emit_0_c1:
719
+ push_bits %out, 0b00, 2;
720
+ set_reg c, 1;
721
+ goto entry;
722
+
723
+ exit_zero_done:
724
+ push_bits %out, 0b10, 2; // emit '_'
725
+ close %out;
726
+ retire;
727
+
728
+ exit_carry_done:
729
+ push_bits %out, 0b01, 2; // emit '1'
730
+ push_bits %out, 0b10, 2; // emit '_'
731
+ close %out;
732
+ retire;
733
+
734
+ exit_splice_y:
735
+ splice %y -> %out; // O(1) zero-copy tail splice!
736
+ retire;
737
+
738
+ exit_splice_x:
739
+ splice %x -> %out; // O(1) zero-copy tail splice!
740
+ retire;
741
+
742
+ err:
743
+ fail;
744
+ }
745
+
746
+ table &tab_lsb_add chunk_table {
747
+ states: 2;
748
+ inputs: [
749
+ { port: 0, raw_bits: 8, eff_bits: 8, compress: none },
750
+ { port: 1, raw_bits: 8, eff_bits: 8, compress: none }
751
+ ];
752
+ outputs: [ { port: 0, mode: push, max_emit_bits: 10 } ];
753
+ verified_against: @_lsb_add_kernel;
754
+ mwtr: { rho: 16.0, bytes: 196608, budget_class: "L2" };
755
+ packed_base64 "AAA="; // placeholder in spec example
756
+ }
757
+ ```
758
+
759
+ ### 10.3 Virtual-Stack Kernel: Online `_lsb_trim` (`ktvm/fixtures/integer-streaming.k`)
760
+
761
+ Demonstrates a first-class kernel-local LIFO bit-stack (`stack z : bits`) accelerating single-pass trailing-zero trimming without an external `BitDeque` channel:
762
+
763
+ ```ktvm
764
+ kernel @_lsb_trim_kernel(%in: $bits) -> (%out: $bits) total tmc {
765
+ reg mode : enum(2) = 0; // 0 = scan, 1 = flush deferred '0's
766
+ stack z : bits; // local LIFO tally of pending '0' tags
767
+
768
+ entry:
769
+ yield %out, 64;
770
+ stack_table_step &tab_lsb_trim, mode, %in, z, %out -> exits {
771
+ short: slow_step,
772
+ 0: exit_eof,
773
+ fail: err
774
+ };
775
+
776
+ slow_step:
777
+ switch_reg mode {
778
+ case 0: goto scan;
779
+ case 1: goto flush;
780
+ }
781
+
782
+ scan:
783
+ %t = peek_bits %in, @0, 2 else err;
784
+ switch_bits %t {
785
+ case 0b10: goto scan_eof; // '_': drop all deferred '0's in z!
786
+ case 0b00: goto scan_zero; // '0': defer onto local stack z
787
+ case 0b01: goto scan_one; // '1': flush z then emit '1'
788
+ default: goto err;
789
+ }
790
+
791
+ scan_eof:
792
+ shift_tag %in, 2 -> unit;
793
+ drain_guard %in : unit;
794
+ stack_clear z;
795
+ goto exit_eof;
796
+
797
+ scan_zero:
798
+ shift_tag %in, 2 -> $bits;
799
+ stack_push z, 0b0, 1;
800
+ goto entry;
801
+
802
+ scan_one:
803
+ shift_tag %in, 2 -> $bits;
804
+ %_top = stack_pop z, 1 else emit_one_scan;
805
+ push_bits %out, 0b00, 2;
806
+ set_reg mode, 1;
807
+ goto entry;
808
+
809
+ flush:
810
+ %_top = stack_pop z, 1 else emit_one_scan;
811
+ push_bits %out, 0b00, 2;
812
+ goto entry;
813
+
814
+ emit_one_scan:
815
+ push_bits %out, 0b01, 2;
816
+ set_reg mode, 0;
817
+ goto entry;
818
+
819
+ exit_eof:
820
+ push_bits %out, 0b10, 2;
821
+ close %out;
822
+ retire;
823
+
824
+ err:
825
+ fail;
826
+ }
827
+ ```
828
+
829
+ ### 10.4 Branching Recursion with Sequential Sibling Settlement: Karatsuba `lsb_mul`
830
+
831
+ Demonstrates explicit `after %tok` sequencing on the 3 branching recursive `lsb_mul` calls (derived statically from `isBranchingRecursive`), keeping peak live network topology $O(\log n)$ instead of $O(n^{\log_2 3})$ while preserving textbook non-tail recursion:
832
+
833
+ ```ktvm
834
+ proc @lsb_mul_karatsuba(%x: $bits, %y: $bits) -> (%out: $bits) branching total {
835
+ chan %x0 : $bits; chan %x1 : $bits;
836
+ chan %y0 : $bits; chan %y1 : $bits;
837
+ chan %k : $bits; chan %k0 : $bits; chan %k1 : $bits; chan %k2 : $bits;
838
+ chan %xlo : $bits; chan %xhi : $bits;
839
+ chan %ylo : $bits; chan %yhi : $bits;
840
+ chan %xlo0 : $bits; chan %xlo1 : $bits; chan %xhi0 : $bits; chan %xhi1 : $bits;
841
+ chan %ylo0 : $bits; chan %ylo1 : $bits; chan %yhi0 : $bits; chan %yhi1 : $bits;
842
+ chan %sx : $bits; chan %sy : $bits;
843
+ chan %z0 : $bits; chan %z2 : $bits; chan %z3 : $bits;
844
+
845
+ tee %x -> (%x0, %x1);
846
+ tee %y -> (%y0, %y1);
847
+ spawn @half_max_tally(%x0, %y0) -> (%k);
848
+ tee %k -> (%k0, %k1, %k2);
849
+
850
+ spawn @lsb_split(%x1, %k0) -> (%xlo, %xhi);
851
+ spawn @lsb_split(%y1, %k1) -> (%ylo, %yhi);
852
+
853
+ tee %xlo -> (%xlo0, %xlo1);
854
+ tee %xhi -> (%xhi0, %xhi1);
855
+ tee %ylo -> (%ylo0, %ylo1);
856
+ tee %yhi -> (%yhi0, %yhi1);
857
+
858
+ spawn @lsb_add(%xlo1, %xhi1) -> (%sx);
859
+ spawn @lsb_add(%ylo1, %yhi1) -> (%sy);
860
+
861
+ // Sequential sibling settlement: each recursive subtree retires into a plain
862
+ // BitDeque before the next expands -> O(log n) peak live nodes!
863
+ spawn @lsb_mul(%xlo0, %ylo0) -> (%z0) as %t0;
864
+ spawn @lsb_mul(%xhi0, %yhi0) -> (%z2) after %t0 as %t1;
865
+ spawn @lsb_mul(%sx, %sy) -> (%z3) after %t1;
866
+
867
+ spawn @_karatsuba_combine(%k2, %z0, %z2, %z3) -> (%out);
868
+ }
869
+ ```
870
+
871
+ ---
872
+
873
+ ## 11. Implementation Structure and Evolution Hooks
874
+
875
+ ### 11.1 Production Implementation (`ktvm/`, Peer Backend Alongside `kVM`)
876
+
877
+ 1. **Core IR, Validator, Specializer & Reference VM (`ktvm/`):**
878
+ - `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`.
880
+ - `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`).
882
+ - `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`).
884
+ - Verified by `ktvm/test-ktvm.mjs`.
885
+ 2. **`KIR-P → kTVM-P` Lowering & Full Standard-Library Parity (`ktvm/lower-kir.mjs`):**
886
+ - Lowers all `KIR-P` opcodes (`usedPaths`, deterministic `switch` vs. `spec`, `isBranchingRecursive` `after %tok`, optional `retypeObjectRelationForBackend` fallback).
887
+ - Exposed via `backend-api.mjs`, `harness/cli.mjs`, and `npm test` while keeping `lib/*.k` untouched.
888
+ - 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
+ 3. **Verified `kTVM → kTVM` Optimization Passes (`ktvm/optimize/`):**
890
+ - 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).
892
+ - Verified by `ktvm/test-optimize.mjs`.
893
+ 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`.
895
+ - `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
+
897
+ ### 11.2 Intentionally Isolated Evolution Hooks
898
+
899
+ 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.
901
+ - **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
+ - **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.