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