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