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