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