@fraczak/k 8.4.1 → 8.5.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 (109) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/DOCS/ARCHITECTURE.md +83 -0
  3. package/DOCS/CODECS.md +93 -204
  4. package/DOCS/DICTIONARY.md +42 -1241
  5. package/DOCS/FILE_FORMATS.md +170 -625
  6. package/DOCS/GETTING_STARTED.md +164 -0
  7. package/DOCS/KIR_V1.md +22 -33
  8. package/DOCS/KVM_EXECUTION_MODEL.md +88 -481
  9. package/DOCS/PATTERNS.md +155 -138
  10. package/DOCS/POLYMORPHIC_IR.md +83 -101
  11. package/DOCS/PROFILING_AND_TRACING.md +52 -166
  12. package/DOCS/README.md +35 -0
  13. package/DOCS/REPL.md +100 -377
  14. package/DOCS/TEXTUAL_VALUES.md +53 -81
  15. package/DOCS/TYPE_DERIVATION.md +95 -234
  16. package/DOCS/book-combined.md +3786 -0
  17. package/Examples/arithmetics.k +45 -59
  18. package/Examples/djson.k +102 -112
  19. package/Examples/karatsuba-mult.k +2 -3
  20. package/Examples/list.k +6 -7
  21. package/Examples/nat.k +6 -6
  22. package/Examples/poly.k +45 -45
  23. package/LICENSE +15 -0
  24. package/README.md +72 -410
  25. package/backends/llvm/README.md +75 -97
  26. package/backends/wasm/README.md +88 -66
  27. package/canonical-pattern.mjs +7 -3
  28. package/codecs/README.md +23 -261
  29. package/codecs/WIRE_FORMAT.md +132 -0
  30. package/core.k +5 -15
  31. package/named-patterns.mjs +19 -7
  32. package/objects/README.md +24 -109
  33. package/package.json +8 -3
  34. package/paper/Makefile +17 -0
  35. package/paper/k-paper.pdf +0 -0
  36. package/paper/k-paper.tex +435 -0
  37. package/parser.jison +0 -10
  38. package/parser.mjs +32 -43
  39. package/repl.mjs +74 -29
  40. package/scripts/benchmark-idempotency.mjs +3 -3
  41. package/scripts/run-tests.mjs +1 -1
  42. package/scripts/test-package.mjs +64 -0
  43. package/tests/README.md +66 -46
  44. package/tests/code-derivation/core.mjs +61 -0
  45. package/tests/helpers/cli.mjs +45 -0
  46. package/tests/integration.sh +2 -3
  47. package/tests/test-arithmetics.mjs +47 -237
  48. package/tests/test-djson-methods.mjs +71 -275
  49. package/tests/test-hash-normalization.mjs +22 -1
  50. package/tests/test-karatsuba.mjs +18 -126
  51. package/tests/test-named-patterns.mjs +174 -621
  52. package/tests/test-paper-examples.mjs +90 -0
  53. package/tests/test-poly.mjs +2 -2
  54. package/tests/test-repl-html.mjs +2 -2
  55. package/tests/test-repl.mjs +49 -41
  56. package/tests/test.mjs +27 -68
  57. package/AGENTS.md +0 -35
  58. package/CLAUDE.md +0 -64
  59. package/DOCS/BIG_PICTURE.md +0 -439
  60. package/DOCS/BINARY_CODEC_STATUS_AND_TODO.md +0 -74
  61. package/DOCS/CANONICAL_PATTERNS.md +0 -362
  62. package/DOCS/CODEC_ARCHITECTURE.md +0 -257
  63. package/DOCS/CONVERGENCE.md +0 -123
  64. package/DOCS/DIVERGENCE_DETECTION.md +0 -23
  65. package/DOCS/JSON_APPROACHES_COMPARISON.md +0 -302
  66. package/DOCS/KIR_SPECIALIZATION_DESIGN.md +0 -472
  67. package/DOCS/Makefile +0 -99
  68. package/DOCS/NAMED_PATTERNS.md +0 -361
  69. package/DOCS/OBJECT_FILE_AND_PATTERN.md +0 -343
  70. package/DOCS/PATTERNS_AND_TYPED_VALUES.md +0 -665
  71. package/DOCS/WEB_REPL_REQUIREMENTS.md +0 -134
  72. package/DOCS/book/01-introduction.md +0 -48
  73. package/DOCS/book/02-syntax-and-values.md +0 -110
  74. package/DOCS/book/03-types-as-finite-automata.md +0 -155
  75. package/DOCS/book/04-partial-functions-and-composition.md +0 -145
  76. package/DOCS/book/05-typing-filters-and-normalization.md +0 -109
  77. package/DOCS/book/06-values-in-memory.md +0 -1085
  78. package/DOCS/book/07-the-partial-function-abi.md +0 -143
  79. package/DOCS/book/08-operational-semantics-and-execution.md +0 -196
  80. package/DOCS/book/09-compiler-architecture.md +0 -160
  81. package/DOCS/book/10-from-ast-to-intermediate-representation.md +0 -166
  82. package/DOCS/book/14-canonical-serialization.md +0 -176
  83. package/DOCS/book/appendix-b-incorporating-external-predefined-types-and-functions.md +0 -156
  84. package/DOCS/book/overview.txt +0 -68
  85. package/DOCS/book.md +0 -50
  86. package/Examples/bnat.k +0 -308
  87. package/Examples/buda.k +0 -66
  88. package/Examples/byte.k +0 -35
  89. package/Examples/code.k +0 -43
  90. package/Examples/vhdl_to_k.k +0 -67
  91. package/JOURNAL.md +0 -288
  92. package/TODO.md +0 -107
  93. package/backends/wasm/DOCS/USE-WEB-ASSEMBLY.md +0 -233
  94. package/backends/wasm/TECHNICAL-DEBT.md +0 -58
  95. package/backends/wasm/demo_ieee.mjs +0 -318
  96. package/browser/vfs-data.mjs +0 -21
  97. package/codecs/BINARY_FORMAT.md +0 -53
  98. package/codecs/POLYMORPHIC_BINARY_FORMAT.md +0 -303
  99. package/codecs/pandoc.css +0 -71
  100. package/tests/code-derivation/blowup.mjs +0 -25
  101. package/tests/code-derivation/bnat.mjs +0 -11
  102. package/tests/code-derivation/dot.mjs +0 -37
  103. package/tests/code-derivation/index.mjs +0 -20
  104. package/tests/code-derivation/loop.mjs +0 -17
  105. package/tests/code-derivation/nat.mjs +0 -10
  106. package/tests/code-derivation/not-not.mjs +0 -14
  107. package/tests/code-derivation/product.mjs +0 -22
  108. package/tests/code-derivation/rlz.mjs +0 -13
  109. package/tests/test-fingerprint.mjs +0 -38
