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