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