@@ -1,184 +1,70 @@
1
- # Profiling and Execution Tracing in k
2
-
3
- This document describes the performance benchmarking, macro-phase execution tracing,
4
- and function-level call profiling infrastructure for `k` backends.
5
-
6
- The profiling framework allows fine-grained performance analysis of polymorphic `k`
7
- programs across multiple execution targets:
8
- - **WebAssembly** (in-process Wasm module via single-pass kVM lowering)
9
- - **LLVM** (native specialized executable via KIR-P lowering)
10
- - **kVM Interpreter** (in-process TypeScript/JavaScript kVM evaluator)
11
- - **Native JS Baselines** (envelope-aware and envelope-free reference runs)
12
-
13
- ---
14
-
15
- ## 1. Motivation: Apples-to-Apples Backend Comparison
16
-
17
- When measuring end-to-end request latency across backends, wall-clock
18
- time can be dominated by factors outside the core relation algorithm:
19
- - **Process IPC**: Out-of-process native executables (LLVM)
20
- communicate via stdin/stdout pipes, incurring OS context switches and
21
- pipe buffer copies.
22
- - **Wire Codec**: Decoding and validating the binary wire format
23
- (`pattern + value`) and encoding the response.
24
- - **In-Memory Representation**: WebAssembly converts incoming values into
25
- a flat linear memory arena layout.
26
- - **Pure Evaluation**: The actual relational instruction loop performing
27
- the algorithm.
28
-
29
- Without detailed accounting, native LLVM binaries communicating over
30
- pipes can appear slower than in-process WebAssembly or the interpreter
31
- simply because of IPC overhead. The tracing infrastructure breaks
32
- request latency down into nanosecond-level phases so that pure
33
- execution time can be measured and compared directly.
34
-
35
- In addition, **per-function invocation profiling** verifies that every backend performs the
36
- exact same number of relational evaluations and loop iterations for a given input.
37
-
38
- ---
39
-
40
- ## 2. Test Workload: Polymorphic List Operations (`Examples/poly.k`)
41
-
42
- The primary benchmark for polymorphic kVM execution is [`Examples/poly.k`](../Examples/poly.k),
43
- which defines canonical polymorphic operations over recursive lists:
44
- - `reverse`: Linear reverse using an accumulator.
45
- - `concat`: Polymorphic list concatenation.
46
- - `split_by`: Splits a list at index $N$ into `{ first, second }`.
47
- - `get_nth`: Retrieves the $N$-th element (0-indexed).
48
- - `length`: Computes list length using arbitrary-precision Peano/bit integers.
49
-
50
- ### Modular Compilation and Name Isolation
51
-
52
- `Examples/poly.k` depends on integer and list operations defined in [`Examples/arithmetics.k`](../Examples/arithmetics.k).
53
- Following `k`'s canonical content-addressed design:
54
- - `arithmetics.k` is compiled as a separate library (`--lib`).
55
- - Only required symbols (`0`, `int`, `inc`, `dec`, `nat`, `zero_int?`, `nil`, `cons`, `car`, `cdr`) are exported into `poly.k`'s scope.
56
- - Bitstring `concat` in `arithmetics.k` remains strictly private and does not conflict with polymorphic list `concat` in `poly.k`. Each function receives its own unique canonical content hash.
57
-
58
- ---
59
-
60
- ## 3. Macro-Phase Execution Tracing (Level 1)
61
-
62
- When tracing is enabled, each request is instrumented to measure 7 discrete phases with nanosecond precision:
63
-
64
- | Phase | Description | LLVM | WebAssembly | kVM Interp |
65
- | :--- | :--- | :---: | :---: | :---: |
66
- | **1. IPC Read (Pipe In)** | Waiting for and reading input payload from stdin | Yes | N/A (in-process) | N/A (in-process) |
67
- | **2. Wire Decode & Validate** | Decoding wire buffer and validating against pattern | Yes | N/A (in-process) | N/A (in-process) |
68
- | **3. Flat Input Prep (Arena)** | Flattening decoded structures into linear arena memory | N/A | Yes | N/A |
69
- | **4. Pure Evaluation** | Core relational execution loop | **Yes** | **Yes** | **Yes** |
70
- | **5. Flat Output Prep (Arena)** | Serializing/reading in-memory representations | N/A | Yes | N/A |
71
- | **6. Wire Encode** | Encoding result to canonical wire format | Yes | N/A (in-process) | N/A (in-process) |
72
- | **7. IPC Write (Pipe Out)** | Writing output wire bytes to stdout pipe | Yes | Yes (driver) | N/A |
73
-
74
- ### Phase Timing Output Example
75
-
76
- ```text
77
- --- Operation: reverse (len 40) ---
78
- Phase | LLVM | WebAssembly | kVM Interp
79
- -------------------------+---------------+---------------+---------------
80
- 1. IPC Read (Pipe In) | 161.42 µs | - | -
81
- 2. Wire Decode & Validate | 1.58 µs | - | -
82
- 3. Flat Input Prep (Arena) | - | 80.88 µs | -
83
- 4. Pure Evaluation | 0.54 µs | 1.71 µs | 26.04 µs
84
- 5. Flat Output Prep (Arena) | - | 76.71 µs | -
85
- 6. Wire Encode | 4.88 µs | - | -
86
- 7. IPC Write (Pipe Out) | 11.08 µs | 0.62 µs | -
87
- -------------------------+---------------+---------------+---------------
88
- Total Request Time | 179.50 µs | 159.92 µs | 26.04 µs
89
- ```
1
+ # Profiling and benchmarks
90
2
 
