repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

refactor: deslop pass over sealed wasi, alloc, http, session, agent

0b0de9c6beb6718d4152f6d966fec0adaa3bb7d3

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (5)

+98 / −47 text lines

Diff layout

smith-alloc/src/lib.rs

Modified

+47 / −17 text lines

5252 pub peak: u64,
55struct Counters([AtomicU64; 4]);
55struct Counters {
56 allocations: AtomicU64,
57 bytes: AtomicU64,
58 live: AtomicU64,
59 peak: AtomicU64,
60}
57static COUNTERS: [Counters; 6] = [const { Counters([const { AtomicU64::new(0) }; 4]) }; 6];
62static COUNTERS: [Counters; SCOPES.len()] = [const {
63 Counters {
64 allocations: AtomicU64::new(0),
65 bytes: AtomicU64::new(0),
66 live: AtomicU64::new(0),
67 peak: AtomicU64::new(0),
68 }
69}; SCOPES.len()];
5971const DEPTH: usize = 16;
123135/// Counters recorded for `scope`.
124136pub fn snapshot(scope: Scope) -> Stats {
125 let [allocations, bytes, live, peak] = &COUNTERS[scope as usize].0;
137 let counters = &COUNTERS[scope as usize];
126138 Stats {
127 allocations: allocations.load(Relaxed),
128 bytes: bytes.load(Relaxed),
129 live: live.load(Relaxed),
130 peak: peak.load(Relaxed),
139 allocations: counters.allocations.load(Relaxed),
140 bytes: counters.bytes.load(Relaxed),
141 live: counters.live.load(Relaxed),
142 peak: counters.peak.load(Relaxed),
131143 }
134146/// Every scope with its counters.
135pub fn snapshot_all() -> [(Scope, Stats); 6] {
147pub fn snapshot_all() -> [(Scope, Stats); SCOPES.len()] {
136148 SCOPES.map(|scope| (scope, snapshot(scope)))
139151fn 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);
152 let counters = &COUNTERS[scope as usize];
153 counters.allocations.fetch_add(1, Relaxed);
154 counters.bytes.fetch_add(size as u64, Relaxed);
155 let now = counters.live.fetch_add(size as u64, Relaxed) + size as u64;
156 counters.peak.fetch_max(now, Relaxed);
147159fn record_free(tag: u8, size: usize) {
148160 // A tag outside the scope range means a foreign block; nothing to charge.
149161 if let Some(counters) = COUNTERS.get(usize::from(tag)) {
150 counters.0[2].fetch_sub(size as u64, Relaxed);
162 counters.live.fetch_sub(size as u64, Relaxed);
151163 }
210222 }
212224 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()))
225 // The grown outer layout must itself be valid, as `System.realloc` requires.
226 let new_layout = Layout::from_size_align(new_size, layout.align()).ok();
227 let (Some((outer, pad)), Some((new_outer, _))) =
228 (padded(layout), new_layout.and_then(padded))
215229 else {
216230 return std::ptr::null_mut();
217231 };
218232 // SAFETY: as `dealloc`; on success `System` moved the header with the data.
219233 unsafe {
220234 let tag = ptr.sub(1).read();
221 let base = System.realloc(ptr.sub(pad), outer, new_outer);
235 let base = System.realloc(ptr.sub(pad), outer, new_outer.size());
222236 if base.is_null() {
223237 return base;
224238 }
283297 assert_eq!(page.0[4095], 0);
284298 }
300 #[test]
301 fn realloc_past_header_capacity_fails_and_keeps_block() {
302 use std::alloc::{GlobalAlloc, Layout};
303 let layout = Layout::new::<u64>();
304 // Valid for the caller, but no room left for the header in front.
305 let new_size = isize::MAX.cast_unsigned() - 7;
306 // SAFETY: `layout` is non-zero; `new_size` rounded to its alignment
307 // fits `isize`; the block is freed with the layout it was made with.
308 unsafe {
309 let block = Counting.alloc(layout);
310 assert!(!block.is_null());
311 assert!(Counting.realloc(block, layout, new_size).is_null());
312 Counting.dealloc(block, layout);
313 }
314 }
286316 #[test]
287317 fn spawned_threads_start_at_process_scope() {
288318 let _turn = enter(Scope::Turn);

smith-cli/src/main.rs

Modified

+4 / −4 text lines

348348 api_key: None,
349349 };
350350 let mut agent = build_agent(&config)?;
351 let turn = smith_alloc::enter(smith_alloc::Scope::Turn);
352 let outcome = agent.run_turn(prompt);
353 drop(turn);
354 let outcome = outcome?;
351 let outcome = {
352 let _turn = smith_alloc::enter(smith_alloc::Scope::Turn);
353 agent.run_turn(prompt)
354 }?;
355355 if json {
356356 println!(
357357 "{}",

smith-core/src/session.rs

Modified

+29 / −4 text lines

281281 Some((branch, idx))
282282 })?;
283283 let chain = &branch.entries[..=idx];
284 let rooted = chain.first().is_some_and(|root| root.parent.is_none());
284285 let linked = chain
285 .iter()
286 .enumerate()
287 .all(|(i, entry)| entry.parent == i.checked_sub(1).map(|p| chain[p].id));
288 linked.then_some(chain)
286 .windows(2)
287 .all(|pair| pair[1].parent == Some(pair[0].id));
288 (rooted && linked).then_some(chain)
289289 }
291291 /// Fork the history ending at `at` into a new session.
575575 assert_eq!(err.code(), "ENTRY_NOT_FOUND");
576576 }
578 #[test]
579 fn fork_rejects_broken_ancestry_and_forks_sibling_branches() {
580 // A stored chain whose root parent is missing restores, but cannot fork.
581 let orphan = message("orphan", Some(EntryId::new()));
582 let child = message("child", Some(orphan.id));
583 let broken = Session::from_entries(None, &[orphan, child.clone()], None);
584 assert_eq!(broken.selected_id(), Some(child.id));
585 let err = broken.fork_at(child.id).unwrap_err();
586 assert_eq!(err.code(), "ENTRY_NOT_FOUND");
588 // A leaf on an inactive sibling branch forks along its own chain.
589 let root = message("root", None);
590 let first = message("first", Some(root.id));
591 let second = message("second", Some(root.id));
592 let siblings = Session::from_entries(None, &[root.clone(), first.clone(), second], None);
593 let forked = siblings.fork_at(first.id).unwrap();
594 let ids: Vec<EntryId> = forked
595 .active_branch()
596 .entries
597 .iter()
598 .map(|e| e.id)
599 .collect();
600 assert_eq!(ids, vec![root.id, first.id]);
601 }
578603 #[test]
579604 fn compaction_boundary_survives_a_frame_round_trip() {
580605 let mut session = Session::new();

smith-core/tests/alloc_bounds.rs

Modified

+15 / −19 text lines

22//! memory accounting). Bounds only tighten.
44use smith::message::{Message, Role};
5use smith_alloc::{Counting, Scope, Stats, enter, snapshot};
5use smith_alloc::{Counting, Scope, enter, snapshot};
66use smith_core::session::{Entry, Session};
88#[global_allocator]
2424 session
27fn fork_cost(session: &Session, scope: Scope) -> Stats {
27/// Allocations and bytes charged to [`Scope::Session`] by one `fork_at` of the leaf.
28fn fork_cost(session: &Session) -> (u64, u64) {
2829 let leaf = session.selected_id().expect("non-empty session");
29 let before = snapshot(scope);
30 let guard = enter(scope);
30 let before = snapshot(Scope::Session);
31 let guard = enter(Scope::Session);
3132 let fork = session.fork_at(leaf).expect("leaf is known");
3233 drop(guard);
33 let after = snapshot(scope);
34 let after = snapshot(Scope::Session);
3435 assert_eq!(
3536 fork.active_branch().entries.len(),
3637 session.active_branch().entries.len()
3738 );
3839 drop(fork);
39 Stats {
40 allocations: after.allocations - before.allocations,
41 bytes: after.bytes - before.bytes,
42 live: after.live - before.live,
43 peak: after.peak,
44 }
40 (
41 after.allocations - before.allocations,
42 after.bytes - before.bytes,
43 )
4746#[test]
4847fn fork_at_over_1000_entries_is_bounded_and_reproducible() {
4948 let session = linear_session(1000);
50 let first = fork_cost(&session, Scope::Session);
51 let second = fork_cost(&session, Scope::Session);
49 let first = fork_cost(&session);
50 let second = fork_cost(&session);
5251 assert!(
53 first.allocations <= FORK_AT_1000_ALLOCATIONS,
52 first.0 <= FORK_AT_1000_ALLOCATIONS,
5453 "fork_at allocated {} times, bound is {FORK_AT_1000_ALLOCATIONS}",
55 first.allocations
56 );
57 assert_eq!(
58 (first.allocations, first.bytes),
59 (second.allocations, second.bytes)
54 first.0
6055 );
56 assert_eq!(first, second);

smith-harness/src/http.rs

Modified

+3 / −3 text lines

4141 Self::with_timeouts(HEAD_TIMEOUT, CHUNK_TIMEOUT)
4242 }
44 /// An executor bounding connect plus response head by `head` and every
45 /// socket wait after that by `gap`.
44 /// An executor bounding the connect and the response head wait each by
45 /// `head`, and every single socket wait by `gap`.
4646 #[must_use]
4747 pub fn with_timeouts(head: Duration, gap: Duration) -> Self {
4848 let config = ureq::Agent::config_builder()
181181 Ok(0) | Err(_) => return,
182182 Ok(read) => read,
183183 };
184 total += u64::try_from(read).unwrap_or(u64::MAX);
184 total = total.saturating_add(u64::try_from(read).unwrap_or(u64::MAX));
185185 if cancel.is_cancelled() || total > MAX_BODY_BYTES {
186186 return;
187187 }