Skip to main content

weirdnet_agent/remote/
pool.rs

1//! The asking side of remote inference: a pool of inference nodes.
2//!
3//! [`Pool`] sends a [`Request`] to the first node of its [`NodeSource`] that takes it
4//! (infer/2, falling back to infer/1 on nodes that only serve that), streams the answer to an
5//! [`EventSink`], and moves on to the next node when one fails:
6//!
7//! - **Before any text** (unreachable, busy, no such model, no `Accepted` in time): the next
8//!   node is tried, as `RemoteModel` always did. `Queued` frames reset the accept timeout.
9//! - **During the answer** (the stream drops, the node fails, or no frame arrives within the
10//!   [`Stall`] timeout, after which the pool sends `Cancel` itself rather than wait out
11//!   `weirdnet-net`'s 30 s stream resume): with [`PoolOptions::resume`] on, the request goes to
12//!   the next node as the same job with `attempt + 1` and the text shown so far as
13//!   `assistant_prefix`, but only to a node whose `Accepted` says `resume: true`. Frames are
14//!   placed by offset, so nothing is shown twice. At most [`PoolOptions::max_resumes`] resumes
15//!   per answer; each is recorded in the answer's [`Meta::resumes`]. With resume off, or once
16//!   nothing more can take it, the partial answer comes back in [`Interrupted`].
17//! - **Continue:** a request that already carries an `assistant_prefix` (the user asked to
18//!   continue a stopped or cut-off answer) continues that text: the answer starts from the
19//!   prefix ([`Answer::prefix`]; `text` and `reasoning` include it, events carry only what is
20//!   new), and only nodes whose `Accepted` says `resume: true` take it. Failover keeps the
21//!   prefix whether or not resume is on; infer/1 nodes are skipped.
22//!
23//! - **Images and audio:** a request whose messages carry image or audio parts
24//!   ([`Request::needs`]) is routed by the catalog first ([`Catalog::route`]): a named model must
25//!   list those inputs, and with none named the pool picks one that does. When the catalog says
26//!   no model takes them, the request fails with `BadRequest` before any node runs it. With no
27//!   catalog to ask, the nodes decide (model nodes refuse inputs their model can't read). Such
28//!   requests never go to infer/1 nodes, which predate content parts.
29//!
30//! The pool also queries and subscribes to the [`catalog`], sends embeddings and transcription
31//! requests ([`Pool::transcribe`]), and runs [`Job`]s in the background. It has no networking of its own: a [`Dialer`] opens
32//! channels and a [`NodeSource`] says which nodes to try, in order. The `pool` cargo feature
33//! provides both over `weirdnet-net` (`crate::pool`).
34
35use std::collections::BTreeMap;
36use std::sync::Arc;
37use std::time::Duration;
38
39use tokio::time::Instant;
40
41use async_trait::async_trait;
42use tokio::sync::{mpsc, watch};
43use tokio::task::JoinHandle;
44
45use super::catalog::{self, Catalog};
46use super::infer::v2::{
47    self, ClientFrame, EmbedRequest, Finish, Meta, Prefix, Request, Resume, ServerFrame, TranscribeRequest, Transcript, Usage, chars,
48};
49use super::infer::{self as v1, DEFAULT_ACCEPT_TIMEOUT};
50use super::{Channel, Dialer, RemoteError, request_id};
51use crate::cancel::CancelToken;
52use crate::model::{DeltaSink, ModelTurn, ToolCall};
53
54/// Resumes per answer when [`PoolOptions::resume`] is on.
55pub const DEFAULT_MAX_RESUMES: u32 = 2;
56
57/// When an accepted stream counts as stalled: no frame for `max(min, factor × the recent gap
58/// between frames)`, capped at `max`. Before the first frame after `Accepted` (prompt
59/// processing) the wait is `max`. The defaults (15 s, 3×, 25 s) stay under `weirdnet-net`'s
60/// 30 s stream resume window, so the pool cancels and moves on before the transport would give
61/// up.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63#[non_exhaustive]
64pub struct Stall {
65    pub min: Duration,
66    pub factor: u32,
67    pub max: Duration,
68}
69
70impl Default for Stall {
71    fn default() -> Self {
72        Self { min: Duration::from_secs(15), factor: 3, max: Duration::from_secs(25) }
73    }
74}
75
76impl Stall {
77    pub fn new(min: Duration, factor: u32, max: Duration) -> Self {
78        Self { min, factor, max }
79    }
80
81    /// The wait for the first frame after `Accepted`.
82    pub fn first(&self) -> Duration {
83        self.max.max(self.min)
84    }
85
86    /// The timeout given the recent gap between frames.
87    pub fn timeout(&self, recent_gap: Option<Duration>) -> Duration {
88        let scaled = recent_gap.map(|g| g * self.factor).unwrap_or_default();
89        scaled.max(self.min).min(self.max.max(self.min))
90    }
91}
92
93/// The recent gap between frames: a moving average.
94#[derive(Debug, Default)]
95struct Gaps {
96    last: Option<Instant>,
97    recent: Option<Duration>,
98}
99
100impl Gaps {
101    fn wait(&self, stall: &Stall) -> Duration {
102        if self.last.is_none() { stall.first() } else { stall.timeout(self.recent) }
103    }
104
105    fn tick(&mut self) {
106        let now = Instant::now();
107        if let Some(last) = self.last {
108            let gap = now - last;
109            self.recent = Some(match self.recent {
110                Some(r) => (r * 3 + gap) / 4,
111                None => gap,
112            });
113        }
114        self.last = Some(now);
115    }
116}
117
118/// How a [`Pool`] behaves.
119#[derive(Debug, Clone, PartialEq, Eq)]
120#[non_exhaustive]
121pub struct PoolOptions {
122    /// How long a node has to accept (reset by each `Queued`), and to open a channel.
123    pub accept_timeout: Duration,
124    pub stall: Stall,
125    /// Continue an interrupted answer on another node. On by default; `RemoteModel` turns it off.
126    pub resume: bool,
127    pub max_resumes: u32,
128    /// Try infer/1 on nodes that do not serve infer/2 (only before any text has streamed).
129    pub infer_v1_fallback: bool,
130    /// The certificate presented with every request (for Weirdnet a CBOR `NodeCert`).
131    pub cert: Option<Vec<u8>>,
132}
133
134impl Default for PoolOptions {
135    fn default() -> Self {
136        Self {
137            accept_timeout: DEFAULT_ACCEPT_TIMEOUT,
138            stall: Stall::default(),
139            resume: true,
140            max_resumes: DEFAULT_MAX_RESUMES,
141            infer_v1_fallback: true,
142            cert: None,
143        }
144    }
145}
146
147impl PoolOptions {
148    pub fn with_accept_timeout(mut self, timeout: Duration) -> Self {
149        self.accept_timeout = timeout;
150        self
151    }
152
153    pub fn with_stall(mut self, stall: Stall) -> Self {
154        self.stall = stall;
155        self
156    }
157
158    pub fn with_resume(mut self, resume: bool) -> Self {
159        self.resume = resume;
160        self
161    }
162
163    pub fn with_max_resumes(mut self, max: u32) -> Self {
164        self.max_resumes = max;
165        self
166    }
167
168    pub fn with_infer_v1_fallback(mut self, on: bool) -> Self {
169        self.infer_v1_fallback = on;
170        self
171    }
172
173    pub fn with_cert(mut self, cert: Option<Vec<u8>>) -> Self {
174        self.cert = cert;
175        self
176    }
177}
178
179/// Which inference nodes to try, best first (for example the local one, then the closest).
180#[async_trait]
181pub trait NodeSource: Send + Sync {
182    async fn nodes(&self) -> Vec<String>;
183}
184
185#[async_trait]
186impl NodeSource for Vec<String> {
187    async fn nodes(&self) -> Vec<String> {
188        self.clone()
189    }
190}
191
192/// What the pool reports while an answer streams.
193#[derive(Debug, Clone, PartialEq)]
194#[non_exhaustive]
195pub enum PoolEvent {
196    /// Waiting on `node` at this place.
197    Queued {
198        node: String,
199        position: u32,
200    },
201    Accepted {
202        node: String,
203        model: String,
204        resume: bool,
205    },
206    Text(String),
207    Reasoning(String),
208    ToolCall(ToolCall),
209    Usage(Usage),
210    /// The answer continues on `node` from `offset` characters.
211    Resumed {
212        node: String,
213        offset: u64,
214    },
215    /// Response metadata the node knew before the answer, such as a cache hit (0.4.1 servers
216    /// and later; the final [`Answer::meta`] has it too).
217    Meta(Meta),
218}
219
220/// Where a [`Pool`] streams [`PoolEvent`]s. A [`DeltaSink`] takes the text and reasoning.
221pub trait EventSink: Send + Sync {
222    fn event(&self, event: PoolEvent);
223}
224
225impl EventSink for DeltaSink {
226    fn event(&self, event: PoolEvent) {
227        match event {
228            PoolEvent::Text(t) => self.text(t),
229            PoolEvent::Reasoning(t) => self.reasoning(t),
230            _ => {}
231        }
232    }
233}
234
235impl EventSink for mpsc::UnboundedSender<PoolEvent> {
236    fn event(&self, event: PoolEvent) {
237        let _ = self.send(event);
238    }
239}
240
241/// An [`EventSink`] that drops everything.
242#[derive(Debug, Clone, Copy, Default)]
243pub struct NoEvents;
244
245impl EventSink for NoEvents {
246    fn event(&self, _: PoolEvent) {}
247}
248
249/// A whole answer.
250#[derive(Debug, Clone, PartialEq, Default)]
251#[non_exhaustive]
252pub struct Answer {
253    pub text: String,
254    pub reasoning: String,
255    pub tool_calls: Vec<ToolCall>,
256    pub finish_reason: Option<String>,
257    pub usage: Option<Usage>,
258    pub meta: Meta,
259    /// The inference node that finished it.
260    pub node: String,
261    /// The model it reported.
262    pub model: String,
263    /// The `assistant_prefix` the request asked to continue (empty if none). `text` and
264    /// `reasoning` start with it; [`Answer::continuation`] is the text after it.
265    pub prefix: Prefix,
266}
267
268impl Answer {
269    /// As a model turn (text and tool calls).
270    pub fn turn(&self) -> ModelTurn {
271        ModelTurn { text: self.text.clone(), tool_calls: self.tool_calls.clone() }
272    }
273
274    /// The text generated after [`Answer::prefix`] (all of it when there is none).
275    pub fn continuation(&self) -> &str {
276        let at = self.text.char_indices().nth(self.prefix.len as usize).map_or(self.text.len(), |(i, _)| i);
277        &self.text[at..]
278    }
279
280    /// Something was generated beyond the prefix.
281    fn has_output(&self) -> bool {
282        chars(&self.text) > self.prefix.len || chars(&self.reasoning) > self.prefix.reasoning_len || !self.tool_calls.is_empty()
283    }
284
285    /// The text and reasoning so far, as the prefix of a next attempt.
286    fn shown(&self) -> Option<Prefix> {
287        (!self.text.is_empty() || !self.reasoning.is_empty()).then(|| Prefix::new(self.text.clone(), self.reasoning.clone()))
288    }
289}
290
291/// An answer that could not be finished: why, what was shown, and every node tried.
292#[derive(Debug, Clone, PartialEq, thiserror::Error)]
293#[error("{error}")]
294#[non_exhaustive]
295pub struct Interrupted {
296    pub error: RemoteError,
297    /// What streamed before it stopped (empty if nothing did).
298    pub partial: Box<Answer>,
299    /// Each node tried and why it did not finish.
300    pub tried: Vec<(String, RemoteError)>,
301}
302
303impl Interrupted {
304    /// Some of the answer was shown.
305    pub fn streamed(&self) -> bool {
306        self.partial.has_output()
307    }
308}
309
310/// Embeddings for each input, in order.
311#[derive(Debug, Clone, PartialEq, Default)]
312#[non_exhaustive]
313pub struct Embeddings {
314    pub vectors: Vec<Vec<f32>>,
315    pub model: String,
316    pub node: String,
317    pub meta: Meta,
318    /// Prompt tokens, when the serving node reports them (0.4.1 servers and later).
319    pub usage: Option<Usage>,
320}
321
322/// A transcript and where it came from ([`Pool::transcribe`]).
323#[derive(Debug, Clone, PartialEq, Default)]
324#[non_exhaustive]
325pub struct Transcription {
326    pub transcript: Transcript,
327    /// The backend that served it, as its node named it in `Accepted`.
328    pub model: String,
329    pub node: String,
330    pub meta: Meta,
331    /// Token counts, when the serving node reports them.
332    pub usage: Option<Usage>,
333}
334
335enum Fail {
336    Cancelled,
337    /// The node does not serve the protocol.
338    Unsupported(RemoteError),
339    /// The node would not resume.
340    NoResume,
341    Error(RemoteError),
342}
343
344/// The error to report when every node failed, kind intact: the last node answer
345/// ([`RemoteError::is_node_answer`]), else the last error; `Unavailable(none)` with no nodes.
346pub(crate) fn reported<'a>(errors: impl DoubleEndedIterator<Item = &'a RemoteError> + Clone, none: &str) -> RemoteError {
347    let mut last = errors.clone().rev();
348    errors.rev().find(|e| e.is_node_answer()).or_else(|| last.next()).cloned().unwrap_or_else(|| RemoteError::unavailable(none))
349}
350
351/// Places `text` at `offset` in `buf`: `Ok(Some(new))` with the part that was not there yet,
352/// `Ok(None)` if it was all there, `Err` on a gap.
353fn splice(buf: &mut String, offset: u64, text: &str) -> Result<Option<String>, u64> {
354    let have = chars(buf);
355    if offset > have {
356        return Err(offset - have);
357    }
358    let skip = (have - offset) as usize;
359    let new: String = text.chars().skip(skip).collect();
360    if new.is_empty() {
361        return Ok(None);
362    }
363    buf.push_str(&new);
364    Ok(Some(new))
365}
366
367/// A pool of inference nodes. Cheap to clone.
368#[derive(Clone)]
369pub struct Pool {
370    dialer: Arc<dyn Dialer>,
371    nodes: Arc<dyn NodeSource>,
372    opts: PoolOptions,
373}
374
375impl Pool {
376    pub fn new(dialer: Arc<dyn Dialer>, nodes: impl NodeSource + 'static) -> Self {
377        Self { dialer, nodes: Arc::new(nodes), opts: PoolOptions::default() }
378    }
379
380    pub fn with_options(mut self, opts: PoolOptions) -> Self {
381        self.opts = opts;
382        self
383    }
384
385    pub fn options(&self) -> &PoolOptions {
386        &self.opts
387    }
388
389    pub(crate) fn dialer(&self) -> &Arc<dyn Dialer> {
390        &self.dialer
391    }
392
393    pub(crate) fn options_mut(&mut self) -> &mut PoolOptions {
394        &mut self.opts
395    }
396
397    /// The nodes it would try now, in order.
398    pub async fn nodes(&self) -> Vec<String> {
399        self.nodes.nodes().await
400    }
401
402    async fn open(&self, node: &str, protocol: &str, cancel: &CancelToken) -> Result<Channel, Fail> {
403        let open = tokio::select! {
404            r = tokio::time::timeout(self.opts.accept_timeout, self.dialer.open(node, protocol)) => r,
405            _ = cancel.cancelled() => return Err(Fail::Cancelled),
406        };
407        match open {
408            Ok(Ok(ch)) => Ok(ch),
409            Ok(Err(e @ RemoteError::Unsupported { .. })) => Err(Fail::Unsupported(e)),
410            Ok(Err(e)) => Err(Fail::Error(e)),
411            Err(_) => Err(Fail::Error(RemoteError::Timeout)),
412        }
413    }
414
415    /// Runs one answer to the end, failing over (and, with resume on, resuming) between nodes.
416    pub async fn infer(&self, mut request: Request, events: &dyn EventSink, cancel: &CancelToken) -> Result<Answer, Interrupted> {
417        if request.cert.is_none() {
418            request.cert.clone_from(&self.opts.cert);
419        }
420        let needed = request.needs();
421        if !needed.is_text() {
422            let refuse = |error| Err(Interrupted { error, partial: Box::default(), tried: Vec::new() });
423            if let Some(Err(message)) = request.inline_messages().unwrap_or_default().iter().map(|m| m.content.check()).find(Result::is_err) {
424                return refuse(RemoteError::BadRequest { message });
425            }
426            match self.catalog().await {
427                Ok(catalog) => match catalog.route(request.model.as_deref(), needed) {
428                    Ok(model) => request.model = model,
429                    Err(e) => return refuse(e),
430                },
431                Err(e) if e.is_request_error() => return refuse(e),
432                // No catalog to ask: the nodes decide.
433                Err(_) => {}
434            }
435        }
436        let mut answer = Answer::default();
437        // Continue: the answer starts from the caller's prefix, so the node's frames (which
438        // start at its length) line up, and failover keeps it.
439        if let Some(p) = request.assistant_prefix.clone().filter(|p| !p.is_empty() && p.is_consistent()) {
440            answer.text.clone_from(&p.text);
441            answer.reasoning.clone_from(&p.reasoning);
442            answer.prefix = p;
443        }
444        let mut tried: Vec<(String, RemoteError)> = Vec::new();
445        let mut resumes: Vec<Resume> = Vec::new();
446        let mut next = request;
447        let mut first = true;
448        let interrupted = |error, partial, tried| Interrupted { error, partial: Box::new(partial), tried };
449        for node in self.nodes.nodes().await {
450            if cancel.is_cancelled() {
451                return Err(interrupted(RemoteError::Cancelled, answer, tried));
452            }
453            let resuming = answer.has_output();
454            if !first {
455                next = next.next_attempt();
456                next.assistant_prefix = answer.shown();
457            }
458            first = false;
459            let pending = resuming.then(|| chars(&answer.text));
460            let outcome = match self.attempt(&node, &next, &mut answer, pending, &mut resumes, events, cancel).await {
461                Err(Fail::Unsupported(e)) if self.opts.infer_v1_fallback && next.assistant_prefix.is_none() && needed.is_text() => {
462                    match self.attempt_v1(&node, &next, &mut answer, events, cancel).await {
463                        Err(Fail::Unsupported(_)) => Err(Fail::Unsupported(e)),
464                        other => other,
465                    }
466                }
467                other => other,
468            };
469            match outcome {
470                Ok(finish) => {
471                    answer.finish_reason = finish.finish_reason;
472                    if finish.usage.is_some() {
473                        answer.usage = finish.usage;
474                    }
475                    answer.meta = finish.meta;
476                    answer.meta.resumes.extend(resumes);
477                    answer.node = node;
478                    return Ok(answer);
479                }
480                Err(Fail::Cancelled) => return Err(interrupted(RemoteError::Cancelled, answer, tried)),
481                Err(Fail::NoResume) => {
482                    tried.push((node, RemoteError::Unsupported { message: "the node cannot resume or continue an answer".into() }))
483                }
484                Err(Fail::Unsupported(e)) => tried.push((node, e)),
485                Err(Fail::Error(e)) if e.is_request_error() => {
486                    tried.push((node, e.clone()));
487                    return Err(interrupted(e, answer, tried));
488                }
489                Err(Fail::Error(e)) => {
490                    tried.push((node, e.clone()));
491                    if answer.has_output() && (!self.opts.resume || resumes.len() as u32 >= self.opts.max_resumes) {
492                        return Err(interrupted(e, answer, tried));
493                    }
494                }
495            }
496        }
497        let error = reported(tried.iter().map(|(_, e)| e), "no inference node to run on");
498        Err(interrupted(error, answer, tried))
499    }
500
501    #[allow(clippy::too_many_arguments)]
502    async fn attempt(
503        &self,
504        node: &str,
505        request: &Request,
506        answer: &mut Answer,
507        resume_from: Option<u64>,
508        resumes: &mut Vec<Resume>,
509        events: &dyn EventSink,
510        cancel: &CancelToken,
511    ) -> Result<Finish, Fail> {
512        let mut ch = self.open(node, v2::PROTOCOL, cancel).await?;
513        let id = request.id.clone();
514        let mut sent = request.clone();
515        sent.early_meta = true;
516        ch.send_cbor(&ClientFrame::Infer(sent)).await.map_err(Fail::Error)?;
517        let wants_resume = request.assistant_prefix.as_ref().is_some_and(|p| !p.is_empty());
518        let mut accepted = false;
519        let mut gaps = Gaps::default();
520        let calls_before = answer.tool_calls.len();
521        loop {
522            let wait = if accepted { gaps.wait(&self.opts.stall) } else { self.opts.accept_timeout };
523            let next = tokio::select! {
524                _ = cancel.cancelled() => {
525                    let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
526                    return Err(Fail::Cancelled);
527                }
528                r = tokio::time::timeout(wait, ch.recv_cbor::<ServerFrame>()) => r,
529            };
530            let frame = match next {
531                Err(_) => {
532                    let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
533                    let e = if accepted { RemoteError::Stalled { ms: wait.as_millis() as u64 } } else { RemoteError::Timeout };
534                    return Err(Fail::Error(e));
535                }
536                Ok(Err(e)) => return Err(Fail::Error(e)),
537                Ok(Ok(None)) => return Err(Fail::Error(RemoteError::Closed)),
538                Ok(Ok(Some(f))) => f,
539            };
540            if frame.id() != id {
541                continue;
542            }
543            match frame {
544                ServerFrame::Queued { position, .. } if !accepted => events.event(PoolEvent::Queued { node: node.into(), position }),
545                ServerFrame::Accepted { model, resume, .. } if !accepted => {
546                    if wants_resume && !resume {
547                        let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
548                        return Err(Fail::NoResume);
549                    }
550                    accepted = true;
551                    answer.model.clone_from(&model);
552                    events.event(PoolEvent::Accepted { node: node.into(), model, resume });
553                    if let Some(offset) = resume_from {
554                        resumes.push(Resume::new(offset, node));
555                        events.event(PoolEvent::Resumed { node: node.into(), offset });
556                    }
557                }
558                ServerFrame::Delta { offset, text, .. } if accepted => match splice(&mut answer.text, offset, &text) {
559                    Ok(Some(new)) => {
560                        gaps.tick();
561                        events.event(PoolEvent::Text(new));
562                    }
563                    Ok(None) => gaps.tick(),
564                    Err(gap) => {
565                        let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
566                        return Err(Fail::Error(RemoteError::protocol(format!("{gap} characters of the answer are missing"))));
567                    }
568                },
569                ServerFrame::Reasoning { offset, text, .. } if accepted => match splice(&mut answer.reasoning, offset, &text) {
570                    Ok(Some(new)) => {
571                        gaps.tick();
572                        events.event(PoolEvent::Reasoning(new));
573                    }
574                    Ok(None) => gaps.tick(),
575                    Err(gap) => {
576                        let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
577                        return Err(Fail::Error(RemoteError::protocol(format!("{gap} characters of the reasoning are missing"))));
578                    }
579                },
580                ServerFrame::ToolCall { index, call, .. } if accepted => {
581                    gaps.tick();
582                    // Calls are whole; after a resume one already held may come again.
583                    let slot = calls_before + index as usize;
584                    let seen = answer.tool_calls.iter().any(|c| c.name == call.name && c.arguments == call.arguments);
585                    if slot >= answer.tool_calls.len() && !seen {
586                        answer.tool_calls.push(call.clone());
587                        events.event(PoolEvent::ToolCall(call));
588                    }
589                }
590                ServerFrame::Usage { usage, .. } if accepted => {
591                    gaps.tick();
592                    answer.usage = Some(usage);
593                    events.event(PoolEvent::Usage(usage));
594                }
595                ServerFrame::Meta { meta, .. } if accepted => {
596                    gaps.tick();
597                    events.event(PoolEvent::Meta(meta));
598                }
599                ServerFrame::Done { finish, .. } if accepted => return Ok(finish),
600                ServerFrame::Failed { error, .. } => {
601                    return Err(match error {
602                        e @ RemoteError::Unsupported { .. } if !accepted => Fail::Unsupported(e),
603                        e => Fail::Error(e),
604                    });
605                }
606                ServerFrame::Cancelled { .. } => return Err(Fail::Error(RemoteError::Failed { message: "cancelled by the node".into() })),
607                other => return Err(Fail::Error(RemoteError::protocol(format!("unexpected frame {other:?}")))),
608            }
609        }
610    }
611
612    /// One try on an infer/1 node (0.3 and older): inline messages and tools only, no resume.
613    async fn attempt_v1(
614        &self,
615        node: &str,
616        request: &Request,
617        answer: &mut Answer,
618        events: &dyn EventSink,
619        cancel: &CancelToken,
620    ) -> Result<Finish, Fail> {
621        let Some(messages) = request.inline_messages() else {
622            return Err(Fail::Unsupported(RemoteError::Unsupported { message: "infer/1 takes inline messages only".into() }));
623        };
624        let mut ch = self.open(node, v1::PROTOCOL, cancel).await?;
625        let id = request_id();
626        let req = v1::InferRequest { id: id.clone(), model: request.model.clone(), messages: messages.to_vec(), tools: request.tools.clone() };
627        ch.send(&v1::ClientMsg::Infer { request: req }).await.map_err(Fail::Error)?;
628        let mut accepted = false;
629        loop {
630            let next = tokio::select! {
631                _ = cancel.cancelled() => {
632                    let _ = ch.send(&v1::ClientMsg::Cancel { id }).await;
633                    return Err(Fail::Cancelled);
634                }
635                m = async {
636                    if accepted {
637                        Ok(ch.recv::<v1::ServerMsg>().await)
638                    } else {
639                        tokio::time::timeout(self.opts.accept_timeout, ch.recv::<v1::ServerMsg>()).await
640                    }
641                } => m,
642            };
643            let msg = match next {
644                Err(_) => return Err(Fail::Error(RemoteError::Timeout)),
645                Ok(Err(e)) => return Err(Fail::Error(e)),
646                Ok(Ok(None)) => return Err(Fail::Error(RemoteError::Closed)),
647                Ok(Ok(Some(m))) => m,
648            };
649            match msg {
650                v1::ServerMsg::Accepted { id: rid, model } if rid == id => {
651                    accepted = true;
652                    answer.model.clone_from(&model);
653                    events.event(PoolEvent::Accepted { node: node.into(), model, resume: false });
654                }
655                v1::ServerMsg::Delta { id: rid, text } if rid == id && accepted => {
656                    answer.text.push_str(&text);
657                    events.event(PoolEvent::Text(text));
658                }
659                v1::ServerMsg::Done { id: rid, turn } if rid == id && accepted => {
660                    answer.text = turn.text;
661                    let calls = !turn.tool_calls.is_empty();
662                    for call in turn.tool_calls {
663                        answer.tool_calls.push(call.clone());
664                        events.event(PoolEvent::ToolCall(call));
665                    }
666                    let mut finish = Finish::new(if calls { "tool_calls" } else { "stop" });
667                    finish.meta.served_by = Some(node.to_string());
668                    return Ok(finish);
669                }
670                v1::ServerMsg::Failed { id: rid, error } if rid == id => return Err(Fail::Error(error)),
671                v1::ServerMsg::Cancelled { id: rid } if rid == id => {
672                    return Err(Fail::Error(RemoteError::Failed { message: "cancelled by the node".into() }));
673                }
674                other => return Err(Fail::Error(RemoteError::protocol(format!("unexpected message {other:?}")))),
675            }
676        }
677    }
678
679    /// Embeddings for every input, from the first node that serves them all (infer/2 only).
680    pub async fn embed(&self, mut request: EmbedRequest, cancel: &CancelToken) -> Result<Embeddings, RemoteError> {
681        if request.cert.is_none() {
682            request.cert.clone_from(&self.opts.cert);
683        }
684        let mut tried = Vec::new();
685        for node in self.nodes.nodes().await {
686            match self.embed_on(&node, &request, cancel).await {
687                Ok(e) => return Ok(e),
688                Err(Fail::Cancelled) => return Err(RemoteError::Cancelled),
689                Err(Fail::Error(e) | Fail::Unsupported(e)) if e.is_request_error() => return Err(e),
690                Err(Fail::Error(e) | Fail::Unsupported(e)) => tried.push(e),
691                Err(Fail::NoResume) => {}
692            }
693            request.id = request_id();
694        }
695        Err(reported(tried.iter(), "no inference node to run on"))
696    }
697
698    async fn embed_on(&self, node: &str, request: &EmbedRequest, cancel: &CancelToken) -> Result<Embeddings, Fail> {
699        let mut ch = self.open(node, v2::PROTOCOL, cancel).await?;
700        let id = request.id.clone();
701        ch.send_cbor(&ClientFrame::Embed(request.clone())).await.map_err(Fail::Error)?;
702        let mut out = Embeddings { node: node.to_string(), ..Default::default() };
703        let mut got: BTreeMap<u32, Vec<f32>> = BTreeMap::new();
704        let mut accepted = false;
705        let mut gaps = Gaps::default();
706        loop {
707            let wait = if accepted { gaps.wait(&self.opts.stall) } else { self.opts.accept_timeout };
708            let next = tokio::select! {
709                _ = cancel.cancelled() => {
710                    let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
711                    return Err(Fail::Cancelled);
712                }
713                r = tokio::time::timeout(wait, ch.recv_cbor::<ServerFrame>()) => r,
714            };
715            let frame = match next {
716                Err(_) => {
717                    let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
718                    return Err(Fail::Error(if accepted { RemoteError::Stalled { ms: wait.as_millis() as u64 } } else { RemoteError::Timeout }));
719                }
720                Ok(Err(e)) => return Err(Fail::Error(e)),
721                Ok(Ok(None)) => return Err(Fail::Error(RemoteError::Closed)),
722                Ok(Ok(Some(f))) => f,
723            };
724            if frame.id() != id {
725                continue;
726            }
727            match frame {
728                ServerFrame::Queued { .. } if !accepted => {}
729                ServerFrame::Accepted { model, .. } if !accepted => {
730                    accepted = true;
731                    out.model = model;
732                }
733                ServerFrame::Embedding { index, vector, .. } if accepted => {
734                    gaps.tick();
735                    got.insert(index, v2::bytes_f32(&vector).map_err(Fail::Error)?);
736                }
737                ServerFrame::Done { finish, .. } if accepted => {
738                    if got.len() != request.inputs.len() || got.keys().enumerate().any(|(i, k)| *k as usize != i) {
739                        return Err(Fail::Error(RemoteError::protocol(format!("{} of {} embeddings arrived", got.len(), request.inputs.len()))));
740                    }
741                    out.vectors = got.into_values().collect();
742                    out.meta = finish.meta;
743                    out.usage = finish.usage;
744                    return Ok(out);
745                }
746                ServerFrame::Failed { error, .. } => return Err(Fail::Error(error)),
747                ServerFrame::Cancelled { .. } => return Err(Fail::Error(RemoteError::Failed { message: "cancelled by the node".into() })),
748                other => return Err(Fail::Error(RemoteError::protocol(format!("unexpected frame {other:?}")))),
749            }
750        }
751    }
752
753    /// The transcript of one audio clip, from the first node that serves it (infer/2, nodes from
754    /// 0.5.8). Node errors fail over to the next node; a `BadRequest` (no audio, or a named model
755    /// that does not transcribe) comes back at once. A node too old to read the request closes
756    /// the stream, which counts as `Unsupported`. With no model named, each node picks its own
757    /// transcriber; to pick one across the pool first, see
758    /// [`Catalog::route_transcribe`](super::catalog::Catalog::route_transcribe).
759    pub async fn transcribe(&self, mut request: TranscribeRequest, cancel: &CancelToken) -> Result<Transcription, RemoteError> {
760        request.check()?;
761        if request.cert.is_none() {
762            request.cert.clone_from(&self.opts.cert);
763        }
764        let mut tried = Vec::new();
765        for node in self.nodes.nodes().await {
766            match self.transcribe_on(&node, &request, cancel).await {
767                Ok(t) => return Ok(t),
768                Err(Fail::Cancelled) => return Err(RemoteError::Cancelled),
769                Err(Fail::Error(e) | Fail::Unsupported(e)) if e.is_request_error() => return Err(e),
770                Err(Fail::Error(e) | Fail::Unsupported(e)) => tried.push(e),
771                Err(Fail::NoResume) => {}
772            }
773            request.id = request_id();
774        }
775        Err(reported(tried.iter(), "no inference node to run on"))
776    }
777
778    async fn transcribe_on(&self, node: &str, request: &TranscribeRequest, cancel: &CancelToken) -> Result<Transcription, Fail> {
779        let mut ch = self.open(node, v2::PROTOCOL, cancel).await?;
780        let id = request.id.clone();
781        ch.send_cbor(&ClientFrame::Transcribe(request.clone())).await.map_err(Fail::Error)?;
782        let mut out = Transcription { node: node.to_string(), ..Default::default() };
783        let mut transcript = None;
784        let mut accepted = false;
785        loop {
786            // Between `Accepted` and the transcript only `Working` keepalives arrive (every
787            // `QUEUE_KEEPALIVE`), so the wait after acceptance is the stall cap.
788            let wait = if accepted { self.opts.stall.max } else { self.opts.accept_timeout };
789            let next = tokio::select! {
790                _ = cancel.cancelled() => {
791                    let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
792                    return Err(Fail::Cancelled);
793                }
794                r = tokio::time::timeout(wait, ch.recv_cbor::<ServerFrame>()) => r,
795            };
796            let frame = match next {
797                Err(_) => {
798                    let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
799                    return Err(Fail::Error(if accepted { RemoteError::Stalled { ms: wait.as_millis() as u64 } } else { RemoteError::Timeout }));
800                }
801                Ok(Err(e)) => return Err(Fail::Error(e)),
802                // A node before 0.5.8 can't read the request and closes the stream unanswered.
803                Ok(Ok(None)) if !accepted => {
804                    return Err(Fail::Unsupported(RemoteError::Unsupported {
805                        message: format!("node {node} closed the stream without answering; it may predate transcription (weirdnet-agent 0.5.8)"),
806                    }));
807                }
808                Ok(Ok(None)) => return Err(Fail::Error(RemoteError::Closed)),
809                Ok(Ok(Some(f))) => f,
810            };
811            if frame.id() != id {
812                continue;
813            }
814            match frame {
815                ServerFrame::Queued { .. } if !accepted => {}
816                ServerFrame::Accepted { model, .. } if !accepted => {
817                    accepted = true;
818                    out.model = model;
819                }
820                ServerFrame::Working { .. } if accepted => {}
821                ServerFrame::Transcript { transcript: t, .. } if accepted && transcript.is_none() => transcript = Some(t),
822                ServerFrame::Done { finish, .. } if accepted => {
823                    let Some(t) = transcript else {
824                        return Err(Fail::Error(RemoteError::protocol("transcription finished without a transcript")));
825                    };
826                    out.transcript = t;
827                    out.meta = finish.meta;
828                    out.usage = finish.usage;
829                    return Ok(out);
830                }
831                ServerFrame::Failed { error, .. } => return Err(Fail::Error(error)),
832                ServerFrame::Cancelled { .. } => return Err(Fail::Error(RemoteError::Failed { message: "cancelled by the node".into() })),
833                other => return Err(Fail::Error(RemoteError::protocol(format!("unexpected frame {other:?}")))),
834            }
835        }
836    }
837
838    /// The catalog of the first node that answers.
839    pub async fn catalog(&self) -> Result<Catalog, RemoteError> {
840        let mut tried = Vec::new();
841        for node in self.nodes.nodes().await {
842            let r = tokio::time::timeout(self.opts.accept_timeout, async {
843                let mut ch = self.dialer.open(&node, catalog::PROTOCOL).await?;
844                catalog::query(&mut ch, self.opts.cert.clone()).await
845            })
846            .await
847            .unwrap_or(Err(RemoteError::Timeout));
848            match r {
849                Ok(c) => return Ok(c),
850                Err(e) if e.is_request_error() => return Err(e),
851                Err(e) => tried.push(e),
852            }
853        }
854        Err(reported(tried.iter(), "no inference node to ask"))
855    }
856
857    /// Follows the catalog: the first node that answers streams its changes; when it goes away
858    /// the next one takes over. Stops when the [`CatalogWatch`] is dropped.
859    pub fn subscribe(&self) -> CatalogWatch {
860        let (tx, rx) = watch::channel(None);
861        let pool = self.clone();
862        let task = tokio::spawn(async move {
863            let mut backoff = Duration::from_millis(200);
864            loop {
865                for node in pool.nodes.nodes().await {
866                    let opened = tokio::time::timeout(pool.opts.accept_timeout, pool.dialer.open(&node, catalog::PROTOCOL)).await;
867                    let Ok(Ok(mut ch)) = opened else { continue };
868                    let sent = catalog::subscribe(&mut ch, pool.opts.cert.clone(), |c| {
869                        tx.send_replace(Some((node.clone(), c)));
870                    });
871                    tokio::select! {
872                        r = sent => if r.is_ok() { backoff = Duration::from_millis(200) },
873                        _ = tx.closed() => return,
874                    }
875                }
876                tokio::select! {
877                    _ = tokio::time::sleep(backoff) => {}
878                    _ = tx.closed() => return,
879                }
880                backoff = (backoff * 2).min(Duration::from_secs(30));
881            }
882        });
883        CatalogWatch { rx, task }
884    }
885
886    /// Runs a job in the background: the same failover and resume as [`Pool::infer`], with its
887    /// events on [`Job::events`]. Batch work usually sets `Priority::Batch`.
888    pub fn submit(&self, request: Request) -> Job {
889        let (tx, events) = mpsc::unbounded_channel();
890        let cancel = CancelToken::new();
891        let job_id = request.job_id.clone();
892        let pool = self.clone();
893        let c = cancel.clone();
894        let handle = tokio::spawn(async move { pool.infer(request, &tx, &c).await });
895        Job { job_id, cancel, handle, events }
896    }
897}
898
899/// A followed catalog ([`Pool::subscribe`]).
900pub struct CatalogWatch {
901    rx: watch::Receiver<Option<(String, Catalog)>>,
902    task: JoinHandle<()>,
903}
904
905impl CatalogWatch {
906    /// The latest catalog and the node it came from, if one has arrived.
907    pub fn current(&self) -> Option<(String, Catalog)> {
908        self.rx.borrow().clone()
909    }
910
911    /// Waits for the next catalog.
912    pub async fn changed(&mut self) -> Option<(String, Catalog)> {
913        self.rx.changed().await.ok()?;
914        self.rx.borrow_and_update().clone()
915    }
916}
917
918impl Drop for CatalogWatch {
919    fn drop(&mut self) {
920        self.task.abort();
921    }
922}
923
924/// A job running in the background ([`Pool::submit`]).
925pub struct Job {
926    job_id: String,
927    cancel: CancelToken,
928    handle: JoinHandle<Result<Answer, Interrupted>>,
929    events: mpsc::UnboundedReceiver<PoolEvent>,
930}
931
932impl Job {
933    pub fn job_id(&self) -> &str {
934        &self.job_id
935    }
936
937    pub fn cancel(&self) {
938        self.cancel.cancel();
939    }
940
941    /// The job's events as they happen.
942    pub fn events(&mut self) -> &mut mpsc::UnboundedReceiver<PoolEvent> {
943        &mut self.events
944    }
945
946    /// Waits for the job to end.
947    pub async fn wait(self) -> Result<Answer, Interrupted> {
948        match self.handle.await {
949            Ok(r) => r,
950            Err(e) => Err(Interrupted { error: RemoteError::Failed { message: e.to_string() }, partial: Box::default(), tried: Vec::new() }),
951        }
952    }
953}
954
955#[cfg(test)]
956mod tests {
957    use super::*;
958
959    #[test]
960    fn splice_places_by_offset() {
961        let mut b = String::new();
962        assert_eq!(splice(&mut b, 0, "Hel"), Ok(Some("Hel".into())));
963        assert_eq!(splice(&mut b, 3, "lo"), Ok(Some("lo".into())));
964        assert_eq!(splice(&mut b, 0, "Hell"), Ok(None));
965        assert_eq!(splice(&mut b, 4, "o wö"), Ok(Some(" wö".into())));
966        assert_eq!(b, "Hello wö");
967        assert_eq!(splice(&mut b, 10, "x"), Err(2));
968    }
969
970    #[test]
971    fn the_stall_timeout_follows_the_token_gap_within_bounds() {
972        let s = Stall::default();
973        assert_eq!(s.timeout(None), Duration::from_secs(15));
974        assert_eq!(s.timeout(Some(Duration::from_secs(1))), Duration::from_secs(15));
975        assert_eq!(s.timeout(Some(Duration::from_secs(7))), Duration::from_secs(21));
976        assert_eq!(s.timeout(Some(Duration::from_secs(20))), Duration::from_secs(25), "stays under net's 30 s resume window");
977    }
978}