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