README Source History Refs Reviews Compare Notes Search Review guide refactor(ai,harness): single-owner auth registry and catalog state, atomic mock script index; no Mutex
636833813a889be3ce03ca508514e4d5fddc2387
Oliver Jan Krylow <oliver@bugabinga.net > · 26 Sep 2026
unsigned
Browse files Compare with HEAD
Changed files (4) Diff layout Auto Unified Split
smith-ai/src/auth.rs Modified +18 / −27 text lines
9 9 use std::collections::HashMap;use std::collections::HashMap;10 10 use std::path::{Path, PathBuf};use std::path::{Path, PathBuf};11 - use std::sync::{ Arc, Mutex } ;12 12 use std::time::{Duration, SystemTime};use std::time::{Duration, SystemTime};14 14 use crate ::models::ProviderKind;use crate ::models::ProviderKind;127 - #[derive(Clone , Default)]128 129 pub struct AuthRegistry {pub struct AuthRegistry {129 - credentials: Arc < Mutex < HashMap<String , Credential>> > ,130 + credentials: HashMap<String , Credential>,132 133 impl AuthRegistry {impl AuthRegistry {140 - pub fn set (& self, provider: impl Into <String >, credential: Credential) {141 - if let Ok (mut guard) = self.credentials.lock () {142 - guard .insert (provider.into (), credential);141 + pub fn set (&mut self, provider: impl Into <String >, credential: Credential) {142 + self .credentials . insert (provider.into (), credential);147 146 #[must_use] #[must_use]148 - pub fn get (& self, provider: &str ) -> Option <Credential> {152 - .and_then (|guard| guard.get (provider).cloned ())147 + pub fn get (& self, provider: &str ) -> Option <& Credential> {148 + self.credentials. get ( provider ) 156 152 #[must_use] #[must_use]157 153 pub fn is_ready (& self, provider: &str ) -> bool { pub fn is_ready (& self, provider: &str ) -> bool {159 - .is_some_and (|credential| credential.is_ready ())154 + self.get (provider).is_some_and (Credential::is_ready)336 - fn concurrent_updates_preserve_unrelated_providers () {337 - let registry = AuthRegistry::new();331 + fn interleaved_updates_preserve_unrelated_providers () {332 + let mut registry = AuthRegistry::new();338 333 registry.set ("anthropic" , Credential::explicit("a" )); registry.set ("anthropic" , Credential::explicit("a" ));339 334 registry.set ("openai" , Credential::explicit("o" )); registry.set ("openai" , Credential::explicit("o" ));340 - let writer = std::thread::spawn({341 - let registry = registry.clone ();343 - for round in 0 .. 100 {344 - registry.set ("anthropic" , Credential::explicit(format! ("a{round}" )));335 + for round in 0 .. 100 {336 + registry.set ("anthropic" , Credential::explicit(format! ("a{round}" )));349 337 assert! (registry.is_ready ("openai" )); assert! (registry.is_ready ("openai" ));350 338 assert! (registry.is_ready ("anthropic" )); assert! (registry.is_ready ("anthropic" ));341 + registry.get ("openai" ).map (Credential::describe),342 + Some ("explicit:<redacted>" .to_string ())smith-ai/src/refresh.rs Modified +35 / −60 text lines
8 8 use crate ::models::Catalog;use crate ::models::Catalog;9 9 use smith::tool::CancelHandle;use smith::tool::CancelHandle;10 - use std::sync::{Arc, Mutex};
11 10 use std::time::SystemTime;use std::time::SystemTime;21 20 pub published_at: Option <SystemTime>, pub published_at: Option <SystemTime>,25 24 #[derive(Clone, Debug)]#[derive(Clone, Debug)]26 25 pub struct CatalogState {pub struct CatalogState {27 - inner: Arc<Mutex<CatalogSnapshot>>,26 + published: CatalogSnapshot,30 29 impl CatalogState {impl CatalogState {36 35 pub fn with_builtin () -> smith::error::Result <Self > { pub fn with_builtin () -> smith::error::Result <Self > {38 - inner: Arc::new(Mutex::new(CatalogSnapshot {37 + published: CatalogSnapshot {39 38 catalog: Catalog::builtin()? , catalog: Catalog::builtin()? ,40 39 generation: 0 , generation: 0 ,41 40 published_at: None , published_at: None ,47 46 #[must_use] #[must_use]48 - pub fn from_snapshot (snapshot: CatalogSnapshot) -> Self {47 + pub const fn from_snapshot (snapshot: CatalogSnapshot) -> Self {50 - inner: Arc::new(Mutex::new(snapshot)),55 54 #[must_use] #[must_use]56 - pub fn snapshot (& self) -> CatalogSnapshot {57 - match self.inner.lock () {58 - Ok (guard) => guard.clone (),59 - Err (poisoned) => poisoned.into_inner ().clone (),55 + pub const fn snapshot (& self) -> & CatalogSnapshot {91 87 pub type Fetch = dyn Fn (u64 , & CancelHandle) -> smith::error::Result <(u64 , Catalog)>;pub type Fetch = dyn Fn (u64 , & CancelHandle) -> smith::error::Result <(u64 , Catalog)>;100 - state: & CatalogState,102 - cancel: & CancelHandle,103 - ) -> smith::error::Result <RefreshOutcome> {104 - let started_generation = state.snapshot ().generation;91 + pub fn refresh (state: &mut CatalogState, fetch: & Fetch, cancel: & CancelHandle) -> RefreshOutcome {105 92 if cancel.is_cancelled () { if cancel.is_cancelled () {106 - return Ok ( RefreshOutcome::Cancelled) ;93 + return RefreshOutcome::Cancelled;108 - let attempt = fetch (started_generation, cancel);95 + let attempt = fetch (state.published.generation, cancel);109 96 if cancel.is_cancelled () { if cancel.is_cancelled () {110 - return Ok ( RefreshOutcome::Cancelled) ;97 + return RefreshOutcome::Cancelled;112 99 let Ok ((fetched_generation, catalog)) = attempt else { let Ok ((fetched_generation, catalog)) = attempt else {113 - return Ok ( RefreshOutcome::KeptCache) ;100 + return RefreshOutcome::KeptCache;115 - let published = state.snapshot ().generation;116 - if fetched_generation <= published {117 - return Ok ( RefreshOutcome::StaleDiscarded) ;103 + if fetched_generation <= state . published. generation {104 + return RefreshOutcome::StaleDiscarded;119 - let Ok (mut guard) = state.inner.lock () else {120 - return Err (smith::error::SmithError::Session {121 - code: "CATALOG_LOCK_POISONED" .to_string (),122 - message: "catalog state lock poisoned" .to_string (),126 - if fetched_generation <= guard.generation {127 - return Ok (RefreshOutcome::StaleDiscarded);129 - guard.generation = fetched_generation;130 - guard.catalog = catalog;131 - guard.published_at = Some (SystemTime::now());132 - Ok (RefreshOutcome::Published {106 + state.published = CatalogSnapshot {133 108 generation: fetched_generation, generation: fetched_generation,109 + published_at: Some (SystemTime::now()),111 + RefreshOutcome::Published {112 + generation: fetched_generation,137 116 #[cfg(test)]#[cfg(test)]161 140 fn newer_publication_wins_and_stale_work_is_discarded () { fn newer_publication_wins_and_stale_work_is_discarded () {162 - let state = CatalogState::from_snapshot(snapshot (0 ));141 + let mut state = CatalogState::from_snapshot(snapshot (0 ));163 142 let cancel = CancelHandle::new(); let cancel = CancelHandle::new();165 144 let outcome = refresh ( let outcome = refresh (167 146 &| _gen, _cancel| Ok ((5 , Catalog::builtin().unwrap ())), &| _gen, _cancel| Ok ((5 , Catalog::builtin().unwrap ())),171 149 assert_eq! (outcome, RefreshOutcome::Published { generation: 5 }); assert_eq! (outcome, RefreshOutcome::Published { generation: 5 });174 152 let outcome = refresh ( let outcome = refresh (176 154 &| _gen, _cancel| Ok ((2 , Catalog::builtin().unwrap ())), &| _gen, _cancel| Ok ((2 , Catalog::builtin().unwrap ())),180 157 assert_eq! (outcome, RefreshOutcome::StaleDiscarded); assert_eq! (outcome, RefreshOutcome::StaleDiscarded);181 158 assert_eq! (state.snapshot ().generation, 5 ); assert_eq! (state.snapshot ().generation, 5 );185 162 fn cancelled_and_failed_fetches_keep_the_cache () { fn cancelled_and_failed_fetches_keep_the_cache () {186 - let state = CatalogState::from_snapshot(snapshot (3 ));163 + let mut state = CatalogState::from_snapshot(snapshot (3 ));187 164 let cancel = CancelHandle::new(); let cancel = CancelHandle::new();188 165 let cancelled_handle = CancelHandle::new(); let cancelled_handle = CancelHandle::new();189 166 cancelled_handle.cancel (); cancelled_handle.cancel ();190 167 let outcome = refresh ( let outcome = refresh (192 169 &| _gen, _cancel| Ok ((9 , Catalog::builtin().unwrap ())), &| _gen, _cancel| Ok ((9 , Catalog::builtin().unwrap ())),193 170 & cancelled_handle, & cancelled_handle,196 172 assert_eq! (outcome, RefreshOutcome::Cancelled); assert_eq! (outcome, RefreshOutcome::Cancelled);197 173 let outcome = refresh ( let outcome = refresh (199 175 &| _gen, _cancel| { &| _gen, _cancel| {200 176 Err (smith::error::SmithError::Provider { Err (smith::error::SmithError::Provider {201 177 fault: smith::error::ProviderFault::Transient { fault: smith::error::ProviderFault::Transient {209 184 assert_eq! (outcome, RefreshOutcome::KeptCache); assert_eq! (outcome, RefreshOutcome::KeptCache);210 185 assert_eq! (state.snapshot ().generation, 3 ); assert_eq! (state.snapshot ().generation, 3 );smith-harness/src/lib.rs Modified +8 / −21 text lines
20 20 use smith::provider::{ProviderStream, StreamFn};use smith::provider::{ProviderStream, StreamFn};21 21 use smith::stream::StreamEvent;use smith::stream::StreamEvent;22 22 use std::sync::Arc;use std::sync::Arc;23 + use std::sync::atomic::{AtomicUsize, Ordering};27 27 #[must_use]#[must_use]29 - script: Vec <Vec <StreamEvent>>,30 - ) -> (StreamFn, Arc<Mutex<Vec <smith::provider::ProviderRequest>>>) {31 - let seen: Arc<Mutex<Vec <smith::provider::ProviderRequest>>> = Arc::new(Mutex::new(Vec ::new()));32 - let script = Arc::new(Mutex::new(script));33 - let seen_stream = Arc::clone(& seen);34 - let stream: StreamFn = Arc::new(move | request, _cancel| {35 - if let Ok (mut guard) = seen_stream.lock () {38 - let index = seen_stream40 - .map_or (0 , |guard| guard.len ().saturating_sub (1 ));41 - let response = script44 - .and_then (|guard| guard.get (index).cloned ())45 - .unwrap_or_default ();28 + pub fn mock_stream (script: Vec <Vec <StreamEvent>>) -> StreamFn {29 + let script: Arc<[Vec <StreamEvent>]> = script.into ();30 + let next = AtomicUsize::new(0 );31 + Arc::new(move | _request, _cancel| {32 + let index = next.fetch_add (1 , Ordering::Relaxed);33 + let response = script.get (index).cloned ().unwrap_or_default ();46 34 let stream: ProviderStream = Box ::pin(futures::stream::iter(response.into_iter ().map (Ok ))); let stream: ProviderStream = Box ::pin(futures::stream::iter(response.into_iter ().map (Ok )));smith-harness/src/runtime.rs Modified +1 / −4 text lines
136 136 records: RecordSink, records: RecordSink,137 137 ) -> Result <StreamFn> {) -> Result <StreamFn> {138 138 match provider { match provider {139 - RuntimeProvider::Mock(script) => {140 - let (stream, _seen) = crate ::mock_stream(script.clone ());139 + RuntimeProvider::Mock(script) => Ok (crate ::mock_stream(script.clone ())),143 140 RuntimeProvider::OpenAiCompatible { base_url, model } RuntimeProvider::OpenAiCompatible { base_url, model }144 141 | RuntimeProvider::Anthropic { base_url, model } | RuntimeProvider::Anthropic { base_url, model }145 142 | RuntimeProvider::Google { base_url, model } => { | RuntimeProvider::Google { base_url, model } => {