@fraczak/k 8.9.0 → 9.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/DOCS/ARCHITECTURE.md +5 -4
- package/DOCS/DICTIONARY.md +2 -2
- package/DOCS/FILE_FORMATS.md +11 -9
- package/DOCS/KIR_V1.md +5 -1
- package/DOCS/KTVM_SPEC.md +907 -0
- package/DOCS/KVM_EXECUTION_MODEL.md +3 -2
- package/DOCS/KVM_VS_KTVM_COMPARATIVE_STUDY.md +127 -0
- package/DOCS/PROFILING_AND_TRACING.md +13 -4
- package/DOCS/README.md +3 -2
- package/DOCS/REPL.md +16 -12
- package/README.md +138 -2
- package/backend-api.mjs +31 -16
- package/backends/llvm/README.md +4 -5
- package/backends/llvm/bin/k-llvm-build.mjs +7 -19
- package/backends/llvm/bin/k-llvm-compile.mjs +6 -18
- package/backends/llvm/bin/k-llvm.mjs +11 -33
- package/backends/llvm/src/cli.mjs +2 -12
- package/backends/llvm/src/executable.mjs +7 -95
- package/backends/llvm/src/kvm2llvm.mjs +1 -7
- package/backends/llvm/src/llvm.mjs +4 -113
- package/backends/llvm/tests/k-llvm-run.mjs +1 -6
- package/backends/llvm/tests/perf-support.mjs +3 -5
- package/backends/llvm/tests/test-llvm.mjs +2 -16
- package/backends/wasm/README.md +7 -3
- package/backends/wasm/bin/k-wasm-compile.mjs +4 -7
- package/backends/wasm/bin/k-wasm.mjs +4 -6
- package/backends/wasm/src/cli.mjs +8 -24
- package/backends/wasm/src/wasm.mjs +60 -57
- package/backends/wasm/tests/test-wasm.mjs +41 -2
- package/browser/repl-browser.mjs +9 -8
- package/browser/shims/buffer.mjs +31 -2
- package/browser/shims/child_process.mjs +26 -0
- package/browser/shims/fs.mjs +3 -1
- package/codecs/runtime/prefix-codec.mjs +67 -1
- package/conformance/run.mjs +17 -2
- package/harness/adapters/ktvm-llvm.mjs +118 -0
- package/harness/adapters/ktvm-wasm.mjs +104 -0
- package/harness/adapters/ktvm.mjs +133 -0
- package/harness/registry.mjs +9 -0
- package/ktvm/ast.mjs +218 -0
- package/ktvm/bit-deque.mjs +497 -0
- package/ktvm/fixtures/integer-streaming.k +477 -0
- package/ktvm/index.mjs +130 -0
- package/ktvm/llvm/index.mjs +202 -0
- package/ktvm/llvm/lower-c.mjs +1258 -0
- package/ktvm/llvm/runtime.h +3542 -0
- package/ktvm/llvm/test-llvm.mjs +476 -0
- package/ktvm/lower-kir.mjs +2221 -0
- package/ktvm/optimize/fuse-kernel.mjs +2111 -0
- package/ktvm/optimize/index.mjs +116 -0
- package/ktvm/optimize/mwtr.mjs +283 -0
- package/ktvm/optimize/simplify-procs.mjs +5250 -0
- package/ktvm/optimize/synthesize-tables.mjs +1105 -0
- package/ktvm/parser.mjs +1101 -0
- package/ktvm/printer.mjs +281 -0
- package/ktvm/schema.mjs +1134 -0
- package/ktvm/specialize.mjs +538 -0
- package/ktvm/test-conformance.mjs +597 -0
- package/ktvm/test-ktvm.mjs +1805 -0
- package/ktvm/test-optimize.mjs +598 -0
- package/ktvm/validator.mjs +1280 -0
- package/ktvm/vm.mjs +2225 -0
- package/ktvm/wasm/index.mjs +331 -0
- package/ktvm/wasm/lower-wasm.mjs +1272 -0
- package/ktvm/wasm/runtime.wat +4404 -0
- package/ktvm/wasm/test-wasm.mjs +429 -0
- package/ktvm/wire.mjs +679 -0
- package/package.json +1 -9
- package/paper/Makefile +8 -5
- package/paper/k-transducer-compiler.pdf +0 -0
- package/paper/k-transducer-compiler.tex +658 -0
- package/paper/replay-diagnostic.mjs +63 -0
- package/repl.mjs +101 -20
- package/scripts/build-repl-html.mjs +40 -18
- package/scripts/perf-bigint-compare.mjs +12 -16
- package/scripts/perf-ieee.mjs +14 -232
- package/scripts/perf-int.mjs +16 -274
- package/scripts/perf-multiplication.mjs +116 -121
- package/scripts/perf-poly.mjs +9 -263
- package/scripts/run-tests.mjs +5 -2
- package/scripts/test-package.mjs +15 -3
- package/tests/README.md +3 -3
- package/tests/test-repl-html.mjs +72 -15
- package/tests/test-repl.mjs +24 -17
- package/DOCS/POLYMORPHIC_IR.md +0 -86
- package/access-table.mjs +0 -343
- package/pkir.mjs +0 -772
- package/tests/test-access-table.mjs +0 -213
- package/tests/test-pkir.mjs +0 -530
|
@@ -0,0 +1,658 @@
|
|
|
1
|
+
\documentclass[10pt,a4paper]{article}
|
|
2
|
+
|
|
3
|
+
% --- Packages ---
|
|
4
|
+
\usepackage[margin=0.84in]{geometry}
|
|
5
|
+
\usepackage[T1]{fontenc}
|
|
6
|
+
\usepackage[utf8]{inputenc}
|
|
7
|
+
\usepackage{lmodern}
|
|
8
|
+
\usepackage{amsmath,amssymb,amsthm,stmaryrd}
|
|
9
|
+
\usepackage{microtype}
|
|
10
|
+
\usepackage{booktabs}
|
|
11
|
+
\usepackage{array}
|
|
12
|
+
\usepackage{tabularx}
|
|
13
|
+
\usepackage{enumitem}
|
|
14
|
+
\usepackage{xcolor}
|
|
15
|
+
\usepackage{listings}
|
|
16
|
+
\usepackage{cite}
|
|
17
|
+
\usepackage{tikz}
|
|
18
|
+
\usetikzlibrary{arrows.meta,positioning,shapes.geometric,fit,calc}
|
|
19
|
+
\usepackage[colorlinks=true,
|
|
20
|
+
linkcolor=blue!70!black,
|
|
21
|
+
citecolor=blue!70!black,
|
|
22
|
+
urlcolor=blue!70!black]{hyperref}
|
|
23
|
+
|
|
24
|
+
\setlist{itemsep=2pt, topsep=3pt, parsep=0pt}
|
|
25
|
+
|
|
26
|
+
% --- Theorem Environments ---
|
|
27
|
+
\newtheorem{theorem}{Theorem}[section]
|
|
28
|
+
\newtheorem{definition}[theorem]{Definition}
|
|
29
|
+
\newtheorem{invariant}[theorem]{Invariant}
|
|
30
|
+
\newtheorem{proposition}[theorem]{Proposition}
|
|
31
|
+
|
|
32
|
+
% --- Macros ---
|
|
33
|
+
\newcommand{\ktvm}{kTVM}
|
|
34
|
+
\newcommand{\ktvmp}{kTVM-P}
|
|
35
|
+
\newcommand{\kvm}{kVM}
|
|
36
|
+
\newcommand{\kirp}{KIR-P}
|
|
37
|
+
\newcommand{\kwire}{\texttt{k-wire}}
|
|
38
|
+
\newcommand{\BitDeque}{\texttt{BitDeque}}
|
|
39
|
+
\newcommand{\sprod}{\sigma_{\mathrm{prod}}}
|
|
40
|
+
\newcommand{\scons}{\sigma_{\mathrm{cons}}}
|
|
41
|
+
\newcommand{\lang}{\mathcal{L}}
|
|
42
|
+
\newcommand{\sem}[1]{\llbracket #1 \rrbracket}
|
|
43
|
+
\newcommand{\stOpen}{\mathsf{OPEN}}
|
|
44
|
+
\newcommand{\stClosed}{\mathsf{CLOSED}}
|
|
45
|
+
\newcommand{\stFailed}{\mathsf{FAILED}}
|
|
46
|
+
|
|
47
|
+
% --- Code Listings Configuration ---
|
|
48
|
+
\lstdefinelanguage{ktvm}{
|
|
49
|
+
morecomment=[l]{//},
|
|
50
|
+
morecomment=[l]{--},
|
|
51
|
+
morekeywords={ktvm,poly,mono,entry,schema,unit,any,product,union,open_product,open_union,
|
|
52
|
+
proc,kernel,table,chunk_table,stack_table,fsm_table,total,tmc,branching,
|
|
53
|
+
chan,barrier,drain,gate,splice,coerce,const_unit,tee,wrap,match,demux,mux,
|
|
54
|
+
project,guard,spawn,exec,after,as,switch,case,default,spec,branch,
|
|
55
|
+
reg,enum,stack,bits,peek_bits,shift_bits,shift_tag,push_bits,unshift_bits,
|
|
56
|
+
set_reg,stack_push,stack_pop,stack_clear,drain_guard,dpda_copy,close,yield,
|
|
57
|
+
goto,handoff,retire,fail,table_step,stack_table_step,fsm_table_step,exits,else},
|
|
58
|
+
sensitive=true,
|
|
59
|
+
basicstyle=\ttfamily\footnotesize,
|
|
60
|
+
keywordstyle=\bfseries\color{blue!75!black},
|
|
61
|
+
commentstyle=\itshape\color{gray!75!black},
|
|
62
|
+
stringstyle=\color{green!50!black},
|
|
63
|
+
breaklines=true,
|
|
64
|
+
tabsize=2,
|
|
65
|
+
columns=fullflexible,
|
|
66
|
+
keepspaces=true,
|
|
67
|
+
frame=single,
|
|
68
|
+
rulecolor=\color{gray!30},
|
|
69
|
+
backgroundcolor=\color{gray!5},
|
|
70
|
+
aboveskip=0.6em,
|
|
71
|
+
belowskip=0.6em
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
\lstdefinelanguage{k}{
|
|
75
|
+
morecomment=[l]{--},
|
|
76
|
+
morekeywords={bit,bits,list,int,reverse,_reverse,lsb_add,lsb_trim},
|
|
77
|
+
sensitive=true,
|
|
78
|
+
basicstyle=\ttfamily\footnotesize,
|
|
79
|
+
keywordstyle=\bfseries\color{blue!75!black},
|
|
80
|
+
commentstyle=\itshape\color{gray!75!black},
|
|
81
|
+
breaklines=true,
|
|
82
|
+
tabsize=2,
|
|
83
|
+
columns=fullflexible,
|
|
84
|
+
keepspaces=true,
|
|
85
|
+
frame=single,
|
|
86
|
+
rulecolor=\color{gray!30},
|
|
87
|
+
backgroundcolor=\color{gray!5},
|
|
88
|
+
aboveskip=0.6em,
|
|
89
|
+
belowskip=0.6em
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
% --- Metadata ---
|
|
93
|
+
\title{\textbf{\ktvm: A Packed-Wire Execution Model\\and Compiler for K}}
|
|
94
|
+
\author{
|
|
95
|
+
\textbf{Wojciech Fraczak}\\
|
|
96
|
+
\texttt{fraczak@gmail.com}
|
|
97
|
+
}
|
|
98
|
+
\date{November 2026}
|
|
99
|
+
\hypersetup{pdftitle={kTVM: A Packed-Wire Execution Model and Compiler for K},
|
|
100
|
+
pdfauthor={Wojciech Fraczak}}
|
|
101
|
+
|
|
102
|
+
\begin{document}
|
|
103
|
+
|
|
104
|
+
\maketitle
|
|
105
|
+
|
|
106
|
+
\begin{abstract}
|
|
107
|
+
\emph{K: the programming language}~\cite{fraczak2026k} defines computation as first-order partial functions (\emph{relations}) over finite, rooted, edge-labeled trees paired with a self-delimiting binary wire format (\kwire). This sequel presents a self-contained description of \textbf{\ktvm} (the K Transducer Virtual Machine), a packed-wire execution model and multi-target compiler that evaluates K relations on packed \kwire{} payloads without materializing pointer-linked heap trees.
|
|
108
|
+
|
|
109
|
+
We formalize the closed schema algebra, wire equivalence, and prefix derivatives. The Dual-Schema Suffix Invariant specifies how single-producer, single-consumer \BitDeque{} channels preserve their schema obligations under \texttt{splice}. We define the iterative pull semantics of K's combinators, including barriers for strict partiality and scoped replay for ordered choice. We then describe direct specialization of \kirp{} and boundary specialization of \ktvmp{} templates, the two-tier network/kernel optimization pipeline with Minimum Weight-to-Time Ratio (MWTR) multi-bit lookup tables, the JavaScript interpreter and code generation for WebAssembly and C/LLVM, and the principal qualitative trade-offs observed against K's heap-allocated register machine (\kvm).
|
|
110
|
+
\end{abstract}
|
|
111
|
+
|
|
112
|
+
\vspace{0.35em}
|
|
113
|
+
\noindent\textbf{Keywords:} Operational semantics, Pushdown transducers, Packed-wire compilation, Streaming dataflow, Regular tree languages, Minimum weight-to-time ratio.
|
|
114
|
+
|
|
115
|
+
% ============================================================================
|
|
116
|
+
\section{Introduction}
|
|
117
|
+
% ============================================================================
|
|
118
|
+
|
|
119
|
+
K relations are first-order partial functions on finite, rooted, edge-labeled trees called \emph{documents}, each interpreted under a deterministic regular tree schema (a \emph{pattern}). Following CCS~\cite{milner1989ccs} and CSP~\cite{hoare1985csp}, the first paper~\cite{fraczak2026k} builds all relations from three combinators: \textbf{chaining} \lstinline[language=k]|(f g)| feeds $f$'s output to $g$ (with \lstinline[language=k]|()| as identity); \textbf{concurrent (ordered) choice} \lstinline[language=k]|<f, g>| tries $f$ first and falls back to $g$ only if $f$ is undefined (\lstinline[language=k]|<>| is everywhere undefined); and \textbf{parallel composition} \lstinline[language=k]|{f a, g b}| applies both branches to the same input to form a labeled product, failing if either branch is undefined (the empty product \lstinline[language=k]|{}| yields the unit document whenever its input is defined). Elementary relations project product fields (\lstinline[language=k]|.l|), match variant tags (\lstinline[language=k]|/t|), wrap values under tags (\lstinline[language=k]!|t!), and embed static schema filters (\lstinline[language=k]|?P|).
|
|
120
|
+
|
|
121
|
+
At a framed wire boundary, K pairs a document $d$ with its closed schema $S$ in a canonical, prefix-free binary bitstream (\kwire):
|
|
122
|
+
\begin{equation}
|
|
123
|
+
\mathrm{Stream}(S, d) \;=\; \mathrm{encode}\bigl(S : \texttt{pattern}[]\bigr) \;\cdot\; \mathrm{encode}(d : S),
|
|
124
|
+
\end{equation}
|
|
125
|
+
where \texttt{pattern[]} is the fixed self-hosted schema of pattern graphs shared by encoder and decoder~\cite{fraczak2026k}. The header and payload share one contiguous bit sequence, padded to a whole byte only at the end of the frame.
|
|
126
|
+
|
|
127
|
+
\paragraph{Running Example.}
|
|
128
|
+
As a running example carried over from the first paper~\cite{fraczak2026k}, consider the complete K half adder below (where \texttt{if} and \texttt{then} are ordinary product labels):
|
|
129
|
+
\begin{lstlisting}[language=k, aboveskip=0.45em, belowskip=0.45em]
|
|
130
|
+
bit[] = < {} 0, {} 1 >;
|
|
131
|
+
0 = {} |0 ?bit[]; 1 = {} |1 ?bit[]; not = < /0 1, 0 >;
|
|
132
|
+
half_add = ?{ bit[] a, bit[] b } <
|
|
133
|
+
{ .a /0 if, { .b sum, 0 carry } then } .then,
|
|
134
|
+
{ .b not sum, .b carry }
|
|
135
|
+
>;
|
|
136
|
+
\end{lstlisting}
|
|
137
|
+
Its input schema has two \texttt{bit[]} fields, \texttt{a} and \texttt{b} (tag \texttt{0} encodes as bit \texttt{0}, tag \texttt{1} as bit \texttt{1}), so for $a=b=1$ the input payload is \texttt{11}. Its output has fields \texttt{carry} and \texttt{sum} in canonical alphabetical order, so the output payload is \texttt{10}. The first branch tests \texttt{.a /0} inside field \texttt{if}; projecting \texttt{.then} discards \texttt{if}'s unit value, yet \texttt{if} must still succeed for the branch to apply.
|
|
138
|
+
|
|
139
|
+
The heap-oriented \kvm{} backends used in the comparison in Section~\ref{sec:eval} decode wire inputs into pointer-linked trees and re-encode results at the boundary. A constructor can share a subtree by storing a pointer. Marshaling, temporary tree allocation, and host stack depth can each affect the cost of a run.
|
|
140
|
+
|
|
141
|
+
In \ktvm{}, the input envelope supplies the concrete schema $S_{\mathrm{in}}$ for specialization. Internal channels carry payload bits in wire format between producers and consumers. Figure~\ref{fig:pipeline} summarizes the resulting compilation and execution pipeline. Sections~\ref{sec:schemas} and~\ref{sec:channels} formalize the schema algebra, \BitDeque{} channel state, and \texttt{splice}. Section~\ref{sec:semantics} defines the abstract machine and operational semantics of K combinators. Sections~\ref{sec:poly} and~\ref{sec:opt} cover boundary specialization, kernel fusion, MWTR lookup tables, and target backends. Section~\ref{sec:eval} summarizes the main qualitative performance trade-offs, and Section~\ref{sec:conclusion} discusses related work, open directions, and concludes.
|
|
142
|
+
|
|
143
|
+
\begin{figure}[t]
|
|
144
|
+
\centering
|
|
145
|
+
\begin{tikzpicture}[
|
|
146
|
+
node distance=5.5mm and 6mm,
|
|
147
|
+
box/.style={draw=blue!45!black, fill=blue!4, rounded corners=2pt, align=center,
|
|
148
|
+
font=\footnotesize, minimum height=9mm, inner xsep=4.5pt, inner ysep=2.5pt},
|
|
149
|
+
dec/.style={draw=orange!65!black, fill=orange!6, rounded corners=2pt, align=center,
|
|
150
|
+
font=\footnotesize, minimum height=9mm, inner xsep=4.5pt, inner ysep=2.5pt},
|
|
151
|
+
io/.style={draw=teal!60!black, fill=teal!5, rounded corners=2pt, align=center,
|
|
152
|
+
font=\footnotesize, minimum height=8.5mm, inner xsep=4.5pt, inner ysep=2.5pt},
|
|
153
|
+
err/.style={draw=red!60!black, fill=red!5, rounded corners=2pt, align=center,
|
|
154
|
+
font=\footnotesize, inner xsep=4.5pt, inner ysep=2.5pt},
|
|
155
|
+
arr/.style={-{Stealth[length=2mm]}, semithick, draw=black!75}
|
|
156
|
+
]
|
|
157
|
+
\node[io] (ksrc) {K source\\and libraries};
|
|
158
|
+
\node[box, right=of ksrc] (kir) {Object and\\portable \kirp};
|
|
159
|
+
\node[dec, right=of kir] (spec) {Specialize for\\input schema};
|
|
160
|
+
\node[box, right=of spec] (ktvm) {Concrete \ktvm\\network};
|
|
161
|
+
\node[box, below=of kir] (poly) {\ktvmp{} template};
|
|
162
|
+
\node[io, above=of spec] (env) {\kwire{} input $(S_{\mathrm{in}}, b_{\mathrm{in}})$};
|
|
163
|
+
\node[err, below=of spec] (serr) {\texttt{SchemaError}};
|
|
164
|
+
\node[box, below=of ktvm] (opt) {Optional\\optimization};
|
|
165
|
+
\node[io, below=of opt] (exec) {JS / Wasm / native\\$\to (S_{\mathrm{out}}, b_{\mathrm{out}})$ or $\bot$};
|
|
166
|
+
|
|
167
|
+
\draw[arr] (ksrc) -- (kir);
|
|
168
|
+
\draw[arr] ([yshift=2mm]kir.east) -- ([yshift=2mm]spec.west);
|
|
169
|
+
\draw[arr] (kir) -- (poly);
|
|
170
|
+
\draw[arr] (poly.east) -| ($(kir.east)!0.5!(spec.west)$) |- ([yshift=-2.5mm]spec.west);
|
|
171
|
+
\draw[arr] (env) -- (spec);
|
|
172
|
+
\draw[arr] (spec.south) -- node[right, font=\scriptsize] {mismatch} (serr.north);
|
|
173
|
+
\draw[arr] (spec) -- (ktvm);
|
|
174
|
+
\draw[arr] (ktvm) -- (opt);
|
|
175
|
+
\draw[arr] (opt) -- (exec);
|
|
176
|
+
\end{tikzpicture}
|
|
177
|
+
\caption{End-to-end compilation and execution routes in \ktvm{}. The direct lowerer specializes \kirp{} with $S_{\mathrm{in}}$. The template route emits \ktvmp{} ahead of time and specializes it at the boundary. Specialization reports incompatible input schemas as \texttt{SchemaError}. The runtime reports an undefined relation result as $\bot$.}
|
|
178
|
+
\label{fig:pipeline}
|
|
179
|
+
\end{figure}
|
|
180
|
+
|
|
181
|
+
% ============================================================================
|
|
182
|
+
\section{Schemas, Wire Encoding, and Prefix Derivatives}
|
|
183
|
+
\label{sec:schemas}
|
|
184
|
+
% ============================================================================
|
|
185
|
+
|
|
186
|
+
K patterns denote regular tree languages represented by finite, possibly recursive deterministic graphs~\cite{fraczak2026k,comon2008tree,hosoya2003regular}. In a concrete \ktvm{} module, every closed schema $\sigma$ is a finite graph whose vertices are \emph{product} or \emph{union} nodes with unique outgoing labels sorted strictly in canonical Unicode code-point order.\footnote{The current JavaScript \ktvm{} schema comparator orders UTF-16 code units. It agrees with code-point order on the labels in this paper, but places U+10000 before U+E000. Interoperability requires a common label order.} Documents are finite trees, so the language of a recursive schema is given by its finite derivations. A cycle can have no finite inhabitant. For example, a product whose sole field refers back to itself denotes the empty language.
|
|
187
|
+
|
|
188
|
+
\begin{definition}[Canonical \kwire{} Payload Encoding]
|
|
189
|
+
\label{def:encode}
|
|
190
|
+
Write $\mathrm{bits}_w(i) \in \{0,1\}^w$ for the $w$-bit MSB-first unsigned binary encoding of $i \in \{0,\dots,2^w{-}1\}$ (with $\mathrm{bits}_0(0) = \varepsilon$). For a document $d$ conforming to a closed schema $\sigma$, $\mathrm{encode}(d:\sigma) \in \{0,1\}^*$ is defined inductively:
|
|
191
|
+
\begin{itemize}
|
|
192
|
+
\item \textbf{Unit (empty product)} \lstinline[language=k]|{}|: $\mathrm{encode}(\{\} : \{\}) = \varepsilon$ ($0$ bits).
|
|
193
|
+
\item \textbf{Product} $\{\sigma_0\; f_0, \dots, \sigma_{m-1}\; f_{m-1}\}$ with $f_0 < \dots < f_{m-1}$: concatenation of field encodings without separators,
|
|
194
|
+
$\mathrm{encode}(\{d_0\; f_0, \dots, d_{m-1}\; f_{m-1}\} : \sigma) = \mathrm{encode}(d_0:\sigma_0)\cdots\mathrm{encode}(d_{m-1}:\sigma_{m-1})$.
|
|
195
|
+
\item \textbf{Union (variant)} $\langle \sigma_0\; t_0, \dots, \sigma_{n-1}\; t_{n-1} \rangle$ with $n \ge 1$ and $t_0 < \dots < t_{n-1}$: the tag ordinal $i \in \{0,\dots,n{-}1\}$ encoded in $w = \lceil \log_2 n \rceil$ bits ($0$ bits when $n = 1$), followed immediately by the payload encoding,
|
|
196
|
+
$\mathrm{encode}((d'\; |t_i) : \sigma) = \mathrm{bits}_w(i)\cdot \mathrm{encode}(d' : \sigma_i)$.
|
|
197
|
+
An empty union $\langle \rangle$ admits no documents.
|
|
198
|
+
\end{itemize}
|
|
199
|
+
The payload language of $\sigma$ is $\lang(\sigma) = \{ \mathrm{encode}(d:\sigma) \mid d \text{ conforms to } \sigma \} \subseteq \{0,1\}^*$, which is always prefix-free (no valid encoding is a proper prefix of another).
|
|
200
|
+
\end{definition}
|
|
201
|
+
|
|
202
|
+
Polymorphic \ktvmp{} modules additionally admit open products (\lstinline[language=k]|{ P f, ... }|), open unions (\lstinline[language=k]|< P t, ... >|), unconstrained wildcards \lstinline[language=k]|(...)|, and schema parameters $X$ (written \texttt{\$X} in \ktvm{}'s textual IR). All open forms are resolved to closed schemas at the input boundary (Section~\ref{sec:poly}).
|
|
203
|
+
|
|
204
|
+
\begin{definition}[Wire Equivalence]
|
|
205
|
+
\label{def:wire-equiv}
|
|
206
|
+
Every closed schema $\sigma$ induces a finite rooted deterministic labeled graph $G(\sigma) = (V, E, v_0)$, where each vertex $v \in V$ has a kind $\mathrm{kind}(v) \in \{\mathsf{prod}, \mathsf{union}\}$ and a canonically ordered list of outgoing labeled edges $(l_0, u_0), \dots, (l_{r-1}, u_{r-1})$. Two closed schemas $\sigma_1, \sigma_2$ are \emph{wire-equivalent}, written $\sigma_1 \equiv \sigma_2$, if and only if their rooted labeled graphs are bisimilar (equivalently, their minimal quotients under bisimulation are isomorphic): starting at the roots, related vertices share identical kinds, identical ordered label lists, and related targets under every label.
|
|
207
|
+
\end{definition}
|
|
208
|
+
|
|
209
|
+
Because Definition~\ref{def:encode} depends solely on vertex kinds and canonically ordered edge lists, wire equivalence implies exact bit-for-bit language identity:
|
|
210
|
+
\begin{equation}
|
|
211
|
+
\sigma_1 \equiv \sigma_2 \;\implies\; \lang(\sigma_1) = \lang(\sigma_2) \subseteq \{0,1\}^*.
|
|
212
|
+
\end{equation}
|
|
213
|
+
The converse fails. Two unions of two unit variants both have payload language $\{0,1\}$ even if their tag names differ. At an aligned boundary, \texttt{splice} requires the labeled equivalence of Definition~\ref{def:wire-equiv}, so forwarding preserves the meaning of each bit.
|
|
214
|
+
|
|
215
|
+
\paragraph{Prefix Derivatives as Node Lists.}
|
|
216
|
+
A nonempty prefix code other than $\{\varepsilon\}$ is prime if it cannot be written as a concatenation of two prefix codes that both differ from $\{\varepsilon\}$. Every nonempty prefix code factors uniquely into an ordered sequence of primes. The empty factor sequence represents $\{\varepsilon\}$. For a simple language ($s$-language), recognized by a one-state deterministic pushdown automaton, the nonempty left quotients are generated by a finite set of such primes~\cite{fraczak2004slang,bastien2006pnf}. Thus there is a finite set $\mathcal{P}$ such that, for every prefix $w$ with a valid completion,
|
|
217
|
+
\begin{equation}
|
|
218
|
+
w^{-1}\lang(\sigma) = P_1\cdots P_k,\qquad P_i\in\mathcal{P},
|
|
219
|
+
\end{equation}
|
|
220
|
+
and this ordered sequence is unique. This gives a canonical semantic representation of the remaining input as a stack over a finite alphabet, even when the set of residual languages is infinite.
|
|
221
|
+
|
|
222
|
+
The runtime represents this residual using nodes of the original schema graph. Write $\lang([v_1,\dots,v_k])=\lang(v_1)\cdots\lang(v_k)$ and $\lang([])=\{\varepsilon\}$. At a tag or sub-value boundary, $w^{-1}\lang(\sigma)=\lang([v_1,\dots,v_k])$, where the list records the sub-values still to be read in wire order. Factoring the language of each pending schema node and concatenating the factors recovers the unique prime sequence. A single schema node may account for several prime factors. A scanner paused inside a multi-bit tag must also remember the partial ordinal. A prefix that has no valid completion has empty derivative.
|
|
223
|
+
|
|
224
|
+
For example, a four-tag union with unit payloads has language $\{00,01,10,11\}=\{0,1\}\{0,1\}$. Its prime factorization has two factors even though the schema presents a single two-bit tag. A product of two binary unit unions has the same factorization and a different labeled layout. The JavaScript schema library implements a separate bit-language key for closed schemas and residual node lists. It erases labels, expands ordinals into binary tries, and applies bounded right-suffix factoring with Moore minimization. Splice validation uses labeled graph equivalence from Definition~\ref{def:wire-equiv}. The scanners traverse schema nodes at runtime.
|
|
225
|
+
|
|
226
|
+
\begin{definition}[Schema Prefix Derivative on Node Lists]
|
|
227
|
+
\label{def:deriv}
|
|
228
|
+
Over node lists $\vec{v} \in V^*$ of $G(\sigma)$, consuming aligned prefixes advances the residual list by head rewriting:
|
|
229
|
+
\begin{align*}
|
|
230
|
+
[v_{\{\}},\, \vec{u}] &\;\xrightarrow{\;\varepsilon\;}\; \vec{u} && \text{(unit removal)}, \\
|
|
231
|
+
[v_{\{u_0\,f_0, \dots, u_{m-1}\,f_{m-1}\}},\, \vec{u}] &\;\xrightarrow{\;\varepsilon\;}\; [u_0, \dots, u_{m-1},\, \vec{u}] && \text{(product expansion)}, \\
|
|
232
|
+
[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,\text{ tag step}), \\
|
|
233
|
+
[v_1,\, \vec{u}] &\;\xrightarrow{\;d \in \lang(v_1)\;}\; \vec{u} && \text{(complete sub-value step)}.
|
|
234
|
+
\end{align*}
|
|
235
|
+
Reaching $[]$ completes the encoding with residual language $\{\varepsilon\}$. In particular, emitting a union tag $|t_i$ reduces $[v_{\langle\dots\rangle}]$ to $[u_i]$, and emitting fields $f_0 \cdots f_{m-2}$ of an $m$-field product reduces $[v_{\{u_0\dots u_{m-1}\}}]$ to $[u_{m-1}]$.
|
|
236
|
+
\end{definition}
|
|
237
|
+
|
|
238
|
+
% ============================================================================
|
|
239
|
+
\section{Channel Calculus: \BitDeque{}, Dual Schemas, and \texttt{splice}}
|
|
240
|
+
\label{sec:channels}
|
|
241
|
+
% ============================================================================
|
|
242
|
+
|
|
243
|
+
As in Kahn process networks~\cite{kahn1974semantics}, every data link in \ktvm{} connects a single producer to a single consumer (SPSC). Each channel carries a bit-addressable double-ended queue (\BitDeque) whose abstract state is an 8-tuple:
|
|
244
|
+
\begin{equation}
|
|
245
|
+
\label{eq:chan}
|
|
246
|
+
c = \bigl\langle \mathrm{buf},\; \mathrm{st},\; \sprod,\; \scons,\; \mathrm{aligned},\; \mathrm{prod},\; \mathrm{cons},\; \mathrm{scope} \bigr\rangle,
|
|
247
|
+
\end{equation}
|
|
248
|
+
whose components have the following domains and runtime roles:
|
|
249
|
+
\begin{itemize}
|
|
250
|
+
\item $\mathrm{buf} \in \{0,1\}^*$: the unread bit sequence. Producers append at the back (\texttt{push\_bits}), consumers inspect or remove from the front (\texttt{peek\_bits}, \texttt{shift\_bits}), and prefix constructors, tail-splicers, and speculative rollbacks prepend at the front (\texttt{unshift\_bits}, \texttt{unshift\_deque}). Merging two buffers appends or prepends via \texttt{push\_deque} or \texttt{unshift\_deque}.
|
|
251
|
+
\item $\mathrm{st} \in \{\stOpen, \stClosed, \stFailed\}$: strictly monotone lifecycle status ($\stOpen \to \stClosed$ on successful completion, or $\stOpen \to \stFailed$ on K partial failure $\bot$). Once settled, $\mathrm{st}$ is immutable and $\mathrm{prod} = \mathsf{NONE}$; a $\stClosed$ channel may still hold unread bits in $\mathrm{buf}$.
|
|
252
|
+
\item $\sprod, \scons \in \mathcal{S}_{\mathrm{closed}}$: closed schema states (each a state in the module's closed pattern graphs). $\scons$ is the full schema expected by the consumer starting at its last value boundary; $\sprod$ is the suffix schema still owed by the producer at the back of $\mathrm{buf}$ at producer value boundaries. Initially $\sprod = \scons$.
|
|
253
|
+
\item $\mathrm{aligned} \in \mathbb{B} = \{\mathrm{true}, \mathrm{false}\}$: consumer boundary-alignment flag. At a splice site, $\mathrm{true}$ certifies that the consumer is at the start of a $\scons$ value. The unread buffer can still be empty or contain only a prefix. Shifting raw bits mid-value (e.g., during a schema scan or kernel loop) sets $\mathrm{aligned} := \mathrm{false}$; advancing $\scons$ along a prefix derivative to a clean sub-value boundary (e.g., \texttt{match /tag} or final-field \texttt{demux}) restores $\mathrm{aligned} := \mathrm{true}$.
|
|
254
|
+
\item $\mathrm{prod} \in \mathrm{NodeId} \cup \{\mathsf{EXT\_IN}, \mathsf{NONE}\}$: unique owning producer handle---either an active transducer node ID in the machine's node map $N$, the external wire input $\mathsf{EXT\_IN}$, or $\mathsf{NONE}$ once closed, failed, or retired. The pull scheduler follows $\mathrm{prod}$ to drive upstream work, and \texttt{splice} updates $\mathrm{prod}$ to rewire producers directly to downstream buffers.
|
|
255
|
+
\item $\mathrm{cons} \in \mathrm{NodeId} \cup \{\mathsf{EXT\_OUT}, \mathsf{NONE}\}$: unique owning consumer handle---either an active transducer node ID in $N$, the external wire output $\mathsf{EXT\_OUT}$, or $\mathsf{NONE}$ when detached or retired. Enforces SPSC linearity, enables symmetric \texttt{mux}/\texttt{demux} fusion, and tracks temporary \texttt{tap} interposition during speculation.
|
|
256
|
+
\item $\mathrm{scope} \in \mathrm{ScopeId} = \mathbb{N}$: identifier of the enclosing speculation scope in the machine's rooted scope tree $S$ (Section~\ref{sec:semantics}), where $0$ is the root scope. Every non-final speculative choice branch allocates a child scope; destroying a scope reclaims all channels, nodes, and barriers in its subtree. Ordinary fusion is confined to a scope. Commit explicitly transfers the staged outputs to the parent (Section~\ref{sec:spec}).
|
|
257
|
+
\end{itemize}
|
|
258
|
+
|
|
259
|
+
\paragraph{Why Two Schemas?}
|
|
260
|
+
Consider wrapping a \lstinline[language=k]|bits[]| value with tag \lstinline[language=k]!|+! into \mbox{\lstinline[language=k]|int[] = < bits[] +, bits[] - >|}. Once the constructor emits the sign bit \texttt{0}, the consumer still expects a complete \texttt{int[]} starting at the front of the buffer, whereas the producer now owes only the \texttt{bits[]} suffix. Separating $\sprod(c)$ from $\scons(c)$ makes this asymmetric state explicit (Figure~\ref{fig:splice}).
|
|
261
|
+
|
|
262
|
+
\begin{figure}[t]
|
|
263
|
+
\centering
|
|
264
|
+
\begin{tikzpicture}[
|
|
265
|
+
font=\footnotesize,
|
|
266
|
+
node distance=5mm,
|
|
267
|
+
ch/.style={draw=blue!50!black, fill=blue!4, rounded corners=2pt, inner sep=4pt, align=center},
|
|
268
|
+
op/.style={draw=orange!65!black, fill=orange!6, rounded corners=2pt, inner sep=4pt, align=center},
|
|
269
|
+
arr/.style={-{Stealth[length=2mm]}, semithick, draw=black!75}
|
|
270
|
+
]
|
|
271
|
+
\node[ch] (src) {\textbf{Channel $\mathit{src}$} (\texttt{aligned=true})\\
|
|
272
|
+
$\sprod=\texttt{bits[]}$, $\scons=\texttt{bits[]}$\\
|
|
273
|
+
\texttt{buf}: \texttt{00\,01\,00\dots} (buffered prefix)};
|
|
274
|
+
\node[op, right=6mm of src] (sp) {\texttt{splice}\\$\scons(\mathit{src}) \equiv \sprod(\mathit{dst})$};
|
|
275
|
+
\node[ch, right=6mm of sp] (dst) {\textbf{Channel $\mathit{dst}$} (after \texttt{wrap |+})\\
|
|
276
|
+
$\sprod=\texttt{bits[]}$, $\scons=\texttt{int[]}$\\
|
|
277
|
+
\texttt{buf}: \texttt{0} (1-bit tag prefix)};
|
|
278
|
+
|
|
279
|
+
\draw[arr] (src) -- (sp);
|
|
280
|
+
\draw[arr] (sp) -- (dst);
|
|
281
|
+
|
|
282
|
+
\node[ch, draw=teal!60!black, fill=teal!5, below=6mm of sp, minimum width=11.4cm] (res)
|
|
283
|
+
{\textbf{Resulting $\mathit{dst}$} (prefix prepended, source buffer adopted)\\
|
|
284
|
+
$\sprod=\sprod(\mathit{src})$, $\scons=\texttt{int[]}$,\quad
|
|
285
|
+
\texttt{buf}: \texttt{\textbf{0}\,|\,00\,01\,00\dots}};
|
|
286
|
+
|
|
287
|
+
\draw[arr, dashed] (sp.south) -- (res.north);
|
|
288
|
+
\end{tikzpicture}
|
|
289
|
+
\caption{Wrapping a bit sequence as a positive integer. The destination already holds the one-bit sign; \texttt{splice} prepends it to the source buffer and transfers ownership to the destination. The vertical bar marks the join and occupies no wire bit.}
|
|
290
|
+
\label{fig:splice}
|
|
291
|
+
\end{figure}
|
|
292
|
+
|
|
293
|
+
\begin{invariant}[Dual-Schema Suffix Invariant $\mathcal{I}(c)$]
|
|
294
|
+
\label{inv:dual}
|
|
295
|
+
Write $h_c \in \{0,1\}^*$ for the ghost history of bits consumed since the last aligned value boundary, excluding any bits restored by rollback (so $c.\mathrm{aligned} = \mathrm{true} \implies h_c = \varepsilon$), and $b_c = c.\mathrm{buf}$ for the unread buffer. Let $R_c \subseteq \{0,1\}^*$ be the residual language of suffixes still owed by the producer. By Section~\ref{sec:schemas}, at any aligned producer position $R_c = \lang(\vec{p}_c) = \lang(p_1)\cdots\lang(p_k)$ for a finite list of schema nodes $\vec{p}_c = [p_1, \dots, p_k] \in V^*$ (the remaining sub-patterns to be emitted, maintained by the producer's control or scanner stack); at a boundary where the producer owes just one value, $\vec{p}_c$ can be represented by the singleton list $[\sprod(c)]$, so $R_c = \lang(\sprod(c))$. Every well-formed open or closed channel $c$ satisfies
|
|
296
|
+
\begin{equation}
|
|
297
|
+
\label{eq:inv}
|
|
298
|
+
\mathcal{I}(c) \;:\;\;
|
|
299
|
+
\begin{cases}
|
|
300
|
+
\forall w \in R_c,\quad h_c\,b_c\,w \in \lang(\scons(c)) & \text{if } c.\mathrm{st} = \stOpen, \\
|
|
301
|
+
h_c\,b_c \in \lang(\scons(c)) & \text{if } c.\mathrm{st} = \stClosed.
|
|
302
|
+
\end{cases}
|
|
303
|
+
\end{equation}
|
|
304
|
+
\end{invariant}
|
|
305
|
+
|
|
306
|
+
\paragraph{The Unified \texttt{splice} Primitive.}
|
|
307
|
+
Identity forwarding, matched variant stripping, prefix wrapping, and final-field multiplexing all reduce to a single primitive $\texttt{splice}(s \to d)$ from source channel $s$ to an open destination channel $d$.
|
|
308
|
+
|
|
309
|
+
For an open or closed source, the preconditions for transferring bits are (i) $s.\mathrm{aligned} = \mathrm{true}$ (so $h_s = \varepsilon$, preventing a truncated tail from being spliced into $d$); (ii) $\scons(s) \equiv \sprod(d)$ and $R_d = \lang(\sprod(d))$ (destination is at a producer value boundary); and (iii) compatible scopes---either $s.\mathrm{scope} = d.\mathrm{scope}$, or $s$ is a staging output being committed from a speculative child scope into its parent scope's $d$ immediately before the child scope is destroyed.
|
|
310
|
+
|
|
311
|
+
\emph{Operational effect.} A failed source immediately fails $d$ and is retired, regardless of alignment. An open or closed source transfers its bits as follows.
|
|
312
|
+
\begin{enumerate}
|
|
313
|
+
\item \textbf{Minimal-copy buffer join} forming $b_d\,b_s$: if $|b_d| = 0$, $d$ adopts $s$'s buffer in $O(1)$; if $|b_s| = 0$, $b_d$ is kept; otherwise, if $|b_d| \le |b_s|$ we prepend $b_d$ onto $s$'s buffer (\texttt{unshift\_deque}) and adopt it, else we append $b_s$ onto $d$ (\texttt{push\_deque}). The abstract join moves $\min(|b_d|,|b_s|)$ payload bits. A capacity increase can also move the existing contents. The Wasm and native implementations transfer an external buffer by pointer and copy a fixed 16 bytes when adopting an inline buffer. In tail-recursive list construction, prepending a small tag and head onto a long accumulated tail avoids repeatedly copying the tail.
|
|
314
|
+
\item \textbf{Ownership and suffix transfer.} The destination keeps its consumer, $\scons$, alignment, and history $h_d$. It inherits the source's status, $\sprod$, and producer handle. For an open source, the upstream producer rebinds its output to $d$ and $R_d \leftarrow R_s$. A closed source has no producer and owes no further bits. Channel $s$ is retired.
|
|
315
|
+
\end{enumerate}
|
|
316
|
+
|
|
317
|
+
\begin{theorem}[Preservation of $\mathcal{I}$ under \texttt{splice}]
|
|
318
|
+
\label{thm:splice}
|
|
319
|
+
Suppose $s$ and $d$ satisfy the \texttt{splice} preconditions above together with $\mathcal{I}(s)$ and $\mathcal{I}(d)$. If $s.\mathrm{st} \in \{\stOpen, \stClosed\}$, then $\mathcal{I}(d)$ holds after $\texttt{splice}(s \to d)$.
|
|
320
|
+
\end{theorem}
|
|
321
|
+
\begin{proof}
|
|
322
|
+
Since $s.\mathrm{aligned} = \mathrm{true}$, we have $h_s = \varepsilon$. If $s.\mathrm{st} = \stOpen$, let $w \in R_s$; then $\mathcal{I}(s)$ yields $b_s w \in \lang(\scons(s)) = \lang(\sprod(d)) = R_d$. Substituting $b_s w$ into $\mathcal{I}(d)$ yields $h_d (b_d b_s) w \in \lang(\scons(d))$, establishing the open-channel condition for the joined buffer and inherited obligation $R_s$. If $s.\mathrm{st} = \stClosed$, then $\mathcal{I}(s)$ gives $b_s \in R_d$, and substituting $b_s$ into $\mathcal{I}(d)$ gives $h_d (b_d b_s) \in \lang(\scons(d))$, independent of whether $d.\mathrm{aligned}$ is true or false.
|
|
323
|
+
\end{proof}
|
|
324
|
+
|
|
325
|
+
% ============================================================================
|
|
326
|
+
\section{Operational Semantics of K in \ktvm{}}
|
|
327
|
+
\label{sec:semantics}
|
|
328
|
+
% ============================================================================
|
|
329
|
+
|
|
330
|
+
\subsection{Abstract Machine State, Schema DPDA, and Pull Scheduling}
|
|
331
|
+
|
|
332
|
+
A running \ktvm{} instance maintains the finite configuration
|
|
333
|
+
\begin{equation}
|
|
334
|
+
\label{eq:machine}
|
|
335
|
+
\Sigma \;=\; \bigl\langle N,\; C,\; B,\; S,\; \mathrm{dstack},\; \mathcal{M},\; \mathrm{root\_in},\; \mathrm{root\_out} \bigr\rangle,
|
|
336
|
+
\end{equation}
|
|
337
|
+
whose components are defined as follows:
|
|
338
|
+
\begin{itemize}
|
|
339
|
+
\item $\mathcal{M}$: the immutable concrete module containing closed schema graphs, network procedures (\texttt{proc}), compiled state machines (\texttt{kernel}), and static lookup tables.
|
|
340
|
+
\item $N : \mathrm{NodeId} \rightharpoonup \mathrm{NodeState}$: finite map of active transducer nodes. Each node state records its kind (\texttt{splice}, \texttt{coerce}, \texttt{const\_unit}, \texttt{wrap}, \texttt{match}, \texttt{mux}, \texttt{demux}, \texttt{tee}, \texttt{drain}, \texttt{gate}, \texttt{switch}, \texttt{spec}, \texttt{tap}, \texttt{spawn}, \texttt{kernel}), its bound input/output channel IDs, its local control or scanner state, its enclosing $\mathrm{scope} \in \mathrm{ScopeId}$, and its lifecycle status $\in \{\mathsf{ACTIVE}, \mathsf{RETIRED}\}$.
|
|
341
|
+
\item $C : \mathrm{ChanId} \rightharpoonup \mathrm{ChanState}$: finite map of live channels (the 8-tuples of equation~\eqref{eq:chan}).
|
|
342
|
+
\item $B : \mathrm{BarrierId} \rightharpoonup \langle D \subseteq \mathrm{NodeId},\; \mathrm{st} \in \{\mathsf{PENDING}, \mathsf{PASSED}, \mathsf{FAILED}\},\; \mathrm{scope} \in \mathrm{ScopeId} \rangle$: partiality barriers with a set $D$ of pending drains. A gate can demand a member of $D$ directly. Successful drains leave $D$, and the barrier passes once $D$ is empty. A failed drain fails the barrier.
|
|
343
|
+
\item $S$: rooted finite tree of active speculation scopes (root $0$), mapping each $\mathrm{ScopeId}$ to its parent scope and the sets of node, channel, and barrier IDs owned by that scope.
|
|
344
|
+
\item $\mathrm{dstack}$: an explicit stack of tagged channel and node frames. A channel frame drives its producer. A node frame drives a pending drain for a gate. The scheduler iterates over this stack.
|
|
345
|
+
\item $\mathrm{root\_in}, \mathrm{root\_out} \in \mathrm{ChanId}$: root wire-boundary channels in scope~$0$ carrying the input and output payloads.
|
|
346
|
+
\end{itemize}
|
|
347
|
+
|
|
348
|
+
\paragraph{Schema DPDA.}
|
|
349
|
+
Because \kwire{} omits internal length prefixes, locating the end of a variable-width value requires traversing $G(\sigma)$ with a \emph{one-state deterministic pushdown automaton} (DPDA)~\cite{fraczak2004slang} whose explicit stack $[v_1, \dots, v_k] \in V^*$ directly executes Definition~\ref{def:deriv}: encountering unit $\{\}$ pops it; expanding a product pops it and pushes its field targets in reverse canonical order so $u_0$ sits on top; an empty union fails immediately. At a union with $n \ge 1$ tags the scanner reads $\lceil \log_2 n \rceil$ bits (failing if the ordinal is $\ge n$) and replaces the top with $u_i$. Here a whole-tag read abbreviates a finite tree of bit decisions. The empty stack $[]$ marks the exact end of the value. The same mechanism implements \texttt{dpda\_skip} (discarding a value), \texttt{dpda\_copy} (forwarding bits verbatim), and \texttt{dpda\_coerce} (rewriting bits between compatible schemas, e.g., widening a union).
|
|
350
|
+
|
|
351
|
+
\paragraph{Sequencing Tokens (\texttt{after}).}
|
|
352
|
+
To bound live network size across independent sibling subcomputations (such as divide-and-conquer recursive calls or accumulator loops), a procedure may bind an \texttt{after} token $t$ to the output channel set of an earlier \texttt{spawn}. A later \texttt{spawn} annotated with \texttt{after}~$t$ may not expand until every channel in $t$ has settled ($\stClosed$ or $\stFailed$).
|
|
353
|
+
|
|
354
|
+
\paragraph{Demand-Driven Pull Loop.}
|
|
355
|
+
For each root output, the scheduler pushes a channel frame and drives the stack until the output settles. If a yield empties the stack while the root is open, it pushes the root again.
|
|
356
|
+
\begin{enumerate}
|
|
357
|
+
\item Inspect the top frame. Pop a settled channel or a retired node. Otherwise let $u$ be the channel's producer or the node named by the frame.
|
|
358
|
+
\item If $u$ is an unexpanded \texttt{spawn} carrying an unsettled token $\texttt{after}(t)$, push the first still-$\stOpen$ channel of $t$ onto $\mathrm{dstack}$ and continue, forcing $t$ to settle before $u$ expands.
|
|
359
|
+
\item Step $u$. A request for input pushes the corresponding channel frame. A gate waiting on a drain pushes a node frame. A cooperative yield pops the current frame. When an internal channel becomes readable or settles, its waiting consumer can resume.
|
|
360
|
+
\item Once $\mathrm{root\_out}.\mathrm{st} = \stClosed$, frame $\mathrm{root\_out}.\mathrm{buf}$ with the derived schema $S_{\mathrm{out}}$; if $\mathrm{root\_out}.\mathrm{st} = \stFailed$, terminate with K's ordinary partial failure ($\bot$).
|
|
361
|
+
\end{enumerate}
|
|
362
|
+
|
|
363
|
+
\subsection{Compositional Translation of K Combinators}
|
|
364
|
+
|
|
365
|
+
For a specialized K relation $e$ with closed boundary schemas $S_{\mathrm{in}} \to S_{\mathrm{out}}$, lowering produces an acyclic network subgraph $\sem{e}(c_{\mathrm{in}} \to c_{\mathrm{out}})$ wiring $c_{\mathrm{in}} : S_{\mathrm{in}}$ to $c_{\mathrm{out}} : S_{\mathrm{out}}$. Table~\ref{tab:translation} summarizes the operational semantics of every K construct.
|
|
366
|
+
|
|
367
|
+
\begin{table}[t]
|
|
368
|
+
\centering
|
|
369
|
+
\caption{Operational semantics of core K forms in a concrete \ktvm{} network.}
|
|
370
|
+
\label{tab:translation}
|
|
371
|
+
\footnotesize
|
|
372
|
+
\begin{tabularx}{\textwidth}{@{} >{\ttfamily}l l X @{}}
|
|
373
|
+
\toprule
|
|
374
|
+
\normalfont\textbf{K Form} & \textbf{\ktvm{} Construct} & \textbf{Small-Step Operational Semantics} \\
|
|
375
|
+
\midrule
|
|
376
|
+
() & \texttt{splice} & Transfer input buffer and producer handle directly to the output channel. \\
|
|
377
|
+
\{\} & \texttt{drain}, \texttt{barrier}, \texttt{gate} & Drain the input via DPDA until $\stClosed$; on barrier pass release a $0$-bit unit (\texttt{const\_unit}), otherwise propagate $\stFailed$. \\
|
|
378
|
+
<> & empty \texttt{spec} & Immediately mark output $\stFailed$ and retire. \\
|
|
379
|
+
|tag & \texttt{wrap} & Emit tag ordinal of \texttt{tag}, narrow $\sprod(c_{\mathrm{out}}) := \sigma_{\mathrm{tag}}$, then \texttt{splice} (or \texttt{coerce} if schemas differ). \\
|
|
380
|
+
/tag & \texttt{match} & Pull tag ordinal; mismatch or invalid ordinal fails $c_{\mathrm{out}}$. On match, shift ordinal, set $\scons(c_{\mathrm{in}}) := \sigma_{\mathrm{tag}}$ and $\mathrm{aligned}:=\mathrm{true}$, then \texttt{splice} (or \texttt{coerce}). \\
|
|
381
|
+
.field & \texttt{demux}, \texttt{gate} & Scan preceding fields via DPDA and tail-splice the last field; a matching same-scope upstream \texttt{mux} fuses directly without scanning. Gate the selected field on draining all unused siblings. \\
|
|
382
|
+
(f g) & \texttt{chan} & Allocate fresh intermediate channel $\%t : S_{\mathrm{mid}}$ wiring $\sem{f}(c_{\mathrm{in}} \to \%t)$ and $\sem{g}(\%t \to c_{\mathrm{out}})$. \\
|
|
383
|
+
\{f$_1$ l$_1$, \dots\} & \texttt{tee}, \texttt{mux} & Broadcast $c_{\mathrm{in}}$ via \texttt{tee} to each live branch (or drain if constant); \texttt{mux} streams fields $0\dots m{-}2$ in canonical label order and tail-splices field $m{-}1$, failing if any branch fails. \\
|
|
384
|
+
<f$_1$, \dots, f$_k$> & \texttt{switch} or \texttt{spec} & Use non-destructive tag peek \texttt{switch} when leading tags distinguish branches; otherwise use scoped speculative replay \texttt{spec} (Section~\ref{sec:spec}). \\
|
|
385
|
+
name & \texttt{spawn} [\texttt{after}] & Allocate a lazy stub expanded in-place on first pull, respecting any \texttt{after} token. \\
|
|
386
|
+
?P & \texttt{splice}, \texttt{coerce}, or failure & An implied filter forwards its input. A disjoint filter fails. For partial overlap, direct lowering emits a checked \texttt{coerce} that can fail on the actual tag. The template instruction \texttt{guard} is resolved during specialization. \\
|
|
387
|
+
\bottomrule
|
|
388
|
+
\end{tabularx}
|
|
389
|
+
\end{table}
|
|
390
|
+
|
|
391
|
+
\paragraph{Strict Partiality via \texttt{drain}/\texttt{barrier}/\texttt{gate}.}
|
|
392
|
+
In K, \lstinline[language=k]|(f {})| returns unit only if $f$ succeeds, and projecting \texttt{.a} from \lstinline[language=k]|{ f a, g b }| requires both $f$ and $g$ to succeed even though \texttt{b} is discarded. Because \ktvm{} is pull-driven, simply dropping an unread channel would turn undefined relations into defined ones. Instead, every discarded channel attaches to a \texttt{drain} node that runs \texttt{dpda\_skip} until end-of-value \emph{and} verifies that the channel actually reaches $\stClosed$ (crucial even for $0$-bit units, whose producer may still fail). Only when all drains registered on barrier $b$ succeed does $\texttt{gate}\;b, c_{\mathrm{val}} \to c_{\mathrm{out}}$ execute $\texttt{splice}(c_{\mathrm{val}} \to c_{\mathrm{out}})$; any failed drain immediately fails $c_{\mathrm{out}}$.
|
|
393
|
+
|
|
394
|
+
\subsection{Speculative Choice (\texttt{spec})}
|
|
395
|
+
\label{sec:spec}
|
|
396
|
+
|
|
397
|
+
When concurrent choice \lstinline[language=k]|<f1, ..., fk>| cannot be dispatched deterministically by peeking leading tags, \ktvm{} lowers it to a \texttt{spec} node wired to parent inputs $(i_0, \dots, i_{m-1})$ and parent outputs $(o_0, \dots, o_{r-1})$ in enclosing scope $s_{\mathrm{par}}$. Branches $B_0, \dots, B_{k-1}$ are tried strictly in source order:
|
|
398
|
+
\begin{itemize}
|
|
399
|
+
\item \textbf{Empty choice ($k = 0$):} fail all $o_l$ immediately and retire.
|
|
400
|
+
\item \textbf{Last branch ($j = k - 1$):} instantiate $B_{k-1}$ directly in $s_{\mathrm{par}}$ wired to the parent channels and retire \texttt{spec}---allocating no child scope, taps, or replay buffers.
|
|
401
|
+
\item \textbf{Speculative branch ($j < k - 1$):} allocate a fresh child scope $s_j$ under $s_{\mathrm{par}}$ in $S$. For each parent input $i_p$, attach a \texttt{tap} node with state $\langle \mathrm{parentCh}=i_p,\; \mathrm{childCh}=i'_p,\; \mathrm{replay}_p \in \{0,1\}^*,\; \mathrm{sawUpstreamFailure} \in \mathbb{B} \rangle$ (temporarily setting $i_p.\mathrm{cons} := \mathrm{tap}_p$); each tap shifts bits from $i_p$, appends them to both $\mathrm{replay}_p$ and $i'_p$, and sets $\mathrm{sawUpstreamFailure}$ if $i_p$ fails. Allocate staging outputs $o'_0, \dots, o'_{r-1}$ in $s_j$ and drive them until one of three mutually exclusive outcomes occurs:
|
|
402
|
+
\begin{enumerate}
|
|
403
|
+
\item \emph{Commit:} all $o'_l$ reach $\stClosed$. Return any unread bits remaining in each $i'_p$ back to the front of $i_p$, discard all $\mathrm{replay}_p$, detach taps, move each $o'_l$ out of $s_j$'s channel set and execute $\texttt{splice}(o'_l \to o_l)$, destroy $s_j$, and retire \texttt{spec}.
|
|
404
|
+
\item \emph{Upstream failure:} some $o'_l$ reaches $\stFailed$ \emph{and} some parent input $i_p$ failed (or $\mathrm{sawUpstreamFailure}$ is set). Destroy $s_j$, fail all $o_l$, and retire \texttt{spec} \emph{without} trying $B_{j+1}$ (preserving K's composition law: in \lstinline[language=k]|(f <g, h>)|, failure of $f$ must never fall through to $h$).
|
|
405
|
+
\item \emph{Local branch failure:} some $o'_l$ reaches $\stFailed$ while no parent input failed. Destroy $s_j$ (reclaiming all child nodes, channels, and barriers in its subtree), restore every parent input bit-for-bit via $\texttt{unshift\_deque}(i_p, \mathrm{replay}_p)$ with $i_p.\mathrm{cons}$ restored to \texttt{spec}, and advance to $B_{j+1}$.
|
|
406
|
+
\end{enumerate}
|
|
407
|
+
\end{itemize}
|
|
408
|
+
If $B_j$ diverges without settling its staging outputs, \texttt{spec} waits indefinitely, preserving left-to-right choice priority even if $B_{j+1}$ would succeed.
|
|
409
|
+
|
|
410
|
+
\subsection{Static Validation and Soundness Boundaries}
|
|
411
|
+
|
|
412
|
+
By default, execution and backend code generation invoke a validator that checks five structural properties on concrete modules: (1) closed schemas with unique, canonically ordered labels and no cycles consisting solely of aliases; (2) per-branch SPSC channel ownership (each local channel has a single writer and a single reader); (3) local DAG acyclicity within each procedure over channel edges, barriers, and \texttt{after} dependencies; (4) compatible schema annotations for network \texttt{splice} instructions; and (5) kernel control-flow integrity (valid port, register, stack, and block-target references) plus bounded lookup-table checking (Section~\ref{sec:opt}).
|
|
413
|
+
|
|
414
|
+
The JavaScript interpreter also checks alignment and schema compatibility when splicing. Compiled runtimes rely on lowering to satisfy these preconditions. The local acyclicity check concerns the declared dependencies of a procedure. Recursive \texttt{spawn} can still generate an unbounded demand chain. Theorem~\ref{thm:splice} proves payload-invariant preservation for \texttt{splice}; end-to-end equivalence of the full compiler and optimization pipeline against K's reference semantics is checked empirically by the K conformance suite rather than mechanized as a whole-compiler proof.
|
|
415
|
+
|
|
416
|
+
% ============================================================================
|
|
417
|
+
\section{Boundary Specialization (\ktvmp{} \texorpdfstring{$\to$}{->} \ktvm)}
|
|
418
|
+
\label{sec:poly}
|
|
419
|
+
% ============================================================================
|
|
420
|
+
|
|
421
|
+
K supports parametric patterns such as \lstinline[language=k]|list[X] = < {} nil, { X car, L cdr } cons > = L| and open structural contracts such as \lstinline[language=k]|{ X a, ... }|~\cite{fraczak2026k}. A list-reversing relation can be typed independently of the element schema \texttt{X}, yet a packed-wire scanner must know the concrete element schema to locate where each serialized element ends.
|
|
422
|
+
|
|
423
|
+
\ktvm{} therefore separates polymorphic representation from closed wire execution via two compilation routes (Figure~\ref{fig:pipeline}): a \emph{direct lowerer} that specializes portable \kirp{} together with a concrete input schema $S_{\mathrm{in}}$ on the fly, and a \emph{template path} that emits a polymorphic \ktvmp{} module (retaining open schemas, schema parameters \texttt{\$X}, and symbolic \texttt{project}/\texttt{guard} instructions) and later specializes it via
|
|
424
|
+
\begin{equation}
|
|
425
|
+
\mathrm{specialize}\bigl(M_P,\; @\mathrm{entry},\; S_{\mathrm{in}}\bigr) \;\longrightarrow\; \mathsf{Ok}\bigl(M,\; @\mathrm{entry}',\; S_{\mathrm{out}}\bigr) \;\mid\; \mathsf{SchemaError}(\mathrm{reason}).
|
|
426
|
+
\end{equation}
|
|
427
|
+
The two routes share the following tasks.
|
|
428
|
+
\begin{enumerate}
|
|
429
|
+
\item \textbf{Input contract checking and parameter binding:} intersect $S_{\mathrm{in}}$ with the entry's input pattern graph. Open products admit unlisted fields, and repeated occurrences of a parameter $X$ enforce wire equivalence ($\equiv$). A structural contradiction raises \texttt{SchemaError} before evaluation, distinct from runtime partial failure ($\stFailed$).
|
|
430
|
+
\item \textbf{Memoized output schema derivation.} Direct lowering specializes a relation for its input and, when supplied, its expected output. Template specialization reuses a procedure instance for the same parameter bindings and input schemas. A recursive call with the same key can refer to the instance under construction. Execution requires closed output schemas.
|
|
431
|
+
\item \textbf{Access-profile port splitting:} direct lowering can split an accessed product into field channels, while a template's symbolic field projection specializes to a concrete demultiplexer. Conversely, when a polymorphic parameter refines to a composite schema (such as \texttt{int[]}) that the procedure never inspects, keep it as a \emph{single opaque \BitDeque{}}, avoiding unnecessary \texttt{demux}/\texttt{mux} nodes while still compiling its DPDA copier to a closed automaton.
|
|
432
|
+
\item \textbf{Wire-operation resolution:} resolve every union tag to its concrete ordinal and width $\lceil \log_2 n \rceil$, prune unreachable switch arms, erase satisfied \texttt{guard}s to \texttt{splice}, and insert \texttt{coerce} transducers wherever compatible schemas have different wire layouts.
|
|
433
|
+
\end{enumerate}
|
|
434
|
+
Both routes can cache results by entry and minimized input schema. The direct lowerer keeps a cache per input object or \kirp{} instance. The template cache uses the serialized module and supports a list of input-port schemas.
|
|
435
|
+
|
|
436
|
+
\paragraph{Worked Example: Polymorphic List Reversal.}
|
|
437
|
+
In K's standard library, \texttt{reverse} delegates to a two-argument tail-recursive helper \texttt{\_reverse} over the unprocessed list \texttt{xs} and an initially empty accumulator \texttt{acc}. Listing~\ref{lst:reverse} shows a self-contained two-port implementation of the helper at \texttt{list[int[]]}. Supplying \texttt{nil} on the accumulator port computes ordinary reversal. The declarations \texttt{unit}, \texttt{product}, and \texttt{union} give the concrete wire schemas. On \texttt{cons}, the machine demultiplexes the cell, copies the opaque \texttt{\$int} element verbatim, reading its tag bits only to locate its end, prepends the new cell to \texttt{\%acc}, and tail-spawns on \texttt{\%cdr}. On \texttt{nil}, it drains the empty payload and releases \texttt{\%acc}.
|
|
438
|
+
|
|
439
|
+
\begin{lstlisting}[language=ktvm, float=htbp, caption={Self-contained concrete \ktvm{} textual IR for specialized list reversal (\texttt{list[int[]]}). Opaque \texttt{\$int} heads travel on a single channel while \texttt{cons}/\texttt{nil} resolve to a 1-bit tag peek.}, label={lst:reverse}]
|
|
440
|
+
ktvm 0.1 mono entry @_reverse__int;
|
|
441
|
+
schema $bits = union { 0: $bits, 1: $bits, _: unit };
|
|
442
|
+
schema $int = union { "+": $bits, "-": $bits };
|
|
443
|
+
schema $cell = product { car: $int, cdr: $list_int };
|
|
444
|
+
schema $list_int = union { cons: $cell, nil: unit };
|
|
445
|
+
|
|
446
|
+
proc @_reverse__int(%xs: $list_int, %acc: $list_int) -> (%out: $list_int) total {
|
|
447
|
+
switch (%xs) { // 1-bit non-destructive peek: 0 -> cons, 1 -> nil
|
|
448
|
+
case (/nil): {
|
|
449
|
+
chan %u : unit; barrier %b;
|
|
450
|
+
match /nil %xs -> %u; drain %u : unit -> %b; gate %b, %acc -> %out;
|
|
451
|
+
}
|
|
452
|
+
case (/cons): {
|
|
453
|
+
chan %cell : $cell;
|
|
454
|
+
chan %car : $int; // opaque single BitDeque (unsplit)
|
|
455
|
+
chan %cdr : $list_int; chan %newcell : $cell;
|
|
456
|
+
chan %newacc : $list_int;
|
|
457
|
+
match /cons %xs -> %cell;
|
|
458
|
+
demux %cell : $cell -> (car: %car, cdr: %cdr);
|
|
459
|
+
mux (car: %car, cdr: %acc) -> %newcell : $cell;
|
|
460
|
+
wrap |cons %newcell -> %newacc; // prepend 1-bit cons tag + car onto %acc
|
|
461
|
+
spawn @_reverse__int(%cdr, %newacc) -> (%out);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
\end{lstlisting}
|
|
466
|
+
|
|
467
|
+
% ============================================================================
|
|
468
|
+
\section{Optimization Pipeline and Target Backends}
|
|
469
|
+
\label{sec:opt}
|
|
470
|
+
% ============================================================================
|
|
471
|
+
|
|
472
|
+
\subsection{Two-Tier ISA, Graph Simplification, and Kernel Fusion}
|
|
473
|
+
|
|
474
|
+
Executing tight bit-level loops purely as network procedures (\texttt{proc}) would invoke the scheduler on every symbol. \ktvm{} therefore provides a second instruction tier: a compiled \textbf{\texttt{kernel}} runs as a single scheduled node whose state consists of a control-flow graph (CFG) of basic blocks, a program counter, bounded finite-enum registers (\texttt{reg r : enum(K)}), optional local LIFO bit-stacks (\texttt{stack z : bits}), and bound input/output channels. Basic blocks execute bit operations (\texttt{peek\_bits}, \texttt{shift\_bits}, \texttt{push\_bits}, \texttt{dpda\_copy}, table dispatches), cooperative backpressure (\texttt{yield}~$c, \theta$ when $|c.\mathrm{buf}| \ge \theta$), and terminators (\texttt{goto} for in-place loop iteration with zero node allocation, \texttt{handoff} to transfer channels to a successor procedure/kernel, \texttt{retire}, or \texttt{fail}).
|
|
475
|
+
|
|
476
|
+
Given a concrete module, the \ktvm{} $\to$ \ktvm{} optimizer runs five staged transformations:
|
|
477
|
+
\begin{enumerate}
|
|
478
|
+
\item \textbf{Network simplification and entry-guard compilation:} inlines eligible wrapper procedures, eliminates dead channels and redundant fan-outs, cancels known \texttt{wrap}/\texttt{match} pairs, and analyzes leading tag guards across ordered choices to lift prefix-disjoint alternatives from \texttt{spec} into deterministic multi-port \texttt{switch} nodes (retaining \texttt{spec} wherever disjointness has not been established).
|
|
479
|
+
\item \textbf{Bounded-topology sequencing (\texttt{after}):} inserts \texttt{after} tokens on branching recursive calls and eligible accumulator loops so intermediate subtrees settle into flat \BitDeque{}s before subsequent subcomputations expand.
|
|
480
|
+
\item \textbf{CPS kernel fusion, TMC streaming, and virtual stacks:} fuses eligible acyclic helpers and self-recursive streaming loops into single-node \texttt{kernel} state machines. Tail-modulo-constructor (TMC) loops such as LSB-first binary addition promote carry bits into finite registers and stream output bits forward via \texttt{push\_bits}; deferred-run loops such as single-pass trailing-zero trimming record pending zeros on a local LIFO bit-stack, either emitting them upon seeing a later \texttt{1} or discarding them at end-of-input.
|
|
481
|
+
\item \textbf{Multi-bit lookup table synthesis:} tabulates multiple iterations of fused kernels under a global static size budget (Section~\ref{sec:mwtr}).
|
|
482
|
+
\item \textbf{Post-fusion inlining and bounded short-bit unfolding:} inlines residual wrappers exposed by fusion and performs bounded unfolding on remaining short-consuming recursive procedures to amortize \texttt{spawn} overhead.
|
|
483
|
+
\end{enumerate}
|
|
484
|
+
|
|
485
|
+
\paragraph{Tracing the Half Adder.}
|
|
486
|
+
On the half-adder running example from Section~1, direct lowering emits a \texttt{spec} with a \texttt{match /0} on \texttt{a}, a \texttt{gate} for \texttt{.then}, a \texttt{tee} on \texttt{b} in the second branch, and a \texttt{mux} ordering \texttt{carry} before \texttt{sum}. Simplification inlines \texttt{0}, \texttt{1}, and \texttt{not} and lifts both choices into tag peeks; fusion collapses the body into a single decision \texttt{kernel}. Its entry procedure splits the input into \texttt{a} and \texttt{b}, invokes the kernel, and joins the two output bits: a one-bit peek on \texttt{a} either emits carry \texttt{0} and splices \texttt{b} directly to \texttt{sum}, or reads \texttt{b}, emits its value as the carry, and emits its complement as the sum. Thus inputs \texttt{10} and \texttt{11} produce \texttt{01} and \texttt{10}, respectively.
|
|
487
|
+
|
|
488
|
+
\subsection{Multi-Bit Lookup Tables and the MWTR Throughput Criterion}
|
|
489
|
+
\label{sec:mwtr}
|
|
490
|
+
|
|
491
|
+
Even a fused kernel normally advances by one schema tag per CFG iteration. \ktvm{} makes immutable multi-bit transition tables first-class module declarations in three forms:
|
|
492
|
+
\begin{itemize}
|
|
493
|
+
\item \texttt{chunk\_table}: indexes a finite control state $q \in \{0,\dots,Q{-}1\}$ together with bit windows of effective widths $W_i$ across one or more input ports, returning per-port shift counts, emitted output bits, and the next state or exit. Don't-care bits that cannot affect the transition may be compressed out of the index.
|
|
494
|
+
\item \texttt{stack\_table}: augments the index with a bounded view of a kernel-local bit-stack, pushing or popping stack bits alongside input shifts.
|
|
495
|
+
\item \texttt{fsm\_table}: tabulates bounded multi-bit decisions in acyclic helpers.
|
|
496
|
+
\end{itemize}
|
|
497
|
+
Every table dispatch retains an exact fallback path to the kernel's original CFG when a closed input has fewer than $W_i$ bits remaining or an entry requests fallback.
|
|
498
|
+
|
|
499
|
+
\paragraph{Choosing Table Widths under a Byte Budget.}
|
|
500
|
+
Because table size grows exponentially as $O(Q \cdot 2^{\sum_i W_i})$, choosing window widths naively risks cache thrashing, while asymmetric branches can trap throughput in a slow bottleneck cycle. Following the worst-case content-inspection speed criterion of Yazdani, Fraczak, Welfeld, and Lambadaris~\cite{yazdani2006speed}, the compiler models each candidate loop table as a finite directed graph $G = (V, E)$ of continuing transitions, annotating each edge $e \in E$ with weight $w(e)$ (input bits consumed, with amortized credit for stack pops in stack tables) and time $t(e) = 1$ lookup. For a graph containing a cycle, the minimum weight per lookup along a continuing cycle is the Minimum Weight-to-Time Ratio (MWTR)
|
|
501
|
+
\begin{equation}
|
|
502
|
+
\label{eq:mwtr}
|
|
503
|
+
\rho^*(G) \;=\; \min_{C \text{ a cycle in } G} \frac{\sum_{e \in C} w(e)}{\sum_{e \in C} t(e)}.
|
|
504
|
+
\end{equation}
|
|
505
|
+
\ktvm{} evaluates this graph model with Howard's policy-improvement algorithm~\cite{cochet1998howard}, using floating-point comparisons and an iteration cap. It scores acyclic decision tables by input width and allocates upgrades greedily by estimated gain per additional byte. The default 64~KiB budget bounds static table size. Actual cache residency and elapsed time depend on the target.
|
|
506
|
+
|
|
507
|
+
\paragraph{Bounded Verification Against Reference CFGs.}
|
|
508
|
+
Each synthesized table names its source kernel via \texttt{verified\_against}. By default, the validator symbolically simulates explicit entries against the kernel's fallback CFG, checking shifts, output bits, next state, and exits. It skips tables above the configurable row limit (65{,}536 by default). For compressed chunk indexes it enumerates raw state/window combinations only up to 16{,}384.
|
|
509
|
+
|
|
510
|
+
\subsection{Target Backends and Streaming Boundaries}
|
|
511
|
+
|
|
512
|
+
The three backends execute the same concrete module semantics. The implementation described here is at repository revision \href{https://github.com/fraczak/k/commit/c5e04c0}{\texttt{c5e04c0}}.
|
|
513
|
+
\begin{itemize}
|
|
514
|
+
\item \textbf{JavaScript Reference VM:} interprets concrete modules using power-of-two word ring buffers and an explicit demand stack, with configurable quotas on steps, live nodes, and buffer bytes (exceeding a quota raises a resource error, distinct from $\bot$).
|
|
515
|
+
\item \textbf{WebAssembly Backend:} lowers concrete modules to validated Wasm binaries. At the boundary, the host uses a prefix cache for canonical input headers and copies the frame into linear memory. The runtime loads the payload and its trailing pad bits into the input \BitDeque{}, scans it in place to find the exact endpoint and verify the padding, then rewinds its cursor to expose just the validated payload. For noncanonical headers that pass the schema check, the host validates and extracts the exact payload before entering Wasm. Short \BitDeque{}s live inline in 128 bits and larger buffers grow in powers of two and can be reused. This backend also powers K's terminal and interactive browser REPLs.
|
|
516
|
+
\item \textbf{Native C99/LLVM Backend:} emits standalone C99 that Clang compiles with \texttt{-O3} by default. The executable reads and writes \kwire{} on standard input and output and can serve repeated requests. At ingress it validates with a DPDA that copies the accepted payload from a temporary deque into the root input channel. Its runtime also specializes common fixed-width and self-looping bit schemas into fast DPDA loops, emits simple constructors without transient nodes, and recycles retired nodes, channels, and buffers.
|
|
517
|
+
\end{itemize}
|
|
518
|
+
|
|
519
|
+
\paragraph{Internal Streaming vs.\ Whole-Frame I/O.}
|
|
520
|
+
In the current Wasm and native runners, streaming occurs \emph{between internal producers and consumers}: the runner accepts a complete input wire buffer and emits the framed output once $\mathrm{root\_out}$ closes. Even under a future incremental I/O interface, wire layout itself constrains minimum latency. For example, binary addition \texttt{lsb\_add} accepts a product of fields \texttt{x} and \texttt{y}: the first sum bit depends on both low-order digits, yet \kwire{} serializes all of \texttt{x} before the first bit of \texttt{y}, so any one-pass reader must buffer information about \texttt{x} across that field boundary even though the fused addition kernel itself needs only a single carry bit.
|
|
521
|
+
|
|
522
|
+
% ============================================================================
|
|
523
|
+
\section{Practical Trade-Offs and Qualitative Observations}
|
|
524
|
+
\label{sec:eval}
|
|
525
|
+
% ============================================================================
|
|
526
|
+
|
|
527
|
+
The repository's comparison of the heap-oriented \kvm{} and packed \ktvm{} reports whole-frame and evaluation timings on WebAssembly and native LLVM~\cite{kstudy}. These measurements describe the cited revision. The current \kvm{} Wasm runner can forward a validated frame for a proven identity with matching canonical headers, and the native \kvm{} backend now preserves arena-block reuse when rolling back within a block. Current boundary and memory costs depend on the relation and target.
|
|
528
|
+
\begin{itemize}
|
|
529
|
+
\item \textbf{Boundary marshaling and subtree sharing.} In the measured Wasm list workloads, conversion between wire bytes and arena values dominated the \kvm{} round trip. With the persistent native runners, \kvm{} finished the reported group of list operations sooner. Its constructors can attach a previously computed tail with a single reference.
|
|
530
|
+
\item \textbf{Stack use and live memory.} Some deep bitstream workloads exhausted the \kvm{} Wasm stack in the cited runs. An iterative \ktvm{} streaming loop can reuse the same nodes as the input grows. The buffered payload, replay data, and demand stack can still grow, and divide-and-conquer computations can keep several subproblems live.
|
|
531
|
+
\item \textbf{Kernel and network costs.} The reported native arithmetic runs include cases where optimized \ktvm{} finished sooner. A fused table can consume several bits per dispatch. Calls and network scheduling outside the fused loop also contribute to elapsed time, so the timings alone do not isolate the table's contribution.
|
|
532
|
+
\item \textbf{Field order and replay.} A packed product starts at its first field. To reach a later field, a sequential reader must find the ends of the preceding fields. Once positioned at the final field, it can splice the tail when the schemas agree. A single late-failing speculative branch can retain the entire remaining payload in its replay buffer.
|
|
533
|
+
\end{itemize}
|
|
534
|
+
|
|
535
|
+
% ============================================================================
|
|
536
|
+
\section{Related Work, Open Directions, and Conclusion}
|
|
537
|
+
\label{sec:conclusion}
|
|
538
|
+
% ============================================================================
|
|
539
|
+
|
|
540
|
+
\ktvm{} connects four research lines that point to natural extensions:
|
|
541
|
+
\begin{itemize}
|
|
542
|
+
\item \textbf{Process calculi, Kahn networks, and backtracking cuts:} K draws on CCS~\cite{milner1989ccs} and CSP~\cite{hoare1985csp}, while \ktvm{}'s SPSC channels recall Kahn process networks~\cite{kahn1974semantics} extended with bit-exact rollback. Analogous to inferred \emph{cuts} in packrat PEG parsers~\cite{mizushima2010cuts}, static analysis could release a branch's replay buffer once all remaining alternatives are guaranteed to fail locally on every completion of the observed prefix, while preserving upstream failure and enclosing scopes.
|
|
543
|
+
\item \textbf{Tree automata, $s$-languages, and packed-data compilers:} Regular tree languages~\cite{comon2008tree,hosoya2003regular} underpin K schemas, while their \kwire{} bit encodings form $s$-languages~\cite{fraczak2004slang,bastien2006pnf} closely tied to Concatenation State Machines~\cite{debski2005csm}. Closest among packed-representation compilers are Gibbon/LoCal~\cite{vollmer2019gibbon} and Parallel Gibbon~\cite{koparkar2021parallel}, which compile byte-packed trees using locations and selective indirections. \ktvm{} works at bit granularity on \kwire{} payloads with strict partiality and ordered choice. Recording selected aligned bit offsets together with their residual node lists $[v_1,\dots,v_k]$ (Section~\ref{sec:schemas}) alongside immutable input frames (generalizing K's lazy JS codec) could avoid repeated scans on multi-consumer products without changing the wire format.
|
|
544
|
+
\item \textbf{Single-pass transducers, ordered types, and incremental chunking:} Streaming tree transducers~\cite{alur2017stt} and ordered linear types~\cite{kodama2008ordered} characterize single-pass traversals and suggest separating wire-order procedures from buffering ones (\texttt{reverse}, \texttt{lsb\_add}). For incremental I/O beyond whole frames, XStream~\cite{frisch2007xstream} interleaves parsing and emission, while Cutler et al.~\cite{cutler2024stream} use type derivatives and a chunking homomorphism theorem to establish independence from chunk boundaries. An incremental K runner would also have to withhold tentative output until the computation can no longer invalidate it.
|
|
545
|
+
\item \textbf{Worst-case wire-speed inspection:} The MWTR criterion~\cite{yazdani2006speed} gives table synthesis a way to score the slowest continuing cycle in a candidate kernel~\cite{cochet1998howard}.
|
|
546
|
+
\end{itemize}
|
|
547
|
+
|
|
548
|
+
\paragraph{Conclusion.}
|
|
549
|
+
The first K paper~\cite{fraczak2026k} paired every tree document with the schema needed to interpret its wire encoding. In \ktvm{}, that same schema governs execution itself---determining where constructors emit prefixes, where projections scan, when a splice can transfer ownership of a buffer, and how multi-bit tables are synthesized and checked. Combined with an iterative pull scheduler, partiality barriers, and scoped speculative replay, \ktvm{} provides a direct packed-wire execution model across JavaScript, WebAssembly, and native LLVM backends.
|
|
550
|
+
|
|
551
|
+
% ============================================================================
|
|
552
|
+
% References
|
|
553
|
+
% ============================================================================
|
|
554
|
+
{\small
|
|
555
|
+
\begin{thebibliography}{19}
|
|
556
|
+
\setlength{\itemsep}{1pt}
|
|
557
|
+
|
|
558
|
+
\bibitem{fraczak2026k}
|
|
559
|
+
W.~Fraczak.
|
|
560
|
+
\newblock K: the programming language.
|
|
561
|
+
\newblock \emph{Zenodo}, Record 23652382, October 2026.
|
|
562
|
+
\newblock \url{https://zenodo.org/records/23652382}.
|
|
563
|
+
|
|
564
|
+
\bibitem{kstudy}
|
|
565
|
+
K project.
|
|
566
|
+
\newblock \kvm{} vs.\ \ktvm{}: A High-Level Comparative Study.
|
|
567
|
+
\newblock Repository revision \texttt{93f281c}.
|
|
568
|
+
\newblock \url{https://github.com/fraczak/k/blob/93f281c/DOCS/KVM_VS_KTVM_COMPARATIVE_STUDY.md}.
|
|
569
|
+
|
|
570
|
+
\bibitem{fraczak2004slang}
|
|
571
|
+
W.~Fraczak and A.~Podolak.
|
|
572
|
+
\newblock A characterization of s-languages.
|
|
573
|
+
\newblock \emph{Information Processing Letters}, 89(2), 65--70, 2004. \url{https://doi.org/10.1016/j.ipl.2003.10.006}.
|
|
574
|
+
|
|
575
|
+
\bibitem{bastien2006pnf}
|
|
576
|
+
C.~Bastien, J.~Czyzowicz, W.~Fraczak, and W.~Rytter.
|
|
577
|
+
\newblock Prime normal form and equivalence of simple grammars.
|
|
578
|
+
\newblock \emph{Theoretical Computer Science}, 363(2), 124--134, 2006. \url{https://doi.org/10.1016/j.tcs.2006.07.021}.
|
|
579
|
+
|
|
580
|
+
\bibitem{debski2005csm}
|
|
581
|
+
W.~Debski and W.~Fraczak.
|
|
582
|
+
\newblock Concatenation state machines and simple functions.
|
|
583
|
+
\newblock In \emph{Implementation and Application of Automata (CIAA 2004)}, LNCS 3317, pages 113--124. Springer, 2005. \url{https://doi.org/10.1007/978-3-540-30500-2_11}.
|
|
584
|
+
|
|
585
|
+
\bibitem{yazdani2006speed}
|
|
586
|
+
M.~Yazdani, W.~Fraczak, F.~Welfeld, and I.~Lambadaris.
|
|
587
|
+
\newblock A criterion for speed evaluation of content inspection engines.
|
|
588
|
+
\newblock In \emph{Proceedings of the International Conference on Networking, International Conference on Systems and International Conference on Mobile Communications and Learning Technologies (ICNICONSMCL'06)}, IEEE Computer Society, 2006. \url{https://doi.org/10.1109/ICNICONSMCL.2006.8}.
|
|
589
|
+
|
|
590
|
+
\bibitem{cochet1998howard}
|
|
591
|
+
J.~Cochet-Terrasson, G.~Cohen, S.~Gaubert, M.~Mc~Gettrick, and J.-P.~Quadrat.
|
|
592
|
+
\newblock Numerical computation of spectral elements in max-plus algebra.
|
|
593
|
+
\newblock \emph{IFAC Proceedings Volumes}, 31(18), 667--674, 1998. \url{https://doi.org/10.1016/S1474-6670(17)42067-2}.
|
|
594
|
+
|
|
595
|
+
\bibitem{milner1989ccs}
|
|
596
|
+
R.~Milner.
|
|
597
|
+
\newblock \emph{Communication and Concurrency}.
|
|
598
|
+
\newblock Prentice Hall, 1989.
|
|
599
|
+
|
|
600
|
+
\bibitem{hoare1985csp}
|
|
601
|
+
C.~A.~R.~Hoare.
|
|
602
|
+
\newblock \emph{Communicating Sequential Processes}.
|
|
603
|
+
\newblock Prentice Hall, 1985.
|
|
604
|
+
|
|
605
|
+
\bibitem{kahn1974semantics}
|
|
606
|
+
G.~Kahn.
|
|
607
|
+
\newblock The semantics of a simple language for parallel programming.
|
|
608
|
+
\newblock In \emph{Information Processing 74: Proceedings of the IFIP Congress}, pages 471--475. North-Holland, 1974.
|
|
609
|
+
|
|
610
|
+
\bibitem{comon2008tree}
|
|
611
|
+
H.~Comon, M.~Dauchet, R.~Gilleron, F.~Jacquemard, D.~Lugiez, C.~L{\"o}ding, S.~Tison, and M.~Tommasi.
|
|
612
|
+
\newblock \emph{Tree Automata Techniques and Applications}.
|
|
613
|
+
\newblock 2008 edition. \url{https://inria.hal.science/hal-03367725}.
|
|
614
|
+
|
|
615
|
+
\bibitem{hosoya2003regular}
|
|
616
|
+
H.~Hosoya and B.~C.~Pierce.
|
|
617
|
+
\newblock Regular expression pattern matching for {XML}.
|
|
618
|
+
\newblock \emph{Journal of Functional Programming}, 13(6), 961--1004, 2003. \url{https://doi.org/10.1017/S0956796802004410}.
|
|
619
|
+
|
|
620
|
+
\bibitem{vollmer2019gibbon}
|
|
621
|
+
M.~Vollmer, C.~Koparkar, M.~Rainey, L.~Sakka, M.~Kulkarni, and R.~R.~Newton.
|
|
622
|
+
\newblock {LoCal}: A language for programs operating on serialized data.
|
|
623
|
+
\newblock In \emph{Proceedings of the 40th ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI 2019)}, pages 48--62. ACM, 2019. \url{https://doi.org/10.1145/3314221.3314631}.
|
|
624
|
+
|
|
625
|
+
\bibitem{alur2017stt}
|
|
626
|
+
R.~Alur and L.~D'Antoni.
|
|
627
|
+
\newblock Streaming tree transducers.
|
|
628
|
+
\newblock \emph{Journal of the ACM}, 64(5), article 31, 2017. \url{https://doi.org/10.1145/3092842}.
|
|
629
|
+
|
|
630
|
+
\bibitem{kodama2008ordered}
|
|
631
|
+
K.~Kodama, K.~Suenaga, and N.~Kobayashi.
|
|
632
|
+
\newblock Translation of tree-processing programs into stream-processing programs based on ordered linear type.
|
|
633
|
+
\newblock \emph{Journal of Functional Programming}, 18(3), 333--371, 2008. \url{https://doi.org/10.1017/S0956796807006570}.
|
|
634
|
+
|
|
635
|
+
\bibitem{frisch2007xstream}
|
|
636
|
+
A.~Frisch and K.~Nakano.
|
|
637
|
+
\newblock Streaming XML transformations using term rewriting.
|
|
638
|
+
\newblock In \emph{Programming Language Technologies for XML (PLAN-X 2007)}, pages 2--13, 2007. \url{https://gallium.inria.fr/~frisch/xstream/long.pdf}.
|
|
639
|
+
|
|
640
|
+
\bibitem{cutler2024stream}
|
|
641
|
+
J.~W.~Cutler, C.~Watson, E.~Nkurumeh, P.~Hilliard, H.~Goldstein, C.~Stanford, and B.~C.~Pierce.
|
|
642
|
+
\newblock Stream types.
|
|
643
|
+
\newblock \emph{Proceedings of the ACM on Programming Languages}, 8(PLDI), article 204, 2024. \url{https://doi.org/10.1145/3656434}.
|
|
644
|
+
|
|
645
|
+
\bibitem{mizushima2010cuts}
|
|
646
|
+
K.~Mizushima, A.~Maeda, and Y.~Yamaguchi.
|
|
647
|
+
\newblock Packrat parsers can handle practical grammars in mostly constant space.
|
|
648
|
+
\newblock In \emph{Workshop on Program Analysis for Software Tools and Engineering (PASTE 2010)}, pages 29--36. ACM, 2010. \url{https://doi.org/10.1145/1806672.1806679}.
|
|
649
|
+
|
|
650
|
+
\bibitem{koparkar2021parallel}
|
|
651
|
+
C.~Koparkar, M.~Rainey, M.~Vollmer, M.~Kulkarni, and R.~R.~Newton.
|
|
652
|
+
\newblock Efficient tree-traversals: Reconciling parallelism and dense data representations.
|
|
653
|
+
\newblock \emph{Proceedings of the ACM on Programming Languages}, 5(ICFP), article 91, 2021. \url{https://doi.org/10.1145/3473596}.
|
|
654
|
+
|
|
655
|
+
\end{thebibliography}
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
\end{document}
|