repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

feat(alloc): smith-alloc scope-tagged counting allocator, fork_at allocation bound

4d5af16fc8792d3ca6820db17241c85d7244c6ec

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (9)

+420 / −3 text lines

Diff layout

Cargo.lock

Modified

+6 / −0 text lines

22492249 "smith",
2252[[package]]
2253name = "smith-alloc"
2254version = "0.1.0"
22522256[[package]]
22532257name = "smith-cli"
22542258version = "0.1.0"
22592263 "predicates",
22602264 "serde_json",
22612265 "smith",
2266 "smith-alloc",
22622267 "smith-harness",
22632268 "smith-rpc",
22752280 "serde",
22762281 "serde_json",
22772282 "smith",
2283 "smith-alloc",
22802286[[package]]

Cargo.toml

Modified

+2 / −0 text lines

88 "smith-rpc",
99 "smith-harness",
1010 "smith-cli",
11 "smith-alloc",
1112 "plugins/echo",
1213 "xtask",
2425 "smith-rpc",
2526 "smith-harness",
2627 "smith-cli",
28 "smith-alloc",
2729 "xtask",

smith-alloc/Cargo.toml

Added
new file mode 100644

+8 / −0 text lines

1[package]
2name = "smith-alloc"
3edition.workspace = true
4version.workspace = true
5license.workspace = true
6
7[lib]
8path = "src/lib.rs"

smith-alloc/src/lib.rs

Added
new file mode 100644

+303 / −0 text lines

