repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

refactor(ai,harness): single-owner auth registry and catalog state, atomic mock script index; no Mutex

636833813a889be3ce03ca508514e4d5fddc2387

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (4)

+62 / −112 text lines

Diff layout

smith-ai/src/auth.rs

Modified

+18 / −27 text lines

99use std::collections::HashMap;
1010use std::path::{Path, PathBuf};
11use std::sync::{Arc, Mutex};
11use std::sync::Arc;
1212use std::time::{Duration, SystemTime};
1414use crate::models::ProviderKind;
123123 }
126/// Per-provider credential registry with concurrent update safety.
127#[derive(Clone, Default)]
126/// Per-provider credential registry; one owner, updates never touch
127/// unrelated providers.
128#[derive(Default)]
128129pub struct AuthRegistry {
129 credentials: Arc<Mutex<HashMap<String, Credential>>>,
130 credentials: HashMap<String, Credential>,
132133impl AuthRegistry {
137138 }
139140 /// Register or replace the credential for one provider.
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);
143 }
141 pub fn set(&mut self, provider: impl Into<String>, credential: Credential) {
142 self.credentials.insert(provider.into(), credential);
144143 }
146145 /// The registered credential, when present.
147146 #[must_use]
148 pub fn get(&self, provider: &str) -> Option<Credential> {
149 self.credentials
150 .lock()
151 .ok()
152 .and_then(|guard| guard.get(provider).cloned())
147 pub fn get(&self, provider: &str) -> Option<&Credential> {
148 self.credentials.get(provider)
153149 }
155151 /// Whether the provider has a ready credential, without network access.
156152 #[must_use]
157153 pub fn is_ready(&self, provider: &str) -> bool {
158 self.get(provider)
159 .is_some_and(|credential| credential.is_ready())
154 self.get(provider).is_some_and(Credential::is_ready)
160155 }
333328 }
335330 #[test]
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();
338333 registry.set("anthropic", Credential::explicit("a"));
339334 registry.set("openai", Credential::explicit("o"));
340 let writer = std::thread::spawn({
341 let registry = registry.clone();
342 move || {
343 for round in 0..100 {
344 registry.set("anthropic", Credential::explicit(format!("a{round}")));
345 }
346 }
347 });
348 for _ in 0..100 {
335 for round in 0..100 {
336 registry.set("anthropic", Credential::explicit(format!("a{round}")));
349337 assert!(registry.is_ready("openai"));
350338 assert!(registry.is_ready("anthropic"));
351339 }
352 writer.join().ok();
340 assert_eq!(
341 registry.get("openai").map(Credential::describe),
342 Some("explicit:<redacted>".to_string())
343 );
353344 }

smith-ai/src/refresh.rs

Modified

+35 / −60 text lines

