# `ihb2032/tervyx/slot_map` — Generational Arenas (`SlotMap` / `DenseSlotMap` / `SecondaryMap`)

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

Entity-component systems (ECS), graph/scene nodes, timer/connection handle
tables, and self-referential arenas need **`O(1)` lookup/insert/remove + compact
stable handles + ABA protection when slots are recycled + cache-friendly
iteration**. A `Map[Int32, T]` with monotonic IDs pays hashing and probing on
each lookup, while raw array indices suffer silent ABA aliasing on reuse.
`ihb2032/tervyx/slot_map` provides a complete generational arena family:

- **Cross-language design influences**:
  - **Rust (`slotmap` crate)**:
    - `@slot_map.Key`: `#valtype` immutable value handle (`idx : UInt32`, `ver : UInt32`) with zero heap boxing and derived `Eq`, `Compare`, `Hash`, and `@debug.Debug`.
    - `@slot_map.SlotMap`: Flat `FixedArray` SoA slot storage with intrusive free list (`free_head`) and `insert_with_key` for self-referential objects.
    - `@slot_map.DenseSlotMap`: Packs live keys and values into contiguous `keys_arr` / `vals_arr` arrays with `swap-remove`, eliminating hole scanning under heavy fragmentation.
    - `@slot_map.SecondaryMap`: SoA auxiliary property map keyed by `Key` handles minted by a primary `SlotMap` or `DenseSlotMap`, independently checking generational versions.
  - **OCaml (`update`) / Rust (`retain`, `extract_if`) / Go (`append_to`, `drain_into`)**: Unified across the 3 arena types (see [api_conventions.md](../api_conventions.md)).
- **Rejected alternatives**:
  - **Per-slot heap `Slot[T]` structs with `Option[T]`**: Replaced by flat Structure-of-Arrays (SoA) buffers + `UninitializedArray[T]`, removing both per-slot heap object indirection and redundant `Option` tagging.

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

- **Flat `FixedArray` SoA + `UninitializedArray[T]` (zero per-slot heap structs, zero `Array` wrapper indirection on `SlotMap`, zero `Option` wrapping)**:
  - `SlotMap[T]` stores flat `vers : FixedArray[UInt32]`, `next_free : FixedArray[Int32]`, `vals : UninitializedArray[T]`, and a direct `slot_len : Int32` field (unified single growth check on insert, removing `Array` header indirection on every `get`, `set`, `remove`, and iterator step).
  - `DenseSlotMap[T]` stores `vers : Array[UInt32]`, `pos_or_next : Array[Int32]`, `keys_arr : Array[Key]`, and `vals_arr : Array[T]`.
  - `SecondaryMap[T]` stores `vers : Array[UInt32]` and `vals : UninitializedArray[T]`.
  - On `clear()` and `drain_into()`, `SlotMap` and `SecondaryMap` replace `vals` with a fresh `UninitializedArray::make(...)` so cleared objects become immediately GC-eligible.
- **Odd/even generation encoding & direct bounds checks**: Live slots hold odd non-zero versions (`1U, 3U, 5U, ...`), free slots hold even versions, and `Key::null()` uses `ver == 0U`. `SlotMap::alloc_slot` returns `#valtype Key` directly (zero `(Int32, UInt32)` tuple allocation on insert), and `SlotMap` validates `idx >= 0 && idx < self.slot_len` directly against the `slot_len` field before unchecked indexing. Iterators (`values`, `keys`, `iter`) hoist backing references and use dedicated loops so `SecondaryMap::keys` / `SecondaryMap::values` avoid `(Key, T)` tuple allocation.
- **`SlotMap` vs `DenseSlotMap`**:
  - Prefer `SlotMap` for lowest point-lookup latency (`get`/`set`/`update`) when fragmentation is modest.
  - Prefer `DenseSlotMap` when iteration over heavily fragmented tables dominates.

## 3. Invariants & Formal Verification

- **Colocated Why3/Z3 formal verification (`slot_map/key.mbt`, `slot_map/slot_map.mbt` + `slot_map/proof.mbtp`, `proof_enabled = true`)**:
  - `Key::null`, `Key::is_null`, `Key::version`: Public method contracts proved directly by Z3, establishing sentinel nullness (`ver == 0U && idx == 0U`) and version observation semantics.
  - `clamp_nonneg` (called directly by `SlotMap`, `DenseSlotMap`, and `SecondaryMap` constructors): Z3 proves negative capacities clamp safely to `0`.
  - Scope note: `SlotMap`, `DenseSlotMap`, and `SecondaryMap` contain `mut` fields (outside `moonc-prove 1.0.0-rc1` support); full generational lifecycle, ABA rejection, `DenseSlotMap` swap-remove, and `SecondaryMap` synchronization are covered by 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/slot_map --target all --release`.

| Benchmark | `wasm` | `wasm-gc` | `js` | `native` |
| :--- | ---: | ---: | ---: | ---: |
| `bench_slot_map_lookup_1000` | `2.09 µs` | `1.57 µs` | `2.75 µs` | `732.22 ns` |
| `bench_core_map_int_lookup_1000` | `5.70 µs` | `3.59 µs` | `4.18 µs` | `2.53 µs` |
| `bench_dense_slot_map_iter_fragmented_1000` | `1.88 µs` | `1.77 µs` | `1.46 µs` | `813.27 ns` |
| `bench_slot_map_iter_fragmented_1000` | `2.65 µs` | `1.88 µs` | `2.43 µs` | `1.12 µs` |
| `bench_core_map_iter_fragmented_1000` | `13.49 µs` | `2.47 µs` | `2.62 µs` | `3.90 µs` |

### Takeaways & Guidance

- **1000 random lookups**: Flat `FixedArray` `SlotMap` outperforms `core/Map[Int32, V]` across the 4 backends — **`native` 3.46×** (`732.22 ns`, `0.73 ns`/lookup), **`wasm` 2.73×**, **`wasm-gc` 2.29×**, **`js` 1.52×**.
- **Fragmented iteration (50% deleted)**: `DenseSlotMap` is fastest across the 4 backends — **`wasm` 7.18×**, **`native` 4.80×**, **`js` 1.79×**, **`wasm-gc` 1.40×** vs `core/Map`; flat `FixedArray` `SlotMap` iteration also beats `core/Map` across the 4 targets (**`wasm` 5.09×**, **`native` 3.48×**, **`wasm-gc` 1.31×**, **`js` 1.08×**).
