1 //! `inf3r-web` — the process that holds the core and answers HTTP.2 //!3 //! Startup is the deploy file, in this order: read it, refuse it if it cannot be4 //! honoured, then for each bind start the plugin, greet it, load it, and put its5 //! models in the catalog. Nothing answers a request until every warm plugin is6 //! ready, so a client never sees a half-built engine.7 //!8 //! Usage: `inf3r-web [--deploy <path>]`. The default is `deploy.toml` in the9 //! working directory.10 11 use std::collections::BTreeMap;12 use std::fs::{self, File, OpenOptions};13 use std::io::{self, Read, Write};14 use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};15 use std::path::{Path, PathBuf};16 use std::process::ExitCode;17 use std::sync::{Arc, Mutex, MutexGuard};18 use std::thread;19 use std::time::Duration;20 21 use inf3r_blobs::Blobs;22 use inf3r_cache::{Cache, CacheConfig, Persist, TierConfig};23 use inf3r_container::{ContainerSpec, Mount, Probe};24 use inf3r_core::{25 CacheRuntime, Core, DEFAULT_SETTLE_STEP, HostMemory, Loader, Memory, MemoryPlan, Priority,26 Served, Settle,27 };28 use inf3r_deploy::{Bind, CacheMode, Deploy, Node, Runtime};29 use inf3r_host::{Host, Profile};30 use inf3r_proto::body::{Catalogue, Model};31 use inf3r_server::app::App;32 use inf3r_server::auth::Auth;33 use inf3r_server::{Limits, Stop, serve_unix_until, serve_until};34 use inf3r_supervisor::{Child, Command as SpawnCommand, Failure, SpawnError};35 36 /// The largest request head that the web accepts. A head is a request line and37 /// its headers; a real client sends a few hundred bytes, so 8 KiB is room for38 /// the doubles that a proxy adds and no more.39 const MAX_HEAD: usize = 8 << 10;40 41 /// The most junk that the web buffers in memory. This equals `MAX_INLINE` in42 /// `app`: a part that does not fit in the body is not an inline part, it is an43 /// upload, and an upload is spooled instead of buffered.44 const MAX_BODY: usize = 1 << 20;45 46 /// The longest one socket read may block. A client that stops in the middle47 /// of a request is closed instead of holding a thread until the drain ends.48 const READ_TIMEOUT: Duration = Duration::from_secs(30);49 50 /// The total time that the web gives a client to send a request line and its51 /// headers. The deadline is absolute, so a slowloris that drips one byte at a52 /// time still ends.53 const HEAD_TIMEOUT: Duration = Duration::from_secs(30);54 55 /// The longest one socket write may block. A client that stops reading a56 /// stream cannot hold the connection open past this.57 const WRITE_TIMEOUT: Duration = Duration::from_secs(30);58 59 /// The most connections that the web serves at once. A connection above this60 /// count gets 503 and is closed; the acceptor does not grow a thread for it.61 const MAX_CONNECTIONS: usize = 64;62 63 /// The handshake and load deadline of one plugin. A plugin that has not64 /// connected and loaded in this time is reported and not served; the operator65 /// decides what to do about it. It is not a retry: a load that is slow is slow66 /// on the second attempt too.67 const START: Duration = Duration::from_secs(120);68 69 /// The variable in which the binder finds its bundle. The web knows the70 /// directory; a binary installed away from the checkout does not.71 const BUNDLE_DIR: &str = inf3r_container::BUNDLE_DIR_ENV;72 73 /// The build record that turns an image reference into a content pin. A74 /// control in a container does not have the repository's `target/`, so a75 /// compose deployment mounts the lock and names it here.76 const IMAGES_LOCK: &str = "INF3R_IMAGES_LOCK";77 78 /// One mebibyte. A VRAM figure is declared in MiB; the ledger counts bytes.79 const MB: u64 = 1 << 20;80 81 /// The pause between a stop and a kill.82 const GRACE: Duration = Duration::from_secs(10);83 84 /// The bytes of the bearer token. The deploy file spells it as 64 hex digits.85 const TOKEN_BYTES: usize = 32;86 87 /// The only private directory mode: no group, no other.88 const PRIVATE_DIR: u32 = 0o700;89 90 /// The token file is readable by its owner and nobody else.91 const PRIVATE_FILE: u32 = 0o600;92 93 /// The pause between two idle sweeps. An idle window is measured in minutes94 /// for a real model, so one second is fine enough and cheap when nothing is95 /// resident.96 const IDLE_SWEEP: Duration = Duration::from_secs(1);97 98 /// The pause between two crash checks. A dead peer is a broken socket, so the99 /// wait is short enough that a client sees the failed stream, not a stall.100 const REAP: Duration = Duration::from_millis(100);101 102 /// How long a finished job stays visible at `/jobs`. The row is the only place103 /// that an operator can find the outcome of a request after its client left.104 const JOB_KEEP: Duration = Duration::from_secs(10 * 60);105 106 /// The pause between two job-table sweeps. A job row is small, but a busy web107 /// can make thousands, and the table must not grow with uptime.108 const JOB_SWEEP: Duration = Duration::from_secs(60);109 110 /// The pause between two cache maintenance passes. Demotion and promotion are111 /// background economics, not request latency.112 const CACHE_MAINTENANCE: Duration = Duration::from_secs(5);113 114 /// The bytes that the filesystem can still give to unprivileged writers, for115 /// a blob store with no declared bound. The number can never be `u64::MAX`.116 fn free_space(dir: &Path) -> Result<u64, String> {117 let stat =118 rustix::fs::statvfs(dir).map_err(|why| format!("statvfs {}: {why}", dir.display()))?;119 let unit = if stat.f_frsize == 0 {120 stat.f_bsize121 } else {122 stat.f_frsize123 };124 Ok(stat.f_bavail.saturating_mul(unit))125 }126 127 fn main() -> ExitCode {128 let mut deploy = PathBuf::from("deploy.toml");129 let mut init_token = false;130 let mut args = std::env::args().skip(1);131 while let Some(arg) = args.next() {132 match arg.as_str() {133 "--deploy" => match args.next() {134 Some(path) => deploy = PathBuf::from(path),135 None => {136 eprintln!("--deploy needs a path");137 return ExitCode::from(2);138 }139 },140 "--version" | "-V" => {141 println!("{}", env!("CARGO_PKG_VERSION"));142 return ExitCode::SUCCESS;143 }144 "--init-token" => init_token = true,145 "--help" | "-h" => {146 println!("usage: inf3r-web [--deploy <path>] [--init-token] [--version]");147 return ExitCode::SUCCESS;148 }149 other => {150 eprintln!("unknown argument {other}");151 return ExitCode::from(2);152 }153 }154 }155 156 if init_token {157 return match prepare_token(&deploy) {158 Ok(()) => ExitCode::SUCCESS,159 Err(why) => {160 eprintln!("inf3r-web: {why}");161 ExitCode::FAILURE162 }163 };164 }165 match run(&deploy) {166 Ok(()) => ExitCode::SUCCESS,167 Err(why) => {168 eprintln!("inf3r-web: {why}");169 ExitCode::FAILURE170 }171 }172 }173 174 /// Creates the state directories and the first bearer token without ever175 /// overwriting an existing token. The release image has no shell, `od`, or176 /// `tr`; this is the one-shot initialisation that replaces the entrypoint.177 fn prepare_token(path: &Path) -> Result<(), String> {178 let deploy = Deploy::read(path).map_err(|why| why.to_string())?;179 let node = &deploy.node;180 private_dir(&node.blob_dir)?;181 if let Some(socket_dir) = &node.socket_dir {182 private_dir(socket_dir)?;183 }184 if let Some(parent) = node.auth_file.parent()185 && !parent.as_os_str().is_empty()186 {187 private_dir(parent)?;188 }189 if node.auth_file.exists() {190 return Ok(());191 }192 let mut bytes = [0u8; TOKEN_BYTES];193 File::open("/dev/urandom")194 .and_then(|mut file| file.read_exact(&mut bytes))195 .map_err(|why| format!("read /dev/urandom: {why}"))?;196 let mut token = String::with_capacity(TOKEN_BYTES * 2);197 for byte in bytes {198 use std::fmt::Write as _;199 write!(&mut token, "{byte:02x}").expect("a String accepts formatting");200 }201 let mut file = OpenOptions::new()202 .write(true)203 .create_new(true)204 .mode(PRIVATE_FILE)205 .open(&node.auth_file)206 .map_err(|why| format!("create {}: {why}", node.auth_file.display()))?;207 writeln!(file, "{token}")208 .map_err(|why| format!("write {}: {why}", node.auth_file.display()))?;209 Ok(())210 }211 212 /// Creates a private directory, or tightens an existing one to 0700.213 fn private_dir(path: &Path) -> Result<(), String> {214 fs::create_dir_all(path).map_err(|why| format!("create {}: {why}", path.display()))?;215 fs::set_permissions(path, fs::Permissions::from_mode(PRIVATE_DIR))216 .map_err(|why| format!("chmod {}: {why}", path.display()))217 }218 219 fn run(path: &Path) -> Result<(), String> {220 let deploy = Deploy::read(path).map_err(|why| why.to_string())?;221 let node = &deploy.node;222 // Every conflict is reported before anything starts. A host that binds223 // half of its plugins is worse than one that refuses, because a client224 // cannot tell an absent model from one that failed.225 let conflicts = node.conflicts();226 if !conflicts.is_empty() {227 for conflict in &conflicts {228 eprintln!("inf3r-web: {conflict}");229 }230 return Err(format!(231 "{} conflict(s); no plugin started",232 conflicts.len()233 ));234 }235 println!(236 "inf3r-web: host {} with {} bind(s)",237 node.host,238 node.binds.len()239 );240 241 if node242 .binds243 .iter()244 .any(|bind| bind.runtime == Runtime::Container)245 {246 inf3r_container::docker_reachable().map_err(|why| {247 format!(248 "a container bind needs Docker: {why}. The host service runs as the inf3r account; use the compose control or give that account access to the rootless daemon socket."249 )250 })?;251 }252 253 // A container bind is measured through the generic probe helper, because254 // the control may be in its own PID namespace and has no GPU. A process255 // bind keeps the local probe. The profile check uses whichever host record256 // the deploy's runtime mode provides.257 let probe = node258 .probe_image259 .as_ref()260 .map(|image| Arc::new(Probe::new(image.clone(), cdi_devices(node))));261 let host = match &probe {262 Some(probe) => probe.host().map_err(|why| {263 format!(264 "probe image {}: {why}",265 node.probe_image.as_deref().unwrap_or("")266 )267 })?,268 None => Host::probe(),269 };270 271 let image_lock = images_lock();272 // The target profile is authority: every bind is checked against the273 // machine before any child starts, so a refusal never leaves half the host274 // running (spec section 16.1, requirement R34).275 let mut profiles = BTreeMap::new();276 for bind in &node.binds {277 let profile = ensure_profile(node, &bind.bundle, &bind.devices, &host)?;278 profiles.insert(bind.bundle.clone(), profile);279 if bind.runtime == Runtime::Container {280 // A container bind is discovered from manifests, not from a281 // binary in the control. `bundle.toml` is the bundle's identity;282 // requiring it here also names a missing manifest mount before283 // Docker starts anything.284 let manifest = node285 .bundle_dirs286 .iter()287 .map(|root| root.join(&bind.bundle).join("bundle.toml"))288 .find(|path| path.is_file())289 .ok_or_else(|| format!("bundle {} has no bundle.toml", bind.bundle))?;290 std::fs::read(&manifest)291 .map_err(|why| format!("bundle {}: {}: {why}", bind.bundle, manifest.display()))?;292 }293 if bind.runtime == Runtime::Container {294 let image = bind.image.as_deref().unwrap_or_default();295 if !inf3r_container::image_present(image) {296 return Err(format!(297 "bundle {} image {:?} is not in the local Docker store; the control never pulls",298 bind.bundle, bind.image299 ));300 }301 inf3r_container::verify_image(image, &bind.bundle, image_lock.as_deref())302 .map_err(|why| format!("bundle {} image {:?}: {why}", bind.bundle, bind.image))?;303 }304 }305 if node306 .binds307 .iter()308 .any(|bind| bind.runtime == Runtime::Container)309 {310 // A previous instance of this control may have been killed before311 // `--rm` ran. The scope is the runtime root, so another control on the312 // same daemon is never swept.313 let control = inf3r_container::control_scope(314 node.socket_dir.as_deref(),315 node.socket_host_dir.as_deref(),316 );317 inf3r_container::sweep(&control);318 }319 320 // The local credential is the process uid. A Unix socket peer has no321 // bearer token, so the allow list must hold the uid that this process322 // runs as; an empty list refuses every local request (spec section 9.1).323 let mut auth = Auth::from_token_file(&node.auth_file).map_err(|why| why.to_string())?;324 auth.allow_uid(rustix::process::geteuid().as_raw());325 let blob_bound = match node.blob_bound {326 Some(bound) => bound,327 None => free_space(&node.blob_dir)?,328 };329 let blobs = Blobs::open(&node.blob_dir, blob_bound)330 .map_err(|why| format!("blob store {}: {why}", node.blob_dir.display()))?;331 332 let run_dir = node333 .socket_dir334 .clone()335 .unwrap_or_else(inf3r_supervisor::default_run_dir);336 let run_host_dir = node337 .socket_host_dir338 .clone()339 .unwrap_or_else(|| run_dir.clone());340 let _ = inf3r_supervisor::sweep_stale(&run_dir);341 let loader = Arc::new(Children::new(run_dir.clone(), run_host_dir.clone()));342 let core = Arc::new(Core::with_loader(loader.clone()));343 if let Some(cache) = &node.cache344 && cache.enabled345 {346 let config = cache_config(node, cache);347 let store = Cache::open(config.clone()).map_err(|why| format!("cache: {why}"))?;348 core.set_cache(Arc::new(CacheRuntime::new(store, config)));349 println!(350 "inf3r-web: cache enabled with {} tier(s)",351 cache.tiers.len()352 );353 }354 core.residency().set_settle(Settle {355 budget: node.settle,356 step: DEFAULT_SETTLE_STEP,357 });358 if let Some(probe) = &probe {359 let probe = Arc::clone(probe);360 core.residency()361 .set_free_sampler(move |device| probe.free(device));362 }363 for bind in &node.binds {364 let profile = profiles365 .get(&bind.bundle)366 .cloned()367 .ok_or_else(|| format!("bundle {} has no checked profile", bind.bundle))?;368 let launch = launch_spec(node, bind);369 // The loader is what a later unload and reload uses, so it must know370 // the weight files before the first child starts.371 loader.configure(&bind.bundle, bind.weights.clone(), launch.clone());372 core.set_priority(&bind.bundle, priority(bind.priority));373 core.set_cache_intent(374 &bind.bundle,375 bind.cache_class.clone(),376 bind.cache_mode != CacheMode::Off,377 bind.cache_mode == CacheMode::Auto,378 );379 if let Some(slots) = bind.max_inflight {380 core.set_max_inflight(&bind.bundle, slots);381 }382 383 if bind.warm {384 core.residency()385 .capture_free_on(&bind.bundle, &bind.devices);386 match start(387 &launch,388 &bind.bundle,389 &bind.weights,390 &run_dir,391 &run_host_dir,392 ) {393 Ok((mut served, mut child)) => {394 let pid = match child.host_pid() {395 Some(pid) => pid,396 None => {397 eprintln!("inf3r-web: {} has no host pid", bind.bundle);398 let _ = child.stop(GRACE);399 continue;400 }401 };402 loader.adopt(&bind.bundle, child);403 if let Err(why) = select_served(&mut served, &bind.models) {404 eprintln!("inf3r-web: {}: {why}", bind.bundle);405 let _ = loader.stop(&bind.bundle);406 continue;407 }408 // The catalogue declares the weights of the models this409 // bind serves. A split target moves part of that number to410 // host RAM; the child is measured on both sides before any411 // job can reach it.412 let plan = match memory_plan(&profile, &served.catalogue, &bind.devices) {413 Ok(plan) => plan,414 Err(why) => {415 eprintln!("inf3r-web: {}: {why}", bind.bundle);416 let _ = loader.stop(&bind.bundle);417 continue;418 }419 };420 if let Some(plan) = &plan {421 core.set_memory_plan(&bind.bundle, plan.clone());422 }423 let declared = plan.as_ref().map_or_else(424 || served.models.iter().map(Model::reserved_bytes).sum(),425 MemoryPlan::device_total,426 );427 let memory = MemoryFor {428 probe: probe.as_deref(),429 };430 match core431 .residency()432 .verify_devices(pid, declared, &bind.devices, &memory)433 {434 Ok(Some(measured)) => {435 core.residency().remember_measured(&bind.bundle, measured);436 }437 Ok(None) => {}438 Err(why) => {439 eprintln!("inf3r-web: {} did not load: {why}", bind.bundle);440 let _ = loader.stop(&bind.bundle);441 continue;442 }443 }444 if let Some(plan) = &plan445 && let Err(why) = core.residency().verify_ram(pid, plan.ram_bytes, &memory)446 {447 eprintln!("inf3r-web: {} did not load: {why}", bind.bundle);448 let _ = loader.stop(&bind.bundle);449 continue;450 }451 let wants =452 declare_devices(&core, &host, bind, &served.catalogue, plan.as_ref());453 let reservation = match core.residency().reserve(&wants) {454 Ok(reservation) => reservation,455 Err(why) => {456 eprintln!("inf3r-web: {} does not fit: {why}", bind.bundle);457 let _ = loader.stop(&bind.bundle);458 continue;459 }460 };461 core.residency().hold(&bind.bundle, reservation);462 println!(463 "inf3r-web: {} loaded in {} ms",464 bind.bundle,465 served.load_ms().unwrap_or(0)466 );467 if let Err(why) = core.register(served) {468 let _ = loader.stop(&bind.bundle);469 return Err(format!("{}: {why}", bind.bundle));470 }471 core.residency()472 .declare_intent(&bind.bundle, bind.pin, bind.idle_unload);473 }474 Err(why) => {475 // A bind that cannot start is reported and skipped: the rest476 // of the host still serves, and the operator sees which477 // plugin is missing at startup and in `/models`.478 eprintln!("inf3r-web: {} did not start: {why}", bind.bundle);479 }480 }481 } else {482 // A cold bind is discovered, not loaded. `--describe` reads the483 // catalogue without weights or a device, so a missing weight file484 // does not hide the name that the operator bound.485 match launch.describe() {486 Ok(catalogue) => match select_catalogue(catalogue, &bind.models) {487 Ok(catalogue) => {488 match memory_plan(&profile, &catalogue, &bind.devices) {489 Ok(Some(plan)) => core.set_memory_plan(&bind.bundle, plan),490 Ok(None) => {}491 Err(why) => {492 eprintln!("inf3r-web: {}: {why}", bind.bundle);493 continue;494 }495 }496 declare_devices(&core, &host, bind, &catalogue, None);497 if let Err(why) = core.register_cold(498 &bind.bundle,499 &catalogue,500 bind.max_inflight.unwrap_or(1),501 ) {502 eprintln!("inf3r-web: {}: {why}", bind.bundle);503 continue;504 }505 core.residency()506 .declare_intent(&bind.bundle, bind.pin, bind.idle_unload);507 println!("inf3r-web: {} cold", bind.bundle);508 }509 Err(why) => eprintln!("inf3r-web: {}: {why}", bind.bundle),510 },511 Err(why) => eprintln!("inf3r-web: {} did not describe: {why}", bind.bundle),512 }513 }514 }515 if let Err(why) = core.finish_catalog() {516 core.shutdown();517 for plugin in loader.running() {518 let _ = loader.stop(&plugin);519 }520 return Err(why.to_string());521 }522 523 let sweeping = Arc::clone(&core);524 let checking = Arc::clone(&core);525 let cleaning = Arc::clone(&core);526 let caching = Arc::clone(&core);527 let shutdown = Arc::clone(&core);528 let app = Arc::new(App::new(core, blobs, auth));529 let limits = Limits {530 max_head_bytes: MAX_HEAD,531 max_body_bytes: MAX_BODY,532 max_upload_bytes: usize::try_from(blob_bound).unwrap_or(usize::MAX),533 read_timeout: READ_TIMEOUT,534 head_timeout: HEAD_TIMEOUT,535 write_timeout: WRITE_TIMEOUT,536 max_connections: MAX_CONNECTIONS,537 };538 539 // The first signal drains, the second leaves. The flag is read by the540 // accept loop; the connections that are running finish their own jobs.541 let stop = Stop::new();542 stop.install()543 .map_err(|why| format!("signal handler: {why}"))?;544 545 // A crash is a process exit or a fatal frame. The reader wakes a job when546 // its peer dies; this timer is what removes the peer, stops the child,547 // gives the ledger back, and remembers the failure for the next start.548 let until = stop.clone();549 thread::spawn(move || {550 while !until.stopping() {551 for plugin in checking.reap() {552 println!("inf3r-web: {plugin} failed");553 }554 thread::sleep(REAP);555 }556 });557 558 // Idle unload has to happen while no request is arriving, or it only runs559 // when the next request asks for a model and the memory is already needed.560 let until = stop.clone();561 thread::spawn(move || {562 while !until.stopping() {563 for plugin in sweeping.sweep_idle_now() {564 println!("inf3r-web: {plugin} idle");565 }566 thread::sleep(IDLE_SWEEP);567 }568 });569 570 // A finished row is useful for a while, then it is a leak. The sweep is on571 // its own slow clock: the job table does not need the crash monitor's572 // hundred-millisecond attention.573 let until = stop.clone();574 thread::spawn(move || {575 while !until.stopping() {576 cleaning.sweep_jobs(JOB_KEEP);577 thread::sleep(JOB_SWEEP);578 }579 });580 581 // Cache demotion, promotion, expiry, and compaction are host chores. They582 // run on a slow clock so a busy cache never spends a request thread on583 // bytes that no current job needs.584 let until = stop.clone();585 thread::spawn(move || {586 while !until.stopping() {587 let _ = caching.maintain_cache();588 thread::sleep(CACHE_MAINTENANCE);589 }590 });591 592 let web = &node.web;593 if web.unix.is_none() && web.tcp.is_none() {594 return Err("the deploy file names no listener".to_string());595 }596 // A TCP bind comes first so that a failed bind does not leave a Unix socket597 // file behind. Both listeners see the same `App` and the same `Stop`, so a598 // local CLI and a remote client reach one core and one drain.599 let tcp = match &web.tcp {600 Some(tcp) => {601 let listener =602 std::net::TcpListener::bind(tcp).map_err(|why| format!("bind {tcp}: {why}"))?;603 println!("inf3r-web: listening on {tcp}");604 Some(listener)605 }606 None => None,607 };608 let unix = match &web.unix {609 Some(unix) => {610 if unix.exists() {611 std::fs::remove_file(unix)612 .map_err(|why| format!("remove {}: {why}", unix.display()))?;613 }614 let listener = std::os::unix::net::UnixListener::bind(unix)615 .map_err(|why| format!("bind {}: {why}", unix.display()))?;616 println!("inf3r-web: listening on {}", unix.display());617 Some(listener)618 }619 None => None,620 };621 let result = serve_all(unix, tcp, limits, &stop, Arc::clone(&app));622 623 shutdown.shutdown();624 for plugin in loader.running() {625 match loader.stop(&plugin) {626 Ok(()) => println!("inf3r-web: {plugin} stopped"),627 Err(why) => eprintln!("inf3r-web: {plugin} did not stop: {why}"),628 }629 }630 result.map_err(|why| why.to_string())631 }632 633 /// Runs every configured listener and waits for each accept loop to drain.634 ///635 /// The two loops share one `App` and one `Stop`. The first loop to end (a636 /// signal, an accept error, or a panic) stops the other. A listener error is637 /// returned instead of hidden by a clean shutdown.638 fn serve_all(639 unix: Option<std::os::unix::net::UnixListener>,640 tcp: Option<std::net::TcpListener>,641 limits: Limits,642 stop: &Stop,643 app: Arc<App>,644 ) -> io::Result<()> {645 if unix.is_none() && tcp.is_none() {646 return Err(io::Error::other("no web listener is configured"));647 }648 let unix_thread = unix.map(|listener| {649 let app = Arc::clone(&app);650 let stop = stop.clone();651 thread::spawn(move || {652 serve_unix_until(listener, limits, &stop, move |request| app.handle(request))653 })654 });655 let tcp_thread = tcp.map(|listener| {656 let app = Arc::clone(&app);657 let stop = stop.clone();658 thread::spawn(move || {659 serve_until(listener, limits, &stop, move |request| app.handle(request))660 })661 });662 663 // A listener that has finished must stop the other before it drains. The664 // join then sees both results; a panic becomes an error instead of a665 // process that waits forever on a thread that will not return.666 loop {667 let unix_done = unix_thread668 .as_ref()669 .is_some_and(|thread| thread.is_finished());670 let tcp_done = tcp_thread671 .as_ref()672 .is_some_and(|thread| thread.is_finished());673 if unix_done || tcp_done {674 break;675 }676 thread::sleep(Stop::pause());677 }678 stop.request();679 680 let mut failed = None;681 if let Some(thread) = unix_thread {682 match thread.join() {683 Ok(Ok(())) => {}684 Ok(Err(why)) => failed = Some(why),685 Err(_) => failed = Some(io::Error::other("the unix listener panicked")),686 }687 }688 if let Some(thread) = tcp_thread {689 match thread.join() {690 Ok(Ok(())) => {}691 Ok(Err(why)) => {692 if failed.is_none() {693 failed = Some(why);694 }695 }696 Err(_) => {697 if failed.is_none() {698 failed = Some(io::Error::other("the TCP listener panicked"));699 }700 }701 }702 }703 failed.map_or(Ok(()), Err)704 }705 706 /// Reads the target profile of one bundle and checks it against the host on707 /// the devices that this bind selected.708 ///709 /// The bundle directory is the first one that holds the id, in deploy order.710 /// An absent directory or an absent profile is a refusal with the path, because711 /// a bundle without its hardware declaration cannot be checked. A mixed host712 /// checks only the bind's cards, so a card that this bundle does not target713 /// cannot refuse it.714 fn ensure_profile(715 node: &Node,716 bundle: &str,717 devices: &[String],718 host: &Host,719 ) -> Result<Profile, String> {720 let dir = node721 .bundle_dirs722 .iter()723 .map(|root| root.join(bundle))724 .find(|dir| dir.is_dir())725 .ok_or_else(|| format!("bundle {bundle} is below no bundle directory"))?;726 let path = dir.join("target.toml");727 if !path.is_file() {728 return Err(format!(729 "bundle {bundle} has no target profile at {}",730 path.display()731 ));732 }733 let profile =734 inf3r_host::Profile::read(&path).map_err(|why| format!("bundle {bundle}: {why}"))?;735 profile.check(host, devices).map_err(|mismatch| {736 format!(737 "bundle {bundle} needs {} {}, host has {}",738 mismatch.field, mismatch.required, mismatch.measured739 )740 })?;741 Ok(profile)742 }743 744 /// Keeps the models that one bind names, and refuses a name the plugin omits.745 fn select_catalogue(mut catalogue: Catalogue, models: &[String]) -> Result<Catalogue, String> {746 for model in models {747 if !catalogue748 .models749 .iter()750 .any(|offered| &offered.serve == model)751 {752 return Err(format!("the catalogue serves no model {model}"));753 }754 }755 catalogue756 .models757 .retain(|offered| models.iter().any(|model| model == &offered.serve));758 Ok(catalogue)759 }760 761 /// The same selection for a plugin that is already loaded.762 fn select_served(served: &mut Served, models: &[String]) -> Result<(), String> {763 for model in models {764 if !served.names().any(|name| name == model) {765 return Err(format!("the catalogue serves no model {model}"));766 }767 }768 served.retain_models(models);769 Ok(())770 }771 772 /// Validates and builds the split resident plan for one bind.773 ///774 /// The profile names one device count and one RAM count. The bind must select775 /// exactly that many CUDA devices, and the two parts must not claim more than776 /// the catalogue's total resident bytes. A target without a split returns777 /// `None`, which keeps the old whole-set-on-every-device accounting.778 fn memory_plan(779 profile: &Profile,780 catalogue: &Catalogue,781 devices: &[String],782 ) -> Result<Option<MemoryPlan>, String> {783 let Some((device_bytes, ram_bytes)) = profile.split_resident() else {784 return Ok(None);785 };786 if device_bytes.len() != devices.len() {787 return Err(format!(788 "the split names {} devices but the bind selects {}",789 device_bytes.len(),790 devices.len()791 ));792 }793 if !devices.iter().all(|device| device.starts_with("cuda:")) {794 return Err("a split target must select CUDA devices".to_string());795 }796 let total: u64 = catalogue.models.iter().map(Model::reserved_bytes).sum();797 let claimed = device_bytes798 .iter()799 .copied()800 .fold(ram_bytes, u64::saturating_add);801 if claimed > total {802 return Err(format!(803 "the split claims {claimed} resident bytes for a {total} byte catalogue"804 ));805 }806 Ok(Some(MemoryPlan {807 device_bytes,808 ram_bytes,809 }))810 }811 812 /// The bytes that a bind asks of each device.813 ///814 /// A load holds one copy of the weights and one KV cache on every device that815 /// the bind names. The deploy file chooses the devices; the catalogue declares816 /// the bytes.817 fn device_wants(818 bind: &Bind,819 catalogue: &Catalogue,820 plan: Option<&MemoryPlan>,821 ) -> BTreeMap<String, u64> {822 // Weights plus the one KV cache that a load uses. The deploy file says823 // which devices, not how many bytes the model needs. A split target puts824 // its host-RAM bytes in the profile, so they are not charged here.825 let bytes: u64 = catalogue.models.iter().map(Model::reserved_bytes).sum();826 bind.devices827 .iter()828 .enumerate()829 .map(|(index, device)| {830 let want = match plan {831 Some(plan) if device.starts_with("cuda:") => {832 plan.device_bytes.get(index).copied().unwrap_or(0)833 }834 Some(_) => 0,835 None => bytes,836 };837 (device.clone(), want)838 })839 .collect()840 }841 842 /// Declares the capacity of each bound device and returns this bind's wants.843 ///844 /// The probe is authority for a GPU that it can see. A CPU device, or a GPU845 /// whose driver does not report bytes, falls back to the target profile that846 /// the bundle declared. The first declaration of a device wins, so two binds847 /// on one card share the capacity that the machine reported.848 fn declare_devices(849 core: &Core,850 host: &Host,851 bind: &Bind,852 catalogue: &Catalogue,853 plan: Option<&MemoryPlan>,854 ) -> BTreeMap<String, u64> {855 core.set_devices(&bind.bundle, bind.devices.clone());856 for (index, device) in bind.devices.iter().enumerate() {857 let probed = host.gpu(device).and_then(|gpu| gpu.bytes);858 let declared = bind.vram.get(index).copied().or_else(|| {859 catalogue860 .target861 .vram_mb862 .get(index)863 .map(|mb| u64::from(*mb) * MB)864 });865 core.residency()866 .declare(device, probed.or(declared).unwrap_or_default());867 }868 device_wants(bind, catalogue, plan)869 }870 871 /// The core's spelling of the deploy file's priority.872 fn priority(priority: inf3r_deploy::Priority) -> Priority {873 match priority {874 inf3r_deploy::Priority::Interactive => Priority::Interactive,875 inf3r_deploy::Priority::Background => Priority::Background,876 }877 }878 879 /// How one bind starts its engine.880 #[derive(Clone)]881 enum LaunchSpec {882 /// A binary in `bin_dir`, started as a child of the control.883 Process {884 program: PathBuf,885 env: Vec<(String, String)>,886 },887 /// A sibling Docker container. The image carries the plugin and its engine888 /// libraries; the control supplies only the socket and descriptor grants.889 Container(ContainerSpec),890 }891 892 impl LaunchSpec {893 /// Whether a weight grant carries the host path.894 fn carries_paths(&self) -> bool {895 matches!(self, LaunchSpec::Process { .. })896 }897 898 /// The catalogue that a cold bind prints.899 fn describe(&self) -> Result<Catalogue, String> {900 match self {901 LaunchSpec::Process { program, env } => {902 let mut command = std::process::Command::new(program);903 command.arg("--describe");904 for (key, value) in env {905 command.env(key, value);906 }907 let output = command908 .output()909 .map_err(|why| format!("{} --describe: {why}", program.display()))?;910 if !output.status.success() {911 return Err(format!(912 "{} --describe exited {}",913 program.display(),914 output.status915 ));916 }917 let text = String::from_utf8(output.stdout)918 .map_err(|_| format!("{} --describe is not UTF-8", program.display()))?;919 parse_catalogue(&text, &program.display().to_string())920 }921 LaunchSpec::Container(spec) => {922 let output = spec923 .describe()924 .map_err(|why| format!("{} --describe: {why}", spec.image))?;925 if !output.status.success() {926 let stderr = String::from_utf8_lossy(&output.stderr);927 return Err(format!(928 "{} --describe exited {}: {}",929 spec.image,930 output.status,931 stderr.trim()932 ));933 }934 let text = String::from_utf8(output.stdout)935 .map_err(|_| format!("{} --describe is not UTF-8", spec.image))?;936 parse_catalogue(&text, &spec.image)937 }938 }939 }940 }941 942 /// Builds the launch record that both startup and a later reload use.943 fn launch_spec(node: &Node, bind: &Bind) -> LaunchSpec {944 match bind.runtime {945 Runtime::Process => LaunchSpec::Process {946 program: binary(&node.bin_dir, &bind.bundle),947 env: bundle_env(node, &bind.bundle),948 },949 Runtime::Container => {950 let mut spec =951 ContainerSpec::new(bind.image.clone().unwrap_or_default(), bind.bundle.clone());952 spec.control = inf3r_container::control_scope(953 node.socket_dir.as_deref(),954 node.socket_host_dir.as_deref(),955 );956 if let Some(value) = bind.pids_limit {957 spec.pids_limit = value;958 }959 if let Some(value) = bind.memory_bytes {960 spec.memory_bytes = value;961 }962 if let Some(value) = bind.shm_bytes {963 spec.shm_bytes = value;964 }965 if let Some(value) = bind.log_max_bytes {966 spec.log_max_bytes = value;967 }968 if let Some(value) = bind.log_max_files {969 spec.log_max_files = value;970 }971 spec.env.push((972 inf3r_container::BUNDLE_DIR_ENV.to_string(),973 inf3r_container::bundle_dir(&bind.bundle),974 ));975 spec.command = bind.command.clone();976 spec.network = bind.network.clone();977 spec.devices = bind978 .devices979 .iter()980 .filter_map(|device| inf3r_container::device_reference(device))981 .collect();982 spec.mounts = bind983 .mounts984 .iter()985 .map(|mount| Mount {986 source: mount.source.clone(),987 target: mount.target.clone(),988 read_only: mount.read_only,989 })990 .collect();991 LaunchSpec::Container(spec)992 }993 }994 }995 996 /// The CDI references that the probe helper may see.997 ///998 /// CDI renumbers the devices in every container: a container that receives only999 /// `cuda:1` sees that card as `cuda:0`. The probe must keep the host index that1000 /// the deploy file uses, or a bind on the second card would be checked and1001 /// measured against the first. `nvidia.com/gpu=all` is the one CDI device that1002 /// preserves every host index, so the probe asks for all cards as soon as any1003 /// bind names a CUDA device. The engine still receives only the device that its1004 /// own bind names.1005 fn cdi_devices(node: &Node) -> Vec<String> {1006 let wants_cuda = node1007 .binds1008 .iter()1009 .flat_map(|bind| bind.devices.iter())1010 .any(|device| inf3r_container::device_reference(device).is_some());1011 if wants_cuda {1012 vec!["nvidia.com/gpu=all".to_string()]1013 } else {1014 Vec::new()1015 }1016 }1017 1018 /// The memory seam for a container that may be in another PID namespace.1019 struct MemoryFor<'a> {1020 probe: Option<&'a Probe>,1021 }1022 1023 impl Memory for MemoryFor<'_> {1024 fn rss(&self, root: u32) -> Option<u64> {1025 match self.probe {1026 Some(probe) => probe.rss(root),1027 None => HostMemory.rss(root),1028 }1029 }1030 1031 fn vram(&self, root: u32, device: &str) -> Option<u64> {1032 match self.probe {1033 Some(probe) => probe.vram(root, device),1034 None => HostMemory.vram(root, device),1035 }1036 }1037 }1038 1039 /// Starts one plugin and connects to it, handing it the bind's weight files.1040 fn start(1041 launch: &LaunchSpec,1042 plugin: &str,1043 weights: &[PathBuf],1044 run_dir: &Path,1045 run_host_dir: &Path,1046 ) -> Result<(Served, Child), inf3r_core::CoreError> {1047 let mut child = match launch {1048 LaunchSpec::Process { program, env } => Child::spawn_in(1049 SpawnCommand {1050 program: program.clone(),1051 args: Vec::new(),1052 env: env.clone(),1053 },1054 run_dir,1055 ),1056 LaunchSpec::Container(spec) => {1057 Child::spawn_container_in_host(spec.clone(), run_dir, run_host_dir)1058 }1059 }1060 .map_err(|why| inf3r_core::CoreError::Io(why.to_string()))?;1061 let socket = match child.accept(START) {1062 Ok(socket) => socket,1063 Err(SpawnError::Connect(status)) => {1064 let logs = child.logs();1065 let detail = if logs.trim().is_empty() {1066 format!("the plugin exited before it connected: {status}")1067 } else {1068 format!(1069 "the plugin exited before it connected: {status}; logs: {}",1070 logs.trim()1071 )1072 };1073 return Err(inf3r_core::CoreError::Failed {1074 failure: Failure::from_exit(status),1075 message: detail,1076 });1077 }1078 Err(SpawnError::Timeout) => {1079 return Err(inf3r_core::CoreError::Failed {1080 failure: Failure::Timeout,1081 message: "the plugin did not connect in time".into(),1082 });1083 }1084 Err(SpawnError::Io(why)) => {1085 let logs = child.logs();1086 return Err(inf3r_core::CoreError::Io(if logs.trim().is_empty() {1087 format!("accept io: {why}")1088 } else {1089 format!("accept io: {why}; logs: {}", logs.trim())1090 }));1091 }1092 };1093 let served = Served::connect_paths(1094 plugin,1095 socket,1096 plugin,1097 weights,1098 START,1099 launch.carries_paths(),1100 )1101 .map_err(|why| {1102 let logs = child.logs();1103 if logs.trim().is_empty() {1104 why1105 } else {1106 inf3r_core::CoreError::Io(format!("{why}; logs: {}", logs.trim()))1107 }1108 })?;1109 Ok((served, child))1110 }1111 1112 /// Parses the one JSON object that `--describe` prints.1113 fn parse_catalogue(text: &str, label: &str) -> Result<Catalogue, String> {1114 let value = inf3r_json::parse(text).map_err(|why| format!("{label} --describe: {why}"))?;1115 let value = inf3r_proto::mirror::from_json(&value)1116 .ok_or_else(|| format!("{label} --describe is not a protocol value"))?;1117 Catalogue::from_value(&value).map_err(|why| format!("{label} --describe: {why}"))1118 }1119 1120 /// The binary of a plugin id.1121 ///1122 /// The id is a path below a bundle directory, so `mock/x64-cpu` becomes1123 /// `bin_dir/inf3r-mock-x64-cpu`: one rule, and the binary of a plugin is found1124 /// without a manifest that names it (spec section 17, rule 9).1125 fn bundle_env(node: &Node, plugin: &str) -> Vec<(String, String)> {1126 for root in &node.bundle_dirs {1127 let dir = root.join(plugin);1128 if dir.join("bundle.toml").is_file() {1129 return vec![(BUNDLE_DIR.to_string(), dir.to_string_lossy().into_owned())];1130 }1131 }1132 Vec::new()1133 }1134 1135 /// The image lock that this process can read.1136 ///1137 /// An explicit `INF3R_IMAGES_LOCK` is authoritative even when the file is1138 /// missing, so a typo is refused instead of silently disabling provenance. A1139 /// control container has no `target/`; compose mounts the lock. With no lock1140 /// the verifier falls back to the image's content tag and source label.1141 fn images_lock() -> Option<PathBuf> {1142 std::env::var_os(IMAGES_LOCK).map(PathBuf::from)1143 }1144 1145 /// Translates the deploy file's cache intent into the store's configuration.1146 fn cache_config(node: &Node, cache: &inf3r_deploy::Cache) -> CacheConfig {1147 CacheConfig {1148 enabled: cache.enabled,1149 persist: match cache.persist {1150 inf3r_deploy::CachePersist::Reboot => Persist::Reboot,1151 inf3r_deploy::CachePersist::Session => Persist::Session,1152 },1153 pin_bound: cache.pin_bound,1154 flush_budget: cache.flush_budget,1155 default_ttl: cache.default_ttl,1156 classes: cache1157 .classes1158 .iter()1159 .map(|class| (class.name.clone(), class.ttl))1160 .collect(),1161 tiers: cache1162 .tiers1163 .iter()1164 .map(|tier| TierConfig {1165 name: tier.name.clone(),1166 dir: tier.dir.clone(),1167 bound: tier.bound,1168 headroom: tier.headroom,1169 ttl: tier.ttl,1170 })1171 .collect(),1172 blob_dir: node.blob_dir.clone(),1173 }1174 }1175 1176 fn binary(bin_dir: &Path, plugin: &str) -> PathBuf {1177 bin_dir.join(format!("inf3r-{}", plugin.replace('/', "-")))1178 }1179 1180 /// The children that the web owns.1181 ///1182 /// The core decides when a model leaves; the supervisor knows how a child is1183 /// stopped. This is the seam between them, and the mutex is what lets a switch1184 /// on one request thread and a shutdown on another share the same map.1185 struct Children {1186 run_dir: PathBuf,1187 run_host_dir: PathBuf,1188 running: Mutex<BTreeMap<String, Child>>,1189 launches: Mutex<BTreeMap<String, LaunchSpec>>,1190 weights: Mutex<BTreeMap<String, Vec<PathBuf>>>,1191 start_failures: Mutex<BTreeMap<String, Failure>>,1192 }1193 1194 impl Children {1195 fn new(run_dir: PathBuf, run_host_dir: PathBuf) -> Children {1196 Children {1197 run_dir,1198 run_host_dir,1199 running: Mutex::new(BTreeMap::new()),1200 launches: Mutex::new(BTreeMap::new()),1201 weights: Mutex::new(BTreeMap::new()),1202 start_failures: Mutex::new(BTreeMap::new()),1203 }1204 }1205 1206 fn configure(&self, plugin: &str, weights: Vec<PathBuf>, launch: LaunchSpec) {1207 lock(&self.weights).insert(plugin.to_string(), weights);1208 lock(&self.launches).insert(plugin.to_string(), launch);1209 }1210 1211 fn adopt(&self, plugin: &str, child: Child) {1212 lock(&self.running).insert(plugin.to_string(), child);1213 }1214 1215 /// The plugins that have a child now. A cold load enters the same map.1216 fn running(&self) -> Vec<String> {1217 lock(&self.running).keys().cloned().collect()1218 }1219 }1220 1221 impl Loader for Children {1222 fn start_failure(&self, plugin: &str) -> Option<Failure> {1223 lock(&self.start_failures).remove(plugin)1224 }1225 1226 fn exit(&self, plugin: &str) -> Result<Option<Failure>, String> {1227 let mut running = lock(&self.running);1228 let Some(child) = running.get_mut(plugin) else {1229 return Ok(None);1230 };1231 let status = child.exited().map_err(|why| why.to_string())?;1232 if let Some(status) = status {1233 running.remove(plugin);1234 return Ok(Some(Failure::from_exit(status)));1235 }1236 Ok(None)1237 }1238 1239 fn stop(&self, plugin: &str) -> Result<(), String> {1240 let Some(mut child) = lock(&self.running).remove(plugin) else {1241 return Ok(());1242 };1243 child.stop(GRACE).map(|_| ()).map_err(|why| why.to_string())1244 }1245 1246 fn start(&self, plugin: &str) -> Result<Served, String> {1247 lock(&self.start_failures).remove(plugin);1248 let Some(launch) = lock(&self.launches).get(plugin).cloned() else {1249 return Err(format!("no launch record for {plugin}"));1250 };1251 let weights = lock(&self.weights).get(plugin).cloned().unwrap_or_default();1252 let (served, child) =1253 match start(&launch, plugin, &weights, &self.run_dir, &self.run_host_dir) {1254 Ok((served, child)) => (served, child),1255 Err(why) => {1256 if let Some(failure) = why.failure() {1257 lock(&self.start_failures).insert(plugin.to_string(), failure);1258 }1259 return Err(why.to_string());1260 }1261 };1262 lock(&self.running).insert(plugin.to_string(), child);1263 Ok(served)1264 }1265 }1266 1267 fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {1268 m.lock().unwrap_or_else(|poisoned| poisoned.into_inner())1269 }1270 1271 #[cfg(test)]1272 mod tests {1273 use super::free_space;1274 1275 #[test]1276 fn a_store_without_a_bound_uses_the_free_space_not_a_negative_number() {1277 let bytes = free_space(&std::env::temp_dir()).unwrap();1278 assert!(bytes > 0);1279 assert_ne!(bytes, u64::MAX);1280 assert!(i64::try_from(bytes).is_ok());1281 }1282 }1283 1284 #[cfg(test)]1285 mod capacity_tests {1286 use super::*;1287 use std::collections::BTreeSet;1288 1289 use inf3r_host::Gpu;1290 use inf3r_proto::body::{Capability, Model, Target};1291 1292 fn bind(vram: u64) -> Bind {1293 Bind {1294 bundle: "example/cpu".into(),1295 runtime: Runtime::Process,1296 image: None,1297 command: Vec::new(),1298 network: "none".into(),1299 mounts: Vec::new(),1300 models: vec!["demo".into()],1301 devices: vec!["cuda:0".into()],1302 weights: Vec::new(),1303 vram: vec![vram],1304 pin: false,1305 warm: true,1306 idle_unload: None,1307 priority: inf3r_deploy::Priority::Interactive,1308 max_inflight: None,1309 cache_class: None,1310 cache_mode: inf3r_deploy::CacheMode::Auto,1311 pids_limit: None,1312 memory_bytes: None,1313 shm_bytes: None,1314 log_max_bytes: None,1315 log_max_files: None,1316 }1317 }1318 1319 fn catalogue(weights: u64) -> Catalogue {1320 Catalogue {1321 target: Target {1322 id: "cuda".into(),1323 backend: "cuda".into(),1324 arch: vec!["sm00".into()],1325 devices: 1,1326 vram_mb: vec![50],1327 },1328 models: vec![Model {1329 serve: "demo".into(),1330 alias_of: None,1331 weights_bytes: weights,1332 load_ms: 0,1333 capabilities: BTreeMap::from([(1334 "chat".into(),1335 Capability {1336 vocab: "chat.v1".into(),1337 parts: vec![inf3r_proto::body::PartKind::Text],1338 channels: vec!["text".into()],1339 limits: BTreeMap::new(),1340 cancel: inf3r_proto::body::Cancel::default(),1341 stops: inf3r_proto::body::Stops::default(),1342 queue: inf3r_proto::body::Queue::default(),1343 },1344 )]),1345 }],1346 runtime: None,1347 cache: None,1348 }1349 }1350 1351 fn node(binds: Vec<Bind>) -> Node {1352 Node {1353 host: "test".into(),1354 bin_dir: PathBuf::new(),1355 bundle_dirs: Vec::new(),1356 asset_dirs: Vec::new(),1357 blob_dir: PathBuf::new(),1358 socket_dir: None,1359 socket_host_dir: None,1360 probe_image: None,1361 blob_bound: None,1362 settle: Duration::ZERO,1363 web: inf3r_deploy::Web {1364 unix: None,1365 tcp: None,1366 },1367 auth_file: PathBuf::new(),1368 binds,1369 cache: None,1370 }1371 }1372 1373 #[test]1374 fn a_container_launch_maps_cuda_and_cdi_devices_the_same_way() {1375 let mut cuda = bind(0);1376 cuda.runtime = Runtime::Container;1377 cuda.image = Some("inf3r/example:test".into());1378 cuda.devices = vec!["cuda:1".into()];1379 let node_cuda = node(vec![cuda.clone()]);1380 let LaunchSpec::Container(cuda_spec) = launch_spec(&node_cuda, &cuda) else {1381 panic!("a container bind must produce a container launch");1382 };1383 1384 let mut cdi = cuda.clone();1385 cdi.devices = vec!["nvidia.com/gpu=1".into()];1386 let node_cdi = node(vec![cdi.clone()]);1387 let LaunchSpec::Container(cdi_spec) = launch_spec(&node_cdi, &cdi) else {1388 panic!("a CDI bind must produce a container launch");1389 };1390 assert_eq!(cuda_spec.devices, vec!["nvidia.com/gpu=1"]);1391 assert_eq!(cuda_spec.devices, cdi_spec.devices);1392 }1393 1394 #[test]1395 fn a_container_launch_names_the_bundle_root_inside_the_image() {1396 let mut container = bind(0);1397 container.runtime = Runtime::Container;1398 container.image = Some("inf3r/example:test".into());1399 container.devices = vec!["cpu:0".into()];1400 let node = node(vec![container.clone()]);1401 let LaunchSpec::Container(spec) = launch_spec(&node, &container) else {1402 panic!("a container bind must produce a container launch");1403 };1404 assert!(1405 spec.env.iter().any(|(key, value)| {1406 key == inf3r_container::BUNDLE_DIR_ENV && value == "/opt/inf3r/plugins/example/cpu"1407 }),1408 "{:?}",1409 spec.env1410 );1411 }1412 1413 #[test]1414 fn the_probe_sees_every_gpu_so_cdi_visibility_keeps_the_host_index() {1415 let mut first = bind(50);1416 first.devices = vec!["cuda:0".into()];1417 let mut second = bind(50);1418 second.devices = vec!["cuda:1".into()];1419 assert_eq!(1420 cdi_devices(&node(vec![first, second])),1421 vec!["nvidia.com/gpu=all"]1422 );1423 let mut cpu = bind(50);1424 cpu.devices = vec!["cpu:0".into()];1425 assert!(cdi_devices(&node(vec![cpu])).is_empty());1426 }1427 1428 fn host(bytes: u64) -> Host {1429 Host {1430 arch: std::env::consts::ARCH.into(),1431 driver: Some("test".into()),1432 cuda: Some("13.0".into()),1433 gpus: vec![Gpu {1434 id: "cuda:0".into(),1435 name: "test".into(),1436 bus: "0000:00:00.0".into(),1437 bytes: Some(bytes),1438 free_bytes: Some(bytes),1439 compute: Some("sm00".into()),1440 }],1441 sonames: BTreeSet::new(),1442 }1443 }1444 1445 #[test]1446 fn a_gpu_capacity_comes_from_the_probe_not_from_the_bind() {1447 let core = Core::new();1448 let wants = declare_devices(&core, &host(200), &bind(50), &catalogue(100), None);1449 assert_eq!(wants["cuda:0"], 100);1450 assert_eq!(core.residency().total("cuda:0"), Some(200));1451 let held = core.residency().reserve(&wants).expect("200 bytes fit");1452 core.residency().release(held);1453 }1454 1455 #[test]1456 fn a_device_without_a_probe_falls_back_to_the_declared_capacity() {1457 let mut host = host(0);1458 host.gpus[0].bytes = None;1459 let core = Core::new();1460 declare_devices(&core, &host, &bind(50), &catalogue(100), None);1461 assert_eq!(core.residency().total("cuda:0"), Some(50));1462 }1463 1464 #[test]1465 fn the_profile_check_uses_the_bind_devices_not_every_card() {1466 let root = std::env::temp_dir().join(format!("inf3r-profile-call-{}", std::process::id()));1467 let _ = std::fs::remove_dir_all(&root);1468 let bundle = root.join("demo/cuda");1469 std::fs::create_dir_all(&bundle).expect("a bundle directory");1470 std::fs::write(1471 bundle.join("target.toml"),1472 format!(1473 "[target]\nname = \"one\"\nbackend = \"cuda\"\narch = [\"{}\"]\ncompute = \"sm00\"\ndevices = 1\nvram_mb = [1024]\n",1474 std::env::consts::ARCH1475 ),1476 )1477 .expect("a target profile");1478 let node = Node {1479 host: "test".into(),1480 bin_dir: PathBuf::new(),1481 bundle_dirs: vec![root.clone()],1482 asset_dirs: Vec::new(),1483 blob_dir: PathBuf::new(),1484 socket_dir: None,1485 socket_host_dir: None,1486 probe_image: None,1487 blob_bound: None,1488 settle: Duration::ZERO,1489 web: inf3r_deploy::Web {1490 unix: None,1491 tcp: None,1492 },1493 auth_file: PathBuf::new(),1494 binds: Vec::new(),1495 cache: None,1496 };1497 let mut mixed = host(12 * MB * 1024);1498 mixed.gpus[0].compute = Some("sm02".into());1499 mixed.gpus.push(Gpu {1500 id: "cuda:1".into(),1501 name: "test".into(),1502 bus: "0000:01:00.0".into(),1503 bytes: Some(12 * MB * 1024),1504 free_bytes: Some(12 * MB * 1024),1505 compute: Some("sm00".into()),1506 });1507 1508 assert!(ensure_profile(&node, "demo/cuda", &["cuda:1".to_string()], &mixed).is_ok());1509 let why = ensure_profile(&node, "demo/cuda", &["cuda:0".to_string()], &mixed)1510 .expect_err("the second card does not meet the profile");1511 assert!(why.contains("compute"), "{why}");1512 let _ = std::fs::remove_dir_all(&root);1513 }1514 }