88use crate::models::Catalog;
99use smith::tool::CancelHandle;
10use std::sync::{Arc, Mutex};
1110use std::time::SystemTime;
1312/// One published catalog snapshot with its generation and origin.
2120 pub published_at: Option<SystemTime>,
24/// Shared catalog state with generation-checked publication.
23/// Owned catalog state with generation-checked publication.
2524#[derive(Clone, Debug)]
2625pub struct CatalogState {
27 inner: Arc<Mutex<CatalogSnapshot>>,
26 published: CatalogSnapshot,
3029impl CatalogState {
3534 /// Returns the built-in catalog's load error unchanged.
3635 pub fn with_builtin() -> smith::error::Result<Self> {
3736 Ok(Self {
38 inner: Arc::new(Mutex::new(CatalogSnapshot {
37 published: CatalogSnapshot {
3938 catalog: Catalog::builtin()?,
4039 generation: 0,
4140 published_at: None,
42 })),
41 },
4342 })
4443 }
4645 /// Start from an explicit snapshot, for tests.
4746 #[must_use]
48 pub fn from_snapshot(snapshot: CatalogSnapshot) -> Self {
47 pub const fn from_snapshot(snapshot: CatalogSnapshot) -> Self {
4948 Self {
50 inner: Arc::new(Mutex::new(snapshot)),
49 published: snapshot,
5150 }
5251 }
5453 /// The currently published snapshot.
5554 #[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(),
60 }
55 pub const fn snapshot(&self) -> &CatalogSnapshot {
56 &self.published
6157 }
9086/// An injected catalog fetch: beat `generation`, honoring cancellation.
9187pub type Fetch = dyn Fn(u64, &CancelHandle) -> smith::error::Result<(u64, Catalog)>;
93/// Run one refresh attempt against an injected fetch.
94///
95/// # Errors
96///
97/// Propagates a lock-poisoning error only; fetch failures and cancellation
98/// are reported as outcomes with the cache untouched.
99pub fn refresh(
100 state: &CatalogState,
101 fetch: &Fetch,
102 cancel: &CancelHandle,
103) -> smith::error::Result<RefreshOutcome> {
104 let started_generation = state.snapshot().generation;
89/// Run one refresh attempt against an injected fetch; fetch failures and
90/// cancellation are outcomes with the cache untouched.
91pub fn refresh(state: &mut CatalogState, fetch: &Fetch, cancel: &CancelHandle) -> RefreshOutcome {
10592 if cancel.is_cancelled() {
106 return Ok(RefreshOutcome::Cancelled);
93 return RefreshOutcome::Cancelled;
10794 }
108 let attempt = fetch(started_generation, cancel);
95 let attempt = fetch(state.published.generation, cancel);
10996 if cancel.is_cancelled() {
110 return Ok(RefreshOutcome::Cancelled);
97 return RefreshOutcome::Cancelled;
11198 }
11299 let Ok((fetched_generation, catalog)) = attempt else {
113 return Ok(RefreshOutcome::KeptCache);
100 return RefreshOutcome::KeptCache;
114101 };
115 let published = state.snapshot().generation;
116 if fetched_generation <= published {
117 return Ok(RefreshOutcome::StaleDiscarded);
102 // Only the newest generation may publish.
103 if fetched_generation <= state.published.generation {
104 return RefreshOutcome::StaleDiscarded;
118105 }
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(),
123 });
124 };
125 // Re-check under the lock: only the newest generation may publish.
126 if fetched_generation <= guard.generation {
127 return Ok(RefreshOutcome::StaleDiscarded);
128 }
129 guard.generation = fetched_generation;
130 guard.catalog = catalog;
131 guard.published_at = Some(SystemTime::now());
132 Ok(RefreshOutcome::Published {
106 state.published = CatalogSnapshot {
107 catalog,
133108 generation: fetched_generation,
134 })
109 published_at: Some(SystemTime::now()),
110 };
111 RefreshOutcome::Published {
112 generation: fetched_generation,
113 }
137116#[cfg(test)]
160139 #[test]
161140 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));
163142 let cancel = CancelHandle::new();
164143 // Fast refresh publishes generation 5.
165144 let outcome = refresh(
166 &state,
145 &mut state,
167146 &|_gen, _cancel| Ok((5, Catalog::builtin().unwrap())),
168147 &cancel,
169 )
170 .unwrap();
148 );
171149 assert_eq!(outcome, RefreshOutcome::Published { generation: 5 });
172150 // Slow refresh from generation 0 completes later with generation 2:
173151 // stale, must not replace generation 5.
174152 let outcome = refresh(
175 &state,
153 &mut state,
176154 &|_gen, _cancel| Ok((2, Catalog::builtin().unwrap())),
177155 &cancel,
178 )
179 .unwrap();
156 );
180157 assert_eq!(outcome, RefreshOutcome::StaleDiscarded);
181158 assert_eq!(state.snapshot().generation, 5);
182159 }
184161 #[test]
185162 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));
187164 let cancel = CancelHandle::new();
188165 let cancelled_handle = CancelHandle::new();
189166 cancelled_handle.cancel();
190167 let outcome = refresh(
191 &state,
168 &mut state,
192169 &|_gen, _cancel| Ok((9, Catalog::builtin().unwrap())),
193170 &cancelled_handle,
194 )
195 .unwrap();
171 );
196172 assert_eq!(outcome, RefreshOutcome::Cancelled);
197173 let outcome = refresh(
198 &state,
174 &mut state,
199175 &|_gen, _cancel| {
200176 Err(smith::error::SmithError::Provider {
201177 fault: smith::error::ProviderFault::Transient {
204180 })
205181 },
206182 &cancel,
207 )
208 .unwrap();
183 );
209184 assert_eq!(outcome, RefreshOutcome::KeptCache);
210185 assert_eq!(state.snapshot().generation, 3);
211186 }

smith-harness/src/lib.rs

Modified

+8 / −21 text lines

2020use smith::provider::{ProviderStream, StreamFn};
2121use smith::stream::StreamEvent;
2222use std::sync::Arc;
23use std::sync::Mutex;
23use std::sync::atomic::{AtomicUsize, Ordering};
2525/// A scripted mock provider: one canned response per request, then a final
2626/// apologetic refusal.
2727#[must_use]
28pub fn mock_stream(
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() {
36 guard.push(request);
37 }
38 let index = seen_stream
39 .lock()
40 .map_or(0, |guard| guard.len().saturating_sub(1));
41 let response = script
42 .lock()
43 .ok()
44 .and_then(|guard| guard.get(index).cloned())
45 .unwrap_or_default();
28pub 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();
4634 let stream: ProviderStream = Box::pin(futures::stream::iter(response.into_iter().map(Ok)));
4735 stream
48 });
49 (stream, seen)
36 })
5239/// Convenience: a mock reply of plain text.

smith-harness/src/runtime.rs

Modified

+1 / −4 text lines

136136 records: RecordSink,
137137) -> Result<StreamFn> {
138138 match provider {
139 RuntimeProvider::Mock(script) => {
140 let (stream, _seen) = crate::mock_stream(script.clone());
141 Ok(stream)
142 }
139 RuntimeProvider::Mock(script) => Ok(crate::mock_stream(script.clone())),
143140 RuntimeProvider::OpenAiCompatible { base_url, model }
144141 | RuntimeProvider::Anthropic { base_url, model }
145142 | RuntimeProvider::Google { base_url, model } => {