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