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