91
- **Key Takeaways**:
92
- - **Pure evaluation** in LLVM native code (`0.54 µs`) is ~3.2× faster
93
- than WebAssembly (`1.71 µs`) and ~48× faster than the interpreter
94
- (`26.04 µs`).
95
- - **End-to-end request time** for native binaries is dominated by pipe
96
- IPC read (`~160 µs`).
97
- - **WebAssembly overhead** is concentrated in flat arena conversion
98
- (`~80 µs` in, `~76 µs` out).
99
-
100
- ---
101
-
102
- ## 4. Per-Function Invocation Profiling (Level 2)
103
-
104
- Per-function profiling increments dedicated counters at the entry point of every relation
105
- body and tail-call loop. This proves semantic equivalence across targets by verifying that
106
- every backend executes the exact same call path.
107
-
108
- ### Function Profile Output Example
109
-
110
- ```text
111
- Function Call Profile: reverse
112
- Function Name | WebAssembly Calls | kVM Interp Calls
113
- -------------------------+-------------------+------------------
114
- reverse | 1 | 1
115
- _reverse | 41 | 41
116
- car | 40 | 40
117
- cdr | 40 | 40
118
- cons | 40 | 40
119
- nil | 1 | 1
120
- -------------------------+-------------------+------------------
121
- Total Calls | 163 | 163
122
- ```
3
+ Benchmarks compare reference JavaScript, kVM, Wasm, LLVM, and PKIR execution.
4
+ Run commands from the repository root; LLVM lanes need Clang.
123
5
 