1//! Scope-tagged counting allocator.
2//!
3//! [`Counting`] wraps [`System`] and attributes every allocation, including
4//! third-party ones, to the innermost [`Scope`] entered on the allocating
5//! thread. Each block carries its scope tag in a header, so a free is charged
6//! to the scope that allocated it and live bytes stay exact per scope.
7//! Scopes do not propagate to spawned threads; those start at
8//! [`Scope::Process`].
9
10use std::alloc::{GlobalAlloc, Layout, System};
11use std::cell::Cell;
12use std::marker::PhantomData;
13use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
15/// Logical lifetime an allocation is charged to.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17#[repr(u8)]
18pub enum Scope {
19 /// Everything outside an explicit scope, including pre-main.
20 Process,
21 /// One session.
22 Session,
23 /// One agent turn.
24 Turn,
25 /// One kernel call.
26 KernelCall,
27 /// One rendered frame.
28 Frame,
29 /// One I/O request.
30 IoRequest,
31}
33const SCOPES: [Scope; 6] = [
34 Scope::Process,
35 Scope::Session,
36 Scope::Turn,
37 Scope::KernelCall,
38 Scope::Frame,
39 Scope::IoRequest,
40];
42/// Counters recorded for one scope since process start.
43#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
44pub struct Stats {
45 /// Allocations, reallocations included.
46 pub allocations: u64,
47 /// Bytes requested by those allocations.
48 pub bytes: u64,
49 /// Bytes allocated in this scope and not yet freed.
50 pub live: u64,
51 /// Highest `live` observed.
52 pub peak: u64,
53}
55struct Counters([AtomicU64; 4]);
57static COUNTERS: [Counters; 6] = [const { Counters([const { AtomicU64::new(0) }; 4]) }; 6];
59const DEPTH: usize = 16;
61#[derive(Clone, Copy)]
62struct Stack {
63 len: usize,
64 items: [Scope; DEPTH],
65}
67thread_local! {
68 // Const-initialized and drop-free: access never allocates or registers a destructor.
69 static STACK: Cell<Stack> = const { Cell::new(Stack { len: 0, items: [Scope::Process; DEPTH] }) };
70}
72fn current() -> Scope {
73 STACK
74 .try_with(|stack| {
75 let stack = stack.get();
76 stack.items.get(stack.len.wrapping_sub(1)).copied()
77 })
78 .ok()
79 .flatten()
80 .unwrap_or(Scope::Process)
81}
83/// Restores the enclosing scope when dropped; bound to its thread.
84#[must_use = "the scope ends when the guard drops"]
85pub struct Guard {
86 previous: usize,
87 _thread_bound: PhantomData<*const ()>,
88}
90impl Drop for Guard {
91 fn drop(&mut self) {
92 let _ = STACK.try_with(|cell| {
93 let mut stack = cell.get();
94 // `min` tolerates non-LIFO drops, such as a `Vec` of guards.
95 stack.len = stack.len.min(self.previous);
96 cell.set(stack);
97 });
98 }
99}
101/// Charge this thread's allocations to `scope` until the guard drops.
102///
103/// Nesting deeper than 16 keeps charging the outer scope (soft limit).
104pub fn enter(scope: Scope) -> Guard {
105 let previous = STACK
106 .try_with(|cell| {
107 let mut stack = cell.get();
108 let previous = stack.len;
109 if let Some(slot) = stack.items.get_mut(previous) {
110 *slot = scope;
111 stack.len += 1;
112 cell.set(stack);
113 }
114 previous
115 })
116 .unwrap_or(0);
117 Guard {
118 previous,
119 _thread_bound: PhantomData,
120 }
121}
123/// Counters recorded for `scope`.
124pub fn snapshot(scope: Scope) -> Stats {
125 let [allocations, bytes, live, peak] = &COUNTERS[scope as usize].0;
126 Stats {
127 allocations: allocations.load(Relaxed),
128 bytes: bytes.load(Relaxed),
129 live: live.load(Relaxed),
130 peak: peak.load(Relaxed),
131 }
132}
134/// Every scope with its counters.
135pub fn snapshot_all() -> [(Scope, Stats); 6] {
136 SCOPES.map(|scope| (scope, snapshot(scope)))
137}
139fn record_alloc(scope: Scope, size: usize) {
140 let [allocations, bytes, live, peak] = &COUNTERS[scope as usize].0;
141 allocations.fetch_add(1, Relaxed);
142 bytes.fetch_add(size as u64, Relaxed);
143 let now = live.fetch_add(size as u64, Relaxed) + size as u64;
144 peak.fetch_max(now, Relaxed);
145}
147fn record_free(tag: u8, size: usize) {
148 // A tag outside the scope range means a foreign block; nothing to charge.
149 if let Some(counters) = COUNTERS.get(usize::from(tag)) {
150 counters.0[2].fetch_sub(size as u64, Relaxed);
151 }
152}
154/// Header of `align` bytes in front of each block; its last byte is the scope tag.
155fn padded(layout: Layout) -> Option<(Layout, usize)> {
156 let pad = layout.align();
157 let size = layout.size().checked_add(pad)?;
158 Layout::from_size_align(size, pad)
159 .ok()
160 .map(|outer| (outer, pad))
161}
163/// Counting wrapper around [`System`]; install with `#[global_allocator]`.
164pub struct Counting;
166impl Counting {
167 /// # Safety
168 /// `raw` must allocate a block for the layout it is given, like [`GlobalAlloc::alloc`].
169 unsafe fn tagged(layout: Layout, raw: impl FnOnce(Layout) -> *mut u8) -> *mut u8 {
170 let Some((outer, pad)) = padded(layout) else {
171 return std::ptr::null_mut();
172 };
173 let base = raw(outer);
174 if base.is_null() {
175 return base;
176 }
177 let scope = current();
178 // SAFETY: `base` spans `pad + size` bytes and `pad >= 1`, so the user
179 // pointer and its tag byte lie inside the block; `pad` keeps alignment.
180 let user = unsafe { base.add(pad) };
181 unsafe { user.sub(1).write(scope as u8) };
182 record_alloc(scope, layout.size());
183 user
184 }
185}
187// SAFETY: every block is a `System` block of `padded(layout)`; the user
188// pointer sits `pad` bytes in, so `System` receives back exactly what it gave.
189unsafe impl GlobalAlloc for Counting {
190 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
191 // SAFETY: forwards the caller's non-zero layout, grown by the header.
192 unsafe { Self::tagged(layout, |outer| System.alloc(outer)) }
193 }
195 unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
196 // SAFETY: as `alloc`.
197 unsafe { Self::tagged(layout, |outer| System.alloc_zeroed(outer)) }
198 }
200 unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
201 let Some((outer, pad)) = padded(layout) else {
202 return;
203 };
204 // SAFETY: `ptr` came from `tagged` with this layout, so the tag byte
205 // and the `System` base lie `1` and `pad` bytes before it.
206 unsafe {
207 record_free(ptr.sub(1).read(), layout.size());
208 System.dealloc(ptr.sub(pad), outer);
209 }
210 }
212 unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
213 let (Some((outer, pad)), Some(new_outer)) =
214 (padded(layout), new_size.checked_add(layout.align()))
215 else {
216 return std::ptr::null_mut();
217 };
218 // SAFETY: as `dealloc`; on success `System` moved the header with the data.
219 unsafe {
220 let tag = ptr.sub(1).read();
221 let base = System.realloc(ptr.sub(pad), outer, new_outer);
222 if base.is_null() {
223 return base;
224 }
225 let user = base.add(pad);
226 let scope = current();
227 user.sub(1).write(scope as u8);
228 record_free(tag, layout.size());
229 record_alloc(scope, new_size);
230 user
231 }
232 }
233}
235#[cfg(test)]
236mod tests {
237 use super::{Counting, Scope, enter, snapshot};
239 #[global_allocator]
240 static ALLOC: Counting = Counting;
242 // Each test owns a distinct scope: counters are process-wide and libtest runs tests in parallel.
244 #[test]
245 fn free_outside_scope_is_charged_to_allocating_scope() {
246 let guard = enter(Scope::Frame);
247 let block = std::hint::black_box(vec![0u8; 1000]);
248 drop(guard);
249 let inside = snapshot(Scope::Frame);
250 assert_eq!(
251 (inside.allocations, inside.bytes, inside.live),
252 (1, 1000, 1000)
253 );
254 drop(block);
255 let after = snapshot(Scope::Frame);
256 assert_eq!((after.live, after.peak), (0, 1000));
257 }
259 #[test]
260 fn nested_scope_restores_outer_and_realloc_retags() {
261 let outer = enter(Scope::KernelCall);
262 let mut grown: Vec<u8> = Vec::with_capacity(8);
263 {
264 let _inner = enter(Scope::IoRequest);
265 grown.reserve_exact(64);
266 }
267 let tail = std::hint::black_box(vec![1u8; 16]);
268 drop(outer);
269 let kernel = snapshot(Scope::KernelCall);
270 let io = snapshot(Scope::IoRequest);
271 assert_eq!((kernel.allocations, kernel.bytes, kernel.live), (2, 24, 16));
272 assert_eq!((io.allocations, io.bytes, io.live), (1, 64, 64));
273 drop((grown, tail));
274 assert_eq!(snapshot(Scope::IoRequest).live, 0);
275 }
277 #[test]
278 fn overaligned_blocks_stay_aligned() {
279 #[repr(align(4096))]
280 struct Page([u8; 4096]);
281 let page = Box::new(Page([0; 4096]));
282 assert_eq!(std::ptr::from_ref(&*page).addr() % 4096, 0);
283 assert_eq!(page.0[4095], 0);
284 }
286 #[test]
287 fn spawned_threads_start_at_process_scope() {
288 let _turn = enter(Scope::Turn);
289 let seen = std::thread::spawn(super::current)
290 .join()
291 .map_err(|_| "join");
292 assert_eq!(seen, Ok(Scope::Process));
293 }
295 #[test]
296 fn overflowing_depth_keeps_outer_scope() {
297 let _session = enter(Scope::Session);
298 let guards: Vec<_> = (0..20).map(|_| enter(Scope::Process)).collect();
299 assert_eq!(super::current(), Scope::Process);
300 drop(guards);
301 assert_eq!(super::current(), Scope::Session);
302 }
303}

