forge
Explore
Log in

Don't you dare go Hollow

Withdraw a capability a service refuses as unknown

Browse files at this commit

0eb20f9e1d7214499ec5253af36c0657d3fe3333Ahmet Kaan GümüşParent: 81a8384
  • fix
    • withdraw a capability a service refuses as unknown
Show full message
🐛 fix(ai): withdraw a capability a service refuses as unknown

A service that advertises `insight.refresh` in its `Hello` and then answers
the dispatch with `unknown_capability` has contradicted its own handshake.
The door read that advertisement as availability, queued the work with a
`202`, and the refusal could only ever be a WARN — the user saw success and
nothing happened. `rag.index`, `insight.refresh` and `insight.student` have
each bitten this way.

Now the registry withdraws the contradicted claim (`Registry::withdraw`):
`Worker::offers` — what `pick`, `has_capability` and the snapshots read — is
false for it, so routing drops the name and `GET /ai/capabilities` stops
listing it. Every door already branches on `has_capability`, so the next
call takes the `503` path it already had instead of queuing work nobody will
do. The WARN names the service, the capability and the refusal code.

Only a permanent, self-contradictory refusal does this. `unknown_capability`
is the one code the protocol defines for "no operation by this name" — its
example service-defined code (`unsupported_image`) is a verdict about a
payload, not a claim about what the worker serves. Transient verdicts
(`unavailable`, `timed_out`, `internal`, `capacity`) leave the claim
standing, so a busy or restarting service keeps getting the next request.

The withdrawal is per connection, never durable: every reconnect inserts a
fresh worker built from its `Hello` alone, so a service that fixes itself
restores the capability with no operator action.

