repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

docs: add arena allocation research

f3af9036447e25cdd73cab5e7fb8321828346a5e

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (3)

+462 / −0 text lines

Diff layout

docs/research/ARENA-ALLOCATION-RESEARCH.md

Added
new file mode 100644

+223 / −0 text lines

1# Arena Allocation Research
2
3**Date:** 2026-05-23
4**Status:** Research notes; not requirements.
5
6## Scope
7
8Observed arena allocation patterns relevant to a Rust TUI/agent runtime:
9
10- phase-local allocation,
11- cyclic/self-referential data,
12- handle/index arenas,
13- bump allocation crates,
14- virtual-memory linear arenas.
16## Sources
18| Source | Kind | Notes |
19|--------|------|-------|
20| Manish Goregaokar, “Arenas in Rust” | article | Rust lifetime model, `bumpalo`, `typed-arena`, self-referential arenas, destructor/drop-check caveats |
21| LogRocket, “Guide to using arenas in Rust” | article | General arena model, common Rust crates, games/compilers/web-request examples |
22| Russell Winder, “Arenas in Rust” | article | Handle arenas as deterministic, bounds-checked replacement for pointer graphs |
23| `github.com/fitzgen/bumpalo` | repo | Mature bump allocator, MIT/Apache-2.0, current clone `84654ace6be4444da3ff102a0a0af3b38c4df4fb` |
24| `github.com/emoon/arena-allocator` | repo | Virtual-memory linear allocator, MIT/Apache-2.0, current clone `266fd1f90c430523b08b7b76bb4ea43fd93c5896` |
25| crates.io API | metadata | Version/download comparison for arena-related crates |
27Local research cache:
29- `~/.pi/research/pages/manishearth.github.io.blog.2021-03-15.arenas-in-rust.html`
30- `~/.pi/research/pages/blog.logrocket.com.guide-using-arenas-rust.html`
31- `~/.pi/research/pages/russellw.github.io.arenas.html`
32- `~/.pi/research/repos/github.com.fitzgen.bumpalo/`
33- `~/.pi/research/repos/github.com.emoon.arena-allocator/`
35## Core model
37Arena allocation groups many allocations under one lifetime/phase. Fast path:
391. reserve/chunk memory,
402. keep next-free pointer,
413. allocate by pointer bump + alignment,
424. free/reset whole group.
44Observed benefits:
46- fewer global allocator calls,
47- lower allocator/syscall pressure,
48- cheap mass deallocation,
49- stable post-warmup memory profile when capacity is reused,
50- bounded phase-local scratch capacity,
51- better locality for phase-local objects,
52- simpler cyclic structures if all participants die together.
54Observed costs:
56- no normal individual deallocation,
57- reset invalidates everything,
58- destructors may not run,
59- wrong lifetime boundary creates leaks or use-after-reset bugs,
60- direct references are poor persistence boundaries.
62## Rust patterns
64### 1. Bump arena (`bumpalo`)
66Observed properties:
68- heterogeneous allocation via `Bump::alloc`,
69- `reset(&mut self)` frees all arena allocations en masse,
70- `Bump::with_capacity`/`try_with_capacity` support pre-sizing,
71- optional `collections` feature provides arena-backed `Vec`, `String`, etc.,
72- optional `boxed` feature runs `Drop` for wrapped values,
73- no `Drop` for plain `Bump::alloc` values,
74- `Bump` is `!Sync`,
75- stable Rust supported; crate is `no_std` by default.
77Good fit candidates:
79- per-render scratch strings/vectors,
80- temporary markdown/syntax/diff formatting buffers,
81- one-turn provider request assembly,
82- transient plugin/layout intermediate trees.
84Bad fit candidates:
86- persisted session entries,
87- values owning files/sockets/mmap unless explicitly dropped,
88- cross-thread shared state,
89- long-lived cyclic state with meaningful destructors.
91### 2. Typed reference arena (`typed-arena`-style)
93Observed properties:
95- one type per arena,
96- references can form cycles through interior mutability,
97- destructors normally run when arena drops,
98- cycles + custom destructors become borrow-check/drop-check hazards.
100Candidate use is narrow. Direct arena references fight persistence, replay, and CBOR. Smith-like trees should prefer stable IDs/indices over `&'arena T` links.
102### 3. Handle/index arena (`id_arena`, `generational-arena`, `slotmap`-style)
104Observed properties:
106- objects live in a vector/map,
107- links are handles/indices/keys, not references,
108- cycles are easy,
109- bugs remain deterministic bounds/key errors, not arbitrary memory corruption,
110- generational handles detect stale keys after deletion.
112Good fit candidates:
114- ephemeral graph structures,
115- layout/widget tree construction,
116- session DAG in memory if handles are separate from persisted IDs,
117- plugin registry graphs.
119Bad fit candidates:
121- persistent storage unless handle ↔ stable ID mapping is explicit,
122- generational arenas when deletion is not required.
124For append-only immutable branches, plain `Vec<Entry>` + stable `EntryId` + parent index/map may beat a full arena crate.
126### 4. Virtual-memory linear arena (`arena-allocator`)
128Observed properties:
130- reserves large virtual address ranges,
131- commits/decommits pages on demand,
132- `rewind` invalidates previous allocations,
133- debug mode uses memory protection to catch use-after-rewind,
134- API exposes unsafe allocation and safe methods that can invalidate prior returned references,
135- implementation uses OS-specific unsafe code and `unwrap` in drop/protection paths,
136- crate is young (`0.1.0`) with very low crates.io usage relative to `bumpalo`.
138Fit for Smith: poor. Too sharp, too low-level, too much unsafe surface for current needs.
140## Crate metadata snapshot
142Fetched 2026-05-23 from crates.io API.
144| Crate | Latest | Total downloads | Recent downloads | Repository |
145|-------|--------|-----------------|------------------|------------|
146| `bumpalo` | 3.20.3 | 397,043,585 | 93,582,712 | `github.com/fitzgen/bumpalo` |
147| `slotmap` | 1.1.1 | 71,614,488 | 17,195,183 | `github.com/orlp/slotmap` |
148| `id-arena` | 2.3.0 | 63,434,687 | 37,055,795 | `github.com/fitzgen/id-arena` |
149| `typed-arena` | 2.0.2 | 61,546,744 | 11,142,653 | `github.com/SimonSapin/rust-typed-arena` |
150| `elsa` | 1.11.2 | 14,198,162 | 2,347,949 | `github.com/manishearth/elsa` |
151| `generational-arena` | 0.2.9 | 8,561,359 | 1,117,475 | `github.com/fitzgen/generational-arena` |
152| `arena-allocator` | 0.1.0 | 1,485 | 57 | `github.com/emoon/arena-allocator` |
154## Smith-specific candidates
156Candidates, not mandates:
1581. Default to normal Rust ownership until profiling finds allocation pressure,
159 allocator-call pressure, or unstable memory profile.
1602. For scratch phase allocation, evaluate `bumpalo` first.
1613. Judge arenas on allocator calls, elapsed time, RSS/peak-live stability, reset
162 cadence, and complexity — not only allocation-count reduction.
1634. For cyclic in-memory graphs, evaluate handles/indices before direct references.
1645. For persisted/session structures, keep stable IDs as primary identity; do not persist arena handles.
1656. Avoid custom arenas and virtual-memory arenas unless a measured workload demands them.
1667. Avoid arena-stored values with important `Drop` behavior unless teardown is explicit.
168Plugin heap limits are related but distinct: `mlua::Lua` has VM memory accounting
169and `set_memory_limit`. That should be tested as Lua heap quota enforcement, not
170as a Rust arena allocation strategy.
172Plugin reload/unload is a strong arena/domain use case. A plugin instance can own
173a whole memory/resource domain: Lua state, registry handles, descriptors, render
174caches, subscriptions, async cancellation token, and host-side scratch arena.
175Reload becomes whole-domain replacement instead of per-resource cleanup. The hard
176part is preventing escapes: callbacks, async tasks, event subscriptions, and host
177registry entries must not outlive their domain.
179Likely no-go cases:
181- storing session history in a bump arena,
182- returning arena references across async/task/thread boundaries,
183- using direct `&'arena` links in serializable data,
184- relying on reset while external refs may still exist,
185- adding project-local unsafe arena code under current invariants.
187## Edge cases found
189- `Drop` + cyclic arena references can fail borrow checking or become logically invalid during destruction.
190- `bumpalo` plain allocations intentionally skip destructors.
191- `bumpalo::boxed::Box<T>` runs `Drop`, but boxed values should not participate in cycles.
192- `Bump::reset` needs `&mut self`; this is good because active borrows block reset.
193- `Bump` is not `Sync`; use per-thread arenas or a pool if ever needed.
194- Stable Rust `std` allocator parameterization is still incomplete; `bumpalo::collections` or `allocator-api2` fills the gap.
195- Handle arenas solve cycles but not semantic validity; stale/mismatched handles still need domain checks.
196- Virtual-memory arenas can turn lifetime mistakes into use-after-rewind bugs; debug protection catches some, release may not.
198## Benchmark questions
200Measure before adopting:
202- render-loop allocations per 16ms tick,
203- markdown/syntax-highlight/diff allocation hot spots,
204- session load/replay allocation volume,
205- provider request construction copies,
206- Lua bridge allocations and conversion costs,
207- arena reset cadence and max live bytes per phase.
209Minimal benchmark shape:
211- compare baseline `Vec`/`String` vs `bumpalo` scratch buffers,
212- record allocations with a counting allocator,
213- include TUI TestBackend render snapshots,
214- include one large session replay,
215- include one pathological markdown/diff render.
217## Working conclusion
219Arena 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.
221Best first experiment if needed: `bumpalo` for scratch allocation.
222Best graph shape: handles/indices + stable IDs.
223Avoid: virtual-memory linear arenas and custom unsafe arenas.

