diff --git a/src/ai/registry.rs b/src/ai/registry.rs index 7f4c30d..693462c 100644 --- a/src/ai/registry.rs +++ b/src/ai/registry.rs @@ -7,7 +7,7 @@ //! silently dead service into a closed connection, and the connection task //! turns that into a [`Registry::remove`]. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; @@ -23,6 +23,12 @@ pub struct Worker { pub id: String, pub service: String, pub capabilities: Vec, + /// Capabilities this worker claimed in its `Hello` and then answered + /// `unknown_capability` for. The advertised list is left untouched; this + /// is the subtraction applied on top of it, so a self-contradicting answer + /// stops routing without rewriting what the service declared. See + /// [`Registry::withdraw`]. + withdrawn: Mutex>, /// Ceiling from the worker's `Hello`, already clamped by /// [`clamp_concurrency`]. pub max_concurrent: usize, @@ -41,6 +47,18 @@ impl Worker { pub fn conn(&self) -> &C { &self.conn } + + /// Does this worker offer `capability` right now? False for a name it + /// never declared, and false for one it declared and then withdrew by + /// refusing it as unknown ([`Registry::withdraw`]). + pub fn offers(&self, capability: &str) -> bool { + self.capabilities.iter().any(|c| c == capability) + && !self + .withdrawn + .lock() + .expect("ai registry lock") + .contains(capability) + } } /// A reserved slot on a worker. Holding one is what makes the worker's @@ -114,6 +132,12 @@ impl Default for Registry { impl Registry { /// Add a freshly handshaken worker. `id` is caller-assigned (a ULID) and /// must be unique; reusing one replaces the old entry. + /// + /// A fresh `Hello` is also how a withdrawn capability comes back: the + /// entry is built from the handshake alone (see [`Registry::withdraw`] for + /// why a claim is ever subtracted), so a service that reconnects — + /// necessarily landing here under a new worker id — offers everything it + /// declares again. pub fn insert( &self, id: String, @@ -126,6 +150,7 @@ impl Registry { id: id.clone(), service, capabilities, + withdrawn: Mutex::new(HashSet::new()), max_concurrent, inflight: AtomicUsize::new(0), conn, @@ -158,7 +183,7 @@ impl Registry { let workers = self.workers.lock().expect("ai registry lock"); let mut offering = workers .values() - .filter(|w| w.capabilities.iter().any(|c| c == capability)) + .filter(|w| w.offers(capability)) .peekable(); if offering.peek().is_none() { return Err(AiError::NoWorker(capability.to_string())); @@ -185,7 +210,15 @@ impl Registry { .map(|w| WorkerSnapshot { id: w.id.clone(), service: w.service.clone(), - capabilities: w.capabilities.clone(), + // What the worker is offering, not what it declared: a + // withdrawn capability must vanish from discovery exactly as + // it vanishes from routing. + capabilities: w + .capabilities + .iter() + .filter(|c| w.offers(c)) + .cloned() + .collect(), inflight: w.inflight(), max_concurrent: w.max_concurrent, }) @@ -195,12 +228,46 @@ impl Registry { } /// Is anything at all connected for `capability`? + /// + /// What counts is what a worker is *offering*, so a claim one of them has + /// withdrawn ([`Registry::withdraw`]) reads as absent — which is what lets + /// a door branch on this and stop queuing work nobody will do. pub fn has_capability(&self, capability: &str) -> bool { self.workers .lock() .expect("ai registry lock") .values() - .any(|w| w.capabilities.iter().any(|c| c == capability)) + .any(|w| w.offers(capability)) + } + + /// Withdraw one capability from one worker: it advertised the name in its + /// `Hello` and then answered a dispatch with a permanent, self-contradictory + /// refusal (`unknown_capability`). The claim cannot be trusted again for + /// this connection, so `pick` and `has_capability` stop seeing it and the + /// worker drops out of discovery for that name. + /// + /// This is a subtraction, never a mutation of the declared list: a fresh + /// [`Registry::insert`] — every reconnect does one, under a new worker id — + /// restores the capability, so a service that fixes itself recovers with no + /// operator action. Scoped to the one worker that answered: a sibling + /// process declaring the same capability is untouched. + /// + /// A no-op for a worker already removed (its connection closed) or for a + /// capability it never declared, so a late answer from a dead or confused + /// worker cannot invent a state. + pub fn withdraw(&self, id: &str, capability: &str) { + let workers = self.workers.lock().expect("ai registry lock"); + let Some(worker) = workers.get(id) else { + return; + }; + if !worker.capabilities.iter().any(|c| c == capability) { + return; + } + worker + .withdrawn + .lock() + .expect("ai registry lock") + .insert(capability.to_string()); } } @@ -345,6 +412,53 @@ mod tests { assert!(reg.snapshot().is_empty()); } + #[tokio::test] + async fn a_withdrawn_capability_stops_routing_and_a_fresh_hello_restores_it() { + let reg = registry_with(&[("w1", &["ocr.extract", "ocr.classify"], 4)]); + reg.withdraw("w1", "ocr.extract"); + assert!(!reg.has_capability("ocr.extract")); + assert!( + reg.has_capability("ocr.classify"), + "the sibling claim is untouched" + ); + assert!(matches!( + reg.pick("ocr.extract").unwrap_err(), + AiError::NoWorker(_) + )); + assert_eq!( + reg.snapshot()[0].capabilities, + vec!["ocr.classify".to_string()], + "discovery reports what is offered, not what was declared" + ); + + // A reconnect re-inserts the worker from its handshake alone. + reg.insert( + "w1".into(), + "svc".into(), + vec!["ocr.extract".into(), "ocr.classify".into()], + 4, + (), + ); + assert!(reg.has_capability("ocr.extract")); + reg.pick("ocr.extract").expect("restored"); + } + + #[tokio::test] + async fn withdrawing_one_worker_leaves_a_sibling_offering_the_same() { + let reg = registry_with(&[("w1", &["ocr.extract"], 2), ("w2", &["ocr.extract"], 2)]); + reg.withdraw("w1", "ocr.extract"); + assert!(reg.has_capability("ocr.extract")); + assert_eq!(reg.pick("ocr.extract").unwrap().worker().id, "w2"); + + // Neither a name the worker never declared nor a worker already gone + // is a state withdraw may invent. + reg.withdraw("w2", "grade.essay"); + assert!(!reg.has_capability("grade.essay")); + reg.remove("w2"); + reg.withdraw("w2", "ocr.extract"); + assert!(!reg.has_capability("ocr.extract")); + } + #[tokio::test] async fn declared_concurrency_is_clamped_into_range() { assert_eq!(clamp_concurrency(None), AI_DEFAULT_CONCURRENT_PER_WORKER); diff --git a/src/ai/server.rs b/src/ai/server.rs index d94674b..a45700c 100644 --- a/src/ai/server.rs +++ b/src/ai/server.rs @@ -336,6 +336,25 @@ impl AiBridge { .instrument(span.clone()) .await; + // A worker that answers `unknown_capability` for a name it advertised + // in its own `Hello` has contradicted its handshake. That claim is the + // only reason this dispatch was routed here, and the only reason the + // caller's door answered `202` instead of "nothing is connected", so it + // is withdrawn: `has_capability` stops seeing it and the next door call + // refuses instead of queuing work nobody will do. A reconnect restores + // it (every fresh `Hello` inserts a worker with its declared list). + if let Err(AiError::Remote { code, .. }) = &outcome + && contradicts_its_own_claim(code) + { + self.inner.registry.withdraw(&lease.worker().id, capability); + tracing::warn!( + service = %lease.worker().service, + capability, + code = %code, + "AI service refused a capability it advertised; claim withdrawn until it reconnects" + ); + } + metrics .ai_request_duration .record(started.elapsed().as_secs_f64(), &attrs); @@ -381,6 +400,22 @@ impl AiBridge { } } +/// Does this refusal code mean the worker contradicted a claim it made in its +/// own `Hello` — it advertised the capability and then answered that this name +/// is not one it implements? +/// +/// Only `unknown_capability` does. The protocol's refusal vocabulary names no +/// sibling for "no operation by this name": its one example of a service-defined +/// code (`unsupported_image`) is a verdict about *this request's payload*, and +/// the other codes a service may answer — `invalid_payload`, `unavailable`, +/// `timed_out`, `internal`, `capacity` — are the same kind of thing. Those must +/// leave the claim standing so a busy, restarting or overloaded service keeps +/// getting the next request; only a permanent "this name is not mine" licenses +/// a withdrawal (see [`Registry::withdraw`]). +fn contradicts_its_own_claim(code: &str) -> bool { + code == "unknown_capability" +} + /// Accept connections until the endpoint closes. One task per service. async fn accept_loop(inner: Arc) { while let Some(incoming) = inner.endpoint.accept().await { diff --git a/tests/ai_bridge.rs b/tests/ai_bridge.rs index a39d579..b5900a5 100644 --- a/tests/ai_bridge.rs +++ b/tests/ai_bridge.rs @@ -3539,6 +3539,221 @@ async fn no_insight_refresh_worker_means_503_and_nothing_is_dispatched() { assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); } +// ---- a capability a service contradicts -------------------------------- +// +// The class this closes: a service announces `insight.refresh` in its `Hello`, +// the door reads that as availability and answers `202`, and the service then +// answers the dispatch with `unknown_capability` — a permanent, self- +// contradictory refusal. Nothing is queued and nobody is told. So the registry +// withdraws the contradicted claim, and the *next* door call takes the `503` +// path it already had. A transient refusal must not do this: a busy or +// restarting service keeps its claim. + +/// Wait until `bridge` offers (or no longer offers) `capability`. +async fn await_capability(bridge: &AiBridge, capability: &str, offered: bool) { + for _ in 0..500 { + if bridge.has_capability(capability) == offered { + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + panic!("the bridge never turned `{capability}` offered={offered}"); +} + +/// The capability names `GET /ai/capabilities` lists right now. +async fn listed_capabilities(app: &Router, cookie: &str) -> Vec { + let res = common::send(app, "GET", "/ai/capabilities", Some(cookie), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + res.body["capabilities"] + .as_array() + .expect("a capabilities array") + .iter() + .map(|entry| { + entry["capability"] + .as_str() + .expect("a capability name") + .to_string() + }) + .collect() +} + +#[tokio::test] +async fn a_capability_refused_as_unknown_is_withdrawn_so_the_door_stops_queuing() { + let bridge = bridge().await; + let service = connect_service( + &bridge, + hello("zeka", &[AI_INSIGHT_REFRESH_CAPABILITY]), + Behaviour::Fail { + code: "unknown_capability".into(), + message: "'insight.refresh' bu serviste tanimli degil".into(), + }, + ) + .await; + await_workers(&bridge, 1).await; + let (app, db) = chat_app(&bridge).await; + let staff = common::login_as(&app, &db, "mudur", "manager").await; + + // While the claim stands the door queues — the `202` the user saw. + let res = common::send( + &app, + "POST", + "/insights/refresh", + Some(&staff), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); + assert_eq!( + await_seen(&service, 1).await[0].capability, + AI_INSIGHT_REFRESH_CAPABILITY + ); + + // The refusal is permanent and contradicts the handshake, so the claim is + // withdrawn — and the very next refresh is refused rather than queued. + await_capability(&bridge, AI_INSIGHT_REFRESH_CAPABILITY, false).await; + let res = common::send( + &app, + "POST", + "/insights/refresh", + Some(&staff), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body); + assert_eq!(res.body["error"], "no AI service is connected right now"); + assert_eq!( + service.seen().len(), + 1, + "the refused refresh dispatched nothing" + ); + + // Discovery tells the same story: the capability is gone from the list. + assert!( + !listed_capabilities(&app, &staff) + .await + .contains(&AI_INSIGHT_REFRESH_CAPABILITY.to_string()), + "a withdrawn capability must not be advertised as available" + ); +} + +#[tokio::test] +async fn a_transient_refusal_keeps_the_claim_and_the_door_keeps_queuing() { + let bridge = bridge().await; + let service = connect_service( + &bridge, + hello("zeka", &[AI_INSIGHT_REFRESH_CAPABILITY]), + Behaviour::Fail { + code: "unavailable".into(), + message: "the school database could not be reached".into(), + }, + ) + .await; + await_workers(&bridge, 1).await; + + // Drive one dispatch through the registry directly so the refusal is known + // to have been processed before the claim is read — the door's own + // dispatch is detached and would leave this racy. + let err = bridge + .dispatch(&demo(), AI_INSIGHT_REFRESH_CAPABILITY, json!({})) + .await + .unwrap_err(); + assert!( + matches!(&err, AiError::Remote { code, .. } if code == "unavailable"), + "{err}" + ); + assert!( + bridge.has_capability(AI_INSIGHT_REFRESH_CAPABILITY), + "a busy or unreachable service has not contradicted its claim" + ); + + // So the door still queues, and discovery still lists it. + let (app, db) = chat_app(&bridge).await; + let staff = common::login_as(&app, &db, "mudur", "manager").await; + let res = common::send( + &app, + "POST", + "/insights/refresh", + Some(&staff), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); + assert_eq!( + await_seen(&service, 1).await[0].capability, + AI_INSIGHT_REFRESH_CAPABILITY + ); + assert!( + listed_capabilities(&app, &staff) + .await + .contains(&AI_INSIGHT_REFRESH_CAPABILITY.to_string()) + ); +} + +#[tokio::test] +async fn a_reconnecting_service_restores_a_withdrawn_capability() { + let bridge = bridge().await; + let broken = connect_service( + &bridge, + hello("zeka", &[AI_INSIGHT_REFRESH_CAPABILITY]), + Behaviour::Fail { + code: "unknown_capability".into(), + message: "not implemented".into(), + }, + ) + .await; + await_workers(&bridge, 1).await; + let (app, db) = chat_app(&bridge).await; + let staff = common::login_as(&app, &db, "mudur", "manager").await; + + // One refresh withdraws the claim. + common::send( + &app, + "POST", + "/insights/refresh", + Some(&staff), + Some(json!({})), + ) + .await; + await_capability(&bridge, AI_INSIGHT_REFRESH_CAPABILITY, false).await; + + // The service restarts — the withdrawal is per connection, never durable. + broken.conn.close(0u32.into(), b"restarting"); + drop(broken); + await_workers(&bridge, 0).await; + + let fixed = connect_service( + &bridge, + hello("zeka", &[AI_INSIGHT_REFRESH_CAPABILITY]), + Behaviour::Echo, + ) + .await; + await_workers(&bridge, 1).await; + assert!( + bridge.has_capability(AI_INSIGHT_REFRESH_CAPABILITY), + "a fresh Hello restores the declared capability" + ); + assert!( + listed_capabilities(&app, &staff) + .await + .contains(&AI_INSIGHT_REFRESH_CAPABILITY.to_string()) + ); + + // And it serves again: the door queues and the dispatch reaches it. + let res = common::send( + &app, + "POST", + "/insights/refresh", + Some(&staff), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); + assert_eq!( + await_seen(&fixed, 1).await[0].capability, + AI_INSIGHT_REFRESH_CAPABILITY + ); +} + // ------------------------------------------- the backend-served capabilities -- // // The other direction: a service calling the *backend*. ZEKA's storage