# `ihb2032/tervyx/flat_map` — SwissTable Maps, Unboxed `IntMap` & `SortedFlatMap`

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

Symbol tables, request caches, integer-ID registries, and read-heavy small
ordered maps benefit strongly from flat contiguous memory layouts.
`ihb2032/tervyx/flat_map` provides 4 flat-array containers conforming to the
unified Map & Set vocabulary ([api_conventions.md](../api_conventions.md)):

- **Cross-language design influences**:
  - **C++ (Abseil `flat_hash_map` / Folly `F14`) & Rust (`hashbrown`)**: `@flat_map.FlatHashMap` and `@flat_map.FlatHashSet` use open-addressed SwissTable metadata (`ctrl : FixedArray[Byte]` storing `CTRL_EMPTY = 0x80`, `CTRL_DELETED = 0xFE`, or 7-bit `H2` fingerprints) with `7/8` (87.5%) max load and a 16-byte mirrored tail.
  - **Java (Agrona `Int2ObjectHashMap` / `fastutil`)**: `@flat_map.IntMap` specializes `Int32` keys in a flat unboxed `FixedArray[Int32]` with inline single-multiply 32-bit mixing (`0x45D9F3BU`) and direct integer equality — zero `Hash`/`Eq` trait dispatch and zero key boxing.
  - **C++23 (`std::flat_map`) / `boost::container::flat_map`**: `@flat_map.SortedFlatMap` stores keys and values in two parallel contiguous arrays (`keys_arr`, `vals_arr`) with `O(n)` `from_sorted_array`, `O(log n)` `lower_bound` / `upper_bound`, and cache-line `range` / `range_into`.
  - **OCaml (Jane Street `Core`) / Rust (`extract_if`) / Go (`append_to`, `range_into`)**: Unified single-probe `change`, `update`, `get_or_init`, `retain`, `extract_if`, and caller-buffer `append_to`.
- **Rejected alternatives**:
  - **`FixedArray[K?]` / `FixedArray[V?]` backing arrays**: Replaced with `UninitializedArray[K]` / `UninitializedArray[V]` since `ctrl` already tracks slot occupancy, removing `Option` boxing, redundant `is Some` checks, and `O(cap)` `None`-fill loops.
  - **64-bit internal table hashing**: Pure single-multiply 32-bit mixing (`(h ^ (h >> 16)) * 0x45D9F3BU` followed by `^ (m >> 16)`) avoids `UInt64` emulation overhead on `js` while mixing high and low bits into both `H1` and `H2`.

## 2. MoonBit Data Layout & Multi-Backend Probing Architecture

- **Zero-`Option` SoA backing storage & cached `mask`**: `FlatHashMap` stores `ctrl : FixedArray[Byte]`, `keys_buf : UninitializedArray[K]`, `vals_buf : UninitializedArray[V]`, and a precomputed `mask = cap - 1`; `IntMap` stores `ctrl : FixedArray[Byte]`, `keys_buf : FixedArray[Int32]`, `vals_buf : UninitializedArray[V]`, and `mask`. `clear()` and `shrink_to_fit()` allocate fresh `UninitializedArray` buffers to release cleared references immediately.
- **Target-specialized probing (same `ctrl` layout, optimal per-target algorithm)**:
  - **`wasm` & `native` (`flat_map/group_simd.mbt`)**: Combines a **1-load home-slot hit fast path** (`ctrl[pos0] == tag && keys[pos0] == key`, resolving uncollided hits without `V128` setup) with 16-byte `V128` SIMD SwissTable quadratic triangular group probing on collisions, lazy `CTRL_EMPTY` splatting on misses, and Abseil `was_never_full` erasure.
  - **`wasm-gc` & `js` (`flat_map/group_scalar.mbt`)**: Without hardware 16-byte SIMD, constructing two 16-bit masks per group costs 32 byte loads even on an immediate hit or empty bucket. Instead, non-SIMD targets run **fused H2-tagged linear probing** directly over `ctrl`: an immediate hit or miss inspects **1 control byte**, hash collisions reject `127/128` wrong keys via the 7-bit H2 tag before touching `keys_buf`, and erasure resets `idx` to `CTRL_EMPTY` when `ctrl[(idx + 1) & mask] == CTRL_EMPTY` (otherwise `CTRL_DELETED`), preserving the invariant that no `CTRL_EMPTY` appears between a live key's home bucket and its stored slot.
  - **Single-probe insert preparation across the 4 targets**: `FlatHashMap::find_or_prepare_insert` and `IntMap::find_or_prepare_insert` (modeled on Abseil `find_or_prepare_insert` and Rust `hashbrown`) return `idx >= 0` on existing key hits or `-(avail + 1)` for the first `EMPTY`/`DELETED` slot encountered during the same probe, eliminating the second table probe on `set`, `get_or_init`, `change`, and `FlatHashSet::insert`.
  - **Formally verified `SortedFlatMap` binary search**: `SortedFlatMap` stores parallel flat `FixedArray` buffers (`keys_arr`, `vals_arr`) with `sorted_lower_bound`, `sorted_upper_bound`, and `sorted_search` directly proved by Why3/Z3 over `FixedArray[K]` (`K : Compare`), using direct `<` / `<=` comparisons and `keys.unsafe_get(mid)` whose bounds safety is machine-checked.

