# `ihb2032/tervyx/btree` — Cache-Friendly High-Fanout B-Tree Map & Set

## 1. Purpose, Cross-Language Selection & Tradeoffs

Balanced binary search trees (red-black / AVL trees) allocate one heap node per
key and incur frequent pointer chasing and rotations during sequential builds.
`ihb2032/tervyx/btree` implements a multi-way B-Tree (`@btree.BTreeMap` and
`@btree.BTreeSet`) tailored for compact node allocation, fast bulk construction,
and contiguous range scans:

- **Cross-language design influences**:
  - **C++ (Abseil `btree_map`) & Rust (`std::collections::BTreeMap`)**: Minimum degree `B = 8` (`MIN_KEYS = 7`, `MAX_KEYS = 15`, up to 16 child pointers per internal node), keeping tree height `<= 7` up to 1M keys and cutting node allocations by roughly an order of magnitude compared to binary trees.
  - **OCaml (Jane Street `Core`)**: `@btree.BTreeMap::change` runs a single recursive descent (`Node::change_rec`) that locates, inserts/updates/deletes, and rebalances (split or borrow/merge) in one traversal.
  - **Java (`Arrays.binarySearch`) / C# (`Array.BinarySearch`)**: Internal `search_keys` returns an unboxed `Int32` (`>= 0` found index, `-(slot + 1) < 0` child routing slot) with zero per-level tuple allocation.
  - **Rust (`extract_if`, `retain`, `pop_min`, `pop_max`) & Go (`append_to`, `range_into`)**: Inclusive `[lo, hi]` lazy `range`, zero-intermediate-allocation `range_into`, `O(log n)` endpoint pops, and conditional extraction.
- **Rejected alternatives**:
  - **B+Tree (leaf-linked with duplicated separator keys)**: Requires duplicating keys into internal nodes and maintaining doubly-linked leaf pointers during deletes; storing `(K, V)` directly in internal and leaf nodes (like Rust and Abseil) avoids key duplication and simplifies rebalancing.
  - **Loop-based signed-division binary search in nodes**: Signed `(hi - lo) / 2` emits `i32.div_s` on Wasm/JS and 3-way `.compare` costs 4 instructions per step; unrolling the fixed 4-step radix-2 search (`8/4/2/1`) with single `<` and `==` eliminates loops, divisions, and 3-way compare overhead while remaining directly provable by Z3.

## 2. MoonBit Data Layout & Multi-Backend Tradeoffs

- **Node layout**: Each `Node[K, V]` holds three flat `FixedArray` buffers (`keys` of capacity `16`, `vals` of capacity `16`, and `children` of capacity `0` for leaves or `17` for internal nodes) plus a shared `mut len : Int32`. Storing flat `FixedArray` buffers directly inside `Node` eliminates 3 `Array` wrapper heap objects per node and pre-split buffer reallocations; vacated trailing slots are overwritten with live slot `0` on shrink/split so removed references remain GC-eligible. `BTreeMap` tracks rare splits via an in-place `SplitNode` field, avoiding per-call enum heap allocations during `set` and `change`.
- **Formally verified unrolled radix-2 search & borrowed tail-recursive lookup**: `search_keys(keys, len, key)` executes a loop-free, division-free 4-step radix-2 lower-bound (`8 → 4 → 2 → 1`) with single `<` comparisons followed by a final `==` hit check (using `keys.unsafe_get`, proved in-bounds by Z3 for `0 <= len <= 15`). `BTreeMap::get` descends via the borrowed tail-recursive method `Node::get_rec`, eliminating Perceus RC `incref`/`decref` traffic on `node`, `keys`, and `children` on `wasm` and `native` (cutting `wasm` 1000-key lookup from `46.58 µs` to **`17.78 µs`**). `BTreeMap::iter` and `BTreeMap::range` maintain two parallel flat cursor stacks (`nodes : Array[Node[K, V]]`, `idxs : Array[Int32]`) and increment `idxs` in place, eliminating per-element cursor tuple allocation across iteration and bulk exports (`append_to`, `to_array`, `range_into`).
- **Backend tradeoffs**:
  - **Sequential / bulk insertion**: `BTreeMap` outperforms `core/sorted_map` across the 4 backends (**2.11×–8.49×**) due to ~10× fewer heap node allocations, flat `FixedArray` node buffers, division-free node search, and zero red-black rotations.
  - **In-order iteration (`n = 1000`)**: Parallel flat cursor arrays make `BTreeMap::iter2` beat `core/sorted_map` on `native` (**1.39×**), `wasm` (**1.09×**), and `wasm-gc` (**1.05×**).
  - **Point lookup (`n = 1000`)**: On `wasm`, `BTreeMap` is **3.29× faster** than `core/sorted_map` (`17.78 µs` vs `58.50 µs`). On `wasm-gc`, `BTreeMap` dropped to `9.62 µs` (within `1.28×` of `core/sorted_map`), while excelling on insertion throughput, lower object count, iteration, single-traversal `change`, and contiguous range queries (`range_into`).

