Skip to main content

switchyard_libsy/core/
algorithm.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Routing algorithms request external work through [`Driver`] and receive typed replies.
5//! Hosts execute that work, keeping routing policy independent of transport.
6
7use std::{
8    collections::HashMap, future::Future, panic::AssertUnwindSafe, pin::Pin, sync::Arc,
9    time::Instant,
10};
11
12use async_trait::async_trait;
13use futures::{FutureExt, Stream, StreamExt};
14use parking_lot::{Mutex, RwLock};
15use serde_json::Value;
16use switchyard_costs::Pricing;
17use tokio::sync::{mpsc, oneshot};
18use tokio_stream::wrappers::ReceiverStream;
19use tracing::Instrument;
20
21/// The request/response protocol types come from [`switchyard_protocol`].
22/// [`switchyard_protocol::LlmRequest`] is the normalized request;
23/// [`switchyard_protocol::AggLlmResponse`] is the buffered response;
24/// [`switchyard_protocol::LlmResponseChunk`] is normalized streaming content;
25/// [`switchyard_protocol::LlmResponseStreamEvent`] is its host/algorithm envelope; and
26/// [`switchyard_protocol::LlmResponse`] carries either a live
27/// [`switchyard_protocol::LlmResponseStream`] or the terminal aggregate.
28use switchyard_protocol::{
29    AggLlmResponse, Category, ContentBlock, DecisionRequest, DecisionResponse, ModelId, Request,
30    Response, StopReason,
31};
32
33use crate::{DriverError, LibsyError, Result, State, observability};
34
35/// A boxed, `Send` stream of [`Step`]s — the output of
36/// [`Algorithm::run_stream`]. Boxed so the trait method that produces it keeps
37/// `Arc<dyn Algorithm>` object-safe.
38pub type StepStream = Pin<Box<dyn Stream<Item = Result<Step>> + Send>>;
39
40/// The models one algorithm run may use, grouped by [`Category`]. Within a
41/// category they are ordered best-first.
42///
43/// Delegated sub-agent work gets its own groups, reachable only through
44/// [`Driver::for_subagent`]. Keeping them separate is what stops a sub-agent's
45/// `capable` from resolving to the parent's, and stops the parent falling back
46/// onto a model only its sub-agents were given.
47///
48/// One run's driver clones all read the same value, so it is passed as
49/// `Arc<RuntimeModels>` rather than cloned per driver.
50#[derive(Clone, Debug, Default)]
51pub struct RuntimeModels {
52    /// When using subagents this is the parent agent category.
53    by_category: HashMap<Category, Vec<ModelId>>,
54    subagent: Option<HashMap<Category, Vec<ModelId>>>,
55    has_target_restriction: bool,
56    provider_models: HashMap<ModelId, ModelId>,
57    pricing: Arc<RwLock<Option<Arc<Pricing>>>>,
58}
59
60impl RuntimeModels {
61    /// The models available to the algorithm itself.
62    pub fn new(by_category: HashMap<Category, Vec<ModelId>>) -> Self {
63        Self {
64            by_category,
65            subagent: None,
66            has_target_restriction: false,
67            provider_models: HashMap::new(),
68            pricing: Arc::default(),
69        }
70    }
71
72    /// Supplies provider identities for telemetry while routing keeps using target keys.
73    pub fn with_provider_models(mut self, models: HashMap<ModelId, ModelId>) -> Self {
74        self.provider_models = models;
75        self
76    }
77
78    /// Installs the deployment's price catalog for all drivers using these targets.
79    pub fn set_pricing(&self, pricing: Arc<Pricing>) {
80        *self.pricing.write() = Some(pricing);
81    }
82
83    /// Filtered target groups use the same price catalog as the parent route.
84    pub fn share_pricing_from(&mut self, parent: &Self) {
85        self.pricing = Arc::clone(&parent.pricing);
86    }
87
88    /// Returns the provider model for a routing key, or the key for direct library callers.
89    pub fn provider_model<'a>(&'a self, target: &'a ModelId) -> &'a ModelId {
90        self.provider_models.get(target).unwrap_or(target)
91    }
92
93    /// Adds the groups used for delegated sub-agent work.
94    pub fn with_subagent(mut self, models: HashMap<Category, Vec<ModelId>>) -> Self {
95        self.subagent = Some(models);
96        self
97    }
98
99    /// Rejects routing calls and completion candidates outside the configured model groups.
100    /// Enforced by the driver and [`drive`]; hosts bind IDs to permitted deployments.
101    pub fn with_target_restriction(mut self) -> Self {
102        self.has_target_restriction = true;
103        self
104    }
105
106    fn check_targets(&self, targets: &[ModelId]) -> Result<()> {
107        if !self.has_target_restriction {
108            return Ok(());
109        }
110        // Include delegated groups: the parent driver publishes subagent outcomes too.
111        for target in targets {
112            if !self
113                .by_category
114                .values()
115                .chain(self.subagent.iter().flat_map(HashMap::values))
116                .any(|models| models.contains(target))
117            {
118                return Err(LibsyError::TargetNotFound {
119                    target: target.clone(),
120                });
121            }
122        }
123        Ok(())
124    }
125
126    fn check_request_targets(&self, request: &Request, targets: &[ModelId]) -> Result<()> {
127        self.check_targets(targets)?;
128        if self.has_target_restriction {
129            let selected = targets.first().ok_or(LibsyError::NoTargets)?;
130            if request.llm_request.model.as_deref() != Some(selected.as_str()) {
131                return Err(LibsyError::AlgorithmError {
132                    message: "request model does not match selected target".into(),
133                });
134            }
135        }
136        Ok(())
137    }
138
139    /// The models in `category`, ordered best-first.
140    pub fn models_for(&self, category: &Category) -> &[ModelId] {
141        self.by_category.get(category).map_or(&[], Vec::as_slice)
142    }
143
144    /// The models delegated sub-agent work uses for `category`, ordered best-first.
145    pub fn subagent_models_for(&self, category: &Category) -> &[ModelId] {
146        self.subagent
147            .as_ref()
148            .and_then(|models| models.get(category))
149            .map_or(&[], Vec::as_slice)
150    }
151}
152
153impl From<HashMap<Category, Vec<ModelId>>> for RuntimeModels {
154    fn from(by_category: HashMap<Category, Vec<ModelId>>) -> Self {
155        Self::new(by_category)
156    }
157}
158
159/// Which of a [`RuntimeModels`]' groups a driver reads.
160#[derive(Clone, Copy)]
161enum Scope {
162    Parent,
163    Subagent,
164}
165
166/// An offloaded model call, surfaced inside [`Step::CallModel`].
167///
168/// The host reads the public fields and passes its model-call future to
169/// [`respond`](Self::respond), unblocking the algorithm's [`Driver::call_model`] on the
170/// other side. `switchyard-llm-client`'s `run` is the ready-made consumer that does this for
171/// you.
172///
173/// [`Driver::call_model`] stamps the first candidate model onto the request before publishing
174/// the call. A consumer that falls through to a later candidate must re-stamp it.
175pub struct CallModel {
176    /// The name of the algorithm that produced this call, so a host instrumenting the
177    /// calls it serves can attribute its own spans to the algorithm behind them.
178    pub algorithm: String,
179    /// The request to serve; its `model` is stamped with the first candidate.
180    pub request: Request,
181    /// Candidate models in fallback order. Never empty.
182    ///
183    /// The host owns candidate execution and fallback. The native
184    /// `switchyard-llm-client` consumer calls only the first candidate during routing.
185    /// A failure stops its run unless [`Self::recover_errors`] is enabled, which
186    /// returns the error to the algorithm without trying later candidates.
187    /// Terminal completion fallback is handled separately.
188    pub models: Vec<ModelId>,
189    /// Return client errors to the algorithm so it can apply its fallback policy.
190    pub recover_errors: bool,
191    telemetry_model: ModelId,
192    /// How to send the response back to the algorithm. `None` once the call is recorded.
193    reply: Option<oneshot::Sender<Result<Response>>>,
194    started: Instant,
195    // Retain the originating span even if the waiting algorithm is cancelled first.
196    span: tracing::Span,
197}
198
199impl CallModel {
200    /// Run host work until it completes or the algorithm stops waiting for this call.
201    /// Dropping the waiting [`Driver::call_model`] future drops `work` and returns `Ok(())`.
202    /// Errors stop the host's run unless [`Self::recover_errors`] is enabled.
203    /// Use `std::future::ready(result)` for an already available response.
204    /// A delivered response stream owns its subsequent lifetime.
205    pub async fn respond(mut self, work: impl Future<Output = Result<Response>>) -> Result<()> {
206        let reply = self.reply.as_mut().ok_or(DriverError::ResponseDropped)?;
207        let result = tokio::select! {
208            biased;
209            _ = reply.closed() => return Ok(()),
210            result = work => result,
211        };
212        if self.reply.as_ref().is_some_and(oneshot::Sender::is_closed) {
213            return Ok(());
214        }
215        if !self.recover_errors
216            && let Err(error) = result
217        {
218            return self.fail(error);
219        }
220        self.record(result.is_ok());
221        if let Ok(response) = &result {
222            observability::record_llm_response(response, &self.span);
223        }
224        self.reply
225            .take()
226            .ok_or(DriverError::ResponseDropped)?
227            .send(result)
228            .ok();
229        Ok(())
230    }
231
232    /// Record a failed call and return its error to stop [`drive`].
233    /// Leaves the promise unfulfilled so the driver can cancel the algorithm.
234    pub fn fail(mut self, error: LibsyError) -> Result<()> {
235        self.reply = None;
236        self.record(false);
237        Err(error)
238    }
239
240    fn record(&self, is_ok: bool) {
241        observability::record_llm_call(
242            &self.algorithm,
243            self.telemetry_model.as_str(),
244            self.started.elapsed(),
245            is_ok,
246        );
247        self.span
248            .record("outcome", if is_ok { "ok" } else { "error" });
249    }
250}
251
252impl Drop for CallModel {
253    fn drop(&mut self) {
254        if self.reply.is_some() {
255            self.record(false);
256        }
257    }
258}
259
260/// A host-owned decision call. Dropping it without replying yields [`DriverError::ResponseDropped`].
261/// Completion or drop records one call and its duration, including time waiting for the host.
262pub struct CallDecision {
263    /// Algorithm name for attributing host telemetry.
264    pub algorithm: String,
265    /// Its model is set to [`Self::model`] before dispatch.
266    pub request: DecisionRequest,
267    /// Target ID for client lookup.
268    pub model: ModelId,
269    reply: Option<oneshot::Sender<Result<DecisionResponse>>>,
270    started: Instant,
271    // Retain the originating span even if the waiting algorithm is cancelled first.
272    span: tracing::Span,
273}
274
275impl CallDecision {
276    /// Run host work and return its response or error to the algorithm.
277    /// Dropping the waiting [`Driver::call_decision`] future drops `work` and returns `Ok(())`.
278    /// Use `std::future::ready(result)` for an already available response.
279    pub async fn respond(
280        mut self,
281        work: impl Future<Output = Result<DecisionResponse>>,
282    ) -> Result<()> {
283        let reply = self.reply.as_mut().ok_or(DriverError::ResponseDropped)?;
284        let result = tokio::select! {
285            biased;
286            _ = reply.closed() => return Ok(()),
287            result = work => result,
288        };
289        self.record(result.is_ok());
290        if let Ok(response) = &result {
291            observability::record_decision_response(response, &self.span);
292        }
293        self.reply
294            .take()
295            .ok_or(DriverError::ResponseDropped)?
296            .send(result)
297            .ok();
298        Ok(())
299    }
300
301    /// Returning this error from the host handler aborts [`drive`].
302    pub fn fail(mut self, error: LibsyError) -> Result<()> {
303        self.reply = None;
304        self.record(false);
305        Err(error)
306    }
307
308    fn record(&self, is_ok: bool) {
309        observability::record_decision_call(
310            &self.algorithm,
311            &self.model,
312            self.started.elapsed(),
313            is_ok,
314        );
315        self.span
316            .record("outcome", if is_ok { "ok" } else { "error" });
317    }
318}
319
320impl Drop for CallDecision {
321    fn drop(&mut self) {
322        if self.reply.is_some() {
323            self.record(false);
324        }
325    }
326}
327
328/// The terminal result of routing.
329pub struct RoutingOutcome {
330    /// Models selected by the algorithm, ordered best model first.
331    pub selected_model_ids: Vec<ModelId>,
332    /// The request after all routing-time rewrites, stamped with the selected model.
333    pub request: Request,
334    /// The request the fallback candidates receive instead of `request`, when routing
335    /// rewrote `request` for the selected model only.
336    /// Content-policy denials do not advance to these fallback candidates.
337    pub fallback_request: Option<Request>,
338    /// Candidate-specific requests, including model-specific instructions.
339    pub candidate_requests: HashMap<ModelId, Request>,
340    /// A response produced while routing, or `None` when the client must make the answer call.
341    pub response: Option<Response>,
342    /// Outcome identity and optional algorithm evidence.
343    ///
344    /// Constructors leave this empty; [`Algorithm::run_stream`] fills it before publishing a
345    /// successful outcome.
346    pub metadata: Option<crate::OutcomeMetadata>,
347    /// Routing state after the run, for hosts that store state outside the algorithm.
348    pub state: State,
349}
350
351impl RoutingOutcome {
352    /// The model the algorithm recommends, the best model for this request.
353    /// `LibsyError::NoTargets` if the algorithm selected no models, which should be impossible.
354    pub fn selected_model_id(&self) -> Result<&ModelId> {
355        self.selected_model_ids.first().ok_or(LibsyError::NoTargets)
356    }
357
358    /// The decision is that client should send this `request`. The `selected_model_id`
359    /// will be written into it by this function.
360    /// If that fails client should try the `fallback_models` in order.
361    pub fn route_to(
362        selected_model_id: ModelId,
363        fallback_models: Vec<ModelId>,
364        mut request: Request,
365    ) -> Self {
366        request.llm_request.model = Some(selected_model_id.to_string());
367        let mut selected_model_ids = Vec::with_capacity(1 + fallback_models.len());
368        selected_model_ids.push(selected_model_id);
369        selected_model_ids.extend(fallback_models);
370        Self {
371            selected_model_ids,
372            request,
373            fallback_request: None,
374            candidate_requests: HashMap::new(),
375            response: None,
376            metadata: None,
377            state: State::default(),
378        }
379    }
380
381    /// Algorithm generated the response as part of the routing decision. Here it is.
382    /// The `request` will have the `selected_model_id` written into it by this function.
383    pub fn answered(selected_model_id: ModelId, mut request: Request, response: Response) -> Self {
384        request.llm_request.model = Some(selected_model_id.to_string());
385        Self {
386            selected_model_ids: vec![selected_model_id],
387            request,
388            fallback_request: None,
389            candidate_requests: HashMap::new(),
390            response: Some(response),
391            metadata: None,
392            state: State::default(),
393        }
394    }
395}
396
397/// What the host saw of the answer it served for a routed request.
398#[derive(Clone, Copy, Debug, Eq, PartialEq)]
399pub struct AnswerSummary {
400    /// The answer ended its turn with visible text and requested no tool call.
401    pub final_reply: bool,
402}
403
404impl AnswerSummary {
405    /// Summarizes a completed answer.
406    pub fn of(response: &AggLlmResponse) -> Self {
407        let final_reply = response.outputs.iter().all(|output| {
408            matches!(output.stop_reason, None | Some(StopReason::EndTurn))
409                && !output
410                    .content
411                    .iter()
412                    .any(|block| matches!(block, ContentBlock::ToolCall(_)))
413        }) && response.outputs.iter().any(|output| {
414            output.role == switchyard_protocol::Role::Assistant
415                && output.content.iter().any(
416                    |block| matches!(block, ContentBlock::Text { text } if !text.trim().is_empty()),
417                )
418        });
419        Self { final_reply }
420    }
421}
422
423#[derive(Default)]
424struct RunEvidence {
425    failed_models: Vec<ModelId>,
426    outcome: Option<Value>,
427    judgments: Vec<crate::JudgeDecision>,
428}
429
430/// An algorithm's handle for requesting external work and awaiting the host's typed replies.
431#[derive(Clone)]
432pub struct Driver {
433    step_tx: mpsc::Sender<Result<Step>>,
434
435    /// The owning algorithm's telemetry label, stamped onto every call this driver publishes.
436    algorithm: String,
437
438    /// Run-scoped evidence shared by driver clones and attached only to a successful outcome.
439    evidence: Arc<Mutex<RunEvidence>>,
440
441    /// Caller-supplied routing state, read and updated when a request carries no session ID.
442    state: Arc<Mutex<State>>,
443
444    /// Every group this run may route over, shared by all driver clones.
445    models: Arc<RuntimeModels>,
446
447    /// Which of those groups this driver reads.
448    scope: Scope,
449    judge: Option<ModelId>,
450    tier_targets: std::sync::OnceLock<[ModelId; 2]>,
451}
452
453impl Driver {
454    /// Build an empty driver with its step channel ready. Created per call by
455    /// [`run_stream`](Algorithm::run_stream). Also returns the Step receiver.
456    pub(crate) fn new(
457        algorithm: &str,
458        models: Arc<RuntimeModels>,
459    ) -> (Self, mpsc::Receiver<Result<Step>>) {
460        // Capacity one keeps the algorithm paced by the stream consumer. It limits queued steps,
461        // not model calls already pulled from the stream, which can still run at the same time.
462        // A larger buffer would use more memory and let the algorithm run farther ahead with
463        // little benefit because reading a step is cheap compared with serving a model call.
464        let (step_tx, step_rx) = mpsc::channel(1);
465        (
466            Self {
467                step_tx,
468                algorithm: algorithm.to_string(),
469                evidence: Arc::new(Mutex::new(RunEvidence::default())),
470                state: Arc::new(Mutex::new(State::default())),
471                models,
472                scope: Scope::Parent,
473                tier_targets: Default::default(),
474                judge: None,
475            },
476            step_rx,
477        )
478    }
479
480    pub(crate) fn take_state(&self) -> State {
481        std::mem::take(&mut *self.state.lock())
482    }
483
484    pub(crate) fn set_state(&self, state: State) {
485        *self.state.lock() = state;
486    }
487
488    /// Record a generation failure for this run, independently of session or backend health.
489    pub(crate) fn record_model_failure(&self, model: ModelId) {
490        self.evidence.lock().failed_models.push(model);
491    }
492
493    pub(crate) fn model_failed(&self, model: &ModelId) -> bool {
494        self.evidence.lock().failed_models.contains(model)
495    }
496
497    /// Replace the current run's evidence when a component makes the final decision.
498    pub(crate) fn set_evidence(&self, evidence: Value) {
499        self.evidence.lock().outcome = Some(evidence);
500    }
501
502    /// Supply fallback evidence without replacing a decision made earlier in the cascade.
503    pub(crate) fn set_evidence_if_empty(&self, evidence: Value) {
504        let mut current = self.evidence.lock();
505        if current.outcome.is_none() {
506            current.outcome = Some(evidence);
507        }
508    }
509
510    pub(crate) fn record_judgment(&self, selected: Option<crate::Score>, evidence: Option<Value>) {
511        let (target, category) = selected
512            .map(|score| (Some(score.target), score.category))
513            .unwrap_or_default();
514        self.evidence.lock().judgments.push(crate::JudgeDecision {
515            target,
516            category: category.map(|category| category.as_str().to_string()),
517            evidence,
518        });
519    }
520
521    /// Publish a model call and await the consumer's response.
522    ///
523    /// Errors if the stream is closed or the call failed.
524    /// The await is wrapped in a `libsy.llm_call` span measuring *fulfillment* as
525    /// the algorithm observes it (host queueing/serving included; a streamed
526    /// response resolves when its stream handle arrives). The host records call metrics,
527    /// outcome, and buffered token usage when it completes or drops the call, even if the
528    /// waiting algorithm has been cancelled. The provider call itself is the
529    /// host's, and is instrumented by whoever makes it.
530    pub async fn call_model(&self, request: Request, models: Vec<ModelId>) -> Result<Response> {
531        self.call_model_with_error_recovery(request, models, false)
532            .await
533    }
534
535    /// Allows a routing policy to handle a failed call when recovery is enabled.
536    #[tracing::instrument(
537        target = "libsy",
538        name = "libsy.llm_call",
539        skip_all,
540        fields(
541            algorithm = self.algorithm,
542            selected_model = %models.first().map(|model| self.provider_model(model).as_str()).unwrap_or("NoTargets"),
543            openinference.span.kind = "CHAIN",
544            outcome = tracing::field::Empty,
545            input_tokens = tracing::field::Empty,
546            output_tokens = tracing::field::Empty,
547            total_tokens = tracing::field::Empty,
548            reasoning_tokens = tracing::field::Empty,
549        )
550    )]
551    pub(crate) async fn call_model_with_error_recovery(
552        &self,
553        mut request: Request,
554        models: Vec<ModelId>,
555        recover_errors: bool,
556    ) -> Result<Response> {
557        let Some(selected_model_id) = models.first() else {
558            return Err(LibsyError::NoTargets);
559        };
560        self.models.check_targets(&models)?;
561        request.llm_request.model = Some(selected_model_id.to_string());
562        let started = Instant::now();
563        let (reply, response) = oneshot::channel::<Result<Response>>();
564        let call = CallModel {
565            algorithm: self.algorithm.clone(),
566            request,
567            telemetry_model: self.provider_model(selected_model_id).clone(),
568            models,
569            recover_errors,
570            reply: Some(reply),
571            started,
572            span: tracing::Span::current(),
573        };
574        self.step_tx
575            .send(Ok(Step::CallModel(Box::new(call))))
576            .await
577            .map_err(|_| DriverError::StreamClosed)?;
578        response
579            .await
580            .map_err(|_| LibsyError::from(DriverError::ResponseDropped))?
581    }
582
583    /// Override the request's model with `model` and wait for the host to reply.
584    #[tracing::instrument(
585        target = "libsy",
586        name = "libsy.decision_call",
587        skip_all,
588        fields(
589            algorithm = self.algorithm,
590            selected_model = %model,
591            openinference.span.kind = "CHAIN",
592            outcome = tracing::field::Empty,
593            input_tokens = tracing::field::Empty,
594            output_tokens = tracing::field::Empty,
595            total_tokens = tracing::field::Empty,
596            reasoning_tokens = tracing::field::Empty,
597            gen_ai.response.id = tracing::field::Empty,
598            gen_ai.response.model = tracing::field::Empty,
599        ),
600    )]
601    pub async fn call_decision(
602        &self,
603        mut request: DecisionRequest,
604        model: ModelId,
605    ) -> Result<DecisionResponse> {
606        self.models.check_targets(std::slice::from_ref(&model))?;
607        request.model = Some(model.clone());
608        let started = Instant::now();
609        let (reply, response) = oneshot::channel();
610        let call = CallDecision {
611            algorithm: self.algorithm.clone(),
612            request,
613            model,
614            reply: Some(reply),
615            started,
616            span: tracing::Span::current(),
617        };
618        self.step_tx
619            .send(Ok(Step::CallDecision(Box::new(call))))
620            .await
621            .map_err(|_| DriverError::StreamClosed)?;
622        response
623            .await
624            .map_err(|_| LibsyError::from(DriverError::ResponseDropped))?
625    }
626
627    /// Provider identity for telemetry; algorithms still route on the original target key.
628    pub fn provider_model<'a>(&'a self, target: &'a ModelId) -> &'a ModelId {
629        self.models.provider_model(target)
630    }
631
632    /// The deployment's price catalog, when the host supplied one.
633    pub fn pricing(&self) -> Option<Arc<Pricing>> {
634        self.models.pricing.read().clone()
635    }
636
637    /// Narrows stage selection and completion fallbacks for the rest of this request.
638    pub(crate) fn select_tier_targets(&self, targets: &[ModelId; 2]) -> Result<()> {
639        for target in targets {
640            ensure_model_is_target(self.models_for(&Category::Any), target)?;
641        }
642        self.tier_targets.get_or_init(|| targets.clone());
643        Ok(())
644    }
645
646    /// The available models for this category, typically ordered best-first.
647    pub fn models_for(&self, category: &Category) -> &[ModelId] {
648        if let Some(pair) = self.tier_targets.get() {
649            match category {
650                Category::Capable => return &pair[..1],
651                Category::Efficient => return &pair[1..],
652                Category::Any => return pair,
653                _ => {}
654            }
655        }
656        if *category == Category::Judge
657            && let Some(judge) = &self.judge
658        {
659            return std::slice::from_ref(judge);
660        }
661        match self.scope {
662            Scope::Parent => self.models.models_for(category),
663            Scope::Subagent => self.models.subagent_models_for(category),
664        }
665    }
666
667    pub(crate) fn for_judge(&self, judge: ModelId) -> Self {
668        Self {
669            judge: Some(judge),
670            ..self.clone()
671        }
672    }
673
674    /// The first available model for `category`.
675    pub fn first_model_for(&self, category: &Category) -> Result<&ModelId> {
676        self.models_for(category)
677            .first()
678            .ok_or_else(|| LibsyError::AlgorithmError {
679                message: format!("no models available for category {}", category.as_str()),
680            })
681    }
682
683    /// A driver scoped to delegated sub-agent work: its categories are the
684    /// sub-agent's own, and the parent's are no longer reachable through it.
685    pub fn for_subagent(&self) -> Result<Self> {
686        if self.models.subagent.is_none() {
687            return Err(LibsyError::AlgorithmError {
688                message: "delegated work has no sub-agent models".to_string(),
689            });
690        }
691        Ok(Self {
692            scope: Scope::Subagent,
693            tier_targets: Default::default(),
694            ..self.clone()
695        })
696    }
697
698    /// Emit the terminal step: [`Step::Done`] on `Ok`, or an `Err` stream
699    /// item on failure. Internal: called once by [`run_stream`](Algorithm::run_stream)
700    /// when the algorithm finishes.
701    pub(crate) async fn finish(&self, result: Result<RoutingOutcome>) -> Result<()> {
702        let result = result.map(|mut outcome| {
703            outcome.state = self.take_state();
704            let evidence = std::mem::take(&mut *self.evidence.lock());
705            let metadata = outcome.metadata.get_or_insert_with(|| {
706                crate::OutcomeMetadata::new(self.algorithm.clone(), evidence.outcome)
707            });
708            metadata.judgments.extend(evidence.judgments);
709            let provider_models = outcome
710                .selected_model_ids
711                .iter()
712                .map(|target| self.provider_model(target).clone())
713                .collect::<Vec<_>>();
714            observability::record_outcome(metadata, &provider_models);
715            outcome
716        });
717        let selected_model = result
718            .as_ref()
719            .ok()
720            .and_then(|outcome| outcome.selected_model_id().ok().cloned());
721        let step = result.map(|outcome| Step::Done(Box::new(outcome)));
722        self.step_tx
723            .send(step)
724            .await
725            .map_err(|_| DriverError::StreamClosed)?;
726        if let Some(selected_model) = selected_model {
727            observability::record_decision(&self.algorithm, self.provider_model(&selected_model));
728        }
729        Ok(())
730    }
731}
732
733/// Work requests and the terminal outcome of [`Algorithm::run_stream`].
734/// Each call carries its own reply channel, so the host can execute calls concurrently.
735pub enum Step {
736    /// The algorithm needs this model call performed. The host serves it and fulfills
737    /// it with [`CallModel::respond`]. Boxed: it is by far the largest variant.
738    CallModel(Box<CallModel>),
739    /// The host fulfills this decision call with [`CallDecision::respond`].
740    CallDecision(Box<CallDecision>),
741    /// The algorithm finished with its routing outcome — the last step of a run.
742    Done(Box<RoutingOutcome>),
743}
744
745/// Work dispatched through one host handler, with a typed reply channel per variant.
746/// [`drive`] handles terminal outcomes separately; the handler only executes calls.
747pub enum Call {
748    /// Fulfilled with an LLM [`Response`].
749    Model(Box<CallModel>),
750    /// Fulfilled with a [`DecisionResponse`].
751    Decision(Box<CallDecision>),
752}
753
754/// Drive [`Algorithm::run_stream`] to its routing outcome, serving calls concurrently.
755///
756/// The shared execution loop lets hosts supply clients or test doubles through `serve`
757/// without reimplementing stream handling and cancellation.
758///
759/// `serve` owns each [`Call`] and performs its I/O. Passing an error to `respond`
760/// lets the algorithm fall back; returning an error from `serve` aborts the run.
761///
762/// Dropping this future cancels the algorithm and pending handler futures.
763pub async fn drive<F, Fut>(
764    algorithm: Arc<dyn Algorithm>,
765    request: Request,
766    models: Arc<RuntimeModels>,
767    serve: F,
768) -> Result<RoutingOutcome>
769where
770    F: Fn(Call) -> Fut,
771    Fut: Future<Output = Result<()>>,
772{
773    drive_with_state(algorithm, request, models, State::default(), serve).await
774}
775
776/// [`drive`] starting from caller-supplied `state`.
777pub(crate) async fn drive_with_state<F, Fut>(
778    algorithm: Arc<dyn Algorithm>,
779    request: Request,
780    models: Arc<RuntimeModels>,
781    state: State,
782    serve: F,
783) -> Result<RoutingOutcome>
784where
785    F: Fn(Call) -> Fut,
786    Fut: Future<Output = Result<()>>,
787{
788    let stream = algorithm.run_stream(request, Arc::clone(&models), state);
789    tokio::pin!(stream);
790
791    let mut in_flight = futures::stream::FuturesUnordered::new();
792    let mut final_outcome: Option<RoutingOutcome> = None;
793
794    loop {
795        tokio::select! {
796            Some(result) = in_flight.next() => match result {
797                Ok(()) => {}, // Call completed successfully
798                Err(err) => return Err(err), // Call failed, propagate the error
799            },
800            step = stream.next() => {
801                match step {
802                    None => break, // stream has ended, no more steps
803                    Some(item) => match item? {
804                        Step::CallModel(call) => {
805                            models.check_request_targets(&call.request, &call.models)?;
806                            in_flight.push(serve(Call::Model(call)));
807                        }
808                        Step::CallDecision(call) => {
809                            models.check_targets(std::slice::from_ref(&call.model))?;
810                            if models.has_target_restriction
811                                && call.request.model.as_ref() != Some(&call.model)
812                            {
813                                return Err(LibsyError::AlgorithmError {
814                                    message: "decision payload model does not match selected target".into(),
815                                });
816                            }
817                            in_flight.push(serve(Call::Decision(call)));
818                        }
819                        Step::Done(outcome) => {
820                            if outcome.response.is_none() {
821                                models.check_request_targets(&outcome.request, &outcome.selected_model_ids)?;
822                            }
823                            final_outcome = Some(*outcome);
824                            break;
825                        }
826                    }
827                }
828            },
829        }
830    }
831    final_outcome.ok_or(LibsyError::MissingFinalResponse)
832}
833
834/// Recover the message from an algorithm's panic.
835fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
836    payload
837        .downcast_ref::<&'static str>()
838        .map(|message| (*message).to_string())
839        .or_else(|| payload.downcast_ref::<String>().cloned())
840        .unwrap_or_else(|| "unknown panic payload".to_string())
841}
842
843/// Abort guard
844struct AbortOnDrop(tokio::task::AbortHandle);
845
846impl Drop for AbortOnDrop {
847    fn drop(&mut self) {
848        self.0.abort();
849    }
850}
851
852/// Errors unless `targets` contains `name`.
853///
854/// Config target names must be resolved before an algorithm is built. This list contains
855/// model IDs, not target names.
856pub(crate) fn ensure_model_is_target(targets: &[ModelId], name: &ModelId) -> Result<()> {
857    targets
858        .iter()
859        .any(|target| target == name)
860        .then_some(())
861        .ok_or_else(|| LibsyError::TargetNotFound {
862            target: name.clone(),
863        })
864}
865
866/// Key for routing affinity: a root request by its session, a child request by its session
867/// and agent.
868#[derive(Clone, Hash, PartialEq, Eq)]
869pub(crate) enum RoutingIdentity {
870    /// Root request, keyed by session ID.
871    Session(String),
872    /// Child request, keyed by session and agent IDs.
873    Subagent { session: String, agent: String },
874}
875
876impl RoutingIdentity {
877    /// Builds a root or child identity from non-empty request metadata.
878    ///
879    /// A child request missing either ID returns `None`, so it keeps no routing history
880    /// rather than sharing the parent's.
881    pub(crate) fn from_request(request: &Request) -> Option<Self> {
882        let metadata = request.metadata.as_ref()?;
883        let session = metadata.session_id.as_deref().filter(|id| !id.is_empty())?;
884        if metadata.is_subagent {
885            let agent = metadata.agent_id.as_deref().filter(|id| !id.is_empty())?;
886            Some(Self::Subagent {
887                session: session.to_string(),
888                agent: agent.to_string(),
889            })
890        } else {
891            Some(Self::Session(session.to_string()))
892        }
893    }
894}
895
896/// Routing policy independent of how external calls are executed.
897/// Implement [`route`](Self::route), using [`Driver`] to request work from the host.
898/// Hosts can use [`drive`] for the shared execution loop or consume
899/// [`run_stream`](Self::run_stream) for custom execution.
900///
901/// Methods take `self: Arc<Self>`: one algorithm (`Arc<dyn Algorithm>`) is shared across
902/// requests and run concurrently, so it owns its thread-safety and any shared state.
903///
904/// # Concurrency
905///
906/// A host may run the same algorithm concurrently for many requests. Implementations
907/// must synchronize their own mutable shared state. Each call to [`run_stream`](Self::run_stream)
908/// creates an independent [`Driver`], so model-call promises and emitted [`Step`]s cannot
909/// cross between runs.
910///
911/// # Observability
912///
913/// [`run_stream`](Self::run_stream) creates a `libsy.run` span, and each offloaded model
914/// call creates a nested span for its call kind, with outcome and available token usage.
915/// Call metrics include host queueing and count unfulfilled drops as errors.
916/// Successful outcomes record their
917/// [`OutcomeMetadata::outcome_id`](crate::OutcomeMetadata::outcome_id) on `libsy.run`,
918/// alongside `selected_model_ids` (an ordered OpenTelemetry string array).
919/// `algorithm` and `switchyard.algorithm` retain the run's [`Algorithm::name`].
920/// Optional `evidence.source`, `evidence.verdict`, `evidence.trigger`, and
921/// `evidence.reason_code` are strings; `evidence.score`, `evidence.confidence`,
922/// `evidence.threshold`, `evidence.capable_score`, and `evidence.capable_threshold`
923/// are numbers. Unknown evidence fields are not exported.
924/// These fields are span attributes, never metric labels.
925///
926/// The run/call observability helpers retain `outcome` status and operational metrics,
927/// but omit error details and arbitrary request extra metadata. Algorithms and hosts
928/// may emit their own logs. Errors still reach the caller unchanged.
929/// The host controls the tracing subscriber and global OpenTelemetry
930/// meter provider; libsy installs no exporter and performs no telemetry network I/O.
931#[async_trait]
932pub trait Algorithm: Send + Sync + 'static {
933    /// Stable, low-cardinality name identifying this algorithm — the
934    /// `algorithm` attribute on every span, metric, and log line the crate
935    /// emits for its runs.
936    fn name(&self) -> &str;
937
938    /// Select a route, requesting external work through [`Driver`] as needed.
939    /// [`run_stream`](Self::run_stream) runs this method and exposes its work to the host.
940    async fn route(self: Arc<Self>, driver: Driver, request: Request) -> Result<RoutingOutcome>;
941
942    /// Whether to report final solver usage for this request.
943    fn tracks_usage(&self, _request: &Request) -> bool {
944        false
945    }
946
947    /// Records the actual serving model and its usage after a successful answer.
948    async fn observe_usage(
949        &self,
950        _session_id: &str,
951        _agent_id: Option<&str>,
952        _served_model: &ModelId,
953        _usage: Option<&switchyard_protocol::Usage>,
954    ) {
955    }
956
957    /// Whether the host should summarize served answers for [`Self::observe_answer`].
958    fn tracks_answers(&self) -> bool {
959        false
960    }
961
962    /// Records the answer the host served for a request in `session_id`.
963    ///
964    /// The host reports a streamed answer before forwarding its final chunk, so the
965    /// session's next request is routed with this answer already recorded.
966    async fn observe_answer(&self, _session_id: &str, _answer: AnswerSummary) {}
967
968    /// Expose work requests and the final outcome so the host can control execution.
969    ///
970    /// Each call waits for its host reply. A run ends with one terminal item — [`Step::Done`] on
971    /// success, an `Err` item on failure, including when the algorithm panics. Dropping
972    /// the stream aborts the spawned algorithm task.
973    ///
974    /// Every invocation owns a separate [`Driver`].
975    fn run_stream(
976        self: Arc<Self>,
977        request: Request,
978        models: Arc<RuntimeModels>,
979        state: State,
980    ) -> StepStream {
981        let (driver, step_rx) = Driver::new(self.name(), models);
982        driver.set_state(state);
983        let span = observability::run_span(self.name(), &request);
984        let handle = tokio::spawn(
985            async move {
986                let algorithm = self.name().to_string();
987                // Catch a panicking algorithm so the run still publishes a terminal step.
988                let route = AssertUnwindSafe(self.route(driver.clone(), request)).catch_unwind();
989                let result = observability::observe_run(&algorithm, async {
990                    let outcome = route.await.unwrap_or_else(|payload| {
991                        Err(LibsyError::AlgorithmError {
992                            message: format!(
993                                "algorithm task panicked: {}",
994                                panic_message(payload.as_ref())
995                            ),
996                        })
997                    })?;
998                    if outcome.response.is_none() {
999                        driver
1000                            .models
1001                            .check_request_targets(&outcome.request, &outcome.selected_model_ids)?;
1002                    }
1003                    Ok(outcome)
1004                })
1005                .await;
1006
1007                let _ = driver.finish(result).await;
1008            }
1009            .instrument(span),
1010        );
1011        // Dropping the stream aborts the algorithm task when its consumer goes away.
1012        let abort_guard = AbortOnDrop(handle.abort_handle());
1013        Box::pin(ReceiverStream::new(step_rx).map(move |step| {
1014            // link abort guard to stream
1015            let _keep_alive = &abort_guard;
1016            step
1017        }))
1018    }
1019}
1020
1021#[cfg(test)]
1022mod tests {
1023    use std::collections::HashMap;
1024
1025    use super::*;
1026    use crate::core::testing::{Serve, ServeResult, echo, reply, serve_decision, test_drive};
1027    use futures::StreamExt;
1028    use switchyard_protocol::{
1029        LlmResponse, LlmResponseChunk, completion_text, text_request, text_response,
1030    };
1031
1032    #[test]
1033    fn a_final_answer_has_text_and_no_unfinished_or_tool_output() {
1034        let mut answer = text_response(None, "done");
1035        assert!(AnswerSummary::of(&answer).final_reply);
1036        answer.outputs[0].stop_reason = Some(StopReason::MaxTokens);
1037        assert!(!AnswerSummary::of(&answer).final_reply);
1038        answer.outputs[0].stop_reason = Some(StopReason::EndTurn);
1039        let mut tool = answer.outputs[0].clone();
1040        tool.content = vec![ContentBlock::ToolCall(switchyard_protocol::ToolCall {
1041            id: "call".into(),
1042            name: "bash".into(),
1043            arguments: serde_json::json!({}),
1044        })];
1045        answer.outputs.push(tool);
1046        assert!(!AnswerSummary::of(&answer).final_reply);
1047        answer.outputs.pop();
1048        answer.outputs[0].content = vec![ContentBlock::Text { text: "  ".into() }];
1049        assert!(!AnswerSummary::of(&answer).final_reply);
1050        assert!(!AnswerSummary::of(&AggLlmResponse::default()).final_reply);
1051    }
1052
1053    #[derive(Debug, thiserror::Error)]
1054    #[error("{0}")]
1055    struct TestError(&'static str);
1056
1057    fn test_error(message: &'static str) -> LibsyError {
1058        LibsyError::external("test", TestError(message))
1059    }
1060
1061    /// Trivial algo used only to exercise the orchestrator: calls the first target
1062    /// and returns its response as the routing outcome.
1063    struct TestAlgo {
1064        target_set: Vec<ModelId>,
1065    }
1066
1067    #[async_trait]
1068    impl Algorithm for TestAlgo {
1069        fn name(&self) -> &str {
1070            "test"
1071        }
1072
1073        async fn route(
1074            self: Arc<Self>,
1075            driver: Driver,
1076            request: Request,
1077        ) -> Result<RoutingOutcome> {
1078            let target = self
1079                .target_set
1080                .first()
1081                .ok_or(LibsyError::NoTargets)?
1082                .clone();
1083            let response = driver
1084                .call_model(request.clone(), vec![target.clone()])
1085                .await?;
1086            driver.record_judgment(
1087                Some(crate::Score {
1088                    target: target.clone(),
1089                    category: Some(Category::Capable),
1090                    confidence: 1.0,
1091                }),
1092                Some(serde_json::json!({"source": "judge"})),
1093            );
1094            driver.set_evidence(serde_json::json!({"source": "test"}));
1095            driver.set_evidence_if_empty(serde_json::json!({"source": "ignored"}));
1096            Ok(RoutingOutcome::answered(target, request, response))
1097        }
1098    }
1099
1100    /// Build a shared `TestAlgo` over the given target set.
1101    fn orch(target_set: Vec<ModelId>) -> Arc<dyn Algorithm> {
1102        Arc::new(TestAlgo { target_set })
1103    }
1104
1105    fn request() -> Request {
1106        Request {
1107            llm_request: text_request(Some("auto".to_string()), "hi".to_string()),
1108            raw_request: None,
1109            metadata: None,
1110        }
1111    }
1112
1113    #[test]
1114    fn routing_outcome_constructors_stamp_selection_and_preserve_payloads() {
1115        let outcome = RoutingOutcome::route_to(
1116            "selected".into(),
1117            target_set(&["fallback-one", "fallback-two"]),
1118            request(),
1119        );
1120
1121        assert_eq!(
1122            outcome.selected_model_ids,
1123            target_set(&["selected", "fallback-one", "fallback-two"])
1124        );
1125        assert_eq!(outcome.request.model_id().as_deref(), Some("selected"));
1126        assert!(outcome.response.is_none());
1127        assert!(outcome.metadata.is_none());
1128
1129        let outcome = RoutingOutcome::route_to("only".into(), Vec::new(), request());
1130        assert_eq!(outcome.selected_model_ids, target_set(&["only"]));
1131
1132        let outcome = RoutingOutcome::answered(
1133            "answered".into(),
1134            request(),
1135            Response {
1136                llm_response: LlmResponse::Agg(text_response(None, "existing")),
1137                metadata: None,
1138                upstream_headers: http::HeaderMap::new(),
1139            },
1140        );
1141
1142        assert_eq!(outcome.selected_model_ids, target_set(&["answered"]));
1143        assert_eq!(outcome.request.model_id().as_deref(), Some("answered"));
1144        assert_eq!(
1145            outcome
1146                .response
1147                .as_ref()
1148                .and_then(|response| response.llm_response.as_agg())
1149                .map(completion_text),
1150            Some("existing".to_string())
1151        );
1152    }
1153
1154    fn target_set(names: &[&str]) -> Vec<ModelId> {
1155        names.iter().map(|name| ModelId::from(*name)).collect()
1156    }
1157
1158    enum TargetProbe {
1159        Model(&'static [&'static str]),
1160        Decision(&'static str),
1161        Completion(&'static [&'static str]),
1162        MismatchedCompletion,
1163    }
1164
1165    #[async_trait]
1166    impl Algorithm for TargetProbe {
1167        fn name(&self) -> &str {
1168            "target_probe"
1169        }
1170
1171        async fn route(
1172            self: Arc<Self>,
1173            driver: Driver,
1174            request: Request,
1175        ) -> Result<RoutingOutcome> {
1176            match &*self {
1177                Self::Model(models) => {
1178                    let response = driver
1179                        .call_model(request.clone(), target_set(models))
1180                        .await?;
1181                    Ok(RoutingOutcome::answered(
1182                        models[0].into(),
1183                        request,
1184                        response,
1185                    ))
1186                }
1187                Self::Decision(model) => {
1188                    driver
1189                        .call_decision(
1190                            DecisionRequest {
1191                                model: None,
1192                                input: Value::Null,
1193                                questions: Default::default(),
1194                            },
1195                            (*model).into(),
1196                        )
1197                        .await?;
1198                    Ok(RoutingOutcome::route_to("allowed".into(), vec![], request))
1199                }
1200                Self::Completion(models) => Ok(RoutingOutcome::route_to(
1201                    models[0].into(),
1202                    target_set(&models[1..]),
1203                    request,
1204                )),
1205                Self::MismatchedCompletion => {
1206                    let mut outcome = RoutingOutcome::route_to("allowed".into(), vec![], request);
1207                    outcome.request.llm_request.model = Some("outside".into());
1208                    Ok(outcome)
1209                }
1210            }
1211        }
1212    }
1213
1214    struct RewrittenSteps(Arc<TargetProbe>, fn(&mut Step));
1215
1216    #[async_trait]
1217    impl Algorithm for RewrittenSteps {
1218        fn name(&self) -> &str {
1219            "rewritten_steps"
1220        }
1221
1222        async fn route(
1223            self: Arc<Self>,
1224            driver: Driver,
1225            request: Request,
1226        ) -> Result<RoutingOutcome> {
1227            Arc::clone(&self.0).route(driver, request).await
1228        }
1229
1230        fn run_stream(
1231            self: Arc<Self>,
1232            request: Request,
1233            models: Arc<RuntimeModels>,
1234            state: State,
1235        ) -> StepStream {
1236            Box::pin(
1237                Arc::clone(&self.0)
1238                    .run_stream(request, models, state)
1239                    .map(move |step| {
1240                        step.map(|mut step| {
1241                            (self.1)(&mut step);
1242                            step
1243                        })
1244                    }),
1245            )
1246        }
1247    }
1248
1249    fn restricted_models() -> RuntimeModels {
1250        RuntimeModels::new(HashMap::from([
1251            (Category::Any, target_set(&["allowed", "fallback"])),
1252            (Category::Judge, target_set(&["judge"])),
1253        ]))
1254        .with_target_restriction()
1255        .with_subagent(HashMap::from([(Category::Any, target_set(&["subagent"]))]))
1256    }
1257
1258    #[tokio::test]
1259    async fn target_restriction_checks_default_streams() {
1260        for probe in [
1261            TargetProbe::Model(&["outside"]),
1262            TargetProbe::Model(&["allowed", "outside"]),
1263            TargetProbe::Decision("outside"),
1264            TargetProbe::Completion(&["outside"]),
1265            TargetProbe::Completion(&["allowed", "outside"]),
1266        ] {
1267            let mut stream = Arc::new(probe).run_stream(
1268                request(),
1269                Arc::new(restricted_models()),
1270                State::default(),
1271            );
1272            assert!(matches!(
1273                stream.next().await,
1274                Some(Err(LibsyError::TargetNotFound { target })) if target == "outside"
1275            ));
1276            assert!(stream.next().await.is_none());
1277        }
1278        let mut stream = Arc::new(TargetProbe::MismatchedCompletion).run_stream(
1279            request(),
1280            Arc::new(restricted_models()),
1281            State::default(),
1282        );
1283        assert!(matches!(
1284            stream.next().await,
1285            Some(Err(LibsyError::AlgorithmError { .. }))
1286        ));
1287
1288        let mut stream = Arc::new(TargetProbe::Model(&["outside"])).run_stream(
1289            request(),
1290            Arc::new(RuntimeModels::default()),
1291            State::default(),
1292        );
1293        assert!(matches!(stream.next().await, Some(Ok(Step::CallModel(_)))));
1294    }
1295
1296    #[tokio::test]
1297    async fn target_restriction_rechecks_rewritten_steps() {
1298        for probe in [
1299            TargetProbe::Model(&["allowed"]),
1300            TargetProbe::Decision("judge"),
1301            TargetProbe::Completion(&["allowed"]),
1302        ] {
1303            let probe = Arc::new(probe);
1304            let run = |rewrite| {
1305                drive(
1306                    Arc::new(RewrittenSteps(Arc::clone(&probe), rewrite)),
1307                    request(),
1308                    Arc::new(restricted_models()),
1309                    |_| async { panic!("invalid work must not reach the host") },
1310                )
1311            };
1312            let result = run(|step| match step {
1313                Step::CallModel(call) => call.models.push("outside".into()),
1314                Step::CallDecision(call) => call.model = "outside".into(),
1315                Step::Done(outcome) => outcome.selected_model_ids.push("outside".into()),
1316            })
1317            .await;
1318            assert!(
1319                matches!(result, Err(LibsyError::TargetNotFound { target }) if target == "outside")
1320            );
1321
1322            let result = run(|step| match step {
1323                Step::CallModel(call) => call.request.llm_request.model = Some("outside".into()),
1324                Step::CallDecision(call) => call.request.model = Some("allowed".into()),
1325                Step::Done(outcome) => outcome.request.llm_request.model = Some("outside".into()),
1326            })
1327            .await;
1328            assert!(matches!(result, Err(LibsyError::AlgorithmError { .. })));
1329        }
1330    }
1331
1332    #[tokio::test]
1333    async fn target_restriction_preserves_allowed_work() -> Result<()> {
1334        for (probe, expected) in [
1335            (
1336                TargetProbe::Model(&["allowed", "fallback"]),
1337                &["allowed"][..],
1338            ),
1339            (TargetProbe::Model(&["judge"]), &["judge"][..]),
1340            (TargetProbe::Decision("judge"), &["allowed"][..]),
1341            (
1342                TargetProbe::Completion(&["allowed", "fallback"]),
1343                &["allowed", "fallback"][..],
1344            ),
1345            (TargetProbe::Completion(&["subagent"]), &["subagent"][..]),
1346        ] {
1347            let outcome = drive(
1348                Arc::new(probe),
1349                request(),
1350                Arc::new(restricted_models()),
1351                |call| async move {
1352                    match call {
1353                        Call::Model(call) => {
1354                            call.respond(std::future::ready(Ok(reply("ok")))).await
1355                        }
1356                        Call::Decision(call) => serve_decision(*call).await,
1357                    }
1358                },
1359            )
1360            .await?;
1361            assert_eq!(outcome.selected_model_ids, target_set(expected));
1362        }
1363        let outcome = drive(
1364            Arc::new(crate::Noop {}),
1365            request(),
1366            Arc::new(RuntimeModels::default().with_target_restriction()),
1367            |_| async { panic!("Noop must not request model calls") },
1368        )
1369        .await?;
1370        assert!(outcome.response.is_some());
1371        Ok(())
1372    }
1373
1374    #[tokio::test]
1375    async fn typed_driver_preserves_call_and_stream_boundaries() -> Result<()> {
1376        tokio::time::timeout(std::time::Duration::from_secs(1), async {
1377            // Distinct oneshots keep reverse-order replies paired with their producers, and a
1378            // retained call remains pending until the host responds.
1379            let (driver, mut step_rx) = Driver::new("test", Arc::new(RuntimeModels::default()));
1380            let first_driver = driver.clone();
1381            let mut first = tokio::spawn(async move {
1382                first_driver
1383                    .call_model(request(), vec![ModelId::from("first")])
1384                    .await
1385            });
1386            let second = tokio::spawn(async move {
1387                driver
1388                    .call_model(request(), vec![ModelId::from("second")])
1389                    .await
1390            });
1391
1392            let mut calls = HashMap::new();
1393            for _ in 0..2 {
1394                let step = step_rx.recv().await.ok_or(DriverError::StreamClosed)??;
1395                let Step::CallModel(call) = step else {
1396                    return Err(test_error("expected a CallModel step"));
1397                };
1398                let selected_model = call
1399                    .models
1400                    .first()
1401                    .ok_or_else(|| test_error("model call has no candidates"))?
1402                    .to_string();
1403                calls.insert(selected_model, call);
1404            }
1405            assert!(
1406                tokio::time::timeout(std::time::Duration::from_millis(20), &mut first)
1407                    .await
1408                    .is_err(),
1409                "call completed before the host responded"
1410            );
1411            calls
1412                .remove("second")
1413                .ok_or_else(|| test_error("missing second call"))?
1414                .respond(std::future::ready(Ok(reply("second response")))).await?;
1415            calls
1416                .remove("first")
1417                .ok_or_else(|| test_error("missing first call"))?
1418                .respond(std::future::ready(Ok(reply("first response")))).await?;
1419
1420            let first_response = first
1421                .await
1422                .map_err(|source| LibsyError::external("joining a test task", source))??;
1423            let second_response = second
1424                .await
1425                .map_err(|source| LibsyError::external("joining a test task", source))??;
1426            assert_eq!(
1427                first_response.llm_response.as_agg().map(completion_text),
1428                Some("first response".to_string())
1429            );
1430            assert_eq!(
1431                second_response.llm_response.as_agg().map(completion_text),
1432                Some("second response".to_string())
1433            );
1434
1435            // Dropping the host-facing promise closes only that call's reply channel.
1436            let (driver, mut step_rx) = Driver::new("test", Arc::new(RuntimeModels::default()));
1437            let producer = tokio::spawn(async move {
1438                driver
1439                    .call_model(request(), vec![ModelId::from("dropped")])
1440                    .await
1441            });
1442            let step = step_rx.recv().await.ok_or(DriverError::StreamClosed)??;
1443            let Step::CallModel(call) = step else {
1444                return Err(test_error("expected a CallModel step"));
1445            };
1446            drop(call);
1447            let result = producer
1448                .await
1449                .map_err(|source| LibsyError::external("joining a test task", source))?;
1450            assert!(matches!(
1451                result,
1452                Err(LibsyError::Driver(DriverError::ResponseDropped))
1453            ));
1454
1455            // A standalone driver reports the typed step receiver disappearing at its next call.
1456            let (driver, step_rx) = Driver::new("test", Arc::new(RuntimeModels::default()));
1457            drop(step_rx);
1458            let result = driver
1459                .call_model(request(), vec![ModelId::from("closed")])
1460                .await;
1461            assert!(matches!(
1462                result,
1463                Err(LibsyError::Driver(DriverError::StreamClosed))
1464            ));
1465
1466            fn decision_request() -> DecisionRequest {
1467                DecisionRequest {
1468                    model: Some("overwritten".into()),
1469                    input: serde_json::json!({"task": "choose a route"}),
1470                    questions: Default::default(),
1471                }
1472            }
1473
1474            fn decision_response() -> DecisionResponse {
1475                DecisionResponse {
1476                    id: Some("decision-1".to_string()),
1477                    model: Some("provider-model".into()),
1478                    answers: [(
1479                        "p_solve".to_string(),
1480                        switchyard_protocol::DecisionAnswer {
1481                            value: switchyard_protocol::DecisionValue::Boolean(
1482                                switchyard_protocol::BooleanEstimate::ProbabilityTrue(
1483                                    switchyard_protocol::Probability(0.8),
1484                                ),
1485                            ),
1486                            provider_confidence: None,
1487                        },
1488                    )]
1489                    .into(),
1490                    usage: Default::default(),
1491                }
1492            }
1493
1494            struct MixedCalls(&'static str);
1495
1496            #[async_trait]
1497            impl Algorithm for MixedCalls {
1498                fn name(&self) -> &str {
1499                    "mixed"
1500                }
1501
1502                async fn route(
1503                    self: Arc<Self>,
1504                    driver: Driver,
1505                    request: Request,
1506                ) -> Result<RoutingOutcome> {
1507                    let (llm, decision) = tokio::join!(
1508                        driver.call_model(request.clone(), vec!["llm".into()]),
1509                        driver.call_decision(decision_request(), "decision".into()),
1510                    );
1511                    assert_eq!(
1512                        llm?.llm_response.as_agg().map(completion_text),
1513                        Some("llm reply".into())
1514                    );
1515                    match self.0 {
1516                        "mock" => assert_eq!(decision?, DecisionResponse {
1517                            id: None,
1518                            model: Some("decision".into()),
1519                            answers: Default::default(),
1520                            usage: Default::default(),
1521                        }),
1522                        "reply" => assert_eq!(decision?, decision_response()),
1523                        "error" => assert!(matches!(
1524                            decision,
1525                            Err(LibsyError::AlgorithmError { message }) if message == "provider failed"
1526                        )),
1527                        "drop" => assert!(matches!(
1528                            decision,
1529                            Err(LibsyError::Driver(DriverError::ResponseDropped))
1530                        )),
1531                        "abort" => return std::future::pending().await,
1532                        _ => unreachable!(),
1533                    }
1534                    Ok(RoutingOutcome::route_to("answer".into(), vec![], request))
1535                }
1536            }
1537
1538            for mode in ["mock", "reply", "error", "drop", "abort"] {
1539                // Serial dispatch would deadlock here and fail the enclosing timeout.
1540                let barrier = Arc::new(tokio::sync::Barrier::new(2));
1541                let outcome = drive(
1542                    Arc::new(MixedCalls(mode)),
1543                    request(),
1544                    Arc::new(RuntimeModels::default()),
1545                    move |call| {
1546                        let barrier = barrier.clone();
1547                        async move {
1548                            barrier.wait().await;
1549                            let call = match call {
1550                                Call::Model(call) => return call.respond(std::future::ready(Ok(reply("llm reply")))).await,
1551                                Call::Decision(call) => *call,
1552                            };
1553                            assert_eq!(call.algorithm, "mixed");
1554                            assert_eq!(call.model, "decision");
1555                            assert_eq!(call.request.model, Some("decision".into()));
1556                            assert_eq!(call.request.input, decision_request().input);
1557                            match mode {
1558                                "mock" => serve_decision(call).await,
1559                                "reply" => call.respond(std::future::ready(Ok(decision_response()))).await,
1560                                "error" => call.respond(std::future::ready(Err(LibsyError::AlgorithmError {
1561                                    message: "provider failed".into(),
1562                                }))).await,
1563                                "drop" => {
1564                                    drop(call);
1565                                    Ok(())
1566                                }
1567                                "abort" => call.fail(test_error("host aborted")),
1568                                _ => unreachable!(),
1569                            }
1570                        }
1571                    },
1572                )
1573                .await;
1574                if mode == "abort" {
1575                    assert!(matches!(outcome, Err(LibsyError::External { .. })));
1576                } else {
1577                    assert_eq!(outcome?.selected_model_id()?, "answer");
1578                }
1579            }
1580
1581            let (driver, mut steps) = Driver::new("test", Arc::new(RuntimeModels::default()));
1582            let mut pending = Box::pin(driver.call_decision(decision_request(), "decision".into()));
1583            assert!(futures::poll!(&mut pending).is_pending());
1584            let Some(Ok(Step::CallDecision(call))) = steps.recv().await else {
1585                return Err(test_error("expected a decision call"));
1586            };
1587            drop(pending);
1588            call.respond(async { panic!("cancelled work must not be polled") }).await?;
1589            drop(steps);
1590            assert!(matches!(
1591                driver.call_decision(decision_request(), "decision".into()).await,
1592                Err(LibsyError::Driver(DriverError::StreamClosed))
1593            ));
1594            Ok(())
1595        })
1596        .await
1597        .map_err(|error| LibsyError::external("waiting for typed driver boundaries", error))?
1598    }
1599
1600    #[test]
1601    fn target_lookup_returns_the_missing_target() {
1602        let error = ensure_model_is_target(&target_set(&[]), &ModelId::from("missing")).err();
1603        assert!(matches!(
1604            error,
1605            Some(LibsyError::TargetNotFound { target }) if target == "missing"
1606        ));
1607    }
1608
1609    /// Build a single-target algo, plus a `serve` that answers it as a token stream
1610    /// replaying `chunks` in order (as `Ok` items).
1611    fn streaming_orch(chunks: Vec<LlmResponseChunk>) -> (Arc<dyn Algorithm>, impl Serve) {
1612        let algo = orch(target_set(&["stream/model"]));
1613        let serve = move |_target: ModelId, _request: Request| {
1614            let chunks = chunks.clone();
1615            async move {
1616                let stream =
1617                    futures::stream::iter(chunks.into_iter().map(|chunk| Ok(chunk.into()))).boxed();
1618                Ok(Response {
1619                    llm_response: LlmResponse::Stream(stream),
1620                    metadata: None,
1621                    upstream_headers: http::HeaderMap::new(),
1622                })
1623            }
1624        };
1625        (algo, serve)
1626    }
1627
1628    #[tokio::test]
1629    async fn run_returns_a_streamed_response_the_caller_aggregates() -> Result<()> {
1630        // A streaming client -> its chunks flow through the promise and `Done`,
1631        // and `run` returns the live stream untouched for the caller to fold.
1632        let (orch, serve) = streaming_orch(vec![
1633            LlmResponseChunk::MessageStart {
1634                id: Some("m1".to_string()),
1635                model: Some("stream/model".to_string()),
1636            },
1637            LlmResponseChunk::TextDelta {
1638                index: 0,
1639                text: "hel".to_string(),
1640            },
1641            LlmResponseChunk::TextDelta {
1642                index: 0,
1643                text: "lo".to_string(),
1644            },
1645            LlmResponseChunk::MessageStop {
1646                reason: Some("stop".to_string()),
1647            },
1648        ]);
1649        let (selected_model, response) = test_drive(orch, request(), serve).await?;
1650        // The run handed back the live stream; the caller folds it to a buffered aggregate.
1651        let agg = response
1652            .llm_response
1653            .into_agg()
1654            .await
1655            .map_err(|error| LibsyError::external("aggregating response stream", error))?;
1656        assert_eq!(completion_text(&agg), "hello");
1657        assert_eq!(agg.model.as_deref(), Some("stream/model"));
1658        assert_eq!(selected_model, "stream/model");
1659        Ok(())
1660    }
1661
1662    #[tokio::test]
1663    async fn aggregating_a_streamed_response_propagates_a_mid_stream_error() -> Result<()> {
1664        // The run succeeds and returns the stream; the in-band `Error` chunk surfaces only
1665        // when the caller aggregates it.
1666        let (orch, serve) = streaming_orch(vec![
1667            LlmResponseChunk::TextDelta {
1668                index: 0,
1669                text: "partial".to_string(),
1670            },
1671            LlmResponseChunk::StreamError {
1672                message: "upstream exploded".to_string(),
1673            },
1674        ]);
1675        let (_, response) = test_drive(orch, request(), serve).await?;
1676        match response.llm_response.into_agg().await {
1677            Ok(_) => panic!("expected a mid-stream error, got an aggregate"),
1678            Err(err) => {
1679                assert!(err.to_string().contains("upstream exploded"));
1680                Ok(())
1681            }
1682        }
1683    }
1684
1685    #[tokio::test]
1686    async fn run_offloads_via_promise_then_finishes() -> Result<()> {
1687        // Every call is offloaded via a promise the orchestrator surfaces as a
1688        // `CallModel` step for us to fulfill.
1689        let stream = orch(target_set(&["offload/model"])).run_stream(
1690            request(),
1691            Arc::new(RuntimeModels::default()),
1692            State::default(),
1693        );
1694        tokio::pin!(stream);
1695
1696        let mut saw_call = false;
1697        let mut final_completion = None;
1698        while let Some(step) = stream.next().await {
1699            match step? {
1700                Step::CallDecision(_) => return Err(test_error("unexpected decision call")),
1701                Step::CallModel(call) => {
1702                    saw_call = true;
1703                    assert_eq!(call.models, vec![ModelId::from("offload/model")]);
1704                    // Fulfilling the promise is the "real" model call the caller makes.
1705                    call.respond(std::future::ready(Ok(Response {
1706                        llm_response: LlmResponse::Agg(text_response(
1707                            None,
1708                            "fulfilled".to_string(),
1709                        )),
1710                        metadata: None,
1711                        upstream_headers: http::HeaderMap::new(),
1712                    })))
1713                    .await?;
1714                }
1715                Step::Done(outcome) => {
1716                    let metadata = outcome
1717                        .metadata
1718                        .as_ref()
1719                        .expect("run_stream should attach outcome metadata");
1720                    assert_eq!(metadata.algorithm, "test");
1721                    assert_eq!(
1722                        uuid::Uuid::parse_str(metadata.outcome_id())
1723                            .expect("outcome id should be a UUID")
1724                            .get_version_num(),
1725                        7
1726                    );
1727                    assert_eq!(
1728                        metadata.evidence,
1729                        Some(serde_json::json!({"source": "test"}))
1730                    );
1731                    assert_eq!(
1732                        metadata.judgments[0].evidence,
1733                        Some(serde_json::json!({"source": "judge"}))
1734                    );
1735                    let response = outcome
1736                        .response
1737                        .ok_or_else(|| test_error("expected an answered outcome"))?;
1738                    final_completion = Some(
1739                        response
1740                            .llm_response
1741                            .as_agg()
1742                            .map(completion_text)
1743                            .unwrap_or_default(),
1744                    );
1745                }
1746            }
1747        }
1748
1749        assert!(saw_call, "expected a CallModel step before Done");
1750        assert_eq!(
1751            final_completion.ok_or_else(|| test_error("no Done step"))?,
1752            "fulfilled"
1753        );
1754        Ok(())
1755    }
1756
1757    #[tokio::test(flavor = "multi_thread", worker_threads = 12)]
1758    async fn requests_are_processed_in_parallel() -> Result<()> {
1759        use std::time::Duration;
1760        use tokio::sync::Barrier;
1761
1762        const N: usize = 12;
1763
1764        // Serving blocks until all N concurrent calls have arrived. If requests were
1765        // serialized (one algorithm behind a `Mutex`), only one call could be in flight,
1766        // the barrier would never reach N, and the test would time out. It passes only
1767        // because the shared algorithm is driven concurrently across requests.
1768        let barrier = Arc::new(Barrier::new(N));
1769        // One shared algorithm driven by many concurrent requests.
1770        let algo = orch(target_set(&["m"]));
1771
1772        let mut handles = Vec::new();
1773        for _ in 0..N {
1774            let algo = algo.clone();
1775            let barrier = barrier.clone();
1776            let serve = move |target: ModelId, _request: Request| {
1777                let barrier = barrier.clone();
1778                async move {
1779                    barrier.wait().await;
1780                    Ok(reply(target))
1781                }
1782            };
1783            handles.push(tokio::spawn(async move {
1784                test_drive(algo, request(), serve)
1785                    .await
1786                    .map(|(_, response)| {
1787                        response
1788                            .llm_response
1789                            .as_agg()
1790                            .map(completion_text)
1791                            .unwrap_or_default()
1792                    })
1793            }));
1794        }
1795
1796        for handle in handles {
1797            // The timeout turns a serialization deadlock into a failure, not a hang.
1798            let completion = tokio::time::timeout(Duration::from_secs(5), handle)
1799                .await
1800                .map_err(|error| LibsyError::external("waiting for test task", error))?
1801                .map_err(|source| LibsyError::external("joining a test task", source))??;
1802            assert_eq!(completion, "m");
1803        }
1804        Ok(())
1805    }
1806
1807    #[tokio::test]
1808    async fn offload_error_propagates_back_to_the_algorithm() -> Result<()> {
1809        // A client-less target offloads its call; we fulfill the promise with an
1810        // Err, which must flow back through `call_model_target` into the algorithm and
1811        // out as an error step — not a response.
1812        let stream = orch(target_set(&["offload/model"])).run_stream(
1813            request(),
1814            Arc::new(RuntimeModels::default()),
1815            State::default(),
1816        );
1817        tokio::pin!(stream);
1818
1819        let mut saw_error = false;
1820        while let Some(step) = stream.next().await {
1821            match step {
1822                Ok(Step::CallDecision(_)) => return Err(test_error("unexpected decision call")),
1823                Ok(Step::CallModel(mut call)) => {
1824                    call.recover_errors = true;
1825                    call.respond(std::future::ready(Err(test_error(
1826                        "upstream model call failed",
1827                    ))))
1828                    .await?;
1829                }
1830                Ok(Step::Done(..)) => {
1831                    return Err(test_error(
1832                        "expected the offload error to propagate, got a response",
1833                    ));
1834                }
1835                Err(err) => {
1836                    // The algorithm's `call_model_target` saw the error via the promise.
1837                    assert!(err.to_string().contains("upstream model call failed"));
1838                    saw_error = true;
1839                }
1840            }
1841        }
1842
1843        assert!(saw_error, "expected an error step");
1844        Ok(())
1845    }
1846
1847    #[tokio::test]
1848    async fn dropping_the_stream_cancels_the_algorithm_task() -> Result<()> {
1849        use std::sync::atomic::{AtomicBool, Ordering};
1850        use std::time::Duration;
1851        use tokio::sync::mpsc;
1852
1853        // Sets a flag when dropped, so we can observe whether the algorithm task was
1854        // cancelled/dropped.
1855        struct DropGuard(Arc<AtomicBool>);
1856        impl Drop for DropGuard {
1857            fn drop(&mut self) {
1858                self.0.store(true, Ordering::SeqCst);
1859            }
1860        }
1861
1862        struct StuckAlgo {
1863            started: mpsc::UnboundedSender<()>,
1864            dropped: Arc<AtomicBool>,
1865        }
1866
1867        #[async_trait]
1868        impl Algorithm for StuckAlgo {
1869            fn name(&self) -> &str {
1870                "stuck"
1871            }
1872
1873            async fn route(
1874                self: Arc<Self>,
1875                _driver: Driver,
1876                _request: Request,
1877            ) -> Result<RoutingOutcome> {
1878                let _guard = DropGuard(self.dropped.clone());
1879                let _ = self.started.send(());
1880                // Await forever without ever touching the driver.
1881                std::future::pending::<()>().await;
1882                unreachable!()
1883            }
1884        }
1885
1886        let (started_tx, mut started_rx) = mpsc::unbounded_channel();
1887        let dropped = Arc::new(AtomicBool::new(false));
1888        let algo: Arc<dyn Algorithm> = Arc::new(StuckAlgo {
1889            started: started_tx,
1890            dropped: dropped.clone(),
1891        });
1892
1893        let stream = algo.run_stream(
1894            request(),
1895            Arc::new(RuntimeModels::default()),
1896            State::default(),
1897        );
1898        started_rx
1899            .recv()
1900            .await
1901            .ok_or_else(|| test_error("task never started"))?;
1902        drop(stream);
1903        tokio::time::sleep(Duration::from_millis(100)).await;
1904
1905        assert!(
1906            dropped.load(Ordering::SeqCst),
1907            "algorithm task was NOT cancelled after dropping the stream"
1908        );
1909        Ok(())
1910    }
1911
1912    #[tokio::test]
1913    async fn route_panic_surfaces_as_a_stream_error() -> Result<()> {
1914        // An algorithm whose task panics must surface an `Err` step carrying the panic
1915        // message, not abort the process from an unobserved detached task.
1916        struct Panicky;
1917
1918        #[async_trait]
1919        impl Algorithm for Panicky {
1920            fn name(&self) -> &str {
1921                "panicky"
1922            }
1923
1924            async fn route(
1925                self: Arc<Self>,
1926                _driver: Driver,
1927                _request: Request,
1928            ) -> Result<RoutingOutcome> {
1929                panic!("boom");
1930            }
1931        }
1932
1933        let algo: Arc<dyn Algorithm> = Arc::new(Panicky);
1934        let stream = algo.run_stream(
1935            request(),
1936            Arc::new(RuntimeModels::default()),
1937            State::default(),
1938        );
1939        tokio::pin!(stream);
1940
1941        let mut saw_error = false;
1942        while let Some(step) = stream.next().await {
1943            match step {
1944                Err(err) => {
1945                    // The panic message is preserved, not flattened into an opaque failure.
1946                    assert!(err.to_string().contains("algorithm task panicked: boom"));
1947                    saw_error = true;
1948                }
1949                Ok(_) => return Err(test_error("expected the panic to surface as an error step")),
1950            }
1951        }
1952
1953        assert!(saw_error, "expected an error step from the panicked task");
1954        Ok(())
1955    }
1956
1957    /// A panicking algorithm must publish its terminal step even when it left a `Driver`
1958    /// clone alive in another task. That clone holds the step channel open, so a run that
1959    /// merely unwound would never terminate and the consumer would wait forever.
1960    #[tokio::test]
1961    async fn a_panic_with_a_leaked_driver_clone_still_terminates_the_run() -> Result<()> {
1962        struct LeakyPanic;
1963
1964        #[async_trait]
1965        impl Algorithm for LeakyPanic {
1966            fn name(&self) -> &str {
1967                "leaky_panic"
1968            }
1969
1970            async fn route(
1971                self: Arc<Self>,
1972                driver: Driver,
1973                _request: Request,
1974            ) -> Result<RoutingOutcome> {
1975                tokio::spawn(async move {
1976                    // Outlives the panic below, keeping a sender clone alive.
1977                    let _keep_alive = driver;
1978                    std::future::pending::<()>().await;
1979                });
1980                tokio::task::yield_now().await;
1981                panic!("boom");
1982            }
1983        }
1984
1985        let algo: Arc<dyn Algorithm> = Arc::new(LeakyPanic);
1986        // The timeout turns the hang this guards against into a failure rather than a hang.
1987        let result = tokio::time::timeout(
1988            std::time::Duration::from_secs(1),
1989            test_drive(algo, request(), echo()),
1990        )
1991        .await
1992        .map_err(|error| LibsyError::external("waiting for the panicked run to end", error))?;
1993
1994        match result {
1995            Ok(_) => Err(test_error(
1996                "expected the panic to end the run with an error",
1997            )),
1998            Err(err) => {
1999                assert!(err.to_string().contains("algorithm task panicked: boom"));
2000                Ok(())
2001            }
2002        }
2003    }
2004
2005    #[tokio::test]
2006    async fn cancelling_run_cancels_the_algorithm_task() -> Result<()> {
2007        use std::sync::atomic::{AtomicBool, Ordering};
2008        use std::time::Duration;
2009        use tokio::sync::mpsc;
2010
2011        // Sets a flag when dropped, so we can observe whether the algorithm task was
2012        // cancelled once the `run` future driving it is dropped.
2013        struct DropGuard(Arc<AtomicBool>);
2014        impl Drop for DropGuard {
2015            fn drop(&mut self) {
2016                self.0.store(true, Ordering::SeqCst);
2017            }
2018        }
2019
2020        struct StuckAlgo {
2021            started: mpsc::UnboundedSender<()>,
2022            dropped: Arc<AtomicBool>,
2023        }
2024
2025        #[async_trait]
2026        impl Algorithm for StuckAlgo {
2027            fn name(&self) -> &str {
2028                "stuck"
2029            }
2030
2031            async fn route(
2032                self: Arc<Self>,
2033                _driver: Driver,
2034                _request: Request,
2035            ) -> Result<RoutingOutcome> {
2036                let _guard = DropGuard(self.dropped.clone());
2037                let _ = self.started.send(());
2038                // Hang forever without ever touching the driver, so only cancellation
2039                // (not a dropped step channel) can stop this task.
2040                std::future::pending::<()>().await;
2041                unreachable!()
2042            }
2043        }
2044
2045        let (started_tx, mut started_rx) = mpsc::unbounded_channel();
2046        let dropped = Arc::new(AtomicBool::new(false));
2047        let algo: Arc<dyn Algorithm> = Arc::new(StuckAlgo {
2048            started: started_tx,
2049            dropped: dropped.clone(),
2050        });
2051
2052        // Drive the run on its own task, wait until the algorithm task is up, then cancel
2053        // it — dropping its future (and the `run_stream` stream it holds).
2054        let run_task = tokio::spawn(async move { test_drive(algo, request(), echo()).await });
2055        started_rx
2056            .recv()
2057            .await
2058            .ok_or_else(|| test_error("task never started"))?;
2059        run_task.abort();
2060        tokio::time::sleep(Duration::from_millis(100)).await;
2061
2062        assert!(
2063            dropped.load(Ordering::SeqCst),
2064            "algorithm task was NOT cancelled after cancelling run"
2065        );
2066        Ok(())
2067    }
2068
2069    // --- first-wins hedging: `run` must not wait on losing speculative calls -------------
2070
2071    /// Offloads two targets concurrently and returns the first to resolve, dropping the
2072    /// loser's call (first-wins hedging).
2073    struct Hedge {
2074        winner: String,
2075        loser: String,
2076    }
2077
2078    #[async_trait]
2079    impl Algorithm for Hedge {
2080        fn name(&self) -> &str {
2081            "hedge"
2082        }
2083
2084        async fn route(
2085            self: Arc<Self>,
2086            driver: Driver,
2087            request: Request,
2088        ) -> Result<RoutingOutcome> {
2089            let outcome_request = request.clone();
2090            let win = driver.call_model(request.clone(), vec![self.winner.clone().into()]);
2091            let lose = driver.call_model(request, vec![self.loser.clone().into()]);
2092            // First to resolve wins; `select!` drops the losing future (and its promise).
2093            tokio::select! {
2094                res = win => Ok(RoutingOutcome::answered(
2095                    self.winner.clone().into(),
2096                    outcome_request,
2097                    res?,
2098                )),
2099                res = lose => Ok(RoutingOutcome::answered(
2100                    self.loser.clone().into(),
2101                    outcome_request,
2102                    res?,
2103                )),
2104            }
2105        }
2106    }
2107
2108    /// Builds a hedging algo and the `serve` that drives it: the winner is gated behind the
2109    /// loser starting (so the loser's serve is guaranteed in flight when the winner wins),
2110    /// and the loser finishes after `loser_delay` — or never, when `None`.
2111    fn hedge(loser_delay: Option<std::time::Duration>) -> (Arc<dyn Algorithm>, impl Serve) {
2112        let started = Arc::new(tokio::sync::Notify::new());
2113        let algo = Arc::new(Hedge {
2114            winner: "winner".to_string(),
2115            loser: "loser".to_string(),
2116        });
2117        let serve = move |target: ModelId, _request: Request| {
2118            let started = started.clone();
2119            async move {
2120                if target == "loser" {
2121                    started.notify_one();
2122                    match loser_delay {
2123                        Some(delay) => tokio::time::sleep(delay).await,
2124                        None => std::future::pending::<()>().await,
2125                    }
2126                } else {
2127                    started.notified().await;
2128                }
2129                Ok(reply(target))
2130            }
2131        };
2132        (algo, serve)
2133    }
2134
2135    #[tokio::test]
2136    async fn run_returns_the_winner_without_a_late_loser_overwriting_it() -> Result<()> {
2137        // The loser responds 50ms after the winner has already won. `run` must return the
2138        // winner, not the loser's `respond`-to-a-dropped-receiver error.
2139        let (algo, serve) = hedge(Some(std::time::Duration::from_millis(50)));
2140        let (_, response) = test_drive(algo, request(), serve).await?;
2141        assert_eq!(
2142            response
2143                .llm_response
2144                .as_agg()
2145                .map(completion_text)
2146                .unwrap_or_default(),
2147            "winner"
2148        );
2149        Ok(())
2150    }
2151
2152    #[tokio::test]
2153    async fn run_returns_the_winner_without_hanging_on_a_pending_loser() -> Result<()> {
2154        // The loser never resolves. `run` must return the winner promptly, not hang
2155        // waiting for the in-flight loser.
2156        let (algo, serve) = hedge(None);
2157        let run = test_drive(algo, request(), serve);
2158        let (_, response) = tokio::time::timeout(std::time::Duration::from_secs(1), run)
2159            .await
2160            .map_err(|error| LibsyError::external("waiting for pending loser", error))??;
2161        assert_eq!(
2162            response
2163                .llm_response
2164                .as_agg()
2165                .map(completion_text)
2166                .unwrap_or_default(),
2167            "winner"
2168        );
2169        Ok(())
2170    }
2171
2172    #[tokio::test]
2173    async fn run_surfaces_a_terminal_error_with_many_calls_in_flight() -> Result<()> {
2174        use std::sync::atomic::{AtomicUsize, Ordering};
2175
2176        // A large fan-out (10 matched the old, now-removed concurrency cap). The terminal
2177        // error must still reach the caller with all of these calls pending.
2178        const N: usize = 10;
2179
2180        // Fans out N calls, then errors as soon as all N are in flight — exercising a
2181        // terminal failure emitted while the offloaded calls are still pending.
2182        struct FanOutThenError {
2183            all_started: Arc<tokio::sync::Notify>,
2184            n: usize,
2185        }
2186
2187        #[async_trait]
2188        impl Algorithm for FanOutThenError {
2189            fn name(&self) -> &str {
2190                "fan_out_then_error"
2191            }
2192
2193            async fn route(
2194                self: Arc<Self>,
2195                driver: Driver,
2196                request: Request,
2197            ) -> Result<RoutingOutcome> {
2198                let offloads = futures::future::join_all(
2199                    (0..self.n)
2200                        .map(|i| driver.call_model(request.clone(), vec![format!("m{i}").into()])),
2201                );
2202                tokio::select! {
2203                    _ = offloads => Err(test_error("offloads unexpectedly completed")),
2204                    _ = self.all_started.notified() => {
2205                        Err(test_error("terminal error while calls pending"))
2206                    }
2207                }
2208            }
2209        }
2210
2211        let all_started = Arc::new(tokio::sync::Notify::new());
2212        let algo: Arc<dyn Algorithm> = Arc::new(FanOutThenError {
2213            all_started: all_started.clone(),
2214            n: N,
2215        });
2216
2217        // Serving enters each call; once all N are in flight it signals, then pends forever.
2218        let started = Arc::new(AtomicUsize::new(0));
2219        let serve = move |_target: ModelId, _request: Request| {
2220            let started = started.clone();
2221            let all_started = all_started.clone();
2222            async move {
2223                if started.fetch_add(1, Ordering::SeqCst) + 1 == N {
2224                    all_started.notify_one();
2225                }
2226                std::future::pending::<ServeResult>().await
2227            }
2228        };
2229
2230        // With the cap gone, the driver keeps polling the stream even with N calls in
2231        // flight, so the terminal error surfaces promptly instead of hanging.
2232        let run = test_drive(algo, request(), serve);
2233        let result = tokio::time::timeout(std::time::Duration::from_millis(500), run)
2234            .await
2235            .map_err(|error| {
2236                LibsyError::external("waiting for terminal error with full call cap", error)
2237            })?;
2238        match result {
2239            Ok(_) => Err(test_error("expected the terminal error, got a response")),
2240            Err(err) => {
2241                assert!(
2242                    err.to_string()
2243                        .contains("terminal error while calls pending")
2244                );
2245                Ok(())
2246            }
2247        }
2248    }
2249}