## 3. Invariants, Differential Tests & Formal Verification

- **Colocated Why3/Z3 formal verification (`flat_map/flat_hash_map.mbt`, `flat_map/sorted_flat_map.mbt` + `flat_map/proof.mbtp`, `proof_enabled = true`)**:
  - `max_load_for` (called directly by `FlatHashMap` and `IntMap`): Z3 proves `0 < max_load < cap` and `max_load == cap - cap / 8` for `cap >= 16`, guaranteeing at least one `CTRL_EMPTY` slot so open-addressing probe loops terminate.
  - `grow_pow2_cap` / `next_pow2_cap` (called directly by table initialization and `reserve`): Z3 proves termination of doubling growth via `proof_decrease` and verifies capacity accommodates `min_entries` at `7/8` load.
  - `max_cap` (called directly by `FlatHashMap`, `IntMap`, `FlatHashSet`, and `SortedFlatMap` constructors): Z3 proves `res >= 0`, `res >= entries_len`, and `res >= capacity`.
  - `sorted_lower_bound`, `sorted_upper_bound`, and `sorted_search` (called directly by `SortedFlatMap` for arbitrary `K : Compare`): Z3 proves loop termination, `unsafe_get` bounds safety, and exact ordering/hit/miss postconditions.
- **Differential & collision tests**: Both `FlatHashMap` and `IntMap` run 15,000-step randomized differential tests against reference maps plus deterministic `H1`/`H2` collision whitebox tests covering tombstone churn and same-capacity tombstone compaction (`flat_map/flat_map_wbtest.mbt`, `flat_map/int_map_wbtest.mbt`), 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/flat_map --target all --release`.

| Benchmark | `wasm` | `wasm-gc` | `js` | `native` |
| :--- | ---: | ---: | ---: | ---: |
| `bench_int_map_insert_1000` | `9.80 µs` | `6.30 µs` | `9.09 µs` | `6.22 µs` |
| `bench_int_map_hit_1000` | `5.22 µs` | `3.15 µs` | `2.73 µs` | `1.99 µs` |
| `bench_int_map_miss_1000` | `5.97 µs` | `4.33 µs` | `2.16 µs` | `2.69 µs` |
| `bench_flat_hash_map_insert_1000` | `12.73 µs` | `8.54 µs` | `9.45 µs` | `6.37 µs` |
| `bench_core_hashmap_insert_1000` | `28.86 µs` | `7.70 µs` | `9.68 µs` | `9.13 µs` |
| `bench_flat_hash_map_hit_1000` | `7.82 µs` | `4.66 µs` | `4.20 µs` | `2.90 µs` |
| `bench_core_hashmap_hit_1000` | `6.47 µs` | `4.61 µs` | `4.01 µs` | `2.45 µs` |
| `bench_flat_hash_map_miss_1000` | `7.73 µs` | `6.91 µs` | `3.53 µs` | `3.42 µs` |
| `bench_core_hashmap_miss_1000` | `11.40 µs` | `2.85 µs` | `3.02 µs` | `2.56 µs` |
| `bench_sorted_flat_map_get_128` | `1.09 µs` | `912.80 ns` | `1.07 µs` | `651.38 ns` |
| `bench_core_sorted_map_get_128` | `1.89 µs` | `698.14 ns` | `810.18 ns` | `825.67 ns` |

### Takeaways & Guidance

- **`IntMap` vs `FlatHashMap`**: Removing generic `Hash`/`Eq` dispatch makes `IntMap` faster than `FlatHashMap` across the 4 backends (`js` hit **1.54×**, `wasm` hit **1.50×**, `wasm-gc` hit **1.48×**, `native` hit **1.46×**). Use `IntMap` whenever keys are `Int32`.
- **Compared to `core/hashmap`**:
  - **Insert (`1000` keys)**: Single-probe `IntMap` beats `core/hashmap` across the 4 targets — **`wasm` 2.94×**, **`native` 1.47×**, **`wasm-gc` 1.22×**, **`js` 1.06×**. `FlatHashMap` beats `core/hashmap` on **`wasm` 2.27×**, **`native` 1.43×**, and **`js` 1.02×**.
  - **Hit (`1000` keys)**: `IntMap` beats `core/hashmap` across the 4 targets — **`js` 1.47×** (`2.73 µs` vs `4.01 µs`), **`wasm-gc` 1.46×** (`3.15 µs` vs `4.61 µs`), **`wasm` 1.24×** (`5.22 µs` vs `6.47 µs`), and **`native` 1.23×** (`1.99 µs` vs `2.45 µs`, sub-2 ns/lookup).
  - **Miss (`1000` keys)**: `IntMap` beats `core/hashmap` on **`wasm` 1.91×** and **`js` 1.40×** (`2.16 µs` vs `3.02 µs`); `FlatHashMap` beats `core/hashmap` on **`wasm` 1.47×**.
- **`SortedFlatMap`**: Beats `core/sorted_map` by **1.73×** on `wasm` (`1.09 µs` vs `1.89 µs`) and **1.27×** on `native` (`651.38 ns` vs `825.67 ns`) for 128-key ordered lookup with formally verified binary search and minimal contiguous `FixedArray` footprint; for write-heavy larger ordered maps, use `ihb2032/tervyx/btree`.
