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