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