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::{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`] can serve.
149#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
150#[serde(rename_all = "snake_case")]
151#[non_exhaustive]
152pub enum AdapterChange {
153    /// Now, or whenever the base is next ready: the base wasn't running.
154    Live,
155    /// After the base's next load: its engine is running without the adapter. Loading the
156    /// adapter ([`Supervisor::load`]) restarts the base.
157    NextLoad,
158}
159
160/// Where a pool id goes: its base model's slot, and the adapter if it is one.
161struct Route {
162    base: String,
163    adapter: Option<LoraAdapter>,
164}
165
166struct Running {
167    base: String,
168    /// The adapter ids the engine was started with, in `--lora` order.
169    adapters: Vec<String>,
170    api_key: Option<String>,
171    pid: Option<u32>,
172    stop: Option<oneshot::Sender<()>>,
173    exited: watch::Receiver<Option<String>>,
174    /// Keeps a wrapped server's never-firing exit channel open.
175    _exit_tx: Option<watch::Sender<Option<String>>>,
176    /// The key-checking proxy in front of an MLX-LM server; stops when the engine record goes.
177    _proxy: Option<crate::mlx::ProxyHandle>,
178}
179
180struct Slot {
181    launch: ModelLaunch,
182    state: ModelState,
183    running: Option<Running>,
184    in_flight: Arc<AtomicUsize>,
185    /// Milliseconds since the supervisor's epoch when the last request finished.
186    last_used: Arc<AtomicU64>,
187    /// Bumped on every start, so a late exit notice from an old process is ignored.
188    generation: u64,
189    load_secs: Option<f32>,
190    crashes: Vec<Instant>,
191    crash_loop: bool,
192    restart_at: Option<Instant>,
193}
194
195impl Slot {
196    fn new(launch: ModelLaunch) -> Self {
197        Self {
198            launch,
199            state: ModelState::Unloaded,
200            running: None,
201            in_flight: Arc::new(AtomicUsize::new(0)),
202            last_used: Arc::new(AtomicU64::new(0)),
203            generation: 0,
204            load_secs: None,
205            crashes: Vec::new(),
206            crash_loop: false,
207            restart_at: None,
208        }
209    }
210}
211
212struct Inner {
213    engines: HashMap<EngineKind, EngineConfig>,
214    opts: SupervisorOptions,
215    http: reqwest::Client,
216    slots: Mutex<HashMap<String, Slot>>,
217    /// Serializes load and unload, so swaps never interleave.
218    ops: tokio::sync::Mutex<()>,
219    events: broadcast::Sender<SupervisorEvent>,
220    epoch: Instant,
221}
222
223/// The per-node supervisor. Cheap to clone.
224#[derive(Clone)]
225pub struct Supervisor {
226    inner: Arc<Inner>,
227}
228
229impl Supervisor {
230    pub fn new(engines: Vec<EngineConfig>, models: Vec<ModelLaunch>, opts: SupervisorOptions) -> Self {
231        let slots = models.into_iter().map(|launch| (launch.id.clone(), Slot::new(launch))).collect();
232        let http =
233            reqwest::Client::builder().connect_timeout(Duration::from_secs(5)).no_proxy().build().expect("an HTTP client without TLS always builds");
234        let (events, _) = broadcast::channel(256);
235        Self {
236            inner: Arc::new(Inner {
237                engines: engines.into_iter().map(|e| (e.kind, e)).collect(),
238                opts,
239                http,
240                slots: Mutex::new(slots),
241                ops: tokio::sync::Mutex::new(()),
242                events,
243                epoch: Instant::now(),
244            }),
245        }
246    }
247
248    fn slots(&self) -> std::sync::MutexGuard<'_, HashMap<String, Slot>> {
249        self.inner.slots.lock().unwrap_or_else(|e| e.into_inner())
250    }
251
252    fn emit(&self, ev: SupervisorEvent) {
253        let _ = self.inner.events.send(ev);
254    }
255
256    /// The slot serving `id`: a model's own, or the base of an adapter.
257    fn route(&self, id: &str) -> Result<Route, RemoteError> {
258        let slots = self.slots();
259        if slots.contains_key(id) {
260            return Ok(Route { base: id.to_string(), adapter: None });
261        }
262        slots
263            .values()
264            .find_map(|s| s.launch.adapters.iter().find(|a| a.id == id).map(|a| Route { base: s.launch.id.clone(), adapter: Some(a.clone()) }))
265            .ok_or_else(|| unknown_model(id))
266    }
267
268    /// Whether `id` names a model or an adapter on this node.
269    fn taken(slots: &HashMap<String, Slot>, id: &str) -> bool {
270        slots.contains_key(id) || slots.values().any(|s| s.launch.adapters.iter().any(|a| a.id == id))
271    }
272
273    /// Adds LoRA adapter `adapter` to model `base`, after [`ModelLaunch::check_adapters`]. Its id
274    /// must be free on the node. Returns [`AdapterChange::NextLoad`] when the base's engine is
275    /// running (llama.cpp and vLLM take adapters at start here), else [`AdapterChange::Live`].
276    /// Emits [`SupervisorEvent::Added`] for the adapter.
277    pub fn add_adapter(&self, base: &str, adapter: LoraAdapter) -> Result<AdapterChange, RemoteError> {
278        let mut launch = self.slots().get(base).map(|s| s.launch.clone()).ok_or_else(|| unknown_model(base))?;
279        launch.adapters.push(adapter.clone());
280        launch.check_adapters().map_err(bad_request)?;
281        let running = {
282            let mut slots = self.slots();
283            if Self::taken(&slots, &adapter.id) {
284                return Err(bad_request(format!("{} is already configured on this node", adapter.id)));
285            }
286            let slot = slots.get_mut(base).ok_or_else(|| unknown_model(base))?;
287            slot.launch.adapters.push(adapter.clone());
288            slot.running.is_some()
289        };
290        self.emit(SupervisorEvent::Added { model: adapter.id });
291        Ok(if running { AdapterChange::NextLoad } else { AdapterChange::Live })
292    }
293
294    /// Stops serving adapter `id` on `base` (requests for it fail from now on; the engine keeps
295    /// it loaded until the base's next load). Emits [`SupervisorEvent::Removed`].
296    pub fn remove_adapter(&self, base: &str, id: &str) -> Result<LoraAdapter, RemoteError> {
297        let removed = {
298            let mut slots = self.slots();
299            let slot = slots.get_mut(base).ok_or_else(|| unknown_model(base))?;
300            let at = slot.launch.adapters.iter().position(|a| a.id == id).ok_or_else(|| bad_request(format!("{base} has no adapter {id}")))?;
301            slot.launch.adapters.remove(at)
302        };
303        self.emit(SupervisorEvent::Removed { model: id.into() });
304        Ok(removed)
305    }
306
307    /// Adds a model the node may load from now on, without a restart (for example one just
308    /// downloaded). It starts unloaded. Refused when the id is taken; [`Supervisor::remove_model`]
309    /// first to replace one. Emits [`SupervisorEvent::Added`].
310    pub fn add_model(&self, launch: ModelLaunch) -> Result<(), RemoteError> {
311        if launch.id.trim().is_empty() {
312            return Err(bad_request("a model needs an id"));
313        }
314        if let Some(w) = &launch.wrap {
315            w.check().map_err(bad_request)?;
316        }
317        launch.check_adapters().map_err(bad_request)?;
318        let id = launch.id.clone();
319        let ids = launch.served_ids();
320        {
321            let mut slots = self.slots();
322            if let Some(t) = ids.iter().find(|i| Self::taken(&slots, i)) {
323                return Err(bad_request(format!("{t} is already configured on this node")));
324            }
325            slots.insert(id.clone(), Slot::new(launch));
326        }
327        for model in ids {
328            self.emit(SupervisorEvent::Added { model });
329        }
330        Ok(())
331    }
332
333    /// Unloads `id` (draining requests under way) and forgets it, with its adapters. Emits
334    /// [`SupervisorEvent::Removed`] for each. Returns its launch settings. An adapter's id is
335    /// refused: use [`Supervisor::remove_adapter`].
336    pub async fn remove_model(&self, id: &str) -> Result<ModelLaunch, RemoteError> {
337        let _op = self.inner.ops.lock().await;
338        if let Route { base, adapter: Some(_) } = self.route(id)? {
339            return Err(bad_request(format!("{id} is an adapter on {base}; remove it with remove_adapter")));
340        }
341        self.stop(id, false).await;
342        let slot = self.slots().remove(id).ok_or_else(|| unknown_model(id))?;
343        for model in slot.launch.served_ids() {
344            self.emit(SupervisorEvent::Removed { model });
345        }
346        Ok(slot.launch)
347    }
348
349    /// The configured models' launch settings, sorted by id.
350    pub fn launches(&self) -> Vec<ModelLaunch> {
351        let mut out: Vec<ModelLaunch> = self.slots().values().map(|s| s.launch.clone()).collect();
352        out.sort_by(|a, b| a.id.cmp(&b.id));
353        out
354    }
355
356    /// Engine events from now on.
357    pub fn subscribe(&self) -> broadcast::Receiver<SupervisorEvent> {
358        self.inner.events.subscribe()
359    }
360
361    fn now_ms(&self) -> u64 {
362        self.inner.epoch.elapsed().as_millis() as u64
363    }
364
365    /// One row per model, and one per adapter (with [`ModelStatus::base`] set, the base's engine,
366    /// capabilities and state; `Unloaded` while the base runs without it).
367    pub fn status(&self) -> Vec<ModelStatus> {
368        let mut out: Vec<ModelStatus> = self
369            .slots()
370            .values()
371            .flat_map(|s| {
372                let row = Self::row(s);
373                let adapters: Vec<ModelStatus> = s
374                    .launch
375                    .adapters
376                    .iter()
377                    .map(|a| {
378                        let mut r = row.clone();
379                        let loaded = s.running.as_ref().is_none_or(|run| run.adapters.contains(&a.id));
380                        if !loaded {
381                            r.state = ModelState::Unloaded;
382                            r.pid = None;
383                        }
384                        r.id = a.id.clone();
385                        r.base = Some(s.launch.id.clone());
386                        r.size_bytes = std::fs::metadata(&a.path).ok().filter(|m| m.is_file()).map(|m| m.len());
387                        r
388                    })
389                    .collect();
390                std::iter::once(row).chain(adapters)
391            })
392            .collect();
393        out.sort_by(|a, b| a.id.cmp(&b.id));
394        out
395    }
396
397    fn row(s: &Slot) -> ModelStatus {
398        ModelStatus {
399            id: s.launch.id.clone(),
400            engine: s.launch.engine,
401            state: s.state.clone(),
402            in_flight: s.in_flight.load(Ordering::SeqCst),
403            swap_group: s.launch.swap_group.clone(),
404            embedding: s.launch.embedding,
405            pid: s.running.as_ref().and_then(|r| r.pid),
406            last_load_secs: s.load_secs,
407            size_bytes: if s.launch.wrap.is_some() { None } else { std::fs::metadata(&s.launch.source).ok().map(|m| m.len()) },
408            wrapped: s.launch.wrap.is_some(),
409            crashes: s.crashes.len(),
410            context: s.launch.context,
411            slots: s.launch.slots,
412            capabilities: Some(s.launch.capabilities()),
413            base: None,
414        }
415    }
416
417    /// Requests under way across all models.
418    pub fn in_flight(&self) -> usize {
419        self.slots().values().map(|s| s.in_flight.load(Ordering::SeqCst)).sum()
420    }
421
422    /// `id`'s state; an adapter has its base's (`Unloaded` while the base runs without it).
423    pub fn state(&self, id: &str) -> Option<ModelState> {
424        let route = self.route(id).ok()?;
425        let slots = self.slots();
426        let s = slots.get(&route.base)?;
427        match (&route.adapter, &s.running) {
428            (Some(a), Some(r)) if !r.adapters.contains(&a.id) => Some(ModelState::Unloaded),
429            _ => Some(s.state.clone()),
430        }
431    }
432
433    /// What `id` takes ([`ModelLaunch::capabilities`]); an adapter takes what its base does.
434    pub fn capabilities(&self, id: &str) -> Option<Capabilities> {
435        let route = self.route(id).ok()?;
436        self.slots().get(&route.base).map(|s| s.launch.capabilities())
437    }
438
439    /// Starts `id` and waits until it is ready (see [`Supervisor::load_with`]).
440    pub async fn load(&self, id: &str) -> Result<(), RemoteError> {
441        self.load_with(id, false).await
442    }
443
444    /// Starts `id` and waits until its engine is ready. Loading a model in a swap group unloads the
445    /// group's other models first. Already ready: returns at once. A model in a crash loop or
446    /// waiting for its restart refuses unless `force` (an operator's explicit load), which also
447    /// clears the crash history.
448    ///
449    /// An adapter loads its base. When the base is ready without it (added after the base
450    /// started), the base is restarted.
451    pub async fn load_with(&self, id: &str, force: bool) -> Result<(), RemoteError> {
452        let route = self.route(id)?;
453        let wanted = route.adapter.map(|a| a.id);
454        let id = route.base.as_str();
455        // A request during a crash backoff waits it out (at most `backoff_max`) rather than
456        // failing; the scheduled restart and this load serialize on `ops`.
457        if !force {
458            let wait = {
459                let slots = self.slots();
460                let slot = slots.get(id).ok_or_else(|| unknown_model(id))?;
461                slot.restart_at.and_then(|at| at.checked_duration_since(Instant::now()))
462            };
463            if let Some(d) = wait {
464                tokio::time::sleep(d.min(self.inner.opts.backoff_max)).await;
465            }
466        }
467        let _op = self.inner.ops.lock().await;
468        let (launch, group_mates) = {
469            let mut slots = self.slots();
470            let slot = slots.get_mut(id).ok_or_else(|| unknown_model(id))?;
471            let has_wanted = wanted.as_ref().is_none_or(|w| slot.running.as_ref().is_some_and(|r| r.adapters.contains(w)));
472            if slot.state == ModelState::Ready && has_wanted {
473                return Ok(());
474            }
475            if force {
476                slot.crashes.clear();
477                slot.crash_loop = false;
478                slot.restart_at = None;
479            } else if slot.crash_loop {
480                return Err(unavailable(format!("{id} is in a crash loop ({} crashes); fix it, then load it again with force", slot.crashes.len())));
481            }
482            let launch = slot.launch.clone();
483            let mates: Vec<String> = match &launch.swap_group {
484                Some(g) => slots
485                    .values()
486                    .filter(|s| s.launch.id != id && s.launch.swap_group.as_ref() == Some(g) && s.running.is_some())
487                    .map(|s| s.launch.id.clone())
488                    .collect(),
489                None => Vec::new(),
490            };
491            (launch, mates)
492        };
493        for mate in group_mates {
494            tracing::info!(model = %mate, for_model = %id, "swap group: unloading");
495            self.stop(&mate, false).await;
496        }
497        // A failed engine may still have a process record; clear it.
498        self.stop(id, false).await;
499        let started = Instant::now();
500        self.emit(SupervisorEvent::Starting { model: id.into() });
501        let result = match &launch.wrap {
502            Some(_) => self.attach(&launch).await,
503            None => self.start(&launch).await,
504        };
505        match &result {
506            Ok(()) => {
507                let secs = started.elapsed().as_secs_f32();
508                if let Some(s) = self.slots().get_mut(id) {
509                    s.load_secs = Some(secs);
510                    s.restart_at = None;
511                    s.last_used.store(self.now_ms(), Ordering::SeqCst);
512                }
513                self.emit(SupervisorEvent::Ready { model: id.into(), load_secs: secs });
514            }
515            Err(e) => self.emit(SupervisorEvent::LoadFailed { model: id.into(), why: e.to_string() }),
516        }
517        result
518    }
519
520    /// Drains and stops `id`. A wrapped server is only detached (the node doesn't own it).
521    /// An adapter's id is refused: unload its base.
522    pub async fn unload(&self, id: &str) -> Result<(), RemoteError> {
523        let _op = self.inner.ops.lock().await;
524        if let Route { base, adapter: Some(_) } = self.route(id)? {
525            return Err(bad_request(format!("{id} is an adapter on {base}; unload {base} instead")));
526        }
527        self.stop(id, false).await;
528        Ok(())
529    }
530
531    /// Stops every engine (daemon shutdown).
532    pub async fn shutdown(&self) {
533        let _op = self.inner.ops.lock().await;
534        let ids: Vec<String> = self.slots().keys().cloned().collect();
535        for id in ids {
536            self.stop(&id, false).await;
537        }
538    }
539
540    /// Unloads ready models idle past their `idle_ttl`. Returns what it unloaded. Run it every few
541    /// seconds ([`Supervisor::spawn_reaper`]).
542    pub async fn reap_idle(&self) -> Vec<String> {
543        let now = self.now_ms();
544        let idle: Vec<String> = self
545            .slots()
546            .values()
547            .filter(|s| s.state == ModelState::Ready && s.in_flight.load(Ordering::SeqCst) == 0)
548            .filter(|s| s.launch.idle_ttl.is_some_and(|ttl| now.saturating_sub(s.last_used.load(Ordering::SeqCst)) >= ttl.as_millis() as u64))
549            .map(|s| s.launch.id.clone())
550            .collect();
551        let mut done = Vec::new();
552        for id in idle {
553            // Never wait behind a load or swap; try again next round.
554            let Ok(_op) = self.inner.ops.try_lock() else { break };
555            let still_idle = self.slots().get(&id).is_some_and(|s| s.state == ModelState::Ready && s.in_flight.load(Ordering::SeqCst) == 0);
556            if still_idle {
557                tracing::info!(model = %id, "idle: unloading");
558                self.stop(&id, true).await;
559                done.push(id);
560            }
561        }
562        done
563    }
564
565    /// Runs [`Supervisor::reap_idle`] every `every` until the returned handle is aborted.
566    pub fn spawn_reaper(&self, every: Duration) -> tokio::task::JoinHandle<()> {
567        let me = self.clone();
568        tokio::spawn(async move {
569            let mut tick = tokio::time::interval(every);
570            loop {
571                tick.tick().await;
572                me.reap_idle().await;
573            }
574        })
575    }
576
577    /// A wrapped stock server: probe it and mark it ready.
578    async fn attach(&self, launch: &ModelLaunch) -> Result<(), RemoteError> {
579        let wrap = launch.wrap.as_ref().expect("attach is for wrapped models");
580        wrap.check().map_err(unavailable)?;
581        let base = wrap.base();
582        let ok = self.inner.http.get(format!("{base}/health")).timeout(Duration::from_secs(5)).send().await.is_ok_and(|r| r.status().is_success());
583        // A stock mlx_lm.server still needs the proxy for `default_model` and text-only checks.
584        let (base, api_key, proxy) = if ok && launch.engine == EngineKind::Mlx {
585            let l = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.map_err(|e| unavailable(format!("mlx proxy: {e}")))?;
586            let url = format!("http://{}", l.local_addr().map_err(|e| unavailable(format!("mlx proxy: {e}")))?);
587            let key = random_hex(24);
588            (url, Some(key.clone()), Some(crate::mlx::spawn_proxy(l, base, launch.id.clone(), key)))
589        } else {
590            (base, wrap.api_key.clone(), None)
591        };
592        let (tx, rx) = watch::channel(None);
593        let mut slots = self.slots();
594        let slot = slots.get_mut(&launch.id).expect("checked by load");
595        slot.generation += 1;
596        if !ok {
597            slot.state = ModelState::Failed(format!("wrapped server {base} is not answering /health"));
598            return Err(unavailable(format!("{}: wrapped server {base} is not answering /health", launch.id)));
599        }
600        slot.state = ModelState::Ready;
601        slot.running = Some(Running { base, adapters: Vec::new(), api_key, pid: None, stop: None, exited: rx, _exit_tx: Some(tx), _proxy: proxy });
602        Ok(())
603    }
604
605    async fn start(&self, launch: &ModelLaunch) -> Result<(), RemoteError> {
606        let engine = self
607            .inner
608            .engines
609            .get(&launch.engine)
610            .ok_or_else(|| unavailable(format!("engine {} is not configured on this node", launch.engine.name())))?
611            .clone();
612        if let Err(why) = launch.check_adapters() {
613            if let Some(s) = self.slots().get_mut(&launch.id) {
614                s.state = ModelState::Failed(why.clone());
615            }
616            return Err(bad_request(why));
617        }
618        let mlx = launch.engine == EngineKind::Mlx;
619        if mlx && launch.embedding {
620            let why = "MLX-LM serves no embeddings; run embedding models on llama.cpp or vLLM".to_string();
621            if let Some(s) = self.slots().get_mut(&launch.id) {
622                s.state = ModelState::Failed(why.clone());
623            }
624            return Err(bad_request(format!("{}: {why}", launch.id)));
625        }
626        let no_port = |e: std::io::Error| unavailable(format!("no free loopback port: {e}"));
627        // MLX-LM has no API key: it gets a private port, and the advertised one is the proxy's,
628        // bound now so nothing else can take it.
629        let (port, proxy_listener) = if mlx {
630            let l = std::net::TcpListener::bind(("127.0.0.1", 0)).map_err(no_port)?;
631            l.set_nonblocking(true).map_err(no_port)?;
632            (l.local_addr().map_err(no_port)?.port(), Some(l))
633        } else {
634            (free_port().map_err(no_port)?, None)
635        };
636        let engine_port = if mlx { free_port().map_err(no_port)? } else { port };
637        let api_key = random_hex(24);
638        let mut cmd = engine.command(launch, engine_port, &api_key);
639        cmd.stdin(Stdio::null());
640        match self.log_file(&launch.id) {
641            Some((out, err)) => {
642                cmd.stdout(out).stderr(err);
643            }
644            None => {
645                cmd.stdout(Stdio::null()).stderr(Stdio::null());
646            }
647        }
648        #[cfg(unix)]
649        {
650            cmd.process_group(0);
651            #[cfg(target_os = "linux")]
652            // SAFETY: prctl is async-signal-safe and touches no memory of the parent.
653            unsafe {
654                cmd.pre_exec(|| {
655                    libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM);
656                    Ok(())
657                });
658            }
659        }
660        let mut child = cmd.spawn().map_err(|e| unavailable(format!("could not start {}: {e}", engine.program.display())))?;
661        let pid = child.id();
662        let proxy = match proxy_listener.map(tokio::net::TcpListener::from_std) {
663            Some(Ok(l)) => Some(crate::mlx::spawn_proxy(l, format!("http://127.0.0.1:{engine_port}"), launch.id.clone(), api_key.clone())),
664            Some(Err(e)) => {
665                let _ = terminate(&mut child, pid, self.inner.opts.stop_grace).await;
666                return Err(unavailable(format!("mlx proxy: {e}")));
667            }
668            None => None,
669        };
670        let (exit_tx, exit_rx) = watch::channel(None);
671        let (stop_tx, stop_rx) = oneshot::channel::<()>();
672        let generation = {
673            let mut slots = self.slots();
674            let slot = slots.get_mut(&launch.id).expect("checked by load");
675            slot.generation += 1;
676            slot.state = ModelState::Loading;
677            slot.running = Some(Running {
678                base: format!("http://127.0.0.1:{port}"),
679                adapters: launch.adapters.iter().map(|a| a.id.clone()).collect(),
680                api_key: Some(api_key),
681                pid,
682                stop: Some(stop_tx),
683                exited: exit_rx.clone(),
684                _exit_tx: None,
685                _proxy: proxy,
686            });
687            slot.generation
688        };
689        tracing::info!(model = %launch.id, pid, port, engine = launch.engine.name(), "engine starting");
690
691        // The monitor owns the child: it reaps it and does the stopping.
692        let grace = self.inner.opts.stop_grace;
693        let me = self.clone();
694        let id = launch.id.clone();
695        tokio::spawn(async move {
696            let status = tokio::select! {
697                s = child.wait() => s,
698                _ = stop_rx => terminate(&mut child, pid, grace).await,
699            };
700            let desc = match status {
701                Ok(s) => format!("engine exited ({s})"),
702                Err(e) => format!("engine wait failed: {e}"),
703            };
704            // Record the exit (and count a crash) before anyone waiting on it wakes up.
705            me.exited(&id, generation, desc.clone());
706            let _ = exit_tx.send(Some(desc));
707        });
708
709        let started = Instant::now();
710        let health = format!("http://127.0.0.1:{port}/health");
711        let mut exited = exit_rx;
712        loop {
713            let gone = exited.borrow().clone();
714            if let Some(desc) = gone {
715                return Err(self.failed(&launch.id, generation, format!("{desc} while loading{}", self.log_tail(&launch.id))));
716            }
717            if let Ok(resp) = self.inner.http.get(&health).timeout(Duration::from_secs(2)).send().await
718                && resp.status().is_success()
719            {
720                break;
721            }
722            if started.elapsed() > engine.ready_timeout {
723                self.stop(&launch.id, false).await;
724                return Err(self.failed(&launch.id, generation, format!("not ready after {:?}{}", engine.ready_timeout, self.log_tail(&launch.id))));
725            }
726            let _ = tokio::time::timeout(Duration::from_millis(200), exited.changed()).await;
727        }
728        let mut slots = self.slots();
729        let slot = slots.get_mut(&launch.id).expect("slot exists");
730        if slot.generation == generation && slot.state == ModelState::Loading {
731            slot.state = ModelState::Ready;
732            tracing::info!(model = %launch.id, secs = started.elapsed().as_secs_f32(), "engine ready");
733            Ok(())
734        } else {
735            Err(unavailable(format!("{} stopped while loading", launch.id)))
736        }
737    }
738
739    /// The monitor saw the engine exit. A stop sets `Unloaded` before signalling, so anything else
740    /// is a crash: count it, and schedule a restart with backoff unless it is a crash loop.
741    fn exited(&self, id: &str, generation: u64, desc: String) {
742        let opts = &self.inner.opts;
743        let (event, restart_in) = {
744            let mut slots = self.slots();
745            let Some(slot) = slots.get_mut(id).filter(|s| s.generation == generation) else { return };
746            slot.running = None;
747            if slot.state == ModelState::Unloaded {
748                return;
749            }
750            let was_serving = slot.state == ModelState::Ready;
751            let now = Instant::now();
752            slot.crashes.retain(|t| now.duration_since(*t) < opts.crash_window);
753            slot.crashes.push(now);
754            let n = slot.crashes.len();
755            tracing::warn!(model = %id, crashes = n, "{desc}");
756            if n >= opts.max_crashes {
757                slot.crash_loop = true;
758                slot.state = ModelState::Failed(format!("crash loop: {n} crashes in {}s ({desc})", opts.crash_window.as_secs()));
759                (SupervisorEvent::CrashLoop { model: id.into(), crashes: n }, None)
760            } else {
761                slot.state = ModelState::Failed(desc.clone());
762                // A crash while loading is reported to whoever is loading; only a crash while
763                // serving restarts on its own.
764                let delay = (opts.restart && was_serving).then(|| backoff(opts.backoff_base, opts.backoff_max, n));
765                slot.restart_at = delay.map(|d| now + d);
766                (SupervisorEvent::Crashed { model: id.into(), why: desc, crashes: n, restart_in_secs: delay.map(|d| d.as_secs_f32()) }, delay)
767            }
768        };
769        self.emit(event);
770        if let Some(delay) = restart_in {
771            let me = self.clone();
772            let id = id.to_string();
773            tokio::spawn(async move {
774                tokio::time::sleep(delay).await;
775                let due = me.slots().get(&id).is_some_and(|s| {
776                    matches!(s.state, ModelState::Failed(_)) && !s.crash_loop && s.restart_at.is_some_and(|at| at <= Instant::now())
777                });
778                if due {
779                    tracing::info!(model = %id, "restarting after crash");
780                    if let Some(s) = me.slots().get_mut(&id) {
781                        s.restart_at = None;
782                    }
783                    if let Err(e) = me.load(&id).await {
784                        tracing::warn!(model = %id, "restart failed: {e}");
785                    }
786                }
787            });
788        }
789    }
790
791    fn failed(&self, id: &str, generation: u64, why: String) -> RemoteError {
792        if let Some(slot) = self.slots().get_mut(id).filter(|s| s.generation == generation)
793            && !slot.crash_loop
794        {
795            slot.state = ModelState::Failed(why.clone());
796        }
797        unavailable(format!("{id}: {why}"))
798    }
799
800    /// Drains, marks unloaded and stops the engine. Caller holds `ops`.
801    async fn stop(&self, id: &str, idle: bool) {
802        let in_flight = {
803            let mut slots = self.slots();
804            let Some(slot) = slots.get_mut(id) else { return };
805            if slot.running.is_none() {
806                if !matches!(slot.state, ModelState::Failed(_)) {
807                    slot.state = ModelState::Unloaded;
808                }
809                return;
810            }
811            slot.state = ModelState::Draining;
812            slot.in_flight.clone()
813        };
814        let deadline = Instant::now() + self.inner.opts.drain_timeout;
815        while in_flight.load(Ordering::SeqCst) > 0 && Instant::now() < deadline {
816            tokio::time::sleep(Duration::from_millis(50)).await;
817        }
818        let (stop, mut exited) = {
819            let mut slots = self.slots();
820            let Some(slot) = slots.get_mut(id) else { return };
821            slot.state = ModelState::Unloaded;
822            match slot.running.as_mut() {
823                Some(r) if r.stop.is_some() => (r.stop.take(), r.exited.clone()),
824                Some(_) => {
825                    // Wrapped: detach only.
826                    slot.running = None;
827                    drop(slots);
828                    self.emit(SupervisorEvent::Unloaded { model: id.into(), idle });
829                    return;
830                }
831                None => return,
832            }
833        };
834        if let Some(stop) = stop {
835            let _ = stop.send(());
836        }
837        let wait = self.inner.opts.stop_grace + Duration::from_secs(5);
838        let _ = tokio::time::timeout(wait, exited.wait_for(Option::is_some)).await;
839        tracing::info!(model = %id, "engine stopped");
840        self.emit(SupervisorEvent::Unloaded { model: id.into(), idle });
841    }
842
843    /// The engine, request target, URL, key and in-flight guard for pool id `id` (a model, or an
844    /// adapter on a ready base that was started with it).
845    fn routed(&self, id: &str) -> Result<(EngineKind, Target, String, Option<String>, InFlight), RemoteError> {
846        let route = self.route(id)?;
847        let (engine, target) = {
848            let slots = self.slots();
849            let slot = slots.get(&route.base).ok_or_else(|| unknown_model(id))?;
850            let engine = slot.launch.engine;
851            let target = match &route.adapter {
852                None => Target::Base { alias: route.base.clone(), has_adapters: slot.running.as_ref().is_some_and(|r| !r.adapters.is_empty()) },
853                Some(a) => {
854                    let index = slot
855                        .running
856                        .as_ref()
857                        .and_then(|r| r.adapters.iter().position(|x| *x == a.id))
858                        .ok_or_else(|| unavailable(format!("{id} is not loaded; load it (this restarts {})", route.base)))?;
859                    Target::Adapter { base: route.base.clone(), index, id: a.id.clone(), scale: a.effective_scale() }
860                }
861            };
862            (engine, target)
863        };
864        let (base, key, guard) = self.target(&route.base)?;
865        Ok((engine, target, base, key, guard))
866    }
867
868    /// Where requests for `id` go, with the in-flight guard taken.
869    fn target(&self, id: &str) -> Result<(String, Option<String>, InFlight), RemoteError> {
870        let slots = self.slots();
871        let slot = slots.get(id).ok_or_else(|| unknown_model(id))?;
872        match (&slot.state, &slot.running) {
873            (ModelState::Ready, Some(r)) => {
874                Ok((r.base.clone(), r.api_key.clone(), InFlight::new(slot.in_flight.clone(), slot.last_used.clone(), self.inner.epoch)))
875            }
876            (state, _) => Err(unavailable(format!("{id} is not ready ({state:?})"))),
877        }
878    }
879
880    async fn post(&self, url: String, key: Option<&str>, body: &Value) -> Result<reqwest::Response, RemoteError> {
881        let mut req = self.inner.http.post(url).json(body);
882        if let Some(k) = key {
883            req = req.bearer_auth(k);
884        }
885        let resp = req.send().await.map_err(|e| engine_error(format!("request failed: {e}")))?;
886        let status = resp.status();
887        if status.as_u16() == 503 || status.as_u16() == 429 {
888            return Err(RemoteError::Busy);
889        }
890        if !status.is_success() {
891            let body = resp.text().await.unwrap_or_default();
892            return Err(match status.as_u16() {
893                400 | 422 => bad_request(trim(&body)),
894                _ => engine_error(format!("{status}: {}", trim(&body))),
895            });
896        }
897        Ok(resp)
898    }
899
900    /// Streams a chat answer from `id`, which must be ready. Dropping the stream aborts the engine
901    /// request.
902    pub async fn chat(&self, id: &str, request: &Request) -> Result<ChunkStream, RemoteError> {
903        let (engine, target, base, key, guard) = self.routed(id)?;
904        let body = openai::chat_body_for(request, &target, engine)?;
905        let resp = self.post(format!("{base}/v1/chat/completions"), key.as_deref(), &body).await?;
906        Ok(stream_chunks(resp, guard))
907    }
908
909    /// Streams a raw text completion of `prompt` from `id`, which must be ready. Response
910    /// formats and tools don't apply.
911    pub async fn complete(&self, id: &str, prompt: &str, sampling: &Sampling, seed: Option<u64>) -> Result<ChunkStream, RemoteError> {
912        let (engine, target, base, key, guard) = self.routed(id)?;
913        let body = openai::completion_body_for(prompt, sampling, seed, &target, engine);
914        let resp = self.post(format!("{base}/v1/completions"), key.as_deref(), &body).await?;
915        Ok(stream_chunks(resp, guard))
916    }
917
918    fn engine_of(&self, id: &str) -> Result<EngineKind, RemoteError> {
919        if let Route { base, adapter: Some(_) } = self.route(id)? {
920            return Err(bad_request(format!("{id} is an adapter on {base}; adapters serve chat and completions only")));
921        }
922        self.slots().get(id).map(|s| s.launch.engine).ok_or_else(|| unknown_model(id))
923    }
924
925    /// Embeds `input` with `id` (an embedding model). Returns the vectors in input order and the
926    /// prompt tokens used.
927    pub async fn embed(&self, id: &str, input: &[String]) -> Result<(Vec<Vec<f32>>, u64), RemoteError> {
928        if self.engine_of(id)? == EngineKind::Mlx {
929            return Err(bad_request(format!("{id} runs on MLX-LM, which serves no embeddings")));
930        }
931        let (base, key, _guard) = self.target(id)?;
932        let resp =
933            self.post(format!("{base}/v1/embeddings"), key.as_deref(), &json!({"model": id, "input": input, "encoding_format": "float"})).await?;
934        let v: Value = resp.json().await.map_err(|e| engine_error(format!("bad embeddings response: {e}")))?;
935        let mut rows: Vec<(u64, Vec<f32>)> = v["data"]
936            .as_array()
937            .ok_or_else(|| engine_error("embeddings response has no data"))?
938            .iter()
939            .enumerate()
940            .map(|(i, d)| {
941                (
942                    d["index"].as_u64().unwrap_or(i as u64),
943                    d["embedding"].as_array().map(|e| e.iter().filter_map(Value::as_f64).map(|x| x as f32).collect()).unwrap_or_default(),
944                )
945            })
946            .collect();
947        rows.sort_by_key(|(i, _)| *i);
948        if rows.len() != input.len() {
949            return Err(engine_error(format!("asked for {} embeddings, got {}", input.len(), rows.len())));
950        }
951        Ok((rows.into_iter().map(|(_, e)| e).collect(), v["usage"]["prompt_tokens"].as_u64().unwrap_or(0)))
952    }
953
954    fn log_file(&self, id: &str) -> Option<(std::fs::File, std::fs::File)> {
955        let dir = self.inner.opts.log_dir.as_ref()?;
956        std::fs::create_dir_all(dir).ok()?;
957        let f = std::fs::OpenOptions::new().create(true).append(true).open(dir.join(format!("{id}.log"))).ok()?;
958        Some((f.try_clone().ok()?, f))
959    }
960
961    fn log_tail(&self, id: &str) -> String {
962        let Some(dir) = &self.inner.opts.log_dir else { return String::new() };
963        let Ok(text) = std::fs::read_to_string(dir.join(format!("{id}.log"))) else { return String::new() };
964        let lines: Vec<&str> = text.lines().rev().take(8).collect();
965        let tail: Vec<&str> = lines.into_iter().rev().collect();
966        format!("; log {}:\n{}", dir.join(format!("{id}.log")).display(), tail.join("\n"))
967    }
968}
969
970/// `base * 2^(n-1)`, at most `max`.
971fn backoff(base: Duration, max: Duration, n: usize) -> Duration {
972    let factor = 1u32.checked_shl(n.saturating_sub(1).min(16) as u32).unwrap_or(u32::MAX);
973    base.saturating_mul(factor).min(max)
974}
975
976fn stream_chunks(resp: reqwest::Response, guard: InFlight) -> ChunkStream {
977    let (tx, rx) = tokio::sync::mpsc::channel(64);
978    tokio::spawn(async move {
979        let _guard = guard;
980        let mut bytes = resp.bytes_stream();
981        let mut parser = SseParser::default();
982        let mut decoder = ChunkDecoder::default();
983        loop {
984            let payloads = match bytes.next().await {
985                Some(Ok(chunk)) => parser.feed(&chunk),
986                Some(Err(e)) => {
987                    let _ = tx.send(Err(engine_error(format!("stream broke: {e}")))).await;
988                    return;
989                }
990                None => {
991                    let rest: Vec<String> = parser.finish().into_iter().collect();
992                    for p in rest {
993                        if !send_all(&tx, decoder.decode(&p)).await {
994                            return;
995                        }
996                    }
997                    let last = if decoder.complete() { decoder.finish().map(Ok) } else { Some(Err(engine_error("engine stream ended early"))) };
998                    if let Some(last) = last {
999                        let _ = tx.send(last).await;
1000                    }
1001                    return;
1002                }
1003            };
1004            for p in payloads {
1005                let done = p.trim() == "[DONE]";
1006                if !send_all(&tx, decoder.decode(&p)).await || done {
1007                    return;
1008                }
1009            }
1010        }
1011    });
1012    Box::pin(ReceiverStream::new(rx))
1013}
1014
1015/// Sends decoded frames; false when the stream should end (receiver gone, or an error was sent).
1016async fn send_all(tx: &tokio::sync::mpsc::Sender<Result<Chunk, RemoteError>>, evs: Result<Vec<Chunk>, RemoteError>) -> bool {
1017    match evs {
1018        Ok(evs) => {
1019            for ev in evs {
1020                if tx.send(Ok(ev)).await.is_err() {
1021                    return false;
1022                }
1023            }
1024            true
1025        }
1026        Err(e) => {
1027            let _ = tx.send(Err(e)).await;
1028            false
1029        }
1030    }
1031}
1032
1033/// Counts a request in flight; on drop, records when the model was last used.
1034struct InFlight {
1035    n: Arc<AtomicUsize>,
1036    last_used: Arc<AtomicU64>,
1037    epoch: Instant,
1038}
1039
1040impl InFlight {
1041    fn new(n: Arc<AtomicUsize>, last_used: Arc<AtomicU64>, epoch: Instant) -> Self {
1042        n.fetch_add(1, Ordering::SeqCst);
1043        Self { n, last_used, epoch }
1044    }
1045}
1046
1047impl Drop for InFlight {
1048    fn drop(&mut self) {
1049        self.last_used.store(self.epoch.elapsed().as_millis() as u64, Ordering::SeqCst);
1050        self.n.fetch_sub(1, Ordering::SeqCst);
1051    }
1052}
1053
1054async fn terminate(child: &mut tokio::process::Child, pid: Option<u32>, grace: Duration) -> std::io::Result<std::process::ExitStatus> {
1055    #[cfg(unix)]
1056    if let Some(pid) = pid.and_then(|p| i32::try_from(p).ok()) {
1057        // SAFETY: plain syscall; the negative pid targets the engine's own process group.
1058        unsafe {
1059            libc::kill(-pid, libc::SIGTERM);
1060        }
1061        if let Ok(status) = tokio::time::timeout(grace, child.wait()).await {
1062            return status;
1063        }
1064        // SAFETY: as above.
1065        unsafe {
1066            libc::kill(-pid, libc::SIGKILL);
1067        }
1068        return child.wait().await;
1069    }
1070    let _ = (pid, grace);
1071    child.start_kill()?;
1072    child.wait().await
1073}
1074
1075fn free_port() -> std::io::Result<u16> {
1076    Ok(std::net::TcpListener::bind(("127.0.0.1", 0))?.local_addr()?.port())
1077}
1078
1079/// Random hex from the OS RNG.
1080pub(crate) fn random_hex(bytes: usize) -> String {
1081    let mut buf = vec![0u8; bytes];
1082    getrandom::fill(&mut buf).expect("the OS RNG is available");
1083    buf.iter().map(|b| format!("{b:02x}")).collect()
1084}
1085
1086fn trim(s: &str) -> String {
1087    let s = s.trim();
1088    if s.len() > 500 { format!("{}...", &s[..s.floor_char_boundary(500)]) } else { s.to_string() }
1089}
1090
1091#[cfg(test)]
1092mod tests {
1093    use super::*;
1094
1095    #[test]
1096    fn backoff_doubles_and_caps() {
1097        let b = |n| backoff(Duration::from_secs(1), Duration::from_secs(60), n);
1098        assert_eq!(b(1), Duration::from_secs(1));
1099        assert_eq!(b(2), Duration::from_secs(2));
1100        assert_eq!(b(4), Duration::from_secs(8));
1101        assert_eq!(b(10), Duration::from_secs(60));
1102        assert_eq!(b(100), Duration::from_secs(60));
1103    }
1104}