feat(alloc): smith-alloc scope-tagged counting allocator, fork_at allocation bound
4d5af16fc8792d3ca6820db17241c85d7244c6ec
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: 33d04b803551
There are many coding harnesses - but this one is fast
4d5af16fc8792d3ca6820db17241c85d7244c6ec
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
+420 / −3 text lines
+6 / −0 text lines
+2 / −0 text lines
new file mode 100644+8 / −0 text lines
new file mode 100644+303 / −0 text lines
//! Scope-tagged counting allocator.//!//! [`Counting`] wraps [`System`] and attributes every allocation, including//! third-party ones, to the innermost [`Scope`] entered on the allocating//! thread. Each block carries its scope tag in a header, so a free is charged//! to the scope that allocated it and live bytes stay exact per scope.//! Scopes do not propagate to spawned threads; those start at//! [`Scope::Process`].use std::alloc::{GlobalAlloc, Layout, System};use std::cell::Cell;use std::marker::PhantomData;use std::sync::atomic::{AtomicU64, Ordering::Relaxed};/// Logical lifetime an allocation is charged to.#[derive(Clone, Copy, Debug, PartialEq, Eq)]#[repr(u8)]pub enum Scope { /// Everything outside an explicit scope, including pre-main. Process, /// One session. Session, /// One agent turn. Turn, /// One kernel call. KernelCall, /// One rendered frame. Frame, /// One I/O request. IoRequest,}const SCOPES: [Scope; 6] = [ Scope::Process, Scope::Session, Scope::Turn, Scope::KernelCall, Scope::Frame, Scope::IoRequest,];/// Counters recorded for one scope since process start.#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]pub struct Stats { /// Allocations, reallocations included. pub allocations: u64, /// Bytes requested by those allocations. pub bytes: u64, /// Bytes allocated in this scope and not yet freed. pub live: u64, /// Highest `live` observed. pub peak: u64,}struct Counters([AtomicU64; 4]);static COUNTERS: [Counters; 6] = [const { Counters([const { AtomicU64::new(0) }; 4]) }; 6];const DEPTH: usize = 16;#[derive(Clone, Copy)]struct Stack { len: usize, items: [Scope; DEPTH],}thread_local! { // Const-initialized and drop-free: access never allocates or registers a destructor. static STACK: Cell<Stack> = const { Cell::new(Stack { len: 0, items: [Scope::Process; DEPTH] }) };}fn current() -> Scope { STACK .try_with(|stack| { let stack = stack.get(); stack.items.get(stack.len.wrapping_sub(1)).copied() }) .ok() .flatten() .unwrap_or(Scope::Process)}/// Restores the enclosing scope when dropped; bound to its thread.#[must_use = "the scope ends when the guard drops"]pub struct Guard { previous: usize, _thread_bound: PhantomData<*const ()>,}impl Drop for Guard { fn drop(&mut self) { let _ = STACK.try_with(|cell| { let mut stack = cell.get(); // `min` tolerates non-LIFO drops, such as a `Vec` of guards. stack.len = stack.len.min(self.previous); cell.set(stack); }); }}/// Charge this thread's allocations to `scope` until the guard drops.////// Nesting deeper than 16 keeps charging the outer scope (soft limit).pub fn enter(scope: Scope) -> Guard { let previous = STACK .try_with(|cell| { let mut stack = cell.get(); let previous = stack.len; if let Some(slot) = stack.items.get_mut(previous) { *slot = scope; stack.len += 1; cell.set(stack); } previous }) .unwrap_or(0); Guard { previous, _thread_bound: PhantomData, }}/// Counters recorded for `scope`.pub fn snapshot(scope: Scope) -> Stats { let [allocations, bytes, live, peak] = &COUNTERS[scope as usize].0; Stats { allocations: allocations.load(Relaxed), bytes: bytes.load(Relaxed), live: live.load(Relaxed), peak: peak.load(Relaxed), }}/// Every scope with its counters.pub fn snapshot_all() -> [(Scope, Stats); 6] { SCOPES.map(|scope| (scope, snapshot(scope)))}fn record_alloc(scope: Scope, size: usize) { let [allocations, bytes, live, peak] = &COUNTERS[scope as usize].0; allocations.fetch_add(1, Relaxed); bytes.fetch_add(size as u64, Relaxed); let now = live.fetch_add(size as u64, Relaxed) + size as u64; peak.fetch_max(now, Relaxed);}fn record_free(tag: u8, size: usize) { // A tag outside the scope range means a foreign block; nothing to charge. if let Some(counters) = COUNTERS.get(usize::from(tag)) { counters.0[2].fetch_sub(size as u64, Relaxed); }}/// Header of `align` bytes in front of each block; its last byte is the scope tag.fn padded(layout: Layout) -> Option<(Layout, usize)> { let pad = layout.align(); let size = layout.size().checked_add(pad)?; Layout::from_size_align(size, pad) .ok() .map(|outer| (outer, pad))}/// Counting wrapper around [`System`]; install with `#[global_allocator]`.pub struct Counting;impl Counting { /// # Safety /// `raw` must allocate a block for the layout it is given, like [`GlobalAlloc::alloc`]. unsafe fn tagged(layout: Layout, raw: impl FnOnce(Layout) -> *mut u8) -> *mut u8 { let Some((outer, pad)) = padded(layout) else { return std::ptr::null_mut(); }; let base = raw(outer); if base.is_null() { return base; } let scope = current(); // SAFETY: `base` spans `pad + size` bytes and `pad >= 1`, so the user // pointer and its tag byte lie inside the block; `pad` keeps alignment. let user = unsafe { base.add(pad) }; unsafe { user.sub(1).write(scope as u8) }; record_alloc(scope, layout.size()); user }}// SAFETY: every block is a `System` block of `padded(layout)`; the user// pointer sits `pad` bytes in, so `System` receives back exactly what it gave.unsafe impl GlobalAlloc for Counting { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { // SAFETY: forwards the caller's non-zero layout, grown by the header. unsafe { Self::tagged(layout, |outer| System.alloc(outer)) } } unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { // SAFETY: as `alloc`. unsafe { Self::tagged(layout, |outer| System.alloc_zeroed(outer)) } } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { let Some((outer, pad)) = padded(layout) else { return; }; // SAFETY: `ptr` came from `tagged` with this layout, so the tag byte // and the `System` base lie `1` and `pad` bytes before it. unsafe { record_free(ptr.sub(1).read(), layout.size()); System.dealloc(ptr.sub(pad), outer); } } unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { let (Some((outer, pad)), Some(new_outer)) = (padded(layout), new_size.checked_add(layout.align())) else { return std::ptr::null_mut(); }; // SAFETY: as `dealloc`; on success `System` moved the header with the data. unsafe { let tag = ptr.sub(1).read(); let base = System.realloc(ptr.sub(pad), outer, new_outer); if base.is_null() { return base; } let user = base.add(pad); let scope = current(); user.sub(1).write(scope as u8); record_free(tag, layout.size()); record_alloc(scope, new_size); user } }}#[cfg(test)]mod tests { use super::{Counting, Scope, enter, snapshot}; #[global_allocator] static ALLOC: Counting = Counting; // Each test owns a distinct scope: counters are process-wide and libtest runs tests in parallel. #[test] fn free_outside_scope_is_charged_to_allocating_scope() { let guard = enter(Scope::Frame); let block = std::hint::black_box(vec![0u8; 1000]); drop(guard); let inside = snapshot(Scope::Frame); assert_eq!( (inside.allocations, inside.bytes, inside.live), (1, 1000, 1000) ); drop(block); let after = snapshot(Scope::Frame); assert_eq!((after.live, after.peak), (0, 1000)); } #[test] fn nested_scope_restores_outer_and_realloc_retags() { let outer = enter(Scope::KernelCall); let mut grown: Vec<u8> = Vec::with_capacity(8); { let _inner = enter(Scope::IoRequest); grown.reserve_exact(64); } let tail = std::hint::black_box(vec![1u8; 16]); drop(outer); let kernel = snapshot(Scope::KernelCall); let io = snapshot(Scope::IoRequest); assert_eq!((kernel.allocations, kernel.bytes, kernel.live), (2, 24, 16)); assert_eq!((io.allocations, io.bytes, io.live), (1, 64, 64)); drop((grown, tail)); assert_eq!(snapshot(Scope::IoRequest).live, 0); } #[test] fn overaligned_blocks_stay_aligned() { #[repr(align(4096))] struct Page([u8; 4096]); let page = Box::new(Page([0; 4096])); assert_eq!(std::ptr::from_ref(&*page).addr() % 4096, 0); assert_eq!(page.0[4095], 0); } #[test] fn spawned_threads_start_at_process_scope() { let _turn = enter(Scope::Turn); let seen = std::thread::spawn(super::current) .join() .map_err(|_| "join"); assert_eq!(seen, Ok(Scope::Process)); } #[test] fn overflowing_depth_keeps_outer_scope() { let _session = enter(Scope::Session); let guards: Vec<_> = (0..20).map(|_| enter(Scope::Process)).collect(); assert_eq!(super::current(), Scope::Process); drop(guards); assert_eq!(super::current(), Scope::Session); }}+1 / −0 text lines
smith-alloc = { path = "../smith-alloc", version = "0.1.0" }+8 / −1 text lines
let outcome = agent.run_turn(prompt)?;+4 / −1 text lines
new file mode 100644+60 / −0 text lines
//! Allocation-count bounds on session hot paths (`SMH-SPEC-SPEC0001`,//! memory accounting). Bounds only tighten.use smith::message::{Message, Role};use smith_alloc::{Counting, Scope, Stats, enter, snapshot};use smith_core::session::{Entry, Session};#[global_allocator]static ALLOC: Counting = Counting;/// `fork_at` over 1000 entries; clones every entry on the chain today.const FORK_AT_1000_ALLOCATIONS: u64 = 2020;fn linear_session(len: usize) -> Session { let mut session = Session::new(); for turn in 0..len { let entry = Entry::message( Message::with_text(Role::User, format!("turn {turn}")), session.selected_id(), ); session.append_to_active(entry); } session}fn fork_cost(session: &Session, scope: Scope) -> Stats { let leaf = session.selected_id().expect("non-empty session"); let before = snapshot(scope); let guard = enter(scope); let fork = session.fork_at(leaf).expect("leaf is known"); drop(guard); let after = snapshot(scope); assert_eq!( fork.active_branch().entries.len(), session.active_branch().entries.len() ); drop(fork); Stats { allocations: after.allocations - before.allocations, bytes: after.bytes - before.bytes, live: after.live - before.live, peak: after.peak, }}#[test]fn fork_at_over_1000_entries_is_bounded_and_reproducible() { let session = linear_session(1000); let first = fork_cost(&session, Scope::Session); let second = fork_cost(&session, Scope::Session); assert!( first.allocations <= FORK_AT_1000_ALLOCATIONS, "fork_at allocated {} times, bound is {FORK_AT_1000_ALLOCATIONS}", first.allocations ); assert_eq!( (first.allocations, first.bytes), (second.allocations, second.bytes) );}+28 / −1 text lines