Skip to main content

weirdnet_backends/
supervisor.rs

1//! Starts, probes, drains and stops engine processes for one model node: swap groups, idle
2//! unload, crash detection with restart backoff, and readiness probes.
3
4use std::collections::HashMap;
5use std::path::PathBuf;
6use std::process::Stdio;
7use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
8use std::sync::{Arc, Mutex};
9use std::time::{Duration, Instant};
10
11use futures::StreamExt;
12use serde::{Deserialize, Serialize};
13use serde_json::{Value, json};
14use tokio::sync::{broadcast, oneshot, watch};
15use tokio_stream::wrappers::ReceiverStream;
16use weirdnet_agent::remote::RemoteError;
17use weirdnet_agent::remote::infer::v2::{
18    AudioHeader, AudioStream, Request, Sampling, SpeakRequest, SpeechPiece, TranscribeRequest, Transcript, Usage,
19};
20use weirdnet_agent::speech::{AudioFormat, SpeechProfile};
21use weirdnet_model::ModelStore;
22use weirdnet_model::limits::LimitsRecord;
23
24use crate::engine::{Capabilities, EngineConfig, EngineKind, LoraAdapter, ModelLaunch};
25
26/// An engine's answer as it streams.
27pub type ChunkStream = std::pin::Pin<Box<dyn futures::Stream<Item = Result<Chunk, RemoteError>> + Send>>;
28
29/// A model's state on this node.
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31#[serde(tag = "state", content = "detail", rename_all = "snake_case")]
32#[non_exhaustive]
33pub enum ModelState {
34    Unloaded,
35    Loading,
36    Ready,
37    Draining,
38    Failed(String),
39}
40use crate::error::{bad_request, engine_error, unavailable, unknown_model};
41use crate::openai::{self, Target};
42use crate::sse::{Chunk, ChunkDecoder, SseParser};
43
44#[derive(Debug, Clone)]
45pub struct SupervisorOptions {
46    /// Per-model engine logs (`<id>.log`); `None` discards engine output.
47    pub log_dir: Option<PathBuf>,
48    /// How long `unload` waits for in-flight requests.
49    pub drain_timeout: Duration,
50    /// How long a stopped engine gets after SIGTERM before SIGKILL.
51    pub stop_grace: Duration,
52    /// Restart an engine that crashed while serving.
53    pub restart: bool,
54    /// First restart delay; doubles per crash in the window, up to `backoff_max`.
55    pub backoff_base: Duration,
56    pub backoff_max: Duration,
57    /// This many crashes within `crash_window` is a crash loop: no more restarts until an explicit
58    /// (forced) load.
59    pub max_crashes: usize,
60    pub crash_window: Duration,
61}
62
63impl Default for SupervisorOptions {
64    fn default() -> Self {
65        Self {
66            log_dir: None,
67            drain_timeout: Duration::from_secs(30),
68            stop_grace: Duration::from_secs(10),
69            restart: true,
70            backoff_base: Duration::from_secs(1),
71            backoff_max: Duration::from_secs(60),
72            max_crashes: 5,
73            crash_window: Duration::from_secs(600),
74        }
75    }
76}
77
78/// Something that happened to an engine; the node's alerting and metrics listen to these.
79#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
80#[serde(tag = "kind", rename_all = "snake_case")]
81#[non_exhaustive]
82pub enum SupervisorEvent {
83    Starting {
84        model: String,
85    },
86    Ready {
87        model: String,
88        load_secs: f32,
89    },
90    LoadFailed {
91        model: String,
92        why: String,
93    },
94    Crashed {
95        model: String,
96        why: String,
97        crashes: usize,
98        restart_in_secs: Option<f32>,
99    },
100    CrashLoop {
101        model: String,
102        crashes: usize,
103    },
104    Unloaded {
105        model: String,
106        idle: bool,
107    },
108    /// A model was added at run time ([`Supervisor::add_model`]).
109    Added {
110        model: String,
111    },
112    /// A model was removed at run time ([`Supervisor::remove_model`]).
113    Removed {
114        model: String,
115    },
116}
117
118/// A hold on the node's accelerators ([`Supervisor::reserve`]): while it lasts the supervisor
119/// starts no engine, so nothing is placed on the node. For a job that needs the GPU to itself,
120/// such as a training run.
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
122#[non_exhaustive]
123pub struct Reservation {
124    /// Who holds it: the application's name for the job (for example a run id). Releasing takes
125    /// the same name.
126    pub holder: String,
127    /// When it was taken, in Unix milliseconds.
128    pub since_ms: i64,
129}
130
131impl Reservation {
132    pub fn new(holder: impl Into<String>) -> Self {
133        let since_ms = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64);
134        Self { holder: holder.into(), since_ms }
135    }
136}
137
138/// One model's row in the node's capability record.
139#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
140#[non_exhaustive]
141pub struct ModelStatus {
142    pub id: String,
143    pub engine: EngineKind,
144    pub state: ModelState,
145    pub in_flight: usize,
146    pub swap_group: Option<String>,
147    pub embedding: bool,
148    pub pid: Option<u32>,
149    /// The last measured load time.
150    pub last_load_secs: Option<f32>,
151    /// Model file size, for load-time estimates before one was measured.
152    pub size_bytes: Option<u64>,
153    /// A stock server this node only forwards to.
154    pub wrapped: bool,
155    /// Crashes in the current window.
156    pub crashes: usize,
157    /// The configured context window, if set.
158    #[serde(default)]
159    pub context: Option<u32>,
160    /// The configured concurrent sequences, if set.
161    #[serde(default)]
162    pub slots: Option<u32>,
163    /// What the model takes ([`ModelLaunch::capabilities`]); `None` in records from nodes before
164    /// 0.1.3, where only `embedding` is known.
165    #[serde(default)]
166    pub capabilities: Option<Capabilities>,
167    /// For a LoRA adapter's row: the base model it runs on (it shares the base's engine, state
168    /// and capabilities). `None` for models.
169    #[serde(default)]
170    pub base: Option<String>,
171    /// The context per sequence the engine reported when the model last loaded (llama-server's
172    /// `/props` `n_ctx` per slot, vLLM's `max_model_len`): what one request can use, which with
173    /// several slots is less than the configured [`context`](Self::context). `None` until measured,
174    /// when the engine doesn't say, and in records from nodes before 0.4.9.
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub context_tokens: Option<u32>,
177    /// What a speaking model does ([`Capabilities::speak`]): what the engine reported at load
178    /// (llama-server `/props` voices; vLLM-Omni `/v1/audio/voices` and its sample rate) over
179    /// what the GGUF headers or `weirdnet-model`'s catalog entry say
180    /// (`weirdnet_model::SpeechProfile::or`), narrowed by the operator's
181    /// [`ModelLaunch::speech`]. Before the first load, the kept record's or the catalog entry's.
182    /// `None` for models that don't speak, when settings widen what the engine reports, and in
183    /// records from nodes before 0.4.10. Since 0.4.10.
184    #[serde(default, skip_serializing_if = "Option::is_none")]
185    pub speech: Option<SpeechProfile>,
186}
187
188impl ModelStatus {
189    /// Its media and request limits ([`Capabilities::limits`]); unknown when the record has no
190    /// capabilities (nodes before 0.1.3) or the node knows none.
191    pub fn limits(&self) -> weirdnet_agent::MediaLimits {
192        self.capabilities.map(|c| c.limits).unwrap_or_default()
193    }
194
195    /// `entry` with this row's inputs, limits and context window filled in from the record:
196    /// the measured context per sequence ([`context_tokens`](Self::context_tokens)), else the
197    /// configured `--ctx-size` when set; `entry`'s own values stay where the record has none.
198    ///
199    /// Since 0.4.10 also the speech profile ([`speech`](Self::speech), catalog/1
200    /// `CatalogModel::speech`) and video input (`inputs.video` with the video limits).
201    pub fn apply_to(&self, entry: weirdnet_agent::remote::catalog::CatalogModel) -> weirdnet_agent::remote::catalog::CatalogModel {
202        let entry = match self.capabilities {
203            Some(c) => c.apply_to(entry),
204            None => entry,
205        };
206        let entry = match &self.speech {
207            Some(p) => entry.with_speech(p.clone()),
208            None => entry,
209        };
210        match self.context_tokens.or(self.context) {
211            Some(ctx) => entry.with_context(ctx),
212            None => entry,
213        }
214    }
215
216    /// Its catalog/1 purpose ([`Capabilities::purpose`]): embedding, speech
217    /// ([`Capabilities::speak`]), transcription ([`Capabilities::transcribe`]) or chat.
218    pub fn purpose(&self) -> weirdnet_agent::remote::catalog::Purpose {
219        self.capabilities.unwrap_or_default().purpose(self.embedding)
220    }
221
222    /// A catalog/1 entry for this row in `state`: its id, [`purpose`](Self::purpose), and what
223    /// [`apply_to`](Self::apply_to) fills in.
224    pub fn catalog_model(&self, state: weirdnet_agent::remote::catalog::ModelState) -> weirdnet_agent::remote::catalog::CatalogModel {
225        self.apply_to(weirdnet_agent::remote::catalog::CatalogModel::new(self.id.clone(), self.purpose(), state))
226    }
227}
228
229/// When an adapter added with [`Supervisor::add_adapter`] or [`Supervisor::add_adapter_live`]
230/// can serve.
231#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
232#[serde(rename_all = "snake_case")]
233#[non_exhaustive]
234pub enum AdapterChange {
235    /// Now, or whenever the base is next ready: the base wasn't running, or its engine has the
236    /// adapter loaded already (llama.cpp: the same file, loaded at start; vLLM: loaded at start
237    /// or at run time).
238    Live,
239    /// After the base's next load: its engine is running without the adapter (llama-server
240    /// loads adapter files only at start). Loading the adapter ([`Supervisor::load`]) restarts
241    /// the base.
242    NextLoad,
243}
244
245/// Where a pool id goes: its base model's slot, and the adapter if it is one.
246struct Route {
247    base: String,
248    adapter: Option<LoraAdapter>,
249}
250
251struct Running {
252    base: String,
253    /// The adapters the engine has loaded: llama.cpp's in `--lora` order (they stay loaded for
254    /// the engine's life); vLLM's by name, including those loaded at run time.
255    adapters: Vec<LoraAdapter>,
256    /// vLLM started with LoRA on and run-time updates allowed ([`ModelLaunch::runtime_lora`]).
257    runtime_lora: bool,
258    /// The projector the engine started with.
259    mmproj: Option<String>,
260    api_key: Option<String>,
261    pid: Option<u32>,
262    stop: Option<oneshot::Sender<()>>,
263    exited: watch::Receiver<Option<String>>,
264    /// Keeps a wrapped server's never-firing exit channel open.
265    _exit_tx: Option<watch::Sender<Option<String>>>,
266    /// The key-checking proxy in front of an MLX-LM server; stops when the engine record goes.
267    _proxy: Option<crate::mlx::ProxyHandle>,
268}
269
270struct Slot {
271    launch: ModelLaunch,
272    state: ModelState,
273    running: Option<Running>,
274    in_flight: Arc<AtomicUsize>,
275    /// Milliseconds since the supervisor's epoch when the last request finished.
276    last_used: Arc<AtomicU64>,
277    /// Bumped on every start, so a late exit notice from an old process is ignored.
278    generation: u64,
279    load_secs: Option<f32>,
280    crashes: Vec<Instant>,
281    crash_loop: bool,
282    restart_at: Option<Instant>,
283    /// What the last load measured (or the store kept from an earlier one).
284    measured: Option<LimitsRecord>,
285}
286
287impl Running {
288    /// Where the engine has `a` loaded: llama.cpp's `--lora` index (any id with the same file);
289    /// vLLM's module with the same name and path.
290    fn index(&self, engine: EngineKind, a: &LoraAdapter) -> Option<usize> {
291        match engine {
292            EngineKind::Llamacpp => self.adapters.iter().position(|x| x.path == a.path),
293            _ => self.adapters.iter().position(|x| x.id == a.id && x.path == a.path),
294        }
295    }
296}
297
298impl Slot {
299    /// Whether adapter `a` can serve on the running engine (or the base isn't running).
300    fn serves(&self, a: &LoraAdapter) -> bool {
301        self.running.as_ref().is_none_or(|r| r.index(self.launch.engine, a).is_some())
302    }
303
304    fn new(launch: ModelLaunch) -> Self {
305        Self {
306            launch,
307            state: ModelState::Unloaded,
308            running: None,
309            in_flight: Arc::new(AtomicUsize::new(0)),
310            last_used: Arc::new(AtomicU64::new(0)),
311            generation: 0,
312            load_secs: None,
313            crashes: Vec::new(),
314            crash_loop: false,
315            restart_at: None,
316            measured: None,
317        }
318    }
319
320    /// What the model takes, with the operator's limits over the measured ones
321    /// ([`MediaLimits::or`](weirdnet_agent::MediaLimits::or)).
322    fn capabilities(&self) -> Capabilities {
323        let mut c = self.launch.capabilities();
324        if let Some(r) = &self.measured {
325            c.limits = c.limits.or(r.limits.to_media());
326        }
327        c
328    }
329
330    /// What the model speaks, when it speaks here: the measured record's profile (the engine's
331    /// report over the headers' or catalog's), else the catalog entry's, narrowed by the
332    /// operator's settings. `Err` when the settings widen it.
333    fn speech(&self) -> Option<Result<SpeechProfile, String>> {
334        if !self.capabilities().speak {
335            return None;
336        }
337        let found = self.measured.as_ref().and_then(|r| r.speech.clone()).or_else(|| self.launch.cataloged_speech());
338        let own = found.map(|p| p.to_agent()).unwrap_or_default();
339        if self.launch.speech.is_unknown() {
340            return Some(Ok(own));
341        }
342        Some(own.narrowed_by(&self.launch.speech).map_err(|e| format!("speech settings widen what the engine reports: {e}")))
343    }
344}
345
346struct Inner {
347    engines: HashMap<EngineKind, EngineConfig>,
348    opts: SupervisorOptions,
349    http: reqwest::Client,
350    slots: Mutex<HashMap<String, Slot>>,
351    /// Serializes load and unload, so swaps never interleave.
352    ops: tokio::sync::Mutex<()>,
353    events: broadcast::Sender<SupervisorEvent>,
354    epoch: Instant,
355    /// The node's reservation, if any.
356    reserved: watch::Sender<Option<Reservation>>,
357    /// Where measured limits are kept ([`Supervisor::set_limits_store`]).
358    limits_store: Mutex<Option<ModelStore>>,
359}
360
361/// The per-node supervisor. Cheap to clone.
362#[derive(Clone)]
363pub struct Supervisor {
364    inner: Arc<Inner>,
365}
366
367impl Supervisor {
368    pub fn new(engines: Vec<EngineConfig>, models: Vec<ModelLaunch>, opts: SupervisorOptions) -> Self {
369        let slots = models.into_iter().map(|launch| (launch.id.clone(), Slot::new(launch))).collect();
370        let http =
371            reqwest::Client::builder().connect_timeout(Duration::from_secs(5)).no_proxy().build().expect("an HTTP client without TLS always builds");
372        let (events, _) = broadcast::channel(256);
373        Self {
374            inner: Arc::new(Inner {
375                engines: engines.into_iter().map(|e| (e.kind, e)).collect(),
376                opts,
377                http,
378                slots: Mutex::new(slots),
379                ops: tokio::sync::Mutex::new(()),
380                events,
381                epoch: Instant::now(),
382                reserved: watch::Sender::new(None),
383                limits_store: Mutex::new(None),
384            }),
385        }
386    }
387
388    fn slots(&self) -> std::sync::MutexGuard<'_, HashMap<String, Slot>> {
389        self.inner.slots.lock().unwrap_or_else(|e| e.into_inner())
390    }
391
392    fn emit(&self, ev: SupervisorEvent) {
393        let _ = self.inner.events.send(ev);
394    }
395
396    /// The slot serving `id`: a model's own, or the base of an adapter.
397    fn route(&self, id: &str) -> Result<Route, RemoteError> {
398        let slots = self.slots();
399        if slots.contains_key(id) {
400            return Ok(Route { base: id.to_string(), adapter: None });
401        }
402        slots
403            .values()
404            .find_map(|s| s.launch.adapters.iter().find(|a| a.id == id).map(|a| Route { base: s.launch.id.clone(), adapter: Some(a.clone()) }))
405            .ok_or_else(|| unknown_model(id))
406    }
407
408    /// Whether `id` names a model or an adapter on this node.
409    fn taken(slots: &HashMap<String, Slot>, id: &str) -> bool {
410        slots.contains_key(id) || slots.values().any(|s| s.launch.adapters.iter().any(|a| a.id == id))
411    }
412
413    /// Adds LoRA adapter `adapter` to model `base`, after [`ModelLaunch::check_adapters`]. Its id
414    /// must be free on the node. Returns [`AdapterChange::Live`] when the base isn't running or
415    /// its engine already has the adapter loaded (on llama.cpp: the same file, for example one
416    /// removed and added back), else [`AdapterChange::NextLoad`]. It never touches the engine:
417    /// [`Supervisor::add_adapter_live`] also loads it into a running vLLM engine. Emits
418    /// [`SupervisorEvent::Added`] for the adapter.
419    pub fn add_adapter(&self, base: &str, adapter: LoraAdapter) -> Result<AdapterChange, RemoteError> {
420        let mut launch = self.slots().get(base).map(|s| s.launch.clone()).ok_or_else(|| unknown_model(base))?;
421        launch.adapters.push(adapter.clone());
422        launch.check_adapters().map_err(bad_request)?;
423        let running = {
424            let mut slots = self.slots();
425            if Self::taken(&slots, &adapter.id) {
426                return Err(bad_request(format!("{} is already configured on this node", adapter.id)));
427            }
428            let slot = slots.get_mut(base).ok_or_else(|| unknown_model(base))?;
429            slot.launch.adapters.push(adapter.clone());
430            !slot.serves(&adapter)
431        };
432        self.emit(SupervisorEvent::Added { model: adapter.id });
433        Ok(if running { AdapterChange::NextLoad } else { AdapterChange::Live })
434    }
435
436    /// [`Supervisor::add_adapter`], then, when the base runs on vLLM with LoRA on
437    /// ([`ModelLaunch::runtime_lora`]), loads the adapter into the running engine
438    /// (`/v1/load_lora_adapter`) so it serves at once, without restarting the base. If the engine
439    /// refuses it, the adapter is taken off the base again and the engine's error returned.
440    /// On llama.cpp an adapter file the engine didn't start with still waits for the next load
441    /// ([`AdapterChange::NextLoad`]).
442    pub async fn add_adapter_live(&self, base: &str, adapter: LoraAdapter) -> Result<AdapterChange, RemoteError> {
443        let _op = self.inner.ops.lock().await;
444        let change = self.add_adapter(base, adapter.clone())?;
445        if change == AdapterChange::Live {
446            return Ok(change);
447        }
448        let Some((url, key)) = self.runtime_engine(base) else { return Ok(change) };
449        let body = json!({"lora_name": adapter.id, "lora_path": adapter.path});
450        match self.post(format!("{url}/v1/load_lora_adapter"), key.as_deref(), &body).await {
451            Ok(_) => {
452                if let Some(r) = self.slots().get_mut(base).and_then(|s| s.running.as_mut()) {
453                    r.adapters.push(adapter);
454                }
455                Ok(AdapterChange::Live)
456            }
457            Err(e) => {
458                let _ = self.remove_adapter(base, &adapter.id);
459                Err(e)
460            }
461        }
462    }
463
464    /// [`Supervisor::remove_adapter`], then, on a running vLLM engine with run-time LoRA, unloads
465    /// it from the engine too (`/v1/unload_lora_adapter`), freeing its memory. llama-server keeps
466    /// the file loaded (unused) until the base's next load; adding it back is then live.
467    pub async fn remove_adapter_live(&self, base: &str, id: &str) -> Result<LoraAdapter, RemoteError> {
468        let _op = self.inner.ops.lock().await;
469        let removed = self.remove_adapter(base, id)?;
470        let Some((url, key)) = self.runtime_engine(base) else { return Ok(removed) };
471        let loaded = self.slots().get(base).and_then(|s| s.running.as_ref()).is_some_and(|r| r.adapters.iter().any(|x| x.id == id));
472        if loaded {
473            match self.post(format!("{url}/v1/unload_lora_adapter"), key.as_deref(), &json!({"lora_name": id})).await {
474                Ok(_) => {
475                    if let Some(r) = self.slots().get_mut(base).and_then(|s| s.running.as_mut()) {
476                        r.adapters.retain(|x| x.id != id);
477                    }
478                }
479                Err(e) => tracing::warn!(model = %base, adapter = %id, "engine kept the adapter loaded: {e}"),
480            }
481        }
482        Ok(removed)
483    }
484
485    /// Changes how strongly adapter `id` applies, from the next request on (`None`: 1.0). Live:
486    /// llama.cpp takes the scale per request, so the base keeps running. Requests may still set
487    /// their own ([`Request::adapter_scale`]). vLLM applies adapters at full strength and refuses.
488    pub fn set_adapter_scale(&self, id: &str, scale: Option<f32>) -> Result<(), RemoteError> {
489        if let Some(s) = scale {
490            check_scale(s)?;
491        }
492        let route = self.route(id)?;
493        if route.adapter.is_none() {
494            return Err(bad_request(format!("{id} is not an adapter")));
495        }
496        let mut slots = self.slots();
497        let slot = slots.get_mut(&route.base).ok_or_else(|| unknown_model(id))?;
498        if slot.launch.engine != EngineKind::Llamacpp {
499            return Err(bad_request(format!("{id} runs on {}, which applies adapters at full strength", slot.launch.engine.name())));
500        }
501        if let Some(a) = slot.launch.adapters.iter_mut().find(|a| a.id == id) {
502            a.scale = scale;
503        }
504        Ok(())
505    }
506
507    /// The URL and key of `base`'s engine when it is ready and takes adapters at run time.
508    fn runtime_engine(&self, base: &str) -> Option<(String, Option<String>)> {
509        let slots = self.slots();
510        let s = slots.get(base)?;
511        let r = s.running.as_ref().filter(|r| r.runtime_lora && s.state == ModelState::Ready)?;
512        Some((r.base.clone(), r.api_key.clone()))
513    }
514
515    /// Stops serving adapter `id` on `base` (requests for it fail from now on; the engine keeps
516    /// it loaded until the base's next load, see [`Supervisor::remove_adapter_live`]). Emits
517    /// [`SupervisorEvent::Removed`].
518    pub fn remove_adapter(&self, base: &str, id: &str) -> Result<LoraAdapter, RemoteError> {
519        let removed = {
520            let mut slots = self.slots();
521            let slot = slots.get_mut(base).ok_or_else(|| unknown_model(base))?;
522            let at = slot.launch.adapters.iter().position(|a| a.id == id).ok_or_else(|| bad_request(format!("{base} has no adapter {id}")))?;
523            slot.launch.adapters.remove(at)
524        };
525        self.emit(SupervisorEvent::Removed { model: id.into() });
526        Ok(removed)
527    }
528
529    /// Sets (or with `None` clears) llama.cpp model `id`'s multimodal projector
530    /// ([`ModelLaunch::mmproj`]), from the next load on: its capabilities change at once, and
531    /// [`AdapterChange::NextLoad`] says the running engine started with another projector
532    /// (llama-server reads it only at start; loading the model restarts it).
533    pub async fn set_projector_live(&self, id: &str, mmproj: Option<String>) -> Result<AdapterChange, RemoteError> {
534        let _op = self.inner.ops.lock().await;
535        let change = {
536            let mut slots = self.slots();
537            let slot = slots.get_mut(id).ok_or_else(|| unknown_model(id))?;
538            if slot.launch.engine != EngineKind::Llamacpp || slot.launch.wrap.is_some() || slot.launch.embedding {
539                return Err(bad_request(format!("{id}: only a llama.cpp chat model this node starts takes a projector")));
540            }
541            if let Some(p) = &mmproj
542                && p.contains(',')
543            {
544                return Err(bad_request(format!("{id}: llama.cpp can't take a path with a comma ({p})")));
545            }
546            if slot.launch.mmproj != mmproj {
547                // What the old projector measured no longer holds; the next load measures again.
548                slot.measured = None;
549            }
550            slot.launch.mmproj = mmproj.clone();
551            match &slot.running {
552                Some(r) if r.mmproj != mmproj => AdapterChange::NextLoad,
553                _ => AdapterChange::Live,
554            }
555        };
556        Ok(change)
557    }
558
559    /// Adds a model the node may load from now on, without a restart (for example one just
560    /// downloaded). It starts unloaded. Refused when the id is taken; [`Supervisor::remove_model`]
561    /// first to replace one. Emits [`SupervisorEvent::Added`].
562    pub fn add_model(&self, launch: ModelLaunch) -> Result<(), RemoteError> {
563        if launch.id.trim().is_empty() {
564            return Err(bad_request("a model needs an id"));
565        }
566        if let Some(w) = &launch.wrap {
567            w.check().map_err(bad_request)?;
568        }
569        launch.check_adapters().map_err(bad_request)?;
570        launch.check_speech().map_err(bad_request)?;
571        let id = launch.id.clone();
572        let ids = launch.served_ids();
573        {
574            let mut slots = self.slots();
575            if let Some(t) = ids.iter().find(|i| Self::taken(&slots, i)) {
576                return Err(bad_request(format!("{t} is already configured on this node")));
577            }
578            slots.insert(id.clone(), Slot::new(launch));
579        }
580        self.seed_limits(&id);
581        for model in ids {
582            self.emit(SupervisorEvent::Added { model });
583        }
584        Ok(())
585    }
586
587    /// Unloads `id` (draining requests under way) and forgets it, with its adapters. Emits
588    /// [`SupervisorEvent::Removed`] for each. Returns its launch settings. An adapter's id is
589    /// refused: use [`Supervisor::remove_adapter`].
590    pub async fn remove_model(&self, id: &str) -> Result<ModelLaunch, RemoteError> {
591        let _op = self.inner.ops.lock().await;
592        if let Route { base, adapter: Some(_) } = self.route(id)? {
593            return Err(bad_request(format!("{id} is an adapter on {base}; remove it with remove_adapter")));
594        }
595        self.stop(id, false).await;
596        let slot = self.slots().remove(id).ok_or_else(|| unknown_model(id))?;
597        for model in slot.launch.served_ids() {
598            self.emit(SupervisorEvent::Removed { model });
599        }
600        Ok(slot.launch)
601    }
602
603    /// The configured models' launch settings, sorted by id.
604    pub fn launches(&self) -> Vec<ModelLaunch> {
605        let mut out: Vec<ModelLaunch> = self.slots().values().map(|s| s.launch.clone()).collect();
606        out.sort_by(|a, b| a.id.cmp(&b.id));
607        out
608    }
609
610    /// Engine events from now on.
611    pub fn subscribe(&self) -> broadcast::Receiver<SupervisorEvent> {
612        self.inner.events.subscribe()
613    }
614
615    fn now_ms(&self) -> u64 {
616        self.inner.epoch.elapsed().as_millis() as u64
617    }
618
619    /// One row per model, and one per adapter (with [`ModelStatus::base`] set, the base's engine,
620    /// capabilities and state; `Unloaded` while the base runs without it).
621    pub fn status(&self) -> Vec<ModelStatus> {
622        let mut out: Vec<ModelStatus> = self
623            .slots()
624            .values()
625            .flat_map(|s| {
626                let row = Self::row(s);
627                let adapters: Vec<ModelStatus> = s
628                    .launch
629                    .adapters
630                    .iter()
631                    .map(|a| {
632                        let mut r = row.clone();
633                        if !s.serves(a) {
634                            r.state = ModelState::Unloaded;
635                            r.pid = None;
636                        }
637                        r.id = a.id.clone();
638                        r.base = Some(s.launch.id.clone());
639                        r.size_bytes = std::fs::metadata(&a.path).ok().filter(|m| m.is_file()).map(|m| m.len());
640                        r
641                    })
642                    .collect();
643                std::iter::once(row).chain(adapters)
644            })
645            .collect();
646        out.sort_by(|a, b| a.id.cmp(&b.id));
647        out
648    }
649
650    fn row(s: &Slot) -> ModelStatus {
651        ModelStatus {
652            id: s.launch.id.clone(),
653            engine: s.launch.engine,
654            state: s.state.clone(),
655            in_flight: s.in_flight.load(Ordering::SeqCst),
656            swap_group: s.launch.swap_group.clone(),
657            embedding: s.launch.embedding,
658            pid: s.running.as_ref().and_then(|r| r.pid),
659            last_load_secs: s.load_secs,
660            size_bytes: if s.launch.wrap.is_some() { None } else { std::fs::metadata(&s.launch.source).ok().map(|m| m.len()) },
661            wrapped: s.launch.wrap.is_some(),
662            crashes: s.crashes.len(),
663            context: s.launch.context,
664            slots: s.launch.slots,
665            capabilities: Some(s.capabilities()),
666            base: None,
667            context_tokens: s.measured.as_ref().and_then(|r| r.limits.context_tokens),
668            speech: s.speech().and_then(Result::ok),
669        }
670    }
671
672    /// Requests under way across all models.
673    pub fn in_flight(&self) -> usize {
674        self.slots().values().map(|s| s.in_flight.load(Ordering::SeqCst)).sum()
675    }
676
677    /// `id`'s state; an adapter has its base's (`Unloaded` while the base runs without it).
678    pub fn state(&self, id: &str) -> Option<ModelState> {
679        let route = self.route(id).ok()?;
680        let slots = self.slots();
681        let s = slots.get(&route.base)?;
682        match &route.adapter {
683            Some(a) if !s.serves(a) => Some(ModelState::Unloaded),
684            _ => Some(s.state.clone()),
685        }
686    }
687
688    /// What `id` takes ([`ModelLaunch::capabilities`]), with its limits: the operator's
689    /// ([`ModelLaunch::limits`]) over those measured at load ([`Supervisor::measured_limits`]); an
690    /// adapter takes what its base does.
691    pub fn capabilities(&self, id: &str) -> Option<Capabilities> {
692        let route = self.route(id).ok()?;
693        self.slots().get(&route.base).map(Slot::capabilities)
694    }
695
696    /// What `id` speaks ([`ModelStatus::speech`]); `None` when it doesn't speak here (or its
697    /// settings widen what the engine reports). Since 0.4.10.
698    pub fn speech(&self, id: &str) -> Option<SpeechProfile> {
699        let route = self.route(id).ok()?;
700        self.slots().get(&route.base).and_then(Slot::speech).and_then(Result::ok)
701    }
702
703    /// What `id` (or an adapter's base) measured when it last loaded, as `weirdnet-model`'s
704    /// [`LimitsRecord`]: for a llama.cpp model whose source is a GGUF file, what its header and
705    /// its projector's say ([`weirdnet_model::limits::measure`]; llama.cpp `--image-max-tokens`,
706    /// when passed, over the header's per-image cap for size-dependent projectors), and for every
707    /// engine that reports it the context per sequence it runs with (llama-server `/props`, vLLM
708    /// `/v1/models`). Every figure that can't be read is absent, never defaulted. `None` before
709    /// the first load (unless the [store](Supervisor::set_limits_store) kept a record) or when
710    /// nothing could be measured. The capabilities carry these under the operator's
711    /// ([`Supervisor::capabilities`]); the context goes into [`ModelStatus::context_tokens`].
712    pub fn measured_limits(&self, id: &str) -> Option<LimitsRecord> {
713        let route = self.route(id).ok()?;
714        self.slots().get(&route.base).and_then(|s| s.measured.clone())
715    }
716
717    /// Keeps measured limits in `store` (`weirdnet-model`'s [`ModelStore::record_limits`],
718    /// next to the model's files) for llama.cpp models served from it, and reads them back now
719    /// for models not measured yet, so an unloaded model reports its image and audio figures
720    /// after a restart. A record read back has no context (that belongs to the run that measured
721    /// it), and one taken with another projector is ignored. `None` stops keeping them.
722    /// Blocking: reads the store.
723    pub fn set_limits_store(&self, store: Option<ModelStore>) {
724        *self.inner.limits_store.lock().unwrap_or_else(|e| e.into_inner()) = store;
725        let ids: Vec<String> = self.slots().iter().filter(|(_, s)| s.measured.is_none()).map(|(id, _)| id.clone()).collect();
726        for id in ids {
727            self.seed_limits(&id);
728        }
729    }
730
731    fn limits_store(&self) -> Option<ModelStore> {
732        self.inner.limits_store.lock().unwrap_or_else(|e| e.into_inner()).clone()
733    }
734
735    fn engine_args(&self, engine: EngineKind) -> Vec<String> {
736        self.inner.engines.get(&engine).map(|e| e.extra_args.clone()).unwrap_or_default()
737    }
738
739    /// `id`'s record from the store, when it has none yet. Blocking.
740    fn seed_limits(&self, id: &str) {
741        let Some(store) = self.limits_store() else { return };
742        let Some(launch) = self.slots().get(id).filter(|s| s.measured.is_none()).map(|s| s.launch.clone()) else { return };
743        let Some(record) = crate::measure::kept(&store, &launch, &self.engine_args(launch.engine)) else { return };
744        if let Some(s) = self.slots().get_mut(id)
745            && s.measured.is_none()
746            && s.launch == launch
747        {
748            s.measured = Some(record);
749        }
750    }
751
752    /// The context per sequence the engine at `base` reports for `launch`: llama-server's
753    /// `/props` (`default_generation_settings.n_ctx`, per slot), vLLM's `/v1/models`
754    /// (`max_model_len`). `None` when it doesn't answer or doesn't say.
755    async fn served_context(&self, launch: &ModelLaunch, base: &str, key: Option<&str>) -> Option<u32> {
756        let get = |path: &str| {
757            let mut req = self.inner.http.get(format!("{base}{path}")).timeout(Duration::from_secs(5));
758            if let Some(k) = key {
759                req = req.bearer_auth(k);
760            }
761            req
762        };
763        let read = |v: Option<u64>| v.filter(|n| *n > 0).and_then(|n| u32::try_from(n).ok());
764        match launch.engine {
765            EngineKind::Llamacpp => {
766                let v: Value = get("/props").send().await.ok().filter(|r| r.status().is_success())?.json().await.ok()?;
767                read(v["default_generation_settings"]["n_ctx"].as_u64())
768            }
769            EngineKind::Vllm | EngineKind::VllmOmni => {
770                let v: Value = get("/v1/models").send().await.ok().filter(|r| r.status().is_success())?.json().await.ok()?;
771                let row = v["data"].as_array()?.iter().find(|m| m["id"].as_str() == Some(launch.id.as_str()))?;
772                read(row["max_model_len"].as_u64())
773            }
774            _ => None,
775        }
776    }
777
778    /// What the engine at `base` reports about speaking model `launch`: llama-server's `/props`
779    /// `voices`; vLLM-Omni's `GET /v1/audio/voices` and the sample rate of its answer to a
780    /// one-word probe (`x-audio-sample-rate`, else the WAV header). Over what each API always
781    /// does (formats, streaming, vLLM-Omni's speed). `None` for models that don't speak.
782    async fn reported_speech(&self, launch: &ModelLaunch, base: &str, key: Option<&str>) -> Option<weirdnet_model::SpeechProfile> {
783        if !launch.capabilities().speak {
784            return None;
785        }
786        let auth = |mut req: reqwest::RequestBuilder| {
787            if let Some(k) = key {
788                req = req.bearer_auth(k);
789            }
790            req.timeout(Duration::from_secs(10))
791        };
792        let get = |path: &str| auth(self.inner.http.get(format!("{base}{path}")));
793        async fn json_of(req: reqwest::RequestBuilder) -> Option<Value> {
794            req.send().await.ok().filter(|r| r.status().is_success())?.json().await.ok()
795        }
796        match launch.engine {
797            EngineKind::Llamacpp => Some(crate::speak::llama_reported(json_of(get("/props")).await.as_ref())),
798            EngineKind::VllmOmni => {
799                let voices = json_of(get("/v1/audio/voices")).await;
800                let mut probe = json!({"model": launch.id, "input": "Hello.", "response_format": "wav"});
801                if let Some(t) = crate::speak::task_type(launch) {
802                    probe["task_type"] = t.into();
803                }
804                let mut rate = None;
805                if let Ok(resp) = auth(self.inner.http.post(format!("{base}/v1/audio/speech")).json(&probe)).send().await
806                    && resp.status().is_success()
807                {
808                    rate = crate::speak::header_rate(resp.headers());
809                    if rate.is_none()
810                        && let Ok(bytes) = resp.bytes().await
811                    {
812                        rate = crate::speak::wav_format(&bytes).map(|(r, _)| r);
813                    }
814                }
815                Some(crate::speak::omni_reported(voices.as_ref(), rate))
816            }
817            _ => None,
818        }
819    }
820
821    /// Measures `launch`, just loaded at `base`, and keeps the record in the store when set. A
822    /// speaking model's record carries its speech profile: what the engine reported over what
823    /// the headers ([`weirdnet_model::limits::measure`]) or the catalog entry say.
824    async fn measure_loaded(&self, launch: &ModelLaunch, base: &str, key: Option<&str>) -> Option<LimitsRecord> {
825        let context = self.served_context(launch, base, key).await;
826        let reported = self.reported_speech(launch, base, key).await;
827        let (launch, args, store) = (launch.clone(), self.engine_args(launch.engine), self.limits_store());
828        tokio::task::spawn_blocking(move || {
829            let mut record = crate::measure::measure(&launch, &args, context);
830            if let Some(reported) = reported {
831                let mut r = record.unwrap_or_else(|| {
832                    LimitsRecord::new(weirdnet_model::ModelLimits::new(), weirdnet_model::LimitSource::Measured)
833                        .with_engine(launch.engine.name())
834                        .stamped()
835                });
836                let cataloged = launch.cataloged_speech().unwrap_or_default();
837                let fallback = r.speech.as_ref().map_or_else(|| cataloged.clone(), |headers| headers.or(&cataloged));
838                let merged = reported.or(&fallback);
839                r.speech = (!merged.is_unknown()).then_some(merged);
840                record = Some(r);
841            }
842            let record = record?;
843            if let Some(store) = store {
844                crate::measure::keep(&store, &launch, &record);
845            }
846            Some(record)
847        })
848        .await
849        .ok()
850        .flatten()
851    }
852
853    /// Starts `id` and waits until it is ready (see [`Supervisor::load_with`]).
854    pub async fn load(&self, id: &str) -> Result<(), RemoteError> {
855        self.load_with(id, false).await
856    }
857
858    /// Starts `id` and waits until its engine is ready. Loading a model in a swap group unloads the
859    /// group's other models first. Already ready: returns at once. A model in a crash loop or
860    /// waiting for its restart refuses unless `force` (an operator's explicit load), which also
861    /// clears the crash history.
862    ///
863    /// An adapter loads its base. When the base is ready without it (added after the base
864    /// started), the base is restarted.
865    ///
866    /// While the node is reserved ([`Supervisor::reserve`]) every load is refused, `force` too.
867    pub async fn load_with(&self, id: &str, force: bool) -> Result<(), RemoteError> {
868        let route = self.route(id)?;
869        self.check_unreserved()?;
870        let wanted = route.adapter;
871        let id = route.base.as_str();
872        // A request during a crash backoff waits it out (at most `backoff_max`) rather than
873        // failing; the scheduled restart and this load serialize on `ops`.
874        if !force {
875            let wait = {
876                let slots = self.slots();
877                let slot = slots.get(id).ok_or_else(|| unknown_model(id))?;
878                slot.restart_at.and_then(|at| at.checked_duration_since(Instant::now()))
879            };
880            if let Some(d) = wait {
881                tokio::time::sleep(d.min(self.inner.opts.backoff_max)).await;
882            }
883        }
884        let _op = self.inner.ops.lock().await;
885        // Checked again under `ops`: a reservation taken while this load waited wins.
886        self.check_unreserved()?;
887        let (launch, group_mates) = {
888            let mut slots = self.slots();
889            let slot = slots.get_mut(id).ok_or_else(|| unknown_model(id))?;
890            let has_wanted = wanted.as_ref().is_none_or(|w| slot.running.is_some() && slot.serves(w));
891            let projector_current = slot.launch.wrap.is_some() || slot.running.as_ref().is_none_or(|r| r.mmproj == slot.launch.mmproj);
892            if slot.state == ModelState::Ready && has_wanted && projector_current {
893                return Ok(());
894            }
895            if force {
896                slot.crashes.clear();
897                slot.crash_loop = false;
898                slot.restart_at = None;
899            } else if slot.crash_loop {
900                return Err(unavailable(format!("{id} is in a crash loop ({} crashes); fix it, then load it again with force", slot.crashes.len())));
901            }
902            let launch = slot.launch.clone();
903            let mates: Vec<String> = match &launch.swap_group {
904                Some(g) => slots
905                    .values()
906                    .filter(|s| s.launch.id != id && s.launch.swap_group.as_ref() == Some(g) && s.running.is_some())
907                    .map(|s| s.launch.id.clone())
908                    .collect(),
909                None => Vec::new(),
910            };
911            (launch, mates)
912        };
913        for mate in group_mates {
914            tracing::info!(model = %mate, for_model = %id, "swap group: unloading");
915            self.stop(&mate, false).await;
916        }
917        // A failed engine may still have a process record; clear it.
918        self.stop(id, false).await;
919        if let Err(why) = launch.check_speech() {
920            if let Some(s) = self.slots().get_mut(id) {
921                s.state = ModelState::Failed(why.clone());
922            }
923            self.emit(SupervisorEvent::LoadFailed { model: id.into(), why: why.clone() });
924            return Err(bad_request(why));
925        }
926        let started = Instant::now();
927        self.emit(SupervisorEvent::Starting { model: id.into() });
928        let result = match &launch.wrap {
929            Some(_) => self.attach(&launch).await,
930            None => self.start(&launch).await,
931        };
932        match &result {
933            Ok(()) => {
934                let secs = started.elapsed().as_secs_f32();
935                if let Some(s) = self.slots().get_mut(id) {
936                    s.load_secs = Some(secs);
937                    s.restart_at = None;
938                    s.last_used.store(self.now_ms(), Ordering::SeqCst);
939                }
940                self.emit(SupervisorEvent::Ready { model: id.into(), load_secs: secs });
941            }
942            Err(e) => self.emit(SupervisorEvent::LoadFailed { model: id.into(), why: e.to_string() }),
943        }
944        result
945    }
946
947    /// Drains and stops `id`. A wrapped server is only detached (the node doesn't own it).
948    /// An adapter's id is refused: unload its base.
949    pub async fn unload(&self, id: &str) -> Result<(), RemoteError> {
950        let _op = self.inner.ops.lock().await;
951        if let Route { base, adapter: Some(_) } = self.route(id)? {
952            return Err(bad_request(format!("{id} is an adapter on {base}; unload {base} instead")));
953        }
954        self.stop(id, false).await;
955        Ok(())
956    }
957
958    /// Reserves the node for `holder`: from now on no engine starts (loads, loads on demand,
959    /// crash restarts and swaps are refused as unavailable), and every running engine is drained
960    /// (waiting up to `drain_timeout` for requests under way) and stopped. Returns once they are
961    /// stopped. Taking it again under the same holder is a no-op; another holder's reservation is
962    /// refused as unavailable. Held in memory until [`Supervisor::release`]: an application that
963    /// must keep it across a restart records it and reserves again at start.
964    pub async fn reserve(&self, holder: &str) -> Result<Reservation, RemoteError> {
965        let holder = holder.trim();
966        if holder.is_empty() {
967            return Err(bad_request("a reservation needs a holder"));
968        }
969        let mut taken = None;
970        let mut busy = None;
971        self.inner.reserved.send_if_modified(|r| match r {
972            Some(cur) if cur.holder == holder => {
973                taken = Some(cur.clone());
974                false
975            }
976            Some(cur) => {
977                busy = Some(cur.holder.clone());
978                false
979            }
980            None => {
981                let new = Reservation::new(holder);
982                taken = Some(new.clone());
983                *r = Some(new);
984                true
985            }
986        });
987        if let Some(other) = busy {
988            return Err(unavailable(format!("this node is reserved by {other}")));
989        }
990        let _op = self.inner.ops.lock().await;
991        let ids: Vec<String> = self.slots().values().filter(|s| s.running.is_some()).map(|s| s.launch.id.clone()).collect();
992        for id in ids {
993            tracing::info!(model = %id, holder, "reserved: unloading");
994            self.stop(&id, false).await;
995        }
996        Ok(taken.expect("set above"))
997    }
998
999    /// Ends `holder`'s reservation; models load again on the next request or load. `false` when
1000    /// the node was not reserved; another holder's reservation is refused as a bad request.
1001    pub fn release(&self, holder: &str) -> Result<bool, RemoteError> {
1002        let holder = holder.trim();
1003        let mut other = None;
1004        let released = self.inner.reserved.send_if_modified(|r| match r {
1005            Some(cur) if cur.holder == holder => {
1006                *r = None;
1007                true
1008            }
1009            Some(cur) => {
1010                other = Some(cur.holder.clone());
1011                false
1012            }
1013            None => false,
1014        });
1015        match other {
1016            Some(o) => Err(bad_request(format!("this node is reserved by {o}, not {holder}"))),
1017            None => Ok(released),
1018        }
1019    }
1020
1021    /// The node's reservation, if any.
1022    pub fn reservation(&self) -> Option<Reservation> {
1023        self.inner.reserved.borrow().clone()
1024    }
1025
1026    /// Changes to the reservation, from now on.
1027    pub fn reservation_changes(&self) -> watch::Receiver<Option<Reservation>> {
1028        self.inner.reserved.subscribe()
1029    }
1030
1031    fn check_unreserved(&self) -> Result<(), RemoteError> {
1032        match &*self.inner.reserved.borrow() {
1033            Some(r) => Err(unavailable(format!("this node is reserved by {}: it starts no model until released", r.holder))),
1034            None => Ok(()),
1035        }
1036    }
1037
1038    /// Stops every engine (daemon shutdown).
1039    pub async fn shutdown(&self) {
1040        let _op = self.inner.ops.lock().await;
1041        let ids: Vec<String> = self.slots().keys().cloned().collect();
1042        for id in ids {
1043            self.stop(&id, false).await;
1044        }
1045    }
1046
1047    /// Unloads ready models idle past their `idle_ttl`. Returns what it unloaded. Run it every few
1048    /// seconds ([`Supervisor::spawn_reaper`]).
1049    pub async fn reap_idle(&self) -> Vec<String> {
1050        let now = self.now_ms();
1051        let idle: Vec<String> = self
1052            .slots()
1053            .values()
1054            .filter(|s| s.state == ModelState::Ready && s.in_flight.load(Ordering::SeqCst) == 0)
1055            .filter(|s| s.launch.idle_ttl.is_some_and(|ttl| now.saturating_sub(s.last_used.load(Ordering::SeqCst)) >= ttl.as_millis() as u64))
1056            .map(|s| s.launch.id.clone())
1057            .collect();
1058        let mut done = Vec::new();
1059        for id in idle {
1060            // Never wait behind a load or swap; try again next round.
1061            let Ok(_op) = self.inner.ops.try_lock() else { break };
1062            let still_idle = self.slots().get(&id).is_some_and(|s| s.state == ModelState::Ready && s.in_flight.load(Ordering::SeqCst) == 0);
1063            if still_idle {
1064                tracing::info!(model = %id, "idle: unloading");
1065                self.stop(&id, true).await;
1066                done.push(id);
1067            }
1068        }
1069        done
1070    }
1071
1072    /// Runs [`Supervisor::reap_idle`] every `every` until the returned handle is aborted.
1073    pub fn spawn_reaper(&self, every: Duration) -> tokio::task::JoinHandle<()> {
1074        let me = self.clone();
1075        tokio::spawn(async move {
1076            let mut tick = tokio::time::interval(every);
1077            loop {
1078                tick.tick().await;
1079                me.reap_idle().await;
1080            }
1081        })
1082    }
1083
1084    /// A wrapped stock server: probe it and mark it ready.
1085    async fn attach(&self, launch: &ModelLaunch) -> Result<(), RemoteError> {
1086        let wrap = launch.wrap.as_ref().expect("attach is for wrapped models");
1087        wrap.check().map_err(unavailable)?;
1088        let base = wrap.base();
1089        let ok = self.inner.http.get(format!("{base}/health")).timeout(Duration::from_secs(5)).send().await.is_ok_and(|r| r.status().is_success());
1090        // A stock mlx_lm.server still needs the proxy for `default_model` and text-only checks.
1091        let (base, api_key, proxy) = if ok && launch.engine == EngineKind::Mlx {
1092            let l = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.map_err(|e| unavailable(format!("mlx proxy: {e}")))?;
1093            let url = format!("http://{}", l.local_addr().map_err(|e| unavailable(format!("mlx proxy: {e}")))?);
1094            let key = random_hex(24);
1095            (url, Some(key.clone()), Some(crate::mlx::spawn_proxy(l, base, launch.id.clone(), key)))
1096        } else {
1097            (base, wrap.api_key.clone(), None)
1098        };
1099        let measured = if ok { self.measure_loaded(launch, &wrap.base(), wrap.api_key.as_deref()).await } else { None };
1100        let (tx, rx) = watch::channel(None);
1101        let mut slots = self.slots();
1102        let slot = slots.get_mut(&launch.id).expect("checked by load");
1103        slot.generation += 1;
1104        if measured.is_some() {
1105            slot.measured = measured;
1106        }
1107        if !ok {
1108            slot.state = ModelState::Failed(format!("wrapped server {base} is not answering /health"));
1109            return Err(unavailable(format!("{}: wrapped server {base} is not answering /health", launch.id)));
1110        }
1111        slot.state = ModelState::Ready;
1112        slot.running = Some(Running {
1113            base,
1114            adapters: Vec::new(),
1115            runtime_lora: false,
1116            mmproj: None,
1117            api_key,
1118            pid: None,
1119            stop: None,
1120            exited: rx,
1121            _exit_tx: Some(tx),
1122            _proxy: proxy,
1123        });
1124        Ok(())
1125    }
1126
1127    async fn start(&self, launch: &ModelLaunch) -> Result<(), RemoteError> {
1128        let engine = self
1129            .inner
1130            .engines
1131            .get(&launch.engine)
1132            .ok_or_else(|| unavailable(format!("engine {} is not configured on this node", launch.engine.name())))?
1133            .clone();
1134        if let Err(why) = launch.check_adapters() {
1135            if let Some(s) = self.slots().get_mut(&launch.id) {
1136                s.state = ModelState::Failed(why.clone());
1137            }
1138            return Err(bad_request(why));
1139        }
1140        if launch.engine == EngineKind::Mlx && launch.embedding {
1141            let why = "MLX-LM serves no embeddings; run embedding models on llama.cpp or vLLM".to_string();
1142            if let Some(s) = self.slots().get_mut(&launch.id) {
1143                s.state = ModelState::Failed(why.clone());
1144            }
1145            return Err(bad_request(format!("{}: {why}", launch.id)));
1146        }
1147        // The engine is told a free port, which is free when picked but not held (it can't be
1148        // handed over): another process can bind it before the engine does. Then the engine fails
1149        // to bind and exits, or another server answers on the port, and either is caught below and
1150        // the launch is tried again on a new port.
1151        let mut tries = 0;
1152        loop {
1153            tries += 1;
1154            match self.start_once(launch, &engine).await {
1155                Ok(()) => return Ok(()),
1156                Err(Start::PortTaken(e)) if tries < PORT_TRIES => {
1157                    tracing::warn!(model = %launch.id, "{e}; trying another port");
1158                }
1159                Err(Start::PortTaken(e) | Start::Failed(e)) => return Err(e),
1160            }
1161        }
1162    }
1163
1164    /// One launch of `launch` on a newly picked port, up to ready.
1165    async fn start_once(&self, launch: &ModelLaunch, engine: &EngineConfig) -> Result<(), Start> {
1166        let mlx = launch.engine == EngineKind::Mlx;
1167        let no_port = |e: std::io::Error| Start::Failed(unavailable(format!("no free loopback port: {e}")));
1168        // MLX-LM has no API key: it gets a private port, and the advertised one is the proxy's,
1169        // bound now so nothing else can take it.
1170        let (port, proxy_listener) = if mlx {
1171            let l = std::net::TcpListener::bind(("127.0.0.1", 0)).map_err(no_port)?;
1172            l.set_nonblocking(true).map_err(no_port)?;
1173            (l.local_addr().map_err(no_port)?.port(), Some(l))
1174        } else {
1175            (free_port().map_err(no_port)?, None)
1176        };
1177        let engine_port = if mlx { free_port().map_err(no_port)? } else { port };
1178        let api_key = random_hex(24);
1179        let log_from = self.log_len(&launch.id);
1180        let mut cmd = engine.command(launch, engine_port, &api_key);
1181        cmd.stdin(Stdio::null());
1182        match self.log_file(&launch.id) {
1183            Some((out, err)) => {
1184                cmd.stdout(out).stderr(err);
1185            }
1186            None => {
1187                cmd.stdout(Stdio::null()).stderr(Stdio::null());
1188            }
1189        }
1190        #[cfg(unix)]
1191        {
1192            cmd.process_group(0);
1193            #[cfg(target_os = "linux")]
1194            // SAFETY: prctl is async-signal-safe and touches no memory of the parent.
1195            unsafe {
1196                cmd.pre_exec(|| {
1197                    libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM);
1198                    Ok(())
1199                });
1200            }
1201        }
1202        let mut child = cmd.spawn().map_err(|e| Start::Failed(unavailable(format!("could not start {}: {e}", engine.program.display()))))?;
1203        let pid = child.id();
1204        let proxy = match proxy_listener.map(tokio::net::TcpListener::from_std) {
1205            Some(Ok(l)) => Some(crate::mlx::spawn_proxy(l, format!("http://127.0.0.1:{engine_port}"), launch.id.clone(), api_key.clone())),
1206            Some(Err(e)) => {
1207                let _ = terminate(&mut child, pid, self.inner.opts.stop_grace).await;
1208                return Err(Start::Failed(unavailable(format!("mlx proxy: {e}"))));
1209            }
1210            None => None,
1211        };
1212        let (exit_tx, exit_rx) = watch::channel(None);
1213        let (stop_tx, stop_rx) = oneshot::channel::<()>();
1214        let generation = {
1215            let mut slots = self.slots();
1216            let slot = slots.get_mut(&launch.id).expect("checked by load");
1217            slot.generation += 1;
1218            slot.state = ModelState::Loading;
1219            slot.running = Some(Running {
1220                base: format!("http://127.0.0.1:{port}"),
1221                adapters: launch.adapters.clone(),
1222                runtime_lora: launch.runtime_lora(),
1223                mmproj: launch.mmproj.clone(),
1224                api_key: Some(api_key.clone()),
1225                pid,
1226                stop: Some(stop_tx),
1227                exited: exit_rx.clone(),
1228                _exit_tx: None,
1229                _proxy: proxy,
1230            });
1231            slot.generation
1232        };
1233        tracing::info!(model = %launch.id, pid, port, engine = launch.engine.name(), "engine starting");
1234
1235        // The monitor owns the child: it reaps it and does the stopping.
1236        let grace = self.inner.opts.stop_grace;
1237        let me = self.clone();
1238        let id = launch.id.clone();
1239        let port_taken = Arc::new(AtomicBool::new(false));
1240        let taken = port_taken.clone();
1241        tokio::spawn(async move {
1242            let status = tokio::select! {
1243                s = child.wait() => s,
1244                _ = stop_rx => terminate(&mut child, pid, grace).await,
1245            };
1246            let desc = match status {
1247                Ok(s) => format!("engine exited ({s})"),
1248                Err(e) => format!("engine wait failed: {e}"),
1249            };
1250            // An engine that dies while loading because its port was taken is not a crash: the
1251            // launch is tried again on another port.
1252            let lost_port = me.is_loading(&id, generation) && me.lost_port(&id, engine_port, log_from);
1253            taken.store(lost_port, Ordering::SeqCst);
1254            // Record the exit (and count a crash) before anyone waiting on it wakes up.
1255            me.exited(&id, generation, desc.clone(), lost_port);
1256            let _ = exit_tx.send(Some(desc));
1257        });
1258
1259        let started = Instant::now();
1260        let health = format!("http://127.0.0.1:{port}/health");
1261        let mut exited = exit_rx;
1262        loop {
1263            let gone = exited.borrow().clone();
1264            if let Some(desc) = gone {
1265                if port_taken.load(Ordering::SeqCst) {
1266                    return Err(Start::PortTaken(self.failed(
1267                        &launch.id,
1268                        generation,
1269                        format!("{desc} while loading: port {engine_port} was taken by another process"),
1270                    )));
1271                }
1272                return Err(Start::Failed(self.failed(&launch.id, generation, format!("{desc} while loading{}", self.log_tail(&launch.id)))));
1273            }
1274            if let Ok(resp) = self.inner.http.get(&health).timeout(Duration::from_secs(2)).send().await
1275                && resp.status().is_success()
1276            {
1277                match self.identify(launch, port, &api_key).await {
1278                    Some(true) => break,
1279                    // Healthy, but not ours: another server holds the port and ours can't bind it.
1280                    Some(false) => {
1281                        self.stop(&launch.id, false).await;
1282                        return Err(Start::PortTaken(self.failed(
1283                            &launch.id,
1284                            generation,
1285                            format!("another server answers on port {port} (not this launch's key or model)"),
1286                        )));
1287                    }
1288                    None => {}
1289                }
1290            }
1291            if started.elapsed() > engine.ready_timeout {
1292                self.stop(&launch.id, false).await;
1293                return Err(Start::Failed(self.failed(
1294                    &launch.id,
1295                    generation,
1296                    format!("not ready after {:?}{}", engine.ready_timeout, self.log_tail(&launch.id)),
1297                )));
1298            }
1299            let _ = tokio::time::timeout(Duration::from_millis(200), exited.changed()).await;
1300        }
1301        let measured = self.measure_loaded(launch, &format!("http://127.0.0.1:{port}"), Some(&api_key)).await;
1302        let mut slots = self.slots();
1303        let slot = slots.get_mut(&launch.id).expect("slot exists");
1304        if slot.generation == generation && slot.state == ModelState::Loading {
1305            if measured.is_some() {
1306                slot.measured = measured;
1307            }
1308            slot.state = ModelState::Ready;
1309            tracing::info!(model = %launch.id, secs = started.elapsed().as_secs_f32(), "engine ready");
1310            Ok(())
1311        } else {
1312            Err(Start::Failed(unavailable(format!("{} stopped while loading", launch.id))))
1313        }
1314    }
1315
1316    /// Whether the server answering on `port` is this launch's engine: it takes the launch's key
1317    /// on `/v1/models` (llama-server and vLLM check it there) and lists the launch's id. `None`
1318    /// while that can't be told yet (no answer, or a server error). MLX-LM has no key and its port
1319    /// is the proxy's, bound before the engine starts, so it is always ours.
1320    async fn identify(&self, launch: &ModelLaunch, port: u16, key: &str) -> Option<bool> {
1321        if launch.engine == EngineKind::Mlx {
1322            return Some(true);
1323        }
1324        let resp =
1325            self.inner.http.get(format!("http://127.0.0.1:{port}/v1/models")).bearer_auth(key).timeout(Duration::from_secs(5)).send().await.ok()?;
1326        let status = resp.status();
1327        if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
1328            return Some(false);
1329        }
1330        if !status.is_success() {
1331            return None;
1332        }
1333        let v: Value = resp.json().await.ok()?;
1334        Some(lists_model(&v, &launch.id))
1335    }
1336
1337    fn is_loading(&self, id: &str, generation: u64) -> bool {
1338        self.slots().get(id).is_some_and(|s| s.generation == generation && s.state == ModelState::Loading)
1339    }
1340
1341    /// Whether an engine that just exited lost its port to another process: something else holds
1342    /// `port` now, or its log since the launch (from byte `log_from`) says the address was in use.
1343    fn lost_port(&self, id: &str, port: u16, log_from: u64) -> bool {
1344        if std::net::TcpListener::bind(("127.0.0.1", port)).is_err() {
1345            return true;
1346        }
1347        let Some(dir) = &self.inner.opts.log_dir else { return false };
1348        let Ok(bytes) = std::fs::read(dir.join(format!("{id}.log"))) else { return false };
1349        let new = bytes.get(log_from as usize..).unwrap_or_default();
1350        says_address_in_use(&String::from_utf8_lossy(new))
1351    }
1352
1353    fn log_len(&self, id: &str) -> u64 {
1354        let Some(dir) = &self.inner.opts.log_dir else { return 0 };
1355        std::fs::metadata(dir.join(format!("{id}.log"))).map(|m| m.len()).unwrap_or(0)
1356    }
1357
1358    /// The monitor saw the engine exit. A stop sets `Unloaded` before signalling, so anything else
1359    /// is a crash: count it, and schedule a restart with backoff unless it is a crash loop.
1360    /// `lost_port`: it died while loading because its port was taken; the launch is retried, so
1361    /// it is not counted as a crash.
1362    fn exited(&self, id: &str, generation: u64, desc: String, lost_port: bool) {
1363        let opts = &self.inner.opts;
1364        let (event, restart_in) = {
1365            let mut slots = self.slots();
1366            let Some(slot) = slots.get_mut(id).filter(|s| s.generation == generation) else { return };
1367            slot.running = None;
1368            if slot.state == ModelState::Unloaded {
1369                return;
1370            }
1371            if lost_port {
1372                slot.state = ModelState::Failed(format!("{desc}: its port was taken"));
1373                return;
1374            }
1375            let was_serving = slot.state == ModelState::Ready;
1376            let now = Instant::now();
1377            slot.crashes.retain(|t| now.duration_since(*t) < opts.crash_window);
1378            slot.crashes.push(now);
1379            let n = slot.crashes.len();
1380            tracing::warn!(model = %id, crashes = n, "{desc}");
1381            if n >= opts.max_crashes {
1382                slot.crash_loop = true;
1383                slot.state = ModelState::Failed(format!("crash loop: {n} crashes in {}s ({desc})", opts.crash_window.as_secs()));
1384                (SupervisorEvent::CrashLoop { model: id.into(), crashes: n }, None)
1385            } else {
1386                slot.state = ModelState::Failed(desc.clone());
1387                // A crash while loading is reported to whoever is loading; only a crash while
1388                // serving restarts on its own.
1389                let delay = (opts.restart && was_serving).then(|| backoff(opts.backoff_base, opts.backoff_max, n));
1390                slot.restart_at = delay.map(|d| now + d);
1391                (SupervisorEvent::Crashed { model: id.into(), why: desc, crashes: n, restart_in_secs: delay.map(|d| d.as_secs_f32()) }, delay)
1392            }
1393        };
1394        self.emit(event);
1395        if let Some(delay) = restart_in {
1396            let me = self.clone();
1397            let id = id.to_string();
1398            tokio::spawn(async move {
1399                tokio::time::sleep(delay).await;
1400                let due = me.slots().get(&id).is_some_and(|s| {
1401                    matches!(s.state, ModelState::Failed(_)) && !s.crash_loop && s.restart_at.is_some_and(|at| at <= Instant::now())
1402                });
1403                if due {
1404                    tracing::info!(model = %id, "restarting after crash");
1405                    if let Some(s) = me.slots().get_mut(&id) {
1406                        s.restart_at = None;
1407                    }
1408                    if let Err(e) = me.load(&id).await {
1409                        tracing::warn!(model = %id, "restart failed: {e}");
1410                    }
1411                }
1412            });
1413        }
1414    }
1415
1416    fn failed(&self, id: &str, generation: u64, why: String) -> RemoteError {
1417        if let Some(slot) = self.slots().get_mut(id).filter(|s| s.generation == generation)
1418            && !slot.crash_loop
1419        {
1420            slot.state = ModelState::Failed(why.clone());
1421        }
1422        unavailable(format!("{id}: {why}"))
1423    }
1424
1425    /// Drains, marks unloaded and stops the engine. Caller holds `ops`.
1426    async fn stop(&self, id: &str, idle: bool) {
1427        let in_flight = {
1428            let mut slots = self.slots();
1429            let Some(slot) = slots.get_mut(id) else { return };
1430            if slot.running.is_none() {
1431                if !matches!(slot.state, ModelState::Failed(_)) {
1432                    slot.state = ModelState::Unloaded;
1433                }
1434                return;
1435            }
1436            slot.state = ModelState::Draining;
1437            slot.in_flight.clone()
1438        };
1439        let deadline = Instant::now() + self.inner.opts.drain_timeout;
1440        while in_flight.load(Ordering::SeqCst) > 0 && Instant::now() < deadline {
1441            tokio::time::sleep(Duration::from_millis(50)).await;
1442        }
1443        let (stop, mut exited) = {
1444            let mut slots = self.slots();
1445            let Some(slot) = slots.get_mut(id) else { return };
1446            slot.state = ModelState::Unloaded;
1447            match slot.running.as_mut() {
1448                Some(r) if r.stop.is_some() => (r.stop.take(), r.exited.clone()),
1449                Some(_) => {
1450                    // Wrapped: detach only.
1451                    slot.running = None;
1452                    drop(slots);
1453                    self.emit(SupervisorEvent::Unloaded { model: id.into(), idle });
1454                    return;
1455                }
1456                None => return,
1457            }
1458        };
1459        if let Some(stop) = stop {
1460            let _ = stop.send(());
1461        }
1462        let wait = self.inner.opts.stop_grace + Duration::from_secs(5);
1463        let _ = tokio::time::timeout(wait, exited.wait_for(Option::is_some)).await;
1464        tracing::info!(model = %id, "engine stopped");
1465        self.emit(SupervisorEvent::Unloaded { model: id.into(), idle });
1466    }
1467
1468    /// The engine, request target, URL, key and in-flight guard for pool id `id` (a model, or an
1469    /// adapter its ready base's engine has loaded). `scale` overrides the adapter's own.
1470    fn routed(&self, id: &str, scale: Option<f32>) -> Result<(EngineKind, Target, String, Option<String>, InFlight), RemoteError> {
1471        let route = self.route(id)?;
1472        if let Some(s) = scale {
1473            check_scale(s)?;
1474            if route.adapter.is_none() {
1475                return Err(bad_request(format!("{id} is not an adapter; an adapter scale doesn't apply")));
1476            }
1477        }
1478        let (engine, target) = {
1479            let slots = self.slots();
1480            let slot = slots.get(&route.base).ok_or_else(|| unknown_model(id))?;
1481            let engine = slot.launch.engine;
1482            let target = match &route.adapter {
1483                None => Target::Base { alias: route.base.clone(), has_adapters: slot.running.as_ref().is_some_and(|r| !r.adapters.is_empty()) },
1484                Some(a) => {
1485                    if scale.is_some() && engine != EngineKind::Llamacpp {
1486                        return Err(bad_request(format!("{id} runs on {}, which applies adapters at full strength", engine.name())));
1487                    }
1488                    let index = slot
1489                        .running
1490                        .as_ref()
1491                        .and_then(|r| r.index(engine, a))
1492                        .ok_or_else(|| unavailable(format!("{id} is not loaded; load it (this restarts {})", route.base)))?;
1493                    Target::Adapter { base: route.base.clone(), index, id: a.id.clone(), scale: scale.unwrap_or(a.effective_scale()) }
1494                }
1495            };
1496            (engine, target)
1497        };
1498        let (base, key, guard) = self.target(&route.base)?;
1499        Ok((engine, target, base, key, guard))
1500    }
1501
1502    /// Where requests for `id` go, with the in-flight guard taken.
1503    fn target(&self, id: &str) -> Result<(String, Option<String>, InFlight), RemoteError> {
1504        let slots = self.slots();
1505        let slot = slots.get(id).ok_or_else(|| unknown_model(id))?;
1506        match (&slot.state, &slot.running) {
1507            (ModelState::Ready, Some(r)) => {
1508                Ok((r.base.clone(), r.api_key.clone(), InFlight::new(slot.in_flight.clone(), slot.last_used.clone(), self.inner.epoch)))
1509            }
1510            (state, _) => Err(unavailable(format!("{id} is not ready ({state:?})"))),
1511        }
1512    }
1513
1514    async fn post(&self, url: String, key: Option<&str>, body: &Value) -> Result<reqwest::Response, RemoteError> {
1515        self.send(self.inner.http.post(url).json(body), key).await
1516    }
1517
1518    async fn send(&self, mut req: reqwest::RequestBuilder, key: Option<&str>) -> Result<reqwest::Response, RemoteError> {
1519        if let Some(k) = key {
1520            req = req.bearer_auth(k);
1521        }
1522        let resp = req.send().await.map_err(|e| engine_error(format!("request failed: {e}")))?;
1523        let status = resp.status();
1524        if status.as_u16() == 503 || status.as_u16() == 429 {
1525            return Err(RemoteError::Busy);
1526        }
1527        if !status.is_success() {
1528            let body = resp.text().await.unwrap_or_default();
1529            return Err(match status.as_u16() {
1530                400 | 422 => bad_request(trim(&body)),
1531                _ => engine_error(format!("{status}: {}", trim(&body))),
1532            });
1533        }
1534        Ok(resp)
1535    }
1536
1537    /// Transcribes `request.audio` with `id`, which must be ready and transcribe here
1538    /// ([`Capabilities::transcribe`]; otherwise `Unsupported`, so a pool tries elsewhere). Returns
1539    /// the transcript and the engine's token counts when it gives them.
1540    ///
1541    /// - llama.cpp (a model with an audio projector, such as Voxtral): a greedy
1542    ///   `/v1/chat/completions` request with the clip as a base64 `input_audio` part and an
1543    ///   instruction to answer with the transcript only, naming the language and the prompt when
1544    ///   given. No segments (the model can't time its text); the duration is read from a PCM WAV
1545    ///   clip's header. llama-server takes WAV and MP3.
1546    /// - vLLM (Whisper and other transcription models): `/v1/audio/transcriptions`, with the
1547    ///   language and prompt, `verbose_json` (segments, language, duration) when timestamps are
1548    ///   asked for.
1549    pub async fn transcribe(&self, id: &str, request: &TranscribeRequest) -> Result<(Transcript, Option<Usage>), RemoteError> {
1550        let engine = self.engine_of(id)?;
1551        if !self.capabilities(id).is_some_and(|c| c.transcribe) {
1552            return Err(RemoteError::Unsupported { message: format!("model `{id}` does not transcribe on this node") });
1553        }
1554        request.check()?;
1555        match engine {
1556            EngineKind::Llamacpp => {
1557                let mut stream = self.chat(id, &crate::transcribe::chat_request(request)).await?;
1558                let mut text = String::new();
1559                while let Some(chunk) = stream.next().await {
1560                    match chunk? {
1561                        Chunk::Text(t) => text.push_str(&t),
1562                        Chunk::Done { usage, .. } => {
1563                            let mut t = Transcript::new(text.trim());
1564                            if let Some(lang) = request.language.as_deref().map(str::trim).filter(|l| !l.is_empty()) {
1565                                t = t.with_language(lang);
1566                            }
1567                            if let Some(ms) = crate::transcribe::wav_duration_ms(&request.audio) {
1568                                t = t.with_duration_ms(ms);
1569                            }
1570                            return Ok((t, usage));
1571                        }
1572                        _ => {}
1573                    }
1574                }
1575                Err(engine_error("engine stream ended early"))
1576            }
1577            EngineKind::Vllm => {
1578                let (base, key, _guard) = self.target(id)?;
1579                let format = request.format.trim().to_ascii_lowercase();
1580                let file = reqwest::multipart::Part::bytes(request.audio.clone()).file_name(format!("audio.{format}"));
1581                let mut form = reqwest::multipart::Form::new()
1582                    .part("file", file)
1583                    .text("model", id.to_string())
1584                    .text("temperature", "0")
1585                    .text("response_format", if request.timestamps { "verbose_json" } else { "json" });
1586                if request.timestamps {
1587                    form = form.text("timestamp_granularities[]", "segment");
1588                }
1589                if let Some(l) = request.language.as_deref().map(str::trim).filter(|l| !l.is_empty()) {
1590                    form = form.text("language", l.to_string());
1591                }
1592                if let Some(p) = request.prompt.as_deref().filter(|p| !p.trim().is_empty()) {
1593                    form = form.text("prompt", p.to_string());
1594                }
1595                let resp = self.send(self.inner.http.post(format!("{base}/v1/audio/transcriptions")).multipart(form), key.as_deref()).await?;
1596                let v: Value = resp.json().await.map_err(|e| engine_error(format!("bad transcription response: {e}")))?;
1597                let t = crate::transcribe::from_openai(&v).ok_or_else(|| engine_error("transcription response has no text"))?;
1598                Ok((t, crate::transcribe::usage(&v)))
1599            }
1600            other => Err(RemoteError::Unsupported { message: format!("{id} runs on {}, which serves no transcription", other.name()) }),
1601        }
1602    }
1603
1604    /// Streams a chat answer from `id`, which must be ready. Dropping the stream aborts the engine
1605    /// request. For an adapter on llama.cpp, [`Request::adapter_scale`] overrides its scale.
1606    ///
1607    /// Video parts (since 0.4.10) go only to a model that reads video here
1608    /// ([`Capabilities::video`]); otherwise the request is `Unsupported` with `weirdnet-agent`'s
1609    /// `VIDEO_FALLBACK` (send frames instead). A clip over the model's known `video_max_bytes`
1610    /// is a `BadRequest` naming the limit.
1611    pub async fn chat(&self, id: &str, request: &Request) -> Result<ChunkStream, RemoteError> {
1612        if let Some(messages) = request.inline_messages()
1613            && crate::model_needs(messages).video
1614        {
1615            self.check_video(id, messages)?;
1616        }
1617        let (engine, target, base, key, guard) = self.routed(id, request.adapter_scale)?;
1618        let body = openai::chat_body_for(request, &target, engine)?;
1619        let resp = self.post(format!("{base}/v1/chat/completions"), key.as_deref(), &body).await?;
1620        Ok(stream_chunks(resp, guard))
1621    }
1622
1623    /// Streams a raw text completion of `prompt` from `id`, which must be ready. Response
1624    /// formats and tools don't apply.
1625    pub async fn complete(&self, id: &str, prompt: &str, sampling: &Sampling, seed: Option<u64>) -> Result<ChunkStream, RemoteError> {
1626        self.complete_scaled(id, prompt, sampling, seed, None).await
1627    }
1628
1629    /// [`Supervisor::complete`] with an adapter scale for this request (llama.cpp adapters only;
1630    /// `None` uses the adapter's own).
1631    pub async fn complete_scaled(
1632        &self,
1633        id: &str,
1634        prompt: &str,
1635        sampling: &Sampling,
1636        seed: Option<u64>,
1637        adapter_scale: Option<f32>,
1638    ) -> Result<ChunkStream, RemoteError> {
1639        let (engine, target, base, key, guard) = self.routed(id, adapter_scale)?;
1640        let body = openai::completion_body_for(prompt, sampling, seed, &target, engine);
1641        let resp = self.post(format!("{base}/v1/completions"), key.as_deref(), &body).await?;
1642        Ok(stream_chunks(resp, guard))
1643    }
1644
1645    /// Whether `id` takes the video parts in `messages` ([`Supervisor::chat`]).
1646    fn check_video(&self, id: &str, messages: &[weirdnet_agent::Message]) -> Result<(), RemoteError> {
1647        let caps = self.capabilities(id).ok_or_else(|| unknown_model(id))?;
1648        if !caps.video {
1649            return Err(RemoteError::Unsupported {
1650                message: format!("model `{id}` does not take video on this node; {}", weirdnet_agent::remote::catalog::VIDEO_FALLBACK),
1651            });
1652        }
1653        if let Some(max) = caps.limits.video_max_bytes {
1654            for m in messages {
1655                if let weirdnet_agent::Content::Parts(parts) = &m.content {
1656                    for p in parts {
1657                        if let weirdnet_agent::ContentPart::VideoUrl { video_url } = p
1658                            && let Some(n) = video_url.data_len()
1659                            && n > max
1660                        {
1661                            return Err(bad_request(format!("model `{id}` takes video of at most {max} bytes (video_max_bytes); this clip is {n}")));
1662                        }
1663                    }
1664                }
1665            }
1666        }
1667        Ok(())
1668    }
1669
1670    /// Speaks `request` with `id`, which must be ready and speak here ([`Capabilities::speak`];
1671    /// otherwise `Unsupported`, so a pool tries elsewhere), through the engine's
1672    /// `/v1/audio/speech` (llama-server or vLLM-Omni; see the crate's `speak` adapters for the
1673    /// fields each takes). The request is checked against the model's speech profile
1674    /// ([`Supervisor::speech`], `SpeechProfile::covers`): what the model lacks is a
1675    /// `BadRequest` naming it, except an output format this engine doesn't make, which is
1676    /// `Unsupported` (another engine may). Returns the audio as it comes: streamed when asked and
1677    /// the engine streams, else the finished file; the header carries the format and, when
1678    /// known, the sample rate (vLLM-Omni's `x-audio-sample-rate`, a `Content-Type` `rate`, the
1679    /// WAV header, else the profile's) and channels (WAV). Usage counts the characters spoken
1680    /// and, for WAV, the milliseconds of audio. Neither text nor audio is logged. Since 0.4.10.
1681    pub async fn speak(&self, id: &str, request: &SpeakRequest) -> Result<AudioStream, RemoteError> {
1682        let engine = self.engine_of(id)?;
1683        let (speaks, profile, launch) = {
1684            let slots = self.slots();
1685            let s = slots.get(id).ok_or_else(|| unknown_model(id))?;
1686            (s.capabilities().speak, s.speech(), s.launch.clone())
1687        };
1688        if !speaks {
1689            return Err(RemoteError::Unsupported { message: format!("model `{id}` does not speak on this node") });
1690        }
1691        request.check()?;
1692        let profile = match profile {
1693            Some(Ok(p)) => p,
1694            Some(Err(e)) => return Err(bad_request(format!("model `{id}`: {e}"))),
1695            None => return Err(RemoteError::Unsupported { message: format!("model `{id}` does not speak on this node") }),
1696        };
1697        let needs = request.needs();
1698        if let Err(why) = profile.covers(&needs) {
1699            let mut other_format = needs.clone();
1700            other_format.format = None;
1701            return Err(if needs.format.is_some() && profile.covers(&other_format).is_ok() {
1702                RemoteError::Unsupported { message: format!("model `{id}` {why} on this node") }
1703            } else {
1704                bad_request(format!("model `{id}` {why}"))
1705            });
1706        }
1707        let b = crate::speak::body(engine, id, request, &profile, crate::speak::task_type(&launch))?;
1708        let (base, key, guard) = self.target(id)?;
1709        tracing::debug!(model = %id, chars = needs.input_chars, "speaking");
1710        let resp = self.post(format!("{base}/v1/audio/speech"), key.as_deref(), &b.body).await?;
1711        speech_stream(resp, b, request.input.chars(), profile.sample_rate, guard).await
1712    }
1713
1714    fn engine_of(&self, id: &str) -> Result<EngineKind, RemoteError> {
1715        if let Route { base, adapter: Some(_) } = self.route(id)? {
1716            return Err(bad_request(format!("{id} is an adapter on {base}; adapters serve chat and completions only")));
1717        }
1718        self.slots().get(id).map(|s| s.launch.engine).ok_or_else(|| unknown_model(id))
1719    }
1720
1721    /// Embeds `input` with `id` (an embedding model). Returns the vectors in input order and the
1722    /// prompt tokens used.
1723    pub async fn embed(&self, id: &str, input: &[String]) -> Result<(Vec<Vec<f32>>, u64), RemoteError> {
1724        if self.engine_of(id)? == EngineKind::Mlx {
1725            return Err(bad_request(format!("{id} runs on MLX-LM, which serves no embeddings")));
1726        }
1727        let (base, key, _guard) = self.target(id)?;
1728        let resp =
1729            self.post(format!("{base}/v1/embeddings"), key.as_deref(), &json!({"model": id, "input": input, "encoding_format": "float"})).await?;
1730        let v: Value = resp.json().await.map_err(|e| engine_error(format!("bad embeddings response: {e}")))?;
1731        let mut rows: Vec<(u64, Vec<f32>)> = v["data"]
1732            .as_array()
1733            .ok_or_else(|| engine_error("embeddings response has no data"))?
1734            .iter()
1735            .enumerate()
1736            .map(|(i, d)| {
1737                (
1738                    d["index"].as_u64().unwrap_or(i as u64),
1739                    d["embedding"].as_array().map(|e| e.iter().filter_map(Value::as_f64).map(|x| x as f32).collect()).unwrap_or_default(),
1740                )
1741            })
1742            .collect();
1743        rows.sort_by_key(|(i, _)| *i);
1744        if rows.len() != input.len() {
1745            return Err(engine_error(format!("asked for {} embeddings, got {}", input.len(), rows.len())));
1746        }
1747        Ok((rows.into_iter().map(|(_, e)| e).collect(), v["usage"]["prompt_tokens"].as_u64().unwrap_or(0)))
1748    }
1749
1750    fn log_file(&self, id: &str) -> Option<(std::fs::File, std::fs::File)> {
1751        let dir = self.inner.opts.log_dir.as_ref()?;
1752        std::fs::create_dir_all(dir).ok()?;
1753        let f = std::fs::OpenOptions::new().create(true).append(true).open(dir.join(format!("{id}.log"))).ok()?;
1754        Some((f.try_clone().ok()?, f))
1755    }
1756
1757    fn log_tail(&self, id: &str) -> String {
1758        let Some(dir) = &self.inner.opts.log_dir else { return String::new() };
1759        let Ok(text) = std::fs::read_to_string(dir.join(format!("{id}.log"))) else { return String::new() };
1760        let lines: Vec<&str> = text.lines().rev().take(8).collect();
1761        let tail: Vec<&str> = lines.into_iter().rev().collect();
1762        format!("; log {}:\n{}", dir.join(format!("{id}.log")).display(), tail.join("\n"))
1763    }
1764}
1765
1766/// Adapter scales must be finite and within ±[`MAX_ADAPTER_SCALE`].
1767fn check_scale(s: f32) -> Result<(), RemoteError> {
1768    if s.is_finite() && s.abs() <= MAX_ADAPTER_SCALE {
1769        Ok(())
1770    } else {
1771        Err(bad_request(format!("adapter scale {s} must be within ±{MAX_ADAPTER_SCALE}")))
1772    }
1773}
1774
1775/// The largest adapter scale a request or [`Supervisor::set_adapter_scale`] may set.
1776pub const MAX_ADAPTER_SCALE: f32 = 16.0;
1777
1778/// `base * 2^(n-1)`, at most `max`.
1779fn backoff(base: Duration, max: Duration, n: usize) -> Duration {
1780    let factor = 1u32.checked_shl(n.saturating_sub(1).min(16) as u32).unwrap_or(u32::MAX);
1781    base.saturating_mul(factor).min(max)
1782}
1783
1784/// The audio of a `/v1/audio/speech` answer as an [`AudioStream`]: the finished file, or with
1785/// `body.stream` the bytes as they come (the engine request is dropped when the asker goes away).
1786async fn speech_stream(
1787    resp: reqwest::Response,
1788    body: crate::speak::SpeechBody,
1789    chars: u64,
1790    profile_rate: Option<u32>,
1791    guard: InFlight,
1792) -> Result<AudioStream, RemoteError> {
1793    let ct = resp.headers().get(reqwest::header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).unwrap_or("").to_ascii_lowercase();
1794    if ct.starts_with("application/json") || ct.starts_with("text/") {
1795        let text = resp.text().await.unwrap_or_default();
1796        return Err(engine_error(format!("the engine answered with {ct}, not audio: {}", trim(&text))));
1797    }
1798    let rate = crate::speak::header_rate(resp.headers());
1799    let format = body.format;
1800    let pcm = format == AudioFormat::Pcm16;
1801    let pcm_channels = if pcm { crate::speak::header_channels(resp.headers()).or(body.pcm_channels) } else { None };
1802    let pcm_rate = if pcm { rate.or(profile_rate) } else { None };
1803    let header = move |head: &[u8]| {
1804        let wav = if format == AudioFormat::Wav { crate::speak::wav_format(head) } else { None };
1805        let mut h = AudioHeader::new(format);
1806        if let Some(hz) = rate.or(wav.map(|w| w.0)).or(profile_rate) {
1807            h = h.with_sample_rate(hz);
1808        }
1809        if let Some(ch) = wav.map(|w| w.1).or(pcm_channels) {
1810            h = h.with_channels(ch);
1811        }
1812        h
1813    };
1814    // Milliseconds of audio: from the WAV header, or for 16-bit PCM from its known rate and
1815    // channels; otherwise not counted.
1816    let usage = move |head: &[u8], total: u64| {
1817        let ms = match (format, pcm_rate, pcm_channels) {
1818            (AudioFormat::Wav, _, _) => crate::speak::wav_ms(head, total),
1819            (AudioFormat::Pcm16, Some(hz), Some(ch)) => Some(total * 1000 / (u64::from(hz) * 2 * u64::from(ch))),
1820            _ => None,
1821        };
1822        Usage::speech(chars, ms.unwrap_or(0))
1823    };
1824    let meta = (!body.meta.ignored.is_empty()).then_some(body.meta);
1825    if !body.stream {
1826        let bytes = resp.bytes().await.map_err(|e| engine_error(format!("audio broke off: {e}")))?.to_vec();
1827        drop(guard);
1828        if bytes.is_empty() {
1829            return Err(engine_error("the engine sent no audio"));
1830        }
1831        let mut pieces = vec![Ok(SpeechPiece::Start(header(&bytes))), Ok(SpeechPiece::Usage(usage(&bytes, bytes.len() as u64)))];
1832        pieces.insert(1, Ok(SpeechPiece::Audio(bytes)));
1833        pieces.extend(meta.map(|m| Ok(SpeechPiece::Meta(m))));
1834        return Ok(AudioStream::from_pieces(pieces));
1835    }
1836    let (sink, out) = AudioStream::channel(16);
1837    tokio::spawn(async move {
1838        let _guard = guard;
1839        let mut stream = resp.bytes_stream();
1840        let mut head: Vec<u8> = Vec::new();
1841        let mut pending: Vec<u8> = Vec::new();
1842        let mut started = false;
1843        let mut total = 0u64;
1844        loop {
1845            match stream.next().await {
1846                Some(Ok(chunk)) => {
1847                    if chunk.is_empty() {
1848                        continue;
1849                    }
1850                    total += chunk.len() as u64;
1851                    if head.len() < 4096 {
1852                        head.extend_from_slice(&chunk[..chunk.len().min(4096 - head.len())]);
1853                    }
1854                    if !started {
1855                        pending.extend_from_slice(&chunk);
1856                        // A WAV header first, so the rate and channels can be told.
1857                        if format == AudioFormat::Wav && pending.len() < 44 {
1858                            continue;
1859                        }
1860                        if sink.start(header(&head)).await.is_err() || sink.audio(std::mem::take(&mut pending)).await.is_err() {
1861                            return;
1862                        }
1863                        started = true;
1864                    } else if sink.audio(chunk.to_vec()).await.is_err() {
1865                        return;
1866                    }
1867                }
1868                Some(Err(e)) => {
1869                    let _ = sink.fail(engine_error(format!("audio stream broke: {e}"))).await;
1870                    return;
1871                }
1872                None => break,
1873            }
1874        }
1875        if !started {
1876            if pending.is_empty() {
1877                let _ = sink.fail(engine_error("the engine sent no audio")).await;
1878                return;
1879            }
1880            if sink.start(header(&head)).await.is_err() || sink.audio(pending).await.is_err() {
1881                return;
1882            }
1883        }
1884        let _ = sink.usage(usage(&head, total)).await;
1885        if let Some(m) = meta {
1886            let _ = sink.meta(m).await;
1887        }
1888    });
1889    Ok(out)
1890}
1891
1892fn stream_chunks(resp: reqwest::Response, guard: InFlight) -> ChunkStream {
1893    let (tx, rx) = tokio::sync::mpsc::channel(64);
1894    tokio::spawn(async move {
1895        let _guard = guard;
1896        let mut bytes = resp.bytes_stream();
1897        let mut parser = SseParser::default();
1898        let mut decoder = ChunkDecoder::default();
1899        loop {
1900            let payloads = match bytes.next().await {
1901                Some(Ok(chunk)) => parser.feed(&chunk),
1902                Some(Err(e)) => {
1903                    let _ = tx.send(Err(engine_error(format!("stream broke: {e}")))).await;
1904                    return;
1905                }
1906                None => {
1907                    let rest: Vec<String> = parser.finish().into_iter().collect();
1908                    for p in rest {
1909                        if !send_all(&tx, decoder.decode(&p)).await {
1910                            return;
1911                        }
1912                    }
1913                    let last = if decoder.complete() { decoder.finish().map(Ok) } else { Some(Err(engine_error("engine stream ended early"))) };
1914                    if let Some(last) = last {
1915                        let _ = tx.send(last).await;
1916                    }
1917                    return;
1918                }
1919            };
1920            for p in payloads {
1921                let done = p.trim() == "[DONE]";
1922                if !send_all(&tx, decoder.decode(&p)).await || done {
1923                    return;
1924                }
1925            }
1926        }
1927    });
1928    Box::pin(ReceiverStream::new(rx))
1929}
1930
1931/// Sends decoded frames; false when the stream should end (receiver gone, or an error was sent).
1932async fn send_all(tx: &tokio::sync::mpsc::Sender<Result<Chunk, RemoteError>>, evs: Result<Vec<Chunk>, RemoteError>) -> bool {
1933    match evs {
1934        Ok(evs) => {
1935            for ev in evs {
1936                if tx.send(Ok(ev)).await.is_err() {
1937                    return false;
1938                }
1939            }
1940            true
1941        }
1942        Err(e) => {
1943            let _ = tx.send(Err(e)).await;
1944            false
1945        }
1946    }
1947}
1948
1949/// Counts a request in flight; on drop, records when the model was last used.
1950struct InFlight {
1951    n: Arc<AtomicUsize>,
1952    last_used: Arc<AtomicU64>,
1953    epoch: Instant,
1954}
1955
1956impl InFlight {
1957    fn new(n: Arc<AtomicUsize>, last_used: Arc<AtomicU64>, epoch: Instant) -> Self {
1958        n.fetch_add(1, Ordering::SeqCst);
1959        Self { n, last_used, epoch }
1960    }
1961}
1962
1963impl Drop for InFlight {
1964    fn drop(&mut self) {
1965        self.last_used.store(self.epoch.elapsed().as_millis() as u64, Ordering::SeqCst);
1966        self.n.fetch_sub(1, Ordering::SeqCst);
1967    }
1968}
1969
1970async fn terminate(child: &mut tokio::process::Child, pid: Option<u32>, grace: Duration) -> std::io::Result<std::process::ExitStatus> {
1971    #[cfg(unix)]
1972    if let Some(pid) = pid.and_then(|p| i32::try_from(p).ok()) {
1973        // SAFETY: plain syscall; the negative pid targets the engine's own process group.
1974        unsafe {
1975            libc::kill(-pid, libc::SIGTERM);
1976        }
1977        if let Ok(status) = tokio::time::timeout(grace, child.wait()).await {
1978            return status;
1979        }
1980        // SAFETY: as above.
1981        unsafe {
1982            libc::kill(-pid, libc::SIGKILL);
1983        }
1984        return child.wait().await;
1985    }
1986    let _ = (pid, grace);
1987    child.start_kill()?;
1988    child.wait().await
1989}
1990
1991/// How many ports a launch tries when the one it was given turns out to be taken.
1992const PORT_TRIES: usize = 3;
1993
1994/// How one launch attempt failed.
1995enum Start {
1996    /// Another process took the port it was given; worth another try on a new port.
1997    PortTaken(RemoteError),
1998    Failed(RemoteError),
1999}
2000
2001/// `/v1/models` lists `id` (as a model id, or a llama-server alias).
2002fn lists_model(v: &Value, id: &str) -> bool {
2003    v["data"].as_array().is_some_and(|d| {
2004        d.iter().any(|m| m["id"].as_str() == Some(id) || m["aliases"].as_array().is_some_and(|a| a.iter().any(|x| x.as_str() == Some(id))))
2005    })
2006}
2007
2008/// An engine's log says it could not bind its address (llama-server, uvicorn/vLLM, MLX-LM).
2009fn says_address_in_use(log: &str) -> bool {
2010    let l = log.to_ascii_lowercase();
2011    ["address already in use", "couldn't bind", "could not bind", "errno 98", "errno 48", "eaddrinuse", "os error 98", "os error 48", "error 10048"]
2012        .iter()
2013        .any(|p| l.contains(p))
2014}
2015
2016fn free_port() -> std::io::Result<u16> {
2017    Ok(std::net::TcpListener::bind(("127.0.0.1", 0))?.local_addr()?.port())
2018}
2019
2020/// Random hex from the OS RNG.
2021pub(crate) fn random_hex(bytes: usize) -> String {
2022    let mut buf = vec![0u8; bytes];
2023    getrandom::fill(&mut buf).expect("the OS RNG is available");
2024    buf.iter().map(|b| format!("{b:02x}")).collect()
2025}
2026
2027fn trim(s: &str) -> String {
2028    let s = s.trim();
2029    if s.len() > 500 { format!("{}...", &s[..s.floor_char_boundary(500)]) } else { s.to_string() }
2030}
2031
2032#[cfg(test)]
2033mod tests {
2034    use super::*;
2035
2036    #[test]
2037    fn model_status_limits_propagate_and_old_rows_read() {
2038        use weirdnet_agent::remote::catalog::{CatalogModel, ModelState as CatalogState, Purpose};
2039        use weirdnet_agent::{MediaLimits, Modalities};
2040        // A row as a 0.4.7 node sends it: no limits anywhere.
2041        let old = r#"{"id":"g","engine":"llamacpp","state":{"state":"ready"},"in_flight":0,"swap_group":null,"embedding":false,"pid":null,
2042            "last_load_secs":null,"size_bytes":null,"wrapped":false,"crashes":0,"context":8192,"slots":null,
2043            "capabilities":{"chat":true,"embeddings":false,"vision":true,"audio":false},"base":null}"#;
2044        let row: ModelStatus = serde_json::from_str(old).unwrap();
2045        assert!(row.limits().is_unknown());
2046        let e = row.apply_to(CatalogModel::new("g", Purpose::Chat, CatalogState::Warm));
2047        assert_eq!((e.inputs, e.context), (Modalities::VISION, Some(8192)));
2048        assert!(e.limits.is_unknown());
2049        assert!(!serde_json::to_string(&row).unwrap().contains("limits"));
2050
2051        let limits = MediaLimits::new().with_max_images(3).with_image_tokens(576).with_max_request_bytes(8 << 20);
2052        let launch = ModelLaunch::new("g", EngineKind::Llamacpp, "/m/g.gguf").with_mmproj("/p/mm.gguf").with_limits(limits);
2053        let mut row = row;
2054        row.capabilities = Some(launch.capabilities());
2055        let back: ModelStatus = serde_json::from_str(&serde_json::to_string(&row).unwrap()).unwrap();
2056        assert_eq!(back.limits(), limits);
2057        let e = back.apply_to(CatalogModel::new("g", Purpose::Chat, CatalogState::Warm));
2058        assert_eq!((e.limits, e.inputs), (limits, Modalities::new(true, true)));
2059        let none = ModelStatus { capabilities: None, ..back };
2060        assert!(none.limits().is_unknown());
2061
2062        // The measured context per sequence wins over the configured one; old rows have none.
2063        assert_eq!(row.context_tokens, None);
2064        let measured = ModelStatus { context_tokens: Some(4096), ..none.clone() };
2065        assert_eq!(measured.apply_to(CatalogModel::new("g", Purpose::Chat, CatalogState::Warm)).context, Some(4096));
2066        let back: ModelStatus = serde_json::from_str(&serde_json::to_string(&measured).unwrap()).unwrap();
2067        assert_eq!(back.context_tokens, Some(4096));
2068        // Purpose: from the embedding flag and the capabilities (old rows: chat or embedding).
2069        assert_eq!(none.purpose(), Purpose::Chat);
2070        assert_eq!(ModelStatus { embedding: true, ..none.clone() }.purpose(), Purpose::Embedding);
2071        let t = ModelStatus { capabilities: Some(Capabilities::text().with_audio(true).with_transcribe(true)), ..none };
2072        assert_eq!(t.purpose(), Purpose::Transcribe);
2073        let e = t.catalog_model(CatalogState::Loadable);
2074        assert_eq!((e.id.as_str(), e.purpose, e.state, e.inputs), ("g", Purpose::Transcribe, CatalogState::Loadable, Modalities::new(false, true)));
2075
2076        // Speech (0.4.10): old rows have no profile and don't speak; a speaker's row carries it.
2077        assert_eq!(row.speech, None);
2078        assert!(!serde_json::to_string(&row).unwrap().contains("speech"));
2079        let profile = SpeechProfile::new().with_presets(vec!["vivian".into()]).with_formats(vec![AudioFormat::Wav]).with_sample_rate(24_000);
2080        let speaker = ModelStatus { capabilities: Some(Capabilities::default().with_speak(true)), speech: Some(profile.clone()), ..t };
2081        let back: ModelStatus = serde_json::from_str(&serde_json::to_string(&speaker).unwrap()).unwrap();
2082        assert_eq!(back, speaker);
2083        let cbor = weirdnet_agent::remote::to_cbor(&speaker).unwrap();
2084        assert_eq!(weirdnet_agent::remote::from_cbor::<ModelStatus>(&cbor).unwrap(), speaker);
2085        let e = speaker.catalog_model(CatalogState::Loadable);
2086        assert!(e.speaks());
2087        assert_eq!((e.purpose, e.speech), (Purpose::Speak, Some(profile)));
2088    }
2089
2090    #[test]
2091    fn the_engine_is_recognised_by_its_model_list() {
2092        assert!(lists_model(&json!({"data": [{"id": "qwen"}]}), "qwen"));
2093        assert!(lists_model(&json!({"data": [{"id": "x.gguf", "aliases": ["qwen"]}]}), "qwen"));
2094        assert!(!lists_model(&json!({"data": [{"id": "other"}]}), "qwen"));
2095        assert!(!lists_model(&json!({"status": "ok"}), "qwen"));
2096        assert!(says_address_in_use("srv  start: couldn't bind HTTP server socket, hostname: 127.0.0.1, port: 4100"));
2097        assert!(says_address_in_use("ERROR:    [Errno 98] error while attempting to bind on address ('127.0.0.1', 8000): address already in use"));
2098        assert!(!says_address_in_use("loading model\nCUDA error: out of memory"));
2099    }
2100
2101    #[test]
2102    fn backoff_doubles_and_caps() {
2103        let b = |n| backoff(Duration::from_secs(1), Duration::from_secs(60), n);
2104        assert_eq!(b(1), Duration::from_secs(1));
2105        assert_eq!(b(2), Duration::from_secs(2));
2106        assert_eq!(b(4), Duration::from_secs(8));
2107        assert_eq!(b(10), Duration::from_secs(60));
2108        assert_eq!(b(100), Duration::from_secs(60));
2109    }
2110}