Skip to main content

weirdnet_agent/remote/
pool_model.rs

1//! A model cloud as one model: [`PoolModel`] and [`PoolWatch`].
2//!
3//! A pool of inference nodes (for example a [Ymir](https://github.com/WeirdBrains/ymir) cloud on
4//! the user's own devices) is reached through a [`Pool`]. This module adds what an agent app
5//! needs on top:
6//!
7//! - [`PoolModel`]: a [`ModelBackend`] over [`Pool::infer`] (infer/2). Text and reasoning stream
8//!   to the [`DeltaSink`], tool-call frames come back in the turn, cancel stops the node, and a
9//!   node that dies mid-answer is resumed on another one (the pool's
10//!   [`PoolOptions::resume`](super::pool::PoolOptions::resume), on by default), shown as
11//!   [`ModelNotice::Continued`]. When the pool can't take a turn before any text streamed, an
12//!   optional fallback (usually the local model) runs it, shown as [`ModelNotice::FellBack`];
13//!   with no fallback the error is [`ModelError::PoolUnreachable`] when no node could be reached.
14//! - [`PoolWatch`]: follows the pool catalog (catalog/1 subscribe) as a [`PoolStatus`] for a model
15//!   picker (live, searching or unreachable, with each model's state and speed), and knows which
16//!   nodes answered, as a [`NodeSource`] ([`PoolWatch::nodes`]) so turns go only to real
17//!   inference nodes.
18//!
19//! Like the rest of [`remote`](super), it has no networking of its own: the [`Pool`]'s dialer
20//! and node source come from the app.
21
22use std::sync::{Arc, Mutex};
23use std::time::Duration;
24
25use async_trait::async_trait;
26use tokio::sync::{Notify, watch};
27use tokio::task::JoinHandle;
28
29use super::RemoteError;
30use super::catalog::{self, Catalog, CatalogModel, ModelState};
31use super::infer::Route;
32use super::infer::v2::Request;
33use super::pool::{EventSink, Interrupted, NodeSource, Pool, PoolEvent, reported};
34use crate::cancel::CancelToken;
35use crate::model::{DeltaSink, Message, Modalities, ModelBackend, ModelError, ModelNotice, ModelTurn};
36use crate::tool::ToolSpec;
37
38/// A [`ModelBackend`] over a model pool, with an optional fallback.
39pub struct PoolModel {
40    pool: Pool,
41    model: Option<String>,
42    fallback: Option<Arc<dyn ModelBackend>>,
43    reroute: bool,
44    last: Mutex<Option<Route>>,
45}
46
47impl PoolModel {
48    /// Runs turns on `pool` with its options as they are (resume is on by default). For a
49    /// pool of inference nodes only, turn off
50    /// [`infer_v1_fallback`](super::pool::PoolOptions::infer_v1_fallback).
51    pub fn new(pool: Pool) -> Self {
52        Self { pool, model: None, fallback: None, reroute: true, last: Mutex::new(None) }
53    }
54
55    /// Asks for this catalog model instead of the pool's default.
56    pub fn with_model(mut self, model: impl Into<String>) -> Self {
57        self.model = Some(model.into());
58        self
59    }
60
61    /// Runs here when the pool can't take a turn before any text streamed.
62    pub fn with_fallback(mut self, fallback: Arc<dyn ModelBackend>) -> Self {
63        self.fallback = Some(fallback);
64        self
65    }
66
67    /// When the chosen model can't read a turn's images or audio, let the pool pick one that
68    /// can ([`ModelNotice::Rerouted`]) instead of refusing the turn. On by default.
69    pub fn with_reroute(mut self, on: bool) -> Self {
70        self.reroute = on;
71        self
72    }
73
74    pub fn pool(&self) -> &Pool {
75        &self.pool
76    }
77
78    pub fn model(&self) -> Option<&str> {
79        self.model.as_deref()
80    }
81
82    /// Where the last completed turn ran.
83    pub fn last_route(&self) -> Option<Route> {
84        self.last.lock().unwrap_or_else(|e| e.into_inner()).clone()
85    }
86
87    fn set_last(&self, route: Route) {
88        *self.last.lock().unwrap_or_else(|e| e.into_inner()) = Some(route);
89    }
90
91    /// Drops a chosen model that can't read the request's inputs, so the pool routes it.
92    async fn fit(&self, request: &mut Request, deltas: &DeltaSink) {
93        let needed = request.needs();
94        let Some(model) = request.model.clone().filter(|_| self.reroute && !needed.is_text()) else { return };
95        let Ok(catalog) = self.pool.catalog().await else { return };
96        if catalog.find(&model).is_some_and(|m| m.accepts(needed)) {
97            return;
98        }
99        if catalog.models.iter().any(|m| m.accepts(needed)) {
100            request.model = None;
101            deltas.notice(ModelNotice::Rerouted { from: model, needs: Modalities::TEXT.lacking(needed).unwrap_or("these inputs").to_string() });
102        }
103    }
104}
105
106/// Every node tried was unreachable rather than answering, or there was none to try (a request
107/// the pool refused itself, such as images no model reads, is not).
108pub fn is_unreachable(err: &Interrupted) -> bool {
109    if err.tried.is_empty() {
110        return !err.error.is_request_error();
111    }
112    let transport = |e: &RemoteError| {
113        matches!(
114            e,
115            RemoteError::Unreachable { .. }
116                | RemoteError::Timeout
117                | RemoteError::Closed
118                | RemoteError::Unsupported { .. }
119                | RemoteError::Stalled { .. }
120        )
121    };
122    err.tried.iter().all(|(_, e)| transport(e))
123}
124
125/// Why the pool did not take a turn, in one line.
126fn describe(err: &Interrupted) -> String {
127    if err.tried.is_empty() {
128        return err.error.to_string();
129    }
130    err.tried.iter().map(|(n, e)| format!("{n}: {e}")).collect::<Vec<_>>().join("; ")
131}
132
133struct Forward<'a>(&'a DeltaSink);
134
135impl EventSink for Forward<'_> {
136    fn event(&self, event: PoolEvent) {
137        match event {
138            PoolEvent::Text(t) => self.0.text(t),
139            PoolEvent::Reasoning(t) => self.0.reasoning(t),
140            PoolEvent::Resumed { node, offset } => self.0.notice(ModelNotice::Continued { node, offset }),
141            _ => {}
142        }
143    }
144}
145
146#[async_trait]
147impl ModelBackend for PoolModel {
148    /// `model@node` of the last turn (traces record it after each turn).
149    fn name(&self) -> String {
150        match self.last_route() {
151            Some(Route::Node { node, model }) => format!("{model}@{node}"),
152            Some(Route::Fallback) => self.fallback.as_ref().map(|f| f.name()).unwrap_or_default(),
153            _ => format!("{}@pool", self.model.as_deref().unwrap_or("model")),
154        }
155    }
156
157    async fn complete(&self, messages: &[Message], tools: &[ToolSpec], deltas: &DeltaSink, cancel: &CancelToken) -> Result<ModelTurn, ModelError> {
158        let mut request = Request::messages(messages.to_vec()).with_tools(tools.to_vec());
159        request.model.clone_from(&self.model);
160        self.fit(&mut request, deltas).await;
161        let err = match self.pool.infer(request, &Forward(deltas), cancel).await {
162            Ok(answer) => {
163                self.set_last(Route::Node { node: answer.node.clone(), model: answer.model.clone() });
164                return Ok(answer.turn());
165            }
166            Err(e) => e,
167        };
168        if err.error == RemoteError::Cancelled || cancel.is_cancelled() {
169            return Err(ModelError::Cancelled);
170        }
171        if err.streamed() {
172            // Text was shown and could not be resumed: it can't be taken back.
173            let node = err.tried.last().map(|(n, _)| n.as_str()).unwrap_or("pool");
174            return Err(ModelError::Failed(format!("{node}: {}", err.error)));
175        }
176        let error = if is_unreachable(&err) { ModelError::PoolUnreachable(describe(&err)) } else { ModelError::Unavailable(describe(&err)) };
177        let Some(fallback) = &self.fallback else { return Err(error) };
178        deltas.notice(ModelNotice::FellBack { reason: error.to_string(), to: fallback.name() });
179        let r = fallback.complete(messages, tools, deltas, cancel).await;
180        if r.is_ok() {
181            self.set_last(Route::Fallback);
182        }
183        r
184    }
185}
186
187/// The pool as a model picker sees it.
188#[derive(Debug, Clone, PartialEq)]
189#[non_exhaustive]
190pub enum PoolStatus {
191    /// Looking for an inference node: at the start, and after the followed one went away.
192    /// `last` is the catalog seen before, if any.
193    Searching { last: Option<Catalog> },
194    /// Following `node`'s catalog.
195    Live { node: String, catalog: Catalog },
196    /// No inference node answered in a whole round; it keeps trying with backoff.
197    Unreachable { error: RemoteError, last: Option<Catalog> },
198}
199
200impl PoolStatus {
201    pub fn is_live(&self) -> bool {
202        matches!(self, PoolStatus::Live { .. })
203    }
204
205    /// The live catalog, or the last one seen.
206    pub fn catalog(&self) -> Option<&Catalog> {
207        match self {
208            PoolStatus::Live { catalog, .. } => Some(catalog),
209            PoolStatus::Searching { last } | PoolStatus::Unreachable { last, .. } => last.as_ref(),
210        }
211    }
212
213    /// Chat models that can read input needing `needed`, ready ones first (warm, loading,
214    /// loadable, busy), then by id. Models that can't read it are left out.
215    pub fn chat_models(&self, needed: Modalities) -> Vec<&CatalogModel> {
216        let mut models: Vec<&CatalogModel> = self.catalog().map(|c| c.models.iter().filter(|m| m.accepts(needed)).collect()).unwrap_or_default();
217        models.sort_by(|a, b| state_rank(a.state).cmp(&state_rank(b.state)).then_with(|| a.id.cmp(&b.id)));
218        models
219    }
220}
221
222fn state_rank(s: ModelState) -> u8 {
223    match s {
224        ModelState::Warm => 0,
225        ModelState::Loading => 1,
226        ModelState::Loadable => 2,
227        ModelState::Busy => 3,
228    }
229}
230
231/// The nodes that answered the pool catalog, the followed one first: a [`NodeSource`] for the
232/// [`Pool`] that runs turns.
233#[derive(Clone, Default)]
234pub struct CatalogNodes(Arc<Mutex<Vec<String>>>);
235
236impl CatalogNodes {
237    fn first(&self, node: &str) {
238        let mut v = self.0.lock().unwrap_or_else(|e| e.into_inner());
239        v.retain(|n| n != node);
240        v.insert(0, node.to_string());
241    }
242
243    fn forget(&self, node: &str) {
244        self.0.lock().unwrap_or_else(|e| e.into_inner()).retain(|n| n != node);
245    }
246
247    pub fn get(&self) -> Vec<String> {
248        self.0.lock().unwrap_or_else(|e| e.into_inner()).clone()
249    }
250}
251
252#[async_trait]
253impl NodeSource for CatalogNodes {
254    async fn nodes(&self) -> Vec<String> {
255        self.get()
256    }
257}
258
259/// Follows a pool's catalog in the background; stops when dropped.
260pub struct PoolWatch {
261    rx: watch::Receiver<PoolStatus>,
262    nodes: CatalogNodes,
263    retry: Arc<Notify>,
264    task: JoinHandle<()>,
265}
266
267/// The first retry after a round with no catalog; it doubles up to [`MAX_BACKOFF`].
268const FIRST_BACKOFF: Duration = Duration::from_millis(500);
269const MAX_BACKOFF: Duration = Duration::from_secs(30);
270
271impl PoolWatch {
272    /// Asks `probe`'s nodes in order for the catalog and follows the first that answers; when
273    /// it goes away, the next. Call from a Tokio runtime.
274    pub fn spawn(probe: Pool) -> Self {
275        let (tx, rx) = watch::channel(PoolStatus::Searching { last: None });
276        let nodes = CatalogNodes::default();
277        let known = nodes.clone();
278        let retry = Arc::new(Notify::new());
279        let again = retry.clone();
280        let task = tokio::spawn(async move {
281            let (timeout, cert) = (probe.options().accept_timeout, probe.options().cert.clone());
282            let mut last: Option<Catalog> = None;
283            let mut backoff = FIRST_BACKOFF;
284            loop {
285                let mut tried: Vec<RemoteError> = Vec::new();
286                for node in probe.nodes().await {
287                    let opened = tokio::select! {
288                        r = tokio::time::timeout(timeout, probe.dialer().open(&node, catalog::PROTOCOL)) => r.unwrap_or(Err(RemoteError::Timeout)),
289                        _ = tx.closed() => return,
290                    };
291                    let mut ch = match opened {
292                        Ok(ch) => ch,
293                        Err(e) => {
294                            known.forget(&node);
295                            tried.push(e);
296                            continue;
297                        }
298                    };
299                    let mut live = false;
300                    let r = {
301                        let sub = catalog::subscribe(&mut ch, cert.clone(), |c| {
302                            live = true;
303                            known.first(&node);
304                            last = Some(c.clone());
305                            tx.send_replace(PoolStatus::Live { node: node.clone(), catalog: c });
306                        });
307                        tokio::select! {
308                            r = sub => r,
309                            _ = tx.closed() => return,
310                        }
311                    };
312                    if live {
313                        backoff = FIRST_BACKOFF;
314                        tx.send_replace(PoolStatus::Searching { last: last.clone() });
315                    } else {
316                        known.forget(&node);
317                    }
318                    tried.push(r.err().unwrap_or(RemoteError::Closed));
319                }
320                tx.send_replace(PoolStatus::Unreachable { error: reported(tried.iter(), "no inference node to ask"), last: last.clone() });
321                tokio::select! {
322                    _ = tokio::time::sleep(backoff) => backoff = (backoff * 2).min(MAX_BACKOFF),
323                    _ = again.notified() => backoff = FIRST_BACKOFF,
324                    _ = tx.closed() => return,
325                }
326            }
327        });
328        Self { rx, nodes, retry, task }
329    }
330
331    pub fn status(&self) -> PoolStatus {
332        self.rx.borrow().clone()
333    }
334
335    /// Asks the nodes again now instead of after the backoff, e.g. when a turn wants the pool
336    /// while it is unreachable. A round already running is followed by one more.
337    pub fn retry(&self) {
338        self.retry.notify_one();
339    }
340
341    /// A receiver to follow the status elsewhere (a UI thread).
342    pub fn receiver(&self) -> watch::Receiver<PoolStatus> {
343        self.rx.clone()
344    }
345
346    /// Waits for the next status; `None` once the watch has stopped.
347    pub async fn changed(&mut self) -> Option<PoolStatus> {
348        self.rx.changed().await.ok()?;
349        Some(self.rx.borrow_and_update().clone())
350    }
351
352    /// The nodes that answered, the followed one first, for the [`Pool`] that runs turns.
353    pub fn nodes(&self) -> CatalogNodes {
354        self.nodes.clone()
355    }
356}
357
358impl Drop for PoolWatch {
359    fn drop(&mut self) {
360        self.task.abort();
361    }
362}
363
364#[cfg(test)]
365#[path = "pool_model_tests.rs"]
366mod tests;