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