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