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