124
- *(Note: Both backends arrive at the exact same total call count:
125
- 163 calls for reversing a list of length 40).*
6
+ ## Entry points
126
7
 
127
- ---
8
+ | Command | Workload |
9
+ | --- | --- |
10
+ | `npm run compare` | Shared harness for polymorphic list operations |
11
+ | `npm run perf:poly` | List operations across execution lanes |
12
+ | `npm run perf:poly:trace` | List timing phases and call profiles |
13
+ | `npm run perf:int` | Integer arithmetic |
14
+ | `npm run perf:ieee` | Binary64 arithmetic |
15
+ | `npm run perf:mult` | Multiplication algorithm comparison |
16
+ | `npm run benchmark` | End-to-end artifact/execution measurements |
17
+ | `npm run benchmark:html` | Render generated benchmark-results.json |
128
18
 
129
- ## 5. Usage & Commands
19
+ Use each script's `--help` for its flags and environment variables. For a small
20
+ list trace:
130
21
 
131
- ### Running Benchmarks
22
+ ```sh
23
+ ITERATIONS=1 LIST_LENGTH=10 npm run perf:poly:trace
24
+ ```
132
25
 
133
- ```bash
134
- # Standard end-to-end benchmark across all 6 lanes
135
- npm run perf:poly
26
+ `LIST_LENGTH` and `ITERATIONS` set workload and sample counts.
27
+ `TRACE_SAMPLES` controls trace repetitions. `WASM_ONLY=1` or `LLVM_ONLY=1`
28
+ selects a target; `BACKENDS_ONLY=1` skips native JavaScript baselines in the
29
+ performance scripts. Available lanes vary by tool.
136
30
 
137
- # Benchmark with macro-phase breakdown tracing and function profiling
138
- npm run perf:poly:trace
31
+ The shared harness also supports explicit conformance and profile modes:
139
32
 
140
- # Or run the script directly:
141
- node scripts/perf-poly.mjs --trace
33
+ ```sh
34
+ npm run compare -- --listLength 10 --iterations 1
35
+ npm run compare -- --listLength 10 --conformance
36
+ npm run compare -- --listLength 10 --profile
142
37
  ```
143
38
 
144
- ### Environment Variables
39
+ Inspect per-backend status: a tool can report an unavailable or failed lane
40
+ while continuing measurements for others.
145
41
 
146
- | Variable | Default | Description |
147
- | :--- | :---: | :--- |
148
- | `LIST_LENGTH` | `40` | Number of elements in test lists. |
149
- | `ITERATIONS` | `3` | Number of iterations for the benchmark summary table. |
150
- | `TRACE_SAMPLES` | `5` | Repetitions sampled and averaged for phase timings. |
151
- | `TRACE` | `0` | Set to `1` (or pass `--trace`) to enable phase breakdown. |
152
- | `PROFILE` | `1` (with trace) | Set to `0` to disable function call counters. |
153
- | `WASM_RESET` | `1` | Reset the WebAssembly linear memory arena between calls (`1` or `0`). |
154
- | `WASM_ONLY` | `0` | Run only the WebAssembly target. |
155
- | `LLVM_ONLY` | `0` | Run only the LLVM target. |
156
- | `BACKENDS_ONLY` | `0` | Skip the native JS baseline lanes. |
42
+ ## What the timings mean
157
43
 
158
- ### Practical Examples
44
+ End-to-end request time can include:
159
45
 
160
- ```bash
161
- # Fast smoke check with list length 10 and 1 iteration:
162
- ITERATIONS=1 LIST_LENGTH=10 npm run perf:poly:trace
163
-
164
- # Trace WebAssembly on large lists (100 elements):
165
- LIST_LENGTH=100 WASM_ONLY=1 npm run perf:poly:trace
46
+ 1. process input and output;
47
+ 2. wire decoding and encoding;
48
+ 3. conversion to/from a target arena;
49
+ 4. relation evaluation.
166
50
 
