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