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