167
- # Isolate LLVM native execution:
168
- LLVM_ONLY=1 npm run perf:poly:trace
169
- ```
51
+ In-process Wasm measurements and persistent LLVM executables have different
52
+ boundary costs. Compare evaluation and end-to-end time separately, and report
53
+ workload, engine, warmup, sample count, and machine with results.
170
54
 
171
- ---
55
+ Call profiles count relation invocations and tail-loop iterations. Matching
56
+ counts can reveal consistent work across backends; they do not prove identical
57
+ results or semantic equivalence. Correctness checks must compare outputs and
58
+ their envelopes where schema identity matters.
172
59
 
173
- ## 6. Implementation Architecture
60
+ ## Implementation
174
61
 
175
- ### WebAssembly Backend
176
- - **Code Emission** ([`backends/wasm/src/kvm2wasm.mjs`](../backends/wasm/src/kvm2wasm.mjs)): Emits mutable 64-bit Wasm globals:
177
- ```wat
178
- (global $prof_<name> (export "prof_<name>") (mut i64) (i64.const 0))
179
- ```
180
- Inside the function/tail-loop body, `(global.set $prof_<name> (i64.add (global.get $prof_<name>) (i64.const 1)))` increments the counter.
181
- - **Harness Integration** ([`backends/wasm/tests/perf-support.mjs`](../backends/wasm/tests/perf-support.mjs)): `readWasmProfile` and `resetWasmProfile` read and zero the exported globals directly from the Wasm instance exports.
62
+ The shared harness lives in [harness/](../harness/).
63
+ Wasm profiling globals and arena access are emitted by
64
+ [kvm2wasm.mjs](../backends/wasm/src/kvm2wasm.mjs).
65
+ The kVM interpreter increments `context.profile` counters, and backend
66
+ performance helpers collect profiles and phase timings.
182
67
 
183
- ### kVM Interpreter
184
- - **Evaluation Loop** ([`kvm.mjs`](../kvm.mjs)): When `context.profile` is provided, `executeKVM` resolves the active function name or hash via `context.hashToName` and increments `context.profile[name]`.
68
+ Generated benchmark reports are measurements of a particular run, not language
69
+ or performance guarantees. Use the [test suites](../tests/README.md) for
70
+ regression verification.
package/DOCS/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # Documentation
2
+
3
+ Start with [Getting started](GETTING_STARTED.md) for a complete walkthrough,
4
+ or [try the browser REPL](https://fraczak.github.io/k/).
5
+
6
+ ## Language and tools
7
+
8
+ | Guide | Contents |
9
+ | --- | --- |
10
+ | [Patterns and relations](PATTERNS.md) | Core syntax, filters, named patterns, scope, and canonical identity |
11
+ | [REPL](REPL.md) | Session state, loading, codecs, engines, and exports |
12
+ | [File formats and tools](FILE_FORMATS.md) | Source, objects, libraries, kVM, PKIR, and CLI workflows |
13
+ | [Textual values](TEXTUAL_VALUES.md) | Boundary notation and singleton product/variant ambiguity |
14
+ | [Writing codecs](CODECS.md) | Codec module contract and a complete example |
15
+ | [Wire format](../codecs/WIRE_FORMAT.md) | Pattern framing and binary payload encoding |
16
+ | [Glossary](DICTIONARY.md) | The vocabulary used in these guides |
17
+
18
+ The published [paper](https://zenodo.org/records/23652382) has a
19
+ [local PDF](../paper/k-paper.pdf) and [LaTeX source](../paper/k-paper.tex).
20
+
21
+ ## Implementation
22
+
23
+ - [Compiler and runtime](ARCHITECTURE.md)
24
+ - [Contract derivation](TYPE_DERIVATION.md)
25
+ - [KIR-P export](KIR_V1.md)
26
+ - [kVM execution](KVM_EXECUTION_MODEL.md)
27
+ - [PKIR and layout witnesses](POLYMORPHIC_IR.md)
28
+ - [Profiling and benchmarks](PROFILING_AND_TRACING.md)
29
+ - [WebAssembly backend](../backends/wasm/README.md)
30
+ - [LLVM backend](../backends/llvm/README.md)
31
+
32
+ For contributions, read [AGENTS.md](../AGENTS.md) and the
33
+ [test guide](../tests/README.md). Editor setup is documented in the
34
+ [VS Code extension](../k-vscode/README.md); release history is in
35
+ [CHANGELOG.md](../CHANGELOG.md).