docs: add arena allocation research
f3af9036447e25cdd73cab5e7fb8321828346a5e
Oliver Jan Krylow <oliver@bugabinga.net> ·
SSH signature · not checked
- Parent 1: a75810ccfb11
There are many coding harnesses - but this one is fast
f3af9036447e25cdd73cab5e7fb8321828346a5e
Oliver Jan Krylow <oliver@bugabinga.net> ·
SSH signature · not checked
+462 / −0 text lines
new file mode 100644+223 / −0 text lines
# Arena Allocation Research**Date:** 2026-05-23 **Status:** Research notes; not requirements.## ScopeObserved arena allocation patterns relevant to a Rust TUI/agent runtime:- phase-local allocation,- cyclic/self-referential data,- handle/index arenas,- bump allocation crates,- virtual-memory linear arenas.## Sources| Source | Kind | Notes ||--------|------|-------|| Manish Goregaokar, “Arenas in Rust” | article | Rust lifetime model, `bumpalo`, `typed-arena`, self-referential arenas, destructor/drop-check caveats || LogRocket, “Guide to using arenas in Rust” | article | General arena model, common Rust crates, games/compilers/web-request examples || Russell Winder, “Arenas in Rust” | article | Handle arenas as deterministic, bounds-checked replacement for pointer graphs || `github.com/fitzgen/bumpalo` | repo | Mature bump allocator, MIT/Apache-2.0, current clone `84654ace6be4444da3ff102a0a0af3b38c4df4fb` || `github.com/emoon/arena-allocator` | repo | Virtual-memory linear allocator, MIT/Apache-2.0, current clone `266fd1f90c430523b08b7b76bb4ea43fd93c5896` || crates.io API | metadata | Version/download comparison for arena-related crates |Local research cache:- `~/.pi/research/pages/manishearth.github.io.blog.2021-03-15.arenas-in-rust.html`- `~/.pi/research/pages/blog.logrocket.com.guide-using-arenas-rust.html`- `~/.pi/research/pages/russellw.github.io.arenas.html`- `~/.pi/research/repos/github.com.fitzgen.bumpalo/`- `~/.pi/research/repos/github.com.emoon.arena-allocator/`## Core modelArena allocation groups many allocations under one lifetime/phase. Fast path:1. reserve/chunk memory,2. keep next-free pointer,3. allocate by pointer bump + alignment,4. free/reset whole group.Observed benefits:- fewer global allocator calls,- lower allocator/syscall pressure,- cheap mass deallocation,- stable post-warmup memory profile when capacity is reused,- bounded phase-local scratch capacity,- better locality for phase-local objects,- simpler cyclic structures if all participants die together.Observed costs:- no normal individual deallocation,- reset invalidates everything,- destructors may not run,- wrong lifetime boundary creates leaks or use-after-reset bugs,- direct references are poor persistence boundaries.## Rust patterns### 1. Bump arena (`bumpalo`)Observed properties:- heterogeneous allocation via `Bump::alloc`,- `reset(&mut self)` frees all arena allocations en masse,- `Bump::with_capacity`/`try_with_capacity` support pre-sizing,- optional `collections` feature provides arena-backed `Vec`, `String`, etc.,- optional `boxed` feature runs `Drop` for wrapped values,- no `Drop` for plain `Bump::alloc` values,- `Bump` is `!Sync`,- stable Rust supported; crate is `no_std` by default.Good fit candidates:- per-render scratch strings/vectors,- temporary markdown/syntax/diff formatting buffers,- one-turn provider request assembly,- transient plugin/layout intermediate trees.Bad fit candidates:- persisted session entries,- values owning files/sockets/mmap unless explicitly dropped,- cross-thread shared state,- long-lived cyclic state with meaningful destructors.### 2. Typed reference arena (`typed-arena`-style)Observed properties:- one type per arena,- references can form cycles through interior mutability,- destructors normally run when arena drops,- cycles + custom destructors become borrow-check/drop-check hazards.Candidate use is narrow. Direct arena references fight persistence, replay, and CBOR. Smith-like trees should prefer stable IDs/indices over `&'arena T` links.### 3. Handle/index arena (`id_arena`, `generational-arena`, `slotmap`-style)Observed properties:- objects live in a vector/map,- links are handles/indices/keys, not references,- cycles are easy,- bugs remain deterministic bounds/key errors, not arbitrary memory corruption,- generational handles detect stale keys after deletion.Good fit candidates:- ephemeral graph structures,- layout/widget tree construction,- session DAG in memory if handles are separate from persisted IDs,- plugin registry graphs.Bad fit candidates:- persistent storage unless handle ↔ stable ID mapping is explicit,- generational arenas when deletion is not required.For append-only immutable branches, plain `Vec<Entry>` + stable `EntryId` + parent index/map may beat a full arena crate.### 4. Virtual-memory linear arena (`arena-allocator`)Observed properties:- reserves large virtual address ranges,- commits/decommits pages on demand,- `rewind` invalidates previous allocations,- debug mode uses memory protection to catch use-after-rewind,- API exposes unsafe allocation and safe methods that can invalidate prior returned references,- implementation uses OS-specific unsafe code and `unwrap` in drop/protection paths,- crate is young (`0.1.0`) with very low crates.io usage relative to `bumpalo`.Fit for Smith: poor. Too sharp, too low-level, too much unsafe surface for current needs.## Crate metadata snapshotFetched 2026-05-23 from crates.io API.| Crate | Latest | Total downloads | Recent downloads | Repository ||-------|--------|-----------------|------------------|------------|| `bumpalo` | 3.20.3 | 397,043,585 | 93,582,712 | `github.com/fitzgen/bumpalo` || `slotmap` | 1.1.1 | 71,614,488 | 17,195,183 | `github.com/orlp/slotmap` || `id-arena` | 2.3.0 | 63,434,687 | 37,055,795 | `github.com/fitzgen/id-arena` || `typed-arena` | 2.0.2 | 61,546,744 | 11,142,653 | `github.com/SimonSapin/rust-typed-arena` || `elsa` | 1.11.2 | 14,198,162 | 2,347,949 | `github.com/manishearth/elsa` || `generational-arena` | 0.2.9 | 8,561,359 | 1,117,475 | `github.com/fitzgen/generational-arena` || `arena-allocator` | 0.1.0 | 1,485 | 57 | `github.com/emoon/arena-allocator` |## Smith-specific candidatesCandidates, not mandates:1. Default to normal Rust ownership until profiling finds allocation pressure, allocator-call pressure, or unstable memory profile.2. For scratch phase allocation, evaluate `bumpalo` first.3. Judge arenas on allocator calls, elapsed time, RSS/peak-live stability, reset cadence, and complexity — not only allocation-count reduction.4. For cyclic in-memory graphs, evaluate handles/indices before direct references.5. For persisted/session structures, keep stable IDs as primary identity; do not persist arena handles.6. Avoid custom arenas and virtual-memory arenas unless a measured workload demands them.7. Avoid arena-stored values with important `Drop` behavior unless teardown is explicit.Plugin heap limits are related but distinct: `mlua::Lua` has VM memory accountingand `set_memory_limit`. That should be tested as Lua heap quota enforcement, notas a Rust arena allocation strategy.Plugin reload/unload is a strong arena/domain use case. A plugin instance can owna whole memory/resource domain: Lua state, registry handles, descriptors, rendercaches, subscriptions, async cancellation token, and host-side scratch arena.Reload becomes whole-domain replacement instead of per-resource cleanup. The hardpart is preventing escapes: callbacks, async tasks, event subscriptions, and hostregistry entries must not outlive their domain.Likely no-go cases:- storing session history in a bump arena,- returning arena references across async/task/thread boundaries,- using direct `&'arena` links in serializable data,- relying on reset while external refs may still exist,- adding project-local unsafe arena code under current invariants.## Edge cases found- `Drop` + cyclic arena references can fail borrow checking or become logically invalid during destruction.- `bumpalo` plain allocations intentionally skip destructors.- `bumpalo::boxed::Box<T>` runs `Drop`, but boxed values should not participate in cycles.- `Bump::reset` needs `&mut self`; this is good because active borrows block reset.- `Bump` is not `Sync`; use per-thread arenas or a pool if ever needed.- Stable Rust `std` allocator parameterization is still incomplete; `bumpalo::collections` or `allocator-api2` fills the gap.- Handle arenas solve cycles but not semantic validity; stale/mismatched handles still need domain checks.- Virtual-memory arenas can turn lifetime mistakes into use-after-rewind bugs; debug protection catches some, release may not.## Benchmark questionsMeasure before adopting:- render-loop allocations per 16ms tick,- markdown/syntax-highlight/diff allocation hot spots,- session load/replay allocation volume,- provider request construction copies,- Lua bridge allocations and conversion costs,- arena reset cadence and max live bytes per phase.Minimal benchmark shape:- compare baseline `Vec`/`String` vs `bumpalo` scratch buffers,- record allocations with a counting allocator,- include TUI TestBackend render snapshots,- include one large session replay,- include one pathological markdown/diff render.## Working conclusionArena allocation is useful only at phase boundaries. Smith has obvious phase boundaries in render ticks, provider-request assembly, and temporary parsing/rendering. Smith's persistent/session model should remain ID/Vec based, not arena-reference based.Best first experiment if needed: `bumpalo` for scratch allocation. Best graph shape: handles/indices + stable IDs. Avoid: virtual-memory linear arenas and custom unsafe arenas.new file mode 100644+237 / −0 text lines
# Smith Memory Allocation Profile Estimate**Date:** 2026-05-23 **Status:** Estimate from `docs/SPEC.md` + local Pi JSONL session metadata. No session content quoted.## MethodInputs:- Smith SPEC: session model, CBOR append log, agent events, virtual scrolling, TUI widgets, provider request assembly.- Pi sessions under `/home/me/.local/state/pi/sessions` treated as if they were Smith sessions.- Analysis read JSONL structure and string lengths only; no content was copied into this document.Pi corpus:- sessions: 535,- date span observed in filenames: 37 active days,- total JSONL bytes: 414,521,993 B ≈ 395.3 MiB,- bad JSONL lines: 0.## Session size distribution| Metric | p50 | p75 | p90 | p95 | p99 | max | mean ||--------|----:|----:|----:|----:|----:|----:|-----:|| file bytes | 88 KiB | 683 KiB | 1.5 MiB | 3.1 MiB | 9.2 MiB | 29.2 MiB | 757 KiB || entries/lines | 36 | 211 | 559 | 822 | 1,930 | 5,157 | 195 || string chars | 76k | 582k | 1.4M | 2.8M | 8.0M | 27.2M | 649k || duration | 3.0 min | 63 min | 4.5 h | 15.6 h | 40.9 h | 98.1 h | 2.4 h |Large-session counts:- ≥1 MB: 101 sessions,- ≥5 MB: 18 sessions,- ≥10 MB: 5 sessions.Busiest observed day: 87 new sessions.## Entry mixGlobal entry counts:| Entry type | Count ||------------|------:|| `message` | 101,003 || `model_change` | 808 || `thinking_level_change` | 578 || `custom` | 555 || `session` | 535 || `custom_message` | 342 || `session_info` | 317 || `compaction` | 131 |Message roles:| Role | Count | Total chars | Mean chars/message ||------|------:|------------:|-------------------:|| `toolResult` | 49,149 | 142,292,078 | 2,895 || `assistant` | 47,079 | 83,687,447 | 1,778 || `user` | 4,624 | 1,401,645 | 303 || `bashExecution` | 157 | 0 | 0 |Content block counts:| Block | Count ||-------|------:|| `text` | 63,967 || `toolCall` | 49,337 || `thinking` | 28,977 || `image` | 44 |Per-message payloads:| Metric | p50 | p75 | p90 | p95 | p99 | max | mean ||--------|----:|----:|----:|----:|----:|----:|-----:|| JSONL bytes/message | 1.1 KiB | 2.9 KiB | 5.8 KiB | 10.2 KiB | 46.6 KiB | 4.6 MiB | 4.0 KiB || chars/message | 503 | 2,230 | 4,848 | 8,666 | 30,905 | 540,641 | 2,251 || blocks/message | 1 | 2 | 2 | 2 | 4 | 140 | 1.4 |## Compaction observations- Sessions with compaction: 63 / 535.- Compactions/session: p50 0, p90 1, p99 5, max 11.- `tokensBefore`: p50 247k, p75 266k, p90 272k, p95 277k, max 282k.Implication: allocation stress clusters around long sessions near context-window limits, not normal short sessions.## Estimated Smith persistent storageSmith stores length-prefixed CBOR, not JSONL. Rough storage estimate:- JSON key overhead disappears/reduces strongly in CBOR,- text/tool output bytes remain dominant,- expected CBOR session size ≈ 60–85% of Pi JSONL size for text-heavy entries,- corpus would likely be ≈ 237–336 MiB as CBOR instead of 395 MiB JSONL.Worst observed Pi session as Smith CBOR:- file: ≈ 18–25 MiB,- in-memory loaded session: ≈ 30–45 MiB depending on `String` capacity, `Vec` overhead, indexes, and cached render state.Typical Smith loaded session:- p50: < 1 MiB resident,- p75: 1–2 MiB resident,- p95: 4–8 MiB resident,- p99: 12–20 MiB resident.Loading every session fully would be wasteful: estimated resident memory ≈ 0.7–1.2 GiB. Smith should index metadata lazily and load only active/replayed sessions.## Allocation hot spots by subsystem### Session load/replayExpected allocations:- one `Vec<SessionEntry>` growth per loaded session,- one `String` allocation per content block / id / metadata text,- parent/child indexes (`HashMap<EntryId, usize>`, child lists),- preservation buffers for unknown future entries.Dominant bytes: tool results and assistant/thinking text, not entry structs.Candidate optimization:- pre-size entries from frame count where possible,- intern repeated provider/model/tool names only if measured,- lazy decode large content blocks for history browsing if necessary,- keep session discovery metadata separate from full session load.Arena fit: poor for persisted entries. Sessions need stable IDs, replay, unknown-entry preservation, and long lifetimes.### Provider request constructionExpected allocations:- select context entries,- clone/transform message text and tool schemas into provider request shape,- secret proxy scan/replace may allocate rewritten strings,- JSON tool args/definitions allocate maps/strings.Dominant bytes: selected context window, often 100k–300k tokens near compaction.Arena fit: possible for temporary request assembly only if provider API can borrow from scratch lifetime. Async stream boundary likely forces owned request data. Measure before adding arenas.### TUI render / virtual scrollExpected allocations:- visible-window message formatting,- markdown parse/render intermediates,- syntax highlight spans,- diff view lines/spans,- wrapped text buffers,- tool result collapsed/expanded summaries.Dominant cadence: 16ms render tick. Reallocating formatted strings/spans every tick is riskier than session storage size.Arena fit: best candidate, but only for per-frame scratch buffers and only if widgets do not retain references after frame.### Agent event streamingExpected allocations:- many small text/thinking deltas,- growing assistant message buffer,- tool-call argument accumulation,- event fanout to session/TUI/hooks.Optimization candidates:- accumulate deltas in one `String` with capacity growth,- avoid creating one session entry per tiny delta,- TUI incremental append instead of full rerender parse where possible.Arena fit: weak. Streaming state crosses awaits and event consumers.### Lua/plugin bridgeExpected allocations:- Rust ↔ Lua value conversion,- plugin hook return values,- render descriptor tables,- tool schemas/config tables.Arena fit: unlikely. mlua owns Lua values; use lifecycle/cache discipline instead.## Practical profileExpected Smith steady state:- idle TUI + current normal session: tens of MiB RSS mostly from terminal/UI/libs/Lua, not session entries,- active long session: +10–50 MiB for session + render/request buffers,- provider request at compaction threshold: temporary spike proportional to selected context, likely +20–100 MiB depending provider serialization,- pathological large tool output/render: single-line or single-message allocation can reach MiB scale.Memory policy candidates:1. Lazy-load full sessions; discovery reads only metadata.2. Never store session history in arenas.3. Benchmark render/request scratch before adding `bumpalo`.4. Put hard output-size and render-size tests in prototypes.5. Virtual scroll must bound per-frame work by visible rows, not total entries.6. Compaction/request construction needs peak-memory measurement, not only CPU timing.## Arena / allocator decision estimateArenas likely help only where allocation lifetime is phase-bounded. They do notsolve dominant persisted text bytes.Arena value is broader than allocation-count reduction:- fewer global allocator calls → lower allocator/syscall pressure,- stable peak/live memory after repeated phases,- predictable reset cadence,- bounded scratch capacity growth,- easier bulk discard of temporary render/request objects.Recommended prototype gates:- baseline must measure allocation count, allocated bytes, peak live bytes, post-warmup live-memory plateau, elapsed time, and allocator-call pressure;- use `/proc/self/statm` RSS sampling on Linux for stable-memory checks;- `bumpalo` variant only for render/request scratch;- keep/drop decision can pass by allocation reduction OR lower allocator-call pressure OR materially flatter post-warmup memory profile, without lifetime/API complexity.Plugin heap limiting is a separate allocator/control use case. `mlua::Lua`exposes `used_memory()` and `set_memory_limit(limit_bytes)`, which should beprototyped against Smith's locked `mlua + LuaJIT` feature set. This is not`bumpalo`; it is Lua VM heap quota enforcement.Plugin reload is the broader arena/domain use case. A per-plugin domain can ownLua state plus host-side plugin allocations/caches/subscriptions. Dropping thedomain on reload gives predictable reclamation and avoids bespoke cleanup graphs,provided no callback/task/registry handle can escape its domain.+2 / −0 text lines
| `bumpalo` | https://github.com/fitzgen/bumpalo | `84654ace6be4444da3ff102a0a0af3b38c4df4fb` | full shallow clone | Evaluate mature bump allocation for phase-local scratch memory || `arena-allocator` | https://github.com/emoon/arena-allocator | `266fd1f90c430523b08b7b76bb4ea43fd93c5896` | full shallow clone | Evaluate virtual-memory linear allocation risks/tradeoffs |