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