# Tervyx Design & Benchmark Handbook

`ihb2032/tervyx` is a zero-third-party-dependency, high-performance core
extension library for [MoonBit](https://www.moonbitlang.com/) 1.0. Its 6 public
sub-packages can be imported independently, target `wasm`, `wasm-gc`, `js`, and
`native`, and include colocated Why3/Z3 formal verification (`moon prove`) as a
CI gate.

## Cross-Language Design Atlas

Each sub-package synthesizes proven ideas from systems and functional language
ecosystems, adapted to MoonBit's memory model and 4 compilation targets:

| Source Ecosystem | Adopted Strengths | Packages & Representative APIs |
| :--- | :--- | :--- |
| **C++** (Abseil / Folly / LLVM / Boost / C++23) | SwissTable 16-byte control metadata + `7/8` load factor, high-fanout B-Tree, dual contiguous arrays (`std::flat_map`), inline `SmallVector`, fixed-cap `static_vector` | [`flat_map`](packages/flat_map.md), [`btree`](packages/btree.md), [`small_vec`](packages/small_vec.md) |
| **Rust** (`memchr` / `slotmap` / `std`) | SIMD first+last byte substring filtering, 64-bit `#valtype` generational handles (ABA protection) with dense & secondary arenas, `extract_if` conditional removal | [`memscan`](packages/memscan.md), [`slot_map`](packages/slot_map.md), `extract_if` across containers |
| **.NET** (`System.Buffers.SearchValues`) | Precompiled 256-byte lookup table & 4-bit nibble-LUT SIMD byte-set matching | [`memscan`](packages/memscan.md) (`@memscan.SearchValues`) |
| **OCaml** (Jane Street `Core`) | Single-lookup atomic state transitions `change(k, (V?) -> V?)` and `update(k, (V?) -> V)` | [`flat_map`](packages/flat_map.md), [`btree`](packages/btree.md), [`slot_map`](packages/slot_map.md) |
| **Go** (`Append`-into-dst) | Caller-buffer reuse without intermediate allocations (`append_to`, `drain_into`, `range_into`, `find_all_byte_into`) | Containers & [`memscan`](packages/memscan.md) |
| **Java** (Agrona / `fastutil` / `Arrays`) | Primitive-specialized unboxed `IntMap` avoiding `Option` boxing & trait dispatch; unboxed `Int32` binary-search encoding (`>= 0` hit, `-(slot + 1)` miss) | [`flat_map`](packages/flat_map.md) (`@flat_map.IntMap`), [`btree`](packages/btree.md) |
| **MoonBit 1.0 + Why3/Z3** | `UninitializedArray[T]` zero-`Option` backing storage, `#valtype`, `V128` SIMD layering, colocated `moon prove` contracts | `memscan`, `small_vec`, `slot_map`, `flat_map`, `btree` |

## Documentation Index

- **Unified API Conventions**: [api_conventions.md](api_conventions.md) — single authoritative vocabulary for container & scanner verbs, trait implementations, and ownership boundaries.
- **Generated HTML API Reference**: <https://ihb2032.github.io/tervyx/> (built by `moon doc` from source docstrings and deployed automatically on pushes to `main`).

## Package Handbooks

Each public package has a single authoritative handbook combining cross-language
design tradeoffs, MoonBit multi-backend data layout, colocated Why3/Z3 formal
verification, and same-machine 4-backend `--release` benchmarks:

| Package | Core Types & Capabilities | Formal Verification (`moon prove`) | Handbook |
| :--- | :--- | :--- | :--- |
| `ihb2032/tervyx/hash` | `RapidHasher`, 64-bit XXH64 (`hash_bytes`, `hash_string`, `mix64`) | Cross-backend bit-exact vectors & avalanche tests | [packages/hash.md](packages/hash.md) |
| `ihb2032/tervyx/memscan` | `V128` byte scanning, `find_bytes`, `is_valid_ascii`, `SearchValues` | Direct contract on `bytes_match_inner` in `memscan/memscan.mbt` | [packages/memscan.md](packages/memscan.md) |
| `ihb2032/tervyx/small_vec` | `SmallVec4`, `SmallVec8`, `StaticVec`, `SmallBitSet` | Direct contracts on `bitset_words_for`, `bitset_addr`, `clamp_nonneg` in `small_vec/small_bitset_common.mbt` | [packages/small_vec.md](packages/small_vec.md) |
| `ihb2032/tervyx/slot_map` | `#valtype Key`, `SlotMap`, `DenseSlotMap`, `SecondaryMap` | Direct contracts on `Key::null`/`is_null`/`version` (`slot_map/key.mbt`) & `clamp_nonneg` | [packages/slot_map.md](packages/slot_map.md) |
| `ihb2032/tervyx/flat_map` | `FlatHashMap`, `FlatHashSet`, `IntMap`, `SortedFlatMap` | Direct contracts on `max_load_for`, `next_pow2_cap`, `max_cap`, `sorted_lower_bound`, `sorted_upper_bound`, `sorted_search` + `flat_map/proof.mbtp` | [packages/flat_map.md](packages/flat_map.md) |
| `ihb2032/tervyx/btree` | `BTreeMap`, `BTreeSet` (min degree 8, 7..15 keys/node) | Direct contracts on `search_keys` (`K : Compare` binary search) and `btree_split_counts` + `btree/proof.mbtp` | [packages/btree.md](packages/btree.md) |

> **Scope note on `moonc-prove 1.0.0-rc1`**: Contracts (`where { proof_require / proof_ensure }`) live directly on live production functions in each owning package (`proof_enabled = true` + colocated `proof.mbtp`, zero separate shadow proof sub-packages). Current toolchain boundaries shape what can be contracted directly today:
> 1. Structs with `mut` fields are not yet supported inside contracted functions (`[4207]`).
> 2. Mutable `Array[T]` is not yet modeled in `moonbit_builtin_prelude.mlw`, whereas `FixedArray[T]` is first-class — so `BTreeMap` nodes and `SortedFlatMap` use flat `FixedArray` buffers to verify their generic `K : Compare` binary searches directly.
> 3. `V128` SIMD intrinsics do not yet have a Why3 theory.

## 4-Backend Benchmark Highlights (WSL2 Local)

Measured sequentially in `--release` mode on an **AMD Ryzen 7 7840HS** (16 CPUs,
`Linux 6.18.58.1-microsoft-standard-WSL2`, MoonBit `v1.0.0-rc1+3c0520448`, full
tables in each package handbook):

- **`memscan` (4096 B)**: `find_byte` runs in `106.64 ns` on `native` (**8.4×** vs scalar `895.58 ns`, ~`38.4 GB/s`), `144.30 ns` on `wasm` (**11.8×**), `1.10 µs` on `wasm-gc` (**1.58×**), and `1.19 µs` on `js` (**1.57×**); `is_valid_ascii` runs in `94.32 ns` on `native` (**9.6×**, ~`43.4 GB/s`) and `959.55 ns` on `wasm-gc` (**2.11×**); `find_bytes` runs in `211.57 ns` on `native`, `1.30 µs` on `wasm-gc` (**3.36×** faster than lane-packed SIMD), and `1.20 µs` on `js` (**2.43×** faster).
- **`hash`**: Direct-offset `hash_bytes(4096 B)` runs in `255.85 ns` on `wasm` (**5.28×** vs `core` 32-bit `Hasher` at `1.35 µs`, ~`16.0 GB/s`), `312.57 ns` on `native` (**4.19×**, ~`13.1 GB/s`), `1.40 µs` on `wasm-gc` (**1.18×**), and `4.41 µs` on `js` (**4.34×** faster via zero-`BigInt` 32-bit `(lo, hi)` XXH64); `hash_string(64)` is **1.85×–2.64×** faster on `wasm`, `wasm-gc`, and `native` and **4.42×** faster on `js` (`259.99 ns`).
- **`small_vec`**: `SmallBitSet` inline operations run in `18.14 ns` on `native` (**23.5×** vs `core/Map`), `18.63 ns` on `js` (**24.7×** vs `core/Map` via zero-`BigInt` 32-bit split, **14.15×** faster than `UInt64`), `45.03 ns` on `wasm-gc` (**7.92×**), and `89.92 ns` on `wasm` (**11.2×**); both `SmallVec4` and `SmallVec8` beat `Array` across `wasm`, `wasm-gc`, `js`, and `native`.
- **`slot_map`**: Flat `FixedArray` SoA `SlotMap::get(1000)` beats `core/Map` across `wasm`, `wasm-gc`, `js`, and `native` (**1.52×–3.46×**, down to `732.22 ns` on `native`); `DenseSlotMap` (**1.40×–7.18×**) and `SlotMap` (**1.08×–5.09×**) fragmented iteration both beat `core/Map` across the 4 targets.
- **`flat_map`**: Single-probe unboxed `IntMap` beats `core/hashmap` on both `1000`-key insert (`wasm` **2.94×**, `native` **1.47×**, `wasm-gc` **1.22×**, `js` **1.06×**) and hit (`js` **1.47×**, `wasm-gc` **1.46×**, `wasm` **1.24×**, `native` **1.23×** at `1.99 µs`) across the 4 targets, plus miss on `wasm` (**1.91×**) and `js` (**1.40×**); `SortedFlatMap` (`n = 128`) beats `core/sorted_map` on `wasm` (**1.73×**) and `native` (**1.27×**, `651.38 ns`).
- **`btree`**: `BTreeMap` sequential insert (`1000` keys) beats `core/sorted_map` across the 4 targets (**2.11×–8.49×**, down to `20.78 µs` on `wasm-gc` and `30.55 µs` on `native`); borrowed `Node::get_rec` + unrolled radix-2 search reaches `17.78 µs` on `wasm` (**3.29×** vs `core/sorted_map`) and `9.62 µs` on `wasm-gc`; parallel flat-cursor iteration beats `core/sorted_map` on `native` (**1.39×**), `wasm` (**1.09×**), and `wasm-gc` (**1.05×**).

## Reproducing Verification & Benchmarks

```sh
# Cross-backend unit tests
moon test --target all

# Why3/Z3 formal verification (requires Z3 4.12.6 on Linux / WSL2)
moon prove

# Line coverage verification
moon test --enable-coverage && moon coverage analyze

# 4-backend release benchmarks
moon bench --target all --release
```