## 3. Structural Invariants, Tests & Formal Verification

`BTreeMap` maintains 4 structural invariants:
- **INV1 (strict order)**: Inside each node, `keys[0] < keys[1] < ... < keys[k - 1]`.
- **INV2 (fill bounds)**: Non-root nodes hold `7 <= keys.length() <= 15`; non-empty roots hold `1 <= keys.length() <= 15`.
- **INV3 (subtree bounds)**: Internal nodes satisfy `children.length() == keys.length() + 1`, with subtree `i` strictly bounded by `(keys[i - 1], keys[i])`.
- **INV4 (uniform leaf depth)**: Leaf nodes sit at uniform depth equal to `height`.

- **Colocated Why3/Z3 formal verification (`btree/node.mbt` + `btree/proof.mbtp`, `proof_enabled = true`)**:
  - `search_keys` (called directly by `BTreeMap::get` and `Node::search` over `FixedArray[K]` for arbitrary `K : Compare` with `0 <= len <= MAX_KEYS`): Z3 proves `unsafe_get` bounds safety, exact hit (`keys[res].compare(key) == 0`), and exact miss routing slot (`0 <= -(res + 1) <= len` with `keys[i] < key` left of slot and `keys[i] > key` right of slot) over the unrolled 4-step radix-2 search.
  - `btree_split_counts` (called directly by `Node::split_overfull`): Z3 proves splitting an overfull node (`MAX_KEYS + 1 == 16`) around median `MIN_KEYS == 7` produces `(7, 8)` keys, strictly satisfying INV2 (`MIN_KEYS <= count <= MAX_KEYS`) and key conservation (`left + 1 + right == MAX_KEYS + 1`).
- **Whitebox invariant & differential suite**: `btree/btree_wbtest.mbt` recursively verifies INV1–INV4 after insertion, deletion, `pop_min`/`pop_max`, and `change` workloads alongside multi-thousand-step randomized differential tests with 100% line coverage.

## 4. 4-Backend `--release` Benchmarks (WSL2 Local)

Environment: **AMD Ryzen 7 7840HS** (16 CPUs), `Linux 6.18.58.1-microsoft-standard-WSL2`,
MoonBit `v1.0.0-rc1+3c0520448`, `moon bench -p ihb2032/tervyx/btree --target all --release`.

| Benchmark | `wasm` | `wasm-gc` | `js` | `native` |
| :--- | ---: | ---: | ---: | ---: |
| `bench_btree_insert_seq_1000` | `54.70 µs` | `20.78 µs` | `40.43 µs` | `30.55 µs` |
| `bench_core_sorted_map_insert_seq_1000` | `464.19 µs` | `68.06 µs` | `85.37 µs` | `115.55 µs` |
| `bench_btree_lookup_1000` | `17.78 µs` | `9.62 µs` | `17.83 µs` | `14.13 µs` |
| `bench_core_sorted_map_lookup_1000` | `58.50 µs` | `7.52 µs` | `9.27 µs` | `9.58 µs` |
| `bench_btree_iter_1000` | `35.72 µs` | `7.73 µs` | `11.88 µs` | `9.37 µs` |
| `bench_core_sorted_map_iter_1000` | `39.05 µs` | `8.13 µs` | `9.25 µs` | `13.02 µs` |
| `bench_btree_range_200_of_1000` | `7.30 µs` | `1.64 µs` | `2.23 µs` | `1.98 µs` |

### Takeaways & Guidance

- **Write-heavy / sequential builds**: `BTreeMap` beats `core/sorted_map` across the 4 backends — **`wasm` 8.49×**, **`native` 3.78×**, **`wasm-gc` 3.28×**, **`js` 2.11×**.
- **Ordered iteration & range scans**: `BTreeMap::iter2` beats `core/sorted_map` on **`native` 1.39×**, **`wasm` 1.09×**, and **`wasm-gc` 1.05×**; 200-entry `range` scans finish in `1.64 µs` (`wasm-gc`) and `1.98 µs` (`native`).
- **Wasm & Wasm-GC lookup**: Borrowed `Node::get_rec` + unrolled `<` radix-2 search makes `BTreeMap` **3.29×** faster than `core/sorted_map` on `wasm` (`17.78 µs` vs `58.50 µs`) and cuts `wasm-gc` lookup to `9.62 µs`.
- **Range scans & atomic mutations**: Prefer `BTreeMap` / `BTreeSet` when `range`/`range_into`, `pop_min`/`pop_max`, or single-traversal `change`/`update` matter; for small read-only ordered maps (`<= 256` keys), consider [`SortedFlatMap`](flat_map.md).
