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}
202
203/// Where a [`Pool`] streams [`PoolEvent`]s. A [`DeltaSink`] takes the text and reasoning.
204pub trait EventSink: Send + Sync {
205    fn event(&self, event: PoolEvent);
206}
207
208impl EventSink for DeltaSink {
209    fn event(&self, event: PoolEvent) {
210        match event {
211            PoolEvent::Text(t) => self.text(t),
212            PoolEvent::Reasoning(t) => self.reasoning(t),
213            _ => {}
214        }
215    }
216}
217
218impl EventSink for mpsc::UnboundedSender<PoolEvent> {
219    fn event(&self, event: PoolEvent) {
220        let _ = self.send(event);
221    }
222}
223
224/// An [`EventSink`] that drops everything.
225#[derive(Debug, Clone, Copy, Default)]
226pub struct NoEvents;
227
228impl EventSink for NoEvents {
229    fn event(&self, _: PoolEvent) {}
230}
231
232/// A whole answer.
233#[derive(Debug, Clone, PartialEq, Default)]
234#[non_exhaustive]
235pub struct Answer {
236    pub text: String,
237    pub reasoning: String,
238    pub tool_calls: Vec<ToolCall>,
239    pub finish_reason: Option<String>,
240    pub usage: Option<Usage>,
241    pub meta: Meta,
242    /// The inference node that finished it.
243    pub node: String,
244    /// The model it reported.
245    pub model: String,
246}
247
248impl Answer {
249    /// As a model turn (text and tool calls).
250    pub fn turn(&self) -> ModelTurn {
251        ModelTurn { text: self.text.clone(), tool_calls: self.tool_calls.clone() }
252    }
253
254    fn has_output(&self) -> bool {
255        !self.text.is_empty() || !self.reasoning.is_empty() || !self.tool_calls.is_empty()
256    }
257}
258
259/// An answer that could not be finished: why, what was shown, and every node tried.
260#[derive(Debug, Clone, PartialEq, thiserror::Error)]
261#[error("{error}")]
262#[non_exhaustive]
263pub struct Interrupted {
264    pub error: RemoteError,
265    /// What streamed before it stopped (empty if nothing did).
266    pub partial: Box<Answer>,
267    /// Each node tried and why it did not finish.
268    pub tried: Vec<(String, RemoteError)>,
269}
270
271impl Interrupted {
272    /// Some of the answer was shown.
273    pub fn streamed(&self) -> bool {
274        self.partial.has_output()
275    }
276}
277
278/// Embeddings for each input, in order.
279#[derive(Debug, Clone, PartialEq, Default)]
280#[non_exhaustive]
281pub struct Embeddings {
282    pub vectors: Vec<Vec<f32>>,
283    pub model: String,
284    pub node: String,
285    pub meta: Meta,
286}
287
288enum Fail {
289    Cancelled,
290    /// The node does not serve the protocol.
291    Unsupported(RemoteError),
292    /// The node would not resume.
293    NoResume,
294    Error(RemoteError),
295}
296
297/// Places `text` at `offset` in `buf`: `Ok(Some(new))` with the part that was not there yet,
298/// `Ok(None)` if it was all there, `Err` on a gap.
299fn splice(buf: &mut String, offset: u64, text: &str) -> Result<Option<String>, u64> {
300    let have = chars(buf);
301    if offset > have {
302        return Err(offset - have);
303    }
304    let skip = (have - offset) as usize;
305    let new: String = text.chars().skip(skip).collect();
306    if new.is_empty() {
307        return Ok(None);
308    }
309    buf.push_str(&new);
310    Ok(Some(new))
311}
312
313/// A pool of inference nodes. Cheap to clone.
314#[derive(Clone)]
315pub struct Pool {
316    dialer: Arc<dyn Dialer>,
317    nodes: Arc<dyn NodeSource>,
318    opts: PoolOptions,
319}
320
321impl Pool {
322    pub fn new(dialer: Arc<dyn Dialer>, nodes: impl NodeSource + 'static) -> Self {
323        Self { dialer, nodes: Arc::new(nodes), opts: PoolOptions::default() }
324    }
325
326    pub fn with_options(mut self, opts: PoolOptions) -> Self {
327        self.opts = opts;
328        self
329    }
330
331    pub fn options(&self) -> &PoolOptions {
332        &self.opts
333    }
334
335    pub(crate) fn options_mut(&mut self) -> &mut PoolOptions {
336        &mut self.opts
337    }
338
339    /// The nodes it would try now, in order.
340    pub async fn nodes(&self) -> Vec<String> {
341        self.nodes.nodes().await
342    }
343
344    async fn open(&self, node: &str, protocol: &str, cancel: &CancelToken) -> Result<Channel, Fail> {
345        let open = tokio::select! {
346            r = tokio::time::timeout(self.opts.accept_timeout, self.dialer.open(node, protocol)) => r,
347            _ = cancel.cancelled() => return Err(Fail::Cancelled),
348        };
349        match open {
350            Ok(Ok(ch)) => Ok(ch),
351            Ok(Err(e @ RemoteError::Unsupported { .. })) => Err(Fail::Unsupported(e)),
352            Ok(Err(e)) => Err(Fail::Error(e)),
353            Err(_) => Err(Fail::Error(RemoteError::Timeout)),
354        }
355    }
356
357    /// Runs one answer to the end, failing over (and, with resume on, resuming) between nodes.
358    pub async fn infer(&self, mut request: Request, events: &dyn EventSink, cancel: &CancelToken) -> Result<Answer, Interrupted> {
359        if request.cert.is_none() {
360            request.cert.clone_from(&self.opts.cert);
361        }
362        let mut answer = Answer::default();
363        let mut tried: Vec<(String, RemoteError)> = Vec::new();
364        let mut resumes: Vec<Resume> = Vec::new();
365        let mut next = request;
366        let mut first = true;
367        let interrupted = |error, partial, tried| Interrupted { error, partial: Box::new(partial), tried };
368        for node in self.nodes.nodes().await {
369            if cancel.is_cancelled() {
370                return Err(interrupted(RemoteError::Cancelled, answer, tried));
371            }
372            let resuming = answer.has_output();
373            if !first {
374                next = next.next_attempt();
375                next.assistant_prefix = resuming.then(|| Prefix::new(answer.text.clone(), answer.reasoning.clone()));
376            }
377            first = false;
378            let pending = resuming.then(|| chars(&answer.text));
379            let outcome = match self.attempt(&node, &next, &mut answer, pending, &mut resumes, events, cancel).await {
380                Err(Fail::Unsupported(e)) if self.opts.infer_v1_fallback && !resuming => {
381                    match self.attempt_v1(&node, &next, &mut answer, events, cancel).await {
382                        Err(Fail::Unsupported(_)) => Err(Fail::Unsupported(e)),
383                        other => other,
384                    }
385                }
386                other => other,
387            };
388            match outcome {
389                Ok(finish) => {
390                    answer.finish_reason = finish.finish_reason;
391                    if finish.usage.is_some() {
392                        answer.usage = finish.usage;
393                    }
394                    answer.meta = finish.meta;
395                    answer.meta.resumes.extend(resumes);
396                    answer.node = node;
397                    return Ok(answer);
398                }
399                Err(Fail::Cancelled) => return Err(interrupted(RemoteError::Cancelled, answer, tried)),
400                Err(Fail::NoResume) => tried.push((node, RemoteError::Unsupported { message: "the node cannot resume an answer".into() })),
401                Err(Fail::Unsupported(e)) => tried.push((node, e)),
402                Err(Fail::Error(e)) => {
403                    tried.push((node, e.clone()));
404                    if answer.has_output() && (!self.opts.resume || resumes.len() as u32 >= self.opts.max_resumes) {
405                        return Err(interrupted(e, answer, tried));
406                    }
407                }
408            }
409        }
410        let error = match tried.last() {
411            None => RemoteError::unavailable("no inference node to run on"),
412            Some((_, e)) => e.clone(),
413        };
414        Err(interrupted(error, answer, tried))
415    }
416
417    #[allow(clippy::too_many_arguments)]
418    async fn attempt(
419        &self,
420        node: &str,
421        request: &Request,
422        answer: &mut Answer,
423        resume_from: Option<u64>,
424        resumes: &mut Vec<Resume>,
425        events: &dyn EventSink,
426        cancel: &CancelToken,
427    ) -> Result<Finish, Fail> {
428        let mut ch = self.open(node, v2::PROTOCOL, cancel).await?;
429        let id = request.id.clone();
430        ch.send_cbor(&ClientFrame::Infer(request.clone())).await.map_err(Fail::Error)?;
431        let wants_resume = request.assistant_prefix.as_ref().is_some_and(|p| !p.is_empty());
432        let mut accepted = false;
433        let mut gaps = Gaps::default();
434        let calls_before = answer.tool_calls.len();
435        loop {
436            let wait = if accepted { gaps.wait(&self.opts.stall) } else { self.opts.accept_timeout };
437            let next = tokio::select! {
438                _ = cancel.cancelled() => {
439                    let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
440                    return Err(Fail::Cancelled);
441                }
442                r = tokio::time::timeout(wait, ch.recv_cbor::<ServerFrame>()) => r,
443            };
444            let frame = match next {
445                Err(_) => {
446                    let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
447                    let e = if accepted { RemoteError::Stalled { ms: wait.as_millis() as u64 } } else { RemoteError::Timeout };
448                    return Err(Fail::Error(e));
449                }
450                Ok(Err(e)) => return Err(Fail::Error(e)),
451                Ok(Ok(None)) => return Err(Fail::Error(RemoteError::Closed)),
452                Ok(Ok(Some(f))) => f,
453            };
454            if frame.id() != id {
455                continue;
456            }
457            match frame {
458                ServerFrame::Queued { position, .. } if !accepted => events.event(PoolEvent::Queued { node: node.into(), position }),
459                ServerFrame::Accepted { model, resume, .. } if !accepted => {
460                    if wants_resume && !resume {
461                        let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
462                        return Err(Fail::NoResume);
463                    }
464                    accepted = true;
465                    answer.model.clone_from(&model);
466                    events.event(PoolEvent::Accepted { node: node.into(), model, resume });
467                    if let Some(offset) = resume_from {
468                        resumes.push(Resume::new(offset, node));
469                        events.event(PoolEvent::Resumed { node: node.into(), offset });
470                    }
471                }
472                ServerFrame::Delta { offset, text, .. } if accepted => match splice(&mut answer.text, offset, &text) {
473                    Ok(Some(new)) => {
474                        gaps.tick();
475                        events.event(PoolEvent::Text(new));
476                    }
477                    Ok(None) => gaps.tick(),
478                    Err(gap) => {
479                        let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
480                        return Err(Fail::Error(RemoteError::protocol(format!("{gap} characters of the answer are missing"))));
481                    }
482                },
483                ServerFrame::Reasoning { offset, text, .. } if accepted => match splice(&mut answer.reasoning, offset, &text) {
484                    Ok(Some(new)) => {
485                        gaps.tick();
486                        events.event(PoolEvent::Reasoning(new));
487                    }
488                    Ok(None) => gaps.tick(),
489                    Err(gap) => {
490                        let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
491                        return Err(Fail::Error(RemoteError::protocol(format!("{gap} characters of the reasoning are missing"))));
492                    }
493                },
494                ServerFrame::ToolCall { index, call, .. } if accepted => {
495                    gaps.tick();
496                    // Calls are whole; after a resume one already held may come again.
497                    let slot = calls_before + index as usize;
498                    let seen = answer.tool_calls.iter().any(|c| c.name == call.name && c.arguments == call.arguments);
499                    if slot >= answer.tool_calls.len() && !seen {
500                        answer.tool_calls.push(call.clone());
501                        events.event(PoolEvent::ToolCall(call));
502                    }
503                }
504                ServerFrame::Usage { usage, .. } if accepted => {
505                    gaps.tick();
506                    answer.usage = Some(usage);
507                    events.event(PoolEvent::Usage(usage));
508                }
509                ServerFrame::Done { finish, .. } if accepted => return Ok(finish),
510                ServerFrame::Failed { error, .. } => {
511                    return Err(match error {
512                        e @ RemoteError::Unsupported { .. } if !accepted => Fail::Unsupported(e),
513                        e => Fail::Error(e),
514                    });
515                }
516                ServerFrame::Cancelled { .. } => return Err(Fail::Error(RemoteError::Failed { message: "cancelled by the node".into() })),
517                other => return Err(Fail::Error(RemoteError::protocol(format!("unexpected frame {other:?}")))),
518            }
519        }
520    }
521
522    /// One try on an infer/1 node (0.3 and older): inline messages and tools only, no resume.
523    async fn attempt_v1(
524        &self,
525        node: &str,
526        request: &Request,
527        answer: &mut Answer,
528        events: &dyn EventSink,
529        cancel: &CancelToken,
530    ) -> Result<Finish, Fail> {
531        let Some(messages) = request.inline_messages() else {
532            return Err(Fail::Unsupported(RemoteError::Unsupported { message: "infer/1 takes inline messages only".into() }));
533        };
534        let mut ch = self.open(node, v1::PROTOCOL, cancel).await?;
535        let id = request_id();
536        let req = v1::InferRequest { id: id.clone(), model: request.model.clone(), messages: messages.to_vec(), tools: request.tools.clone() };
537        ch.send(&v1::ClientMsg::Infer { request: req }).await.map_err(Fail::Error)?;
538        let mut accepted = false;
539        loop {
540            let next = tokio::select! {
541                _ = cancel.cancelled() => {
542                    let _ = ch.send(&v1::ClientMsg::Cancel { id }).await;
543                    return Err(Fail::Cancelled);
544                }
545                m = async {
546                    if accepted {
547                        Ok(ch.recv::<v1::ServerMsg>().await)
548                    } else {
549                        tokio::time::timeout(self.opts.accept_timeout, ch.recv::<v1::ServerMsg>()).await
550                    }
551                } => m,
552            };
553            let msg = match next {
554                Err(_) => return Err(Fail::Error(RemoteError::Timeout)),
555                Ok(Err(e)) => return Err(Fail::Error(e)),
556                Ok(Ok(None)) => return Err(Fail::Error(RemoteError::Closed)),
557                Ok(Ok(Some(m))) => m,
558            };
559            match msg {
560                v1::ServerMsg::Accepted { id: rid, model } if rid == id => {
561                    accepted = true;
562                    answer.model.clone_from(&model);
563                    events.event(PoolEvent::Accepted { node: node.into(), model, resume: false });
564                }
565                v1::ServerMsg::Delta { id: rid, text } if rid == id && accepted => {
566                    answer.text.push_str(&text);
567                    events.event(PoolEvent::Text(text));
568                }
569                v1::ServerMsg::Done { id: rid, turn } if rid == id && accepted => {
570                    answer.text = turn.text;
571                    let calls = !turn.tool_calls.is_empty();
572                    for call in turn.tool_calls {
573                        answer.tool_calls.push(call.clone());
574                        events.event(PoolEvent::ToolCall(call));
575                    }
576                    let mut finish = Finish::new(if calls { "tool_calls" } else { "stop" });
577                    finish.meta.served_by = Some(node.to_string());
578                    return Ok(finish);
579                }
580                v1::ServerMsg::Failed { id: rid, error } if rid == id => return Err(Fail::Error(error)),
581                v1::ServerMsg::Cancelled { id: rid } if rid == id => {
582                    return Err(Fail::Error(RemoteError::Failed { message: "cancelled by the node".into() }));
583                }
584                other => return Err(Fail::Error(RemoteError::protocol(format!("unexpected message {other:?}")))),
585            }
586        }
587    }
588
589    /// Embeddings for every input, from the first node that serves them all (infer/2 only).
590    pub async fn embed(&self, mut request: EmbedRequest, cancel: &CancelToken) -> Result<Embeddings, RemoteError> {
591        if request.cert.is_none() {
592            request.cert.clone_from(&self.opts.cert);
593        }
594        let mut tried = Vec::new();
595        for node in self.nodes.nodes().await {
596            match self.embed_on(&node, &request, cancel).await {
597                Ok(e) => return Ok(e),
598                Err(Fail::Cancelled) => return Err(RemoteError::Cancelled),
599                Err(Fail::Error(e) | Fail::Unsupported(e)) => tried.push(format!("{node}: {e}")),
600                Err(Fail::NoResume) => {}
601            }
602            request.id = request_id();
603        }
604        Err(if tried.is_empty() { RemoteError::unavailable("no inference node to run on") } else { RemoteError::unavailable(tried.join("; ")) })
605    }
606
607    async fn embed_on(&self, node: &str, request: &EmbedRequest, cancel: &CancelToken) -> Result<Embeddings, Fail> {
608        let mut ch = self.open(node, v2::PROTOCOL, cancel).await?;
609        let id = request.id.clone();
610        ch.send_cbor(&ClientFrame::Embed(request.clone())).await.map_err(Fail::Error)?;
611        let mut out = Embeddings { node: node.to_string(), ..Default::default() };
612        let mut got: BTreeMap<u32, Vec<f32>> = BTreeMap::new();
613        let mut accepted = false;
614        let mut gaps = Gaps::default();
615        loop {
616            let wait = if accepted { gaps.wait(&self.opts.stall) } else { self.opts.accept_timeout };
617            let next = tokio::select! {
618                _ = cancel.cancelled() => {
619                    let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
620                    return Err(Fail::Cancelled);
621                }
622                r = tokio::time::timeout(wait, ch.recv_cbor::<ServerFrame>()) => r,
623            };
624            let frame = match next {
625                Err(_) => {
626                    let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
627                    return Err(Fail::Error(if accepted { RemoteError::Stalled { ms: wait.as_millis() as u64 } } else { RemoteError::Timeout }));
628                }
629                Ok(Err(e)) => return Err(Fail::Error(e)),
630                Ok(Ok(None)) => return Err(Fail::Error(RemoteError::Closed)),
631                Ok(Ok(Some(f))) => f,
632            };
633            if frame.id() != id {
634                continue;
635            }
636            match frame {
637                ServerFrame::Queued { .. } if !accepted => {}
638                ServerFrame::Accepted { model, .. } if !accepted => {
639                    accepted = true;
640                    out.model = model;
641                }
642                ServerFrame::Embedding { index, vector, .. } if accepted => {
643                    gaps.tick();
644                    got.insert(index, v2::bytes_f32(&vector).map_err(Fail::Error)?);
645                }
646                ServerFrame::Done { finish, .. } if accepted => {
647                    if got.len() != request.inputs.len() || got.keys().enumerate().any(|(i, k)| *k as usize != i) {
648                        return Err(Fail::Error(RemoteError::protocol(format!("{} of {} embeddings arrived", got.len(), request.inputs.len()))));
649                    }
650                    out.vectors = got.into_values().collect();
651                    out.meta = finish.meta;
652                    return Ok(out);
653                }
654                ServerFrame::Failed { error, .. } => return Err(Fail::Error(error)),
655                ServerFrame::Cancelled { .. } => return Err(Fail::Error(RemoteError::Failed { message: "cancelled by the node".into() })),
656                other => return Err(Fail::Error(RemoteError::protocol(format!("unexpected frame {other:?}")))),
657            }
658        }
659    }
660
661    /// The catalog of the first node that answers.
662    pub async fn catalog(&self) -> Result<Catalog, RemoteError> {
663        let mut tried = Vec::new();
664        for node in self.nodes.nodes().await {
665            let r = tokio::time::timeout(self.opts.accept_timeout, async {
666                let mut ch = self.dialer.open(&node, catalog::PROTOCOL).await?;
667                catalog::query(&mut ch, self.opts.cert.clone()).await
668            })
669            .await
670            .unwrap_or(Err(RemoteError::Timeout));
671            match r {
672                Ok(c) => return Ok(c),
673                Err(e) => tried.push(format!("{node}: {e}")),
674            }
675        }
676        Err(if tried.is_empty() { RemoteError::unavailable("no inference node to ask") } else { RemoteError::unavailable(tried.join("; ")) })
677    }
678
679    /// Follows the catalog: the first node that answers streams its changes; when it goes away
680    /// the next one takes over. Stops when the [`CatalogWatch`] is dropped.
681    pub fn subscribe(&self) -> CatalogWatch {
682        let (tx, rx) = watch::channel(None);
683        let pool = self.clone();
684        let task = tokio::spawn(async move {
685            let mut backoff = Duration::from_millis(200);
686            loop {
687                for node in pool.nodes.nodes().await {
688                    let opened = tokio::time::timeout(pool.opts.accept_timeout, pool.dialer.open(&node, catalog::PROTOCOL)).await;
689                    let Ok(Ok(mut ch)) = opened else { continue };
690                    let sent = catalog::subscribe(&mut ch, pool.opts.cert.clone(), |c| {
691                        tx.send_replace(Some((node.clone(), c)));
692                    });
693                    tokio::select! {
694                        r = sent => if r.is_ok() { backoff = Duration::from_millis(200) },
695                        _ = tx.closed() => return,
696                    }
697                }
698                tokio::select! {
699                    _ = tokio::time::sleep(backoff) => {}
700                    _ = tx.closed() => return,
701                }
702                backoff = (backoff * 2).min(Duration::from_secs(30));
703            }
704        });
705        CatalogWatch { rx, task }
706    }
707
708    /// Runs a job in the background: the same failover and resume as [`Pool::infer`], with its
709    /// events on [`Job::events`]. Batch work usually sets `Priority::Batch`.
710    pub fn submit(&self, request: Request) -> Job {
711        let (tx, events) = mpsc::unbounded_channel();
712        let cancel = CancelToken::new();
713        let job_id = request.job_id.clone();
714        let pool = self.clone();
715        let c = cancel.clone();
716        let handle = tokio::spawn(async move { pool.infer(request, &tx, &c).await });
717        Job { job_id, cancel, handle, events }
718    }
719}
720
721/// A followed catalog ([`Pool::subscribe`]).
722pub struct CatalogWatch {
723    rx: watch::Receiver<Option<(String, Catalog)>>,
724    task: JoinHandle<()>,
725}
726
727impl CatalogWatch {
728    /// The latest catalog and the node it came from, if one has arrived.
729    pub fn current(&self) -> Option<(String, Catalog)> {
730        self.rx.borrow().clone()
731    }
732
733    /// Waits for the next catalog.
734    pub async fn changed(&mut self) -> Option<(String, Catalog)> {
735        self.rx.changed().await.ok()?;
736        self.rx.borrow_and_update().clone()
737    }
738}
739
740impl Drop for CatalogWatch {
741    fn drop(&mut self) {
742        self.task.abort();
743    }
744}
745
746/// A job running in the background ([`Pool::submit`]).
747pub struct Job {
748    job_id: String,
749    cancel: CancelToken,
750    handle: JoinHandle<Result<Answer, Interrupted>>,
751    events: mpsc::UnboundedReceiver<PoolEvent>,
752}
753
754impl Job {
755    pub fn job_id(&self) -> &str {
756        &self.job_id
757    }
758
759    pub fn cancel(&self) {
760        self.cancel.cancel();
761    }
762
763    /// The job's events as they happen.
764    pub fn events(&mut self) -> &mut mpsc::UnboundedReceiver<PoolEvent> {
765        &mut self.events
766    }
767
768    /// Waits for the job to end.
769    pub async fn wait(self) -> Result<Answer, Interrupted> {
770        match self.handle.await {
771            Ok(r) => r,
772            Err(e) => Err(Interrupted { error: RemoteError::Failed { message: e.to_string() }, partial: Box::default(), tried: Vec::new() }),
773        }
774    }
775}
776
777#[cfg(test)]
778mod tests {
779    use super::*;
780
781    #[test]
782    fn splice_places_by_offset() {
783        let mut b = String::new();
784        assert_eq!(splice(&mut b, 0, "Hel"), Ok(Some("Hel".into())));
785        assert_eq!(splice(&mut b, 3, "lo"), Ok(Some("lo".into())));
786        assert_eq!(splice(&mut b, 0, "Hell"), Ok(None));
787        assert_eq!(splice(&mut b, 4, "o wö"), Ok(Some(" wö".into())));
788        assert_eq!(b, "Hello wö");
789        assert_eq!(splice(&mut b, 10, "x"), Err(2));
790    }
791
792    #[test]
793    fn the_stall_timeout_follows_the_token_gap_within_bounds() {
794        let s = Stall::default();
795        assert_eq!(s.timeout(None), Duration::from_secs(15));
796        assert_eq!(s.timeout(Some(Duration::from_secs(1))), Duration::from_secs(15));
797        assert_eq!(s.timeout(Some(Duration::from_secs(7))), Duration::from_secs(21));
798        assert_eq!(s.timeout(Some(Duration::from_secs(20))), Duration::from_secs(25), "stays under net's 30 s resume window");
799    }
800}