Skip to main content

weirdnet_agent/remote/
catalog.rs

1//! `/weirdnet-agent/catalog/1`: the models an inference node offers.
2//!
3//! ```text
4//! asking node                     inference node
5//!   Query { cert } ->             <- Catalog | Failed
6//!   Subscribe { cert } ->         <- Catalog, then Catalog again on every change (until closed)
7//! ```
8//!
9//! One entry per model with its state, an estimated speed and how many replicas serve it, but
10//! no model-node addresses: apps only ever talk to inference nodes. Messages are CBOR.
11//!
12//! Each entry says which inputs beyond text it takes ([`CatalogModel::inputs`]: images, audio).
13//! Entries from nodes before 0.5 have none, so they count as text-only. [`Catalog::route`] picks
14//! a model for a request that carries images or audio, and the pool uses it so such a request
15//! never lands on a text-only model.
16
17use std::sync::Arc;
18
19use serde::{Deserialize, Serialize};
20use tokio::sync::watch;
21
22use super::{Authorize, Caller, Channel, RemoteError, bytes};
23use crate::model::Modalities;
24
25/// Stream protocol id.
26pub const PROTOCOL: &str = "/weirdnet-agent/catalog/1";
27
28/// What a model is for.
29#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
30#[serde(rename_all = "snake_case")]
31#[non_exhaustive]
32pub enum Purpose {
33    #[default]
34    Chat,
35    Embedding,
36}
37
38/// A model's state across the pool.
39#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
40#[serde(rename_all = "snake_case")]
41#[non_exhaustive]
42pub enum ModelState {
43    /// Loaded somewhere and ready.
44    Warm,
45    /// Not loaded, but a node can load it.
46    #[default]
47    Loadable,
48    Loading,
49    /// Loaded, but every replica is full.
50    Busy,
51}
52
53/// One catalog entry.
54#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
55#[non_exhaustive]
56pub struct CatalogModel {
57    pub id: String,
58    #[serde(default)]
59    pub purpose: Purpose,
60    #[serde(default)]
61    pub state: ModelState,
62    /// Model nodes that have it loaded.
63    #[serde(default)]
64    pub replicas: u32,
65    /// Estimated decode speed.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub tokens_per_sec: Option<f32>,
68    /// Context window in tokens.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub context: Option<u32>,
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub revision: Option<String>,
73    /// The model that answers while this one loads, if the pool policy names one.
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub standin: Option<String>,
76    /// Inputs it takes beyond text (images, audio). Empty: text only.
77    #[serde(default, skip_serializing_if = "Modalities::is_text")]
78    pub inputs: Modalities,
79    /// For a LoRA adapter served on a base model: the base's id. Requests name the adapter's own
80    /// id; apps may show it as a variant of the base. Not sent for models; catalogs from 0.5.1
81    /// and earlier lack it.
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub base: Option<String>,
84}
85
86impl CatalogModel {
87    pub fn new(id: impl Into<String>, purpose: Purpose, state: ModelState) -> Self {
88        Self { id: id.into(), purpose, state, ..Default::default() }
89    }
90
91    pub fn with_replicas(mut self, replicas: u32) -> Self {
92        self.replicas = replicas;
93        self
94    }
95
96    pub fn with_speed(mut self, tokens_per_sec: f32) -> Self {
97        self.tokens_per_sec = Some(tokens_per_sec);
98        self
99    }
100
101    pub fn with_context(mut self, tokens: u32) -> Self {
102        self.context = Some(tokens);
103        self
104    }
105
106    /// The inputs it takes beyond text.
107    pub fn with_inputs(mut self, inputs: Modalities) -> Self {
108        self.inputs = inputs;
109        self
110    }
111
112    /// Marks it as a LoRA adapter on base model `base`.
113    pub fn with_base(mut self, base: impl Into<String>) -> Self {
114        self.base = Some(base.into());
115        self
116    }
117
118    /// Whether it is a LoRA adapter on another model.
119    pub fn is_adapter(&self) -> bool {
120        self.base.is_some()
121    }
122
123    /// A chat model that can read input needing `needed`.
124    pub fn accepts(&self, needed: Modalities) -> bool {
125        self.purpose == Purpose::Chat && self.inputs.covers(needed)
126    }
127}
128
129/// The models on offer. `rev` grows with every change.
130#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
131#[non_exhaustive]
132pub struct Catalog {
133    pub rev: u64,
134    pub models: Vec<CatalogModel>,
135}
136
137impl Catalog {
138    pub fn new(rev: u64, models: Vec<CatalogModel>) -> Self {
139        Self { rev, models }
140    }
141
142    pub fn find(&self, id: &str) -> Option<&CatalogModel> {
143        self.models.iter().find(|m| m.id == id)
144    }
145
146    /// The model for a request that needs `needed`: text requests keep `model` as is. Otherwise
147    /// a named model must take those inputs, and with none named the best chat model that does
148    /// is picked (warm, then busy, loading, loadable; then more replicas). A named model the
149    /// catalog does not list is left to the node. `BadRequest` when nothing here can read it.
150    pub fn route(&self, model: Option<&str>, needed: Modalities) -> Result<Option<String>, RemoteError> {
151        if needed.is_text() {
152            return Ok(model.map(str::to_string));
153        }
154        if let Some(id) = model {
155            return match self.find(id) {
156                Some(m) if !m.accepts(needed) => {
157                    let what = m.inputs.lacking(needed).unwrap_or("this input");
158                    Err(RemoteError::BadRequest { message: format!("model `{id}` does not take {what}; pick one whose catalog entry lists them") })
159                }
160                _ => Ok(Some(id.to_string())),
161            };
162        }
163        let rank = |s: ModelState| match s {
164            ModelState::Warm => 0,
165            ModelState::Busy => 1,
166            ModelState::Loading => 2,
167            _ => 3,
168        };
169        self.models
170            .iter()
171            .filter(|m| m.accepts(needed))
172            .min_by_key(|m| (rank(m.state), std::cmp::Reverse(m.replicas)))
173            .map(|m| Some(m.id.clone()))
174            .ok_or_else(|| {
175                let what = Modalities::TEXT.lacking(needed).unwrap_or("this input");
176                RemoteError::BadRequest { message: format!("no model in the pool takes {what}") }
177            })
178    }
179}
180
181/// Asking node to inference node.
182#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
183#[serde(rename_all = "snake_case")]
184#[non_exhaustive]
185pub enum ClientMsg {
186    Query {
187        #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
188        cert: Option<Vec<u8>>,
189    },
190    Subscribe {
191        #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
192        cert: Option<Vec<u8>>,
193    },
194}
195
196/// Inference node to asking node.
197#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
198#[serde(rename_all = "snake_case")]
199#[non_exhaustive]
200pub enum ServerMsg {
201    Catalog(Catalog),
202    Failed { error: RemoteError },
203}
204
205/// The serving side's catalog (an inference node's merged view).
206pub trait CatalogHost: Send + Sync {
207    fn authorize(&self, caller: &Caller) -> Result<(), RemoteError>;
208
209    /// The catalog for this caller, and its changes.
210    fn watch(&self, caller: &Caller) -> Result<watch::Receiver<Catalog>, RemoteError>;
211}
212
213/// A ready [`CatalogHost`]: publish the models, and subscribers hear about it.
214#[derive(Clone)]
215pub struct CatalogFeed {
216    tx: Arc<watch::Sender<Catalog>>,
217    auth: Arc<dyn Authorize>,
218}
219
220impl CatalogFeed {
221    /// A feed whose callers `auth` admits.
222    pub fn new(auth: Arc<dyn Authorize>) -> Self {
223        Self { tx: Arc::new(watch::channel(Catalog::default()).0), auth }
224    }
225
226    /// Replaces the models; `rev` goes up by one.
227    pub fn publish(&self, models: Vec<CatalogModel>) {
228        self.tx.send_modify(|c| {
229            c.rev += 1;
230            c.models = models;
231        });
232    }
233
234    pub fn current(&self) -> Catalog {
235        self.tx.borrow().clone()
236    }
237}
238
239impl CatalogHost for CatalogFeed {
240    fn authorize(&self, caller: &Caller) -> Result<(), RemoteError> {
241        self.auth.authorize(caller)
242    }
243
244    fn watch(&self, _caller: &Caller) -> Result<watch::Receiver<Catalog>, RemoteError> {
245        Ok(self.tx.subscribe())
246    }
247}
248
249/// Serve one catalog/1 stream. `caller` is the transport-authenticated peer; the certificate the
250/// request presents is attached when the transport gave none, and the host authorizes it first.
251pub async fn serve(mut ch: Channel, caller: Caller, host: &dyn CatalogHost) -> Result<(), RemoteError> {
252    let (cert, follow) = match ch.recv_cbor::<ClientMsg>().await? {
253        Some(ClientMsg::Query { cert }) => (cert, false),
254        Some(ClientMsg::Subscribe { cert }) => (cert, true),
255        None => return Ok(()),
256    };
257    let caller = caller.presenting(cert);
258    let mut rx = match host.authorize(&caller).and_then(|()| host.watch(&caller)) {
259        Ok(rx) => rx,
260        Err(error) => return ch.send_cbor(&ServerMsg::Failed { error }).await,
261    };
262    let now = rx.borrow_and_update().clone();
263    ch.send_cbor(&ServerMsg::Catalog(now)).await?;
264    if !follow {
265        return Ok(());
266    }
267    loop {
268        tokio::select! {
269            changed = rx.changed() => {
270                if changed.is_err() {
271                    return Ok(());
272                }
273                let now = rx.borrow_and_update().clone();
274                ch.send_cbor(&ServerMsg::Catalog(now)).await?;
275            }
276            m = ch.rx.recv() => match m {
277                Ok(Some(_)) => {}
278                Ok(None) | Err(_) => return Ok(()),
279            },
280        }
281    }
282}
283
284/// Asks once.
285pub async fn query(ch: &mut Channel, cert: Option<Vec<u8>>) -> Result<Catalog, RemoteError> {
286    ch.send_cbor(&ClientMsg::Query { cert }).await?;
287    match ch.recv_cbor::<ServerMsg>().await? {
288        Some(ServerMsg::Catalog(c)) => Ok(c),
289        Some(ServerMsg::Failed { error }) => Err(error),
290        None => Err(RemoteError::Closed),
291    }
292}
293
294/// Subscribes and hands every catalog to `on`, until the stream ends (`Ok`) or fails.
295pub async fn subscribe(ch: &mut Channel, cert: Option<Vec<u8>>, mut on: impl FnMut(Catalog)) -> Result<(), RemoteError> {
296    ch.send_cbor(&ClientMsg::Subscribe { cert }).await?;
297    loop {
298        match ch.recv_cbor::<ServerMsg>().await? {
299            Some(ServerMsg::Catalog(c)) => on(c),
300            Some(ServerMsg::Failed { error }) => return Err(error),
301            None => return Ok(()),
302        }
303    }
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309    use crate::remote::memory_pair;
310
311    fn anyone() -> Arc<dyn Authorize> {
312        Arc::new(|_: &Caller| Ok(()))
313    }
314
315    #[tokio::test]
316    async fn query_and_subscribe_see_changes() {
317        let feed = CatalogFeed::new(anyone());
318        feed.publish(vec![CatalogModel::new("gemma", Purpose::Chat, ModelState::Warm).with_replicas(2)]);
319        let (mut ours, theirs) = memory_pair();
320        let f = feed.clone();
321        tokio::spawn(async move { serve(theirs, Caller::new("phone"), &f).await });
322        let c = query(&mut ours, None).await.unwrap();
323        assert_eq!(c.rev, 1);
324        assert_eq!(c.find("gemma").unwrap().replicas, 2);
325
326        let (mut ours, theirs) = memory_pair();
327        let f = feed.clone();
328        tokio::spawn(async move { serve(theirs, Caller::new("phone"), &f).await });
329        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
330        tokio::spawn(async move { subscribe(&mut ours, None, |c| tx.send(c).unwrap()).await });
331        assert_eq!(rx.recv().await.unwrap().rev, 1);
332        feed.publish(vec![CatalogModel::new("gemma", Purpose::Chat, ModelState::Loading)]);
333        let next = rx.recv().await.unwrap();
334        assert_eq!((next.rev, next.models[0].state), (2, ModelState::Loading));
335    }
336
337    #[tokio::test]
338    async fn the_host_authorizes_with_the_presented_cert() {
339        let auth: Arc<dyn Authorize> = Arc::new(|c: &Caller| {
340            if c.peer == "laptop" && c.cert_bytes.as_deref() == Some(b"cert") { Ok(()) } else { Err(RemoteError::refused("unknown-device")) }
341        });
342        let feed = CatalogFeed::new(auth);
343        for (peer, cert, ok) in [("laptop", Some(b"cert".to_vec()), true), ("laptop", None, false), ("stranger", Some(b"cert".to_vec()), false)] {
344            let (mut ours, theirs) = memory_pair();
345            let f = feed.clone();
346            tokio::spawn(async move { serve(theirs, Caller::new(peer), &f).await });
347            let r = query(&mut ours, cert).await;
348            assert_eq!(r.is_ok(), ok, "{peer}");
349            if !ok {
350                assert_eq!(r.unwrap_err(), RemoteError::refused("unknown-device"));
351            }
352        }
353    }
354
355    #[test]
356    fn route_keeps_image_requests_off_text_only_models() {
357        let c = Catalog::new(
358            1,
359            vec![
360                CatalogModel::new("qwen", Purpose::Chat, ModelState::Warm),
361                CatalogModel::new("gemma-cold", Purpose::Chat, ModelState::Loadable).with_inputs(Modalities::new(true, true)),
362                CatalogModel::new("gemma", Purpose::Chat, ModelState::Warm).with_inputs(Modalities::VISION),
363                CatalogModel::new("embed", Purpose::Embedding, ModelState::Warm).with_inputs(Modalities::new(true, true)),
364            ],
365        );
366        assert_eq!(c.route(None, Modalities::TEXT).unwrap(), None);
367        assert_eq!(c.route(Some("qwen"), Modalities::TEXT).unwrap().as_deref(), Some("qwen"));
368        assert_eq!(c.route(None, Modalities::VISION).unwrap().as_deref(), Some("gemma"), "warm first");
369        assert_eq!(c.route(None, Modalities::AUDIO).unwrap().as_deref(), Some("gemma-cold"));
370        let e = c.route(Some("qwen"), Modalities::VISION).unwrap_err();
371        assert!(matches!(&e, RemoteError::BadRequest { message } if message.contains("`qwen` does not take images")), "{e}");
372        assert_eq!(c.route(Some("not-listed"), Modalities::VISION).unwrap().as_deref(), Some("not-listed"));
373        let text_only = Catalog::new(1, vec![CatalogModel::new("qwen", Purpose::Chat, ModelState::Warm)]);
374        let e = text_only.route(None, Modalities::new(true, true)).unwrap_err();
375        assert!(matches!(&e, RemoteError::BadRequest { message } if message == "no model in the pool takes images and audio"), "{e}");
376    }
377
378    #[test]
379    fn inputs_are_optional_on_the_wire() {
380        let plain = CatalogModel::new("qwen", Purpose::Chat, ModelState::Warm);
381        let b = crate::remote::to_cbor(&plain).unwrap();
382        assert!(!b.windows(6).any(|w| w == b"inputs"), "text-only entries look as before");
383        let v = CatalogModel::new("gemma", Purpose::Chat, ModelState::Warm).with_inputs(Modalities::VISION);
384        assert_eq!(crate::remote::from_cbor::<CatalogModel>(&crate::remote::to_cbor(&v).unwrap()).unwrap(), v);
385    }
386
387    #[test]
388    fn base_is_optional_on_the_wire() {
389        let plain = CatalogModel::new("qwen", Purpose::Chat, ModelState::Warm);
390        let b = crate::remote::to_cbor(&plain).unwrap();
391        assert!(!b.windows(4).any(|w| w == b"base"), "models look as before");
392        assert!(!plain.is_adapter());
393        let a = CatalogModel::new("qwen+tune", Purpose::Chat, ModelState::Warm).with_base("qwen");
394        assert!(a.is_adapter());
395        assert_eq!(crate::remote::from_cbor::<CatalogModel>(&crate::remote::to_cbor(&a).unwrap()).unwrap(), a);
396    }
397
398    #[test]
399    fn wire_is_cbor_with_byte_string_certs() {
400        let m = ClientMsg::Query { cert: Some(vec![1, 2, 3]) };
401        let b = crate::remote::to_cbor(&m).unwrap();
402        // map(1) "query" map(1) "cert" bytes(3)
403        assert!(b.windows(4).any(|w| w == [0x43, 1, 2, 3]), "{b:x?}");
404        assert_eq!(crate::remote::from_cbor::<ClientMsg>(&b).unwrap(), m);
405    }
406}