Skip to main content

weirdnet_backends/
models.rs

1//! `/weirdnet-backends/models/1`: the owner manages a model node's model files over
2//! `weirdnet-net`: search the Hugging Face Hub, see which files fit the node, pull one (split
3//! GGUFs too) and serve it without a restart, list and remove what is on disk.
4//!
5//! Only the owner may use it: [`ModelsService`] takes an [`Authorize`] and runs nothing before
6//! it admits the caller. Pass `weirdnet_agent::serve::RosterAuth` for the owner's linked devices
7//! (with `require_roles` to narrow it to devices holding a role the owner granted).
8//!
9//! The Hugging Face token never travels: the node uses its own ([`ModelStore::from_env`]), and
10//! nothing in this protocol carries one.
11//!
12//! Each stream carries one [`ModelsRequest`] (CBOR, with the caller's certificate) and its
13//! answers ([`ModelsReply`]): one answer, or for [`ModelsCommand::Pull`] a stream of
14//! [`ModelsReply::Progress`] then [`ModelsReply::Pulled`]. Closing the stream cancels a pull;
15//! the partial file is kept, so pulling again resumes it.
16
17use std::collections::HashSet;
18use std::path::Path;
19use std::sync::atomic::{AtomicBool, Ordering};
20use std::sync::{Arc, Mutex};
21use std::time::{Duration, Instant};
22
23use serde::{Deserialize, Serialize};
24use weirdnet_agent::remote::{Authorize, Caller, Channel, Dialer, RemoteError, to_cbor};
25use weirdnet_agent::serve::{channel, stream_limits};
26use weirdnet_model::fit::{self, Fit, FitOptions};
27use weirdnet_model::gguf::GgufInfo;
28use weirdnet_model::hf::{RepoModel, Search, SearchHit};
29use weirdnet_model::hw::Budget;
30use weirdnet_model::{Consent, ModelStore, Progress, StoredModel, download_parts};
31use weirdnet_net::node::{Message, Node};
32
33use crate::engine::{EngineKind, ModelLaunch};
34use crate::error::bad_request;
35use crate::supervisor::{ModelState, Supervisor};
36
37/// The protocol id.
38pub const MODELS_PROTOCOL: &str = "/weirdnet-backends/models/1";
39/// Progress messages go out at most this often.
40const PROGRESS_EVERY: Duration = Duration::from_millis(250);
41
42/// What to pull.
43#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
44#[non_exhaustive]
45pub struct Pull {
46    /// The Hub repo, `owner/name`.
47    pub repo: String,
48    /// A model of the repo ([`RepoModel::id`], such as `Qwen3-8B-Q4_K_M`, or one of its file
49    /// names). `None` picks the largest that fits the node ([`fit::choose`]).
50    pub model: Option<String>,
51    /// Context and concurrent requests, for the fit and for serving.
52    pub context: Option<u32>,
53    pub slots: Option<u32>,
54    /// Add it to the supervisor once downloaded (as the model id, on the service's engine).
55    pub serve: bool,
56    /// Also load it (implies `serve`).
57    pub load: bool,
58}
59
60impl Pull {
61    pub fn new(repo: impl Into<String>) -> Self {
62        Self { repo: repo.into(), ..Default::default() }
63    }
64
65    pub fn with_model(mut self, model: impl Into<String>) -> Self {
66        self.model = Some(model.into());
67        self
68    }
69
70    pub fn with_context(mut self, context: u32) -> Self {
71        self.context = Some(context);
72        self
73    }
74
75    pub fn with_slots(mut self, slots: u32) -> Self {
76        self.slots = Some(slots);
77        self
78    }
79
80    /// Serve it after the download, and load it too when `load`.
81    pub fn serving(mut self, load: bool) -> Self {
82        self.serve = true;
83        self.load = load;
84        self
85    }
86}
87
88/// A models/1 request.
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90#[non_exhaustive]
91pub enum ModelsCommand {
92    /// Hub repos (GGUF only), most downloaded first.
93    Search {
94        query: String,
95        limit: u32,
96    },
97    /// A repo's models measured against the node's budget, largest first.
98    Files {
99        repo: String,
100        context: Option<u32>,
101        slots: Option<u32>,
102    },
103    Pull(Pull),
104    /// The models on the node's disk.
105    List,
106    /// Stop serving (if served) and delete a stored model by id.
107    Remove {
108        id: String,
109    },
110}
111
112/// What a client sends: its certificate and one command.
113#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
114pub struct ModelsRequest {
115    /// The caller's CBOR `NodeCert`, for the authorize hook.
116    #[serde(default, with = "serde_bytes")]
117    pub cert: Option<Vec<u8>>,
118    pub command: ModelsCommand,
119}
120
121/// A repo's models against this node.
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123#[non_exhaustive]
124pub struct RepoFits {
125    pub repo: String,
126    /// The header of the repo's smallest model, when it could be read (the KV figures then come
127    /// from it, else they are estimates).
128    pub info: Option<GgufInfo>,
129    /// The node's budget, when it has one (without one nothing `fits`).
130    pub budget: Option<Budget>,
131    pub context: u32,
132    pub slots: u32,
133    /// Largest first.
134    pub fits: Vec<Fit>,
135    /// The largest that fits.
136    pub best: Option<String>,
137}
138
139/// A finished pull.
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
141#[non_exhaustive]
142pub struct Pulled {
143    pub id: String,
144    pub repo: String,
145    /// Paths relative to the store, first part first.
146    pub files: Vec<String>,
147    pub size: u64,
148    /// Added to the supervisor (now or before).
149    pub served: bool,
150    pub loaded: bool,
151}
152
153/// A stored model and, when the supervisor serves it, its state.
154#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
155#[non_exhaustive]
156pub struct StoredEntry {
157    pub model: StoredModel,
158    /// The supervisor's id for it, when served.
159    pub served_as: Option<String>,
160    pub state: Option<ModelState>,
161}
162
163/// What a models/1 node answers.
164#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
165#[non_exhaustive]
166pub enum ModelsReply {
167    Hits(Vec<SearchHit>),
168    Fits(Box<RepoFits>),
169    Progress { done: u64, total: u64 },
170    Pulled(Pulled),
171    List(Vec<StoredEntry>),
172    Removed { id: String, freed: u64 },
173    Failed(RemoteError),
174}
175
176fn model_error(e: weirdnet_model::Error) -> RemoteError {
177    match e {
178        weirdnet_model::Error::BadRepo(_) | weirdnet_model::Error::Consent => bad_request(e.to_string()),
179        weirdnet_model::Error::Http(_) => RemoteError::unavailable(e.to_string()),
180        e => RemoteError::Failed { message: e.to_string() },
181    }
182}
183
184async fn blocking<T: Send + 'static>(f: impl FnOnce() -> weirdnet_model::Result<T> + Send + 'static) -> Result<T, RemoteError> {
185    tokio::task::spawn_blocking(f).await.map_err(|e| RemoteError::Failed { message: format!("worker: {e}") })?.map_err(model_error)
186}
187
188/// A model node's models/1 side. Transport-neutral ([`ModelsService::serve`] takes a channel);
189/// [`ModelsServer`] runs it on a `weirdnet-net` node. Its methods also work in-process (a local
190/// CLI on the node itself).
191pub struct ModelsService {
192    store: ModelStore,
193    supervisor: Supervisor,
194    auth: Arc<dyn Authorize>,
195    budget: Option<Budget>,
196    engine: EngineKind,
197    pulling: Mutex<HashSet<String>>,
198}
199
200impl ModelsService {
201    /// `store` is where files go (and its Hub and token); new models are served by `supervisor`;
202    /// `auth` admits the owner only.
203    pub fn new(store: ModelStore, supervisor: Supervisor, auth: Arc<dyn Authorize>) -> Self {
204        Self { store, supervisor, auth, budget: None, engine: EngineKind::Llamacpp, pulling: Mutex::default() }
205    }
206
207    /// The memory budget fits are measured against (`weirdnet_model::hw::budget`).
208    pub fn with_budget(mut self, budget: Budget) -> Self {
209        self.budget = Some(budget);
210        self
211    }
212
213    /// The engine pulled models are served on (default llama.cpp, the GGUF engine).
214    pub fn with_engine(mut self, engine: EngineKind) -> Self {
215        self.engine = engine;
216        self
217    }
218
219    pub fn store(&self) -> &ModelStore {
220        &self.store
221    }
222
223    /// Hub repos matching `query` (at most `limit`, 100 at most).
224    pub async fn search(&self, query: &str, limit: u32) -> Result<Vec<SearchHit>, RemoteError> {
225        let hub = self.store.hub_client();
226        let search = Search::new(query).with_limit(limit.clamp(1, 100) as usize);
227        blocking(move || hub.search(&search)).await
228    }
229
230    async fn repo(&self, repo: &str) -> Result<(Vec<RepoModel>, Option<GgufInfo>), RemoteError> {
231        let hub = self.store.hub_client();
232        let repo = repo.to_string();
233        blocking(move || {
234            let models = hub.models(&repo)?;
235            // Every quantization shares the architecture; read the smallest one's header.
236            let info = models.iter().find(|m| m.complete).and_then(|m| hub.gguf_info(&repo, &m.first().name).ok());
237            Ok((models, info))
238        })
239        .await
240    }
241
242    fn options(context: Option<u32>, slots: Option<u32>, info: Option<&GgufInfo>) -> FitOptions {
243        let mut opts = FitOptions::default();
244        if let Some(c) = context {
245            opts = opts.with_context(c);
246        }
247        if let Some(s) = slots {
248            opts = opts.with_slots(s);
249        }
250        if let Some(i) = info {
251            opts = opts.with_info(i);
252        }
253        opts
254    }
255
256    /// `repo`'s models measured against the node's budget.
257    pub async fn files(&self, repo: &str, context: Option<u32>, slots: Option<u32>) -> Result<RepoFits, RemoteError> {
258        let (models, info) = self.repo(repo).await?;
259        let opts = Self::options(context, slots, info.as_ref());
260        let budget = self.budget.unwrap_or(Budget { pool_bytes: 0, reserve_bytes: 0, usable_bytes: 0 });
261        let fits = fit::rank(&models, &budget, &opts);
262        let best = fits.iter().find(|f| f.fits).map(|f| f.model.id.clone());
263        Ok(RepoFits { repo: repo.into(), info, budget: self.budget, context: opts.context, slots: opts.slots, fits, best })
264    }
265
266    /// Downloads `pull` (resuming a partial file) and serves it if asked. `progress` returns
267    /// `false` to cancel. One pull per model at a time.
268    pub async fn pull(&self, pull: &Pull, progress: impl FnMut(Progress) -> bool + Send + 'static) -> Result<Pulled, RemoteError> {
269        let (models, info) = self.repo(&pull.repo).await?;
270        let model = match &pull.model {
271            Some(want) => models
272                .iter()
273                .find(|m| m.id == *want || m.parts.iter().any(|p| p.name == *want || p.name.rsplit('/').next() == Some(want.as_str())))
274                .cloned()
275                .ok_or_else(|| bad_request(format!("{} has no model {want}", pull.repo)))?,
276            None => {
277                let budget = self.budget.ok_or_else(|| bad_request("this node has no memory budget; name the model to pull"))?;
278                fit::choose(&models, &budget, &Self::options(pull.context, pull.slots, info.as_ref()))
279                    .map(|f| f.model)
280                    .ok_or_else(|| bad_request(format!("nothing in {} fits this node", pull.repo)))?
281            }
282        };
283        if !model.complete {
284            return Err(bad_request(format!("{} is missing parts in {}", model.id, pull.repo)));
285        }
286        let specs = model.specs(&pull.repo).map_err(model_error)?;
287        let key = format!("{}/{}", pull.repo, model.id);
288        if !self.pulling.lock().unwrap_or_else(|e| e.into_inner()).insert(key.clone()) {
289            return Err(RemoteError::Busy);
290        }
291        let store = self.store.clone();
292        let parts = specs.clone();
293        let mut progress = progress;
294        let done = blocking(move || download_parts(&store, &parts, &Consent::given(&parts[0]), &mut progress)).await;
295        self.pulling.lock().unwrap_or_else(|e| e.into_inner()).remove(&key);
296        let path = done?;
297        let files: Vec<String> = specs.iter().map(|s| s.file.clone()).collect();
298        let (mut served, mut loaded) = (false, false);
299        if pull.serve || pull.load {
300            served = true;
301            if self.served_as(&path).is_none() {
302                let mut launch = ModelLaunch::new(model.id.clone(), self.engine, path.display().to_string());
303                launch.context = pull.context;
304                launch.slots = pull.slots;
305                self.supervisor.add_model(launch)?;
306            }
307            if pull.load {
308                let id = self.served_as(&path).unwrap_or_else(|| model.id.clone());
309                self.supervisor.load(&id).await?;
310                loaded = true;
311            }
312        }
313        Ok(Pulled { id: model.id, repo: pull.repo.clone(), files, size: model.size, served, loaded })
314    }
315
316    /// The supervisor id serving the file at `path`, if any.
317    fn served_as(&self, path: &Path) -> Option<String> {
318        let path = path.display().to_string();
319        self.supervisor.launches().into_iter().find(|l| l.wrap.is_none() && l.source == path).map(|l| l.id)
320    }
321
322    /// The models on disk, with the supervisor's state for the served ones.
323    pub fn list(&self) -> Vec<StoredEntry> {
324        self.store
325            .list()
326            .into_iter()
327            .map(|model| {
328                let served_as = self.served_as(&self.store.dir().join(&model.files[0]));
329                let state = served_as.as_deref().and_then(|id| self.supervisor.state(id));
330                StoredEntry { model, served_as, state }
331            })
332            .collect()
333    }
334
335    /// Stops serving `id` (a stored model's id, or the supervisor id serving it) and deletes its
336    /// files. Returns the bytes freed.
337    pub async fn remove(&self, id: &str) -> Result<u64, RemoteError> {
338        let entries = self.list();
339        let matches: Vec<&StoredEntry> = entries.iter().filter(|e| e.model.id == id || e.served_as.as_deref() == Some(id)).collect();
340        let entry = match matches.as_slice() {
341            [one] => *one,
342            [] => return Err(bad_request(format!("no stored model {id}"))),
343            _ => return Err(bad_request(format!("{id} names {} stored models; remove by the served id", matches.len()))),
344        };
345        if self.pulling.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|k| k.rsplit('/').next() == Some(entry.model.id.as_str())) {
346            return Err(RemoteError::Busy);
347        }
348        if let Some(served) = &entry.served_as {
349            self.supervisor.remove_model(served).await?;
350        }
351        let store = self.store.clone();
352        let model = entry.model.clone();
353        blocking(move || store.remove_local(&model)).await
354    }
355
356    async fn run(&self, command: ModelsCommand) -> Result<ModelsReply, RemoteError> {
357        Ok(match command {
358            ModelsCommand::Search { query, limit } => ModelsReply::Hits(self.search(&query, limit).await?),
359            ModelsCommand::Files { repo, context, slots } => ModelsReply::Fits(Box::new(self.files(&repo, context, slots).await?)),
360            ModelsCommand::List => ModelsReply::List(self.list()),
361            ModelsCommand::Remove { id } => {
362                let freed = self.remove(&id).await?;
363                ModelsReply::Removed { id, freed }
364            }
365            ModelsCommand::Pull(_) => unreachable!("handled by serve"),
366        })
367    }
368
369    /// Serves one models/1 stream. `caller` is the transport-authenticated peer.
370    pub async fn serve(&self, mut ch: Channel, caller: Caller) -> Result<(), RemoteError> {
371        let Some(msg) = ch.recv_cbor::<ModelsRequest>().await? else { return Ok(()) };
372        let caller = match (caller.cert_bytes.is_some(), msg.cert) {
373            (false, Some(cert)) => caller.with_cert(cert),
374            (_, _) => caller,
375        };
376        if let Err(e) = self.auth.authorize(&caller) {
377            return ch.send_cbor(&ModelsReply::Failed(e)).await;
378        }
379        let pull = match msg.command {
380            ModelsCommand::Pull(p) => p,
381            other => {
382                let answer = self.run(other).await.unwrap_or_else(ModelsReply::Failed);
383                return ch.send_cbor(&answer).await;
384            }
385        };
386        let cancel = Arc::new(AtomicBool::new(false));
387        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Progress>();
388        let stop = cancel.clone();
389        let mut last: Option<Instant> = None;
390        let report = move |p: Progress| {
391            let due = p.done == p.total || last.is_none_or(|t| t.elapsed() >= PROGRESS_EVERY);
392            if due {
393                last = Some(Instant::now());
394                let _ = tx.send(p);
395            }
396            !stop.load(Ordering::SeqCst)
397        };
398        let Channel { tx: out, rx: inbound } = &mut ch;
399        let work = self.pull(&pull, report);
400        tokio::pin!(work);
401        let mut closed = false;
402        let result = loop {
403            tokio::select! {
404                r = &mut work => break r,
405                Some(p) = rx.recv() => {
406                    if !closed {
407                        out.send(to_cbor(&ModelsReply::Progress { done: p.done, total: p.total })?).await.ok();
408                    }
409                }
410                r = inbound.recv(), if !closed => {
411                    if matches!(r, Ok(None) | Err(_)) {
412                        closed = true;
413                        cancel.store(true, Ordering::SeqCst);
414                    }
415                }
416            }
417        };
418        if closed {
419            return Ok(());
420        }
421        while let Ok(p) = rx.try_recv() {
422            out.send(to_cbor(&ModelsReply::Progress { done: p.done, total: p.total })?).await?;
423        }
424        let answer = result.map(ModelsReply::Pulled).unwrap_or_else(ModelsReply::Failed);
425        out.send(to_cbor(&answer)?).await
426    }
427}
428
429/// Serves a [`ModelsService`] on a `weirdnet-net` node. Dropping it stops serving.
430pub struct ModelsServer {
431    task: tokio::task::JoinHandle<()>,
432}
433
434impl ModelsServer {
435    /// Starts accepting [`MODELS_PROTOCOL`] streams. Call from a Tokio runtime.
436    pub fn start<Q: Message, R: Message>(node: &Arc<Node<Q, R>>, service: Arc<ModelsService>) -> Result<ModelsServer, RemoteError> {
437        let mut incoming = node.accept_streams(MODELS_PROTOCOL, stream_limits()).map_err(|e| RemoteError::Failed { message: e.to_string() })?;
438        let task = tokio::spawn(async move {
439            while let Some(stream) = futures::StreamExt::next(&mut incoming).await {
440                let caller = Caller::new(stream.peer().to_string());
441                let svc = service.clone();
442                tokio::spawn(async move {
443                    let _ = svc.serve(channel(stream), caller).await;
444                });
445            }
446        });
447        Ok(ModelsServer { task })
448    }
449}
450
451impl Drop for ModelsServer {
452    fn drop(&mut self) {
453        self.task.abort();
454    }
455}
456
457/// The owner's side of models/1, over a [`Dialer`] (`weirdnet_agent::pool::NetDialer` on
458/// Weirdnet).
459pub struct ModelsClient {
460    dialer: Arc<dyn Dialer>,
461    cert: Option<Vec<u8>>,
462}
463
464impl ModelsClient {
465    pub fn new(dialer: Arc<dyn Dialer>) -> Self {
466        Self { dialer, cert: None }
467    }
468
469    /// This device's CBOR `NodeCert` (`weirdnet_agent::pool::encode_cert`), presented to the node.
470    pub fn with_cert(mut self, cert: Option<Vec<u8>>) -> Self {
471        self.cert = cert;
472        self
473    }
474
475    async fn open(&self, node: &str, command: ModelsCommand) -> Result<Channel, RemoteError> {
476        let mut ch = self.dialer.open(node, MODELS_PROTOCOL).await?;
477        ch.send_cbor(&ModelsRequest { cert: self.cert.clone(), command }).await?;
478        Ok(ch)
479    }
480
481    async fn call(&self, node: &str, command: ModelsCommand) -> Result<ModelsReply, RemoteError> {
482        let mut ch = self.open(node, command).await?;
483        match ch.recv_cbor::<ModelsReply>().await? {
484            Some(ModelsReply::Failed(e)) => Err(e),
485            Some(m) => Ok(m),
486            None => Err(RemoteError::Closed),
487        }
488    }
489
490    fn unexpected(what: &str, got: ModelsReply) -> RemoteError {
491        RemoteError::protocol(format!("expected {what}, got {got:?}"))
492    }
493
494    pub async fn search(&self, node: &str, query: &str, limit: u32) -> Result<Vec<SearchHit>, RemoteError> {
495        match self.call(node, ModelsCommand::Search { query: query.into(), limit }).await? {
496            ModelsReply::Hits(h) => Ok(h),
497            other => Err(Self::unexpected("hits", other)),
498        }
499    }
500
501    pub async fn files(&self, node: &str, repo: &str, context: Option<u32>, slots: Option<u32>) -> Result<RepoFits, RemoteError> {
502        match self.call(node, ModelsCommand::Files { repo: repo.into(), context, slots }).await? {
503            ModelsReply::Fits(f) => Ok(*f),
504            other => Err(Self::unexpected("fits", other)),
505        }
506    }
507
508    /// Pulls on `node`, calling `progress` as it goes. Dropping the future cancels the pull
509    /// (the node keeps the partial file for a later resume).
510    pub async fn pull(&self, node: &str, pull: Pull, mut progress: impl FnMut(Progress) + Send) -> Result<Pulled, RemoteError> {
511        let mut ch = self.open(node, ModelsCommand::Pull(pull)).await?;
512        loop {
513            match ch.recv_cbor::<ModelsReply>().await? {
514                Some(ModelsReply::Progress { done, total }) => progress(Progress { done, total }),
515                Some(ModelsReply::Pulled(p)) => return Ok(p),
516                Some(ModelsReply::Failed(e)) => return Err(e),
517                Some(other) => return Err(Self::unexpected("progress", other)),
518                None => return Err(RemoteError::Closed),
519            }
520        }
521    }
522
523    pub async fn list(&self, node: &str) -> Result<Vec<StoredEntry>, RemoteError> {
524        match self.call(node, ModelsCommand::List).await? {
525            ModelsReply::List(l) => Ok(l),
526            other => Err(Self::unexpected("a list", other)),
527        }
528    }
529
530    /// Removes a stored model; returns the bytes freed.
531    pub async fn remove(&self, node: &str, id: &str) -> Result<u64, RemoteError> {
532        match self.call(node, ModelsCommand::Remove { id: id.into() }).await? {
533            ModelsReply::Removed { freed, .. } => Ok(freed),
534            other => Err(Self::unexpected("removed", other)),
535        }
536    }
537}
538
539#[cfg(test)]
540mod tests {
541    use std::io::{BufRead, BufReader, Write};
542
543    use weirdnet_agent::remote::MemoryDialer;
544
545    use super::*;
546    use crate::supervisor::SupervisorOptions;
547
548    /// A GGUF header (llama, one block, one KV head of size 1) padded to `len` bytes.
549    fn gguf(len: usize) -> Vec<u8> {
550        let mut out = b"GGUF".to_vec();
551        out.extend(3u32.to_le_bytes());
552        out.extend(0u64.to_le_bytes());
553        let kv: [(&str, Option<u32>); 5] = [
554            ("general.architecture", None),
555            ("llama.block_count", Some(1)),
556            ("llama.attention.head_count", Some(1)),
557            ("llama.attention.head_count_kv", Some(1)),
558            ("llama.attention.key_length", Some(1)),
559        ];
560        out.extend((kv.len() as u64).to_le_bytes());
561        for (k, v) in kv {
562            out.extend((k.len() as u64).to_le_bytes());
563            out.extend(k.as_bytes());
564            match v {
565                None => {
566                    out.extend(8u32.to_le_bytes());
567                    out.extend(5u64.to_le_bytes());
568                    out.extend(b"llama");
569                }
570                Some(n) => {
571                    out.extend(4u32.to_le_bytes());
572                    out.extend(n.to_le_bytes());
573                }
574            }
575        }
576        out.resize(len, 0);
577        out
578    }
579
580    /// The Hub: a search, repo `o/n` with a single Q4_0 file and a two-part Q8_0, and the files.
581    fn hub() -> String {
582        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
583        let url = format!("http://{}", listener.local_addr().unwrap());
584        let info = r#"{"id":"o/n","siblings":[
585            {"rfilename":"m-Q4_0.gguf","size":4000},
586            {"rfilename":"Q8_0/m-Q8_0-00001-of-00002.gguf","size":3000},
587            {"rfilename":"Q8_0/m-Q8_0-00002-of-00002.gguf","size":3000}]}"#;
588        let search = r#"[{"id":"o/n","downloads":9,"likes":1}]"#;
589        std::thread::spawn(move || {
590            for stream in listener.incoming() {
591                let Ok(mut stream) = stream else { break };
592                let mut reader = BufReader::new(stream.try_clone().unwrap());
593                let mut first = String::new();
594                reader.read_line(&mut first).unwrap();
595                loop {
596                    let mut line = String::new();
597                    if reader.read_line(&mut line).unwrap_or(0) == 0 || line.trim().is_empty() {
598                        break;
599                    }
600                }
601                let path = first.split_whitespace().nth(1).unwrap_or("/").split('?').next().unwrap_or("").to_string();
602                let body: Option<Vec<u8>> = match path.as_str() {
603                    "/api/models" => Some(search.into()),
604                    "/api/models/o/n" => Some(info.into()),
605                    "/o/n/resolve/main/m-Q4_0.gguf" => Some(gguf(4000)),
606                    "/o/n/resolve/main/Q8_0/m-Q8_0-00001-of-00002.gguf" => Some(gguf(3000)),
607                    "/o/n/resolve/main/Q8_0/m-Q8_0-00002-of-00002.gguf" => Some(vec![7; 3000]),
608                    _ => None,
609                };
610                let _ = match body {
611                    Some(b) => {
612                        let _ = stream.write_all(format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", b.len()).as_bytes());
613                        stream.write_all(&b)
614                    }
615                    None => stream.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"),
616                };
617            }
618        });
619        url
620    }
621
622    fn dialer(svc: Arc<ModelsService>, peer: &'static str) -> Arc<dyn Dialer> {
623        let d = MemoryDialer::new();
624        d.route_only("model-node", &[MODELS_PROTOCOL], move |ch, _| {
625            let svc = svc.clone();
626            tokio::spawn(async move {
627                let _ = svc.serve(ch, Caller::new(peer)).await;
628            });
629        });
630        Arc::new(d)
631    }
632
633    #[tokio::test(flavor = "multi_thread")]
634    async fn the_owner_searches_pulls_serves_lists_and_removes() {
635        let tmp = tempfile::tempdir().unwrap();
636        let store = ModelStore::new(tmp.path()).with_hub(hub());
637        let sup = Supervisor::new(vec![], vec![], SupervisorOptions::default());
638        let auth: Arc<dyn Authorize> = Arc::new(|c: &Caller| if c.peer == "owner" { Ok(()) } else { Err(RemoteError::refused("owner only")) });
639        // Q4_0 (4000 bytes plus 32 KiB of KV, plus 10%) fits; the 6000-byte Q8_0 doesn't.
640        let budget = Budget { pool_bytes: 41_000, reserve_bytes: 0, usable_bytes: 41_000 };
641        let svc = Arc::new(ModelsService::new(store, sup.clone(), auth).with_budget(budget));
642        let owner = ModelsClient::new(dialer(svc.clone(), "owner"));
643        let stranger = ModelsClient::new(dialer(svc.clone(), "stranger"));
644
645        assert!(matches!(stranger.list("model-node").await, Err(RemoteError::Refused { .. })));
646        assert!(matches!(stranger.pull("model-node", Pull::new("o/n"), |_| {}).await, Err(RemoteError::Refused { .. })));
647        assert!(!tmp.path().join("m-Q4_0.gguf").exists(), "nothing ran for the stranger");
648
649        let hits = owner.search("model-node", "m", 5).await.unwrap();
650        assert_eq!(hits.iter().map(|h| h.id.as_str()).collect::<Vec<_>>(), ["o/n"]);
651
652        let fits = owner.files("model-node", "o/n", None, None).await.unwrap();
653        assert_eq!(fits.info.as_ref().map(|i| i.kv_bytes_per_token()), Some(4));
654        assert_eq!(fits.best.as_deref(), Some("m-Q4_0"));
655        assert_eq!(fits.fits.iter().map(|f| (f.model.id.as_str(), f.fits)).collect::<Vec<_>>(), [("m-Q8_0", false), ("m-Q4_0", true)]);
656
657        let mut seen = Vec::new();
658        let pulled = owner.pull("model-node", Pull::new("o/n").serving(false), |p| seen.push(p)).await.unwrap();
659        assert_eq!((pulled.id.as_str(), pulled.size, pulled.served, pulled.loaded), ("m-Q4_0", 4000, true, false));
660        assert_eq!(seen.last().map(|p| (p.done, p.total)), Some((4000, 4000)));
661        assert_eq!(sup.state("m-Q4_0"), Some(ModelState::Unloaded), "served without a restart");
662        let launch = sup.launches().into_iter().find(|l| l.id == "m-Q4_0").unwrap();
663        assert_eq!(launch.source, tmp.path().join("m-Q4_0.gguf").display().to_string());
664
665        let split = owner.pull("model-node", Pull::new("o/n").with_model("m-Q8_0"), |_| {}).await.unwrap();
666        assert_eq!(split.files, ["Q8_0/m-Q8_0-00001-of-00002.gguf", "Q8_0/m-Q8_0-00002-of-00002.gguf"]);
667        assert!(!split.served);
668        let err = owner.pull("model-node", Pull::new("o/n").with_model("nope"), |_| {}).await.unwrap_err();
669        assert!(matches!(err, RemoteError::BadRequest { .. }), "{err:?}");
670
671        let list = owner.list("model-node").await.unwrap();
672        assert_eq!(
673            list.iter().map(|e| (e.model.id.as_str(), e.served_as.as_deref())).collect::<Vec<_>>(),
674            [("m-Q4_0", Some("m-Q4_0")), ("m-Q8_0", None)]
675        );
676        assert_eq!(list[0].state, Some(ModelState::Unloaded));
677
678        assert_eq!(owner.remove("model-node", "m-Q4_0").await.unwrap(), 4000);
679        assert_eq!(sup.state("m-Q4_0"), None, "no longer served");
680        assert_eq!(owner.remove("model-node", "m-Q8_0").await.unwrap(), 6000);
681        assert!(owner.list("model-node").await.unwrap().is_empty());
682        assert!(matches!(owner.remove("model-node", "m-Q8_0").await, Err(RemoteError::BadRequest { .. })));
683    }
684
685    #[tokio::test(flavor = "multi_thread")]
686    async fn without_a_budget_the_model_must_be_named() {
687        let tmp = tempfile::tempdir().unwrap();
688        let sup = Supervisor::new(vec![], vec![], SupervisorOptions::default());
689        let auth: Arc<dyn Authorize> = Arc::new(|_: &Caller| Ok(()));
690        let svc = ModelsService::new(ModelStore::new(tmp.path()).with_hub(hub()), sup, auth);
691        let err = svc.pull(&Pull::new("o/n"), |_| true).await.unwrap_err();
692        assert!(err.to_string().contains("no memory budget"), "{err}");
693        assert!(svc.files("o/n", None, None).await.unwrap().best.is_none());
694        let err = svc.pull(&Pull::new("o/n").with_model("m-Q4_0"), |_| false).await.unwrap_err();
695        assert!(err.to_string().contains("cancelled"), "{err}");
696        assert!(matches!(svc.pull(&Pull::new("bad"), |_| true).await, Err(RemoteError::BadRequest { .. })));
697    }
698}