Tests: a refused refresh flips the next `POST /insights/refresh` to 503 and
drops the capability from discovery (proved failing before the change); an
`unavailable` refusal keeps both the 202 and the listing; a reconnect
restores it — plus two registry unit tests.
Local-Gate: 8718d07b6fbc70148eebea518febeb7bba764a46 (1486 passed, 474s)
src/ai/registry.rsmodified+118 -4
@@ -7,7 +7,7 @@
7 //! silently dead service into a closed connection, and the connection task7 //! silently dead service into a closed connection, and the connection task
8 //! turns that into a [`Registry::remove`].8 //! turns that into a [`Registry::remove`].
9 9
10-use std::collections::HashMap;10+use std::collections::{HashMap, HashSet};
11 use std::sync::atomic::{AtomicUsize, Ordering};11 use std::sync::atomic::{AtomicUsize, Ordering};
12 use std::sync::{Arc, Mutex};12 use std::sync::{Arc, Mutex};
13 13
@@ -23,6 +23,12 @@ pub struct Worker<C> {
23 pub id: String,23 pub id: String,
24 pub service: String,24 pub service: String,
25 pub capabilities: Vec<String>,25 pub capabilities: Vec<String>,
26+ /// Capabilities this worker claimed in its `Hello` and then answered
27+ /// `unknown_capability` for. The advertised list is left untouched; this
28+ /// is the subtraction applied on top of it, so a self-contradicting answer
29+ /// stops routing without rewriting what the service declared. See
30+ /// [`Registry::withdraw`].
31+ withdrawn: Mutex<HashSet<String>>,
26 /// Ceiling from the worker's `Hello`, already clamped by32 /// Ceiling from the worker's `Hello`, already clamped by
27 /// [`clamp_concurrency`].33 /// [`clamp_concurrency`].
28 pub max_concurrent: usize,34 pub max_concurrent: usize,
@@ -41,6 +47,18 @@ impl<C> Worker<C> {
41 pub fn conn(&self) -> &C {47 pub fn conn(&self) -> &C {
42 &self.conn48 &self.conn
43 }49 }
50+
51+ /// Does this worker offer `capability` right now? False for a name it
52+ /// never declared, and false for one it declared and then withdrew by
53+ /// refusing it as unknown ([`Registry::withdraw`]).
54+ pub fn offers(&self, capability: &str) -> bool {
55+ self.capabilities.iter().any(|c| c == capability)
56+ && !self
57+ .withdrawn
58+ .lock()
59+ .expect("ai registry lock")
60+ .contains(capability)
61+ }
44 }62 }
45 63
46 /// A reserved slot on a worker. Holding one is what makes the worker's64 /// A reserved slot on a worker. Holding one is what makes the worker's
@@ -114,6 +132,12 @@ impl<C> Default for Registry<C> {
114 impl<C> Registry<C> {132 impl<C> Registry<C> {
115 /// Add a freshly handshaken worker. `id` is caller-assigned (a ULID) and133 /// Add a freshly handshaken worker. `id` is caller-assigned (a ULID) and
116 /// must be unique; reusing one replaces the old entry.134 /// must be unique; reusing one replaces the old entry.
135+ ///
136+ /// A fresh `Hello` is also how a withdrawn capability comes back: the
137+ /// entry is built from the handshake alone (see [`Registry::withdraw`] for
138+ /// why a claim is ever subtracted), so a service that reconnects —
139+ /// necessarily landing here under a new worker id — offers everything it
140+ /// declares again.
117 pub fn insert(141 pub fn insert(
118 &self,142 &self,
119 id: String,143 id: String,
@@ -126,6 +150,7 @@ impl<C> Registry<C> {
126 id: id.clone(),150 id: id.clone(),
127 service,151 service,
128 capabilities,152 capabilities,
153+ withdrawn: Mutex::new(HashSet::new()),
129 max_concurrent,154 max_concurrent,
130 inflight: AtomicUsize::new(0),155 inflight: AtomicUsize::new(0),
131 conn,156 conn,
@@ -158,7 +183,7 @@ impl<C> Registry<C> {
158 let workers = self.workers.lock().expect("ai registry lock");183 let workers = self.workers.lock().expect("ai registry lock");
159 let mut offering = workers184 let mut offering = workers
160 .values()185 .values()
161- .filter(|w| w.capabilities.iter().any(|c| c == capability))186+ .filter(|w| w.offers(capability))
162 .peekable();187 .peekable();
163 if offering.peek().is_none() {188 if offering.peek().is_none() {
164 return Err(AiError::NoWorker(capability.to_string()));189 return Err(AiError::NoWorker(capability.to_string()));
@@ -185,7 +210,15 @@ impl<C> Registry<C> {
185 .map(|w| WorkerSnapshot {210 .map(|w| WorkerSnapshot {
186 id: w.id.clone(),211 id: w.id.clone(),
187 service: w.service.clone(),212 service: w.service.clone(),
188- capabilities: w.capabilities.clone(),213+ // What the worker is offering, not what it declared: a
214+ // withdrawn capability must vanish from discovery exactly as
215+ // it vanishes from routing.
216+ capabilities: w
217+ .capabilities
218+ .iter()
219+ .filter(|c| w.offers(c))
220+ .cloned()
221+ .collect(),
189 inflight: w.inflight(),222 inflight: w.inflight(),
190 max_concurrent: w.max_concurrent,223 max_concurrent: w.max_concurrent,
191 })224 })
@@ -195,12 +228,46 @@ impl<C> Registry<C> {
195 }228 }
196 229
197 /// Is anything at all connected for `capability`?230 /// Is anything at all connected for `capability`?
231+ ///
232+ /// What counts is what a worker is *offering*, so a claim one of them has
233+ /// withdrawn ([`Registry::withdraw`]) reads as absent — which is what lets
234+ /// a door branch on this and stop queuing work nobody will do.
198 pub fn has_capability(&self, capability: &str) -> bool {235 pub fn has_capability(&self, capability: &str) -> bool {
199 self.workers236 self.workers
200 .lock()237 .lock()
201 .expect("ai registry lock")238 .expect("ai registry lock")
202 .values()239 .values()
203- .any(|w| w.capabilities.iter().any(|c| c == capability))240+ .any(|w| w.offers(capability))
241+ }
242+
243+ /// Withdraw one capability from one worker: it advertised the name in its
244+ /// `Hello` and then answered a dispatch with a permanent, self-contradictory
245+ /// refusal (`unknown_capability`). The claim cannot be trusted again for
246+ /// this connection, so `pick` and `has_capability` stop seeing it and the
247+ /// worker drops out of discovery for that name.
248+ ///
249+ /// This is a subtraction, never a mutation of the declared list: a fresh
250+ /// [`Registry::insert`] — every reconnect does one, under a new worker id —
251+ /// restores the capability, so a service that fixes itself recovers with no
252+ /// operator action. Scoped to the one worker that answered: a sibling
253+ /// process declaring the same capability is untouched.
254+ ///
255+ /// A no-op for a worker already removed (its connection closed) or for a
256+ /// capability it never declared, so a late answer from a dead or confused
257+ /// worker cannot invent a state.
258+ pub fn withdraw(&self, id: &str, capability: &str) {
259+ let workers = self.workers.lock().expect("ai registry lock");
260+ let Some(worker) = workers.get(id) else {
261+ return;
262+ };
263+ if !worker.capabilities.iter().any(|c| c == capability) {
264+ return;
265+ }
266+ worker
267+ .withdrawn
268+ .lock()
269+ .expect("ai registry lock")
270+ .insert(capability.to_string());
204 }271 }
205 }272 }
206 273
@@ -345,6 +412,53 @@ mod tests {
345 assert!(reg.snapshot().is_empty());412 assert!(reg.snapshot().is_empty());
346 }413 }
347 414
415+ #[tokio::test]
416+ async fn a_withdrawn_capability_stops_routing_and_a_fresh_hello_restores_it() {
417+ let reg = registry_with(&[("w1", &["ocr.extract", "ocr.classify"], 4)]);
418+ reg.withdraw("w1", "ocr.extract");
419+ assert!(!reg.has_capability("ocr.extract"));
420+ assert!(
421+ reg.has_capability("ocr.classify"),
422+ "the sibling claim is untouched"
423+ );
424+ assert!(matches!(
425+ reg.pick("ocr.extract").unwrap_err(),
426+ AiError::NoWorker(_)
427+ ));
428+ assert_eq!(
429+ reg.snapshot()[0].capabilities,
430+ vec!["ocr.classify".to_string()],
431+ "discovery reports what is offered, not what was declared"
432+ );
433+
434+ // A reconnect re-inserts the worker from its handshake alone.
435+ reg.insert(
436+ "w1".into(),
437+ "svc".into(),
438+ vec!["ocr.extract".into(), "ocr.classify".into()],
439+ 4,
440+ (),
441+ );
442+ assert!(reg.has_capability("ocr.extract"));
443+ reg.pick("ocr.extract").expect("restored");
444+ }
445+
446+ #[tokio::test]
447+ async fn withdrawing_one_worker_leaves_a_sibling_offering_the_same() {
448+ let reg = registry_with(&[("w1", &["ocr.extract"], 2), ("w2", &["ocr.extract"], 2)]);
449+ reg.withdraw("w1", "ocr.extract");
450+ assert!(reg.has_capability("ocr.extract"));
451+ assert_eq!(reg.pick("ocr.extract").unwrap().worker().id, "w2");
452+
453+ // Neither a name the worker never declared nor a worker already gone
454+ // is a state withdraw may invent.
455+ reg.withdraw("w2", "grade.essay");
456+ assert!(!reg.has_capability("grade.essay"));
457+ reg.remove("w2");
458+ reg.withdraw("w2", "ocr.extract");
459+ assert!(!reg.has_capability("ocr.extract"));
460+ }
461+
348 #[tokio::test]462 #[tokio::test]
349 async fn declared_concurrency_is_clamped_into_range() {463 async fn declared_concurrency_is_clamped_into_range() {
350 assert_eq!(clamp_concurrency(None), AI_DEFAULT_CONCURRENT_PER_WORKER);464 assert_eq!(clamp_concurrency(None), AI_DEFAULT_CONCURRENT_PER_WORKER);
src/ai/server.rsmodified+35 -0
@@ -336,6 +336,25 @@ impl AiBridge {
336 .instrument(span.clone())336 .instrument(span.clone())
337 .await;337 .await;
338 338
339+ // A worker that answers `unknown_capability` for a name it advertised
340+ // in its own `Hello` has contradicted its handshake. That claim is the
341+ // only reason this dispatch was routed here, and the only reason the
342+ // caller's door answered `202` instead of "nothing is connected", so it
343+ // is withdrawn: `has_capability` stops seeing it and the next door call
344+ // refuses instead of queuing work nobody will do. A reconnect restores
345+ // it (every fresh `Hello` inserts a worker with its declared list).
346+ if let Err(AiError::Remote { code, .. }) = &outcome
347+ && contradicts_its_own_claim(code)
348+ {
349+ self.inner.registry.withdraw(&lease.worker().id, capability);
350+ tracing::warn!(
351+ service = %lease.worker().service,
352+ capability,
353+ code = %code,
354+ "AI service refused a capability it advertised; claim withdrawn until it reconnects"
355+ );
356+ }
357+
339 metrics358 metrics
340 .ai_request_duration359 .ai_request_duration
341 .record(started.elapsed().as_secs_f64(), &attrs);360 .record(started.elapsed().as_secs_f64(), &attrs);
@@ -381,6 +400,22 @@ impl AiBridge {
381 }400 }
382 }401 }
383 402
403+/// Does this refusal code mean the worker contradicted a claim it made in its
404+/// own `Hello` — it advertised the capability and then answered that this name
405+/// is not one it implements?
406+///
407+/// Only `unknown_capability` does. The protocol's refusal vocabulary names no
408+/// sibling for "no operation by this name": its one example of a service-defined
409+/// code (`unsupported_image`) is a verdict about *this request's payload*, and
410+/// the other codes a service may answer — `invalid_payload`, `unavailable`,
411+/// `timed_out`, `internal`, `capacity` — are the same kind of thing. Those must
412+/// leave the claim standing so a busy, restarting or overloaded service keeps
413+/// getting the next request; only a permanent "this name is not mine" licenses
414+/// a withdrawal (see [`Registry::withdraw`]).
415+fn contradicts_its_own_claim(code: &str) -> bool {
416+ code == "unknown_capability"
417+}
418+
384 /// Accept connections until the endpoint closes. One task per service.419 /// Accept connections until the endpoint closes. One task per service.
385 async fn accept_loop(inner: Arc<Inner>) {420 async fn accept_loop(inner: Arc<Inner>) {
386 while let Some(incoming) = inner.endpoint.accept().await {421 while let Some(incoming) = inner.endpoint.accept().await {
tests/ai_bridge.rsmodified+215 -0
@@ -3539,6 +3539,221 @@ async fn no_insight_refresh_worker_means_503_and_nothing_is_dispatched() {
3539 assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);3539 assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
3540 }3540 }
3541 3541
3542+// ---- a capability a service contradicts --------------------------------
3543+//
3544+// The class this closes: a service announces `insight.refresh` in its `Hello`,
3545+// the door reads that as availability and answers `202`, and the service then
3546+// answers the dispatch with `unknown_capability` — a permanent, self-
3547+// contradictory refusal. Nothing is queued and nobody is told. So the registry
3548+// withdraws the contradicted claim, and the *next* door call takes the `503`
3549+// path it already had. A transient refusal must not do this: a busy or
3550+// restarting service keeps its claim.
3551+
3552+/// Wait until `bridge` offers (or no longer offers) `capability`.
3553+async fn await_capability(bridge: &AiBridge, capability: &str, offered: bool) {
3554+ for _ in 0..500 {
3555+ if bridge.has_capability(capability) == offered {
3556+ return;
3557+ }
3558+ tokio::time::sleep(Duration::from_millis(10)).await;
3559+ }
3560+ panic!("the bridge never turned `{capability}` offered={offered}");
3561+}
3562+
3563+/// The capability names `GET /ai/capabilities` lists right now.
3564+async fn listed_capabilities(app: &Router, cookie: &str) -> Vec<String> {
3565+ let res = common::send(app, "GET", "/ai/capabilities", Some(cookie), None).await;
3566+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
3567+ res.body["capabilities"]
3568+ .as_array()
3569+ .expect("a capabilities array")
3570+ .iter()
3571+ .map(|entry| {
3572+ entry["capability"]
3573+ .as_str()
3574+ .expect("a capability name")
3575+ .to_string()
3576+ })
3577+ .collect()
3578+}
3579+
3580+#[tokio::test]
3581+async fn a_capability_refused_as_unknown_is_withdrawn_so_the_door_stops_queuing() {
3582+ let bridge = bridge().await;
3583+ let service = connect_service(
3584+ &bridge,
3585+ hello("zeka", &[AI_INSIGHT_REFRESH_CAPABILITY]),
3586+ Behaviour::Fail {
3587+ code: "unknown_capability".into(),
3588+ message: "'insight.refresh' bu serviste tanimli degil".into(),
3589+ },
3590+ )
3591+ .await;
3592+ await_workers(&bridge, 1).await;
3593+ let (app, db) = chat_app(&bridge).await;
3594+ let staff = common::login_as(&app, &db, "mudur", "manager").await;
3595+
3596+ // While the claim stands the door queues — the `202` the user saw.
3597+ let res = common::send(
3598+ &app,
3599+ "POST",
3600+ "/insights/refresh",
3601+ Some(&staff),
3602+ Some(json!({})),
3603+ )
3604+ .await;
3605+ assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
3606+ assert_eq!(
3607+ await_seen(&service, 1).await[0].capability,
3608+ AI_INSIGHT_REFRESH_CAPABILITY
3609+ );
3610+
3611+ // The refusal is permanent and contradicts the handshake, so the claim is
3612+ // withdrawn — and the very next refresh is refused rather than queued.
3613+ await_capability(&bridge, AI_INSIGHT_REFRESH_CAPABILITY, false).await;
3614+ let res = common::send(
3615+ &app,
3616+ "POST",
3617+ "/insights/refresh",
3618+ Some(&staff),
3619+ Some(json!({})),
3620+ )
3621+ .await;
3622+ assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body);
3623+ assert_eq!(res.body["error"], "no AI service is connected right now");
3624+ assert_eq!(
3625+ service.seen().len(),
3626+ 1,
3627+ "the refused refresh dispatched nothing"
3628+ );
3629+
3630+ // Discovery tells the same story: the capability is gone from the list.
3631+ assert!(
3632+ !listed_capabilities(&app, &staff)
3633+ .await
3634+ .contains(&AI_INSIGHT_REFRESH_CAPABILITY.to_string()),
3635+ "a withdrawn capability must not be advertised as available"
3636+ );
3637+}
3638+
3639+#[tokio::test]
3640+async fn a_transient_refusal_keeps_the_claim_and_the_door_keeps_queuing() {
3641+ let bridge = bridge().await;
3642+ let service = connect_service(
3643+ &bridge,
3644+ hello("zeka", &[AI_INSIGHT_REFRESH_CAPABILITY]),
3645+ Behaviour::Fail {
3646+ code: "unavailable".into(),
3647+ message: "the school database could not be reached".into(),
3648+ },
3649+ )
3650+ .await;
3651+ await_workers(&bridge, 1).await;
3652+
3653+ // Drive one dispatch through the registry directly so the refusal is known
3654+ // to have been processed before the claim is read — the door's own
3655+ // dispatch is detached and would leave this racy.
3656+ let err = bridge
3657+ .dispatch(&demo(), AI_INSIGHT_REFRESH_CAPABILITY, json!({}))
3658+ .await
3659+ .unwrap_err();
3660+ assert!(
3661+ matches!(&err, AiError::Remote { code, .. } if code == "unavailable"),
3662+ "{err}"
3663+ );
3664+ assert!(
3665+ bridge.has_capability(AI_INSIGHT_REFRESH_CAPABILITY),
3666+ "a busy or unreachable service has not contradicted its claim"
3667+ );
3668+
3669+ // So the door still queues, and discovery still lists it.
3670+ let (app, db) = chat_app(&bridge).await;
3671+ let staff = common::login_as(&app, &db, "mudur", "manager").await;
3672+ let res = common::send(
3673+ &app,
3674+ "POST",
3675+ "/insights/refresh",
3676+ Some(&staff),
3677+ Some(json!({})),
3678+ )
3679+ .await;
3680+ assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
3681+ assert_eq!(
3682+ await_seen(&service, 1).await[0].capability,
3683+ AI_INSIGHT_REFRESH_CAPABILITY
3684+ );
3685+ assert!(
3686+ listed_capabilities(&app, &staff)
3687+ .await
3688+ .contains(&AI_INSIGHT_REFRESH_CAPABILITY.to_string())
3689+ );
3690+}
3691+
3692+#[tokio::test]
3693+async fn a_reconnecting_service_restores_a_withdrawn_capability() {
3694+ let bridge = bridge().await;
3695+ let broken = connect_service(
3696+ &bridge,
3697+ hello("zeka", &[AI_INSIGHT_REFRESH_CAPABILITY]),
3698+ Behaviour::Fail {
3699+ code: "unknown_capability".into(),
3700+ message: "not implemented".into(),
3701+ },
3702+ )
3703+ .await;
3704+ await_workers(&bridge, 1).await;
3705+ let (app, db) = chat_app(&bridge).await;
3706+ let staff = common::login_as(&app, &db, "mudur", "manager").await;
3707+
3708+ // One refresh withdraws the claim.
3709+ common::send(
3710+ &app,
3711+ "POST",
3712+ "/insights/refresh",
3713+ Some(&staff),
3714+ Some(json!({})),
3715+ )
3716+ .await;
3717+ await_capability(&bridge, AI_INSIGHT_REFRESH_CAPABILITY, false).await;
3718+
3719+ // The service restarts — the withdrawal is per connection, never durable.
3720+ broken.conn.close(0u32.into(), b"restarting");
3721+ drop(broken);
3722+ await_workers(&bridge, 0).await;
3723+
3724+ let fixed = connect_service(
3725+ &bridge,
3726+ hello("zeka", &[AI_INSIGHT_REFRESH_CAPABILITY]),
3727+ Behaviour::Echo,
3728+ )
3729+ .await;
3730+ await_workers(&bridge, 1).await;
3731+ assert!(
3732+ bridge.has_capability(AI_INSIGHT_REFRESH_CAPABILITY),
3733+ "a fresh Hello restores the declared capability"
3734+ );
3735+ assert!(
3736+ listed_capabilities(&app, &staff)
3737+ .await
3738+ .contains(&AI_INSIGHT_REFRESH_CAPABILITY.to_string())
3739+ );
3740+
3741+ // And it serves again: the door queues and the dispatch reaches it.
3742+ let res = common::send(
3743+ &app,
3744+ "POST",
3745+ "/insights/refresh",
3746+ Some(&staff),
3747+ Some(json!({})),
3748+ )
3749+ .await;
3750+ assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
3751+ assert_eq!(
3752+ await_seen(&fixed, 1).await[0].capability,
3753+ AI_INSIGHT_REFRESH_CAPABILITY
3754+ );
3755+}
3756+
3542 // ------------------------------------------- the backend-served capabilities --3757 // ------------------------------------------- the backend-served capabilities --
3543 //3758 //
3544 // The other direction: a service calling the *backend*. ZEKA's storage3759 // The other direction: a service calling the *backend*. ZEKA's storage