repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

docs(system): concurrency and memory law, research 4KD6V6IH, memory lints

f4af4acfbafbd422c5bd0abc98fa4263cf41aae8

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (4)

+236 / −5 text lines

Diff layout

.cargo/config.toml

Modified

+14 / −1 text lines

@@ -16,7 +16,6 @@ target.'cfg(all())'
1616 # false-positive friction:
1717 "-A", "clippy::module_name_repetitions",
1818 "-A", "clippy::must_use_candidate",
19 "-A", "clippy::needless_pass_by_value",
2019 "-W", "clippy::nursery",
2120 "-D", "clippy::suspicious",
2221 "-D", "clippy::complexity",
@@ -33,6 +32,20 @@ target.'cfg(all())'
3332 "-D", "clippy::print_stdout",
3433 "-D", "clippy::print_stderr",
35 # Memory law (.system/RULES.md): explicit sharing, no hidden copies
36 "-D", "clippy::clone_on_ref_ptr",
37 "-D", "clippy::rc_buffer",
38 "-D", "clippy::rc_mutex",
39 "-D", "clippy::mutex_atomic",
40 "-D", "clippy::mutex_integer",
41 "-D", "clippy::redundant_clone",
42 "-D", "clippy::implicit_clone",
43 "-D", "clippy::inefficient_to_string",
44 "-D", "clippy::large_stack_arrays",
45 "-D", "clippy::large_types_passed_by_value",
46 "-D", "clippy::trivially_copy_pass_by_ref",
47 "-D", "clippy::needless_pass_by_value",
3649 # Documentation lints
3750 "-D", "missing_docs",
3851 "-D", "rustdoc::missing_crate_level_docs",

.system/RULES.md

Modified

+29 / −3 text lines

4444- Tests may use unwrap/expect/panic.
4545- Prefer `#[expect(..., reason = "...")]` over `#[allow]`.
4646- Proc-macro warning suppression must be narrow and justified on the deriving item or containing module.
47- `#![forbid(unsafe_code)]` in library crates.
48- `smith-cli` unsafe only for OS terminal manipulation, with safe wrapper, `// SAFETY:`, and tests.
47- `#![forbid(unsafe_code)]` in library crates except `smith-alloc`.
48- `smith-cli` unsafe only for OS terminal manipulation; `smith-alloc` unsafe only for `GlobalAlloc`. Both with safe wrapper, `// SAFETY:`, and tests.
4949- Public docs required.
5050- fmt, clippy, tests, docs, audit, arch, and architecture-test gates in CI.
5151- Every `cargo x` command accepts argument passthrough; `-p` scoping overrides workspace defaults. Lockfile-wide commands (`audit`, `bootstrap`, `ci`) reject scope explicitly.
6262smith-rpc/ JSON-RPC frontend over standard input and output
6363smith-harness/ orchestration, wasm plugin host, plugin system, SDK, event bridge, built-ins, help
6464smith-cli/ binary entry point, CLI, session commands, eval/rpc/replay
65smith-alloc/ scope-tagged global allocator, allocation accounting
6566xtask/ cargo-only automation
6667```
7576- `smith-tui`: `smith`, `smith-ui`.
7677- `smith-rpc`: `smith`, `smith-core`.
7778- `smith-harness`: `smith`, `smith-core`, `smith-ai`, `smith-tui`, `smith-ui`.
78- `smith-cli`: `smith`, `smith-harness`, `smith-rpc`.
79- `smith-cli`: `smith`, `smith-harness`, `smith-rpc`, `smith-alloc`.
80- `smith-alloc`: none.
7981- `xtask`: none.
8183## Dependencies
9496- No git dependencies; released versions only.
9597- Determinism boundary: nothing on session, replay, or provider paths adds ambient time, randomness, or iteration-order dependence.
9698- Network and filesystem I/O never run on the render thread.
99- Async runtimes are engine baggage, never a Smith choice: an engine-owner crate may embed one; it never leaks past that crate's boundary.
101## Concurrency
103- Core crates (`smith`, `smith-core`, `smith-ai`, `smith-ui`, `smith-rpc`) contain no async runtime and no futures in public API.
104- Core is a pure function over the session arena and one ordered inbound event log; every nondeterministic input (net, fs, clock, plugin output, user input) enters through that log and is recorded at entry.
105- Threads by role: input, render, core, kernel pool, io. Edges are typed bounded channels; payloads are owned or `Arc<immutable>`; cancellation is an atomic handle.
106- Render thread owns the terminal, drains all pending events, then paints once; it never performs I/O and never waits on a producer.
107- Plugins run as kernels: sync wasmtime, fuel plus epoch, one instance pinned to one thread at a time; effects leave the guest as requests and re-enter as the next call.
108- `Mutex` does not appear in library crates.
109- `'static` boundaries take snapshots; they never force upstream cloning.
111## Memory
113- Lifetime groups are the unit of allocation: process, session, turn, kernel call, frame, io request. Group by lifetime, never by type.
114- Owner at rest, borrow in flight: structs own; fns take `&T`, `&str`, `&[T]`; `Cow` only at I/O edges.
115- Session data is an index arena: contiguous `Vec` per branch, `u32` handles in memory, `Uuid` at rest.
116- Large payloads (tool output, provider bodies) are bytes at rest, parsed on demand into the consuming scope.
117- No clone to satisfy the borrow checker; restructure ownership instead.
118- Sharing order: move → `&T` → `Arc<immutable>` → atomic → channel.
119- `smith-alloc` attributes every allocation, including engine allocations, to the current lifetime group.
120- Ceilings are soft in production (recorded, reported) and hard in tests; hard at runtime only where Smith calls `try_reserve`.
121- Hot paths carry allocation-count tests; bounds tighten, never loosen.
122- Underlying allocator choice is a benchmark result, never a default.
97123- Unused dependencies are flagged by `cargo x check` and removed.
98124- Upgrades are deliberate: `cargo update` in its own commit; lockfile committed.
99125- Duplicate-version warnings are resolved by upgrades, never by skip-lists.