smith-cli/Cargo.toml

Modified

+1 / −0 text lines

1313smith = { path = "../smith", version = "0.1.0" }
1414smith-harness = { path = "../smith-harness", version = "0.1.0" }
1515smith-rpc = { path = "../smith-rpc", version = "0.1.0" }
16smith-alloc = { path = "../smith-alloc", version = "0.1.0" }
1617clap = { workspace = true }
1718serde_json = { workspace = true }

smith-cli/src/main.rs

Modified

+8 / −1 text lines

1414use smith_rpc::{RpcState, handle_line};
1515use std::io::{BufRead, Write};
17/// Every allocation is charged to the current lifetime scope (`SMH-SPEC-SPEC0001`, memory accounting).
18#[global_allocator]
19static ALLOC: smith_alloc::Counting = smith_alloc::Counting;
1721/// Smith, a fast coding-agent runtime.
1822#[derive(Debug, Parser)]
1923#[command(name = "smith", version, about)]
344348 api_key: None,
345349 };
346350 let mut agent = build_agent(&config)?;
347 let outcome = agent.run_turn(prompt)?;
351 let turn = smith_alloc::enter(smith_alloc::Scope::Turn);
352 let outcome = agent.run_turn(prompt);
353 drop(turn);
354 let outcome = outcome?;
348355 if json {
349356 println!(
350357 "{}",

smith-core/Cargo.toml

Modified

+4 / −1 text lines

1717ignore = { workspace = true }
1919[target.'cfg(unix)'.dependencies]
20nix = { workspace = true }No final newline
20nix = { workspace = true }
22[dev-dependencies]
23smith-alloc = { path = "../smith-alloc", version = "0.1.0" }

smith-core/tests/alloc_bounds.rs

Added
new file mode 100644

+60 / −0 text lines

1//! Allocation-count bounds on session hot paths (`SMH-SPEC-SPEC0001`,
2//! memory accounting). Bounds only tighten.
3
4use smith::message::{Message, Role};
5use smith_alloc::{Counting, Scope, Stats, enter, snapshot};
6use smith_core::session::{Entry, Session};
7
8#[global_allocator]
9static ALLOC: Counting = Counting;
11/// `fork_at` over 1000 entries; clones every entry on the chain today.
12const FORK_AT_1000_ALLOCATIONS: u64 = 2020;
14fn linear_session(len: usize) -> Session {
15 let mut session = Session::new();
16 for turn in 0..len {
17 let entry = Entry::message(
18 Message::with_text(Role::User, format!("turn {turn}")),
19 session.selected_id(),
20 );
21 session.append_to_active(entry);
22 }
23 session
24}
26fn fork_cost(session: &Session, scope: Scope) -> Stats {
27 let leaf = session.selected_id().expect("non-empty session");
28 let before = snapshot(scope);
29 let guard = enter(scope);
30 let fork = session.fork_at(leaf).expect("leaf is known");
31 drop(guard);
32 let after = snapshot(scope);
33 assert_eq!(
34 fork.active_branch().entries.len(),
35 session.active_branch().entries.len()
36 );
37 drop(fork);
38 Stats {
39 allocations: after.allocations - before.allocations,
40 bytes: after.bytes - before.bytes,
41 live: after.live - before.live,
42 peak: after.peak,
43 }
44}
46#[test]
47fn fork_at_over_1000_entries_is_bounded_and_reproducible() {
48 let session = linear_session(1000);
49 let first = fork_cost(&session, Scope::Session);
50 let second = fork_cost(&session, Scope::Session);
51 assert!(
52 first.allocations <= FORK_AT_1000_ALLOCATIONS,
53 "fork_at allocated {} times, bound is {FORK_AT_1000_ALLOCATIONS}",
54 first.allocations
55 );
56 assert_eq!(
57 (first.allocations, first.bytes),
58 (second.allocations, second.bytes)
59 );
60}

xtask/src/main.rs

Modified

+28 / −1 text lines

4040 "smith-rpc",
4141 "smith-harness",
4242 "smith-cli",
43 "smith-alloc",
4344 "xtask",
4445];
603604 "smith-tui",
604605 "smith-harness",
605606 "smith-cli",
607 "smith-alloc",
606608 ],
607609 },
608610 DependencyRule {
613615 "smith-tui",
614616 "smith-harness",
615617 "smith-cli",
618 "smith-alloc",
616619 ],
617620 },
618621 DependencyRule {
623626 "smith-tui",
624627 "smith-harness",
625628 "smith-cli",
629 "smith-alloc",
626630 ],
627631 },
628632 DependencyRule {
633637 "smith-tui",
634638 "smith-harness",
635639 "smith-cli",
640 "smith-alloc",
636641 ],
637642 },
638643 DependencyRule {
639644 crate_name: "smith-tui",
640 denied: &["smith-core", "smith-ai", "smith-harness", "smith-cli"],
645 denied: &[
646 "smith-core",
647 "smith-ai",
648 "smith-harness",
649 "smith-cli",
650 "smith-alloc",
651 ],
641652 },
642653 DependencyRule {
643654 crate_name: "smith-rpc",
647658 "smith-tui",
648659 "smith-harness",
649660 "smith-cli",
661 "smith-alloc",
650662 ],
651663 },
652664 DependencyRule {
663675 "smith-tui",
664676 "smith-harness",
665677 "smith-cli",
678 "smith-alloc",
679 ],
680 },
681 DependencyRule {
682 crate_name: "smith-alloc",
683 denied: &[
684 "smith",
685 "smith-core",
686 "smith-ai",
687 "smith-ui",
688 "smith-tui",
689 "smith-rpc",
690 "smith-harness",
691 "smith-cli",
692 "xtask",
666693 ],
667694 },
668695 ]