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//! and since 0.5.10 whole video clips, `inputs.video`). Entries from nodes before 0.5 have none,
14//! so they count as text-only, and entries without `video` (every node before 0.5.10) count as
15//! not reading video. [`Catalog::route`] picks a model for a request that carries images, audio
16//! or video, and the pool uses it so such a request never lands on a model that can't read it.
17//! A refused video request says the fallback ([`VIDEO_FALLBACK`]): send the clip as frames.
18//!
19//! Entries may also say where the model came from ([`CatalogModel::origin`]) and its license
20//! ([`CatalogModel::license`]); both are left off the wire when unset, so older peers read them.
21//!
22//! Entries may carry the model's media and request limits ([`CatalogModel::limits`], a
23//! [`MediaLimits`]: images per request, token cost per image and its edge, audio length and token
24//! rate, request bytes), each absent when the node doesn't know it. Unknown limits are left off
25//! the wire, so peers before 0.5.7 read and send entries unchanged.
26//!
27//! A model may be a speech-to-text model ([`Purpose::Transcribe`], `transcribe` on the wire):
28//! audio in, its transcript out, so a soundtrack can become text for models without audio. It is
29//! never picked for chat; [`Catalog::route_transcribe`] picks one for a transcription request
30//! (infer/2 `Transcribe`). Peers before 0.5.8 can't read that purpose, so [`serve`] leaves such
31//! entries out for askers that don't say they skip what they can't read; [`query`] and
32//! [`subscribe`] say so, and from 0.5.8 an entry this version can't read (a purpose from a newer
33//! version, say) is skipped instead of failing the whole catalog.
34//!
35//! Since 0.5.11 a model may speak ([`Purpose::Speak`], `speak` on the wire): text in, audio out
36//! (infer/2 `Speak`), with its [`SpeechProfile`] ([`CatalogModel::speech`]: preset voices,
37//! design, cloning, scripts, formats and limits; merged across nodes with
38//! [`SpeechProfile::tightest`]). It is never picked for chat or transcription;
39//! [`Catalog::route_speak`] picks one whose profile covers a request's [`SpeechNeeds`]. Askers
40//! before 0.5.8 never see `speak` entries ([`serve`] leaves them out, as for `transcribe`), and
41//! askers from 0.5.8 to 0.5.10 skip them as entries they can't read.
42
43use std::sync::Arc;
44
45use serde::{Deserialize, Serialize};
46use tokio::sync::watch;
47
48use super::{Authorize, Caller, Channel, RemoteError, bytes};
49use crate::limits::MediaLimits;
50use crate::model::Modalities;
51use crate::speech::{SpeechNeeds, SpeechProfile};
52
53/// Stream protocol id.
54pub const PROTOCOL: &str = "/weirdnet-agent/catalog/1";
55
56/// What [`Catalog::route`] tells a client whose video request no model can read natively: the
57/// fallback, sampling the clip into frames (image parts), ends every such `BadRequest` message.
58/// Since 0.5.10.
59pub const VIDEO_FALLBACK: &str = "send the video as frames (image_url parts) instead";
60
61/// What a model is for.
62#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
63#[serde(rename_all = "snake_case")]
64#[non_exhaustive]
65pub enum Purpose {
66    #[default]
67    Chat,
68    Embedding,
69    /// Speech to text: audio in, its transcript out (infer/2 `Transcribe`). Never picked as a
70    /// chat model. Since 0.5.8; older peers don't see these entries (see the module docs).
71    Transcribe,
72    /// Text to speech: text in, audio out (infer/2 `Speak`). Never picked as a chat model or a
73    /// transcriber. Since 0.5.11; older peers don't see these entries (see the module docs).
74    Speak,
75}
76
77impl Purpose {
78    /// The name on the wire and in settings: `chat`, `embedding`, `transcribe` or `speak` (the same names
79    /// as [weirdnet-model](https://crates.io/crates/weirdnet-model)'s `hw::Purpose`).
80    pub fn as_str(&self) -> &'static str {
81        match self {
82            Purpose::Chat => "chat",
83            Purpose::Embedding => "embedding",
84            Purpose::Transcribe => "transcribe",
85            Purpose::Speak => "speak",
86        }
87    }
88
89    /// Parses [`as_str`](Self::as_str)'s names; `None` for anything else.
90    pub fn parse(name: &str) -> Option<Self> {
91        match name {
92            "chat" => Some(Purpose::Chat),
93            "embedding" => Some(Purpose::Embedding),
94            "transcribe" => Some(Purpose::Transcribe),
95            "speak" => Some(Purpose::Speak),
96            _ => None,
97        }
98    }
99
100    /// Known to peers before 0.5.8 (which can't skip an entry they can't read; peers from 0.5.8
101    /// skip `speak` entries themselves).
102    fn before_transcribe(self) -> bool {
103        matches!(self, Purpose::Chat | Purpose::Embedding)
104    }
105}
106
107impl std::fmt::Display for Purpose {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        f.write_str(self.as_str())
110    }
111}
112
113/// A model's state across the pool.
114#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
115#[serde(rename_all = "snake_case")]
116#[non_exhaustive]
117pub enum ModelState {
118    /// Loaded somewhere and ready.
119    Warm,
120    /// Not loaded, but a node can load it.
121    #[default]
122    Loadable,
123    Loading,
124    /// Loaded, but every replica is full.
125    Busy,
126}
127
128/// One catalog entry.
129#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
130#[non_exhaustive]
131pub struct CatalogModel {
132    pub id: String,
133    #[serde(default)]
134    pub purpose: Purpose,
135    #[serde(default)]
136    pub state: ModelState,
137    /// Model nodes that have it loaded.
138    #[serde(default)]
139    pub replicas: u32,
140    /// Estimated decode speed.
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub tokens_per_sec: Option<f32>,
143    /// Context window in tokens: the one the node runs the model with (such as llama.cpp's
144    /// `--ctx-size` per slot) when it knows it, not the model's trained maximum.
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub context: Option<u32>,
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub revision: Option<String>,
149    /// The model that answers while this one loads, if the pool policy names one.
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub standin: Option<String>,
152    /// Inputs it takes beyond text (images, audio, video). Empty: text only. `video` is absent
153    /// from nodes before 0.5.10, so their models count as not reading video.
154    #[serde(default, skip_serializing_if = "Modalities::is_text")]
155    pub inputs: Modalities,
156    /// For a LoRA adapter served on a base model: the base's id. Requests name the adapter's own
157    /// id; apps may show it as a variant of the base. Not sent for models; catalogs from 0.5.1
158    /// and earlier lack it.
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub base: Option<String>,
161    /// Where the model came from: `hub`, `upload` or `train` (the origins of a
162    /// [weirdnet-model](https://crates.io/crates/weirdnet-model) provenance record), or an app's
163    /// own. Absent when the node does not say, and in catalogs from 0.5.3 and earlier.
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    pub origin: Option<String>,
166    /// The model's license as an SPDX id, or `unknown` when the uploader said so. Absent when the
167    /// node does not say, and in catalogs from 0.5.3 and earlier.
168    #[serde(default, skip_serializing_if = "Option::is_none")]
169    pub license: Option<String>,
170    /// Media and request limits, each absent when the node doesn't know it (never defaulted).
171    /// Left off the wire when none is known; absent in catalogs from 0.5.6 and earlier.
172    #[serde(default, skip_serializing_if = "MediaLimits::is_unknown")]
173    pub limits: MediaLimits,
174    /// For a speaking model ([`Purpose::Speak`]): what it does, takes and allows, merged across
175    /// the nodes that serve it ([`SpeechProfile::tightest`]). Absent when no node reported one
176    /// (the model then serves only plain text in its default voice and format), and in catalogs
177    /// from 0.5.10 and earlier. Since 0.5.11.
178    #[serde(default, skip_serializing_if = "Option::is_none")]
179    pub speech: Option<SpeechProfile>,
180    /// For a model served by several machines together (one model too big for any of them, such
181    /// as vLLM over Ray): the node that answers for it and every machine holding part of it.
182    /// Absent for a model each node serves on its own, and in catalogs from 0.5.12 and earlier.
183    /// Since 0.5.13.
184    #[serde(default, skip_serializing_if = "Option::is_none")]
185    pub pooled: Option<Pooled>,
186}
187
188/// [`CatalogModel::pooled`]: one model spread over several machines.
189#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
190#[non_exhaustive]
191pub struct Pooled {
192    /// The node that answers for the model (vLLM's head): requests go there.
193    pub served_by: String,
194    /// Every machine holding part of it, `served_by` first.
195    #[serde(default, skip_serializing_if = "Vec::is_empty")]
196    pub members: Vec<String>,
197    /// How it is split, such as `vllm-ray` or `llamacpp-rpc`; empty when not said.
198    #[serde(default, skip_serializing_if = "String::is_empty")]
199    pub backend: String,
200    /// Whether the members are running it now (the model may still be listed while they are
201    /// stopped and start on the first request).
202    #[serde(default)]
203    pub up: bool,
204}
205
206impl Pooled {
207    /// `served_by` and the members (`served_by` is put first when it is missing from them).
208    pub fn new(served_by: impl Into<String>, members: Vec<String>) -> Self {
209        let served_by = served_by.into();
210        let mut all = vec![served_by.clone()];
211        all.extend(members.into_iter().filter(|m| *m != served_by));
212        Self { served_by, members: all, ..Default::default() }
213    }
214
215    pub fn with_backend(mut self, backend: impl Into<String>) -> Self {
216        self.backend = backend.into();
217        self
218    }
219
220    pub fn with_up(mut self, up: bool) -> Self {
221        self.up = up;
222        self
223    }
224}
225
226/// [`CatalogModel::origin`]: downloaded from a Hub.
227pub const ORIGIN_HUB: &str = "hub";
228/// [`CatalogModel::origin`]: sent from another machine.
229pub const ORIGIN_UPLOAD: &str = "upload";
230/// [`CatalogModel::origin`]: made by a training run.
231pub const ORIGIN_TRAIN: &str = "train";
232
233impl CatalogModel {
234    pub fn new(id: impl Into<String>, purpose: Purpose, state: ModelState) -> Self {
235        Self { id: id.into(), purpose, state, ..Default::default() }
236    }
237
238    pub fn with_replicas(mut self, replicas: u32) -> Self {
239        self.replicas = replicas;
240        self
241    }
242
243    pub fn with_speed(mut self, tokens_per_sec: f32) -> Self {
244        self.tokens_per_sec = Some(tokens_per_sec);
245        self
246    }
247
248    pub fn with_context(mut self, tokens: u32) -> Self {
249        self.context = Some(tokens);
250        self
251    }
252
253    /// The inputs it takes beyond text.
254    pub fn with_inputs(mut self, inputs: Modalities) -> Self {
255        self.inputs = inputs;
256        self
257    }
258
259    /// Marks it as a LoRA adapter on base model `base`.
260    pub fn with_base(mut self, base: impl Into<String>) -> Self {
261        self.base = Some(base.into());
262        self
263    }
264
265    /// Where it came from ([`ORIGIN_HUB`], [`ORIGIN_UPLOAD`], [`ORIGIN_TRAIN`] or an app's own).
266    pub fn with_origin(mut self, origin: impl Into<String>) -> Self {
267        self.origin = Some(origin.into());
268        self
269    }
270
271    /// Its license (an SPDX id, or `unknown`).
272    pub fn with_license(mut self, license: impl Into<String>) -> Self {
273        self.license = Some(license.into());
274        self
275    }
276
277    /// Its media and request limits.
278    pub fn with_limits(mut self, limits: MediaLimits) -> Self {
279        self.limits = limits;
280        self
281    }
282
283    /// Its speech profile (for a [`Purpose::Speak`] model).
284    pub fn with_speech(mut self, speech: SpeechProfile) -> Self {
285        self.speech = Some(speech);
286        self
287    }
288
289    /// Marks it as served by several machines together ([`CatalogModel::pooled`]).
290    pub fn with_pooled(mut self, pooled: Pooled) -> Self {
291        self.pooled = Some(pooled);
292        self
293    }
294
295    /// Whether several machines serve it together.
296    pub fn is_pooled(&self) -> bool {
297        self.pooled.is_some()
298    }
299
300    /// Whether it is a LoRA adapter on another model.
301    pub fn is_adapter(&self) -> bool {
302        self.base.is_some()
303    }
304
305    /// A chat model that can read input needing `needed`.
306    pub fn accepts(&self, needed: Modalities) -> bool {
307        self.purpose == Purpose::Chat && self.inputs.covers(needed)
308    }
309
310    /// A speech-to-text model ([`Purpose::Transcribe`]).
311    pub fn transcribes(&self) -> bool {
312        self.purpose == Purpose::Transcribe
313    }
314
315    /// A text-to-speech model ([`Purpose::Speak`]).
316    pub fn speaks(&self) -> bool {
317        self.purpose == Purpose::Speak
318    }
319
320    /// A speaking model with no speech profile yet (none published, or an empty one): typically
321    /// a cold speaker the catalog has no entry for, whose engine reports its voices when it
322    /// loads. [`Catalog::route_speak`] leaves a request naming it to its node.
323    pub fn speech_unknown(&self) -> bool {
324        self.speaks() && self.speech.as_ref().is_none_or(SpeechProfile::is_unknown)
325    }
326
327    /// Whether this speaking model's profile covers `needs` (no profile: only the plainest
328    /// request). `Err` says what it lacks; `Err` too when it doesn't speak.
329    pub fn speech_covers(&self, needs: &SpeechNeeds) -> Result<(), String> {
330        if !self.speaks() {
331            return Err("does not speak (text to speech)".into());
332        }
333        match &self.speech {
334            Some(p) => p.covers(needs),
335            None => SpeechProfile::default().covers(needs),
336        }
337    }
338}
339
340/// Placement order: warm, then busy, loading, loadable.
341fn rank(s: ModelState) -> u8 {
342    match s {
343        ModelState::Warm => 0,
344        ModelState::Busy => 1,
345        ModelState::Loading => 2,
346        _ => 3,
347    }
348}
349
350/// The models on offer. `rev` grows with every change.
351#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
352#[non_exhaustive]
353pub struct Catalog {
354    pub rev: u64,
355    /// The entries. Reading one this version can't (a purpose from a newer version, say) skips
356    /// that entry instead of failing the catalog (since 0.5.8).
357    #[serde(deserialize_with = "readable_models")]
358    pub models: Vec<CatalogModel>,
359}
360
361/// The entries this version can read; the rest are skipped.
362fn readable_models<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<CatalogModel>, D::Error> {
363    struct Entry(Option<CatalogModel>);
364    impl<'de> Deserialize<'de> for Entry {
365        fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
366            // Entries hold only strings, numbers, booleans and maps, so a JSON value carries
367            // them whole from CBOR as well as from JSON.
368            let v = serde_json::Value::deserialize(d)?;
369            Ok(Entry(serde_json::from_value(v).ok()))
370        }
371    }
372    Ok(Vec::<Entry>::deserialize(d)?.into_iter().filter_map(|e| e.0).collect())
373}
374
375impl Catalog {
376    pub fn new(rev: u64, models: Vec<CatalogModel>) -> Self {
377        Self { rev, models }
378    }
379
380    pub fn find(&self, id: &str) -> Option<&CatalogModel> {
381        self.models.iter().find(|m| m.id == id)
382    }
383
384    /// The model for a request that needs `needed`: text requests keep `model` as is. Otherwise
385    /// a named model must take those inputs, and with none named the best chat model that does
386    /// is picked (warm, then busy, loading, loadable; then more replicas). A named model the
387    /// catalog does not list is left to the node. `BadRequest` when nothing here can read it; for
388    /// a video part no model reads, the message ends with [`VIDEO_FALLBACK`].
389    pub fn route(&self, model: Option<&str>, needed: Modalities) -> Result<Option<String>, RemoteError> {
390        if needed.is_text() {
391            return Ok(model.map(str::to_string));
392        }
393        if let Some(id) = model {
394            return match self.find(id) {
395                Some(m) if !m.accepts(needed) => {
396                    let what = m.inputs.lacking(needed).unwrap_or("this input");
397                    let hint = if needed.video && !m.inputs.video { format!(", or {VIDEO_FALLBACK}") } else { String::new() };
398                    Err(RemoteError::BadRequest {
399                        message: format!("model `{id}` does not take {what}; pick one whose catalog entry lists them{hint}"),
400                    })
401                }
402                _ => Ok(Some(id.to_string())),
403            };
404        }
405        self.models
406            .iter()
407            .filter(|m| m.accepts(needed))
408            .min_by_key(|m| (rank(m.state), std::cmp::Reverse(m.replicas)))
409            .map(|m| Some(m.id.clone()))
410            .ok_or_else(|| {
411                let what = Modalities::TEXT.lacking(needed).unwrap_or("this input");
412                let hint = if needed.video { format!("; {VIDEO_FALLBACK}") } else { String::new() };
413                RemoteError::BadRequest { message: format!("no model in the pool takes {what}{hint}") }
414            })
415    }
416
417    /// The model for a transcription request (infer/2 `Transcribe`): a named model must be a
418    /// speech-to-text model ([`Purpose::Transcribe`]), and with none named the best one is picked
419    /// (warm, then busy, loading, loadable; then more replicas). A named model the catalog does
420    /// not list is left to the node. `BadRequest` when it names a model that does not transcribe
421    /// or nothing here does.
422    pub fn route_transcribe(&self, model: Option<&str>) -> Result<String, RemoteError> {
423        if let Some(id) = model {
424            return match self.find(id) {
425                Some(m) if !m.transcribes() => Err(RemoteError::BadRequest {
426                    message: format!("model `{id}` does not transcribe audio; pick one whose catalog purpose is `transcribe`"),
427                }),
428                _ => Ok(id.to_string()),
429            };
430        }
431        self.transcribers()
432            .min_by_key(|m| (rank(m.state), std::cmp::Reverse(m.replicas)))
433            .map(|m| m.id.clone())
434            .ok_or_else(|| RemoteError::BadRequest { message: "no model in the pool transcribes audio".into() })
435    }
436
437    /// The model for a speech request (infer/2 `Speak`, since 0.5.11): a named model must be a
438    /// speaking model ([`Purpose::Speak`]) whose profile covers `needs`
439    /// ([`SpeakRequest::needs`](crate::remote::infer::v2::SpeakRequest::needs)), and with none
440    /// named the best speaker that covers them is picked (warm, then busy, loading, loadable;
441    /// then more replicas). A named model the catalog does not list is left to the node.
442    /// `BadRequest` names the model and what it lacks, or says no model in the pool speaks, or
443    /// what each speaker lacks.
444    pub fn route_speak(&self, model: Option<&str>, needs: &SpeechNeeds) -> Result<String, RemoteError> {
445        if let Some(id) = model {
446            return match self.find(id) {
447                Some(m) if !m.speaks() => Err(RemoteError::BadRequest {
448                    message: format!("model `{id}` does not speak (text to speech); pick one whose catalog purpose is `speak`"),
449                }),
450                // A speaker with no profile yet (cold, its engine hasn't said what it speaks):
451                // its node loads it and checks the request against what the engine reports.
452                Some(m) if m.speech_unknown() => Ok(id.to_string()),
453                Some(m) => match m.speech_covers(needs) {
454                    Ok(()) => Ok(id.to_string()),
455                    Err(lack) => Err(RemoteError::BadRequest { message: format!("model `{id}` {lack}") }),
456                },
457                None => Ok(id.to_string()),
458            };
459        }
460        let mut lacking = Vec::new();
461        let best = self
462            .speakers()
463            .filter(|m| match m.speech_covers(needs) {
464                Ok(()) => true,
465                Err(lack) => {
466                    lacking.push(format!("`{}` {lack}", m.id));
467                    false
468                }
469            })
470            .min_by_key(|m| (rank(m.state), std::cmp::Reverse(m.replicas)))
471            .map(|m| m.id.clone());
472        best.ok_or_else(|| RemoteError::BadRequest {
473            message: if lacking.is_empty() {
474                "no model in the pool speaks (text to speech)".into()
475            } else {
476                format!("no speaker in the pool covers this request: {}", lacking.join("; "))
477            },
478        })
479    }
480
481    /// The text-to-speech models (since 0.5.11).
482    pub fn speakers(&self) -> impl Iterator<Item = &CatalogModel> {
483        self.models.iter().filter(|m| m.speaks())
484    }
485
486    /// The speech-to-text models.
487    pub fn transcribers(&self) -> impl Iterator<Item = &CatalogModel> {
488        self.models.iter().filter(|m| m.transcribes())
489    }
490
491    /// The catalog as a peer before 0.5.8 can read it: without entries whose purpose it lacks.
492    fn for_older(&self) -> Catalog {
493        Catalog { rev: self.rev, models: self.models.iter().filter(|m| m.purpose.before_transcribe()).cloned().collect() }
494    }
495}
496
497/// Asking node to inference node. [`query`] and [`subscribe`] also say that the asker skips
498/// entries it can't read (a field older nodes ignore); a node leaves entries peers before 0.5.8
499/// can't read ([`Purpose::Transcribe`], [`Purpose::Speak`]) out of its answer to a message without it, so an app that
500/// sends this type itself sees no transcription models.
501#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
502#[serde(rename_all = "snake_case")]
503#[non_exhaustive]
504pub enum ClientMsg {
505    Query {
506        #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
507        cert: Option<Vec<u8>>,
508    },
509    Subscribe {
510        #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
511        cert: Option<Vec<u8>>,
512    },
513}
514
515/// Inference node to asking node.
516#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
517#[serde(rename_all = "snake_case")]
518#[non_exhaustive]
519pub enum ServerMsg {
520    Catalog(Catalog),
521    Failed { error: RemoteError },
522}
523
524/// [`ClientMsg`] as sent and read from 0.5.8: `skips_unknown` says the asker skips entries it
525/// can't read. Older nodes ignore the field; older askers leave it out.
526#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
527#[serde(rename_all = "snake_case")]
528enum Ask {
529    Query {
530        #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
531        cert: Option<Vec<u8>>,
532        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
533        skips_unknown: bool,
534    },
535    Subscribe {
536        #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
537        cert: Option<Vec<u8>>,
538        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
539        skips_unknown: bool,
540    },
541}
542
543/// The serving side's catalog (an inference node's merged view).
544pub trait CatalogHost: Send + Sync {
545    fn authorize(&self, caller: &Caller) -> Result<(), RemoteError>;
546
547    /// The catalog for this caller, and its changes.
548    fn watch(&self, caller: &Caller) -> Result<watch::Receiver<Catalog>, RemoteError>;
549
550    /// Whether a subscriber may still follow the catalog (since 0.5.9): asked before every
551    /// update a subscription sends and every [`RECHECK_EVERY`]; an error closes the subscription
552    /// with that refusal. Hosts that admit guests return their current verdict (usually
553    /// [`authorize`](Self::authorize) again) so revoking a guest ends its subscriptions at once.
554    /// Default: `Ok` (admitted once, followed until closed, as before 0.5.9).
555    fn recheck(&self, caller: &Caller) -> Result<(), RemoteError> {
556        let _ = caller;
557        Ok(())
558    }
559}
560
561/// How often a subscription is re-checked when no update comes ([`CatalogHost::recheck`]).
562pub const RECHECK_EVERY: std::time::Duration = std::time::Duration::from_secs(5);
563
564/// A ready [`CatalogHost`]: publish the models, and subscribers hear about it.
565#[derive(Clone)]
566pub struct CatalogFeed {
567    tx: Arc<watch::Sender<Catalog>>,
568    auth: Arc<dyn Authorize>,
569    recheck: bool,
570}
571
572impl CatalogFeed {
573    /// A feed whose callers `auth` admits.
574    pub fn new(auth: Arc<dyn Authorize>) -> Self {
575        Self { tx: Arc::new(watch::channel(Catalog::default()).0), auth, recheck: false }
576    }
577
578    /// Re-check subscribers with the authorizer ([`CatalogHost::recheck`]), so one it stops
579    /// admitting (a revoked guest or device) loses its subscription within [`RECHECK_EVERY`].
580    /// Since 0.5.9; off by default.
581    pub fn rechecking(mut self) -> Self {
582        self.recheck = true;
583        self
584    }
585
586    /// Replaces the models; `rev` goes up by one.
587    pub fn publish(&self, models: Vec<CatalogModel>) {
588        self.tx.send_modify(|c| {
589            c.rev += 1;
590            c.models = models;
591        });
592    }
593
594    pub fn current(&self) -> Catalog {
595        self.tx.borrow().clone()
596    }
597}
598
599impl CatalogHost for CatalogFeed {
600    fn authorize(&self, caller: &Caller) -> Result<(), RemoteError> {
601        self.auth.authorize(caller)
602    }
603
604    fn watch(&self, _caller: &Caller) -> Result<watch::Receiver<Catalog>, RemoteError> {
605        Ok(self.tx.subscribe())
606    }
607
608    fn recheck(&self, caller: &Caller) -> Result<(), RemoteError> {
609        if self.recheck { self.auth.authorize(caller) } else { Ok(()) }
610    }
611}
612
613/// Serve one catalog/1 stream. `caller` is the transport-authenticated peer; the certificate the
614/// request presents is attached when the transport gave none, and the host authorizes it first.
615/// An asker that doesn't say it skips entries it can't read (one before 0.5.8) gets the catalog
616/// without [`Purpose::Transcribe`] and [`Purpose::Speak`] entries, which it could not decode.
617pub async fn serve(mut ch: Channel, caller: Caller, host: &dyn CatalogHost) -> Result<(), RemoteError> {
618    let (cert, follow, skips_unknown) = match ch.recv_cbor::<Ask>().await? {
619        Some(Ask::Query { cert, skips_unknown }) => (cert, false, skips_unknown),
620        Some(Ask::Subscribe { cert, skips_unknown }) => (cert, true, skips_unknown),
621        None => return Ok(()),
622    };
623    let readable = |c: Catalog| if skips_unknown { c } else { c.for_older() };
624    let caller = caller.presenting(cert);
625    let mut rx = match host.authorize(&caller).and_then(|()| host.watch(&caller)) {
626        Ok(rx) => rx,
627        Err(error) => return ch.send_cbor(&ServerMsg::Failed { error }).await,
628    };
629    let now = readable(rx.borrow_and_update().clone());
630    ch.send_cbor(&ServerMsg::Catalog(now)).await?;
631    if !follow {
632        return Ok(());
633    }
634    let mut tick = tokio::time::interval_at(tokio::time::Instant::now() + RECHECK_EVERY, RECHECK_EVERY);
635    tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
636    loop {
637        tokio::select! {
638            changed = rx.changed() => {
639                if changed.is_err() {
640                    return Ok(());
641                }
642                if let Err(error) = host.recheck(&caller) {
643                    return ch.send_cbor(&ServerMsg::Failed { error }).await;
644                }
645                let now = readable(rx.borrow_and_update().clone());
646                ch.send_cbor(&ServerMsg::Catalog(now)).await?;
647            }
648            _ = tick.tick() => {
649                if let Err(error) = host.recheck(&caller) {
650                    return ch.send_cbor(&ServerMsg::Failed { error }).await;
651                }
652            }
653            m = ch.rx.recv() => match m {
654                Ok(Some(_)) => {}
655                Ok(None) | Err(_) => return Ok(()),
656            },
657        }
658    }
659}
660
661/// Asks once.
662pub async fn query(ch: &mut Channel, cert: Option<Vec<u8>>) -> Result<Catalog, RemoteError> {
663    ch.send_cbor(&Ask::Query { cert, skips_unknown: true }).await?;
664    match ch.recv_cbor::<ServerMsg>().await? {
665        Some(ServerMsg::Catalog(c)) => Ok(c),
666        Some(ServerMsg::Failed { error }) => Err(error),
667        None => Err(RemoteError::Closed),
668    }
669}
670
671/// Subscribes and hands every catalog to `on`, until the stream ends (`Ok`) or fails.
672pub async fn subscribe(ch: &mut Channel, cert: Option<Vec<u8>>, mut on: impl FnMut(Catalog)) -> Result<(), RemoteError> {
673    ch.send_cbor(&Ask::Subscribe { cert, skips_unknown: true }).await?;
674    loop {
675        match ch.recv_cbor::<ServerMsg>().await? {
676            Some(ServerMsg::Catalog(c)) => on(c),
677            Some(ServerMsg::Failed { error }) => return Err(error),
678            None => return Ok(()),
679        }
680    }
681}
682
683#[cfg(test)]
684mod tests {
685    use super::*;
686    use crate::remote::memory_pair;
687
688    fn anyone() -> Arc<dyn Authorize> {
689        Arc::new(|_: &Caller| Ok(()))
690    }
691
692    #[test]
693    fn a_pooled_entry_names_its_head_and_members_and_older_entries_read_without_it() {
694        let m = CatalogModel::new("big", Purpose::Chat, ModelState::Loadable)
695            .with_pooled(Pooled::new("m1", vec!["m2".into(), "m1".into()]).with_backend("vllm-ray"));
696        let p = m.pooled.as_ref().unwrap();
697        assert_eq!(p.served_by, "m1");
698        assert_eq!(p.members, ["m1", "m2"], "the head first, once");
699        assert!(m.is_pooled() && !p.up);
700        let json = serde_json::to_value(&m).unwrap();
701        assert_eq!(json["pooled"]["served_by"], "m1");
702        assert_eq!(json["pooled"]["backend"], "vllm-ray");
703        let back: CatalogModel = serde_json::from_value(json).unwrap();
704        assert_eq!(back, m);
705        // An entry from 0.5.12 or earlier has no `pooled`; a plain entry doesn't send one.
706        let old: CatalogModel = serde_json::from_str(r#"{"id":"gemma","purpose":"chat","state":"warm"}"#).unwrap();
707        assert!(!old.is_pooled());
708        assert!(serde_json::to_value(&old).unwrap().get("pooled").is_none());
709    }
710
711    #[tokio::test(start_paused = true)]
712    async fn a_rechecking_feed_closes_subscriptions_it_stops_admitting() {
713        use std::sync::atomic::{AtomicBool, Ordering};
714        let allowed = Arc::new(AtomicBool::new(true));
715        let auth: Arc<dyn Authorize> = {
716            let a = allowed.clone();
717            Arc::new(move |_: &Caller| if a.load(Ordering::SeqCst) { Ok(()) } else { Err(RemoteError::refused("guest-revoked")) })
718        };
719        // On an update: refused before the update is sent.
720        let feed = CatalogFeed::new(auth.clone()).rechecking();
721        feed.publish(vec![CatalogModel::new("gemma", Purpose::Chat, ModelState::Warm)]);
722        let (mut ours, theirs) = memory_pair();
723        let f = feed.clone();
724        tokio::spawn(async move { serve(theirs, Caller::new("guest"), &f).await });
725        let mut seen = Vec::new();
726        let sub = subscribe(&mut ours, None, |c| seen.push(c.rev));
727        let flip = async {
728            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
729            allowed.store(false, Ordering::SeqCst);
730            feed.publish(vec![]);
731        };
732        let (r, ()) = tokio::join!(sub, flip);
733        assert_eq!(r.unwrap_err(), RemoteError::refused("guest-revoked"));
734        assert_eq!(seen, [1], "nothing after the revocation");
735
736        // With no update: refused on the next tick.
737        allowed.store(true, Ordering::SeqCst);
738        let (mut ours, theirs) = memory_pair();
739        let f = feed.clone();
740        tokio::spawn(async move { serve(theirs, Caller::new("guest"), &f).await });
741        let mut seen = 0;
742        let sub = subscribe(&mut ours, None, |_| seen += 1);
743        let flip = async {
744            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
745            allowed.store(false, Ordering::SeqCst);
746        };
747        let started = tokio::time::Instant::now();
748        let (r, ()) = tokio::join!(sub, flip);
749        assert_eq!(r.unwrap_err(), RemoteError::refused("guest-revoked"));
750        assert_eq!(seen, 1);
751        assert!(started.elapsed() <= RECHECK_EVERY + std::time::Duration::from_millis(100));
752
753        // A feed that doesn't re-check (the default) keeps following, as before 0.5.9.
754        allowed.store(true, Ordering::SeqCst);
755        let feed = CatalogFeed::new(auth);
756        let (mut ours, theirs) = memory_pair();
757        let f = feed.clone();
758        tokio::spawn(async move { serve(theirs, Caller::new("guest"), &f).await });
759        let mut seen = 0;
760        let sub = subscribe(&mut ours, None, |_| seen += 1);
761        let flip = async {
762            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
763            allowed.store(false, Ordering::SeqCst);
764            tokio::time::sleep(RECHECK_EVERY * 3).await;
765            feed.publish(vec![]);
766            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
767        };
768        tokio::select! {
769            r = sub => panic!("ended: {r:?}"),
770            () = flip => {}
771        }
772        assert_eq!(seen, 2);
773    }
774
775    #[tokio::test]
776    async fn query_and_subscribe_see_changes() {
777        let feed = CatalogFeed::new(anyone());
778        feed.publish(vec![CatalogModel::new("gemma", Purpose::Chat, ModelState::Warm).with_replicas(2)]);
779        let (mut ours, theirs) = memory_pair();
780        let f = feed.clone();
781        tokio::spawn(async move { serve(theirs, Caller::new("phone"), &f).await });
782        let c = query(&mut ours, None).await.unwrap();
783        assert_eq!(c.rev, 1);
784        assert_eq!(c.find("gemma").unwrap().replicas, 2);
785
786        let (mut ours, theirs) = memory_pair();
787        let f = feed.clone();
788        tokio::spawn(async move { serve(theirs, Caller::new("phone"), &f).await });
789        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
790        tokio::spawn(async move { subscribe(&mut ours, None, |c| tx.send(c).unwrap()).await });
791        assert_eq!(rx.recv().await.unwrap().rev, 1);
792        feed.publish(vec![CatalogModel::new("gemma", Purpose::Chat, ModelState::Loading)]);
793        let next = rx.recv().await.unwrap();
794        assert_eq!((next.rev, next.models[0].state), (2, ModelState::Loading));
795    }
796
797    #[tokio::test]
798    async fn the_host_authorizes_with_the_presented_cert() {
799        let auth: Arc<dyn Authorize> = Arc::new(|c: &Caller| {
800            if c.peer == "laptop" && c.cert_bytes.as_deref() == Some(b"cert") { Ok(()) } else { Err(RemoteError::refused("unknown-device")) }
801        });
802        let feed = CatalogFeed::new(auth);
803        for (peer, cert, ok) in [("laptop", Some(b"cert".to_vec()), true), ("laptop", None, false), ("stranger", Some(b"cert".to_vec()), false)] {
804            let (mut ours, theirs) = memory_pair();
805            let f = feed.clone();
806            tokio::spawn(async move { serve(theirs, Caller::new(peer), &f).await });
807            let r = query(&mut ours, cert).await;
808            assert_eq!(r.is_ok(), ok, "{peer}");
809            if !ok {
810                assert_eq!(r.unwrap_err(), RemoteError::refused("unknown-device"));
811            }
812        }
813    }
814
815    #[test]
816    fn route_keeps_image_requests_off_text_only_models() {
817        let c = Catalog::new(
818            1,
819            vec![
820                CatalogModel::new("qwen", Purpose::Chat, ModelState::Warm),
821                CatalogModel::new("gemma-cold", Purpose::Chat, ModelState::Loadable).with_inputs(Modalities::new(true, true)),
822                CatalogModel::new("gemma", Purpose::Chat, ModelState::Warm).with_inputs(Modalities::VISION),
823                CatalogModel::new("embed", Purpose::Embedding, ModelState::Warm).with_inputs(Modalities::new(true, true)),
824            ],
825        );
826        assert_eq!(c.route(None, Modalities::TEXT).unwrap(), None);
827        assert_eq!(c.route(Some("qwen"), Modalities::TEXT).unwrap().as_deref(), Some("qwen"));
828        assert_eq!(c.route(None, Modalities::VISION).unwrap().as_deref(), Some("gemma"), "warm first");
829        assert_eq!(c.route(None, Modalities::AUDIO).unwrap().as_deref(), Some("gemma-cold"));
830        let e = c.route(Some("qwen"), Modalities::VISION).unwrap_err();
831        assert!(matches!(&e, RemoteError::BadRequest { message } if message.contains("`qwen` does not take images")), "{e}");
832        assert_eq!(c.route(Some("not-listed"), Modalities::VISION).unwrap().as_deref(), Some("not-listed"));
833        let text_only = Catalog::new(1, vec![CatalogModel::new("qwen", Purpose::Chat, ModelState::Warm)]);
834        let e = text_only.route(None, Modalities::new(true, true)).unwrap_err();
835        assert!(matches!(&e, RemoteError::BadRequest { message } if message == "no model in the pool takes images and audio"), "{e}");
836    }
837
838    #[test]
839    fn route_sends_video_only_to_models_that_read_it() {
840        let both = Modalities::new(true, true);
841        let c = Catalog::new(
842            1,
843            vec![
844                CatalogModel::new("gemma", Purpose::Chat, ModelState::Warm).with_inputs(both),
845                CatalogModel::new("qwen-vl-cold", Purpose::Chat, ModelState::Loadable).with_inputs(Modalities::VISION.with_video(true)),
846                CatalogModel::new("qwen-vl", Purpose::Chat, ModelState::Busy).with_replicas(2).with_inputs(Modalities::VISION.with_video(true)),
847                CatalogModel::new("omni", Purpose::Chat, ModelState::Loadable).with_inputs(both.with_video(true)),
848                CatalogModel::new("embed", Purpose::Embedding, ModelState::Warm).with_inputs(both.with_video(true)),
849                CatalogModel::new("whisper", Purpose::Transcribe, ModelState::Warm).with_inputs(Modalities::AUDIO.with_video(true)),
850            ],
851        );
852        assert_eq!(c.route(None, Modalities::VIDEO).unwrap().as_deref(), Some("qwen-vl"), "busy before loadable; never embed or transcribe");
853        assert_eq!(c.route(None, Modalities::VIDEO.union(Modalities::AUDIO)).unwrap().as_deref(), Some("omni"));
854        assert_eq!(c.route(None, Modalities::VISION).unwrap().as_deref(), Some("gemma"), "image routing unchanged");
855        assert_eq!(c.route(Some("qwen-vl-cold"), Modalities::VIDEO).unwrap().as_deref(), Some("qwen-vl-cold"));
856        let e = c.route(Some("gemma"), Modalities::VIDEO).unwrap_err();
857        assert!(
858            matches!(&e, RemoteError::BadRequest { message } if message.contains("`gemma` does not take video") && message.ends_with(VIDEO_FALLBACK)),
859            "{e}"
860        );
861        let e = c.route(Some("qwen-vl"), Modalities::VIDEO.union(Modalities::AUDIO)).unwrap_err();
862        assert!(
863            matches!(&e, RemoteError::BadRequest { message } if message.contains("does not take audio") && !message.contains(VIDEO_FALLBACK)),
864            "{e}"
865        );
866        assert_eq!(c.route(Some("not-listed"), Modalities::VIDEO).unwrap().as_deref(), Some("not-listed"), "left to the node");
867        let no_video = Catalog::new(1, vec![CatalogModel::new("gemma", Purpose::Chat, ModelState::Warm).with_inputs(both)]);
868        let e = no_video.route(None, Modalities::VIDEO).unwrap_err();
869        assert!(
870            matches!(&e, RemoteError::BadRequest { message } if message == &format!("no model in the pool takes video; {VIDEO_FALLBACK}")),
871            "{e}"
872        );
873        let e = no_video.route(None, Modalities::VISION).unwrap();
874        assert_eq!(e.as_deref(), Some("gemma"));
875    }
876
877    #[test]
878    fn video_input_is_optional_and_old_entries_read_as_no_video() {
879        // A 0.5.9 node's entry (JSON or CBOR) has no `video`: the model does not read video.
880        let old: CatalogModel = serde_json::from_str(r#"{"id":"qwen-vl","state":"warm","inputs":{"vision":true,"audio":true}}"#).unwrap();
881        assert_eq!(old.inputs, Modalities::new(true, true));
882        assert!(!old.accepts(Modalities::VIDEO) && old.accepts(Modalities::VISION));
883        let entry = CatalogModel::new("gemma", Purpose::Chat, ModelState::Warm).with_inputs(Modalities::VISION);
884        let j = serde_json::to_value(&entry).unwrap();
885        assert_eq!(j["inputs"], serde_json::json!({"vision": true}), "no video key unless it reads video");
886        // A video entry round-trips, and a video-only one keeps its inputs on the wire.
887        let v = CatalogModel::new("qwen-vl", Purpose::Chat, ModelState::Warm)
888            .with_inputs(Modalities::VISION.with_video(true))
889            .with_limits(MediaLimits::new().with_video_max_seconds(60).with_video_max_bytes(16 << 20).with_video_frames_per_minute(120));
890        assert_eq!(serde_json::to_value(&v).unwrap()["inputs"], serde_json::json!({"vision": true, "video": true}));
891        assert_eq!(crate::remote::from_cbor::<CatalogModel>(&crate::remote::to_cbor(&v).unwrap()).unwrap(), v);
892        assert_eq!(
893            serde_json::to_value(&v).unwrap()["limits"],
894            serde_json::json!({"video_max_seconds": 60, "video_max_bytes": 16777216, "video_frames_per_minute": 120})
895        );
896        let only = CatalogModel::new("clip", Purpose::Chat, ModelState::Warm).with_inputs(Modalities::VIDEO);
897        assert_eq!(serde_json::to_value(&only).unwrap()["inputs"], serde_json::json!({"video": true}));
898        assert_eq!(crate::remote::from_cbor::<CatalogModel>(&crate::remote::to_cbor(&only).unwrap()).unwrap(), only);
899        // A whole catalog with video entries still reads on a 0.5.9-shaped peer, which keeps the
900        // entry and drops the field.
901        #[derive(Deserialize)]
902        struct OldInputs {
903            #[serde(default)]
904            vision: bool,
905        }
906        #[derive(Deserialize)]
907        struct OldEntry {
908            id: String,
909            #[serde(default)]
910            inputs: Option<OldInputs>,
911        }
912        let seen: OldEntry = crate::remote::from_cbor(&crate::remote::to_cbor(&v).unwrap()).unwrap();
913        assert_eq!((seen.id.as_str(), seen.inputs.map(|i| i.vision)), ("qwen-vl", Some(true)));
914    }
915
916    #[test]
917    fn inputs_are_optional_on_the_wire() {
918        let plain = CatalogModel::new("qwen", Purpose::Chat, ModelState::Warm);
919        let b = crate::remote::to_cbor(&plain).unwrap();
920        assert!(!b.windows(6).any(|w| w == b"inputs"), "text-only entries look as before");
921        let v = CatalogModel::new("gemma", Purpose::Chat, ModelState::Warm).with_inputs(Modalities::VISION);
922        assert_eq!(crate::remote::from_cbor::<CatalogModel>(&crate::remote::to_cbor(&v).unwrap()).unwrap(), v);
923    }
924
925    #[test]
926    fn base_is_optional_on_the_wire() {
927        let plain = CatalogModel::new("qwen", Purpose::Chat, ModelState::Warm);
928        let b = crate::remote::to_cbor(&plain).unwrap();
929        assert!(!b.windows(4).any(|w| w == b"base"), "models look as before");
930        assert!(!plain.is_adapter());
931        let a = CatalogModel::new("qwen+tune", Purpose::Chat, ModelState::Warm).with_base("qwen");
932        assert!(a.is_adapter());
933        assert_eq!(crate::remote::from_cbor::<CatalogModel>(&crate::remote::to_cbor(&a).unwrap()).unwrap(), a);
934    }
935
936    /// A catalog/1 entry as a 0.5.3 node sends it (and reads it): no origin or license.
937    #[derive(Debug, PartialEq, Serialize, Deserialize)]
938    struct OldModel {
939        id: String,
940        #[serde(default)]
941        purpose: Purpose,
942        #[serde(default)]
943        state: ModelState,
944        #[serde(default)]
945        replicas: u32,
946        #[serde(default, skip_serializing_if = "Option::is_none")]
947        revision: Option<String>,
948        #[serde(default, skip_serializing_if = "Option::is_none")]
949        base: Option<String>,
950    }
951
952    #[test]
953    fn origin_and_license_are_optional_on_the_wire() {
954        let plain = CatalogModel::new("qwen", Purpose::Chat, ModelState::Warm);
955        let b = crate::remote::to_cbor(&plain).unwrap();
956        assert!(!b.windows(6).any(|w| w == b"origin"), "entries without an origin look as before");
957        assert!(!b.windows(7).any(|w| w == b"license"), "entries without a license look as before");
958        let m = CatalogModel::new("qwen+tune", Purpose::Chat, ModelState::Warm).with_origin(ORIGIN_TRAIN).with_license("Apache-2.0");
959        assert_eq!((m.origin.as_deref(), m.license.as_deref()), (Some("train"), Some("Apache-2.0")));
960        assert_eq!(crate::remote::from_cbor::<CatalogModel>(&crate::remote::to_cbor(&m).unwrap()).unwrap(), m);
961    }
962
963    #[test]
964    fn old_peers_read_and_send_entries_without_origin() {
965        // An old node's entry reads with neither field.
966        let old =
967            OldModel { id: "qwen".into(), purpose: Purpose::Chat, state: ModelState::Warm, replicas: 1, revision: Some("abc".into()), base: None };
968        let m = crate::remote::from_cbor::<CatalogModel>(&crate::remote::to_cbor(&old).unwrap()).unwrap();
969        assert_eq!((m.origin, m.license, m.revision.as_deref()), (None, None, Some("abc")));
970        // A new node's entry with both fields still reads on an old peer, which skips them.
971        let new = CatalogModel::new("qwen", Purpose::Chat, ModelState::Warm).with_replicas(1).with_origin(ORIGIN_UPLOAD).with_license("unknown");
972        let seen = crate::remote::from_cbor::<OldModel>(&crate::remote::to_cbor(&new).unwrap()).unwrap();
973        assert_eq!(seen, OldModel { revision: None, ..old });
974        // And a whole catalog message from a new node reads on an old peer's catalog type.
975        let msg = ServerMsg::Catalog(Catalog::new(3, vec![new]));
976        assert!(matches!(
977            crate::remote::from_cbor::<ServerMsg>(&crate::remote::to_cbor(&msg).unwrap()).unwrap(),
978            ServerMsg::Catalog(c) if c.models[0].origin.as_deref() == Some("upload")
979        ));
980    }
981
982    #[test]
983    fn limits_round_trip_and_stay_off_the_wire_when_unknown() {
984        let plain = CatalogModel::new("qwen", Purpose::Chat, ModelState::Warm).with_context(8192);
985        let b = crate::remote::to_cbor(&plain).unwrap();
986        assert!(!b.windows(6).any(|w| w == b"limits"), "entries without limits look as before");
987        assert!(!serde_json::to_string(&plain).unwrap().contains("limits"));
988        let limits = MediaLimits::new()
989            .with_max_images(8)
990            .with_image_tokens(256)
991            .with_image_edge(896)
992            .with_audio_max_seconds(30)
993            .with_audio_tokens_per_minute(1500)
994            .with_max_request_bytes(32 << 20);
995        let m = CatalogModel::new("gemma", Purpose::Chat, ModelState::Warm).with_inputs(Modalities::new(true, true)).with_limits(limits);
996        assert_eq!(crate::remote::from_cbor::<CatalogModel>(&crate::remote::to_cbor(&m).unwrap()).unwrap(), m);
997        assert_eq!(serde_json::from_str::<CatalogModel>(&serde_json::to_string(&m).unwrap()).unwrap(), m);
998        let j = serde_json::to_value(&m).unwrap();
999        assert_eq!(j["limits"]["max_images"], 8);
1000        assert_eq!(j["limits"]["max_request_bytes"], 32 << 20);
1001        assert!(j["limits"].get("image_patch").is_none(), "unknown fields stay off");
1002        // Only some limits known: the rest stay absent.
1003        let some = CatalogModel::new("llava", Purpose::Chat, ModelState::Warm).with_limits(MediaLimits::new().with_image_tokens(576));
1004        let back = crate::remote::from_cbor::<CatalogModel>(&crate::remote::to_cbor(&some).unwrap()).unwrap();
1005        assert_eq!((back.limits.image_tokens, back.limits.max_images), (Some(576), None));
1006    }
1007
1008    #[test]
1009    fn old_peers_read_and_send_entries_without_limits() {
1010        // JSON and CBOR from a node before 0.5.7 read with no limits.
1011        let old_json = r#"{"id":"qwen","purpose":"chat","state":"warm","replicas":1,"context":4096,"inputs":{"vision":true}}"#;
1012        let m: CatalogModel = serde_json::from_str(old_json).unwrap();
1013        assert!(m.limits.is_unknown());
1014        assert_eq!(m.context, Some(4096));
1015        let old =
1016            OldModel { id: "qwen".into(), purpose: Purpose::Chat, state: ModelState::Warm, replicas: 1, revision: Some("abc".into()), base: None };
1017        let m = crate::remote::from_cbor::<CatalogModel>(&crate::remote::to_cbor(&old).unwrap()).unwrap();
1018        assert!(m.limits.is_unknown());
1019        // A new entry with limits still reads on an old peer, which skips them.
1020        let new = CatalogModel::new("qwen", Purpose::Chat, ModelState::Warm)
1021            .with_replicas(1)
1022            .with_limits(MediaLimits::new().with_max_images(2).with_max_request_bytes(1 << 20));
1023        let seen = crate::remote::from_cbor::<OldModel>(&crate::remote::to_cbor(&new).unwrap()).unwrap();
1024        assert_eq!(seen, OldModel { revision: None, ..old });
1025        let msg = ServerMsg::Catalog(Catalog::new(4, vec![new]));
1026        assert!(matches!(
1027            crate::remote::from_cbor::<ServerMsg>(&crate::remote::to_cbor(&msg).unwrap()).unwrap(),
1028            ServerMsg::Catalog(c) if c.models[0].limits.max_images == Some(2)
1029        ));
1030    }
1031
1032    #[test]
1033    fn wire_is_cbor_with_byte_string_certs() {
1034        let m = ClientMsg::Query { cert: Some(vec![1, 2, 3]) };
1035        let b = crate::remote::to_cbor(&m).unwrap();
1036        // map(1) "query" map(1) "cert" bytes(3)
1037        assert!(b.windows(4).any(|w| w == [0x43, 1, 2, 3]), "{b:x?}");
1038        assert_eq!(crate::remote::from_cbor::<ClientMsg>(&b).unwrap(), m);
1039    }
1040
1041    fn transcribe_catalog() -> Catalog {
1042        Catalog::new(
1043            7,
1044            vec![
1045                CatalogModel::new("gemma", Purpose::Chat, ModelState::Warm).with_inputs(Modalities::new(true, true)),
1046                CatalogModel::new("nomic", Purpose::Embedding, ModelState::Warm),
1047                CatalogModel::new("voxtral-cold", Purpose::Transcribe, ModelState::Loadable).with_inputs(Modalities::new(false, true)),
1048                CatalogModel::new("voxtral", Purpose::Transcribe, ModelState::Warm).with_replicas(1).with_inputs(Modalities::new(false, true)),
1049                CatalogModel::new("whisper", Purpose::Transcribe, ModelState::Warm).with_replicas(2),
1050            ],
1051        )
1052    }
1053
1054    #[test]
1055    fn transcribe_purpose_names_match_weirdnet_model() {
1056        for (p, name) in [(Purpose::Chat, "chat"), (Purpose::Embedding, "embedding"), (Purpose::Transcribe, "transcribe")] {
1057            assert_eq!(p.as_str(), name);
1058            assert_eq!(p.to_string(), name);
1059            assert_eq!(Purpose::parse(name), Some(p));
1060            assert_eq!(serde_json::to_string(&p).unwrap(), format!("\"{name}\""));
1061            assert_eq!(serde_json::from_str::<Purpose>(&format!("\"{name}\"")).unwrap(), p);
1062            assert_eq!(crate::remote::from_cbor::<Purpose>(&crate::remote::to_cbor(&p).unwrap()).unwrap(), p);
1063        }
1064        assert_eq!(Purpose::parse("speech"), None);
1065        let m = CatalogModel::new("voxtral", Purpose::Transcribe, ModelState::Warm);
1066        assert!(m.transcribes() && !m.accepts(Modalities::TEXT) && !m.accepts(Modalities::AUDIO));
1067    }
1068
1069    #[test]
1070    fn route_transcribe_picks_the_best_transcriber() {
1071        let c = transcribe_catalog();
1072        // Warm before loadable, then more replicas.
1073        assert_eq!(c.route_transcribe(None).unwrap(), "whisper");
1074        assert_eq!(c.transcribers().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["voxtral-cold", "voxtral", "whisper"]);
1075        assert_eq!(c.route_transcribe(Some("voxtral-cold")).unwrap(), "voxtral-cold");
1076        // A model the catalog doesn't list is left to the node.
1077        assert_eq!(c.route_transcribe(Some("elsewhere")).unwrap(), "elsewhere");
1078        for id in ["gemma", "nomic"] {
1079            let e = c.route_transcribe(Some(id)).unwrap_err();
1080            assert!(matches!(&e, RemoteError::BadRequest { message } if message.contains(id) && message.contains("transcribe")), "{e:?}");
1081        }
1082        let none = Catalog::new(1, vec![CatalogModel::new("gemma", Purpose::Chat, ModelState::Warm)]);
1083        assert!(matches!(none.route_transcribe(None), Err(RemoteError::BadRequest { message }) if message.contains("transcribes")));
1084    }
1085
1086    #[test]
1087    fn chat_routing_never_picks_a_transcriber() {
1088        let c = Catalog::new(1, vec![CatalogModel::new("voxtral", Purpose::Transcribe, ModelState::Warm).with_inputs(Modalities::new(false, true))]);
1089        assert!(matches!(c.route(None, Modalities::AUDIO), Err(RemoteError::BadRequest { .. })));
1090        assert!(matches!(c.route(Some("voxtral"), Modalities::AUDIO), Err(RemoteError::BadRequest { .. })));
1091        assert_eq!(transcribe_catalog().route(None, Modalities::AUDIO).unwrap().as_deref(), Some("gemma"));
1092    }
1093
1094    #[test]
1095    fn transcribers_round_trip_and_unreadable_entries_are_skipped() {
1096        let c = transcribe_catalog();
1097        assert_eq!(crate::remote::from_cbor::<Catalog>(&crate::remote::to_cbor(&c).unwrap()).unwrap(), c);
1098        assert_eq!(serde_json::from_str::<Catalog>(&serde_json::to_string(&c).unwrap()).unwrap(), c);
1099        // An entry from a newer version (an unknown purpose) is skipped, not fatal.
1100        let json = r#"{"rev":3,"models":[{"id":"a","purpose":"chat","tokens_per_sec":12.5},{"id":"b","purpose":"diarize"},{"id":"c","purpose":"transcribe"}]}"#;
1101        let read: Catalog = serde_json::from_str(json).unwrap();
1102        assert_eq!(read.models.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["a", "c"]);
1103        assert_eq!(read.models[0].tokens_per_sec, Some(12.5));
1104        let v: serde_json::Value = serde_json::from_str(json).unwrap();
1105        let read: Catalog = crate::remote::from_cbor(&crate::remote::to_cbor(&v).unwrap()).unwrap();
1106        assert_eq!(read.models.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["a", "c"]);
1107        // The whole entry still round-trips through CBOR with every field set.
1108        let full = Catalog::new(
1109            9,
1110            vec![
1111                CatalogModel::new("q", Purpose::Chat, ModelState::Busy)
1112                    .with_speed(31.25)
1113                    .with_context(8192)
1114                    .with_base("base")
1115                    .with_origin(ORIGIN_UPLOAD)
1116                    .with_license("MIT")
1117                    .with_limits(MediaLimits::new().with_max_images(4).with_max_request_bytes(1 << 25)),
1118            ],
1119        );
1120        assert_eq!(crate::remote::from_cbor::<Catalog>(&crate::remote::to_cbor(&full).unwrap()).unwrap(), full);
1121    }
1122
1123    /// The purposes a peer before 0.5.8 knows, and its strict catalog.
1124    #[derive(Debug, PartialEq, Deserialize)]
1125    #[serde(rename_all = "snake_case")]
1126    enum OldPurpose {
1127        Chat,
1128        Embedding,
1129    }
1130
1131    #[derive(Debug, Deserialize)]
1132    struct OldEntry {
1133        id: String,
1134        #[allow(dead_code)]
1135        purpose: OldPurpose,
1136    }
1137
1138    #[derive(Debug, Deserialize)]
1139    struct OldCatalog {
1140        models: Vec<OldEntry>,
1141    }
1142
1143    #[derive(Debug, Deserialize)]
1144    #[serde(rename_all = "snake_case")]
1145    enum OldServerMsg {
1146        Catalog(OldCatalog),
1147    }
1148
1149    #[tokio::test]
1150    async fn older_askers_get_the_catalog_without_transcribers() {
1151        let feed = CatalogFeed::new(anyone());
1152        feed.publish(transcribe_catalog().models);
1153        // An old peer could not read the full catalog at all.
1154        assert!(crate::remote::from_cbor::<OldServerMsg>(&crate::remote::to_cbor(&ServerMsg::Catalog(feed.current())).unwrap()).is_err());
1155
1156        for follow in [false, true] {
1157            // An asker before 0.5.8 sends plain `ClientMsg`s.
1158            let (mut ours, theirs) = memory_pair();
1159            let f = feed.clone();
1160            tokio::spawn(async move { serve(theirs, Caller::new("phone"), &f).await });
1161            let ask = if follow { ClientMsg::Subscribe { cert: None } } else { ClientMsg::Query { cert: None } };
1162            ours.send_cbor(&ask).await.unwrap();
1163            let bytes = ours.rx.recv().await.unwrap().unwrap();
1164            let OldServerMsg::Catalog(old) = crate::remote::from_cbor::<OldServerMsg>(&bytes).unwrap();
1165            assert_eq!(old.models.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["gemma", "nomic"]);
1166        }
1167
1168        // 0.5.8 askers see everything, on query and on every change.
1169        let (mut ours, theirs) = memory_pair();
1170        let f = feed.clone();
1171        tokio::spawn(async move { serve(theirs, Caller::new("phone"), &f).await });
1172        assert_eq!(query(&mut ours, None).await.unwrap().transcribers().count(), 3);
1173        let (mut ours, theirs) = memory_pair();
1174        let f = feed.clone();
1175        tokio::spawn(async move { serve(theirs, Caller::new("phone"), &f).await });
1176        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
1177        tokio::spawn(async move { subscribe(&mut ours, None, |c| tx.send(c).unwrap()).await });
1178        assert_eq!(rx.recv().await.unwrap().models.len(), 5);
1179        feed.publish(vec![CatalogModel::new("whisper", Purpose::Transcribe, ModelState::Busy)]);
1180        assert_eq!(rx.recv().await.unwrap().route_transcribe(None).unwrap(), "whisper");
1181    }
1182
1183    #[test]
1184    fn the_new_ask_reads_on_old_nodes_and_old_asks_read_on_new_ones() {
1185        let new = Ask::Query { cert: Some(vec![1, 2]), skips_unknown: true };
1186        assert_eq!(
1187            crate::remote::from_cbor::<ClientMsg>(&crate::remote::to_cbor(&new).unwrap()).unwrap(),
1188            ClientMsg::Query { cert: Some(vec![1, 2]) }
1189        );
1190        let new = Ask::Subscribe { cert: None, skips_unknown: true };
1191        assert_eq!(crate::remote::from_cbor::<ClientMsg>(&crate::remote::to_cbor(&new).unwrap()).unwrap(), ClientMsg::Subscribe { cert: None });
1192        let old = ClientMsg::Subscribe { cert: Some(vec![3]) };
1193        assert_eq!(
1194            crate::remote::from_cbor::<Ask>(&crate::remote::to_cbor(&old).unwrap()).unwrap(),
1195            Ask::Subscribe { cert: Some(vec![3]), skips_unknown: false }
1196        );
1197        // Unset, the flag stays off the wire: the bytes are what 0.5.7 sends.
1198        let quiet = Ask::Query { cert: None, skips_unknown: false };
1199        assert_eq!(crate::remote::to_cbor(&quiet).unwrap(), crate::remote::to_cbor(&ClientMsg::Query { cert: None }).unwrap());
1200    }
1201
1202    fn speak_catalog() -> Catalog {
1203        use crate::speech::{AudioFormat, CloneMode};
1204        let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
1205        Catalog::new(
1206            4,
1207            vec![
1208                CatalogModel::new("gemma", Purpose::Chat, ModelState::Warm),
1209                CatalogModel::new("voxtral", Purpose::Transcribe, ModelState::Warm),
1210                CatalogModel::new("kokoro", Purpose::Speak, ModelState::Warm).with_speech(
1211                    SpeechProfile::new()
1212                        .with_presets(s(&["af_heart", "am_adam"]))
1213                        .with_raw(true)
1214                        .with_speed(true)
1215                        .with_formats(vec![AudioFormat::Wav, AudioFormat::Pcm16]),
1216                ),
1217                CatalogModel::new("qwen3-tts-base", Purpose::Speak, ModelState::Loadable)
1218                    .with_speech(SpeechProfile::new().with_clone(CloneMode::AudioAndText).with_formats(vec![AudioFormat::Wav, AudioFormat::Mp3])),
1219                CatalogModel::new("qwen3-tts-base-2", Purpose::Speak, ModelState::Warm)
1220                    .with_replicas(2)
1221                    .with_speech(SpeechProfile::new().with_clone(CloneMode::AudioAndText).with_formats(vec![AudioFormat::Wav])),
1222                CatalogModel::new("plain-tts", Purpose::Speak, ModelState::Busy),
1223            ],
1224        )
1225    }
1226
1227    #[test]
1228    fn speak_purpose_names_match_weirdnet_model() {
1229        assert_eq!((Purpose::Speak.as_str(), Purpose::parse("speak")), ("speak", Some(Purpose::Speak)));
1230        assert_eq!(serde_json::to_value(Purpose::Speak).unwrap(), serde_json::json!("speak"));
1231        let m = CatalogModel::new("kokoro", Purpose::Speak, ModelState::Warm);
1232        assert!(m.speaks() && !m.transcribes() && !m.accepts(Modalities::TEXT));
1233        assert!(CatalogModel::new("gemma", Purpose::Chat, ModelState::Warm).speech_covers(&SpeechNeeds::new()).is_err());
1234        // No profile: only the plainest request.
1235        assert!(m.speech_covers(&SpeechNeeds::new().with_input_chars(4)).is_ok());
1236        assert!(m.speech_covers(&SpeechNeeds::new().with_preset("af_heart")).is_err());
1237    }
1238
1239    #[test]
1240    fn route_speak_picks_a_speaker_that_covers_the_request() {
1241        use crate::speech::AudioFormat;
1242        let c = speak_catalog();
1243        assert_eq!(c.speakers().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["kokoro", "qwen3-tts-base", "qwen3-tts-base-2", "plain-tts"]);
1244        let plain = SpeechNeeds::new().with_input_chars(12);
1245        assert_eq!(c.route_speak(None, &plain).unwrap(), "qwen3-tts-base-2", "warm, then more replicas");
1246        assert_eq!(c.route_speak(None, &SpeechNeeds::new().with_preset("am_adam")).unwrap(), "kokoro");
1247        assert_eq!(c.route_speak(None, &SpeechNeeds::new().with_clone(false)).unwrap(), "qwen3-tts-base-2");
1248        assert_eq!(c.route_speak(None, &SpeechNeeds::new().with_clone(true).with_format(AudioFormat::Mp3)).unwrap(), "qwen3-tts-base");
1249        // Named: must speak and cover; unknown names are the node's call.
1250        assert_eq!(c.route_speak(Some("kokoro"), &SpeechNeeds::new().with_raw()).unwrap(), "kokoro");
1251        assert_eq!(c.route_speak(Some("elsewhere"), &plain).unwrap(), "elsewhere");
1252        let bad = |model: Option<&str>, needs: SpeechNeeds, what: &[&str]| {
1253            let e = c.route_speak(model, &needs).unwrap_err();
1254            let RemoteError::BadRequest { message } = &e else { panic!("{e:?}") };
1255            for w in what {
1256                assert!(message.contains(w), "{message}");
1257            }
1258        };
1259        bad(Some("gemma"), plain.clone(), &["`gemma`", "does not speak", "`speak`"]);
1260        bad(Some("voxtral"), plain.clone(), &["`voxtral`", "does not speak"]);
1261        bad(Some("kokoro"), SpeechNeeds::new().with_preset("alloy"), &["model `kokoro`", "`alloy`", "af_heart, am_adam"]);
1262        bad(Some("kokoro"), SpeechNeeds::new().with_clone(true), &["model `kokoro` does not clone voices"]);
1263        // Named but with no profile yet (cold, unknown to the catalog): the node's call, so a
1264        // preset voice isn't refused before the speaker loads and reports its voices.
1265        assert!(c.find("plain-tts").unwrap().speech_unknown() && !c.find("kokoro").unwrap().speech_unknown());
1266        assert_eq!(c.route_speak(Some("plain-tts"), &SpeechNeeds::new().with_preset("af_heart")).unwrap(), "plain-tts");
1267        let empty = Catalog::new(1, vec![CatalogModel::new("cold", Purpose::Speak, ModelState::Loadable).with_speech(SpeechProfile::new())]);
1268        assert_eq!(empty.route_speak(Some("cold"), &SpeechNeeds::new().with_preset("af_heart").with_clone(true)).unwrap(), "cold");
1269        // Not named: a speaker whose profile is known to cover the request is still required.
1270        bad(None, SpeechNeeds::new().with_preset("bf_emma"), &["no speaker in the pool covers", "`plain-tts` has no preset voices"]);
1271        bad(None, SpeechNeeds::new().with_design(), &["no speaker in the pool", "`kokoro` does not design", "`plain-tts` does not design"]);
1272        let none = Catalog::new(1, vec![CatalogModel::new("gemma", Purpose::Chat, ModelState::Warm)]);
1273        assert_eq!(
1274            none.route_speak(None, &plain).unwrap_err(),
1275            RemoteError::BadRequest { message: "no model in the pool speaks (text to speech)".into() }
1276        );
1277        // Chat and transcription routing never pick a speaker.
1278        let only = Catalog::new(1, vec![CatalogModel::new("kokoro", Purpose::Speak, ModelState::Warm).with_inputs(Modalities::AUDIO)]);
1279        assert!(only.route(None, Modalities::AUDIO).is_err());
1280        assert!(only.route_transcribe(None).is_err());
1281    }
1282
1283    #[test]
1284    fn speakers_round_trip_and_older_readers_skip_them() {
1285        let c = speak_catalog();
1286        assert_eq!(crate::remote::from_cbor::<Catalog>(&crate::remote::to_cbor(&c).unwrap()).unwrap(), c);
1287        assert_eq!(serde_json::from_str::<Catalog>(&serde_json::to_string(&c).unwrap()).unwrap(), c);
1288        // Without a profile, nothing of it on the wire.
1289        let v = serde_json::to_value(CatalogModel::new("plain-tts", Purpose::Speak, ModelState::Busy)).unwrap();
1290        assert!(v.get("speech").is_none(), "{v}");
1291        // A 0.5.8-0.5.10 reader doesn't know `speak`: the entry fails to decode, so it skips it
1292        // (as this version skips the unknown `diarize`), and reads the rest.
1293        #[derive(Debug, Deserialize)]
1294        #[serde(rename_all = "snake_case")]
1295        #[allow(dead_code)]
1296        enum Purpose0510 {
1297            Chat,
1298            Embedding,
1299            Transcribe,
1300        }
1301        #[derive(Debug, Deserialize)]
1302        #[allow(dead_code)]
1303        struct Entry0510 {
1304            id: String,
1305            purpose: Purpose0510,
1306        }
1307        let entries = serde_json::to_value(&c).unwrap()["models"].as_array().unwrap().clone();
1308        let readable: Vec<String> = entries.into_iter().filter_map(|e| serde_json::from_value::<Entry0510>(e).ok()).map(|e| e.id).collect();
1309        assert_eq!(readable, ["gemma", "voxtral"]);
1310        assert_eq!(c.for_older().models.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["gemma"]);
1311    }
1312
1313    #[tokio::test]
1314    async fn older_askers_get_the_catalog_without_speakers() {
1315        let feed = CatalogFeed::new(anyone());
1316        feed.publish(speak_catalog().models);
1317        assert!(crate::remote::from_cbor::<OldServerMsg>(&crate::remote::to_cbor(&ServerMsg::Catalog(feed.current())).unwrap()).is_err());
1318        let (mut ours, theirs) = memory_pair();
1319        let f = feed.clone();
1320        tokio::spawn(async move { serve(theirs, Caller::new("phone"), &f).await });
1321        ours.send_cbor(&ClientMsg::Query { cert: None }).await.unwrap();
1322        let bytes = ours.rx.recv().await.unwrap().unwrap();
1323        let OldServerMsg::Catalog(old) = crate::remote::from_cbor::<OldServerMsg>(&bytes).unwrap();
1324        assert_eq!(old.models.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["gemma"]);
1325        // This version's askers get the speakers with their profiles.
1326        let (mut ours, theirs) = memory_pair();
1327        let f = feed.clone();
1328        tokio::spawn(async move { serve(theirs, Caller::new("phone"), &f).await });
1329        let c = query(&mut ours, None).await.unwrap();
1330        assert_eq!(c.speakers().count(), 4);
1331        assert_eq!(c.find("kokoro").unwrap().speech, speak_catalog().find("kokoro").unwrap().speech);
1332    }
1333}