docs/research/SMITH-MEMORY-ALLOCATION-PROFILE.md

Added
new file mode 100644

+237 / −0 text lines

1# Smith Memory Allocation Profile Estimate
2
3**Date:** 2026-05-23
4**Status:** Estimate from `docs/SPEC.md` + local Pi JSONL session metadata. No session content quoted.
5
6## Method
7
8Inputs:
9
10- Smith SPEC: session model, CBOR append log, agent events, virtual scrolling, TUI widgets, provider request assembly.
11- Pi sessions under `/home/me/.local/state/pi/sessions` treated as if they were Smith sessions.
12- Analysis read JSONL structure and string lengths only; no content was copied into this document.
14Pi corpus:
16- sessions: 535,
17- date span observed in filenames: 37 active days,
18- total JSONL bytes: 414,521,993 B ≈ 395.3 MiB,
19- bad JSONL lines: 0.
21## Session size distribution
23| Metric | p50 | p75 | p90 | p95 | p99 | max | mean |
24|--------|----:|----:|----:|----:|----:|----:|-----:|
25| file bytes | 88 KiB | 683 KiB | 1.5 MiB | 3.1 MiB | 9.2 MiB | 29.2 MiB | 757 KiB |
26| entries/lines | 36 | 211 | 559 | 822 | 1,930 | 5,157 | 195 |
27| string chars | 76k | 582k | 1.4M | 2.8M | 8.0M | 27.2M | 649k |
28| duration | 3.0 min | 63 min | 4.5 h | 15.6 h | 40.9 h | 98.1 h | 2.4 h |
30Large-session counts:
32- ≥1 MB: 101 sessions,
33- ≥5 MB: 18 sessions,
34- ≥10 MB: 5 sessions.
36Busiest observed day: 87 new sessions.
38## Entry mix
40Global entry counts:
42| Entry type | Count |
43|------------|------:|
44| `message` | 101,003 |
45| `model_change` | 808 |
46| `thinking_level_change` | 578 |
47| `custom` | 555 |
48| `session` | 535 |
49| `custom_message` | 342 |
50| `session_info` | 317 |
51| `compaction` | 131 |
53Message roles:
55| Role | Count | Total chars | Mean chars/message |
56|------|------:|------------:|-------------------:|
57| `toolResult` | 49,149 | 142,292,078 | 2,895 |
58| `assistant` | 47,079 | 83,687,447 | 1,778 |
59| `user` | 4,624 | 1,401,645 | 303 |
60| `bashExecution` | 157 | 0 | 0 |
62Content block counts:
64| Block | Count |
65|-------|------:|
66| `text` | 63,967 |
67| `toolCall` | 49,337 |
68| `thinking` | 28,977 |
69| `image` | 44 |
71Per-message payloads:
73| Metric | p50 | p75 | p90 | p95 | p99 | max | mean |
74|--------|----:|----:|----:|----:|----:|----:|-----:|
75| JSONL bytes/message | 1.1 KiB | 2.9 KiB | 5.8 KiB | 10.2 KiB | 46.6 KiB | 4.6 MiB | 4.0 KiB |
76| chars/message | 503 | 2,230 | 4,848 | 8,666 | 30,905 | 540,641 | 2,251 |
77| blocks/message | 1 | 2 | 2 | 2 | 4 | 140 | 1.4 |
79## Compaction observations
81- Sessions with compaction: 63 / 535.
82- Compactions/session: p50 0, p90 1, p99 5, max 11.
83- `tokensBefore`: p50 247k, p75 266k, p90 272k, p95 277k, max 282k.
85Implication: allocation stress clusters around long sessions near context-window limits, not normal short sessions.
87## Estimated Smith persistent storage
89Smith stores length-prefixed CBOR, not JSONL. Rough storage estimate:
91- JSON key overhead disappears/reduces strongly in CBOR,
92- text/tool output bytes remain dominant,
93- expected CBOR session size ≈ 60–85% of Pi JSONL size for text-heavy entries,
94- corpus would likely be ≈ 237–336 MiB as CBOR instead of 395 MiB JSONL.
96Worst observed Pi session as Smith CBOR:
98- file: ≈ 18–25 MiB,
99- in-memory loaded session: ≈ 30–45 MiB depending on `String` capacity, `Vec` overhead, indexes, and cached render state.
101Typical Smith loaded session:
103- p50: < 1 MiB resident,
104- p75: 1–2 MiB resident,
105- p95: 4–8 MiB resident,
106- p99: 12–20 MiB resident.
108Loading 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.
110## Allocation hot spots by subsystem
112### Session load/replay
114Expected allocations:
116- one `Vec<SessionEntry>` growth per loaded session,
117- one `String` allocation per content block / id / metadata text,
118- parent/child indexes (`HashMap<EntryId, usize>`, child lists),
119- preservation buffers for unknown future entries.
121Dominant bytes: tool results and assistant/thinking text, not entry structs.
123Candidate optimization:
125- pre-size entries from frame count where possible,
126- intern repeated provider/model/tool names only if measured,
127- lazy decode large content blocks for history browsing if necessary,
128- keep session discovery metadata separate from full session load.
130Arena fit: poor for persisted entries. Sessions need stable IDs, replay, unknown-entry preservation, and long lifetimes.
132### Provider request construction
134Expected allocations:
136- select context entries,
137- clone/transform message text and tool schemas into provider request shape,
138- secret proxy scan/replace may allocate rewritten strings,
139- JSON tool args/definitions allocate maps/strings.
141Dominant bytes: selected context window, often 100k–300k tokens near compaction.
143Arena 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.
145### TUI render / virtual scroll
147Expected allocations:
149- visible-window message formatting,
150- markdown parse/render intermediates,
151- syntax highlight spans,
152- diff view lines/spans,
153- wrapped text buffers,
154- tool result collapsed/expanded summaries.
156Dominant cadence: 16ms render tick. Reallocating formatted strings/spans every tick is riskier than session storage size.
158Arena fit: best candidate, but only for per-frame scratch buffers and only if widgets do not retain references after frame.
160### Agent event streaming
162Expected allocations:
164- many small text/thinking deltas,
165- growing assistant message buffer,
166- tool-call argument accumulation,
167- event fanout to session/TUI/hooks.
169Optimization candidates:
171- accumulate deltas in one `String` with capacity growth,
172- avoid creating one session entry per tiny delta,
173- TUI incremental append instead of full rerender parse where possible.
175Arena fit: weak. Streaming state crosses awaits and event consumers.
177### Lua/plugin bridge
179Expected allocations:
181- Rust ↔ Lua value conversion,
182- plugin hook return values,
183- render descriptor tables,
184- tool schemas/config tables.
186Arena fit: unlikely. mlua owns Lua values; use lifecycle/cache discipline instead.
188## Practical profile
190Expected Smith steady state:
192- idle TUI + current normal session: tens of MiB RSS mostly from terminal/UI/libs/Lua, not session entries,
193- active long session: +10–50 MiB for session + render/request buffers,
194- provider request at compaction threshold: temporary spike proportional to selected context, likely +20–100 MiB depending provider serialization,
195- pathological large tool output/render: single-line or single-message allocation can reach MiB scale.
197Memory policy candidates:
1991. Lazy-load full sessions; discovery reads only metadata.
2002. Never store session history in arenas.
2013. Benchmark render/request scratch before adding `bumpalo`.
2024. Put hard output-size and render-size tests in prototypes.
2035. Virtual scroll must bound per-frame work by visible rows, not total entries.
2046. Compaction/request construction needs peak-memory measurement, not only CPU timing.
206## Arena / allocator decision estimate
208Arenas likely help only where allocation lifetime is phase-bounded. They do not
209solve dominant persisted text bytes.
211Arena value is broader than allocation-count reduction:
213- fewer global allocator calls → lower allocator/syscall pressure,
214- stable peak/live memory after repeated phases,
215- predictable reset cadence,
216- bounded scratch capacity growth,
217- easier bulk discard of temporary render/request objects.
219Recommended prototype gates:
221- baseline must measure allocation count, allocated bytes, peak live bytes,
222 post-warmup live-memory plateau, elapsed time, and allocator-call pressure;
223- use `/proc/self/statm` RSS sampling on Linux for stable-memory checks;
224- `bumpalo` variant only for render/request scratch;
225- keep/drop decision can pass by allocation reduction OR lower allocator-call
226 pressure OR materially flatter post-warmup memory profile, without lifetime/API
227 complexity.
229Plugin heap limiting is a separate allocator/control use case. `mlua::Lua`
230exposes `used_memory()` and `set_memory_limit(limit_bytes)`, which should be
231prototyped against Smith's locked `mlua + LuaJIT` feature set. This is not
232`bumpalo`; it is Lua VM heap quota enforcement.
234Plugin reload is the broader arena/domain use case. A per-plugin domain can own
235Lua state plus host-side plugin allocations/caches/subscriptions. Dropping the
236domain on reload gives predictable reclamation and avoids bespoke cleanup graphs,
237provided no callback/task/registry handle can escape its domain.

docs/research/SOURCES.md

Modified

+2 / −0 text lines

2020| Project | URL | Revision | Sparse paths | Question |
2121|---------|-----|----------|--------------|----------|
22| `bumpalo` | https://github.com/fitzgen/bumpalo | `84654ace6be4444da3ff102a0a0af3b38c4df4fb` | full shallow clone | Evaluate mature bump allocation for phase-local scratch memory |
23| `arena-allocator` | https://github.com/emoon/arena-allocator | `266fd1f90c430523b08b7b76bb4ea43fd93c5896` | full shallow clone | Evaluate virtual-memory linear allocation risks/tradeoffs |
2224| _TBD_ | | | | |
2426## Checkout Convention