.system/research/SMH-RESEARCH-4KD6V6IH-concurrency-and-memory-shape/index.md

Added
new file mode 100644

+188 / −0 text lines

1---
2id: SMH-RESEARCH-4KD6V6IH
3type: research
4title: "Concurrency and Memory Shape"
5---
6
7# Concurrency and Memory Shape
8
9Date: 2026-09-26.
10Status: evidence from code survey and three in-repo spikes; candidates, not mandates.
11Supersedes the runtime-related parts of SMH-RESEARCH-RSCH0001 and SMH-RESEARCH-RSCH0010 (both predate the wasm plugin law and assume Lua and an async provider boundary).
13## Question
15Which thread, runtime, ownership, and allocation shape gives Smith a render loop that never stalls, plugins that run as isolated kernels, bounded network and file I/O, deterministic replay, and cache-efficient data, while staying small enough that later web, daemon, and p2p frontends attach without reshaping the core?
17## Facts
19### Code survey at `tztonmyo` (≈11.5k loc host crates)
21| crate | loc | `.clone()` | `Arc<` | `Box<dyn` | lifetimes | `Cow` | `async fn` |
22|---|---|---|---|---|---|---|---|
23| smith | 1275 | 3 | 4 | 0 | 1 | 0 | 0 |
24| smith-core | 5201 | 68 | 4 | 0 | 0 | 0 | 0 |
25| smith-ai | 3356 | 15 | 8 | 2 | 0 | 0 | 0 |
26| smith-rpc | 487 | 9 | 1 | 0 | 0 | 0 | 0 |
27| smith-harness | 678 | 7 | 2 | 0 | 1 | 0 | 0 |
28| smith-cli | 451 | 2 | 0 | 0 | 0 | 0 | 0 |
30Observed hot spots:
32- `smith-core/src/session.rs` `ancestry`: builds a fresh `HashMap<EntryId, &Entry>` per call, then clones every `Entry` up the chain.
33 Measured: 2020 allocations, 549 KiB for `fork_at` over 1000 entries (spike C).
34- `smith-core/src/agent.rs` request build: clones the full message history per provider turn, then masks in place.
35- `Entry.content` embeds `serde_json::Value`: one heap node per JSON node.
36- `smith::provider::RecordSpool = Arc<Mutex<Vec<Value>>>`: three indirections plus a lock on the recording path.
37- `smith::provider::StreamFn` returns `BoxStream<'static>`; no consumer awaits it, the harness drives it from a thread.
38- `smith-harness/src/http.rs` is already blocking: reader thread, `std::sync::mpsc`, `CancelHandle` atomic.
39- `clippy::needless_pass_by_value` is allowed workspace-wide.
41### Runtime dependency roots at `tztonmyo`
43`tokio` enters only through two engines, never by Smith's choice:
45```text
46tokio 1.53
47├── reqwest 0.13 → hyper 1, hyper-util, tower, tokio-util, tokio-rustls, aws-lc-sys
48└── wasmtime-wasi 49 (hard dep; feature p2 enables wasmtime/async; sync API is block_on)
49```
51`wasmtime-wasi` also pulls `rand`, `cap-primitives`, `rustix` (ambient OS surface).
52`wasmtime-wasi-io` 49 is `no_std` and tokio-free but hard-enables `wasmtime/async` and still leaves clocks and cli unimplemented.
54The echo guest (`wasm32-wasip2`, wit-bindgen 0.62) imports exactly: `wasi:io/{poll,error,streams}`, `wasi:clocks/monotonic-clock`, `wasi:cli/{stdin,stdout,stderr,environment,exit,terminal-*}` at 0.2.9; no filesystem, random, sockets, or wall-clock.
55Guest 0.2.9 imports resolve against host 0.2.12 definitions through semver matching.
57### Allocator control on stable Rust
59| mechanism | stable | effort | fit |
60|---|---|---|---|
61| `#[global_allocator]` swap or wrapper | yes | one `unsafe impl GlobalAlloc` in a bin or dedicated crate | counting, bounding, attribution of all code including engines |
62| `allocator_api` (`Vec::new_in`) | no | nightly; `String` has no `_in`; engines allocate globally anyway | rejected |
63| lifetime arena (`bumpalo`) | yes | `'a` infects async, serde, wasm host, plugin API | rejected for core; scratch only where no reference escapes |
64| index arena (`Vec<T>` + `u32` handle) | yes | layout discipline only | chosen for session data |
66Lifetime grouping by type is almost never the logical grouping; Smith's logical groups are process, session, turn, kernel call, frame, io request.
68## Spikes
70All three ran in-repo as sibling changes off `tztonmyo` (shared build cache); each is a candidate for promotion after spec coverage.
72### A. Sealed WASI shims replace `wasmtime-wasi` (`qwzlzyqk` / `db1b1af4`)
74Result: supported.
76- One `wasmtime::component::bindgen!` call covers the plugin world plus an inline `smith:host` world importing exactly the guest's 12 WASI interfaces; generates sync `Host` traits; `exit` marked trappable.
77- Shims in `smith-harness/src/wasm/sealed_wasi.rs`: empty environment/arguments/cwd, stdin closed, stdout/stderr accept and discard, terminals `None`, exit traps, monotonic clock returns host-injected value (0 at load), every pollable ready, no `ResourceTable`, no `WasiCtx`.
78- WIT: `wit/deps/{io,clocks,cli}.wit` copied from wasmtime-wasi 49.0.1 (Apache-2.0 WITH LLVM-exception); `cli.wit` has its `imports`/`command` worlds removed because they reference filesystem, sockets, random; header states the modification.
79- Gates: `cargo x check|test|lint -p smith-harness` green, 12 tests incl. echo end to end; negative control (drop one import) fails instantiation as expected.
80- Tree: 298 → 277 crates; `wasmtime feature "async"` present → absent; `cap-primitives`, `rand`, `wasmtime-wasi` gone; `tokio` remains only via reqwest.
81- Risks: other guests importing random/filesystem/sockets/wall-clock fail at instantiation until further sealed shims land; nothing recorded to the session trace yet; clock frozen; `smith-cli/tests/architecture.rs` still names `wasmtime-wasi`; pre-existing bench failure (`criterion::black_box` deprecated) untouched.
83### B. `ureq` 3 HTTP executor (`lnrvruyv` / `057ac857`)
85Result: supported.
87- `UreqHttpExecutor` behind the existing `HttpExecutor` trait; shared `admit()` and `stream_body()` pump used by both engines; cancel checked after each read, before send.
88- `ureq = { version = "3.4", default-features = false, features = ["rustls"] }` → ureq 3.4.2, ureq-proto 0.6.4, ring, webpki-roots.
89- Loopback SSE test (3 events, 200 ms apart), both engines: first chunk 1.55 ms (ureq) vs 0.84 ms (reqwest); last 401 ms both; cancel → channel closed ≤ 200 ms; body cap honoured at 64 MiB.
90- Gap timeout (300 ms, server stalls 1 s): body ends at 605 ms.
91 Built as a 40-line `GapTimeout` connector over `ureq::unversioned::transport`, which is semver-unstable across minor releases.
92 ureq has no stable per-read timeout; `timeout_recv_body` is a whole-body budget.
93- reqwest's blocking client had no per-chunk gap timeout; its per-request `.timeout` acts on send and each body read.
94- Tree with reqwest removed: 298 → 271 crates (−27 raw, −15 unique normal packages, −45 lockfile entries); removes hyper, tower, tokio-util, hyper-util, tokio-rustls, aws-lc-sys.
95 `reqwest` is referenced only in `smith-harness/src/http.rs`, `smith-harness/Cargo.toml`, root `Cargo.toml`.
96- TLS trust store changes from platform verifier to bundled Mozilla roots unless `platform-verifier` is enabled.
97- Redirect, proxy env, and user-agent defaults not compared.
99### C. Scope-tagged counting allocator (`onllulxs` / `e124927f`)
101Result: supported.
103- New `smith-alloc` library crate (unsafe permitted, `// SAFETY:` comments, 5 unit tests): `Scope` enum (Process, Session, Turn, KernelCall, Frame, IoRequest), RAII `enter`, `snapshot`, `#[global_allocator]` set in `smith-cli`.
104- Design: `thread_local!` with `const { Cell<[Scope; 16] + len> }` (Copy, no Drop, never allocates, no TLS destructor); per-scope `AtomicU64 × 4` (allocations, bytes, live, peak) Relaxed; `align`-byte header per block carrying the scope tag so `dealloc`/`realloc` charge the allocating scope; guard restores `min(len, previous)`; falls back to Process during TLS teardown.
105- No locks, no allocation in the alloc path; reentrancy verified by exact unit counts.
106- Mock eval turn, XDG isolated, three runs identical: Turn 222 allocations / 20 552 B / peak 17 359 B; Process 573 / 134 446 B / peak 70 056 B.
107 Without XDG isolation counts drift because `eval.smh` grows between runs.
108- `fork_at` over 1000 entries: 2020 allocations, 549 438 B, peak 334 946 B; two consecutive forks equal.
109- Overhead: whole mock eval process −1 % … +8 % (noise); alloc-heavy microbench +12 % ≈ 12 ns per allocation over ≈ 53 ns; four atomic RMWs per alloc dominate, thread-local counters would cut it.
110- Risks: header changes memory layout (allocator comparisons must account for it); parallel tests sharing a scope mix counters; peak is lifetime not per-guard; spike-only `--cfg smith_alloc_off` toggle and `SMITH_ALLOC_STATS` stderr dump must go; `smith-alloc` missing from xtask `CRATES`; RULES unsafe law and spec coverage needed.
112## Tradeoffs
114- Async core vs sync core: async buys nothing at Smith's concurrency scale (a handful of provider streams, one bash process, sync grep) and costs `Send + 'static` on every seam, `Arc` infection, and scheduler-dependent ordering inside the determinism boundary.
115 Sync core with thread roles makes replay a pure function over the recorded inbound log.
116- Runtime crate choice is moot while engines dictate it; the actionable law is confinement (runtime never leaks past the engine-owner crate), not prohibition.
117 p2p (`iroh`) and a web frontend will bring tokio back inside their own crates.
118- `wasmtime-wasi-io` vs own shims: the former keeps `wasmtime/async` on and covers only io; own shims are ≈ 300 lines, fully sync, and match the spec's "Smith implementations" wording, at the cost of maintaining a hand-stripped `cli.wit`.
119- `ureq` vs reqwest: −27 crates, no runtime, ring instead of aws-lc; gap timeout depends on an unstable API and trust-store semantics change.
120 reqwest keeps hyper's maturity and platform roots at the cost of the whole tokio stack.
121- Global counting allocator: ≈ 12 ns per allocation and one header per block; buys attribution of engine allocations to logical scopes and deterministic count tests.
122 Bump-routing scope allocations through the global allocator is unsafe (engine caches, `thread_local!`, lazy statics escape scopes); real frees stay, bump-reset applies only to arenas Smith owns.
123- Hard ceilings in a global allocator abort on infallible `Vec::push` inside engines; ceilings are therefore soft in production, hard only in tests and where Smith calls `try_reserve`.
125## Candidates
127### Concurrency shape
129```text
130core = pure fn (session arena, ordered inbound event log) → (session arena', outbound effects)
131```
133| thread | owns | never |
134|---|---|---|
135| input | terminal events → coalesce → ui channel | blocks on core |
136| render | terminal, frame budget, drains ui channel | I/O, waits on producers |
137| core | Session arena, agent loop, single consumer of inbound channel | races, ambient time or randomness |
138| kernel pool | one plugin instance pinned per worker, sync wasmtime, fuel + epoch | blocking host calls inside guest |
139| io | net + fs on blocking threads, bounded chunks, cancel by atomic | render-thread work |
141Edges: typed bounded channels; payloads owned or `Arc<immutable>`; no `Mutex` in library crates; `'static` boundaries take snapshots, never force upstream cloning.
143Kernel = `(instance, call, inputs) → outputs + effect requests`; effects are dispatched by core to io and re-enter as the next kernel call, so every effect is recorded and replayable and one instance is never on two threads.
145Render: drain all pending events, then one frame; on-demand with a 16 ms deadline; layout from the wasm layout plugin runs on the kernel pool and returns an owned tree; producers block on full channels, the renderer never does.
147Later frontends: web (own HTTP server runtime in its crate), daemon (listener plus one core thread per session), p2p (`iroh`, tokio confined to that crate).
149### Lifetime groups
151| group | lives | dies | contents |
152|---|---|---|---|
153| process | start | exit | config, model catalog, compiled wasm modules, tool registry |
154| session | open | close | entry arena, text pool, payload bytes |
155| turn | user input | provider stop | request buffers, response accumulation, tool-round scratch |
156| kernel call | host→guest | guest returns | guest linear memory, host conversion buffers |
157| frame | tick | paint done | layout tree, cell buffer, diff |
158| io request | send | last chunk | chunk buffers, decoder state |
160### Data layout
162- Session entries: contiguous `Vec<Entry>` per branch, fixed-size `Entry` with `u32` spans into a per-session text pool and a payload byte arena; `EntryId(Uuid)` stays the at-rest identity, `EntryIdx(u32)` the in-memory handle; ancestry becomes an index chase.
163- Payloads (tool input, provider bodies): canonical bytes at rest, parsed on demand into turn scope.
164- Frame: double-buffered `Vec<Cell>`, never reallocated after the first frame.
165- Turn scratch: one bump `Vec<u8>`; provider request serialized straight into it; `clear()` per turn.
166- Underlying allocator (`System` vs `mimalloc`) decided by benchmark once count tests exist; header cost of the counter must be excluded from that comparison.
168### Promotion order
1701. Spike A (sealed WASI) after spec coverage of sealed semantics and trace recording; fix architecture test naming.
1712. Spike C (`smith-alloc`) after RULES unsafe exception and spec coverage; drop spike toggles; add to xtask `CRATES`; switch counters to thread-local.
1723. Spike B (`ureq`) after deciding trust-store policy and pinning `~3.4`; delete reqwest engine and workspace entry.
1734. Hot-spot refactors with count bounds: `ancestry` → request build → spool → `Value` payloads.
175## Open questions
177- Kernel pool sizing: lazy pool capped at cores vs one thread per plugin.
178- Render tick: fixed 60 Hz vs on-demand with deadline.
179- Trust store for ureq: bundled roots vs `platform-verifier`.
180- Sealed WASI breadth: which further imports (random seed, wall-clock, filesystem) get Smith substitutes before a non-trivial guest std program runs.
181- Per-turn peak: reset or epoch API on `smith-alloc`.
183## Sources
185- Code and lockfile at `tztonmyo` (`dd069f92`); spike changes `qwzlzyqk`, `lnrvruyv`, `onllulxs`.
186- Registry sources: `wasmtime-wasi 49.0.1`, `wasmtime-wasi-io 49.0.1`, `ureq 3.4.2`, `ureq-proto 0.6.4`.
187- SMH-SPEC-WASM0001 (sealed WASI law, single-threaded instances), SMH-SPEC-SPEC0001 (bounded frame allocation).
188- SMH-RESEARCH-RSCH0001 (arena patterns), SMH-RESEARCH-RSCH0010 (session size distribution: p99 ≈ 9 MiB JSONL, compaction near 250k tokens).

smith-harness/src/runtime.rs

Modified

+5 / −1 text lines

121121 let opened = open_session(Path::new(&config.session_path), smith_config)?;
122122 let tools = ToolSession::with_session(config.workdir.clone(), opened.session, opened.writer);
123123 let records = smith::provider::new_record_spool();
124 let stream = resolve_stream(&config.provider, config.api_key.clone(), records.clone())?;
124 let stream = resolve_stream(
125 &config.provider,
126 config.api_key.clone(),
127 std::sync::Arc::clone(&records),
128 )?;
125129 Ok(Agent::with_provider_records(
126130 stream,
127131 tools,