diff --git a/crates/deploy/src/app.rs b/crates/deploy/src/app.rs index 33699743..f4960762 100644 --- a/crates/deploy/src/app.rs +++ b/crates/deploy/src/app.rs @@ -301,6 +301,7 @@ pub fn summary_json(ctx: &Context, config: &crate::config::RunConfig) -> Value { "ram_total_bytes": ctx.facts.memory.total, "ram_available_at_start_bytes": ctx.facts.memory.available, "service": ctx.mode.label(), + "expert_tier": crate::expert_profile::tier_report(config, &ctx.opts.dirs.assets), "logs": ctx.paths.logs().display().to_string(), "state": ctx.opts.dirs.state.display().to_string(), "assets": ctx.opts.dirs.assets.display().to_string(), @@ -358,6 +359,7 @@ pub fn summary(ctx: &Context, config: &crate::config::RunConfig) { gib(ctx.facts.memory.total), gib(ctx.facts.memory.available) )); + text.push_str(&format!(" expert {}\n", crate::expert_profile::tier_report(config, &ctx.opts.dirs.assets).line())); text.push_str(&format!(" service {}\n", ctx.mode.label())); if ctx.mode == Mode::Systemd(UnitScopeTag::User) { text.push_str(" a user unit runs while you have a session; `loginctl enable-linger $USER` starts it at boot @@ -411,6 +413,9 @@ async fn status(opts: UpOptions) -> i32 { .ok() .and_then(|t| serde_json::from_str(&t).ok()); let ready = steps::probe_ready_at(&paths, &api).await; + let expert_tier = crate::config::RunConfig::read(&paths.run_config()) + .ok() + .map(|config| crate::expert_profile::tier_report(&config, &config.dirs().assets)); let gateway = if ready { steps::fetch_status(&paths, &api).await } else { None }; let unit = match installed_scope(&paths) { Some(scope) => { @@ -433,6 +438,7 @@ async fn status(opts: UpOptions) -> i32 { unit.map(|state| (paths.unit_name().to_owned(), state)), status, gateway.as_ref(), + expert_tier.as_ref(), &paths.run_dir().display().to_string(), ) } @@ -444,6 +450,7 @@ pub fn print_status( unit: Option<(String, String)>, supervisor: Option, gateway: Option<&Value>, + expert_tier: Option<&crate::expert_profile::TierReport>, run_dir: &str, ) -> i32 { let machine = gateway.map(|g| g["machine"].clone()).filter(Value::is_object); @@ -452,7 +459,7 @@ pub fn print_status( "{}", serde_json::to_string_pretty( &json!({"ready": ready, "unit": unit.as_ref().map(|(_, state)| state), "supervisor": supervisor, "machine": machine, - "prefix_cache": gateway.map(|g| g["prefix_cache"].clone())}) + "prefix_cache": gateway.map(|g| g["prefix_cache"].clone()), "expert_tier": expert_tier}) ) .expect("serializable") ); @@ -476,6 +483,9 @@ pub fn print_status( ), None => println!("supervisor: no status file in {run_dir} (never started?)"), } + if let Some(tier) = expert_tier { + println!("{}", tier.line()); + } if let Some(machine) = &machine { print!("{}", render_machine(machine)); } else if ready { @@ -780,6 +790,10 @@ async fn verify(opts: UpOptions) -> i32 { ); return 2; }; + // The expert tier's table is 192 KiB: checked first, loudly, because losing it is a silent large slowdown. + let tier = crate::expert_profile::tier_report(&config, &paths.dirs.assets); + say(&tier.line()); + let tier_failed = !tier.on && !tier.opted_out && config.profile.expert_profile.is_some(); let started = std::time::Instant::now(); say( "hashing both shards (and the archive, when it is a file) in full, in parallel; this renews the stamps", @@ -853,6 +867,10 @@ async fn verify(opts: UpOptions) -> i32 { code = 1; } } + if tier_failed { + eprintln!("leleka: the expert profile is missing or does not match its pinned digest; rerun `leleka up` (or pass --no-expert-tier to accept the slower decode)"); + code = 1; + } say(&format!( "verification {} in {:.1}s", if code == 0 { "passed" } else { "FAILED" }, diff --git a/crates/deploy/src/cli.rs b/crates/deploy/src/cli.rs index eb002bba..3deab742 100644 --- a/crates/deploy/src/cli.rs +++ b/crates/deploy/src/cli.rs @@ -46,6 +46,10 @@ UP / PREFLIGHT OPTIONS strict re-derivation (hours-scale); the engine still checks its SHA-256 and every CRC against the pinned digest at each load --mtp-pack PATH import the MTP pack (directory or .tar/.tar.gz of data/mtp-rt) into the assets + --expert-profile-file PATH offline: install this copy of the upstream data/expert-profile.bin (the ranked VRAM + expert tier; sha256 8f59b4aa...388975baf is checked). Without it `up` downloads the + file from its pinned upstream commit and fails closed on any other digest + --no-expert-tier run without the ranked VRAM expert tier (much slower decode); status and verify say OFF --cublas-dir DIR use this CUDA 12 cuBLAS directory instead of searching / downloading --no-install-cublas fail instead of downloading cuBLAS 12.9.1.4 --timeout-s N wait this long for readiness (default 3600) @@ -113,6 +117,10 @@ pub struct UpOptions { /// Accept an existing archive of the pinned length without the strict F32 re-derivation. pub trust_archive: bool, pub mtp_pack: Option, + /// `--expert-profile-file`: install this file as the expert profile instead of downloading it. + pub expert_profile_file: Option, + /// `--no-expert-tier`: the explicit opt-out of the ranked VRAM expert tier. + pub no_expert_tier: bool, pub cublas_dir: Option, pub install_cublas: bool, pub timeout_s: u64, @@ -198,6 +206,8 @@ const UP_FLAGS: &[(&str, bool)] = &[ ("--reverify", false), ("--trust-archive", false), ("--mtp-pack", true), + ("--expert-profile-file", true), + ("--no-expert-tier", false), ("--cublas-dir", true), ("--no-install-cublas", false), ("--timeout-s", true), @@ -382,6 +392,10 @@ fn up_options(args: &[String], env: &Environment) -> Result { { return Err("--cublas-dir must be an absolute path".into()); } + let expert_profile_file = text(&flags, "--expert-profile-file").map(PathBuf::from); + if expert_profile_file.is_some() && flags.contains_key("--no-expert-tier") { + return Err("--expert-profile-file and --no-expert-tier contradict each other".into()); + } Ok(UpOptions { dry_run: flags.contains_key("--dry-run"), json: flags.contains_key("--json"), @@ -406,6 +420,8 @@ fn up_options(args: &[String], env: &Environment) -> Result { reverify: flags.contains_key("--reverify"), trust_archive: flags.contains_key("--trust-archive"), mtp_pack: text(&flags, "--mtp-pack").map(PathBuf::from), + expert_profile_file, + no_expert_tier: flags.contains_key("--no-expert-tier"), cublas_dir, install_cublas: !flags.contains_key("--no-install-cublas"), timeout_s: { @@ -596,6 +612,22 @@ mod tests { assert_eq!(options.timeout_s, 3600); } + #[test] + fn the_expert_profile_flags_parse_and_exclude_each_other() { + let Command::Up(options) = parse_as(false, &["up", "--expert-profile-file", "/mnt/usb/expert-profile.bin"]).unwrap() else { + panic!() + }; + assert_eq!(options.expert_profile_file, Some(PathBuf::from("/mnt/usb/expert-profile.bin"))); + assert!(!options.no_expert_tier); + let Command::Up(options) = parse_as(false, &["up", "--no-expert-tier"]).unwrap() else { panic!() }; + assert!(options.no_expert_tier && options.expert_profile_file.is_none()); + let Command::Up(options) = parse_as(false, &["up"]).unwrap() else { panic!() }; + assert!(!options.no_expert_tier && options.expert_profile_file.is_none()); + let error = parse_as(false, &["up", "--no-expert-tier", "--expert-profile-file", "/x"]).unwrap_err(); + assert!(error.contains("contradict"), "{error}"); + assert!(parse_as(false, &["up", "--no-expert-tier=1"]).is_err()); + } + #[test] fn flags_accept_both_forms_and_reject_mistakes() { let Command::Up(options) = parse_as( diff --git a/crates/deploy/src/config.rs b/crates/deploy/src/config.rs index 21c536c4..17f1761a 100644 --- a/crates/deploy/src/config.rs +++ b/crates/deploy/src/config.rs @@ -61,12 +61,20 @@ pub struct RunConfig { /// (`docs/deploy.md`, "Fast restarts"). `leleka verify` hashes everything and renews the stamps. #[serde(default = "default_true")] pub verify_stamps: bool, + /// `false` only after `leleka up --no-expert-tier`: the ranked VRAM expert tier is switched off on purpose. It is written + /// only when `false`, so configurations of builds without the flag stay byte-identical (`expert_profile.rs`). + #[serde(default = "default_true", skip_serializing_if = "is_true")] + pub expert_tier: bool, } fn default_true() -> bool { true } +fn is_true(value: &bool) -> bool { + *value +} + /// How the engine receives the archive on its command line. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum KarArg { @@ -105,6 +113,7 @@ impl RunConfig { stable_after_s: 600, }, verify_stamps: true, + expert_tier: true, } } diff --git a/crates/deploy/src/doctor.rs b/crates/deploy/src/doctor.rs index 06b1a12c..43a9f566 100644 --- a/crates/deploy/src/doctor.rs +++ b/crates/deploy/src/doctor.rs @@ -56,9 +56,10 @@ pub fn volume_missing(paths: &Paths) -> Vec { missing } -/// The expert profile is optional (the engine runs without the ranked VRAM tier, slower). +/// The pinned expert profile is at `data/expert-profile.bin` (the engine runs without the ranked VRAM tier otherwise, much slower). pub fn expert_profile_present(paths: &Paths) -> bool { - paths.dirs.assets.join("data").join("expert-profile.bin").is_file() + use crate::expert_profile::{FileState, PINNED_SHA256, file_state}; + file_state(&paths.dirs.assets.join("data").join("expert-profile.bin"), PINNED_SHA256) == FileState::Valid } /// Everything `advise` looks at. diff --git a/crates/deploy/src/expert_profile.rs b/crates/deploy/src/expert_profile.rs new file mode 100644 index 00000000..7886ba84 --- /dev/null +++ b/crates/deploy/src/expert_profile.rs @@ -0,0 +1,776 @@ +//! The ranked expert-usage table (`data/expert-profile.bin`): provisioning, verification and the "expert tier ON/OFF" report. +//! +//! What the file is, and why it is fetched rather than generated +//! ------------------------------------------------------------- +//! It is Strata's `STRP` v1 table: all 48 x 512 = 24,576 (layer, expert) pairs of the Qwen3.8-Flash-Next model, ranked by how +//! often a calibration workload routed to them, plus the inverse slot table (24 + 4 x 24,576 + 4 x 48 x 512 = 196,632 bytes). +//! `--expert-cache auto` fills the VRAM expert slots in that order (`engine/strata/tools/make_profile.py`, header comment). +//! +//! * It cannot be derived from the model weights: it is a routing statistic. Producing one means running the model on +//! calibration prompts with `--dump-routing` and ranking the routed experts (`make_profile.py`, Python, offline). The +//! upstream calibration set is not published; the file is a binary that upstream ships in its repository. +//! * A locally generated table is a different table. Placement of experts between the GPU and the CPU changes the rounding of +//! the routed experts, so greedy output moves with it: the measured control (`docs/original-serve.md`, "placeholder-profile +//! placement against upstream placement") is 0/6 identical outputs, 43 argmax flips in 1,660 rows (2.59 %), VRAM share 48 % +//! against 90 %. Any other table needs its own quality gate; none exists, so the product pins the upstream bytes. +//! * Upstream publishes it at `data/expert-profile.bin` in https://github.com/Niko1221/Strata (MIT, `engine/strata/LICENSE`), +//! byte-identical at the pin `41cf05a0` and at the older pin `d9ab8435` (`docs/upstream.md` lists it as left out of the import +//! because `*.bin` is git-ignored). Commit-pinned raw URLs are immutable content; the SHA-256 is what is trusted, not the URL. +//! +//! Policy: the expert tier is never silently lost. `leleka up` provisions the file (download or `--expert-profile-file`), +//! checks the pinned digest, installs it atomically and fails closed; `--no-expert-tier` is the explicit opt-out. `status`, +//! `verify`, the ready summary and the supervisor log all say ON with the digest, or OFF with the reason. +use crate::{config::RunConfig, profile::Profile}; +use serde::Serialize; +use sha2::{Digest, Sha256}; +use std::{ + collections::BTreeMap, + path::{Path, PathBuf}, + time::{SystemTime, UNIX_EPOCH}, +}; + +/// SHA-256 of the upstream `data/expert-profile.bin` (the only table that has been quality-measured). +pub const PINNED_SHA256: &str = "8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf"; +/// Its length: 24-byte header, 24,576 (layer, expert) u16 pairs, 48 x 512 i32 slot table. +pub const PINNED_BYTES: u64 = 196_632; +/// Nothing larger is hashed or accepted (the pinned file is 192 KiB). +pub const MAX_BYTES: u64 = 1 << 20; +/// The Strata commit the sources below are pinned to (`docs/upstream.md`). +pub const UPSTREAM_COMMIT: &str = "41cf05a06a25dd29103b7b27a2279a3f60c21876"; +/// Download sources, tried in order. All serve the same bytes; each result is checked against [`PINNED_SHA256`]. +pub const SOURCES: [&str; 3] = [ + "https://raw.githubusercontent.com/Niko1221/Strata/41cf05a06a25dd29103b7b27a2279a3f60c21876/data/expert-profile.bin", + "https://cdn.jsdelivr.net/gh/Niko1221/Strata@41cf05a06a25dd29103b7b27a2279a3f60c21876/data/expert-profile.bin", + // The first import's pin; upstream rewrote its history afterwards, so this one may disappear. + "https://raw.githubusercontent.com/Niko1221/Strata/d9ab8435f654c368c586340d490915f6addf56a3/data/expert-profile.bin", +]; +/// The engine switches `up` sets when the tier is on. +pub const PROFILE_ENV: &str = "LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE"; +pub const SLOTS_ENV: &str = "LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS"; + +/// `8f59b4aa...388975baf`, the form the docs use. +pub fn short_digest(digest: &str) -> String { + if digest.len() > 20 { + format!("{}...{}", &digest[..8], &digest[digest.len() - 9..]) + } else { + digest.to_owned() + } +} + +/// The digest the profile requires: its own `expert_profile_sha256`, else the pinned upstream one. +pub fn expected_digest(profile: &Profile) -> &str { + profile + .expert_profile_sha256 + .as_deref() + .unwrap_or(PINNED_SHA256) +} + +pub fn sha256_hex(bytes: &[u8]) -> String { + hex::encode(Sha256::digest(bytes)) +} + +/// What is at `path`: nothing, a file with the expected digest, or something else (with the digest it has). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum FileState { + Absent, + Valid, + WrongDigest { actual: String }, +} + +pub fn file_state(path: &Path, expected: &str) -> FileState { + use std::io::Read; + let Ok(file) = std::fs::File::open(path) else { + return FileState::Absent; + }; + let mut bytes = Vec::new(); + // One byte over the limit tells "too large" without reading a model-sized file into memory. + if file.take(MAX_BYTES + 1).read_to_end(&mut bytes).is_err() { + return FileState::Absent; + } + if bytes.len() as u64 > MAX_BYTES { + return FileState::WrongDigest { + actual: format!("(larger than {MAX_BYTES} bytes)"), + }; + } + let actual = sha256_hex(&bytes); + if actual == expected { + FileState::Valid + } else { + FileState::WrongDigest { actual } + } +} + +// --------------------------------------------------------------------------------------------------------------- +// provisioning + +/// What `provision` did. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Outcome { + /// The file was already there with the expected digest; nothing was touched. + AlreadyPresent, + Installed { + /// Where the bytes came from (a URL or a local path). + origin: String, + /// A different file that was in the way, moved (never deleted) to this name. + moved_aside: Option, + }, +} + +pub struct Request<'a> { + pub dest: &'a Path, + pub expected: &'a str, + /// `--expert-profile-file`: install this file instead of downloading (the offline route). + pub local: Option<&'a Path>, + /// Download sources in order (empty: no download is attempted). + pub sources: &'a [&'a str], +} + +fn with_suffix(path: &Path, suffix: &str) -> PathBuf { + let mut name = path.as_os_str().to_owned(); + name.push(suffix); + PathBuf::from(name) +} + +/// Verify the staged `part` file and move it into place atomically; a file that was in the way is renamed, not deleted. +fn commit(part: &Path, dest: &Path, expected: &str) -> Result, String> { + match file_state(part, expected) { + FileState::Valid => {} + FileState::Absent => return Err(format!("{} was not written", part.display())), + FileState::WrongDigest { actual } => { + let _ = std::fs::remove_file(part); + return Err(format!("sha256 {actual} is not the expected {expected}")); + } + } + let mut moved = None; + if dest.exists() { + let stamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); + let aside = with_suffix(dest, &format!(".rejected-{stamp}")); + std::fs::rename(dest, &aside) + .map_err(|e| format!("cannot move {} aside: {e}", dest.display()))?; + moved = Some(aside); + } + // Same directory, so the rename is atomic: the engine never sees a half-written table. + std::fs::rename(part, dest).map_err(|e| format!("cannot install {}: {e}", dest.display()))?; + Ok(moved) +} + +/// Put a file with the expected digest at `request.dest`, or fail with a message that says what to do. +/// +/// `fetch(url, part)` downloads one URL to `part` (the caller picks the tool; tests pass a fake). A source that fails or +/// returns another digest is skipped; when none works the error names every failure and the two ways out +/// (`--expert-profile-file PATH`, `--no-expert-tier`). Nothing unverified is ever left at `dest`. +pub fn provision( + request: &Request, + fetch: &mut dyn FnMut(&str, &Path) -> Result<(), String>, +) -> Result { + if file_state(request.dest, request.expected) == FileState::Valid { + return Ok(Outcome::AlreadyPresent); + } + if let Some(parent) = request.dest.parent() { + std::fs::create_dir_all(parent) + .map_err(|e| format!("cannot create {}: {e}", parent.display()))?; + } + let part = with_suffix(request.dest, ".part"); + let _ = std::fs::remove_file(&part); + if let Some(local) = request.local { + let size = std::fs::metadata(local) + .map_err(|e| format!("--expert-profile-file {}: {e}", local.display()))? + .len(); + if size > MAX_BYTES { + return Err(format!( + "--expert-profile-file {} has {size} bytes; the expert profile is {PINNED_BYTES}", + local.display() + )); + } + std::fs::copy(local, &part).map_err(|e| format!("cannot copy {}: {e}", local.display()))?; + let moved_aside = commit(&part, request.dest, request.expected) + .map_err(|e| format!("--expert-profile-file {}: {e}; only the pinned upstream table is accepted (a table of your own needs a profile with its own expert_profile_sha256 and a quality gate)", local.display()))?; + return Ok(Outcome::Installed { + origin: local.display().to_string(), + moved_aside, + }); + } + if request.sources.is_empty() { + return Err(format!( + "no download source is known for sha256 {}; copy the file to {} or pass --expert-profile-file PATH", + request.expected, + request.dest.display() + )); + } + let mut failures = Vec::new(); + for url in request.sources { + let result = fetch(url, &part).and_then(|()| commit(&part, request.dest, request.expected)); + match result { + Ok(moved_aside) => { + return Ok(Outcome::Installed { + origin: (*url).to_owned(), + moved_aside, + }); + } + Err(message) => { + let _ = std::fs::remove_file(&part); + failures.push(format!("{url}: {message}")); + } + } + } + Err(format!( + "the expert profile (sha256 {}) could not be obtained:\n {}\nnothing was installed. Offline or behind a proxy: download {} on another machine, copy it here and pass --expert-profile-file PATH; \ + to run without the ranked VRAM expert tier (slower), pass --no-expert-tier", + short_digest(request.expected), + failures.join("\n "), + request.sources[0] + )) +} + +// --------------------------------------------------------------------------------------------------------------- +// the ON/OFF report + +/// Whether the VRAM expert tier is in force for a configuration, and why not when it is not. Never silent: every +/// consumer (`status`, `verify`, the ready summary, the supervisor log) prints [`TierReport::line`]. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct TierReport { + pub on: bool, + /// The deliberate opt-out (`--no-expert-tier`), as opposed to a missing or wrong file. + pub opted_out: bool, + pub path: Option, + /// SHA-256 of the file on disk (when there is one). + pub sha256: Option, + pub expected_sha256: Option, + pub reason: String, +} + +impl TierReport { + /// One line for the operator; OFF lines start with a capitalised warning so they stand out in a log. + pub fn line(&self) -> String { + if self.on { + format!( + "expert tier ON ({} sha256 {}{})", + self.path.as_deref().unwrap_or("?"), + self.sha256.as_deref().map_or("?".to_owned(), short_digest), + if self.sha256.as_deref() == Some(PINNED_SHA256) { + ", the pinned upstream table" + } else { + ", this profile's own digest" + } + ) + } else { + format!( + "WARNING expert tier OFF: {} (ranked VRAM expert slots are not used; decode is much slower)", + self.reason + ) + } + } +} + +impl FileState { + /// From a digest observed elsewhere (the WSL bridge runs `sha256sum` in the distribution): `None` = no such file. + pub fn from_digest(observed: Option<&str>, expected: &str) -> FileState { + match observed { + None => FileState::Absent, + Some(actual) if actual == expected => FileState::Valid, + Some(actual) => FileState::WrongDigest { + actual: actual.to_owned(), + }, + } + } +} + +/// The tier state of `config`, judged from the files on disk (a 192 KiB hash; no engine, no GPU). +pub fn tier_report(config: &RunConfig, assets: &Path) -> TierReport { + let expected = expected_digest(&config.profile).to_owned(); + match &config.profile.expert_profile { + Some(relative) => { + let path = assets.join(relative); + tier_report_with(config, &path.display().to_string(), || { + file_state(&path, &expected) + }) + } + None => tier_report_with(config, "", || FileState::Absent), + } +} + +/// [`tier_report`] with the file's state supplied by the caller (`shown` is the path to print; `state` is only called when needed). +pub fn tier_report_with( + config: &RunConfig, + shown: &str, + state: impl FnOnce() -> FileState, +) -> TierReport { + let profile = &config.profile; + let expected = expected_digest(profile).to_owned(); + let off = |reason: String, opted_out: bool, path: Option, sha256: Option| { + TierReport { + on: false, + opted_out, + path, + sha256, + expected_sha256: Some(expected.clone()), + reason, + } + }; + if profile.expert_profile.is_none() { + return TierReport { + expected_sha256: None, + ..off( + format!("profile {} names no expert profile", profile.name), + false, + None, + None, + ) + }; + } + let shown = shown.to_owned(); + if !config.expert_tier { + return off( + "--no-expert-tier was given to `leleka up` (explicit opt-out)".into(), + true, + Some(shown), + None, + ); + } + match state() { + FileState::Absent => off( + format!( + "{shown} is missing; run `leleka up` (it fetches the pinned table) or pass --expert-profile-file PATH" + ), + false, + Some(shown), + None, + ), + FileState::WrongDigest { actual } => off( + format!( + "{shown} has sha256 {actual}, not the pinned {}; it is not used", + short_digest(&expected) + ), + false, + Some(shown), + Some(actual), + ), + FileState::Valid => { + if config.engine_env.contains_key(PROFILE_ENV) { + TierReport { + on: true, + opted_out: false, + path: Some(shown), + sha256: Some(expected.clone()), + expected_sha256: Some(expected), + reason: String::new(), + } + } else { + off( + "the file is valid but leleka.json was written without it; rerun `leleka up`" + .into(), + false, + Some(shown), + Some(expected.clone()), + ) + } + } + } +} + +/// The engine environment for a start, and the tier report it was built from: the configured environment minus the +/// expert-tier switches when the table is not valid. `up` only sets them for a verified file; this keeps the engine from +/// reading a file that went missing or changed since, and the report is what the supervisor logs. +pub fn start_environment( + config: &RunConfig, + assets: &Path, +) -> (BTreeMap, TierReport) { + let mut env = config.engine_environment(); + let report = tier_report(config, assets); + if !report.on { + env.remove(PROFILE_ENV); + env.remove(SLOTS_ENV); + } + (env, report) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::RefCell; + + fn temp(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "leleka-expert-profile-{}-{name}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + /// A small stand-in for the table; the real digest is pinned, tests pin the digest of this fixture instead. + const FIXTURE: &[u8] = b"STRP\x01\x00\x00\x00 a small fixture, not a routing table"; + + fn fixture_digest() -> String { + sha256_hex(FIXTURE) + } + + #[test] + fn the_pinned_numbers_are_consistent() { + assert_eq!(PINNED_SHA256.len(), 64); + assert_eq!(PINNED_BYTES, 24 + 4 * 24_576 + 4 * 48 * 512); + assert!(SOURCES.iter().all(|url| url.starts_with("https://"))); + assert!(SOURCES[0].contains(UPSTREAM_COMMIT) && SOURCES[1].contains(UPSTREAM_COMMIT)); + assert_eq!(short_digest(PINNED_SHA256), "8f59b4aa...388975baf"); + assert_eq!(crate::plan::EXPERT_PROFILE_SHA256, PINNED_SHA256); + } + + #[test] + fn a_file_is_absent_valid_or_wrong() { + let dir = temp("state"); + let path = dir.join("p.bin"); + assert_eq!(file_state(&path, &fixture_digest()), FileState::Absent); + std::fs::write(&path, FIXTURE).unwrap(); + assert_eq!(file_state(&path, &fixture_digest()), FileState::Valid); + assert!( + matches!(file_state(&path, PINNED_SHA256), FileState::WrongDigest { actual } if actual == fixture_digest()) + ); + std::fs::write(&path, vec![0u8; (MAX_BYTES + 5) as usize]).unwrap(); + assert!(matches!( + file_state(&path, PINNED_SHA256), + FileState::WrongDigest { .. } + )); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn a_download_is_verified_then_installed_and_a_present_file_is_left_alone() { + let dir = temp("download"); + let dest = dir.join("data").join("expert-profile.bin"); + let calls = RefCell::new(Vec::new()); + let mut fetch = |url: &str, part: &Path| { + calls.borrow_mut().push(url.to_owned()); + std::fs::write(part, FIXTURE).map_err(|e| e.to_string()) + }; + let digest = fixture_digest(); + let request = Request { + dest: &dest, + expected: &digest, + local: None, + sources: &["https://one.test/p.bin", "https://two.test/p.bin"], + }; + let outcome = provision(&request, &mut fetch).unwrap(); + assert_eq!( + outcome, + Outcome::Installed { + origin: "https://one.test/p.bin".into(), + moved_aside: None + } + ); + assert_eq!(std::fs::read(&dest).unwrap(), FIXTURE); + assert!( + !with_suffix(&dest, ".part").exists(), + "the staging file is gone" + ); + // Second run: nothing is fetched. + assert_eq!( + provision(&request, &mut fetch).unwrap(), + Outcome::AlreadyPresent + ); + assert_eq!(calls.borrow().len(), 1); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn a_digest_mismatch_fails_closed_and_installs_nothing() { + let dir = temp("mismatch"); + let dest = dir.join("expert-profile.bin"); + let mut fetch = |_: &str, part: &Path| { + std::fs::write(part, b"an error page, not the table").map_err(|e| e.to_string()) + }; + let digest = fixture_digest(); + let request = Request { + dest: &dest, + expected: &digest, + local: None, + sources: &["https://one.test/p.bin", "https://two.test/p.bin"], + }; + let error = provision(&request, &mut fetch).unwrap_err(); + assert!( + error.contains("one.test") + && error.contains("two.test") + && error.contains("is not the expected"), + "{error}" + ); + assert!( + error.contains("--expert-profile-file") && error.contains("--no-expert-tier"), + "{error}" + ); + assert!(!dest.exists() && !with_suffix(&dest, ".part").exists()); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn the_next_source_is_tried_when_one_fails() { + let dir = temp("fallback"); + let dest = dir.join("expert-profile.bin"); + let mut fetch = |url: &str, part: &Path| { + if url.contains("down") { + Err("curl exited with 22".to_owned()) + } else { + std::fs::write(part, FIXTURE).map_err(|e| e.to_string()) + } + }; + let digest = fixture_digest(); + let request = Request { + dest: &dest, + expected: &digest, + local: None, + sources: &["https://down.test/p.bin", "https://up.test/p.bin"], + }; + assert_eq!( + provision(&request, &mut fetch).unwrap(), + Outcome::Installed { + origin: "https://up.test/p.bin".into(), + moved_aside: None + } + ); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn a_local_file_is_installed_offline_and_a_wrong_one_is_refused() { + let dir = temp("local"); + let dest = dir.join("data").join("expert-profile.bin"); + let good = dir.join("good.bin"); + let bad = dir.join("bad.bin"); + std::fs::write(&good, FIXTURE).unwrap(); + std::fs::write(&bad, b"my own learned table").unwrap(); + let digest = fixture_digest(); + let mut never = |_: &str, _: &Path| -> Result<(), String> { + panic!("offline: no download may be attempted") + }; + let refused = provision( + &Request { + dest: &dest, + expected: &digest, + local: Some(&bad), + sources: &["https://x.test/p"], + }, + &mut never, + ) + .unwrap_err(); + assert!( + refused.contains("only the pinned upstream table"), + "{refused}" + ); + assert!(!dest.exists()); + let outcome = provision( + &Request { + dest: &dest, + expected: &digest, + local: Some(&good), + sources: &["https://x.test/p"], + }, + &mut never, + ) + .unwrap(); + assert!(matches!( + outcome, + Outcome::Installed { + moved_aside: None, + .. + } + )); + assert_eq!(std::fs::read(&dest).unwrap(), FIXTURE); + let missing = provision( + &Request { + dest: &dir.join("other.bin"), + expected: &digest, + local: Some(&dir.join("nope.bin")), + sources: &[], + }, + &mut never, + ) + .unwrap_err(); + assert!(missing.contains("--expert-profile-file"), "{missing}"); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn a_wrong_file_in_the_way_is_moved_aside_never_deleted() { + let dir = temp("aside"); + let dest = dir.join("expert-profile.bin"); + std::fs::write(&dest, b"learned by hand").unwrap(); + let mut fetch = + |_: &str, part: &Path| std::fs::write(part, FIXTURE).map_err(|e| e.to_string()); + let digest = fixture_digest(); + let outcome = provision( + &Request { + dest: &dest, + expected: &digest, + local: None, + sources: &["https://one.test/p.bin"], + }, + &mut fetch, + ) + .unwrap(); + let Outcome::Installed { + moved_aside: Some(aside), + .. + } = outcome + else { + panic!("{outcome:?}") + }; + assert_eq!(std::fs::read(&aside).unwrap(), b"learned by hand"); + assert_eq!(std::fs::read(&dest).unwrap(), FIXTURE); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn a_custom_digest_without_sources_asks_for_the_file() { + let dir = temp("custom"); + let mut fetch = |_: &str, _: &Path| -> Result<(), String> { panic!("no sources") }; + let error = provision( + &Request { + dest: &dir.join("p.bin"), + expected: &fixture_digest(), + local: None, + sources: &[], + }, + &mut fetch, + ) + .unwrap_err(); + assert!(error.contains("no download source"), "{error}"); + let _ = std::fs::remove_dir_all(dir); + } + + fn config(assets: &Path, expert_tier: bool, with_env: bool) -> RunConfig { + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + profile.expert_profile_sha256 = Some(fixture_digest()); + let dirs = crate::layout::Dirs { + prefix: assets.join("p"), + state: assets.join("s"), + assets: assets.to_path_buf(), + }; + let ports = crate::config::Ports { + api: "127.0.0.1:8081".into(), + engine: "127.0.0.1:18766".into(), + daemon: "127.0.0.1:18080".into(), + }; + let mut env = BTreeMap::new(); + if with_env { + env.insert( + PROFILE_ENV.to_owned(), + assets.join("data/expert-profile.bin").display().to_string(), + ); + env.insert(SLOTS_ENV.to_owned(), "auto".to_owned()); + } + let mut config = RunConfig::new(&dirs, ports, 0, profile, env); + config.expert_tier = expert_tier; + config + } + + #[test] + fn the_report_says_on_with_the_digest_or_off_with_the_reason() { + let dir = temp("report"); + let path = dir.join("data").join("expert-profile.bin"); + // missing + let report = tier_report(&config(&dir, true, true), &dir); + assert!( + !report.on && !report.opted_out && report.reason.contains("is missing"), + "{report:?}" + ); + assert!( + report.line().starts_with("WARNING expert tier OFF"), + "{}", + report.line() + ); + // present and valid + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, FIXTURE).unwrap(); + let report = tier_report(&config(&dir, true, true), &dir); + assert!(report.on, "{report:?}"); + assert!( + report.line().starts_with("expert tier ON") + && report.line().contains(&short_digest(&fixture_digest())), + "{}", + report.line() + ); + // valid file but a configuration written without the switches + let report = tier_report(&config(&dir, true, false), &dir); + assert!( + !report.on && report.reason.contains("rerun `leleka up`"), + "{report:?}" + ); + // explicit opt-out + let report = tier_report(&config(&dir, false, false), &dir); + assert!( + !report.on && report.opted_out && report.reason.contains("--no-expert-tier"), + "{report:?}" + ); + // a replaced file + std::fs::write(&path, b"something else").unwrap(); + let report = tier_report(&config(&dir, true, true), &dir); + assert!( + !report.on && report.reason.contains("not the pinned") && report.sha256.is_some(), + "{report:?}" + ); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn a_digest_observed_elsewhere_gives_the_same_report() { + let dir = temp("bridge"); + let cfg = config(&dir, true, true); + let shown = "/home/me/leleka/data/expert-profile.bin"; + let digest = fixture_digest(); + assert!( + tier_report_with(&cfg, shown, || FileState::from_digest( + Some(&digest), + &digest + )) + .on + ); + let missing = tier_report_with(&cfg, shown, || FileState::from_digest(None, &digest)); + assert!(!missing.on && missing.reason.contains(shown), "{missing:?}"); + let wrong = tier_report_with(&cfg, shown, || { + FileState::from_digest(Some("00ff"), &digest) + }); + assert!(!wrong.on && wrong.sha256.as_deref() == Some("00ff")); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn a_profile_without_a_tier_reports_off_and_the_engine_never_gets_a_bad_table() { + let dir = temp("env"); + let mut no_tier = config(&dir, true, true); + no_tier.profile.expert_profile = None; + assert!(!tier_report(&no_tier, &dir).on); + // valid file: the switches pass through + let path = dir.join("data").join("expert-profile.bin"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, FIXTURE).unwrap(); + let cfg = config(&dir, true, true); + let (env, report) = start_environment(&cfg, &dir); + assert!(env.contains_key(PROFILE_ENV) && report.on); + // the file changed since `up`: the switches are dropped + std::fs::write(&path, b"changed").unwrap(); + let (env, report) = start_environment(&cfg, &dir); + assert!(!report.on && !env.contains_key(PROFILE_ENV) && !env.contains_key(SLOTS_ENV)); + let _ = std::fs::remove_dir_all(dir); + } + + /// Live check of the pinned sources (needs network and curl): `cargo test -p leleka-deploy -- --ignored pinned_sources`. + #[test] + #[ignore = "network"] + fn pinned_sources_serve_the_pinned_table() { + let dir = temp("live"); + for url in SOURCES.iter().take(2) { + let out = dir.join("p.bin"); + let status = std::process::Command::new("curl") + .args(["-fsSL", "--proto", "=https", "--max-time", "60", "-o"]) + .arg(&out) + .arg(url) + .status() + .unwrap(); + assert!(status.success(), "{url}"); + assert_eq!(file_state(&out, PINNED_SHA256), FileState::Valid, "{url}"); + assert_eq!(std::fs::metadata(&out).unwrap().len(), PINNED_BYTES); + } + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/crates/deploy/src/lib.rs b/crates/deploy/src/lib.rs index c4a13011..3621d60f 100644 --- a/crates/deploy/src/lib.rs +++ b/crates/deploy/src/lib.rs @@ -7,6 +7,7 @@ pub mod app; pub mod cli; pub mod config; pub mod doctor; +pub mod expert_profile; pub mod facts; pub mod http; pub mod layout; diff --git a/crates/deploy/src/plan.rs b/crates/deploy/src/plan.rs index f7b3187c..d0a9cabe 100644 --- a/crates/deploy/src/plan.rs +++ b/crates/deploy/src/plan.rs @@ -24,8 +24,7 @@ pub const CUBLAS_VERSION: &str = "12.9.1.4"; pub const CUBLAS_URL: &str = "https://developer.download.nvidia.com/compute/cuda/redist/libcublas/linux-x86_64/libcublas-linux-x86_64-12.9.1.4-archive.tar.xz"; pub const CUBLAS_SHA256: &str = "546addc4a9d82b8f23aa9ba9274b6bc0429a63008a31c759884ac24880796057"; pub const CUBLAS_BYTES: u64 = 933_611_504; -pub const EXPERT_PROFILE_SHA256: &str = - "8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf"; +pub const EXPERT_PROFILE_SHA256: &str = crate::expert_profile::PINNED_SHA256; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] #[serde(rename_all = "lowercase")] @@ -110,23 +109,15 @@ fn current_bin_dir() -> PathBuf { } pub fn expert_profile_state(profile: &Profile, assets: &Path) -> Option { + use crate::expert_profile::{FileState, expected_digest, file_state}; let relative = profile.expert_profile.as_ref()?; - let path = assets.join(relative); - let Ok(bytes) = std::fs::read(&path) else { - return Some(ExpertProfileState::Absent); - }; - if bytes.len() > 16 << 20 { - return Some(ExpertProfileState::WrongDigest); - } - let expected = profile - .expert_profile_sha256 - .as_deref() - .unwrap_or(EXPERT_PROFILE_SHA256); - Some(if sha256_hex(&bytes) == expected { - ExpertProfileState::Valid - } else { - ExpertProfileState::WrongDigest - }) + Some( + match file_state(&assets.join(relative), expected_digest(profile)) { + FileState::Absent => ExpertProfileState::Absent, + FileState::Valid => ExpertProfileState::Valid, + FileState::WrongDigest { .. } => ExpertProfileState::WrongDigest, + }, + ) } pub fn sha256_hex(bytes: &[u8]) -> String { @@ -144,8 +135,7 @@ pub fn service_running(paths: &Paths) -> bool { }; let pid = value.get("supervisor_pid").and_then(|v| v.as_u64()); let phase = value.get("phase").and_then(|v| v.as_str()).unwrap_or(""); - matches!(pid, Some(pid) if process_alive(pid)) - && !matches!(phase, "stopped" | "failed") + matches!(pid, Some(pid) if process_alive(pid)) && !matches!(phase, "stopped" | "failed") } #[cfg(not(windows))] @@ -231,10 +221,20 @@ pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option) -> Context state_dir: opts.dirs.state.clone(), prefix_dir: opts.dirs.prefix.clone(), // Windows never fetches or builds: the model volume is copied in (the plan blocks with the reason when it is not). - shard_bytes_missing: if opts.fetch && facts.os != "windows" { shards } else { 0 }, - kar_bytes_missing: if opts.fetch && facts.os != "windows" { kar } else { 0 }, + shard_bytes_missing: if opts.fetch && facts.os != "windows" { + shards + } else { + 0 + }, + kar_bytes_missing: if opts.fetch && facts.os != "windows" { + kar + } else { + 0 + }, install_binaries: !installed_same_dir, - may_install_cublas: opts.install_cublas && opts.cublas_dir.is_none() && facts.os != "windows", + may_install_cublas: opts.install_cublas + && opts.cublas_dir.is_none() + && facts.os != "windows", cublas_download_bytes: CUBLAS_BYTES, wants_systemd: matches!(mode, Mode::Systemd(_)), service_ports: vec![ @@ -256,23 +256,39 @@ pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option) -> Context }; let (config, report) = match &mut profile { Ok(p) => { - needs.expert_profile = expert_profile_state(p, &opts.dirs.assets); + needs.expert_profile = if opts.no_expert_tier && p.expert_profile.is_some() { + Some(ExpertProfileState::OptedOut) + } else { + expert_profile_state(p, &opts.dirs.assets) + }; let mut engine_env = BTreeMap::new(); let base_profile = p.clone(); // An inherited sealed archive is already resident: it is not part of what the engine still needs from the host. - let planned_host = if opts.kar_fd.is_some() { crate::resources::with_resident_archive(&facts) } else { facts.clone() }; + let planned_host = if opts.kar_fd.is_some() { + crate::resources::with_resident_archive(&facts) + } else { + facts.clone() + }; let resources = crate::resources::compute(&planned_host, gpu, p, opts.preset); - crate::resources::apply(&resources, p, &mut engine_env, opts.gpu_budget_gib.is_some()); + crate::resources::apply( + &resources, + p, + &mut engine_env, + opts.gpu_budget_gib.is_some(), + ); needs.resources = Some(resources); - if needs.expert_profile == Some(ExpertProfileState::Valid) + // The tier is configured whenever it is intended (any state but the explicit opt-out): a missing or wrong table is + // provisioned by the `expert-profile` step, which runs before the configuration is written and blocks `up` + // when it cannot succeed. At every start the supervisor re-checks the digest (`expert_profile::start_environment`). + if needs.expert_profile != Some(ExpertProfileState::OptedOut) && let Some(relative) = &p.expert_profile { engine_env.insert( - "LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS".to_owned(), + crate::expert_profile::SLOTS_ENV.to_owned(), "auto".to_owned(), ); engine_env.insert( - "LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE".to_owned(), + crate::expert_profile::PROFILE_ENV.to_owned(), opts.dirs.assets.join(relative).display().to_string(), ); } @@ -284,6 +300,7 @@ pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option) -> Context engine_env, ); config.preset = opts.preset; + config.expert_tier = !opts.no_expert_tier; config.base_profile = Some(base_profile); let report = evaluate(&facts, p, &needs); (Some(config), Some(report)) @@ -409,7 +426,8 @@ pub fn plan_steps(ctx: &Context, fs: &FsState) -> Vec { "host checks", pre_state, vec![if windows { - "nvidia-smi.exe, GlobalMemoryStatusEx, GetDiskFreeSpaceEx, DLL search, loopback ports".into() + "nvidia-smi.exe, GlobalMemoryStatusEx, GetDiskFreeSpaceEx, DLL search, loopback ports" + .into() } else { "nvidia-smi, /proc/meminfo, statvfs, ldconfig, memfd_create".into() }], @@ -456,6 +474,8 @@ pub fn plan_steps(ctx: &Context, fs: &FsState) -> Vec { )], )); + steps.push(expert_profile_step(ctx)); + let cublas_cmd = vec![ format!("curl -fL -C - {CUBLAS_URL} (sha256 {CUBLAS_SHA256})"), format!( @@ -508,7 +528,10 @@ pub fn plan_steps(ctx: &Context, fs: &FsState) -> Vec { let trusted = opts.trust_archive && fs.kar_present; let kar_state = if windows { if fs.kar_present { - StepState::Done(format!("{} bytes with its provenance file (the engine checks SHA-256 and CRCs at each load)", ARCHIVE_BYTES)) + StepState::Done(format!( + "{} bytes with its provenance file (the engine checks SHA-256 and CRCs at each load)", + ARCHIVE_BYTES + )) } else { StepState::Blocked(format!( "{} (pinned length {ARCHIVE_BYTES}) and its .provenance.json must already be on the model volume; the Windows tool does not build the archive (build it in WSL and copy it, see docs/windows.md)", @@ -741,12 +764,79 @@ pub fn plan_steps(ctx: &Context, fs: &FsState) -> Vec { steps } +/// The `expert-profile` step: the ranked VRAM expert tier's table is fetched (or installed from `--expert-profile-file`) and +/// verified before any large download, so that a failure costs seconds and the configuration is never written without it. +fn expert_profile_step(ctx: &Context) -> Step { + use crate::expert_profile::{ + PINNED_BYTES, PINNED_SHA256, SOURCES, expected_digest, short_digest, + }; + let id = "expert-profile"; + let title = "ranked VRAM expert profile (data/expert-profile.bin)"; + let opts = &ctx.opts; + let Ok(profile) = &ctx.profile else { + return step(id, title, StepState::Skip("no profile".into()), vec![]); + }; + let Some(relative) = &profile.expert_profile else { + return step( + id, + title, + StepState::Skip(format!("profile {} has no VRAM expert tier", profile.name)), + vec![], + ); + }; + let dest = opts.dirs.assets.join(relative); + let expected = expected_digest(profile); + let shown = short_digest(expected); + let flag_hint = "pass --expert-profile-file PATH (a copy of the upstream data/expert-profile.bin) or --no-expert-tier"; + let state = match &ctx.needs.expert_profile { + Some(ExpertProfileState::OptedOut) => StepState::Skip("--no-expert-tier: the VRAM expert tier is OFF (explicit opt-out; decode is much slower)".into()), + Some(ExpertProfileState::Valid) => StepState::Done(format!("{} has sha256 {shown}, tier ON", dest.display())), + Some(other) => { + let wrong = *other == ExpertProfileState::WrongDigest; + if let Some(file) = &opts.expert_profile_file { + StepState::Todo(format!( + "install {} (sha256 checked){}", + file.display(), + if wrong { "; the file in the way is moved aside, not deleted" } else { "" } + )) + } else if wrong { + StepState::Blocked(format!( + "{} does not have the expected sha256 {shown} and is not used. Move it aside and rerun (`up` then downloads the pinned table), or {flag_hint}. A table of your own needs a profile with its own expert_profile_sha256 and a quality gate", + dest.display() + )) + } else if !opts.fetch { + StepState::Blocked(format!("{} is missing and --no-fetch was given; {flag_hint}", dest.display())) + } else if expected != PINNED_SHA256 { + StepState::Blocked(format!("{} is missing and this profile pins another digest ({shown}), which has no download source; copy the file there or {flag_hint}", dest.display())) + } else if ctx.facts.os != "windows" && !ctx.facts.tool("curl") && !ctx.facts.tool("wget") { + StepState::Blocked(format!("{} is missing and neither curl nor wget is installed (apt install curl); {flag_hint}", dest.display())) + } else { + StepState::Todo(format!("download the {PINNED_BYTES}-byte table from the pinned upstream commit and check sha256 {shown}")) + } + } + None => StepState::Skip("no expert profile".into()), + }; + step( + id, + title, + state, + vec![format!( + "curl -fsSL --proto =https -o {}.part {} (sha256 {})", + dest.display(), + SOURCES[0], + expected + )], + ) +} + /// Both shards exist with their pinned sizes. fn windows_shards_present(paths: &Paths) -> bool { crate::profile::SHARD_BYTES .iter() .enumerate() - .all(|(index, expected)| std::fs::metadata(paths.shard(index)).is_ok_and(|m| m.len() == *expected)) + .all(|(index, expected)| { + std::fs::metadata(paths.shard(index)).is_ok_and(|m| m.len() == *expected) + }) } fn gib_text(bytes: u64) -> String { @@ -890,9 +980,22 @@ mod tests { ); } let profile = resolve(opts.profile.as_deref(), Some(&gpu)); + // A finished host by default: the pinned table is in place (tests of the other states set `needs.expert_profile`). + let expert_profile = profile + .as_ref() + .ok() + .filter(|p| p.expert_profile.is_some()) + .map(|_| { + if opts.no_expert_tier { + ExpertProfileState::OptedOut + } else { + ExpertProfileState::Valid + } + }); let needs = Needs { shard_bytes_missing: 83_617_662_656, kar_bytes_missing: ARCHIVE_BYTES * 12 / 10, + expert_profile, ..Needs::default() }; let config = profile.as_ref().ok().map(|p| { @@ -926,12 +1029,13 @@ mod tests { #[test] fn fresh_server_plans_every_step() { - let ctx = context( + let mut ctx = context( options(&[]), Mode::Systemd(UnitScopeTag::System), "NVIDIA GeForce RTX 5090", 120, ); + ctx.needs.expert_profile = Some(ExpertProfileState::Absent); let steps = plan_steps( &ctx, &FsState { @@ -943,6 +1047,7 @@ mod tests { for id in [ "layout", "binaries", + "expert-profile", "secrets", "model", "kar", @@ -1001,6 +1106,159 @@ mod tests { assert!(!render_plan(&ctx, &steps[1..]).contains("$ ")); } + fn expert_step(extra: &[&str], state: ExpertProfileState) -> StepState { + let mut ctx = context( + options(extra), + Mode::Foreground, + "NVIDIA GeForce RTX 5090", + 120, + ); + ctx.needs.expert_profile = Some(state); + let steps = plan_steps( + &ctx, + &FsState { + binaries_source_ok: true, + ..FsState::default() + }, + ); + state_of(&steps, "expert-profile").clone() + } + + #[test] + fn the_expert_profile_is_planned_before_the_big_downloads() { + let ctx = context( + options(&[]), + Mode::Foreground, + "NVIDIA GeForce RTX 5090", + 120, + ); + let ids: Vec<&str> = plan_steps(&ctx, &FsState::default()) + .iter() + .map(|s| s.id) + .collect(); + let at = |id: &str| ids.iter().position(|i| *i == id).unwrap(); + assert!( + at("expert-profile") < at("model") + && at("expert-profile") < at("kar") + && at("expert-profile") < at("config"), + "{ids:?}" + ); + } + + #[test] + fn the_expert_profile_step_covers_every_state_and_never_stays_silent() { + // present with the pinned digest: nothing to do + assert!( + matches!(expert_step(&[], ExpertProfileState::Valid), StepState::Done(why) if why.contains("8f59b4aa...388975baf")) + ); + // missing: downloaded (the test host has curl) + assert!( + matches!(expert_step(&[], ExpertProfileState::Absent), StepState::Todo(why) if why.contains("196632")) + ); + // missing and offline: blocked with both ways out + let blocked = expert_step(&["--no-fetch"], ExpertProfileState::Absent); + assert!( + matches!(&blocked, StepState::Blocked(why) if why.contains("--expert-profile-file") && why.contains("--no-expert-tier")), + "{blocked:?}" + ); + // the offline route installs from the local file + let local = expert_step( + &[ + "--no-fetch", + "--expert-profile-file", + "/mnt/usb/expert-profile.bin", + ], + ExpertProfileState::Absent, + ); + assert!( + matches!(&local, StepState::Todo(why) if why.contains("/mnt/usb/expert-profile.bin")), + "{local:?}" + ); + // a file with another digest is never used silently: blocked, or replaced (moved aside) on request + let wrong = expert_step(&[], ExpertProfileState::WrongDigest); + assert!( + matches!(&wrong, StepState::Blocked(why) if why.contains("is not used") && why.contains("Move it aside")), + "{wrong:?}" + ); + let replace = expert_step( + &["--expert-profile-file", "/x/p.bin"], + ExpertProfileState::WrongDigest, + ); + assert!( + matches!(&replace, StepState::Todo(why) if why.contains("moved aside")), + "{replace:?}" + ); + // the explicit opt-out is a Skip that says OFF + let off = expert_step(&["--no-expert-tier"], ExpertProfileState::OptedOut); + assert!( + matches!(&off, StepState::Skip(why) if why.contains("OFF")), + "{off:?}" + ); + } + + #[test] + fn a_host_without_curl_or_wget_blocks_the_download_but_not_the_local_file() { + let mut ctx = context( + options(&[]), + Mode::Foreground, + "NVIDIA GeForce RTX 5090", + 120, + ); + ctx.facts.tools.insert("curl".into(), false); + ctx.needs.expert_profile = Some(ExpertProfileState::Absent); + let steps = plan_steps(&ctx, &FsState::default()); + assert!( + matches!(state_of(&steps, "expert-profile"), StepState::Blocked(why) if why.contains("neither curl nor wget")) + ); + ctx.opts.expert_profile_file = Some("/x/p.bin".into()); + let steps = plan_steps(&ctx, &FsState::default()); + assert!(matches!( + state_of(&steps, "expert-profile"), + StepState::Todo(_) + )); + } + + #[test] + fn the_gathered_environment_names_the_table_unless_the_tier_is_opted_out() { + let dir = std::env::temp_dir().join(format!("leleka-expert-gather-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let gathered = |extra: &[&str]| { + let mut args = vec!["--profile", "rtx5090-32g"]; + args.extend_from_slice(extra); + let mut opts = options(&args); + opts.dirs.assets = dir.clone(); + gather(&opts, &|_| None) + }; + // The table is absent: the configuration still names it (the step provisions it before the configuration is written). + let with_tier = gathered(&[]); + let config = with_tier.config.as_ref().unwrap(); + assert!( + config.expert_tier + && config + .engine_env + .contains_key(crate::expert_profile::PROFILE_ENV) + ); + assert_eq!( + with_tier.needs.expert_profile, + Some(ExpertProfileState::Absent) + ); + // The opt-out leaves the switches out and is recorded, so `status` can say "explicit opt-out". + let without = gathered(&["--no-expert-tier"]); + let config = without.config.as_ref().unwrap(); + assert!( + !config.expert_tier + && !config + .engine_env + .contains_key(crate::expert_profile::PROFILE_ENV) + ); + assert_eq!( + without.needs.expert_profile, + Some(ExpertProfileState::OptedOut) + ); + let _ = std::fs::remove_dir_all(dir); + } + #[test] fn missing_pieces_block_with_the_reason() { let ctx = context( diff --git a/crates/deploy/src/preflight.rs b/crates/deploy/src/preflight.rs index e3d60614..25f73058 100644 --- a/crates/deploy/src/preflight.rs +++ b/crates/deploy/src/preflight.rs @@ -104,6 +104,8 @@ pub enum ExpertProfileState { Absent, Valid, WrongDigest, + /// `--no-expert-tier`: the operator switched the tier off on purpose. + OptedOut, } const GIB: u64 = 1 << 30; @@ -739,22 +741,39 @@ pub fn evaluate(facts: &Facts, profile: &Profile, needs: &Needs) -> Report { Some("if the download answers 401/403, export HF_TOKEN=... (it is only sent to https://huggingface.co and never printed)".into()), )); } - match &needs.expert_profile { - Some(ExpertProfileState::Absent) if profile.expert_profile.is_some() => checks.push(check( - "expert-profile", - Level::Warn, - "VRAM expert tier", - format!("{} is not in the assets directory; the engine runs without the ranked VRAM expert tier (slower)", profile.expert_profile.as_deref().unwrap_or("")), - Some("copy the upstream data/expert-profile.bin (sha256 8f59b4aa...388975baf) there, then rerun".into()), - )), - Some(ExpertProfileState::WrongDigest) => checks.push(check( - "expert-profile", - Level::Warn, - "VRAM expert tier", - "the expert profile does not have the pinned SHA-256; it will not be used".into(), - None, - )), - _ => {} + if let Some(relative) = profile.expert_profile.as_deref() { + let pinned = crate::expert_profile::short_digest(crate::expert_profile::expected_digest(profile)); + let path = needs.assets_dir.join(relative).display().to_string(); + let way_out = "run `leleka up` (it downloads the pinned table and checks the digest), or pass --expert-profile-file PATH offline; --no-expert-tier accepts the slower decode"; + match &needs.expert_profile { + Some(ExpertProfileState::Valid) => checks.push(pass( + "expert-profile", + "VRAM expert tier", + format!("ON: {path} has the pinned sha256 {pinned}"), + )), + Some(ExpertProfileState::Absent) => checks.push(check( + "expert-profile", + Level::Warn, + "VRAM expert tier", + format!("OFF until fetched: {path} is not in the assets directory; without the ranked table the engine runs without the VRAM expert tier (much slower)"), + Some(way_out.into()), + )), + Some(ExpertProfileState::WrongDigest) => checks.push(check( + "expert-profile", + Level::Warn, + "VRAM expert tier", + format!("OFF: {path} does not have the pinned sha256 {pinned}; it will not be used (much slower)"), + Some(format!("move that file aside, then {way_out}")), + )), + Some(ExpertProfileState::OptedOut) => checks.push(check( + "expert-profile", + Level::Warn, + "VRAM expert tier", + "OFF: --no-expert-tier was given; decode is much slower than with the ranked table".into(), + None, + )), + None => {} + } } Report { @@ -842,6 +861,31 @@ mod tests { .level } + #[test] + fn the_expert_tier_is_always_reported_on_or_off() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let report_for = |state: Option| { + let mut n = needs(); + n.expert_profile = state; + evaluate(&server_facts(), &profile, &n) + }; + let report = report_for(Some(ExpertProfileState::Valid)); + assert_eq!(level_of(&report, "expert-profile"), Level::Pass); + assert!(report.render().contains("ON:") && report.render().contains("8f59b4aa...388975baf")); + for (state, needle) in [ + (ExpertProfileState::Absent, "OFF until fetched"), + (ExpertProfileState::WrongDigest, "does not have the pinned sha256"), + (ExpertProfileState::OptedOut, "--no-expert-tier was given"), + ] { + let report = report_for(Some(state)); + assert_eq!(level_of(&report, "expert-profile"), Level::Warn); + let text = report.render(); + assert!(text.contains("OFF") && text.contains(needle), "{text}"); + } + // an absent table names the way out + assert!(report_for(Some(ExpertProfileState::Absent)).render().contains("--expert-profile-file")); + } + #[test] fn healthy_server_passes_everything() { let profile = Profile::builtin("rtx5090-32g").unwrap(); diff --git a/crates/deploy/src/steps.rs b/crates/deploy/src/steps.rs index 6f6dc7a6..b5889a5f 100644 --- a/crates/deploy/src/steps.rs +++ b/crates/deploy/src/steps.rs @@ -297,7 +297,14 @@ pub async fn fetch_status(paths: &Paths, api: &str) -> Option /// `GET /v1/status` with an API key read elsewhere. pub async fn fetch_status_with_key(key: &str, api: &str) -> Option { let address = crate::config::probe_address(api)?; - let response = http::get(address, "/v1/status", Some(key.trim_end()), Duration::from_secs(3)).await.ok()?; + let response = http::get( + address, + "/v1/status", + Some(key.trim_end()), + Duration::from_secs(3), + ) + .await + .ok()?; if response.status != 200 { return None; } @@ -456,6 +463,124 @@ pub fn install_binaries(ctx: &Context) -> Result { Ok(installed) } +/// Download `url` to `part` with curl (or wget), https only, at most 1 MiB; output goes to `log`. +fn download_small(tool: &str, url: &str, part: &Path, log: &Path) -> Result<(), String> { + use std::io::Write; + let part_text = part.display().to_string(); + let args: Vec<&str> = if tool == "wget" { + vec![ + "-q", + "--tries=3", + "--timeout=60", + "--https-only", + "-O", + &part_text, + url, + ] + } else { + vec![ + "-fsSL", + "--proto", + "=https", + "--retry", + "3", + "--retry-delay", + "2", + "--max-time", + "120", + "--max-filesize", + "1048576", + "-o", + &part_text, + url, + ] + }; + let output = std::process::Command::new(tool) + .args(&args) + .stdin(Stdio::null()) + .output() + .map_err(|e| format!("cannot run {tool}: {e}"))?; + if let Ok(mut file) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(log) + { + let _ = writeln!(file, "$ {tool} {}", args.join(" ")); + let _ = file.write_all(&output.stderr); + } + if output.status.success() { + Ok(()) + } else { + let detail = String::from_utf8_lossy(&output.stderr); + Err(format!( + "{tool} failed ({}){}", + output.status, + if detail.trim().is_empty() { + String::new() + } else { + format!(": {}", detail.trim()) + } + )) + } +} + +/// The `expert-profile` step: install the pinned upstream table from `--expert-profile-file` or by download, verified +/// against the profile's digest, atomically; fails closed (`expert_profile::provision`). +pub fn provision_expert_profile(ctx: &Context) -> Result<(), String> { + use crate::expert_profile::{Outcome, Request, SOURCES, expected_digest, provision}; + let profile = ctx.profile.as_ref().map_err(String::clone)?; + let relative = profile + .expert_profile + .as_ref() + .ok_or("the profile has no expert profile")?; + let dest = ctx.opts.dirs.assets.join(relative); + let expected = expected_digest(profile); + let tool = if cfg!(windows) || ctx.facts.tool("curl") { + "curl" + } else { + "wget" + }; + let log = ctx.paths.logs().join("install.log"); + let sources: &[&str] = if expected == crate::expert_profile::PINNED_SHA256 { + &SOURCES + } else { + &[] + }; + let request = Request { + dest: &dest, + expected, + local: ctx.opts.expert_profile_file.as_deref(), + sources, + }; + let mut fetch = |url: &str, part: &Path| { + say(&format!("downloading {url}")); + download_small(tool, url, part, &log) + }; + match provision(&request, &mut fetch)? { + Outcome::AlreadyPresent => say(&format!( + "{} already has the expected digest", + dest.display() + )), + Outcome::Installed { + origin, + moved_aside, + } => { + say(&format!( + "installed {} from {origin}; expert tier ON (sha256 {})", + dest.display(), + crate::expert_profile::short_digest(expected) + )); + if let Some(aside) = moved_aside { + say(&format!( + "the file that was in the way is kept as {}", + aside.display() + )); + } + } + } + Ok(()) +} + pub async fn install_cublas(ctx: &Context) -> Result<(), String> { let paths = &ctx.paths; let lib_dir = paths.dirs.prefix.join("lib"); @@ -1075,6 +1200,7 @@ pub async fn prepare(ctx: &Context, steps: &[Step]) -> Result { ctx.paths.bin_dir().display() )) }), + "expert-profile" => provision_expert_profile(ctx), "cublas" => install_cublas(ctx).await, "secrets" => { write_secrets_and_env(ctx)?; @@ -1161,6 +1287,52 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + /// Live: the real download path (curl, https only, size cap) through `provision` against the pinned upstream sources. + /// `cargo test -p leleka-deploy --lib -- --ignored provisions_the_pinned_table_from_upstream` + #[test] + #[ignore = "network"] + fn provisions_the_pinned_table_from_upstream() { + use crate::expert_profile::{ + FileState, Outcome, PINNED_BYTES, PINNED_SHA256, Request, SOURCES, file_state, + provision, + }; + let dir = temp("live"); + let dest = dir.join("data").join("expert-profile.bin"); + let log = dir.join("install.log"); + let tool = "curl"; + let request = Request { + dest: &dest, + expected: PINNED_SHA256, + local: None, + sources: &SOURCES, + }; + let outcome = provision(&request, &mut |url, part| { + download_small(tool, url, part, &log) + }) + .unwrap(); + assert!(matches!(outcome, Outcome::Installed { .. }), "{outcome:?}"); + assert_eq!(file_state(&dest, PINNED_SHA256), FileState::Valid); + assert_eq!(std::fs::metadata(&dest).unwrap().len(), PINNED_BYTES); + assert!(!dest.with_extension("bin.part").exists()); + // A source that answers with something else fails closed: an https URL that is not the table. + let other = dir.join("other.bin"); + let bad = Request { + dest: &other, + expected: PINNED_SHA256, + local: None, + sources: &[ + "https://raw.githubusercontent.com/Niko1221/Strata/41cf05a06a25dd29103b7b27a2279a3f60c21876/LICENSE", + ], + }; + let error = + provision(&bad, &mut |url, part| download_small(tool, url, part, &log)).unwrap_err(); + assert!( + error.contains("is not the expected") && !other.exists(), + "{error}" + ); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn sha256_of_a_file() { let dir = temp("sha"); diff --git a/crates/deploy/src/supervisor.rs b/crates/deploy/src/supervisor.rs index 03fb1242..4018fb4b 100644 --- a/crates/deploy/src/supervisor.rs +++ b/crates/deploy/src/supervisor.rs @@ -845,7 +845,10 @@ impl Supervisor { /// Engine process -> port -> gateway connected -> typed load -> model_ready. async fn start_engine(&mut self, gateway: &mut Child) -> Result { self.set_phase(Phase::StartingEngine, "starting the engine"); - let env = self.config.engine_environment(); + // The expert tier is re-checked at every start: a missing or changed table is logged loudly and the engine is + // not handed the switches that name it (`expert_profile::start_environment`). + let (env, tier) = crate::expert_profile::start_environment(&self.config, &self.paths.dirs.assets); + self.log.line(&tier.line()); let inference = self.paths.bin("leleka-inference"); let (kar_arg, stdin) = match &self.archive { Some(file) => ( diff --git a/crates/deploy/src/winfront.rs b/crates/deploy/src/winfront.rs index 7d4439e3..36d2d8d4 100644 --- a/crates/deploy/src/winfront.rs +++ b/crates/deploy/src/winfront.rs @@ -414,7 +414,20 @@ async fn status(args: &[String]) -> i32 { if !json && key.is_none() { note(&format!("no API key in {state_dir}/api-key of {} (has `leleka up` run? other state? pass --state-dir)", session.bridge.distro)); } - print_status(json, ready, None, supervisor, gateway.as_ref(), &linux_to_unc(&session.bridge.distro, &format!("{state_dir}/run"))) + // The table lives in the distribution: the digest is taken there (`sha256sum`), the report is the same as on a Linux host. + let expert_tier = session + .bridge + .read_file(&format!("{state_dir}/leleka.json")) + .and_then(|text| serde_json::from_str::(&text).ok()) + .map(|config| { + let expected = crate::expert_profile::expected_digest(&config.profile).to_owned(); + let path = config.profile.expert_profile.as_ref().map(|relative| format!("{}/{relative}", config.assets.trim_end_matches('/'))).unwrap_or_default(); + crate::expert_profile::tier_report_with(&config, &path, || { + let observed = session.bridge.capture("sha256sum", &[path.as_str()]).ok().and_then(|out| out.split_whitespace().next().map(str::to_owned)); + crate::expert_profile::FileState::from_digest(observed.as_deref(), &expected) + }) + }); + print_status(json, ready, None, supervisor, gateway.as_ref(), expert_tier.as_ref(), &linux_to_unc(&session.bridge.distro, &format!("{state_dir}/run"))) } async fn reconfigure(args: &[String]) -> i32 { @@ -644,7 +657,7 @@ async fn doctor(args: &[String]) -> i32 { if volume_missing.is_empty() { println!( " complete{}", - if crate::doctor::expert_profile_present(&paths) { "" } else { " (data\\expert-profile.bin is absent: optional, but it is the ranked VRAM expert tier)" } + if crate::doctor::expert_profile_present(&paths) { "" } else { " (data\\expert-profile.bin is absent or not the pinned table: `leleka up` downloads it, or pass --expert-profile-file; without it the VRAM expert tier is OFF)" } ); } let inputs = crate::doctor::Inputs { diff --git a/crates/deploy/src/wsl.rs b/crates/deploy/src/wsl.rs index 19e210c4..4b3a461c 100644 --- a/crates/deploy/src/wsl.rs +++ b/crates/deploy/src/wsl.rs @@ -146,13 +146,14 @@ pub fn linux_to_unc(distro: &str, linux_path: &str) -> String { } /// Flags of `leleka` whose value is a path in the distribution; their values are translated before forwarding. -pub const PATH_FLAGS: [&str; 7] = [ +pub const PATH_FLAGS: [&str; 8] = [ "--assets", "--state-dir", "--prefix", "--bin-src", "--cublas-dir", "--mtp-pack", + "--expert-profile-file", "--config", ]; diff --git a/crates/deploy/tests/e2e.rs b/crates/deploy/tests/e2e.rs index 7d062959..12b6b4d4 100644 --- a/crates/deploy/tests/e2e.rs +++ b/crates/deploy/tests/e2e.rs @@ -100,6 +100,8 @@ impl Fixture { let mut config = RunConfig::new(&self.dirs, self.ports.clone(), 0, profile, BTreeMap::new()); config.shutdown_grace_s = 2; + // The flow tests are not about the expert tier (it has no table here): it is off on purpose, as after `--no-expert-tier`. + config.expert_tier = false; fs::write(paths.run_config(), to_file_text(&config)).unwrap(); fs::write(paths.daemon_config(), to_file_text(&config.daemon_json())).unwrap(); fs::write(paths.strata_config(), to_file_text(&config.strata_json())).unwrap(); @@ -493,12 +495,27 @@ fn a_broken_configuration_is_exit_code_two_with_a_clear_message() { // ----------------------------------------------------------------------------------------------------------- // the `up` flow +/// `up` options of the 3080 profile with the expert tier switched off on purpose: the flow tests must not download +/// the real table. The tier itself is covered by `up_installs_the_expert_profile_offline_and_reports_it`. fn up_options( fixture: &Fixture, bin_src: &Path, cublas: &Path, mtp: &Path, extra: &[&str], +) -> UpOptions { + let mut all = vec!["--no-expert-tier"]; + all.extend_from_slice(extra); + up_options_with(fixture, bin_src, cublas, mtp, "rtx3080-16g", &all) +} + +fn up_options_with( + fixture: &Fixture, + bin_src: &Path, + cublas: &Path, + mtp: &Path, + profile: &str, + extra: &[&str], ) -> UpOptions { let var = |_: &str| None; let args: Vec = [ @@ -522,7 +539,7 @@ fn up_options( "--daemon-port", fixture.ports.daemon.rsplit(':').next().unwrap(), "--profile", - "rtx3080-16g", + profile, "--mode", "none", ] @@ -792,6 +809,78 @@ async fn trust_archive_skips_the_strict_rederivation_but_still_fetches_and_verif ); } +#[tokio::test] +async fn up_installs_the_expert_profile_offline_and_reports_it() { + use leleka_deploy::expert_profile::{FileState, PROFILE_ENV, file_state, sha256_hex, tier_report}; + let fixture = Fixture::new("expert"); + let bin_src = fixture.root.join("release/bin"); + fixture.install_fake_binaries(&bin_src); + let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); + fake_libraries(&cublas); + mtp_source(&mtp); + // A profile that pins the digest of a small fixture, so that the flow runs without the real 192 KiB table. + let table = b"STRP-fixture: a stand-in for the ranked expert table".to_vec(); + let digest = sha256_hex(&table); + let mut profile = Profile::builtin("rtx3080-16g").unwrap(); + profile.expert_profile_sha256 = Some(digest.clone()); + let profile_file = fixture.root.join("profile.json"); + fs::write(&profile_file, serde_json::to_string(&profile).unwrap()).unwrap(); + let local = fixture.root.join("table.bin"); + fs::write(&local, &table).unwrap(); + let paths = fixture.dirs.paths(); + let table_path = fixture.dirs.assets.join("data/expert-profile.bin"); + let flags = [profile_file.display().to_string(), local.display().to_string()]; + + // No table, offline, no override: the plan blocks with both ways out, before anything is downloaded. + let opts = up_options_with(&fixture, &bin_src, &cublas, &mtp, &flags[0], &["--no-fetch"]); + let ctx = healthy_context(&opts); + let steps = plan_steps(&ctx, &gather_fs(&ctx).await); + let step = steps.iter().find(|s| s.id == "expert-profile").unwrap(); + assert_eq!(step.state.tag(), "BLOCKED", "{step:?}"); + assert!(step.state.why().contains("--expert-profile-file") && step.state.why().contains("--no-expert-tier")); + + // With the local copy: installed, verified, configured, reported ON. + let opts = up_options_with(&fixture, &bin_src, &cublas, &mtp, &flags[0], &["--expert-profile-file", &flags[1]]); + let ctx = healthy_context(&opts); + let steps = plan_steps(&ctx, &gather_fs(&ctx).await); + assert_eq!(steps.iter().find(|s| s.id == "expert-profile").unwrap().state.tag(), "todo"); + assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); + assert_eq!(file_state(&table_path, &digest), FileState::Valid); + let config = RunConfig::read(&paths.run_config()).unwrap(); + assert_eq!(config.engine_env.get(PROFILE_ENV), Some(&table_path.display().to_string())); + let report = tier_report(&config, &fixture.dirs.assets); + assert!(report.on && report.line().starts_with("expert tier ON"), "{}", report.line()); + + // Second run: done, nothing rewritten. + let ctx = healthy_context(&opts); + let steps = plan_steps(&ctx, &gather_fs(&ctx).await); + assert_eq!(steps.iter().find(|s| s.id == "expert-profile").unwrap().state.tag(), "done"); + assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); + + // The file changes behind the service's back: the report turns OFF and the start drops the switches. + fs::write(&table_path, b"corrupted").unwrap(); + let report = tier_report(&config, &fixture.dirs.assets); + assert!(!report.on && report.line().starts_with("WARNING expert tier OFF"), "{}", report.line()); + let (env, _) = leleka_deploy::expert_profile::start_environment(&config, &fixture.dirs.assets); + assert!(!env.contains_key(PROFILE_ENV)); + // `up` without an override refuses to guess: the wrong file blocks the plan (it is never silently ignored). + let opts = up_options_with(&fixture, &bin_src, &cublas, &mtp, &flags[0], &[]); + let ctx = healthy_context(&opts); + let steps = plan_steps(&ctx, &gather_fs(&ctx).await); + assert_eq!(steps.iter().find(|s| s.id == "expert-profile").unwrap().state.tag(), "BLOCKED"); + assert!(run_up(&ctx, &steps).await.unwrap_err().contains("expert-profile")); + + // The explicit opt-out is recorded and reported as such. + let opts = up_options_with(&fixture, &bin_src, &cublas, &mtp, &flags[0], &["--no-expert-tier"]); + let ctx = healthy_context(&opts); + let steps = plan_steps(&ctx, &gather_fs(&ctx).await); + assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); + let config = RunConfig::read(&paths.run_config()).unwrap(); + assert!(!config.expert_tier && !config.engine_env.contains_key(PROFILE_ENV)); + let report = tier_report(&config, &fixture.dirs.assets); + assert!(!report.on && report.opted_out && report.line().contains("explicit opt-out"), "{}", report.line()); +} + #[tokio::test] async fn a_wrong_size_archive_is_refused_before_the_engine_could_reject_it() { let fixture = Fixture::new("wrongkar"); diff --git a/docs/deploy.md b/docs/deploy.md index dd05f17c..ec1ef5eb 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -43,6 +43,7 @@ Container: [section 7](#7-container-image). Build your own release: [section 8]( | 1 | preflight | driver >= 595, GPU architecture, VRAM free vs budget, RAM total/available, disk on each volume, WSL2 mounts, `libcublas.so.12`, `memfd_create`, ports, systemd, the six binaries | read-only; any FAIL stops before anything is changed | | 2 | layout | state (0700), logs, run, stamps, assets | `mkdir -p` | | 3 | binaries | copy `bin/*` to `PREFIX/bin`, SHA-256 checked against `MANIFEST.json` | skipped when identical; replaced by rename (safe for a running binary) | +| 3b | expert profile | the ranked VRAM expert tier's table `ASSETS/data/expert-profile.bin` (192 KiB, upstream Strata at the pinned commit): downloaded over https from the pinned commit, or installed from `--expert-profile-file PATH` (offline); SHA-256 `8f59b4aa...388975baf` is checked, the file is installed by rename, any other digest fails closed (a wrong file already there is moved aside, never deleted); `--no-expert-tier` is the explicit opt-out. Planned before the large downloads. `status`, `verify`, the ready summary and the supervisor log say `expert tier ON (sha256 ...)` or `WARNING expert tier OFF: reason` | skipped when the file has the pinned digest | | 4 | cuBLAS 12 | uses what the host has; otherwise downloads the pinned NVIDIA 12.9.1.4 redistributable (SHA-256 pinned, resumable) into `PREFIX/lib/cublas` | skipped when `libcublas.so.12` and `libcublasLt.so.12` are found | | 5 | secrets | two service tokens into `STATE/runtime.env` (0600), API key through `strata-next api-key init` | never rotated; only missing/invalid ones are created | | 6 | model | `strata-next model fetch qwen-iq3-s` then `model verify` (resumable `.part` files, SHA-256) | stamped with size+mtime: skipped on re-runs unless `--reverify` | @@ -104,7 +105,7 @@ The files live in [`deploy/rust-runtime/profiles/`](../deploy/rust-runtime/profi | profile | selected for | GPU budget | context | KAR archive | routed experts | RAM floor (total / available at start) | other | | --- | --- | --- | --- | --- | --- | --- | --- | | `rtx5090-32g` | sm_12x, >= 30 GB VRAM | 32,819,404,800 B = 31,299 MiB (needs that much free at start: 31,299 of the 32,110 MiB an idle card reports; was 30 GiB, see [vram-footprint-5090](experiments/vram-footprint-5090.md)) | 262,144 | sealed memfd (55.3 GB of RAM) | `resident`: page-locked RAM copy (50.3 GB) | 100 GiB / 113 GB (58 GB when `--kar-fd` supplies the archive) | the documented bring-up configuration | -| `rtx3080-16g` | sm_80..119, 14-24 GB VRAM | 15 GiB (needs 14,500 MiB free) | 8,192 | read-only file | `mapped`: read-only mappings of shard 0 | 22 GiB / 10 GiB; advice `.wslconfig memory=32GB` | optional VRAM expert tier when `ASSETS/data/expert-profile.bin` has the pinned SHA-256 `8f59b4aa...388975baf` | +| `rtx3080-16g` | sm_80..119, 14-24 GB VRAM | 15 GiB (needs 14,500 MiB free) | 8,192 | read-only file | `mapped`: read-only mappings of shard 0 | 22 GiB / 10 GiB; advice `.wslconfig memory=32GB` | VRAM expert tier: `up` fetches `ASSETS/data/expert-profile.bin` (pinned SHA-256 `8f59b4aa...388975baf`; `--no-expert-tier` to run without) | Both profiles also carry a `memory` section (prefix cache `auto`, soft/hard floors 4096/2048 MiB, reserve, lock and heal of the sealed memfd): the engine sizes its caches from the memory left after the fixed footprint, sheds and refuses under pressure, and refuses to start with numbers when the footprint does not fit ([`memory-safety.md`](memory-safety.md)). The unit sets `LimitMEMLOCK=infinity`, which is what lets the lock keep the 55 GB memfd out of swap. @@ -224,6 +225,7 @@ profile as `up` resolved it (`base_profile` in `leleka.json`, written since this | `--reverify` | ignore the stamps and hash everything again | | `--trust-archive` | accept an existing pinned-length archive + provenance without the strict re-derivation (section 2) | | `--mtp-pack PATH` | import the MTP pack (directory or `.tar/.tar.gz/.tgz/.tar.xz`, sub-directories searched) | +| `--expert-profile-file PATH` / `--no-expert-tier` | install the ranked expert table from this copy of the upstream `data/expert-profile.bin` instead of downloading it (the pinned digest is still required) / run without the VRAM expert tier (much slower; reported as OFF) | | `--cublas-dir DIR` / `--no-install-cublas` | use this CUDA 12 cuBLAS / fail instead of downloading it | | `--kar-fd N` | an already sealed archive descriptor inherited from the parent (foreground or `--mode none` only) | | `--timeout-s N` | wait this long for `/ready` (default 3600) | diff --git a/docs/upstream.md b/docs/upstream.md index 5ce46dc4..32b60fac 100644 --- a/docs/upstream.md +++ b/docs/upstream.md @@ -108,7 +108,7 @@ The root `.gitignore` already drops `*.bin`, `*.gguf`, `*.log` and `models/`; th | Binary media and assets added by upstream | 61 | `apps/desktop/src-tauri/icons/**` and `nsis/*.bmp` (app icons), `apps/host/public/**` (favicons, three GT Walsheim Pro `*.woff2` commercial fonts, an example gif/mp4/pdf), `docs/terminal-previews/*.png` (7), `docs/media/*.png` (2), `docs/media/models/*` | upstream | | `docs/work/evidence/**` | 24 | test-run transcripts and JSON self-test output (logs) | upstream | | Model-adjacent binaries that the root `.gitignore` also matches | `data/dsv41/profile-2.00.bin`, `profile-2.25.bin` (hot-expert profiles for the DeepSeek packs), `data/draft_vocab_fr.bin`, `data/expert-profile-sycl.bin`, `tests/fixtures/dsv41/engram-final-header.gguf` | binary data files; needed only to run the DeepSeek engine or its SYCL path | upstream | -| Already left out by the first import and still left out | `data/draft_vocab.bin`, `data/draft_vocab_cyrillic.bin`, `data/draft_vocab_en.bin`, `data/expert-profile.bin`, `data/expert-profile-coder.bin`, `data/experimental-speed-projection/*.gguf`, `bench/results/2026-09-30-community-rtx-5090/engine.log` | same rule | upstream | +| Already left out by the first import and still left out | `data/draft_vocab.bin`, `data/draft_vocab_cyrillic.bin`, `data/draft_vocab_en.bin`, `data/expert-profile.bin` (fetched by `leleka up` from the pinned commit, SHA-256 checked; `crates/deploy/src/expert_profile.rs`), `data/expert-profile-coder.bin`, `data/experimental-speed-projection/*.gguf`, `bench/results/2026-09-30-community-rtx-5090/engine.log` | same rule | upstream | Kept on purpose although they look large: `apps/host` and `apps/desktop` source (TypeScript / Rust text; 8 MB), `tools/qwen35/pictures/*.png` (three small test inputs), `docs/work/*.md`, `bench/prompts/**` (frozen benchmark prompts, hashed byte for byte), `sycl/`, `metal/`, diff --git a/docs/windows.md b/docs/windows.md index d3c259d6..7d3e50a8 100644 --- a/docs/windows.md +++ b/docs/windows.md @@ -97,7 +97,7 @@ ASSETS\model\Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf 28,800,138 ASSETS\qwen-iq3-s-l2-v4.kar 55,295,529,472 bytes (at the root, not in model\) ASSETS\qwen-iq3-s-l2-v4.kar.provenance.json ASSETS\data\mtp-rt\{dense.bin,dense.txt,draft_vocab.bin,experts.bin} -ASSETS\data\expert-profile.bin (sha256 8f59b4aa...8975baf; optional but it is the VRAM expert tier) +ASSETS\data\expert-profile.bin (sha256 8f59b4aa...8975baf; the VRAM expert tier; `leleka up` downloads it, or `--expert-profile-file PATH`) ASSETS\tokenizer-assets\ (made by `up`) ``` @@ -136,7 +136,7 @@ $L = "target\release\leleka.exe" # or dist\bin\leleka.exe ``` * `--assets` may be a Linux path (`/home/para/leleka-assets`), a `\\wsl.localhost\Ubuntu\...` path or `~/...`; Windows paths are translated to - `/mnt/c/...` and refused for `--assets`. The same translation applies to `--state-dir`, `--prefix`, `--bin-src`, `--cublas-dir`, `--mtp-pack`, + `/mnt/c/...` and refused for `--assets`. The same translation applies to `--state-dir`, `--prefix`, `--bin-src`, `--cublas-dir`, `--mtp-pack`, `--expert-profile-file`, `--profile FILE`. `--wsl-distro NAME` / `$env:LELEKA_WSL_DISTRO` choose the distribution (default: the default WSL2 one that is not Docker's). * `up` first prints the `.wslconfig` advice (memory below ~32 GB or no swap), then runs the Linux `leleka up` with its output forwarded. Without systemd in the distribution it runs in the foreground in this window (Ctrl-C drains and stops); with systemd (this laptop has it) it installs and