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