repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

smith-core/tests/alloc_bounds.rs

Raw
File outline
//! 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, enter, snapshot};
use smith_core::session::{Entry, Session};

#[global_allocator]
static ALLOC: Counting = Counting;

/// `fork_at` over 1000 entries: the branch list, the chain `Vec`, and two allocations per cloned
/// text entry (`blocks` and its `String`) until payloads become bytes at rest.
const FORK_AT_1000_ALLOCATIONS: u64 = 2002;

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
}

/// Allocations and bytes charged to [`Scope::Session`] by one `fork_at` of the leaf.
fn fork_cost(session: &Session) -> (u64, u64) {
    let leaf = session.selected_id().expect("non-empty session");
    let before = snapshot(Scope::Session);
    let guard = enter(Scope::Session);
    let fork = session.fork_at(leaf).expect("leaf is known");
    drop(guard);
    let after = snapshot(Scope::Session);
    assert_eq!(
        fork.active_branch().entries.len(),
        session.active_branch().entries.len()
    );
    drop(fork);
    (
        after.allocations - before.allocations,
        after.bytes - before.bytes,
    )
}

#[test]
fn fork_at_over_1000_entries_is_bounded_and_reproducible() {
    let session = linear_session(1000);
    let first = fork_cost(&session);
    let second = fork_cost(&session);
    assert!(
        first.0 <= FORK_AT_1000_ALLOCATIONS,
        "fork_at allocated {} times, bound is {FORK_AT_1000_ALLOCATIONS}",
        first.0
    );
    assert_eq!(first, second);
}