1 //! inf3r-core — discovery, routing, admission, and residency.2 //!3 //! The core is the only process that starts a plugin, holds a device, or knows4 //! which model is resident. It has no HTTP, no JSON of its own, and no auth:5 //! those belong to the web, which is a client of the core over the same framed6 //! protocol that a plugin speaks (spec section 18, rule 5).7 //!8 //! A job reaches a plugin through one `open` frame and leaves through the9 //! events of its stream. The core sits between the two and adds three things:10 //! the served name, a slot, and a deadline.11 12 mod cache;13 mod jobs;14 mod loader;15 mod refusal;16 mod residency;17 18 use std::collections::{BTreeMap, BTreeSet};19 use std::fs::File;20 use std::os::fd::{AsFd, BorrowedFd};21 use std::os::unix::fs::MetadataExt;22 use std::path::{Path, PathBuf};23 use std::sync::{Arc, Mutex, MutexGuard};24 use std::time::{Duration, Instant};25 26 use inf3r_catalog::Catalog;27 use inf3r_host::available_memory;28 use inf3r_ledger::Reservation;29 use inf3r_proto::body::{self, Capability, Model, Open, PartKind};30 use inf3r_proto::client::Item;31 use inf3r_proto::client::{Job, Peer};32 use inf3r_proto::{Value, body::Part};33 use inf3r_sched::{Lease, Sched, SchedError};34 use inf3r_supervisor::{Backoff, Failure};35 36 pub use cache::CacheRuntime;37 38 type CachePolicy = (Option<String>, bool, bool);39 40 /// The role that a grant dependency must carry for a weight file.41 const WEIGHTS_ROLE: &str = "weights";42 43 /// The longest wait between two starts after a transient failure.44 ///45 /// core.md section 2 rule 1 says that a peer that fails twice in one minute is46 /// not spawned a third time without a wait. The measured backoff grows from47 /// the time the failed start took, and this is its ceiling.48 const MAX_BACKOFF: Duration = Duration::from_secs(60);49 50 /// Who a job is for. It is re-exported so a caller that builds a `Submit`51 /// names the same type that admission uses.52 pub use inf3r_sched::Priority;53 pub use jobs::{JobState, JobStatus, JobTable};54 pub use loader::{Loader, NoLoader};55 pub use refusal::{Refusal, RefusalCode};56 pub use residency::{57 DEFAULT_SETTLE_BUDGET, DEFAULT_SETTLE_STEP, HostMemory, HostWaiter, Memory, RSS_TOLERANCE,58 Residency, ResidencyError, Settle, Waiter,59 };60 61 /// What a caller asks for.62 #[derive(Debug)]63 pub struct Submit {64 /// The served name from the catalogue.65 pub model: String,66 /// The capability from the catalogue.67 pub capability: String,68 /// The parts, in the order that the caller declared them. A part that is69 /// held by descriptor names its index in `files`.70 pub parts: Vec<Part>,71 /// The descriptors that a part may name with `Hold::Fd`.72 pub files: Vec<File>,73 /// Capability parameters.74 pub params: Value,75 /// The identifier that the client sent, echoed on every event.76 pub request_id: String,77 /// Bytes of `event` bodies that this job may receive before it must grant78 /// more. The web grants more as the client consumes.79 pub credit: u64,80 /// The whole budget of the job.81 pub budget: Duration,82 /// Who the job is for. A background job may not use a degraded capability.83 pub priority: Priority,84 }85 86 impl Submit {87 /// A job with a request identifier and a budget.88 pub fn new(89 model: impl Into<String>,90 capability: impl Into<String>,91 request_id: impl Into<String>,92 ) -> Submit {93 Submit {94 model: model.into(),95 capability: capability.into(),96 parts: Vec::new(),97 files: Vec::new(),98 params: Value::Map(Vec::new()),99 request_id: request_id.into(),100 credit: 0,101 budget: Duration::from_secs(60),102 priority: Priority::Interactive,103 }104 }105 }106 107 /// What a bounded wait on a job found.108 ///109 /// A job's own deadline is absolute and fails the job. A shorter wait is a110 /// poll: the job is still running when the wait ends, so the caller sends a111 /// keep-alive and asks again.112 #[derive(Debug)]113 pub enum Wait {114 /// The wait ended before an item arrived.115 Idle,116 /// The job produced an item, or the stream ended.117 Item(Option<Item>),118 }119 120 /// A plugin that the core has started, greeted, and loaded.121 ///122 /// The `Peer` is the caller half of the wire. Every thread that has a slot may123 /// open a job on it; the reader thread inside `Peer` is the only reader.124 #[derive(Clone)]125 pub struct Served {126 /// The plugin id, which is its directory.127 pub plugin: String,128 /// The catalogue that the plugin printed, which the catalog is built from.129 pub catalogue: body::Catalogue,130 /// The models that it serves.131 pub models: Vec<Model>,132 /// The capability table, flattened for lookup.133 capabilities: BTreeMap<(String, String), Capability>,134 peer: Arc<Peer>,135 ready: Option<body::Ready>,136 max_inflight: u16,137 /// The weight files that this peer was granted. The cache fingerprint138 /// covers them; an empty list is a mock or a cold catalogue.139 weights: Vec<PathBuf>,140 }141 142 impl Served {143 /// Connects to a plugin, greets it, loads it, and reads its catalogue.144 ///145 /// The load is the core's decision and it happens once, before any job:146 /// a model that cannot load must not take a job and then fail it. The147 /// weight files open here because the plugin reads them through the148 /// descriptors that the grant carries.149 pub fn connect(150 plugin: impl Into<String>,151 socket: std::os::unix::net::UnixStream,152 id: &str,153 weights: &[PathBuf],154 wait: Duration,155 ) -> Result<Served, CoreError> {156 Served::connect_paths(plugin, socket, id, weights, wait, true)157 }158 159 /// Connects with the deploy's weight-delivery contract.160 ///161 /// A process peer receives the host path in the grant. A container peer162 /// receives an empty path: the descriptor is the only name, and the engine163 /// reads `/proc/self/fd/<n>` (D28). The bytes are the same in both cases.164 pub fn connect_paths(165 plugin: impl Into<String>,166 socket: std::os::unix::net::UnixStream,167 id: &str,168 weights: &[PathBuf],169 wait: Duration,170 paths: bool,171 ) -> Result<Served, CoreError> {172 // The files open before the handshake, so a path that the operator173 // wrote wrong does not start a plugin that can never load.174 let mut files = Vec::with_capacity(weights.len());175 let mut deps = Vec::with_capacity(weights.len());176 for (index, path) in weights.iter().enumerate() {177 let file = File::open(path).map_err(|why| CoreError::Failed {178 failure: Failure::Dependency,179 message: format!("{}: {why}", path.display()),180 })?;181 let len = file182 .metadata()183 .map_err(|why| CoreError::Failed {184 failure: Failure::Dependency,185 message: format!("{}: {why}", path.display()),186 })?187 .len();188 let fd = u32::try_from(index)189 .map_err(|_| CoreError::Io("too many weight descriptors".into()))?;190 deps.push(body::Dependency {191 role: WEIGHTS_ROLE.to_string(),192 fd,193 len,194 path: if paths {195 path.to_string_lossy().into_owned()196 } else {197 String::new()198 },199 });200 files.push(file);201 }202 let fds: Vec<BorrowedFd<'_>> = files.iter().map(AsFd::as_fd).collect();203 204 let peer = Peer::connect(socket, id, wait).map_err(|why| {205 if why.kind() == std::io::ErrorKind::TimedOut {206 CoreError::Failed {207 failure: Failure::Timeout,208 message: why.to_string(),209 }210 } else {211 CoreError::Io(why.to_string())212 }213 })?;214 if !peer.compatible() {215 let version = peer.welcome().map(|welcome| welcome.v).unwrap_or_default();216 return Err(CoreError::Failed {217 failure: Failure::Version,218 message: format!("the plugin speaks version {version}"),219 });220 }221 let catalogue = peer.catalogue().ok_or_else(|| CoreError::Failed {222 failure: Failure::Frame,223 message: "the plugin sent no catalogue".into(),224 })?;225 if peer.version() != Some(2) && catalogue.cache.is_some() {226 return Err(CoreError::Failed {227 failure: Failure::Version,228 message: "a Wire 1 catalogue declared a cache".into(),229 });230 }231 let ready = peer232 .load_fds(&body::Grant { deps }, &fds, wait)233 .map_err(|why| {234 let failure = peer235 .refusal()236 .map(|refusal| failure_of(refusal.code))237 .unwrap_or(Failure::Timeout);238 CoreError::Failed {239 failure,240 message: why.to_string(),241 }242 })?;243 let mut served = Served::new(plugin, peer, catalogue).loaded(ready);244 served.weights = weights.to_vec();245 Ok(served)246 }247 248 fn loaded(mut self, ready: body::Ready) -> Served {249 self.ready = Some(ready);250 self251 }252 253 /// Registers a peer and the catalogue that it printed.254 pub fn new(plugin: impl Into<String>, peer: Peer, catalogue: body::Catalogue) -> Served {255 let max_inflight = peer256 .welcome()257 .map(|welcome| welcome.max_inflight)258 .unwrap_or(1);259 let mut capabilities = BTreeMap::new();260 for model in &catalogue.models {261 for (name, capability) in &model.capabilities {262 capabilities.insert((model.serve.clone(), name.clone()), capability.clone());263 }264 }265 Served {266 plugin: plugin.into(),267 models: catalogue.models.clone(),268 catalogue,269 capabilities,270 peer: Arc::new(peer),271 ready: None,272 max_inflight,273 weights: Vec::new(),274 }275 }276 277 /// Installs the core's cache handler on this peer. The handler is optional;278 /// a plugin without a cache declaration never receives cache frames.279 pub fn install_cache(&self, session: u64, host: Arc<dyn inf3r_proto::client::CacheHost>) {280 self.peer.install_cache(session, host);281 }282 283 /// The Wire version negotiated with this peer.284 pub fn wire_version(&self) -> Option<u32> {285 self.peer.version()286 }287 288 /// The capability of one served name.289 pub fn capability(&self, model: &str, capability: &str) -> Option<&Capability> {290 self.capabilities291 .get(&(model.to_string(), capability.to_string()))292 }293 294 /// What the plugin measured when it loaded.295 pub fn load_ms(&self) -> Option<u32> {296 self.ready.map(|ready| ready.load_ms)297 }298 299 /// The served names of this peer.300 pub fn names(&self) -> impl Iterator<Item = &str> {301 self.models.iter().map(|model| model.serve.as_str())302 }303 304 /// The most jobs that this peer runs at once.305 ///306 /// The count of jobs that run now lives in the schedule, which is the only307 /// counter: a second one here would have to be kept in step with it, and two308 /// counters of one quantity always drift.309 pub fn max_inflight(&self) -> u16 {310 self.max_inflight311 }312 313 /// Replaces the slot count that the peer welcomed with the bind's own.314 ///315 /// The welcome is the plugin's claim; a deploy file may choose a smaller316 /// number for this host. The schedule is the only counter, so a later317 /// register sees the chosen number.318 pub fn set_max_inflight(&mut self, slots: u16) {319 self.max_inflight = slots;320 }321 322 /// Keeps only the served names that the bind chose.323 ///324 /// A catalogue may offer more names than one bind serves. The bind is the325 /// local choice, so the names outside it must not enter the catalog or the326 /// schedule.327 pub fn retain_models(&mut self, keep: &[String]) {328 let keep = |name: &str| keep.iter().any(|chosen| chosen == name);329 self.models.retain(|model| keep(&model.serve));330 self.catalogue.models.retain(|model| keep(&model.serve));331 self.capabilities.retain(|(serve, _), _| keep(serve));332 }333 334 /// The failure that the reader saw, if the peer has ended.335 ///336 /// A job learns of a dead peer here rather than from an io error string, so337 /// the same classification reaches the backoff whether the monitor or the338 /// reader noticed first.339 pub fn failure(&self) -> Option<Failure> {340 self.peer.refusal().map(|refusal| failure_of(refusal.code))341 }342 }343 344 /// The usage keys of the terminal frame, as the SDK writes them.345 const USAGE_TOKENS_OUT: &str = "tokens_out";346 const USAGE_FIRST_TOKEN_MS: &str = "first_token_ms";347 const USAGE_TOKENS_PER_S: &str = "tokens_per_s";348 349 /// The last usage that one plugin reported.350 #[derive(Clone, Copy, Default, Debug)]351 struct Usage {352 tokens_out: Option<u64>,353 first_token_ms: Option<u64>,354 tokens_per_s: Option<u64>,355 }356 357 impl Usage {358 fn from_counts(counts: &BTreeMap<String, u64>) -> Usage {359 Usage {360 tokens_out: counts.get(USAGE_TOKENS_OUT).copied(),361 first_token_ms: counts.get(USAGE_FIRST_TOKEN_MS).copied(),362 tokens_per_s: counts.get(USAGE_TOKENS_PER_S).copied(),363 }364 }365 }366 367 /// What the core remembers about a plugin between starts.368 ///369 /// A good start clears the failure count. A crash keeps the uptime so that the370 /// next wait is as long as the work that was lost, and a permanent failure371 /// keeps the peer unloadable until an operator reload.372 #[derive(Default)]373 struct Health {374 backoff: Backoff,375 started: Option<Instant>,376 not_before: Option<Instant>,377 }378 379 /// The shared state that turns a dead peer into a failed plugin.380 ///381 /// A job reader and the web monitor reach this through an `Arc`, so neither has382 /// to own the whole core. The state owns only what a failure changes: the peer383 /// map, the job table, the ledger, the failure memory, and the loader.384 struct FailureState {385 peers: Arc<Mutex<BTreeMap<String, Arc<Served>>>>,386 jobs: Arc<JobTable>,387 residency: Arc<Residency>,388 health: Arc<Mutex<BTreeMap<String, Health>>>,389 stopping: Arc<Mutex<BTreeSet<String>>>,390 /// One mutex for every ledger mutation that waits on a device. A release391 /// that settles while another thread reserves would let the second thread392 /// see a free byte before the driver frees it.393 gate: Mutex<()>,394 loader: Arc<Mutex<Arc<dyn Loader>>>,395 }396 397 impl FailureState {398 fn gate(&self) -> MutexGuard<'_, ()> {399 lock(&self.gate)400 }401 402 fn loader(&self) -> Arc<dyn Loader> {403 Arc::clone(&lock(&self.loader))404 }405 406 fn note_start(&self, plugin: &str) {407 let mut health = lock(&self.health);408 let entry = health.entry(plugin.to_string()).or_default();409 entry.started = Some(Instant::now());410 }411 412 fn note_success(&self, plugin: &str) {413 let mut health = lock(&self.health);414 let entry = health.entry(plugin.to_string()).or_default();415 entry.backoff.success();416 entry.not_before = None;417 entry.started = Some(Instant::now());418 }419 420 fn note_failure(&self, plugin: &str, failure: Failure) {421 let mut health = lock(&self.health);422 let entry = health.entry(plugin.to_string()).or_default();423 let took = entry424 .started425 .take()426 .map(|start| start.elapsed())427 .unwrap_or(Duration::ZERO)428 .min(MAX_BACKOFF);429 if failure.is_permanent() {430 entry.backoff.permanent();431 entry.not_before = None;432 } else {433 let wait = entry.backoff.wait(took, MAX_BACKOFF);434 entry.not_before = Some(Instant::now() + wait);435 }436 }437 438 fn start_allowed(&self, plugin: &str, request_id: &str) -> Result<(), CoreError> {439 if lock(&self.stopping).contains(plugin) {440 return Err(refusal(441 RefusalCode::LoadFailed,442 request_id,443 format!("{plugin} is still stopping"),444 ));445 }446 let health = lock(&self.health);447 let Some(entry) = health.get(plugin) else {448 return Ok(());449 };450 if entry.backoff.unloadable() {451 return Err(refusal(452 RefusalCode::LoadFailed,453 request_id,454 format!("{plugin} is unloadable after a permanent failure; reload it"),455 ));456 }457 if let Some(at) = entry.not_before458 && at > Instant::now()459 {460 return Err(refusal(461 RefusalCode::LoadFailed,462 request_id,463 format!(464 "{plugin} failed and may start again in {} ms",465 at.saturating_duration_since(Instant::now()).as_millis()466 ),467 ));468 }469 Ok(())470 }471 472 fn release_after_stop(&self, plugin: &str, reservation: Reservation) {473 // The ledger still holds these bytes. The target is what the device474 // will report free after this reservation leaves, not the size of the475 // reservation itself: a card that already had that much free would476 // otherwise pass before the driver freed the dead child.477 let targets: Vec<(String, Option<u64>)> = reservation478 .held()479 .iter()480 .map(|(device, want)| {481 (482 device.clone(),483 self.residency.stop_target(plugin, device, *want),484 )485 })486 .collect();487 for (device, target) in targets {488 // A CPU bundle has no driver to settle. Its memory is the process489 // itself, and the stop already waited for the process.490 if !device.starts_with("cuda:") {491 continue;492 }493 let Some(target) = target else {494 continue;495 };496 match self.residency.settle_default(&device, target) {497 Ok(waited) if !waited.is_zero() => {498 eprintln!("{device} settled after {waited:?}");499 }500 Ok(_) => {}501 Err(why) => {502 eprintln!("{device} did not settle: {why}; the reservation is released");503 }504 }505 }506 self.residency.release(reservation);507 }508 509 fn fail(&self, plugin: &str, failure: Failure) {510 // No peer means another reader or the monitor already failed it. The511 // first failure owns the ledger release and the backoff.512 let has_peer = lock(&self.peers)513 .values()514 .any(|served| served.plugin == plugin);515 if !has_peer {516 return;517 }518 {519 let mut stopping = lock(&self.stopping);520 if !stopping.insert(plugin.to_string()) {521 return;522 }523 }524 525 // Recheck under the stop guard: a first failure that finished between526 // the check above and this insert has already removed the peer and527 // recorded the backoff, and a second record would double it.528 if !lock(&self.peers)529 .values()530 .any(|served| served.plugin == plugin)531 {532 lock(&self.stopping).remove(plugin);533 return;534 }535 536 let gone: Vec<Arc<Served>> = {537 let mut peers = lock(&self.peers);538 let names: Vec<String> = peers539 .iter()540 .filter(|(_, served)| served.plugin == plugin)541 .map(|(name, _)| name.clone())542 .collect();543 names544 .into_iter()545 .filter_map(|name| peers.remove(&name))546 .collect()547 };548 for served in &gone {549 let _ = served.peer.shutdown();550 }551 552 if let Err(why) = self.loader().stop(plugin) {553 eprintln!("{plugin} did not stop after a failure: {why}");554 }555 let failed = self556 .jobs557 .fail_plugin(plugin, "the plugin stopped during the job");558 if failed > 0 {559 eprintln!("{plugin} failed {failed} job(s): {failure:?}");560 }561 // Remember the failure before the settle wait. A request that arrives562 // during that wait must see the backoff, and a start that succeeds must563 // be the last word on the health rather than an older stop overwriting564 // it afterwards.565 self.note_failure(plugin, failure);566 if let Some(reservation) = self.residency.release_plugin(plugin) {567 let _gate = self.gate();568 self.release_after_stop(plugin, reservation);569 }570 self.residency.forget_measured(plugin);571 lock(&self.stopping).remove(plugin);572 }573 }574 575 /// One row of `/stats`: what one engine has done and what it is doing now.576 ///577 /// The row joins the catalogue, the schedule, the residency ledger, and the last578 /// terminal frame, because an operator who sees one slow engine needs all four579 /// numbers side by side.580 #[derive(Clone, PartialEq, Eq, Debug)]581 pub struct EngineStat {582 /// The plugin id.583 pub plugin: String,584 /// The served names that this plugin owns.585 pub served: Vec<String>,586 /// The most jobs that the schedule allows at once.587 pub slots: u16,588 /// The jobs that hold a slot now.589 pub in_flight: usize,590 /// The jobs that wait for a slot now.591 pub queued: usize,592 /// The milliseconds that the plugin reported when it loaded.593 pub load_ms: Option<u32>,594 /// The weights bytes that the catalogue declares.595 pub declared_bytes: u64,596 /// The resident bytes that the child reported after its load passed.597 pub measured_bytes: Option<u64>,598 /// The tokens that the last finished job produced.599 pub tokens_out: Option<u64>,600 /// The milliseconds from the last job's start to its first token.601 pub first_token_ms: Option<u64>,602 /// The last job's rate in hundredths of a token per second.603 pub tokens_per_s: Option<u64>,604 }605 606 /// A job that holds one slot of its peer.607 ///608 /// The slot is the semaphore that `max_inflight` describes. Dropping this type609 /// ends the job's hold, so a caller cannot forget to give the slot back.610 pub struct CoreJob {611 job: Job,612 // Held for the life of the job: the drop is the release.613 _slot: Lease,614 model: String,615 plugin: String,616 id: String,617 jobs: Arc<JobTable>,618 residency: Arc<Residency>,619 usage: Arc<Mutex<BTreeMap<String, Usage>>>,620 failures: Arc<FailureState>,621 served: Arc<Served>,622 /// The instant at which the whole job expires. It starts at admission,623 /// before the queue wait, so a long wait leaves less time to run.624 deadline: Instant,625 ended: bool,626 }627 628 impl std::fmt::Debug for CoreJob {629 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {630 f.debug_struct("CoreJob")631 .field("stream", &self.job.id())632 .field("plugin", &self.plugin)633 .finish()634 }635 }636 637 impl CoreJob {638 /// The served name that the job asked for.639 pub fn model(&self) -> &str {640 &self.model641 }642 643 /// The plugin that serves it.644 pub fn plugin(&self) -> &str {645 &self.plugin646 }647 648 /// The stream identifier on the wire.649 pub fn id(&self) -> u16 {650 self.job.id()651 }652 653 /// The identifier that the core gave this job.654 pub fn id_str(&self) -> &str {655 &self.id656 }657 658 /// Blocks until the job produces the next item.659 ///660 /// The table learns the terminal state here, so a caller that only reads661 /// events still updates `GET /jobs/{id}`.662 #[allow(clippy::should_implement_trait)]663 pub fn next(&mut self) -> std::io::Result<Option<Item>> {664 let item = match self.job.next_deadline(self.deadline) {665 Ok(item) => item,666 Err(why) => return Err(self.fail(why)),667 };668 self.observe(&item);669 Ok(item)670 }671 672 /// Blocks for at most `wait`, then returns what happened.673 ///674 /// A wait that ends with no item is not the job's deadline: the job stays675 /// running, and the caller may send a keep-alive and wait again. A wait676 /// that reaches the job's own deadline fails the job through the same path677 /// as [`CoreJob::next`].678 pub fn wait(&mut self, wait: Duration) -> std::io::Result<Wait> {679 let deadline = Instant::now()680 .checked_add(wait)681 .unwrap_or(self.deadline)682 .min(self.deadline);683 match self.job.next_deadline(deadline) {684 Ok(item) => {685 self.observe(&item);686 Ok(Wait::Item(item))687 }688 Err(why)689 if why.kind() == std::io::ErrorKind::TimedOut && Instant::now() < self.deadline =>690 {691 Ok(Wait::Idle)692 }693 Err(why) => Err(self.fail(why)),694 }695 }696 697 fn observe(&mut self, item: &Option<Item>) {698 match item {699 Some(Item::Done(done, _)) => {700 self.ended = true;701 self.remember_usage(done);702 self.jobs.finish(703 &self.id,704 JobState::Done {705 outcome: outcome_name(done.outcome).to_string(),706 },707 );708 }709 Some(Item::Reject(reject)) => {710 self.ended = true;711 self.jobs.finish(712 &self.id,713 JobState::Failed {714 code: RefusalCode::from_wire(reject.code),715 message: reject716 .detail717 .clone()718 .unwrap_or_else(|| "the plugin refused".into()),719 },720 );721 }722 None => {723 self.ended = true;724 self.jobs.lost(&self.id);725 }726 _ => {}727 }728 if self.ended {729 self.residency.touch(&self.plugin);730 }731 }732 733 /// Records a failure that ended this job and hands the error back.734 fn fail(&mut self, why: std::io::Error) -> std::io::Error {735 self.ended = true;736 if why.kind() == std::io::ErrorKind::TimedOut {737 // The row records the client's timeout before failing the peer,738 // because the peer failure marks every still-running job on it739 // as a crash. This job is not a crash: its own budget ended.740 self.jobs.finish(741 &self.id,742 JobState::Failed {743 code: RefusalCode::Timeout,744 message: why.to_string(),745 },746 );747 // Ask the plugin to stop, then fail the peer. A plugin that748 // ignores one job's budget is not allowed to hold the slot or749 // the socket for the next request.750 let _ = self.job.cancel();751 self.residency.touch(&self.plugin);752 self.failures.fail(&self.plugin, Failure::Timeout);753 } else {754 self.jobs.finish(755 &self.id,756 JobState::Failed {757 code: RefusalCode::PluginCrashed,758 message: why.to_string(),759 },760 );761 self.residency.touch(&self.plugin);762 let failure = self.served.failure().unwrap_or(Failure::Crashed);763 self.failures.fail(&self.plugin, failure);764 }765 why766 }767 768 fn remember_usage(&self, done: &body::Done) {769 lock(&self.usage).insert(self.plugin.clone(), Usage::from_counts(&done.usage));770 }771 772 /// Raises the credit watermark of this stream.773 pub fn grant(&self, watermark: u64) -> std::io::Result<()> {774 self.job.grant(watermark)775 }776 777 /// Asks the plugin to stop.778 pub fn cancel(&self) -> std::io::Result<()> {779 self.job.cancel()780 }781 782 /// Total bytes of `event` bodies that this job received.783 pub fn received(&self) -> u64 {784 self.job.received()785 }786 }787 788 impl Drop for CoreJob {789 /// A caller that drops a job without reading it has abandoned the stream.790 ///791 /// The row must not stay `running` forever, or `/jobs` grows without a792 /// bound and the next reader cannot tell a live stream from a leaked one.793 /// The wire cancel is sent by `Job`'s own drop; this only records the end.794 fn drop(&mut self) {795 if !self.ended {796 self.jobs.finish(797 &self.id,798 JobState::Done {799 outcome: outcome_name(body::Outcome::Cancelled).to_string(),800 },801 );802 }803 }804 }805 806 /// The reason a job did not start.807 #[derive(Clone, PartialEq, Eq, Debug)]808 pub enum CoreError {809 /// A client-visible refusal, with the sentence for a human.810 Refused(Refusal),811 /// The socket to a plugin failed.812 Io(String),813 /// The peer failed in a way that the supervisor classifies.814 Failed {815 /// The class that decides whether a restart is allowed.816 failure: Failure,817 /// The sentence for a human.818 message: String,819 },820 }821 822 impl CoreError {823 /// The code of this error, which the web turns into a status.824 pub fn code(&self) -> RefusalCode {825 match self {826 CoreError::Refused(refusal) => refusal.code,827 CoreError::Io(_) => RefusalCode::PluginCrashed,828 CoreError::Failed { failure, .. } => match failure {829 Failure::Dependency | Failure::Timeout => RefusalCode::LoadFailed,830 Failure::Version831 | Failure::Frame832 | Failure::Stream833 | Failure::Size834 | Failure::Crashed835 | Failure::Killed => RefusalCode::Protocol,836 },837 }838 }839 840 /// The supervisor class of a failed load or handshake, when one exists.841 pub fn failure(&self) -> Option<Failure> {842 match self {843 CoreError::Failed { failure, .. } => Some(*failure),844 CoreError::Refused(_) | CoreError::Io(_) => None,845 }846 }847 }848 849 impl std::fmt::Display for CoreError {850 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {851 match self {852 CoreError::Refused(refusal) => write!(f, "{}: {}", refusal.code, refusal.message),853 CoreError::Io(why) => write!(f, "the plugin connection failed: {why}"),854 CoreError::Failed { failure, message } => {855 write!(f, "the plugin failed ({failure:?}): {message}")856 }857 }858 }859 }860 861 impl std::error::Error for CoreError {}862 863 /// How one bundle splits its resident weight set across devices and host RAM.864 ///865 /// A bundle whose target declares `accounting = "split"` gives one byte count866 /// per selected device and one count for host RAM. The core charges the device867 /// count to the device ledger and leaves the RAM count to the host's own868 /// memory check; the sum is still the model's declared weight bytes, so the869 /// wire catalogue does not need a second number.870 #[derive(Clone, PartialEq, Eq, Debug, Default)]871 pub struct MemoryPlan {872 /// Resident bytes on each selected device, in the bind's order.873 pub device_bytes: Vec<u64>,874 /// Resident bytes in host RAM.875 pub ram_bytes: u64,876 }877 878 impl MemoryPlan {879 /// Bytes that this plan charges to the devices.880 pub fn device_total(&self) -> u64 {881 self.device_bytes.iter().copied().sum()882 }883 }884 885 /// The core: the peers that it serves, and the jobs that it admits.886 pub struct Core {887 catalog: Mutex<Catalog>,888 peers: Arc<Mutex<BTreeMap<String, Arc<Served>>>>,889 jobs: Arc<JobTable>,890 sched: Arc<Sched>,891 residency: Arc<Residency>,892 usage: Arc<Mutex<BTreeMap<String, Usage>>>,893 /// The default priority of each bind. A request that names no priority894 /// takes the one that the deploy file chose for its plugin.895 priorities: Mutex<BTreeMap<String, Priority>>,896 /// The slot count that the deploy file chose for a bind. Absent means the897 /// number that the plugin welcomed with.898 max_inflight: Mutex<BTreeMap<String, u16>>,899 /// The devices that a bind named, in its own order. Residency charges only900 /// these devices; a card that another bind owns is not this load's bill.901 devices: Mutex<BTreeMap<String, Vec<String>>>,902 /// The resident split that a bind's target declared. Absent means the903 /// whole reserved weight set belongs to every selected device.904 memory: Mutex<BTreeMap<String, MemoryPlan>>,905 /// The catalogue that a bind described, kept after an eviction. A cold906 /// start needs its weight bytes before it can ask the ledger for room.907 catalogues: Mutex<BTreeMap<String, body::Catalogue>>,908 /// One gate per plugin, so two cold requests start one child, not two.909 starting: Mutex<BTreeMap<String, Arc<Mutex<()>>>>,910 /// The failure path, shared with every job reader.911 failures: Arc<FailureState>,912 /// Plugins that the core is stopping on purpose. A monitor must not call913 /// that stop a crash.914 stopping: Arc<Mutex<BTreeSet<String>>>,915 loader: Arc<Mutex<Arc<dyn Loader>>>,916 /// The most jobs that wait behind one peer. A queue that a client can grow917 /// without bound is a memory leak with a friendly name.918 queue_capacity: u16,919 /// The host cache, when the operator enabled one.920 cache: Mutex<Option<Arc<CacheRuntime>>>,921 /// Per-plugin cache intent: a retention class, whether the cache is used,922 /// and whether this bind may write.923 cache_policy: Mutex<BTreeMap<String, CachePolicy>>,924 }925 926 impl Default for Core {927 fn default() -> Core {928 Core::new()929 }930 }931 932 /// The slots a bind actually gets.933 ///934 /// A deploy value is a host choice and can only lower the capacity that the935 /// plugin welcomed with. Zero is not a capacity; a peer that claims zero is936 /// treated as one so a deploy mistake cannot stop every job.937 fn clamp_inflight(welcome: u16, deploy: Option<u16>) -> u16 {938 deploy.map_or(welcome, |slots| slots.min(welcome)).max(1)939 }940 941 impl Core {942 /// A core with no peer and no supervisor.943 pub fn new() -> Core {944 Core::with_loader(Arc::new(NoLoader))945 }946 947 /// A core whose residency decisions can stop and start a child.948 ///949 /// A loader is an operator choice, not a property of the wire: the library950 /// and a test run without one and refuse every eviction.951 pub fn with_loader(loader: Arc<dyn Loader>) -> Core {952 let peers = Arc::new(Mutex::new(BTreeMap::new()));953 let jobs = Arc::new(JobTable::new());954 let residency = Arc::new(Residency::new());955 let health = Arc::new(Mutex::new(BTreeMap::new()));956 let stopping = Arc::new(Mutex::new(BTreeSet::new()));957 let loader = Arc::new(Mutex::new(loader));958 let failures = Arc::new(FailureState {959 peers: Arc::clone(&peers),960 jobs: Arc::clone(&jobs),961 residency: Arc::clone(&residency),962 health,963 stopping: Arc::clone(&stopping),964 gate: Mutex::new(()),965 loader: Arc::clone(&loader),966 });967 Core {968 catalog: Mutex::new(Catalog::new()),969 peers,970 jobs,971 sched: Arc::new(Sched::new()),972 residency,973 usage: Arc::new(Mutex::new(BTreeMap::new())),974 priorities: Mutex::new(BTreeMap::new()),975 max_inflight: Mutex::new(BTreeMap::new()),976 devices: Mutex::new(BTreeMap::new()),977 memory: Mutex::new(BTreeMap::new()),978 catalogues: Mutex::new(BTreeMap::new()),979 starting: Mutex::new(BTreeMap::new()),980 failures,981 stopping,982 loader,983 queue_capacity: 64,984 cache: Mutex::new(None),985 cache_policy: Mutex::new(BTreeMap::new()),986 }987 }988 989 /// Replaces the loader after the core was built.990 pub fn set_loader(&self, loader: Arc<dyn Loader>) {991 *lock(&self.loader) = loader;992 }993 994 /// Installs the host cache. Without one, Wire 1 and Wire 2 both work and995 /// plugins simply never receive a cache frame.996 pub fn set_cache(&self, cache: Arc<CacheRuntime>) {997 *lock(&self.cache) = Some(cache);998 }999 1000 pub fn cache_runtime(&self) -> Option<Arc<CacheRuntime>> {1001 lock(&self.cache).clone()1002 }1003 1004 /// Evicts cache on the filesystem that contains `path` until `need` bytes1005 /// are free. `blobs` calls this before refusing an upload.1006 pub fn cache_pressure_for_path(&self, path: &Path, need: u64) -> usize {1007 let Some(cache) = self.cache_runtime() else {1008 return 0;1009 };1010 let Ok(meta) = std::fs::metadata(path) else {1011 return 0;1012 };1013 cache.pressure(meta.dev(), need)1014 }1015 1016 /// Releases host memory held by RAM-backed cache before a model load.1017 pub fn cache_relieve_ram(&self, bytes: u64) -> usize {1018 self.cache_runtime()1019 .map(|cache| cache.relieve_ram(bytes))1020 .unwrap_or(0)1021 }1022 1023 /// One background cache maintenance pass.1024 pub fn maintain_cache(&self) -> Option<inf3r_cache::CacheMaintenance> {1025 self.cache_runtime().map(|cache| cache.maintain())1026 }1027 1028 /// Sets one bind's cache intent. A read-only bind still restores; it never1029 /// writes a checkpoint.1030 pub fn set_cache_intent(1031 &self,1032 plugin: &str,1033 class: Option<String>,1034 enabled: bool,1035 writable: bool,1036 ) {1037 lock(&self.cache_policy).insert(plugin.to_string(), (class, enabled, writable));1038 }1039 1040 /// Sets the default priority of one bind.1041 ///1042 /// A request that names no priority is the common case; the deploy file is1043 /// where the operator says that a GPU should serve background work.1044 pub fn set_priority(&self, plugin: &str, priority: Priority) {1045 lock(&self.priorities).insert(plugin.to_string(), priority);1046 }1047 1048 /// Sets the slot count of one bind. A missing number keeps the welcome.1049 pub fn set_max_inflight(&self, plugin: &str, slots: u16) {1050 lock(&self.max_inflight).insert(plugin.to_string(), slots);1051 }1052 1053 /// Names the devices that one bind runs on.1054 ///1055 /// The deploy file is the only place that knows the mapping. The catalogue1056 /// target says how many devices exist, not which ones this bind chose.1057 pub fn set_devices(&self, plugin: &str, devices: Vec<String>) {1058 lock(&self.devices).insert(plugin.to_string(), devices);1059 }1060 1061 /// Names the resident split that one bind's target declared.1062 ///1063 /// A plan with no device bytes and no RAM bytes is the default shape and1064 /// charges the whole catalogue weight count to every selected device.1065 pub fn set_memory_plan(&self, plugin: &str, plan: MemoryPlan) {1066 lock(&self.memory).insert(plugin.to_string(), plan);1067 }1068 1069 /// Records the moment a start begins; the failure path owns the clock.1070 fn note_start(&self, plugin: &str) {1071 self.failures.note_start(plugin);1072 }1073 1074 /// Clears the failure state after a start that reached `ready`.1075 fn note_success(&self, plugin: &str) {1076 self.failures.note_success(plugin);1077 }1078 1079 /// Records a failed peer and decides when it may start again.1080 fn note_failure(&self, plugin: &str, failure: Failure) {1081 self.failures.note_failure(plugin, failure);1082 }1083 1084 /// Refuses a start while the plugin waits or is unloadable.1085 fn start_allowed(&self, plugin: &str, request_id: &str) -> Result<(), CoreError> {1086 self.failures.start_allowed(plugin, request_id)1087 }1088 1089 /// Registers a peer for the served names in its catalogue.1090 pub fn register(&self, mut served: Served) -> Result<(), CoreError> {1091 // A start that raced the failure path must not add a peer while the1092 // old one is still being torn down. The request that owns that start1093 // stops its child and tries again after the backoff.1094 if lock(&self.stopping).contains(&served.plugin) {1095 return Err(CoreError::Refused(1096 Refusal::new(RefusalCode::LoadFailed, String::new())1097 .with(format!("{} is still stopping", served.plugin)),1098 ));1099 }1100 let deploy = lock(&self.max_inflight).get(&served.plugin).copied();1101 served.set_max_inflight(clamp_inflight(served.max_inflight(), deploy));1102 // The cache binder acts on one engine slot. A bind that declared more1103 // inflight jobs would restore and save through whichever slot the1104 // engine chose; serialize the peer until slot affinity exists.1105 if served.catalogue.cache.is_some() {1106 served.set_max_inflight(1);1107 }1108 if let Err(why) = lock(&self.catalog).add(&served.plugin, &served.catalogue) {1109 return Err(CoreError::Refused(1110 Refusal::new(RefusalCode::AmbiguousModel, String::new()).with(why.to_string()),1111 ));1112 }1113 lock(&self.catalogues).insert(served.plugin.clone(), served.catalogue.clone());1114 let served = Arc::new(served);1115 self.install_cache(&served);1116 // One entry per plugin: every served name of this bundle shares the1117 // same slots. An alias is not a second engine.1118 self.sched1119 .register(&served.plugin, served.max_inflight, self.queue_capacity);1120 let mut peers = lock(&self.peers);1121 for model in &served.models {1122 peers.insert(model.serve.clone(), served.clone());1123 }1124 self.residency.serve(1125 &served.plugin,1126 served.models.iter().map(|model| model.serve.clone()),1127 );1128 self.note_success(&served.plugin);1129 Ok(())1130 }1131 1132 /// Registers a catalogue without a peer, for a bind that loads on demand.1133 ///1134 /// `--describe` is the discovery path for a cold bind: a user can ask for a1135 /// name before the child exists. The names enter the catalog and schedule;1136 /// the first request starts the child through the loader and replaces this1137 /// cold registration with a live one.1138 pub fn register_cold(1139 &self,1140 plugin: &str,1141 catalogue: &body::Catalogue,1142 max_inflight: u16,1143 ) -> Result<(), CoreError> {1144 if let Err(why) = lock(&self.catalog).add(plugin, catalogue) {1145 return Err(CoreError::Refused(1146 Refusal::new(RefusalCode::AmbiguousModel, String::new()).with(why.to_string()),1147 ));1148 }1149 lock(&self.catalogues).insert(plugin.to_string(), catalogue.clone());1150 // A cold catalogue has no welcome yet. Admit one job until the live1151 // register returns the peer's own claim; the deploy value cannot1152 // raise a worker past one.1153 let deploy = lock(&self.max_inflight)1154 .get(plugin)1155 .copied()1156 .unwrap_or(max_inflight);1157 self.sched1158 .register(plugin, clamp_inflight(1, Some(deploy)), self.queue_capacity);1159 self.residency.serve(1160 plugin,1161 catalogue.models.iter().map(|model| model.serve.clone()),1162 );1163 Ok(())1164 }1165 1166 /// Ends discovery and resolves every alias that was still pending.1167 pub fn finish_catalog(&self) -> Result<(), CoreError> {1168 lock(&self.catalog).finish().map_err(|why| {1169 CoreError::Refused(1170 Refusal::new(RefusalCode::Mismatch, String::new()).with(why.to_string()),1171 )1172 })1173 }1174 1175 /// Stops the children that have been idle past their window.1176 ///1177 /// The idle predicate is evaluated by the caller's clock, so a test can age1178 /// a model without sleeping. Only the names that were stopped are returned:1179 /// a failed stop leaves the reservation in place, because the child may1180 /// still hold the device.1181 pub fn sweep_idle(&self, now: Instant, busy: &BTreeSet<String>) -> Vec<String> {1182 let _gate = self.failures.gate();1183 let candidates = self.residency.idle_candidates(now, busy);1184 let mut stopped = Vec::new();1185 for plugin in candidates {1186 if !lock(&self.stopping).insert(plugin.clone()) {1187 continue;1188 }1189 self.shutdown_served(&plugin);1190 if let Err(why) = self.loader().stop(&plugin) {1191 eprintln!("{plugin} did not stop: {why}");1192 lock(&self.stopping).remove(&plugin);1193 continue;1194 }1195 if let Some(reservation) = self.residency.release_plugin(&plugin) {1196 self.failures.release_after_stop(&plugin, reservation);1197 }1198 self.residency.forget_measured(&plugin);1199 self.remove_served(&plugin);1200 lock(&self.stopping).remove(&plugin);1201 stopped.push(plugin);1202 }1203 stopped1204 }1205 1206 /// Sweeps idle plugins with the core's own clock and busy set.1207 ///1208 /// The web calls this on a timer; a test can call it directly. The busy set1209 /// is read first, so a plugin with a live job is never a candidate.1210 pub fn sweep_idle_now(&self) -> Vec<String> {1211 let busy = self.busy_plugins();1212 self.sweep_idle(Instant::now(), &busy)1213 }1214 1215 /// Finds every plugin that died on its own and fails it.1216 ///1217 /// The web calls this on a timer. A caller that has just received an error1218 /// from a job can also call it before the next request, so recovery does1219 /// not depend on a monitor's clock.1220 pub fn reap(&self) -> Vec<String> {1221 let plugins: BTreeSet<String> = lock(&self.peers)1222 .values()1223 .map(|served| served.plugin.clone())1224 .collect();1225 let mut failed = Vec::new();1226 for plugin in plugins {1227 if self.reap_plugin(&plugin).is_some() {1228 failed.push(plugin);1229 }1230 }1231 failed1232 }1233 1234 /// Reaps one plugin, if its child or its peer has failed.1235 ///1236 /// A permanent `fatal` frame is the plugin's own verdict and wins over the1237 /// exit status, because a plugin that sent `frame` must not be retried as1238 /// if it had merely crashed. Any other exit is classified by `try_wait`,1239 /// which is the only source of the signal and the exit code.1240 fn reap_plugin(&self, plugin: &str) -> Option<Failure> {1241 if lock(&self.stopping).contains(plugin) {1242 return None;1243 }1244 let exit = match self.loader().exit(plugin) {1245 Ok(exit) => exit,1246 Err(why) => {1247 eprintln!("{plugin} could not be reaped: {why}");1248 None1249 }1250 };1251 let refusal = lock(&self.peers)1252 .values()1253 .find(|served| served.plugin == plugin)1254 .and_then(|served| served.peer.refusal())1255 .map(|refusal| failure_of(refusal.code));1256 // A permanent frame is the plugin's own verdict, even when it exits1257 // before the monitor sees the process. The exit status alone would1258 // call that a transient crash and retry a plugin that cannot work.1259 let failure = match refusal {1260 Some(failure) if failure.is_permanent() => Some(failure),1261 refusal => exit.or(refusal),1262 }?;1263 self.fail_plugin(plugin, failure);1264 Some(failure)1265 }1266 1267 /// Takes a failed plugin out of service and gives its bytes back.1268 ///1269 /// The catalog keeps the names, so a later request can start the same1270 /// plugin after the backoff. Only the peer, the process, and the1271 /// reservation go: an unload is not a switch.1272 fn fail_plugin(&self, plugin: &str, failure: Failure) {1273 self.failures.fail(plugin, failure);1274 }1275 1276 /// Replaces the child and the served names of one plugin.1277 ///1278 /// Every step has its own edge. A stop that fails leaves the old plugin1279 /// registered; a start or a reserve that fails leaves the ledger free. The1280 /// served map never holds a plugin between those two states.1281 pub fn switch(&self, plugin: &str, models: &[String]) -> Result<Served, CoreError> {1282 let busy = self.busy_plugins();1283 if busy.contains(plugin) {1284 return Err(switch_error(RefusalCode::QueueFull, "busy"));1285 }1286 1287 // A plugin that the core does not serve has no child to drain. A cold1288 // bind still has catalog names, and they must go before the new1289 // catalogue can replace them.1290 if !self.catalog_models(plugin).is_empty() {1291 if !lock(&self.stopping).insert(plugin.to_string()) {1292 return Err(switch_error(RefusalCode::QueueFull, "busy"));1293 }1294 self.shutdown_served(plugin);1295 if let Err(why) = self.loader().stop(plugin) {1296 lock(&self.stopping).remove(plugin);1297 return Err(switch_error(1298 RefusalCode::LoadFailed,1299 format!("stop_failed: {why}"),1300 ));1301 }1302 {1303 let _gate = self.failures.gate();1304 if let Some(reservation) = self.residency.release_plugin(plugin) {1305 self.failures.release_after_stop(plugin, reservation);1306 }1307 self.remove_plugin(plugin);1308 }1309 lock(&self.stopping).remove(plugin);1310 }1311 1312 self.note_start(plugin);1313 self.residency.capture_free(plugin);1314 let mut served = match self.loader().start(plugin) {1315 Ok(served) => served,1316 Err(why) => {1317 let failure = self1318 .loader()1319 .start_failure(plugin)1320 .unwrap_or(Failure::Crashed);1321 self.note_failure(plugin, failure);1322 return Err(switch_error(1323 RefusalCode::LoadFailed,1324 format!("start_failed: {why}"),1325 ));1326 }1327 };1328 let deploy = lock(&self.max_inflight).get(plugin).copied();1329 served.set_max_inflight(clamp_inflight(served.max_inflight(), deploy));1330 let offered: BTreeSet<&str> = served1331 .models1332 .iter()1333 .map(|model| model.serve.as_str())1334 .collect();1335 let wanted: BTreeSet<&str> = models.iter().map(String::as_str).collect();1336 if offered != wanted {1337 let _ = self.loader().stop(plugin);1338 return Err(switch_error(RefusalCode::Mismatch, "mismatch"));1339 }1340 1341 if let Err(why) = self.ensure_resident(&served, models, &busy) {1342 let _ = self.loader().stop(plugin);1343 return Err(switch_error(RefusalCode::NoRoom, format!("no_room: {why}")));1344 }1345 1346 let returned = served.clone();1347 if let Err(why) = self.register(served) {1348 let _ = self.loader().stop(plugin);1349 if let Some(reservation) = self.residency.release_plugin(plugin) {1350 self.release_after_stop(plugin, reservation);1351 }1352 return Err(switch_error(1353 RefusalCode::Mismatch,1354 format!("mismatch: {why}"),1355 ));1356 }1357 if let Err(why) = self.finish_catalog() {1358 let _ = self.loader().stop(plugin);1359 if let Some(reservation) = self.residency.release_plugin(plugin) {1360 self.release_after_stop(plugin, reservation);1361 }1362 self.remove_plugin(plugin);1363 return Err(switch_error(1364 RefusalCode::Mismatch,1365 format!("mismatch: {why}"),1366 ));1367 }1368 Ok(returned)1369 }1370 1371 fn loader(&self) -> Arc<dyn Loader> {1372 Arc::clone(&lock(&self.loader))1373 }1374 1375 fn busy_plugins(&self) -> BTreeSet<String> {1376 self.sched1377 .snapshot()1378 .into_iter()1379 .filter(|(_, in_flight, _, queued)| *in_flight > 0 || *queued > 0)1380 .map(|(plugin, _, _, _)| plugin)1381 .collect()1382 }1383 1384 fn remove_served(&self, plugin: &str) {1385 lock(&self.peers).retain(|_, served| served.plugin != plugin);1386 }1387 1388 /// Closes the socket of every peer that one plugin owns.1389 ///1390 /// A stop closes the supervisor's copy of the socket, but the core holds1391 /// another. Without this shutdown the child never sees EOF and waits for1392 /// the supervisor's kill, which is exactly the grace period that an idle1393 /// unload must not spend.1394 fn shutdown_served(&self, plugin: &str) {1395 let budget = self1396 .cache_runtime()1397 .map(|cache| cache.config().flush_budget)1398 .unwrap_or(Duration::from_secs(5));1399 for served in lock(&self.peers).values() {1400 if served.plugin != plugin {1401 continue;1402 }1403 // Cache flushing is the first half of D13. A Wire 1 peer has no1404 // cache frames, so the wait is skipped rather than spent.1405 if served.catalogue.cache.is_some() && served.wire_version() == Some(2) {1406 let _ = served.peer.flush_cache(budget);1407 }1408 let _ = served.peer.shutdown();1409 }1410 }1411 1412 /// Attaches the host cache to one live peer, if both sides declared it.1413 fn install_cache(&self, served: &Served) {1414 let Some(runtime) = self.cache_runtime() else {1415 return;1416 };1417 let Some(spec) = served.catalogue.cache.clone() else {1418 return;1419 };1420 if served.wire_version() != Some(2) {1421 eprintln!(1422 "{}: cache not attached: the peer did not negotiate Wire 2",1423 served.plugin1424 );1425 return;1426 }1427 let (class, enabled, writable) = lock(&self.cache_policy)1428 .get(&served.plugin)1429 .cloned()1430 .unwrap_or((None, true, true));1431 if !enabled {1432 return;1433 }1434 let fingerprint = match runtime.fingerprint(1435 &served.plugin,1436 &served.weights,1437 served.ready.and_then(|ready| ready.cache_fingerprint),1438 &served.catalogue,1439 ) {1440 Ok(fingerprint) => fingerprint,1441 Err(why) => {1442 eprintln!("{}: cache not attached: {why}", served.plugin);1443 return;1444 }1445 };1446 let class = class.unwrap_or_else(|| "standard".to_string());1447 let ttl = inf3r_cache::class_ttl(runtime.config(), &class);1448 match runtime.attach(&served.plugin, &spec, fingerprint, ttl, writable) {1449 Ok((session, host)) => served.install_cache(session, host),1450 Err(why) => eprintln!("{}: cache not attached: {why}", served.plugin),1451 }1452 }1453 1454 /// The catalog names of one plugin, in sorted order.1455 fn catalog_models(&self, plugin: &str) -> Vec<String> {1456 let catalog = lock(&self.catalog);1457 catalog1458 .names()1459 .filter(|name| {1460 catalog1461 .get(name)1462 .is_some_and(|entry| entry.plugin == plugin)1463 })1464 .map(str::to_string)1465 .collect()1466 }1467 1468 /// Removes every trace of a plugin that will not come back.1469 ///1470 /// An unload keeps the catalog names so that the first later request can1471 /// reload the same names. A switch replaces them, so it removes them here.1472 fn remove_plugin(&self, plugin: &str) {1473 lock(&self.catalog).remove_plugin(plugin);1474 lock(&self.catalogues).remove(plugin);1475 self.sched.remove(plugin);1476 self.remove_served(plugin);1477 self.residency.forget(plugin);1478 }1479 1480 fn wants(&self, served: &Served, models: &[String]) -> BTreeMap<String, u64> {1481 self.wants_for(&served.plugin, &served.catalogue, models)1482 }1483 1484 /// The bytes that one catalogue asks of each device, independent of whether1485 /// its child is already running.1486 fn wants_for(1487 &self,1488 plugin: &str,1489 catalogue: &body::Catalogue,1490 models: &[String],1491 ) -> BTreeMap<String, u64> {1492 let bytes: u64 = catalogue1493 .models1494 .iter()1495 .filter(|model| models.iter().any(|name| name == &model.serve))1496 .map(Model::reserved_bytes)1497 .sum();1498 let plan = lock(&self.memory).get(plugin).cloned();1499 let bound = lock(&self.devices).get(plugin).cloned();1500 let devices = match bound {1501 Some(devices) => devices,1502 // A library caller that never names devices still gets the old1503 // behavior: the ledger's own device list is the target.1504 None => self1505 .residency1506 .devices()1507 .into_iter()1508 .map(|(device, _, _)| device)1509 .collect(),1510 };1511 devices1512 .into_iter()1513 .enumerate()1514 .map(|(index, device)| {1515 let want = match &plan {1516 Some(plan) if device.starts_with("cuda:") => {1517 plan.device_bytes.get(index).copied().unwrap_or(0)1518 }1519 Some(_) => 0,1520 None => bytes,1521 };1522 (device, want)1523 })1524 .collect()1525 }1526 1527 /// Frees room for a catalogue before its child is allowed to allocate.1528 ///1529 /// A cold plugin has no live `Served`, so the normal post-load reservation1530 /// would run after the engine had already asked the driver for its1531 /// weights. On a full card that is too late: the engine fails before the1532 /// ledger can evict the previous resident. This preflight reserves the1533 /// declared bytes, drops the reservation, and repeats with an LRU victim1534 /// until the ledger answers. The post-load check still verifies what the1535 /// child actually allocated.1536 fn make_room(1537 &self,1538 wants: &BTreeMap<String, u64>,1539 busy: &BTreeSet<String>,1540 ) -> Result<(), ResidencyError> {1541 let _gate = self.failures.gate();1542 loop {1543 match self.residency.reserve(wants) {1544 Ok(reservation) => {1545 self.residency.release(reservation);1546 return Ok(());1547 }1548 Err(why @ ResidencyError::NoRoom { .. }) => {1549 let ResidencyError::NoRoom { device, .. } = &why else {1550 unreachable!("the match arm is a NoRoom error");1551 };1552 let Some(victim) = self.residency.lru_on(device, busy, &lock(&self.stopping))1553 else {1554 return Err(why);1555 };1556 if !lock(&self.stopping).insert(victim.clone()) {1557 return Err(why);1558 }1559 self.shutdown_served(&victim);1560 if let Err(stop) = self.loader().stop(&victim) {1561 eprintln!("{victim} did not stop: {stop}");1562 lock(&self.stopping).remove(&victim);1563 return Err(why);1564 }1565 if let Some(reservation) = self.residency.release_plugin(&victim) {1566 self.failures.release_after_stop(&victim, reservation);1567 }1568 self.residency.forget_measured(&victim);1569 self.remove_served(&victim);1570 lock(&self.stopping).remove(&victim);1571 }1572 Err(why) => return Err(why),1573 }1574 }1575 }1576 1577 fn ensure_resident(1578 &self,1579 served: &Served,1580 models: &[String],1581 busy: &BTreeSet<String>,1582 ) -> Result<(), ResidencyError> {1583 // One reservation or release at a time. A second thread must not see1584 // bytes that a settle wait has not seen the driver free yet.1585 let _gate = self.failures.gate();1586 if self.residency.resident(&served.plugin) {1587 return Ok(());1588 }1589 if let Some(cache) = self.cache_runtime() {1590 let ram_want: u64 = served1591 .catalogue1592 .models1593 .iter()1594 .filter(|model| models.iter().any(|name| name == &model.serve))1595 .map(|model| model.weights_bytes)1596 .sum::<u64>()1597 .saturating_add(1598 served1599 .catalogue1600 .cache1601 .as_ref()1602 .map(|cache| cache.local_ram_bytes)1603 .unwrap_or(0),1604 );1605 if ram_want != 01606 && let Some(available) = available_memory()1607 && available < ram_want1608 {1609 cache.relieve_ram(ram_want.saturating_sub(available));1610 }1611 for path in &served.weights {1612 if let Ok(meta) = std::fs::metadata(path) {1613 cache.pressure(meta.dev(), meta.len());1614 }1615 }1616 }1617 let wants = self.wants(served, models);1618 loop {1619 match self.residency.reserve(&wants) {1620 Ok(reservation) => {1621 self.residency.hold(&served.plugin, reservation);1622 return Ok(());1623 }1624 Err(why @ ResidencyError::NoRoom { .. }) => {1625 let ResidencyError::NoRoom { device, .. } = &why else {1626 unreachable!("the match arm is a NoRoom error");1627 };1628 let Some(victim) = self.residency.lru_on(device, busy, &lock(&self.stopping))1629 else {1630 return Err(why);1631 };1632 if !lock(&self.stopping).insert(victim.clone()) {1633 return Err(why);1634 }1635 self.shutdown_served(&victim);1636 if let Err(stop) = self.loader().stop(&victim) {1637 eprintln!("{victim} did not stop: {stop}");1638 lock(&self.stopping).remove(&victim);1639 return Err(why);1640 }1641 if let Some(reservation) = self.residency.release_plugin(&victim) {1642 self.failures.release_after_stop(&victim, reservation);1643 }1644 self.residency.forget_measured(&victim);1645 self.remove_served(&victim);1646 lock(&self.stopping).remove(&victim);1647 // The next pass asks the ledger again. One victim that1648 // frees too little must not turn a roomy host into a1649 // refusal while a second cold model could leave.1650 }1651 Err(why) => return Err(why),1652 }1653 }1654 }1655 1656 /// One row per plugin, sorted by plugin id.1657 ///1658 /// The schedule and the residency ledger both count by plugin, so this is1659 /// the place where their rows and the served names are joined for the1660 /// operator.1661 pub fn engines(&self) -> Vec<EngineStat> {1662 let peers: Vec<Arc<Served>> = lock(&self.peers).values().cloned().collect();1663 let usage = lock(&self.usage);1664 let mut rows: BTreeMap<String, EngineStat> = BTreeMap::new();1665 for served in peers {1666 if rows.contains_key(&served.plugin) {1667 continue;1668 }1669 let names: Vec<String> = served1670 .models1671 .iter()1672 .map(|model| model.serve.clone())1673 .collect();1674 let in_flight = usize::from(self.sched.in_flight(&served.plugin));1675 let queued = self.sched.queued(&served.plugin);1676 let last = usage.get(&served.plugin).copied().unwrap_or_default();1677 rows.insert(1678 served.plugin.clone(),1679 EngineStat {1680 plugin: served.plugin.clone(),1681 served: names,1682 slots: served.max_inflight(),1683 in_flight,1684 queued,1685 load_ms: served.load_ms(),1686 declared_bytes: served.models.iter().map(|model| model.weights_bytes).sum(),1687 measured_bytes: self.residency.measured(&served.plugin),1688 tokens_out: last.tokens_out,1689 first_token_ms: last.first_token_ms,1690 tokens_per_s: last.tokens_per_s,1691 },1692 );1693 }1694 rows.into_values().collect()1695 }1696 1697 /// One entry of the catalog, cloned so that no lock is held on return.1698 pub fn entry(&self, model: &str) -> Option<inf3r_catalog::Entry> {1699 lock(&self.catalog).get(model).cloned()1700 }1701 1702 /// Every entry of the catalog, sorted by served name.1703 pub fn entries(&self) -> Vec<inf3r_catalog::Entry> {1704 let catalog = lock(&self.catalog);1705 catalog1706 .names()1707 .filter_map(|name| catalog.get(name).cloned())1708 .collect()1709 }1710 1711 /// Whether the catalog knows a served name.1712 pub fn knows(&self, model: &str) -> bool {1713 lock(&self.catalog).get(model).is_some()1714 }1715 1716 /// One peer by served name.1717 pub fn served(&self, model: &str) -> Option<Arc<Served>> {1718 lock(&self.peers).get(model).cloned()1719 }1720 1721 /// Closes every peer socket before the supervisor stops its child.1722 ///1723 /// The process is leaving, so no job may start; a child that sees EOF can1724 /// exit inside the supervisor's grace instead of waiting for the kill.1725 pub fn shutdown(&self) {1726 let _gate = self.failures.gate();1727 let plugins: BTreeSet<String> = lock(&self.peers)1728 .values()1729 .map(|served| served.plugin.clone())1730 .collect();1731 for plugin in plugins {1732 lock(&self.stopping).insert(plugin.clone());1733 self.shutdown_served(&plugin);1734 }1735 // The process is leaving, so no driver wait is useful. The ledger1736 // still has to lose every reservation before its value is dropped.1737 self.residency.release_all();1738 }1739 1740 /// The job table.1741 pub fn jobs(&self) -> Arc<JobTable> {1742 Arc::clone(&self.jobs)1743 }1744 1745 /// Removes terminal job rows that ended longer than `keep` ago.1746 ///1747 /// The web calls this on a timer. A row that is still running is never1748 /// removed, even if a bug left it behind; the drop of its `CoreJob` is the1749 /// path that ends it.1750 pub fn sweep_jobs(&self, keep: Duration) -> usize {1751 self.jobs.sweep(keep)1752 }1753 1754 /// The schedule, for the stats route.1755 pub fn sched(&self) -> Arc<Sched> {1756 Arc::clone(&self.sched)1757 }1758 1759 /// The ledger of device bytes.1760 pub fn residency(&self) -> Arc<Residency> {1761 Arc::clone(&self.residency)1762 }1763 1764 /// Releases a reservation after the supervisor stopped its child.1765 ///1766 /// A driver frees mmapped weights after the process exits, so a release1767 /// that lands first leaves the next load refused for room that is about to1768 /// appear. The reservation still must not outlive the process: a settle1769 /// that reaches its budget logs the wait and releases anyway.1770 pub fn release_after_stop(&self, plugin: &str, reservation: Reservation) {1771 let _gate = self.failures.gate();1772 self.failures.release_after_stop(plugin, reservation);1773 }1774 1775 /// The peer of a served name, starting its plugin if it is cold.1776 ///1777 /// A name stays in the catalog after an idle unload or an eviction, so the1778 /// first later request finds the plugin id but no peer. The gate is per1779 /// plugin: two requests that arrive together wait for one start, and the1780 /// second sees the peer that the first registered.1781 fn ensure_served(&self, model: &str, request_id: &str) -> Result<Arc<Served>, CoreError> {1782 if let Some(served) = self.served(model) {1783 let _ = self.reap_plugin(&served.plugin);1784 if let Some(served) = self.served(model) {1785 if lock(&self.stopping).contains(&served.plugin) {1786 return Err(refusal(1787 RefusalCode::LoadFailed,1788 request_id,1789 format!("{} is still stopping", served.plugin),1790 ));1791 }1792 return Ok(served);1793 }1794 }1795 let plugin = {1796 let catalog = lock(&self.catalog);1797 let Some(entry) = catalog.get(model) else {1798 return Err(refusal(1799 RefusalCode::UnknownModel,1800 request_id,1801 format!("no model {model}"),1802 ));1803 };1804 entry.plugin.clone()1805 };1806 let gate = {1807 let mut starting = lock(&self.starting);1808 Arc::clone(1809 starting1810 .entry(plugin.clone())1811 .or_insert_with(|| Arc::new(Mutex::new(()))),1812 )1813 };1814 let _held = lock(&gate);1815 if let Some(served) = self.served(model) {1816 return Ok(served);1817 }1818 1819 self.start_allowed(&plugin, request_id)?;1820 // A cold child loads its weights before the post-load reservation can1821 // choose a victim. Ask the ledger for the declared bytes first, so a1822 // full device evicts the previous engine instead of failing inside the1823 // new engine's allocator.1824 if let Some(catalogue) = lock(&self.catalogues).get(&plugin).cloned() {1825 let loaded = self.catalog_models(&plugin);1826 let wants = self.wants_for(&plugin, &catalogue, &loaded);1827 let busy = self.busy_plugins();1828 if let Err(why) = self.make_room(&wants, &busy) {1829 return Err(CoreError::Refused(1830 Refusal::new(why.code(), request_id.to_string()).with(why.to_string()),1831 ));1832 }1833 }1834 self.note_start(&plugin);1835 self.residency.capture_free(&plugin);1836 let mut served = match self.loader().start(&plugin) {1837 Ok(served) => served,1838 Err(why) => {1839 let failure = self1840 .loader()1841 .start_failure(&plugin)1842 .unwrap_or(Failure::Crashed);1843 self.note_failure(&plugin, failure);1844 let _ = self.loader().stop(&plugin);1845 return Err(refusal(1846 RefusalCode::LoadFailed,1847 request_id,1848 format!("{plugin} did not start: {why}"),1849 ));1850 }1851 };1852 // Only the names that the bind chose may enter the catalog. A stale1853 // catalog from before an eviction is exactly that list.1854 served.retain_models(&self.catalog_models(&plugin));1855 if !served.names().any(|name| name == model) {1856 self.note_failure(&plugin, Failure::Frame);1857 let _ = self.loader().stop(&plugin);1858 return Err(refusal(1859 RefusalCode::LoadFailed,1860 request_id,1861 format!("{plugin} started without serving {model}"),1862 ));1863 }1864 if let Err(why) = self.register(served) {1865 let _ = self.loader().stop(&plugin);1866 if let Some(reservation) = self.residency.release_plugin(&plugin) {1867 self.release_after_stop(&plugin, reservation);1868 }1869 return Err(why);1870 }1871 self.served(model).ok_or_else(|| {1872 refusal(1873 RefusalCode::LoadFailed,1874 request_id,1875 format!("{plugin} registered without serving {model}"),1876 )1877 })1878 }1879 1880 /// Admits a job and opens its stream on the plugin that serves it.1881 ///1882 /// The checks run in the order of core.md section 5: name, capability,1883 /// parts, size, then a slot. A refusal is decided before a queue slot, so a1884 /// request that can never work does not wait behind one that can.1885 pub fn submit(&self, mut submit: Submit) -> Result<CoreJob, CoreError> {1886 // The catalog is authority for the name and the capability, even when1887 // the child that serves them is not running yet.1888 let entry = self.entry(&submit.model).ok_or_else(|| {1889 CoreError::Refused(1890 Refusal::new(RefusalCode::UnknownModel, submit.request_id.clone())1891 .with(format!("no model {}", submit.model)),1892 )1893 })?;1894 // A child that exited since the last request is a state, not a dead1895 // route. Reap it before the name is looked up, so the next start sees1896 // the failure count and the ledger sees the release.1897 let _ = self.reap_plugin(&entry.plugin);1898 if let Some(priority) = lock(&self.priorities).get(&entry.plugin).copied() {1899 submit.priority = priority;1900 }1901 let capability = entry.capabilities.get(&submit.capability).ok_or_else(|| {1902 CoreError::Refused(1903 Refusal::new(RefusalCode::UnknownCapability, submit.request_id.clone()).with(1904 format!("{} does not declare {}", submit.model, submit.capability),1905 ),1906 )1907 })?;1908 1909 check_parts(&submit, capability)?;1910 1911 if submit.priority == Priority::Background && capability.degraded() {1912 return Err(refused(1913 &submit,1914 RefusalCode::CapabilityMissing,1915 format!(1916 "{} cannot serve a background job: {} is degraded",1917 submit.model, submit.capability1918 ),1919 ));1920 }1921 1922 // Admission checks are complete before a cold child spends memory on a1923 // request that can never run.1924 let served = self.ensure_served(&submit.model, &submit.request_id)?;1925 1926 let mut busy = self.busy_plugins();1927 // The model that this request asks for is in use by the request even1928 // before it holds a slot, so the sweep must not stop it.1929 busy.insert(served.plugin.clone());1930 let _ = self.sweep_idle(Instant::now(), &busy);1931 1932 // A load brings every name that this plugin serves, so the ledger1933 // reserves the whole catalogue selection, not only the name that this1934 // request happened to ask for.1935 let loaded: Vec<String> = served1936 .models1937 .iter()1938 .map(|model| model.serve.clone())1939 .collect();1940 self.ensure_resident(&served, &loaded, &busy)1941 .map_err(|why| {1942 CoreError::Refused(1943 Refusal::new(why.code(), submit.request_id.clone()).with(why.to_string()),1944 )1945 })?;1946 1947 let now = Instant::now();1948 let deadline = now + submit.budget;1949 let slot = self1950 .sched1951 .acquire(&served.plugin, submit.priority, now, deadline)1952 .map_err(|why| {1953 let code = match why {1954 SchedError::QueueFull => RefusalCode::QueueFull,1955 SchedError::Expired | SchedError::Timeout => RefusalCode::Timeout,1956 SchedError::Unknown => RefusalCode::UnknownModel,1957 };1958 CoreError::Refused(1959 Refusal::new(code, submit.request_id.clone()).with(why.to_string()),1960 )1961 })?;1962 1963 let open = Open {1964 request_id: submit.request_id.clone(),1965 model: submit.model.clone(),1966 capability: submit.capability.clone(),1967 credit: submit.credit,1968 // The plugin gets what the queue did not spend. Its own timer and1969 // the core's absolute deadline then name the same instant.1970 budget_ms: u32::try_from(1971 deadline1972 .saturating_duration_since(Instant::now())1973 .as_millis(),1974 )1975 .unwrap_or(u32::MAX),1976 parts: submit.parts,1977 params: submit.params,1978 };1979 1980 let model = submit.model.clone();1981 let plugin = served.plugin.clone();1982 let id = self1983 .jobs1984 .open(&plugin, &model, &submit.capability, &submit.request_id);1985 let borrowed: Vec<BorrowedFd<'_>> = submit.files.iter().map(AsFd::as_fd).collect();1986 match served.peer.open(open, &borrowed) {1987 Ok(job) => {1988 let attached = self.jobs.attach(&id, job.id(), job.handle());1989 if !attached {1990 let _ = job.cancel();1991 }1992 Ok(CoreJob {1993 job,1994 _slot: slot,1995 model,1996 plugin,1997 id,1998 jobs: Arc::clone(&self.jobs),1999 residency: Arc::clone(&self.residency),2000 usage: Arc::clone(&self.usage),2001 failures: Arc::clone(&self.failures),2002 served: Arc::clone(&served),2003 deadline,2004 // A row that a cancel ended before `attach` is already2005 // terminal. The job object still reads its stream, but it2006 // must not report another end in `Drop`.2007 ended: !attached,2008 })2009 }2010 Err(why) => {2011 let failure = served2012 .peer2013 .refusal()2014 .map(|refusal| failure_of(refusal.code))2015 .unwrap_or(Failure::Crashed);2016 self.fail_plugin(&plugin, failure);2017 self.jobs.finish(2018 &id,2019 JobState::Failed {2020 code: RefusalCode::PluginCrashed,2021 message: why.to_string(),2022 },2023 );2024 Err(CoreError::Io(why.to_string()))2025 }2026 }2027 }2028 }2029 2030 /// Checks the parts against the capability of the model.2031 fn check_parts(submit: &Submit, capability: &Capability) -> Result<(), CoreError> {2032 for part in &submit.parts {2033 if !capability.parts.contains(&part.kind) {2034 return Err(refused(2035 submit,2036 RefusalCode::InvalidPart,2037 format!(2038 "{} does not take a {} part",2039 submit.capability,2040 kind_name(part.kind)2041 ),2042 ));2043 }2044 if part.mime.is_empty() {2045 return Err(refused(2046 submit,2047 RefusalCode::InvalidPart,2048 "a part has no mime type",2049 ));2050 }2051 match &part.hold {2052 body::Hold::Inline(bytes) if bytes.len() as u64 != part.len => {2053 return Err(refused(2054 submit,2055 RefusalCode::InvalidPart,2056 "the declared length of a part is not its length",2057 ));2058 }2059 body::Hold::Inline(_) => {}2060 body::Hold::Fd(index) => {2061 let slot = usize::try_from(*index).unwrap_or(usize::MAX);2062 let Some(file) = submit.files.get(slot) else {2063 return Err(refused(2064 submit,2065 RefusalCode::InvalidPart,2066 format!("a part names descriptor {index}, which did not arrive"),2067 ));2068 };2069 let len = file.metadata().map(|meta| meta.len()).map_err(|why| {2070 refused(2071 submit,2072 RefusalCode::InvalidPart,2073 format!("a part descriptor cannot be measured: {why}"),2074 )2075 })?;2076 if len != part.len {2077 return Err(refused(2078 submit,2079 RefusalCode::InvalidPart,2080 format!(2081 "a part descriptor is {len} bytes and the part declares {}",2082 part.len2083 ),2084 ));2085 }2086 }2087 }2088 }2089 Ok(())2090 }2091 2092 fn refused(submit: &Submit, code: RefusalCode, message: impl Into<String>) -> CoreError {2093 CoreError::Refused(Refusal::new(code, submit.request_id.clone()).with(message))2094 }2095 2096 fn refusal(code: RefusalCode, request_id: &str, message: impl Into<String>) -> CoreError {2097 CoreError::Refused(Refusal::new(code, request_id.to_string()).with(message))2098 }2099 2100 /// A switch failure carries the refusal code that names the edge it stopped at.2101 fn switch_error(code: RefusalCode, message: impl Into<String>) -> CoreError {2102 CoreError::Refused(Refusal::new(code, String::new()).with(message))2103 }2104 2105 /// The supervisor's class for a wire fatal code.2106 ///2107 /// The five permanent codes are exactly the ones in spec section 14 rule 11.2108 /// A timeout is transient; every other code (credit, internal, cancelled) is2109 /// a peer that may be tried again after the wait.2110 fn failure_of(code: body::ErrorCode) -> Failure {2111 use body::ErrorCode as Wire;2112 match code {2113 Wire::Version => Failure::Version,2114 Wire::Frame => Failure::Frame,2115 Wire::Stream => Failure::Stream,2116 Wire::Size => Failure::Size,2117 Wire::Dependency => Failure::Dependency,2118 Wire::Timeout => Failure::Timeout,2119 Wire::UnknownModel2120 | Wire::Capability2121 | Wire::Part2122 | Wire::Busy2123 | Wire::Credit2124 | Wire::Cancelled2125 | Wire::Internal => Failure::Crashed,2126 }2127 }2128 2129 /// The word for a wire outcome, as the client contract spells it.2130 pub fn outcome_name(outcome: body::Outcome) -> &'static str {2131 match outcome {2132 body::Outcome::Completed => "completed",2133 body::Outcome::Cancelled => "cancelled",2134 body::Outcome::Failed => "failed",2135 body::Outcome::Expired => "timeout",2136 }2137 }2138 2139 fn kind_name(kind: PartKind) -> &'static str {2140 match kind {2141 PartKind::Text => "text",2142 PartKind::Image => "image",2143 PartKind::Audio => "audio",2144 PartKind::Video => "video",2145 PartKind::Tokens => "tokens",2146 PartKind::Json => "json",2147 }2148 }2149 2150 fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {2151 m.lock().unwrap_or_else(|poisoned| poisoned.into_inner())2152 }2153 2154 #[cfg(test)]2155 mod inflight {2156 use super::clamp_inflight;2157 2158 #[test]2159 fn a_deploy_value_cannot_raise_a_worker_past_its_welcome() {2160 assert_eq!(clamp_inflight(1, Some(2)), 1);2161 assert_eq!(clamp_inflight(4, Some(2)), 2);2162 assert_eq!(clamp_inflight(4, None), 4);2163 }2164 }