diff --git a/crates/cuda-driver/src/kar_decode_levels_gpu_smoke.rs b/crates/cuda-driver/src/kar_decode_levels_gpu_smoke.rs index 422a34b9..4f344eaf 100644 --- a/crates/cuda-driver/src/kar_decode_levels_gpu_smoke.rs +++ b/crates/cuda-driver/src/kar_decode_levels_gpu_smoke.rs @@ -304,3 +304,55 @@ fn kar_levels_expert_mlp_matches_cpu_within_tolerance() { program.close().unwrap(); ctx.close().unwrap(); } + +/// Cost probe (docs/design/memory-single-copy-and-elastic-state.md, candidate B): the time of one routed-expert MLP of the real +/// shape (hidden 2560, ff 640, three matrices of 1,638,400 elements) through the existing KAR level-decode program: decode to F32 +/// scratch, multiply, SwiGLU, down, copy the result to the host. It includes the host-to-device copy of the packets of each call +/// and one synchronisation, so it is an upper bound of the on-device cost and a lower bound of what the Original serve path +/// would need (no 1 token window of the verify batch, no expert cache). Synthetic bit patterns: decode cost does not depend on +/// the values. Prints one line per level: `KAR_PROBE level=L us_per_expert=.. packet_bytes=.. f32_scratch_bytes=..`. +#[test] +#[ignore = "GPU timing probe, run by hand on the 5090 under the GPU lock"] +fn kar_levels_expert_cost_probe() { + use super::kar_decode_levels_gpu::KarMatrix; + let driver = Driver::load().unwrap(); + let device = driver.device(0).unwrap(); + let ctx = device.create_context(512 * 1024 * 1024).unwrap(); + let program = KarDecodeLevels::open(&ctx).unwrap(); + let mut rng = Rng(0x6a70_c057_0003); + let (hidden, ff) = (2560u32, 640u32); + let input: Vec = (0..hidden).map(|i| ((i % 13) as f32 - 6.0) / 16.0).collect(); + for level in [2u32, 3] { + let count = hidden * ff; + let mut packets = Vec::new(); + let mut geometries = Vec::new(); + for _ in 0..3 { + let t = truth(&mut rng, level, 32, count as usize); + let g = DecodeGeometry::for_window(level, 32, 0, u64::from(count)).unwrap(); + packets.push(t.packet(level, &g, 0)); + geometries.push(g); + } + let shapes = [ + MultiplyGeometry { columns: hidden, rows: ff, tokens: 1 }, + MultiplyGeometry { columns: hidden, rows: ff, tokens: 1 }, + MultiplyGeometry { columns: ff, rows: hidden, tokens: 1 }, + ]; + let matrix = |i: usize| KarMatrix { geometry: geometries[i], shape: shapes[i], packet: &packets[i] }; + for _ in 0..10 { + program.expert_mlp_to_host(&matrix(0), &matrix(1), &matrix(2), &input).unwrap(); + } + let n = 300u32; + let began = std::time::Instant::now(); + for _ in 0..n { + program.expert_mlp_to_host(&matrix(0), &matrix(1), &matrix(2), &input).unwrap(); + } + let us = began.elapsed().as_secs_f64() * 1e6 / f64::from(n); + let packet_bytes: usize = packets.iter().map(Vec::len).sum(); + println!( + "KAR_PROBE level={level} us_per_expert={us:.1} packet_bytes={packet_bytes} f32_scratch_bytes={}", + 3 * 4 * u64::from(count) + ); + } + program.close().unwrap(); + ctx.close().unwrap(); +} diff --git a/crates/deploy/src/app.rs b/crates/deploy/src/app.rs index 8a6e27e0..2a3cf3bf 100644 --- a/crates/deploy/src/app.rs +++ b/crates/deploy/src/app.rs @@ -130,6 +130,13 @@ pub async fn main_native(mut args: Vec) -> i32 { 2 } }, + Command::SealExec(rest) => match crate::sealed::seal_exec(&rest) { + Ok(never) => match never {}, + Err(message) => { + eprintln!("leleka seal-exec: {message}"); + 2 + } + }, } } @@ -410,8 +417,13 @@ pub fn summary(ctx: &Context, config: &crate::config::RunConfig) { config.profile.context_tokens, match config.profile.kar_source { crate::profile::KarSource::Memfd => format!( - "a sealed memfd ({} of RAM held for the life of the service)", - gib(crate::profile::ARCHIVE_BYTES) + "a sealed memfd ({} of RAM held for the life of the service{})", + gib(config.profile.memfd_bytes()), + if config.profile.memfd_extents == crate::profile::MemfdExtents::PleOnly { + "; sparse copy: only the byte ranges the serve path reads, holes elsewhere" + } else { + "" + } ), crate::profile::KarSource::File => "a read-only file (page cache only)".to_owned(), } diff --git a/crates/deploy/src/cli.rs b/crates/deploy/src/cli.rs index 7051808a..baf50666 100644 --- a/crates/deploy/src/cli.rs +++ b/crates/deploy/src/cli.rs @@ -27,6 +27,9 @@ USAGE leleka verify [OPTIONS] hash both shards and the archive in full (in parallel), check the pinned digests, renew the verification stamps that let a restart skip the hashing (needs a prepared state); --quick hashes nothing: it reports the health of the installation (stamps, service, disk, logs) + leleka seal-exec --file PATH [--expect-bytes N] [--sparse-ple] -- COMMAND ARG... + copy the archive into a sealed memfd (--sparse-ple: only the byte ranges the serve path reads, as rtx5090-32g does) + and run COMMAND with the descriptor; {FD} in an argument is its number (Linux; for A/B runs outside `leleka run`) leleka profiles [show NAME] list the memory profiles, or print one as JSON leleka version @@ -199,6 +202,8 @@ pub enum Command { kar_fd: Option, }, ExecInherit(Vec), + /// `leleka seal-exec --file PATH [--expect-bytes N] [--sparse-ple] -- COMMAND ARG...` (Linux). + SealExec(Vec), /// `leleka seal-probe FILE` (not in `--help`): seal FILE into a memfd with the code `leleka run` uses for the archive and compare /// the memfd with the file byte for byte (SHA-256 of both). A measurement and identity tool for the cold-load work. SealProbe(PathBuf), @@ -688,6 +693,7 @@ pub fn parse(args: &[String], env: &Environment) -> Result { up_options(rest, env).map(|options| Command::Service(action, options)) } "exec-inherit" => Ok(Command::ExecInherit(rest.to_vec())), + "seal-exec" => Ok(Command::SealExec(rest.to_vec())), "seal-probe" => match rest { [file] if !file.starts_with("--") => Ok(Command::SealProbe(PathBuf::from(file))), _ => Err("usage: leleka seal-probe FILE".into()), @@ -946,6 +952,10 @@ mod tests { parse_as(false, &["exec-inherit", "--", "x"]).unwrap(), Command::ExecInherit(_) )); + assert!(matches!( + parse_as(false, &["seal-exec", "--file", "f", "--", "x"]).unwrap(), + Command::SealExec(_) + )); assert!(matches!( parse_as(false, &["seal-probe", "/x/y"]).unwrap(), Command::SealProbe(_) diff --git a/crates/deploy/src/plan.rs b/crates/deploy/src/plan.rs index ccabcf47..e6b92ee8 100644 --- a/crates/deploy/src/plan.rs +++ b/crates/deploy/src/plan.rs @@ -265,7 +265,7 @@ pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option) -> Context 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) + crate::resources::with_resident_bytes(&facts, p.memfd_bytes()) } else { facts.clone() }; diff --git a/crates/deploy/src/preflight.rs b/crates/deploy/src/preflight.rs index c8f9f081..3b046b7c 100644 --- a/crates/deploy/src/preflight.rs +++ b/crates/deploy/src/preflight.rs @@ -360,11 +360,11 @@ pub fn evaluate(facts: &Facts, profile: &Profile, needs: &Needs) -> Report { // An inherited sealed archive is already counted in the parent's memory: only the engine's own need remains. let min_available = if needs.kar_fd_inherited { profile - .min_ram_available_bytes - .saturating_sub(ARCHIVE_BYTES) + .min_ram_available() + .saturating_sub(profile.memfd_bytes()) .max(4 * GIB) } else { - profile.min_ram_available_bytes + profile.min_ram_available() }; if ram.available == 0 && ram.total == 0 { checks.push(check( @@ -1085,7 +1085,8 @@ mod tests { #[test] fn an_inherited_sealed_archive_is_not_counted_twice() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + profile.memfd_extents = crate::profile::MemfdExtents::Full; // the full 55 GB copy; the shipped `ple_only` form needs about 39 GB less let mut facts = server_facts(); // 70 GiB available: not enough to copy the archive and hold the 50 GB expert bank, enough when the // parent already holds the sealed archive. diff --git a/crates/deploy/src/profile.rs b/crates/deploy/src/profile.rs index 9a35578e..f4c9ec64 100644 --- a/crates/deploy/src/profile.rs +++ b/crates/deploy/src/profile.rs @@ -30,11 +30,16 @@ pub fn archive_sha256() -> [u8; 32] { /// Bytes of the two pinned IQ3_S GGUF shards. pub const SHARD_BYTES: [u64; 2] = [54_817_524_224, 28_800_138_432]; -pub const BUILTIN: [(&str, &str); 2] = [ +pub const BUILTIN: [(&str, &str); 3] = [ ( "rtx5090-32g", include_str!("../../../deploy/rust-runtime/profiles/rtx5090-32g.json"), ), + // Experimental variant of the server profile (the archive as a read-only file, no 55 GB memfd): never auto-selected (empty window). + ( + "rtx5090-32g-file", + include_str!("../../../deploy/rust-runtime/profiles/rtx5090-32g-file.json"), + ), ( "rtx3080-16g", include_str!("../../../deploy/rust-runtime/profiles/rtx3080-16g.json"), @@ -62,6 +67,61 @@ impl KarSource { } } +/// What the sealed memfd of a `kar_source: memfd` profile holds. `ple_only` is the form of `rtx5090-32g` (one resident copy of every model byte: +/// the memfd holds only what the serve path reads); `full` keeps the whole archive (docs/kar-sparse-memfd.md, scripts/e2e/decode/single-copy-ab.sh). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum MemfdExtents { + /// The whole 55.3 GB archive (today's form). + #[default] + Full, + /// Only the byte ranges the serve path reads (the PLE rows plus header and directory, about 16 GB); the rest of the memfd is a + /// hole. Verified by the pinned digest of those ranges instead of the archive's SHA-256. + PleOnly, +} + +impl MemfdExtents { + pub fn as_str(self) -> &'static str { + match self { + MemfdExtents::Full => "full", + MemfdExtents::PleOnly => "ple_only", + } + } + pub fn is_full(&self) -> bool { + *self == MemfdExtents::Full + } +} + +/// Host RAM a `ple_only` memfd holds: 320,001,536 rows x 50 B = 16,000,076,800 B plus the metadata and page rounding; the exact +/// figure of the real archive printed by `kar_census` (2 extents). +pub const SPARSE_MEMFD_BYTES_ESTIMATE: u64 = 16_000_348_672; + +/// The pinned SHA-256 of the extents of the pinned archive (`leleka_model_format::kar::PLE_EXTENTS_SHA256`), or, while that is not +/// measured yet (all zero), the operator's `LELEKA_KAR_EXTENTS_SHA256` (64 hex digits, from `kar_census --hash-extents` on an +/// archive that matched its full pinned SHA-256). The second form is explicitly experimental and is logged as such. +pub fn extents_sha256(env: &dyn Fn(&str) -> Option) -> Result<([u8; 32], PinSource), String> { + let compiled = leleka_model_format::kar::PLE_EXTENTS_SHA256; + if compiled != [0u8; 32] { + return Ok((compiled, PinSource::Compiled)); + } + let text = env("LELEKA_KAR_EXTENTS_SHA256").ok_or_else(|| { + "memfd_extents=ple_only needs the pinned SHA-256 of the archive's extents, which is not compiled in yet: measure it with `kar_census ARCHIVE --hash-extents` (an archive that matched its full pinned SHA-256) and either commit it as PLE_EXTENTS_SHA256 or set LELEKA_KAR_EXTENTS_SHA256 for this experiment".to_owned() + })?; + let mut out = [0u8; 32]; + hex::decode_to_slice(text.trim(), &mut out).map_err(|_| "LELEKA_KAR_EXTENTS_SHA256 must be 64 hex digits".to_owned())?; + if out == [0u8; 32] { + return Err("LELEKA_KAR_EXTENTS_SHA256 is all zero".into()); + } + Ok((out, PinSource::Operator)) +} + +/// Where the extents pin came from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PinSource { + Compiled, + Operator, +} + /// How the routed experts are admitted (`leleka-inference --expert-source`). #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] @@ -177,6 +237,13 @@ impl MemoryBudget { args } + /// The explicit MiB cap of the prefix cache: `Some(n)` for a number above zero, `None` for `auto`, off or unset. An `auto` cache + /// is sized from the memory that is free when the stack opens (75 % of it, ceiling 96 GiB), so it grows whenever RAM is freed + /// elsewhere; a number never does (`leleka_memory::plan::explicit_prefix_budget`). + pub fn prefix_cache_cap_mib(&self) -> Option { + self.prefix_cache_mib.as_deref()?.parse::().ok().filter(|mib| *mib > 0) + } + /// The prefix cache is configured and not switched off (`0`). pub fn prefix_cache_on(&self) -> bool { self.prefix_cache_mib.as_deref().is_some_and(|mib| mib != "0") @@ -253,6 +320,9 @@ pub struct Profile { #[serde(default)] pub spec_min_p: Option, pub kar_source: KarSource, + /// What the sealed memfd holds (`kar_source: memfd` only; default `full`). + #[serde(default, skip_serializing_if = "MemfdExtents::is_full")] + pub memfd_extents: MemfdExtents, pub expert_source: ExpertSource, pub min_driver_major: u32, pub min_vram_total_mib: u64, @@ -279,6 +349,25 @@ pub struct Profile { } impl Profile { + /// Host RAM the sealed memfd holds for the life of the service (0 for a file-backed archive). + pub fn memfd_bytes(&self) -> u64 { + match (self.kar_source, self.memfd_extents) { + (KarSource::File, _) => 0, + (KarSource::Memfd, MemfdExtents::Full) => ARCHIVE_BYTES, + (KarSource::Memfd, MemfdExtents::PleOnly) => SPARSE_MEMFD_BYTES_ESTIMATE, + } + } + + /// `min_ram_available_bytes` for this profile. The profile figure is written for the full archive copy; a `ple_only` memfd + /// needs that much less. + pub fn min_ram_available(&self) -> u64 { + let saved = match (self.kar_source, self.memfd_extents) { + (KarSource::Memfd, MemfdExtents::PleOnly) => ARCHIVE_BYTES - SPARSE_MEMFD_BYTES_ESTIMATE, + _ => 0, + }; + self.min_ram_available_bytes.saturating_sub(saved) + } + pub fn builtin(name: &str) -> Option { BUILTIN .iter() @@ -310,6 +399,15 @@ impl Profile { } pub fn validate(&self) -> Result<(), String> { + if self.memfd_extents == MemfdExtents::PleOnly { + if self.kar_source != KarSource::Memfd { + return Err("memfd_extents=ple_only needs kar_source=memfd (a file-backed archive has no memfd to make sparse)".into()); + } + // Freed RAM must not be refilled "on purpose" by an `auto` cache (docs/design/memory-single-copy-and-elastic-state.md section B). + if self.memory.prefix_cache_cap_mib().is_none() && self.memory.prefix_cache_on() { + return Err("memfd_extents=ple_only needs an explicit memory.prefix_cache_mib (or 0): `auto` would size the cache from the RAM the sparse memfd frees".into()); + } + } if self.name.is_empty() || self.name.len() > 64 || !self @@ -446,7 +544,36 @@ mod tests { for profile in Profile::builtins() { profile.validate().unwrap(); } - assert_eq!(Profile::builtins().len(), 2); + assert_eq!(Profile::builtins().len(), 3); + } + + #[test] + fn the_file_variant_of_the_server_profile_differs_only_where_the_archive_form_matters() { + let server = Profile::builtin("rtx5090-32g").unwrap(); + let file = Profile::builtin("rtx5090-32g-file").unwrap(); + file.validate().unwrap(); + assert_eq!((file.kar_source, file.expert_source), (KarSource::File, ExpertSource::Resident)); + // same engine configuration: only the archive form, the RAM it needs and the cache budget (explicit, so that the RAM the memfd no longer + // holds is not handed to the prefix cache) and the memfd-only lock/heal switches differ + for (name, same) in [ + ("gpu_budget_bytes", server.gpu_budget_bytes == file.gpu_budget_bytes), + ("context_tokens", server.context_tokens == file.context_tokens), + ("prefill_capacity", server.prefill_capacity == file.prefill_capacity), + ("spec_min_p", server.spec_min_p == file.spec_min_p), + ("expert_profile", server.expert_profile == file.expert_profile), + ("engine_env", server.engine_env == file.engine_env), + ("prefix_cache_tail", server.memory.prefix_cache_tail == file.memory.prefix_cache_tail), + ("prefix_cache_block", server.memory.prefix_cache_block == file.memory.prefix_cache_block), + ("floors", (server.memory.soft_floor_mib, server.memory.hard_floor_mib, server.memory.reserve_mib) == (file.memory.soft_floor_mib, file.memory.hard_floor_mib, file.memory.reserve_mib)), + ] { + assert!(same, "{name} must match rtx5090-32g"); + } + assert_eq!(file.memory.prefix_cache_mib.as_deref(), Some("6144")); + assert!(file.min_ram_available_bytes + ARCHIVE_BYTES - 5_000_000_000 <= server.min_ram_available_bytes, "the file form does not need the archive's RAM"); + // an experimental profile: no GPU is ever matched to it, so `auto` keeps choosing exactly one profile + assert!(!file.matches(&gpu("NVIDIA GeForce RTX 5090", 120, 32607))); + assert_eq!(resolve(None, Some(&gpu("NVIDIA GeForce RTX 5090", 120, 32607))).unwrap().name, "rtx5090-32g"); + assert_eq!(resolve(Some("rtx5090-32g-file"), None).unwrap().kar_source, KarSource::File); } #[test] @@ -538,7 +665,7 @@ mod tests { let server = Profile::builtin("rtx5090-32g").unwrap(); assert_eq!( server.memory.args(), - ["--prefix-cache-mib", "auto", "--prefix-cache-tail", "reply", "--prefix-cache-block", "8192"].map(str::to_owned).to_vec() + ["--prefix-cache-mib", "6144", "--prefix-cache-tail", "reply", "--prefix-cache-block", "8192"].map(str::to_owned).to_vec() ); let mut bad = server.memory.clone(); bad.prefix_cache_tail = Some("always".into()); @@ -558,6 +685,116 @@ mod tests { } } + #[test] + fn the_5090_profile_carries_an_explicit_prefix_cap_so_freed_ram_cannot_grow_the_store() { + let server = Profile::builtin("rtx5090-32g").unwrap(); + // 6144 MiB = what `auto` resolves to on this host today (5.7-6.1 GiB, docs/memory-safety.md section 8): behaviour at 245k is unchanged + assert_eq!(server.memory.prefix_cache_cap_mib(), Some(6144)); + assert!(server.memory.prefix_cache_on()); + assert!(server.memory.args().windows(2).any(|w| w == ["--prefix-cache-mib", "6144"])); + // a cache that fits the cap with room to spare: 245k tokens x 14,208 B + ~4 nodes of ~127 MiB is about 4 GiB + let session_245k = 245_000u64 * 14_208 + 4 * (127 << 20); + assert!(session_245k < 6144 << 20, "{session_245k}"); + // `auto`, `0`, off and unset are not caps + for (value, cap) in [(Some("auto"), None), (Some("0"), None), (None, None), (Some("8192"), Some(8192))] { + let mut memory = server.memory.clone(); + memory.prefix_cache_mib = value.map(str::to_owned); + assert_eq!(memory.prefix_cache_cap_mib(), cap, "{value:?}"); + } + // the dedicated memfd profile must keep an explicit cap; the laptop (file archive, mapped experts) is a different machine + for profile in Profile::builtins().iter().filter(|p| p.kar_source == KarSource::Memfd) { + assert!(profile.memory.prefix_cache_cap_mib().is_some(), "{} uses `auto`", profile.name); + } + } + + fn sparse_server() -> Profile { + Profile::builtin("rtx5090-32g").unwrap() + } + + #[test] + fn only_the_5090_profile_uses_a_sparse_memfd_and_full_is_never_serialized() { + for profile in Profile::builtins() { + let want = if profile.name == "rtx5090-32g" { MemfdExtents::PleOnly } else { MemfdExtents::Full }; + assert_eq!(profile.memfd_extents, want, "{}", profile.name); + assert_eq!(serde_json::to_string(&profile).unwrap().contains("\"memfd_extents\":"), want == MemfdExtents::PleOnly, "{}", profile.name); + } + let mut full = sparse_server(); + full.memfd_extents = MemfdExtents::Full; + assert!(!serde_json::to_string(&full).unwrap().contains("\"memfd_extents\":")); + let text = serde_json::to_string(&sparse_server()).unwrap(); + assert!(text.contains("\"memfd_extents\":\"ple_only\""), "{text}"); + let back: Profile = serde_json::from_str(&text).unwrap(); + assert_eq!(back, sparse_server()); + let mut value: serde_json::Value = serde_json::from_str(&serde_json::to_string(&Profile::builtin("rtx5090-32g").unwrap()).unwrap()).unwrap(); + value["memfd_extents"] = "everything".into(); + assert!(serde_json::from_value::(value).is_err()); + } + + #[test] + fn a_sparse_memfd_profile_needs_a_memfd_and_an_explicit_prefix_cap() { + sparse_server().validate().unwrap(); + // 0 (cache off) and any number are fine; `auto` would refill the freed RAM + for (value, ok) in [("6144", true), ("0", true), ("auto", false)] { + let mut profile = sparse_server(); + profile.memory.prefix_cache_mib = Some(value.into()); + assert_eq!(profile.validate().is_ok(), ok, "{value}"); + } + let mut profile = sparse_server(); + profile.memory.prefix_cache_mib = None; + assert!(profile.validate().is_ok(), "no cache at all cannot refill anything"); + let mut file_backed = sparse_server(); + file_backed.kar_source = KarSource::File; + let error = file_backed.validate().unwrap_err(); + assert!(error.contains("ple_only") && error.contains("memfd"), "{error}"); + // the same profile in the full form validates with `auto` + let mut full = Profile::builtin("rtx5090-32g").unwrap(); + full.memfd_extents = MemfdExtents::Full; + full.memory.prefix_cache_mib = Some("auto".into()); + full.validate().unwrap(); + } + + #[test] + fn a_sparse_memfd_holds_a_third_of_the_archive_and_lowers_the_ram_the_profile_asks_for() { + let mut full = Profile::builtin("rtx5090-32g").unwrap(); + full.memfd_extents = MemfdExtents::Full; + let sparse = sparse_server(); + assert_eq!(full.memfd_bytes(), ARCHIVE_BYTES); + assert_eq!(sparse.memfd_bytes(), SPARSE_MEMFD_BYTES_ESTIMATE); + // 320,001,536 rows x 50 B = 16,000,076,800 B are the floor of what the serve path reads + const { assert!(SPARSE_MEMFD_BYTES_ESTIMATE > 16_000_076_800 && SPARSE_MEMFD_BYTES_ESTIMATE < ARCHIVE_BYTES / 3) }; + assert_eq!(full.min_ram_available(), full.min_ram_available_bytes); + assert_eq!(sparse.min_ram_available(), full.min_ram_available_bytes - (ARCHIVE_BYTES - SPARSE_MEMFD_BYTES_ESTIMATE)); + assert!(sparse.min_ram_available() > 70_000_000_000 && sparse.min_ram_available() < 80_000_000_000); + let laptop = Profile::builtin("rtx3080-16g").unwrap(); + assert_eq!((laptop.memfd_bytes(), laptop.min_ram_available()), (0, laptop.min_ram_available_bytes)); + } + + #[test] + fn the_extents_pin_is_the_compiled_one_or_an_explicit_operator_value_and_never_silent() { + let none = |_: &str| None; + let with = |value: &str| { + let value = value.to_owned(); + move |key: &str| (key == "LELEKA_KAR_EXTENTS_SHA256").then(|| value.clone()) + }; + let hex64 = "ab".repeat(32); + let zeros = "00".repeat(32); + let compiled = leleka_model_format::kar::PLE_EXTENTS_SHA256; + if compiled == [0u8; 32] { + // not measured yet: the sparse form refuses to start without an explicit value, and says how to get one + let error = extents_sha256(&none).unwrap_err(); + assert!(error.contains("kar_census") && error.contains("--hash-extents"), "{error}"); + assert!(extents_sha256(&with("zz")).unwrap_err().contains("64 hex")); + assert!(extents_sha256(&with("abcd")).unwrap_err().contains("64 hex")); + assert!(extents_sha256(&with(&zeros)).unwrap_err().contains("zero")); + let (pin, source) = extents_sha256(&with(&hex64)).unwrap(); + assert_eq!((pin, source), ([0xab; 32], PinSource::Operator)); + } else { + // measured: the binary's value wins and an environment value cannot override it + assert_eq!(extents_sha256(&none).unwrap(), (compiled, PinSource::Compiled)); + assert_eq!(extents_sha256(&with(&hex64)).unwrap(), (compiled, PinSource::Compiled)); + } + } + #[test] fn memory_budget_validation_rejects_nonsense() { let mut profile = Profile::builtin("rtx5090-32g").unwrap(); diff --git a/crates/deploy/src/reconfigure.rs b/crates/deploy/src/reconfigure.rs index 1fe22aed..97a86468 100644 --- a/crates/deploy/src/reconfigure.rs +++ b/crates/deploy/src/reconfigure.rs @@ -342,7 +342,7 @@ pub fn plan( base.validate()?; let mut profile = base.clone(); - let seen = if archive_resident { resources::with_resident_archive(facts) } else { facts.clone() }; + let seen = if archive_resident { resources::with_resident_bytes(facts, profile.memfd_bytes()) } else { facts.clone() }; let gpu = gpu_of(&seen, config.gpu).cloned(); let resources = resources::compute(&seen, gpu.as_ref(), &profile, preset); if !resources.problems.is_empty() { @@ -546,7 +546,8 @@ mod tests { engine: "127.0.0.1:18766".into(), daemon: "127.0.0.1:18080".into(), }; - let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + profile.memfd_extents = crate::profile::MemfdExtents::Full; // the tests describe the full copy; the shipped profile is `ple_only` // `up` resolved the dedicated preset's worker count into the environment let env = BTreeMap::from([(CPU_WORKERS_ENV.to_owned(), "15".to_owned())]); let mut config = RunConfig::new(&dirs, ports, 0, profile.clone(), env); @@ -686,6 +687,8 @@ mod tests { #[test] fn the_prefix_cache_can_be_switched_off_and_a_member_alone_turns_it_on() { let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + // a `ple_only` profile refuses an `auto` cache (the freed RAM would be refilled); the full form accepts it + profile.memfd_extents = crate::profile::MemfdExtents::Full; profile.memory.prefix_cache_mib = None; apply_settings( &mut profile, diff --git a/crates/deploy/src/resources.rs b/crates/deploy/src/resources.rs index fc09a8d3..795873fa 100644 --- a/crates/deploy/src/resources.rs +++ b/crates/deploy/src/resources.rs @@ -144,8 +144,13 @@ pub fn workstation_ram_target(total: u64) -> u64 { /// descriptor a running supervisor holds): its pages are already missing from `MemAvailable`, and `compute` charges the archive to the /// footprint of the pinned form, so without this the archive is paid for twice and a host that fits is told it does not. pub fn with_resident_archive(facts: &Facts) -> Facts { + with_resident_bytes(facts, ARCHIVE_BYTES) +} + +/// [`with_resident_archive`] for a memfd of `bytes` (a `ple_only` memfd holds about 16 GB, not 55). +pub fn with_resident_bytes(facts: &Facts, bytes: u64) -> Facts { let mut facts = facts.clone(); - facts.memory.available = facts.memory.available.saturating_add(ARCHIVE_BYTES); + facts.memory.available = facts.memory.available.saturating_add(bytes); facts } @@ -227,9 +232,12 @@ pub fn compute(facts: &Facts, gpu: Option<&Gpu>, profile: &Profile, preset: Pres let soft = target / MIB; plan.ram_floors_mib = Some((soft, soft / 2)); } - if profile.kar_source == KarSource::Memfd { + // The sealed memfd holds the whole archive; a file-backed archive with a resident expert bank (rtx5090-32g-file) holds only the bank and + // the engine's pins, its archive pages are page cache that the kernel gives back. The mapped file form (laptop) is already the low tier. + let resident_file = profile.kar_source == KarSource::File && profile.expert_source == ExpertSource::Resident; + if profile.kar_source == KarSource::Memfd || resident_file { let engine = if profile.expert_source == ExpertSource::Resident { ENGINE_FIXED_RESIDENT_BYTES } else { ENGINE_EXTRA_BYTES }; - let footprint = ARCHIVE_BYTES + engine; + let footprint = if resident_file { engine } else { profile.memfd_bytes() + engine }; let after = ram.available.saturating_sub(footprint); let reserve = profile.memory.reserve_mib.map_or(DEFAULT_RESERVE_BYTES, |mib| mib * MIB); if after >= target + reserve { @@ -241,10 +249,11 @@ pub fn compute(facts: &Facts, gpu: Option<&Gpu>, profile: &Profile, preset: Pres plan.mapped_resident_gib = Some(resident); plan.ram_expected_free_after_bytes = Some(ram.available.saturating_sub(u64::from(resident) * GIB + MAPPED_OVERHEAD_BYTES)); plan.warnings.push(format!( - "{} of host RAM available, the pinned form needs about {} plus {} free: the archive and the experts are served from disk (memory-mapped), {} GiB of experts stay page-locked; decode is slower than with everything in RAM", + "{} of host RAM available, the pinned form needs about {} plus {} free: {} served from disk (memory-mapped), {} GiB of experts stay page-locked; decode is slower than with everything in RAM", gib_text(ram.available), gib_text(footprint), gib_text(target), + if resident_file { "the experts are" } else { "the archive and the experts are" }, resident )); } @@ -296,6 +305,7 @@ pub fn apply( } if let Some(resident) = plan.mapped_resident_gib { profile.kar_source = KarSource::File; + profile.memfd_extents = crate::profile::MemfdExtents::Full; profile.expert_source = ExpertSource::Mapped; profile.memory.resident_budget_gib.get_or_insert(resident); profile.memory.lock = Some("off".into()); @@ -380,6 +390,7 @@ impl ResourcePlan { mod tests { use super::*; use crate::facts::Memory; + use crate::profile::SPARSE_MEMFD_BYTES_ESTIMATE; fn gpu(total: u64, free: u64) -> Gpu { Gpu { index: 0, name: "gpu".into(), driver: "595.1".into(), vram_total_mib: total, vram_free_mib: free, sm: Some(120) } @@ -393,8 +404,11 @@ mod tests { } } + /// The full-copy form of the server profile (the shipped profile is `ple_only`; the tests below build that explicitly). fn server() -> Profile { - Profile::builtin("rtx5090-32g").unwrap() + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + profile.memfd_extents = crate::profile::MemfdExtents::Full; + profile } fn laptop() -> Profile { Profile::builtin("rtx3080-16g").unwrap() @@ -500,6 +514,38 @@ mod tests { assert!(env.is_empty()); } + #[test] + fn a_sparse_memfd_fits_a_host_the_full_copy_does_not_and_a_resident_one_is_credited_by_its_own_size() { + // 80 GiB available at start: the full pinned form (55.3 GB memfd + the engine's 54 GiB) does not fit next to the 4 GiB target and + // the 2 GiB reserve and is sent to the mapped form; with a 16 GB memfd it does + let facts = host(32, 121, 80); + let gpu = gpu(32607, 32100); + let full = compute(&facts, Some(&gpu), &server(), Preset::Dedicated); + assert!(full.mapped_resident_gib.is_some(), "{:?}", full.warnings); + let mut sparse = server(); + sparse.memfd_extents = crate::profile::MemfdExtents::PleOnly; + let plan = compute(&facts, Some(&gpu), &sparse, Preset::Dedicated); + assert_eq!(plan.mapped_resident_gib, None, "{:?}", plan.warnings); + assert_eq!( + plan.ram_expected_free_after_bytes, + Some(80 * GIB - (SPARSE_MEMFD_BYTES_ESTIMATE + ENGINE_FIXED_RESIDENT_BYTES)), + "the footprint is the sparse memfd plus the engine's own memory" + ); + // a resident sparse memfd is credited with its own size, not the archive's + let resident = host(32, 121, 66); + let credited = with_resident_bytes(&resident, sparse.memfd_bytes()); + assert_eq!(credited.memory.available, 66 * GIB + SPARSE_MEMFD_BYTES_ESTIMATE); + assert_eq!(with_resident_archive(&resident).memory.available, 66 * GIB + ARCHIVE_BYTES); + // a plan that falls back to the mapped form is a different machine: the sparse switch is dropped with the memfd + let tiny = host(32, 121, 2); + let mut profile = sparse.clone(); + let fallback = compute(&tiny, Some(&gpu), &profile, Preset::Dedicated); + assert!(fallback.mapped_resident_gib.is_some()); + apply(&fallback, &mut profile, &mut BTreeMap::new(), false); + assert_eq!((profile.kar_source, profile.memfd_extents), (KarSource::File, crate::profile::MemfdExtents::Full)); + profile.validate().unwrap(); + } + #[test] fn a_resident_sealed_archive_is_not_charged_to_the_footprint_twice() { // the server with the 51.5 GiB memfd already resident: 121 GiB total, 66 GiB available (what the supervisor sees before the engine starts) @@ -516,6 +562,27 @@ mod tests { assert!(with_resident_archive(&host(1, 1, u64::MAX / GIB)).memory.available >= u64::MAX / 2); } + #[test] + fn the_file_form_of_the_server_profile_is_charged_the_engine_only_not_the_archive() { + let file = Profile::builtin("rtx5090-32g-file").unwrap(); + assert_eq!((file.kar_source, file.expert_source), (KarSource::File, ExpertSource::Resident)); + // 121 GiB host with 100 GiB available and no holder: the 54 GiB of the engine fit; the 55 GB archive is page cache, not a charge + let plan = compute(&host(32, 121, 100), Some(&gpu(32607, 32100)), &file, Preset::Dedicated); + assert_eq!(plan.mapped_resident_gib, None); + assert_eq!(plan.ram_expected_free_after_bytes, Some(46 * GIB)); + // the same host is already too small for the memfd profile once it has to create the archive copy + assert!(compute(&host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Dedicated).mapped_resident_gib.is_some()); + // a host that cannot hold the bank is sent to the mapped form, and the warning does not claim the archive moves + let small = host(32, 64, 50); + let plan = compute(&small, Some(&gpu(32607, 32100)), &file, Preset::Dedicated); + assert!(plan.mapped_resident_gib.is_some()); + assert!(plan.warnings[0].contains("the experts are served from disk") && !plan.warnings[0].contains("the archive and"), "{:?}", plan.warnings); + let mut applied = file.clone(); + apply(&plan, &mut applied, &mut BTreeMap::new(), false); + assert_eq!((applied.kar_source, applied.expert_source), (KarSource::File, ExpertSource::Mapped)); + applied.validate().unwrap(); + } + #[test] fn unknown_core_count_leaves_the_engine_default() { let plan = compute(&host(0, 121, 100), None, &server(), Preset::Workstation); diff --git a/crates/deploy/src/sealed.rs b/crates/deploy/src/sealed.rs index 921a18a3..7cb00427 100644 --- a/crates/deploy/src/sealed.rs +++ b/crates/deploy/src/sealed.rs @@ -49,6 +49,23 @@ pub fn seal_file_report( Err("sealed memfd archives require Linux".into()) } +#[cfg(not(target_os = "linux"))] +pub fn seal_extents_report( + _path: &std::path::Path, + _expect_bytes: Option, + _extents: &[leleka_model_format::kar::Extent], + _progress: &mut dyn FnMut(u64, u64), +) -> Result< + ( + std::fs::File, + Option, + leleka_model_format::bulk_read::Report, + ), + String, +> { + Err("sealed memfd archives require Linux".into()) +} + #[cfg(not(target_os = "linux"))] pub fn check_inherited_archive(_fd: u32, _expect_bytes: u64) -> Result<(), String> { Err("inherited descriptors require Linux".into()) @@ -64,6 +81,64 @@ pub fn exec_inherit(_args: &[String]) -> Result Result { + Err("seal-exec requires Linux".into()) +} + +/// The page-aligned ranges of the archive file at `kar` that the serve path reads, from its header and directory (about a megabyte of +/// reads, none of the payload). Refuses a file that is not a valid KAR archive of `expect_bytes`. +pub fn archive_serve_extents(kar: &std::path::Path, expect_bytes: u64) -> Result, String> { + use leleka_model_format::kar::{KarInspection, PLE_PART_NAMES}; + let file = std::fs::File::open(kar).map_err(|e| format!("cannot open {}: {e}", kar.display()))?; + let inspection = KarInspection::inspect(file).map_err(|e| format!("{} is not a valid KAR archive: {e}", kar.display()))?; + if inspection.summary().archive_bytes != expect_bytes { + return Err(format!("{} has {} bytes, expected {expect_bytes}", kar.display(), inspection.summary().archive_bytes)); + } + inspection + .serve_reads(&PLE_PART_NAMES) + .map(|reads| reads.extents) + .map_err(|e| format!("cannot derive the sparse extents of {}: {e}", kar.display())) +} + +/// What `leleka seal-exec` was asked to do. +#[derive(Debug, PartialEq, Eq)] +pub struct SealExecPlan { + pub file: std::path::PathBuf, + pub expect_bytes: Option, + /// Copy only the extents the serve path reads (`memfd_extents: ple_only`, experimental). + pub sparse_ple: bool, + pub command: Vec, +} + +/// `--file PATH [--expect-bytes N] [--sparse-ple] -- COMMAND ARG...` +pub fn parse_seal_exec(args: &[String]) -> Result { + let usage = "usage: leleka seal-exec --file PATH [--expect-bytes N] [--sparse-ple] -- COMMAND ARG... ({FD} marks the sealed descriptor)"; + let (mut file, mut expect_bytes, mut sparse_ple) = (None, None, false); + let mut i = 0; + while i < args.len() { + match args[i].as_str() { + "--" => break, + "--file" => { + i += 1; + file = Some(std::path::PathBuf::from(args.get(i).filter(|v| !v.is_empty()).ok_or(usage)?)); + } + "--expect-bytes" => { + i += 1; + expect_bytes = Some(args.get(i).and_then(|v| v.parse::().ok()).ok_or(usage)?); + } + "--sparse-ple" => sparse_ple = true, + _ => return Err(usage.into()), + } + i += 1; + } + let command: Vec = args.get(i + 1..).unwrap_or_default().to_vec(); + if args.get(i).map(String::as_str) != Some("--") || command.is_empty() { + return Err(usage.into()); + } + Ok(SealExecPlan { file: file.ok_or(usage)?, expect_bytes, sparse_ple, command }) +} + pub const PLACEHOLDER: &str = "{FD}"; /// Replace every `{FD}` in `args`. @@ -76,7 +151,7 @@ pub fn substitute(args: &[String], number: i32) -> Vec { #[cfg(target_os = "linux")] mod linux { use super::substitute; - use leleka_model_format::verify_stamp::FileIdentity; + use leleka_model_format::{kar::Extent, verify_stamp::FileIdentity}; use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, fcntl_get_seals, memfd_create}; use std::{ convert::Infallible, @@ -113,9 +188,7 @@ mod linux { seal_file_with_identity(path, expect_bytes, progress).map(|(file, _)| file) } - /// As [`seal_file`], copying with several threads (positional reads and writes of disjoint 32 MiB ranges into - /// a memfd of the final size, so a 55 GB fill runs at memory bandwidth instead of one core's `read`+`write` - /// loop), and returning the identity of the source file when it is a stable one. The identity is taken from the + /// As [`seal_file`], returning the identity of the source file when it is a stable one. The identity is taken from the /// opened file before the first byte and again after the last; a source that changed while it was copied is /// refused, so the identity describes exactly the bytes that are in the memfd. pub fn seal_file_with_identity( @@ -131,6 +204,58 @@ mod linux { path: &Path, expect_bytes: Option, progress: &mut dyn FnMut(u64, u64), + ) -> Result<(File, Option, leleka_model_format::bulk_read::Report), String> { + seal_ranges(path, expect_bytes, None, progress) + } + + /// A **sparse** sealed memfd: the final length of the archive, but only `extents` are copied; every byte outside them is + /// a hole (no page is allocated, a read returns zeros). File offsets are identical to the archive's, so a reader needs no + /// change. The extents must be sorted, disjoint, page-aligned at the start and inside the archive. The memfd is sealed + /// like the full one, but it is NOT the archive: the engine verifies it against the pinned digest of the extents + /// (`VerifiedKarPleArtifact::verify_sparse`), never against the archive's SHA-256, and the identity returned here must not be + /// used to record a verification stamp of the archive. + pub fn seal_extents( + path: &Path, + expect_bytes: Option, + extents: &[Extent], + progress: &mut dyn FnMut(u64, u64), + ) -> Result<(File, Option), String> { + seal_extents_report(path, expect_bytes, extents, progress).map(|(file, identity, _)| (file, identity)) + } + + /// As [`seal_extents`], also returning how the file was read. + pub fn seal_extents_report( + path: &Path, + expect_bytes: Option, + extents: &[Extent], + progress: &mut dyn FnMut(u64, u64), + ) -> Result<(File, Option, leleka_model_format::bulk_read::Report), String> { + seal_ranges(path, expect_bytes, Some(extents), progress) + } + + fn check_extents(extents: &[Extent], total: u64) -> Result<(), String> { + let mut previous_end = 0; + for (i, e) in extents.iter().enumerate() { + if e.len == 0 + || e.offset % leleka_model_format::kar::EXTENT_ALIGN != 0 + || e.offset < previous_end + || e.offset.checked_add(e.len).is_none_or(|end| end > total) + { + return Err(format!( + "extent {i} ({}+{}) is empty, unaligned, out of order or outside the {total}-byte archive", + e.offset, e.len + )); + } + previous_end = e.end(); + } + Ok(()) + } + + fn seal_ranges( + path: &Path, + expect_bytes: Option, + extents: Option<&[Extent]>, + progress: &mut dyn FnMut(u64, u64), ) -> Result<(File, Option, leleka_model_format::bulk_read::Report), String> { let source = File::open(path).map_err(|e| format!("cannot open {}: {e}", path.display()))?; @@ -149,20 +274,30 @@ mod linux { )); } let identity_before = FileIdentity::of(&metadata); + let total = metadata.len(); + let whole = [Extent::new(0, total)]; + let ranges: &[Extent] = match extents { + Some(extents) => { + check_extents(extents, total)?; + extents + } + None => &whole, + }; + let want: u64 = ranges.iter().map(|r| r.len).sum(); let fd = memfd_create( "leleka-sealed-archive", MemfdFlags::ALLOW_SEALING | MemfdFlags::CLOEXEC, ) .map_err(|e| format!("memfd_create failed: {e}"))?; let memory = File::from(fd); - let total = metadata.len(); let report: Mutex> = Mutex::new(None); // The final size first (before the GROW seal exists), so that workers write disjoint ranges. memory .set_len(total) .map_err(|e| format!("cannot size the memfd (out of memory?): {e}"))?; // Large blocks on many threads (O_DIRECT where the file system allows it): the device sees a deep queue - // instead of one 128 KiB readahead window at a time, and the 55 GB never enters the page cache. + // instead of one 128 KiB readahead window at a time, and what is copied never enters the page cache, so the + // memfd is the only copy of it in RAM (a sparse copy reads each of its extents the same way and nothing else). let plan = leleka_model_format::bulk_read::Plan::from_env(); let copied = AtomicU64::new(0); let finished = AtomicBool::new(false); @@ -177,33 +312,46 @@ mod linux { } } let _finished = Finished(&finished); - let outcome = leleka_model_format::bulk_read::for_each_chunk( - &source, - 0, - total, - plan, - |offset, data| { - memory.write_all_at(data, offset).map_err(|e| { - std::io::Error::other(format!( - "write to memfd failed (out of memory?): {e}" - )) - })?; - copied.fetch_add(data.len() as u64, Ordering::Relaxed); - Ok(()) - }, - ); - match outcome { - Ok(done) => { - if let Ok(mut slot) = report.lock() { - *slot = Some(done); + let mut strategy = None; + let mut elapsed = std::time::Duration::ZERO; + for range in ranges { + let outcome = leleka_model_format::bulk_read::for_each_chunk( + &source, + range.offset, + range.len, + plan, + |offset, data| { + memory.write_all_at(data, offset).map_err(|e| { + std::io::Error::other(format!( + "write to memfd failed (out of memory?): {e}" + )) + })?; + copied.fetch_add(data.len() as u64, Ordering::Relaxed); + Ok(()) + }, + ); + match outcome { + Ok(done) => { + strategy = Some(done.strategy); + elapsed += done.elapsed; } - } - Err(e) => { - if let Ok(mut f) = failure.lock() { - f.get_or_insert(format!("read failed: {e}")); + Err(e) => { + if let Ok(mut f) = failure.lock() { + f.get_or_insert(format!("read failed: {e}")); + } + return; } } } + // No extents at all is a valid (empty) sparse copy: nothing was read. + let strategy = strategy.unwrap_or(leleka_model_format::bulk_read::Strategy::Plain); + if let Ok(mut slot) = report.lock() { + *slot = Some(leleka_model_format::bulk_read::Report { + strategy, + bytes: want, + elapsed, + }); + } }); let mut reported = 0u64; while !finished.load(Ordering::Acquire) { @@ -211,14 +359,14 @@ mod linux { let now = copied.load(Ordering::Relaxed); if now - reported >= 4 << 30 { reported = now; - progress(now, total); + progress(now, want); } } }); if let Some(message) = failure.into_inner().ok().flatten() { return Err(message); } - if copied.load(Ordering::Relaxed) != total { + if copied.load(Ordering::Relaxed) != want { return Err("the archive changed while it was being copied".into()); } let identity_after = source.metadata().ok().and_then(|m| FileIdentity::of(&m)); @@ -232,7 +380,7 @@ mod linux { { return Err("the kernel did not apply every seal".into()); } - progress(total, total); + progress(want, want); let report = report .into_inner() .ok() @@ -302,6 +450,44 @@ mod linux { Err(format!("cannot execute {:?}: {error}", command[0])) } + /// `leleka seal-exec --file PATH [--expect-bytes N] [--sparse-ple] -- COMMAND ARG...`: copy the archive (or only the extents + /// the serve path reads) into a sealed memfd and replace this process with COMMAND, which inherits the descriptor (every `{FD}` in + /// its arguments is the number). The Rust form of `leleka-seal-exec`, with the sparse copy. Nothing is verified here: the engine + /// verifies the memfd it is given (the archive SHA-256, or with `--sparse-ple` the pinned digest of the extents). + pub fn seal_exec(args: &[String]) -> Result { + let plan = super::parse_seal_exec(args)?; + let started = std::time::Instant::now(); + let mut progress = |done: u64, total: u64| { + eprintln!("leleka seal-exec: {:.1} of {:.1} GiB", done as f64 / 1073741824.0, total as f64 / 1073741824.0); + }; + let (memory, extents) = if plan.sparse_ple { + let expect = plan.expect_bytes.ok_or("--sparse-ple needs --expect-bytes (the pinned archive length)")?; + let extents = super::archive_serve_extents(&plan.file, expect)?; + let (memory, _) = seal_extents(&plan.file, Some(expect), &extents, &mut progress)?; + (memory, Some(extents)) + } else { + (seal_file(&plan.file, plan.expect_bytes, &mut progress)?, None) + }; + let moved = rustix::io::dup(memory.as_fd()).map_err(|e| format!("cannot duplicate the sealed descriptor: {e}"))?; + let number = moved.into_raw_fd(); + if number < 3 { + return Err("the sealed descriptor landed on a standard stream".into()); + } + let length = memory.metadata().map(|m| m.len()).unwrap_or(0); + eprintln!( + "leleka seal-exec: sealed memfd fd={number} bytes={length}{} in {:.1}s", + extents.as_ref().map_or(String::new(), |e| format!( + " (SPARSE: {} extents, {:.3} GiB held, the rest is a hole)", + e.len(), + leleka_model_format::kar::extents_bytes(e) as f64 / 1073741824.0 + )), + started.elapsed().as_secs_f64() + ); + let arguments = substitute(&plan.command[1..], number); + let error = Command::new(&plan.command[0]).args(arguments).exec(); + Err(format!("cannot execute {:?}: {error}", plan.command[0])) + } + #[cfg(test)] mod tests { use super::*; @@ -364,6 +550,73 @@ mod linux { std::fs::remove_file(path).unwrap(); } + fn blocks_bytes(f: &File) -> u64 { + f.metadata().unwrap().blocks() * 512 + } + + #[test] + fn a_sparse_seal_copies_only_the_extents_keeps_every_offset_and_leaves_holes() { + let path = std::env::temp_dir().join(format!("leleka-sparse-{}", std::process::id())); + // Two full chunks and a bit, so extents span and split across the 32 MiB pieces. + let size = COPY_CHUNK * 2 + 4096 * 5 + 77; + let payload: Vec = (0..size).map(|n| (((n / 4096) as u8).wrapping_mul(31) ^ (n as u8)) | 1).collect(); + std::fs::write(&path, &payload).unwrap(); + let extents = [ + Extent::new(0, 8192), + Extent::new(COPY_CHUNK as u64 - 4096, 3 * 4096), + Extent::new(COPY_CHUNK as u64 * 2 + 4096 * 3, 4096 * 2 + 77), + ]; + let want: u64 = extents.iter().map(|e| e.len).sum(); + let mut calls = Vec::new(); + let (mut sealed, identity) = + seal_extents(&path, Some(size as u64), &extents, &mut |a, b| calls.push((a, b))).unwrap(); + assert!(identity.is_some()); + assert_eq!(calls.last(), Some(&(want, want)), "progress counts the extent bytes"); + // the memfd has the archive's length and the archive's seals + let meta = sealed.metadata().unwrap(); + assert!(meta.nlink() == 0 && meta.len() == size as u64); + assert!(fcntl_get_seals(&sealed).unwrap().contains(SEALS)); + assert!(sealed.write(b"x").is_err() && sealed.set_len(1).is_err()); + // only the extents were allocated: pages of data, no page for any hole + let pages = |e: &Extent| (e.end().div_ceil(4096) - e.offset / 4096) * 4096; + assert_eq!(blocks_bytes(&sealed), extents.iter().map(pages).sum::()); + assert!(blocks_bytes(&sealed) < size as u64 / 4); + // extents hold the source's bytes at the same offsets; holes read as zeros + let mut copy = vec![0u8; size]; + sealed.read_exact_at(&mut copy, 0).unwrap(); + for (offset, byte) in copy.iter().enumerate() { + let inside = extents.iter().any(|e| (offset as u64) >= e.offset && (offset as u64) < e.end()); + assert_eq!(*byte, if inside { payload[offset] } else { 0 }, "offset {offset}"); + } + // reading the holes did not allocate them either + assert_eq!(blocks_bytes(&sealed), extents.iter().map(pages).sum::()); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn a_sparse_seal_refuses_extents_that_are_empty_unaligned_unsorted_or_outside_and_a_wrong_length() { + let path = std::env::temp_dir().join(format!("leleka-sparse-bad-{}", std::process::id())); + std::fs::write(&path, vec![7u8; 5 * 4096]).unwrap(); + let size = Some(5 * 4096); + for bad in [ + vec![Extent::new(0, 0)], + vec![Extent::new(1, 4096)], + vec![Extent::new(4096, 4096), Extent::new(0, 4096)], + vec![Extent::new(0, 8192), Extent::new(4096, 4096)], + vec![Extent::new(4 * 4096, 2 * 4096)], + vec![Extent::new(u64::MAX - 4095, 4096)], + ] { + let e = seal_extents(&path, size, &bad, &mut |_, _| {}).err().unwrap_or_else(|| panic!("{bad:?} accepted")); + assert!(e.contains("extent"), "{e}"); + } + assert!(seal_extents(&path, Some(1), &[Extent::new(0, 4096)], &mut |_, _| {}).is_err()); + // no extents at all is a valid (empty) sparse memfd, not the full copy + let (empty, _) = seal_extents(&path, size, &[], &mut |_, _| {}).unwrap(); + assert_eq!(blocks_bytes(&empty), 0); + assert_eq!(empty.metadata().unwrap().len(), 5 * 4096); + std::fs::remove_file(path).unwrap(); + } + #[test] fn exec_inherit_needs_a_command() { assert!(exec_inherit(&[]).is_err()); @@ -377,6 +630,49 @@ mod linux { mod tests { use super::*; + fn words(text: &str) -> Vec { + text.split_whitespace().map(str::to_owned).collect() + } + + #[test] + fn seal_exec_arguments_are_parsed_strictly() { + let plan = parse_seal_exec(&words("--file /a/b.kar --expect-bytes 55 --sparse-ple -- bash -c x{FD}")).unwrap(); + assert_eq!( + plan, + SealExecPlan { + file: "/a/b.kar".into(), + expect_bytes: Some(55), + sparse_ple: true, + command: words("bash -c x{FD}") + } + ); + let full = parse_seal_exec(&words("--file f -- true")).unwrap(); + assert!(!full.sparse_ple && full.expect_bytes.is_none()); + for bad in [ + "", + "--file f", + "--file f --", + "-- true", + "--file -- true", + "--file f --expect-bytes x -- true", + "--file f --expect-bytes -- true", + "--file f --bogus -- true", + "--file f true", + ] { + assert!(parse_seal_exec(&words(bad)).is_err(), "{bad:?}"); + } + } + + #[test] + fn archive_serve_extents_refuses_what_is_not_the_pinned_archive() { + let path = std::env::temp_dir().join(format!("leleka-not-a-kar-{}", std::process::id())); + std::fs::write(&path, vec![0u8; 4096]).unwrap(); + let error = archive_serve_extents(&path, 4096).unwrap_err(); + assert!(error.contains("not a valid KAR archive"), "{error}"); + assert!(archive_serve_extents(std::path::Path::new("/definitely/not/here"), 1).unwrap_err().contains("cannot open")); + std::fs::remove_file(path).unwrap(); + } + #[test] fn placeholder_substitution() { let args = vec![ diff --git a/crates/deploy/src/supervisor.rs b/crates/deploy/src/supervisor.rs index 5ce995f8..1423fa95 100644 --- a/crates/deploy/src/supervisor.rs +++ b/crates/deploy/src/supervisor.rs @@ -10,7 +10,7 @@ use crate::{ facts::parse_env_file, http, layout::{MTP_PROFILE, Paths}, - profile::{ARCHIVE_BYTES, KarSource, archive_sha256}, + profile::{ARCHIVE_BYTES, KarSource, MemfdExtents, PinSource, archive_sha256, extents_sha256}, logs, reconfigure, sealed, watchdog, }; use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps}; @@ -105,6 +105,7 @@ struct StatusDoc<'a> { model_digest: &'a str, profile: &'a str, kar_source: &'a str, + memfd_extents: &'a str, /// When this supervisor started (service uptime = now - this). started_unix: u64, /// Engine restarts since the service started (crashes, hangs, failed restarts), whatever the in-a-row counter says. @@ -302,6 +303,10 @@ struct Supervisor { /// The sealed archive is known to match its pinned digest (stamp of its source file, or a previous engine of /// this supervisor verified this very memfd): the engine is told not to hash it again. archive_attested: bool, + /// `memfd_extents: ple_only`: the pinned SHA-256 of the archive's extents. The memfd holds only those bytes (or all of them, when it + /// came from a holder) and the engine verifies it against this digest instead of the archive's SHA-256; no stamp or attestation + /// of the whole archive applies to it. + archive_sparse_pin: Option<[u8; 32]>, stamps: VerifyStamps, api_addr: SocketAddr, engine_addr: SocketAddr, @@ -431,6 +436,7 @@ async fn run_inner(options: Options) -> Result<(), Failure> { archive: None, source_identity: None, archive_attested: false, + archive_sparse_pin: None, stamps: VerifyStamps::new(stamps_dir, false), api_addr, engine_addr, @@ -547,6 +553,7 @@ impl Supervisor { model_digest: &self.config.model_digest, profile: &self.config.profile.name, kar_source: self.config.profile.kar_source.as_str(), + memfd_extents: self.config.profile.memfd_extents.as_str(), started_unix: self.started_unix, restarts_total: self.restarts_total, last_restart_unix: self.last_restart.as_ref().map(|(at, _)| *at), @@ -682,6 +689,35 @@ impl Supervisor { } } + /// The pin of the extents when the profile asks for a sparse memfd (`None` for the full copy); refuses to start without one. + fn sparse_pin(&self) -> Result, Flow> { + if self.config.profile.memfd_extents != MemfdExtents::PleOnly { + return Ok(None); + } + match extents_sha256(&|key| std::env::var(key).ok()) { + Ok((pin, source)) => { + self.log.line(&format!( + "memfd_extents=ple_only: only the byte ranges the serve path reads are in the sealed memfd; the engine verifies them against the extents digest {}{}", + pin.iter().map(|b| format!("{b:02x}")).collect::(), + match source { + PinSource::Compiled => " (pinned in the binary)", + PinSource::Operator => " (supplied by LELEKA_KAR_EXTENTS_SHA256, not pinned in the binary)", + } + )); + Ok(Some(pin)) + } + Err(message) => fail(1, message), + } + } + + /// The page-aligned ranges of the archive file the serve path reads, from its header and directory (about a megabyte of reads). + fn serve_extents(kar: &Path) -> Result, Flow> { + match sealed::archive_serve_extents(kar, ARCHIVE_BYTES) { + Ok(extents) => Ok(extents), + Err(message) => fail(1, message), + } + } + async fn drive(&mut self, kar_fd: Option) -> Result<(), Flow> { // 1. the archive self.archive = match (kar_fd, self.config.profile.kar_source) { @@ -689,18 +725,39 @@ impl Supervisor { self.log.line(&format!( "using the sealed archive descriptor {fd} inherited from the parent" )); + self.archive_sparse_pin = self.sparse_pin()?; Some( sealed::open_inherited(fd) .map_err(|message| Flow::Fatal(Failure { code: 2, message }))?, ) } (None, KarSource::Memfd) => { - self.set_phase(Phase::Sealing, "copying the archive into a sealed memfd"); let kar = self.paths.kar(); - self.log.line(&format!( - "sealing {} into RAM (once per service life)", - kar.display() - )); + // `memfd_extents: ple_only`: only the byte ranges the serve path reads (about 16 GB of 55) go into the memfd. + let sparse = self.sparse_pin()?; + let extents = match sparse { + Some(_) => Some(Self::serve_extents(&kar)?), + None => None, + }; + match &extents { + Some(list) => { + self.set_phase(Phase::Sealing, "copying the archive extents the serve path reads into a sealed memfd"); + self.log.line(&format!( + "sealing {} extents ({:.2} GiB of {:.2} GiB) of {} into RAM; the rest of the memfd is a hole (once per service life)", + list.len(), + leleka_model_format::kar::extents_bytes(list) as f64 / 1073741824.0, + ARCHIVE_BYTES as f64 / 1073741824.0, + kar.display() + )); + } + None => { + self.set_phase(Phase::Sealing, "copying the archive into a sealed memfd"); + self.log.line(&format!( + "sealing {} into RAM (once per service life)", + kar.display() + )); + } + } let started = Instant::now(); let mut preverify = self.spawn_shard_preverify(); // A stamp of the archive file (written after a start whose engine hashed the copy) lets the engine @@ -714,17 +771,17 @@ impl Supervisor { && before .is_some_and(|id| self.stamps.trusts("kar-source", &archive_sha256(), &id)); let log = &self.log; - let sealed = sealed::seal_file_report( - &kar, - Some(ARCHIVE_BYTES), - &mut |done, total| { - log.line(&format!( - "sealing archive: {:.1} of {:.1} GiB", - done as f64 / 1073741824.0, - total as f64 / 1073741824.0 - )); - }, - ); + let mut progress = |done: u64, total: u64| { + log.line(&format!( + "sealing archive: {:.1} of {:.1} GiB", + done as f64 / 1073741824.0, + total as f64 / 1073741824.0 + )); + }; + let sealed = match &extents { + Some(list) => sealed::seal_extents_report(&kar, Some(ARCHIVE_BYTES), list, &mut progress), + None => sealed::seal_file_report(&kar, Some(ARCHIVE_BYTES), &mut progress), + }; if let Some(child) = preverify.as_mut() { let waited = Instant::now(); match child.wait().await { @@ -754,8 +811,15 @@ impl Supervisor { read.strategy.as_str(), read.mb_per_s() )); - self.source_identity = identity; - self.archive_attested = stamped && identity == before; + if sparse.is_some() { + // A sparse copy says nothing about the archive file as a whole: no identity, no stamp, no attestation. + self.archive_sparse_pin = sparse; + self.source_identity = None; + self.archive_attested = false; + } else { + self.source_identity = identity; + self.archive_attested = stamped && identity == before; + } if self.archive_attested { self.log.line("the archive file matches its verification stamp: the engine will not hash the copy again"); } @@ -996,7 +1060,12 @@ impl Supervisor { None => (KarArg::File, None), }; let mut engine_args = self.config.engine_args(kar_arg); - if self.archive_attested && stdin.is_some() { + if let Some(pin) = self.archive_sparse_pin + && stdin.is_some() + { + engine_args.push("--kar-sparse-extents-sha256".into()); + engine_args.push(pin.iter().map(|b| format!("{b:02x}")).collect()); + } else if self.archive_attested && stdin.is_some() { engine_args.push("--kar-attested-by-stamp".into()); } let mut engine = if stdin.is_some() { @@ -1025,7 +1094,7 @@ impl Supervisor { // The engine hashed the sealed copy (or was told it matched). Either way this memfd is known good for the // life of this supervisor, so a restarted engine need not hash it again; and when the copy came from a file // in a stable state, record that state so the next start of the service can skip the hash too. - if self.config.verify_stamps && self.archive.is_some() { + if self.config.verify_stamps && self.archive.is_some() && self.archive_sparse_pin.is_none() { if !self.archive_attested && let Some(identity) = self.source_identity { diff --git a/crates/deploy/tests/e2e.rs b/crates/deploy/tests/e2e.rs index d441fb8e..9747d49a 100644 --- a/crates/deploy/tests/e2e.rs +++ b/crates/deploy/tests/e2e.rs @@ -211,8 +211,13 @@ fn inheritable_sealed_memfd(bytes: &[u8]) -> fs::File { } fn start_supervisor(fixture: &Fixture, config: &Path, kar_fd: Option) -> Child { + start_supervisor_with_env(fixture, config, kar_fd, &[]) +} + +fn start_supervisor_with_env(fixture: &Fixture, config: &Path, kar_fd: Option, env: &[(&str, &str)]) -> Child { let mut command = Process::new(LELEKA); command.arg("run").arg("--config").arg(config); + command.envs(env.iter().copied()); if let Some(fd) = kar_fd { command.arg("--kar-fd").arg(fd.to_string()); } @@ -341,6 +346,105 @@ fn supervisor_lifecycle_with_an_inherited_sealed_descriptor() { lifecycle(KarSource::Memfd); } +/// `memfd_extents: ple_only` profile of the test double (the laptop profile with a sealed memfd and an explicit prefix cap). +fn sparse_profile() -> Profile { + let mut profile = Profile::builtin("rtx3080-16g").unwrap(); + profile.kar_source = KarSource::Memfd; + profile.memfd_extents = leleka_deploy::profile::MemfdExtents::PleOnly; + profile.memory.prefix_cache_mib = Some("4096".into()); + profile.validate().unwrap(); + profile +} + +#[test] +fn a_sparse_memfd_profile_tells_every_engine_the_extents_digest_and_never_claims_the_archive_was_verified() { + let fixture = Fixture::new("sparse"); + fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); + let config = fixture.write_state(sparse_profile()); + let paths = fixture.dirs.paths(); + let memfd = inheritable_sealed_memfd(&vec![7u8; 100_000]); + let pin = "ab".repeat(32); + let compiled = leleka_model_format::kar::PLE_EXTENTS_SHA256; + let expected: String = if compiled == [0u8; 32] { pin.clone() } else { compiled.iter().map(|b| format!("{b:02x}")).collect() }; + let mut supervisor = start_supervisor_with_env( + &fixture, + &config, + Some(std::os::fd::AsRawFd::as_raw_fd(&memfd)), + &[("LELEKA_KAR_EXTENTS_SHA256", &pin)], + ); + let ready = fixture.wait_for("ready", Duration::from_secs(120), |s| s["phase"] == "ready"); + assert_eq!(ready["memfd_extents"], "ple_only"); + signal(ready["engine_pid"].as_u64().unwrap(), "KILL"); + fixture.wait_for("engine restart", Duration::from_secs(60), |s| s["phase"] == "ready" && s["engine_restarts"] == 1); + let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap(); + let starts: Vec<&str> = calls.lines().filter(|l| l.starts_with("leleka-inference ")).collect(); + assert_eq!(starts.len(), 2, "{calls}"); + for (i, line) in starts.iter().enumerate() { + assert!(line.contains(&format!("--kar-sparse-extents-sha256 {expected}")), "engine {i}: {line}"); + assert!(line.contains("--kar-archive-fd"), "{line}"); + // the memfd is not the archive: no attestation by a stamp of the archive file, not even for the restarted engine + assert!(!line.contains("--kar-attested-by-stamp"), "engine {i}: {line}"); + } + // and no stamp of the archive was recorded from it + let stamps: Vec = fs::read_dir(paths.stamps()).map(|d| d.flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect()).unwrap_or_default(); + assert!(!stamps.iter().any(|name| name.starts_with("kar")), "{stamps:?}"); + let log = fs::read_to_string(fixture.root.join("supervisor.out")).unwrap_or_default() + &fixture.logs(); + assert!(log.contains("EXPERIMENTAL") && log.contains(&expected), "{log}"); + signal(u64::from(supervisor.id()), "TERM"); + assert!(wait_exit(&mut supervisor, Duration::from_secs(60)).is_some_and(|s| s.success()), "{}", fixture.logs()); +} + +#[test] +fn a_sparse_memfd_profile_without_a_pinned_digest_does_not_start() { + let fixture = Fixture::new("sparse-nopin"); + fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); + let config = fixture.write_state(sparse_profile()); + let memfd = inheritable_sealed_memfd(&vec![7u8; 100_000]); + let mut supervisor = start_supervisor_with_env(&fixture, &config, Some(std::os::fd::AsRawFd::as_raw_fd(&memfd)), &[]); + let status = wait_exit(&mut supervisor, Duration::from_secs(60)).expect("the supervisor must refuse"); + if leleka_model_format::kar::PLE_EXTENTS_SHA256 == [0u8; 32] { + assert_eq!(status.code(), Some(1)); + let message = fixture.status().unwrap()["message"].as_str().unwrap().to_owned(); + assert!(message.contains("kar_census") && message.contains("--hash-extents"), "{message}"); + // no engine was started + let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap_or_default(); + assert_eq!(calls.matches("leleka-inference ").count(), 0, "{calls}"); + } +} + +#[test] +fn seal_exec_hands_the_command_a_sealed_memfd_of_the_file_and_refuses_what_it_cannot_seal() { + let dir = std::env::temp_dir().join(format!("leleka-seal-exec-{}", std::process::id())); + fs::create_dir_all(&dir).unwrap(); + let file = dir.join("archive.bin"); + let bytes: Vec = (0..300_000u32).map(|n| (n % 251) as u8).collect(); + fs::write(&file, &bytes).unwrap(); + let run = |extra: &[&str]| { + Process::new(LELEKA) + .args(["seal-exec", "--file"]) + .arg(&file) + .args(extra) + .output() + .unwrap() + }; + let ok = run(&["--expect-bytes", "300000", "--", "sh", "-c", "wc -c < /proc/self/fd/{FD}; readlink /proc/self/fd/{FD}; cksum < /proc/self/fd/{FD}"]); + let out = String::from_utf8_lossy(&ok.stdout); + assert!(ok.status.success(), "{}{}", out, String::from_utf8_lossy(&ok.stderr)); + assert!(out.contains("300000") && out.contains("/memfd:leleka-sealed-archive"), "{out}"); + let want = Process::new("cksum").stdin(fs::File::open(&file).unwrap()).output().unwrap(); + assert!(out.contains(String::from_utf8_lossy(&want.stdout).trim()), "the descriptor holds the file byte for byte: {out}"); + // a wrong length, a missing command and the sparse form without its length are refused (exit 2), nothing is run + for extra in [vec!["--expect-bytes", "1", "--", "true"], vec!["--expect-bytes", "300000"], vec!["--sparse-ple", "--", "true"]] { + let refused = run(&extra); + assert_eq!(refused.status.code(), Some(2), "{extra:?}: {}", String::from_utf8_lossy(&refused.stderr)); + } + // a file that is not a KAR archive cannot be sealed sparse + let sparse = run(&["--sparse-ple", "--expect-bytes", "300000", "--", "true"]); + assert_eq!(sparse.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&sparse.stderr).contains("not a valid KAR archive"), "{}", String::from_utf8_lossy(&sparse.stderr)); + fs::remove_dir_all(&dir).unwrap(); +} + #[test] fn supervisor_lifecycle_with_a_read_only_archive_file() { lifecycle(KarSource::File); diff --git a/crates/leleka-memory/src/governor.rs b/crates/leleka-memory/src/governor.rs index 98dfb1d3..ed34760b 100644 --- a/crates/leleka-memory/src/governor.rs +++ b/crates/leleka-memory/src/governor.rs @@ -179,6 +179,9 @@ pub struct LockReport { pub decision: LockDecision, pub outcome: LockOutcome, pub mapping_bytes: u64, + /// A sparse archive (a memfd that holds only the extents the serve path reads): the bytes of those extents, which is what is + /// locked, healed and counted; `None` for a full archive, where it is `mapping_bytes`. + pub extent_bytes: Option, pub memlock_soft: Option, pub memlock_hard: Option, pub millis: f64, @@ -188,6 +191,8 @@ pub struct LockReport { struct Guarded { mapping: crate::lock::FdMapping, report: LockReport, + /// The extents of a sparse archive; `None` = the whole mapping is data. The heal cursor then walks their concatenation. + extents: Option>, cursor: u64, last_swapped: u64, warned_swapped: u64, @@ -644,10 +649,26 @@ impl Governor { /// Map the sealed archive, lock it when the limits allow, and keep the mapping for the residency guard. #[cfg(all(target_os = "linux", target_pointer_width = "64"))] pub fn guard_archive(&self, fd: std::os::fd::BorrowedFd<'_>, len: u64) -> Result { + self.guard_archive_extents(fd, len, None) + } + + /// [`Self::guard_archive`] for a sparse memfd: `extents` are the `(offset, len)` ranges that hold data, everything else of the + /// `len`-byte descriptor is a hole. Only the extents are locked and healed (locking or populating a hole allocates zero + /// pages for it, which would turn the sparse copy back into the full archive), the lock limit is judged against their + /// size, and the report says so. `None` is the whole archive. + pub fn guard_archive_extents(&self, fd: std::os::fd::BorrowedFd<'_>, len: u64, extents: Option<&[crate::lock::Span]>) -> Result { let started = Instant::now(); let facts = self.probe(); let mode = self.inner.cfg.lock_mode; - let decision = plan_lock(mode, len, facts.memlock, &facts.status); + if let Some(spans) = extents + && let Err(why) = crate::lock::check_spans(spans, len) + { + return Err(Refusal { code: "memlock", message: format!("the sparse archive extents are invalid: {why}"), numbers: vec![("archive".to_owned(), len)], advice: vec![] }); + } + // the bytes that are resident and have to be locked + let resident = extents.map_or(len, crate::lock::spans_bytes); + let extent_bytes = extents.map(crate::lock::spans_bytes); + let decision = plan_lock(mode, resident, facts.memlock, &facts.status); // Map a private READ-ONLY reopen of the descriptor, never the descriptor itself: a write-sealed memfd refuses a shared // mapping that could become writable (EPERM on kernels up to 5.15 when the description is read-write), and a read-only // description can never become writable, so the mapping is allowed everywhere and is immutable by construction. @@ -670,6 +691,7 @@ impl Governor { decision, outcome: LockOutcome::NotAttempted { why: format!("mmap of the archive failed: {e}") }, mapping_bytes: 0, + extent_bytes, memlock_soft: facts.memlock.map(|m| m.0), memlock_hard: facts.memlock.map(|m| m.1), millis: started.elapsed().as_secs_f64() * 1e3, @@ -690,7 +712,7 @@ impl Governor { if *hard == u64::MAX { "unlimited".into() } else { (hard >> 20).to_string() }, need >> 20 ); - self.log(&format!("WARNING: the sealed KAR memfd ({}) stays swappable: {why}. To keep it resident: {}", gib(len), advice.join(" | "))); + self.log(&format!("WARNING: the sealed KAR memfd ({}) stays swappable: {why}. To keep it resident: {}", gib(resident), advice.join(" | "))); LockOutcome::NotAttempted { why } } LockDecision::Attempt { raise_soft_to } => { @@ -701,11 +723,15 @@ impl Governor { let policy = self.policy(); let swapped = self.mapping_swapped(&mapping).unwrap_or(0); let src = self.inner.src.clone(); - let outcome = mapping.lock(GIB, |n| { + let allow = |n: u64| { // a swapped-out chunk is read back into RAM: keep the hard floor + reserve let need = if swapped > 0 { n } else { 0 }; HostFacts::probe(&*src).effective_available().is_none_or(|a| a.saturating_sub(need) >= policy.hard_floor + policy.reserve) - }); + }; + let outcome = match extents { + Some(spans) => mapping.lock_ranges(spans, GIB, allow), + None => mapping.lock(GIB, allow), + }; match &outcome { LockOutcome::Locked { bytes } => self.log(&format!("sealed KAR memfd locked in RAM: {} (mlock, never swapped)", gib(*bytes))), LockOutcome::Partial { locked, why, .. } => self.log(&format!("WARNING: sealed KAR memfd lock stopped at {} of {}: {why}", gib(*locked), gib(len))), @@ -719,6 +745,7 @@ impl Governor { decision: decision.clone(), outcome: outcome.clone(), mapping_bytes: len, + extent_bytes, memlock_soft: facts.memlock.map(|m| m.0), memlock_hard: facts.memlock.map(|m| m.1), millis: started.elapsed().as_secs_f64() * 1e3, @@ -729,11 +756,11 @@ impl Governor { vec![("needed to lock".to_owned(), *need), ("RLIMIT_MEMLOCK soft".to_owned(), *soft), ("RLIMIT_MEMLOCK hard".to_owned(), *hard)], advice.clone(), ), - _ => (vec![("archive".to_owned(), len)], vec![]), + _ => (vec![("archive".to_owned(), resident)], vec![]), }; return Err(Refusal { code: "memlock", message: format!("LELEKA_MEMORY_LOCK=require but the sealed KAR memfd could not be locked ({outcome:?})"), numbers, advice }); } - *lock(&self.inner.guarded) = Some(Guarded { mapping, report: report.clone(), cursor: 0, last_swapped: 0, warned_swapped: 0, last_check: None, last: None }); + *lock(&self.inner.guarded) = Some(Guarded { mapping, report: report.clone(), extents: extents.map(<[_]>::to_vec), cursor: 0, last_swapped: 0, warned_swapped: 0, last_check: None, last: None }); Ok(report) } @@ -776,21 +803,43 @@ impl Governor { .effective_available() .is_some_and(|a| a.saturating_sub(budget.min(r.swapped_bytes)) >= policy.soft_floor + policy.reserve); if ok { - let total = g.mapping.len(); let mut done = 0; - while done < budget && done < total { - if g.cursor >= total { - g.cursor = 0; + match g.extents.clone() { + // a sparse archive: walk the concatenation of the extents, never a hole + Some(spans) => { + let total = crate::lock::spans_bytes(&spans); + while done < budget && done < total { + if g.cursor >= total { + g.cursor = 0; + } + let want = (256 * MIB).min(budget - done); + let Some((offset, piece)) = crate::lock::compact_piece(&spans, g.cursor, want) else { break }; + // whole pages; the last page of the last extent may be partial and is rounded up by the kernel + let n = if g.cursor + piece == total || piece < 4096 { piece } else { piece / 4096 * 4096 }; + if g.mapping.populate(offset, n).is_err() { + break; + } + g.cursor += n; + done += n; + } } - let n = (256 * MIB).min(total - g.cursor).min(budget - done) / 4096 * 4096; - if n == 0 { - break; + None => { + let total = g.mapping.len(); + while done < budget && done < total { + if g.cursor >= total { + g.cursor = 0; + } + let n = (256 * MIB).min(total - g.cursor).min(budget - done) / 4096 * 4096; + if n == 0 { + break; + } + if g.mapping.populate(g.cursor, n).is_err() { + break; + } + g.cursor += n; + done += n; + } } - if g.mapping.populate(g.cursor, n).is_err() { - break; - } - g.cursor += n; - done += n; } self.inner.counters.heal_bytes.fetch_add(done, Ordering::Relaxed); self.inner.counters.heal_runs.fetch_add(1, Ordering::Relaxed); diff --git a/crates/leleka-memory/src/lock.rs b/crates/leleka-memory/src/lock.rs index 27028827..c433cd9e 100644 --- a/crates/leleka-memory/src/lock.rs +++ b/crates/leleka-memory/src/lock.rs @@ -121,6 +121,43 @@ pub fn residency_from_smaps(smaps: &str, start: u64, len: u64) -> Option u64 { + spans.iter().map(|s| s.1).sum() +} + +/// Are the spans usable for `mlock` / `madvise` on a mapping of `len` bytes: page-aligned starts, non-empty, sorted, disjoint, inside? +pub fn check_spans(spans: &[Span], len: u64) -> Result<(), String> { + let mut previous_end = 0u64; + for (i, (offset, n)) in spans.iter().enumerate() { + let end = offset.checked_add(*n).ok_or_else(|| format!("span {i} overflows"))?; + if !offset.is_multiple_of(PAGE) || *n == 0 || end > len || *offset < previous_end { + return Err(format!("span {i} ({offset}+{n}) is unaligned, empty, out of order or outside the mapping of {len} bytes")); + } + previous_end = end; + } + Ok(()) +} + +/// The piece of the spans at position `pos` of their concatenation ("compact space"): `(offset in the mapping, bytes)`, at most +/// `max` bytes and never across the end of a span. `None` when `pos` is past the last byte (or `max` is 0). A sparse archive +/// is walked with this so that nothing is ever asked of a hole. +pub fn compact_piece(spans: &[Span], pos: u64, max: u64) -> Option<(u64, u64)> { + let mut start = 0u64; + for (offset, n) in spans { + if pos < start + n { + let inside = pos - start; + let piece = (n - inside).min(max); + return (piece > 0).then_some((offset + inside, piece)); + } + start += n; + } + None +} + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] pub use sys::{FdMapping, raise_memlock_soft}; @@ -142,6 +179,8 @@ mod sys { addr: *mut libc::c_void, len: usize, locked: u64, + /// Ranges locked by `lock_ranges` (a sparse archive locks its extents only; the prefix counter above stays 0). + locked_spans: Vec<(u64, u64)>, } // SAFETY: the pointer is an address-space handle used only by thread-safe system calls on an immutable mapping; it @@ -177,7 +216,7 @@ mod sys { if addr == libc::MAP_FAILED { return Err(io::Error::last_os_error()); } - Ok(Self { addr, len, locked: 0 }) + Ok(Self { addr, len, locked: 0, locked_spans: Vec::new() }) } pub fn start(&self) -> u64 { self.addr as usize as u64 @@ -228,13 +267,54 @@ mod sys { } LockOutcome::Locked { bytes: self.locked } } + /// Lock only `spans` (the extents a sparse archive holds), `chunk` bytes at a time, calling `allow(bytes_that_may_fault_in)` before + /// each; stop at the first refusal. The holes between the spans are never touched: `mlock` of a hole in a shmem file + /// allocates zero pages for it (the sparse copy would silently become the full 55 GB again), so a range outside the + /// spans is not representable here. `check_spans` runs first. The counter `locked_bytes` is the sum of the locked spans. + pub fn lock_ranges(&mut self, spans: &[super::Span], chunk: u64, mut allow: impl FnMut(u64) -> bool) -> LockOutcome { + let wanted = super::spans_bytes(spans); + if let Err(why) = super::check_spans(spans, self.len as u64) { + return LockOutcome::Partial { locked: 0, wanted, why }; + } + let chunk = chunk.max(PAGE) / PAGE * PAGE; + let mut locked = 0u64; + for &(span_offset, span_len) in spans { + let mut done = 0u64; + while done < span_len { + let n = chunk.min(span_len - done); + if !allow(n) { + return LockOutcome::Partial { locked, wanted, why: "host memory guard refused the next chunk".into() }; + } + let (ptr, n_usize) = match self.range(span_offset + done, n) { + Ok(r) => r, + Err(e) => return LockOutcome::Partial { locked, wanted, why: e.to_string() }, + }; + // SAFETY: `ptr..ptr+n_usize` lies inside our live mapping (checked by `range`); mlock only faults/pins pages. + if unsafe { libc::mlock(ptr, n_usize) } != 0 { + let e = io::Error::last_os_error(); + return LockOutcome::Partial { locked, wanted, why: format!("mlock: {e}") }; + } + self.locked_spans.push((span_offset + done, n)); + done += n; + locked += n; + self.locked = locked; + } + } + LockOutcome::Locked { bytes: locked } + } /// Unlock everything this mapping locked. pub fn unlock(&mut self) { - if self.locked > 0 { + if self.locked > 0 && self.locked_spans.is_empty() { // SAFETY: the locked prefix `addr..addr+locked` lies inside our live mapping. let _ = unsafe { libc::munlock(self.addr, self.locked as usize) }; - self.locked = 0; } + for (offset, n) in std::mem::take(&mut self.locked_spans) { + if let Ok((ptr, n_usize)) = self.range(offset, n) { + // SAFETY: the span was locked by `lock_ranges` and lies inside our live mapping (checked by `range`). + let _ = unsafe { libc::munlock(ptr, n_usize) }; + } + } + self.locked = 0; } /// Which 4 KiB pages of `offset..offset+n` are in memory (`mincore`), one flag per page. For a descriptor the caller /// may not write, newer kernels report every page resident: use the smaps number for totals. @@ -339,6 +419,98 @@ mod sys { let f = file(4096); assert!(FdMapping::map_readonly(f.as_fd(), 0).is_err()); } + + /// An anonymous memfd of `pages` pages with data in the page ranges `data` (everything else is a hole). + fn sparse_memfd(pages: u64, data: &[(u64, u64)]) -> std::fs::File { + use std::os::fd::FromRawFd; + use std::os::unix::fs::FileExt; + // SAFETY: memfd_create returns a fresh descriptor that nothing else owns; File takes ownership of it. + let f = unsafe { + let fd = libc::memfd_create(c"leleka-lock-test".as_ptr(), 0); + assert!(fd >= 0, "memfd_create: {}", io::Error::last_os_error()); + std::fs::File::from_raw_fd(fd) + }; + f.set_len(pages * PAGE).unwrap(); + for &(first, count) in data { + for page in first..first + count { + f.write_all_at(&vec![0xA5u8; PAGE as usize], page * PAGE).unwrap(); + } + } + f + } + fn allocated(f: &std::fs::File) -> u64 { + use std::os::unix::fs::MetadataExt; + f.metadata().unwrap().blocks() * 512 + } + fn pages_to_spans(ranges: &[(u64, u64)]) -> Vec<(u64, u64)> { + ranges.iter().map(|&(first, count)| (first * PAGE, count * PAGE)).collect() + } + + #[test] + fn locking_and_populating_the_extents_of_a_sparse_memfd_allocates_nothing_in_the_holes() { + let data = [(10u64, 4u64), (100, 6)]; + let spans = pages_to_spans(&data); + let f = sparse_memfd(256, &data); + assert_eq!(allocated(&f), 10 * PAGE, "only the pages written exist"); + let mut m = FdMapping::map_readonly(f.as_fd(), (256 * PAGE) as usize).unwrap(); + assert_eq!(allocated(&f), 10 * PAGE, "mapping a sparse file allocates nothing"); + let outcome = m.lock_ranges(&spans, 4 * PAGE, |_| true); + assert_eq!(outcome, LockOutcome::Locked { bytes: 10 * PAGE }, "{outcome:?}"); + assert_eq!(m.locked_bytes(), 10 * PAGE); + assert_eq!(allocated(&f), 10 * PAGE, "locking the extents instantiated no hole"); + for &(offset, n) in &spans { + m.populate(offset, n).unwrap(); + } + assert_eq!(allocated(&f), 10 * PAGE, "populating the extents instantiated no hole"); + m.unlock(); + assert_eq!(m.locked_bytes(), 0); + assert_eq!(allocated(&f), 10 * PAGE); + } + + #[test] + fn locking_the_whole_mapping_of_a_sparse_memfd_does_allocate_the_holes_which_is_why_ranges_exist() { + // the negative control of the test above: if this stopped allocating, the extents-only lock would no longer be needed + let f = sparse_memfd(256, &[(10, 4), (100, 6)]); + let mut m = FdMapping::map_readonly(f.as_fd(), (256 * PAGE) as usize).unwrap(); + let outcome = m.lock(64 * PAGE, |_| true); + assert_eq!(outcome, LockOutcome::Locked { bytes: 256 * PAGE }, "{outcome:?}"); + assert_eq!(allocated(&f), 256 * PAGE, "mlock of a shmem hole allocates a zero page"); + } + + #[test] + fn lock_ranges_refuses_spans_that_are_unaligned_overlapping_unsorted_or_outside_before_any_syscall() { + let f = sparse_memfd(16, &[(0, 2)]); + let mut m = FdMapping::map_readonly(f.as_fd(), (16 * PAGE) as usize).unwrap(); + for bad in [ + vec![(1, PAGE)], + vec![(0, 2 * PAGE), (PAGE, PAGE)], + vec![(4 * PAGE, PAGE), (0, PAGE)], + vec![(15 * PAGE, 2 * PAGE)], + vec![(0, 0)], + ] { + let outcome = m.lock_ranges(&bad, PAGE, |_| panic!("the guard must not be consulted for an invalid span")); + assert!(matches!(outcome, LockOutcome::Partial { locked: 0, .. }), "{bad:?}: {outcome:?}"); + } + assert_eq!(m.locked_bytes(), 0); + assert_eq!(allocated(&f), 2 * PAGE); + } + + #[test] + fn the_guard_can_stop_a_ranged_lock_between_chunks_and_unlock_releases_what_was_locked() { + let f = sparse_memfd(64, &[(0, 8), (32, 8)]); + let mut m = FdMapping::map_readonly(f.as_fd(), (64 * PAGE) as usize).unwrap(); + let spans = pages_to_spans(&[(0, 8), (32, 8)]); + let mut calls = 0; + let outcome = m.lock_ranges(&spans, 4 * PAGE, |_| { + calls += 1; + calls <= 3 + }); + assert!(matches!(outcome, LockOutcome::Partial { locked, wanted, .. } if locked == 12 * PAGE && wanted == 16 * PAGE), "{outcome:?}"); + assert_eq!(m.locked_bytes(), 12 * PAGE); + m.unlock(); + assert_eq!(m.locked_bytes(), 0); + assert_eq!(allocated(&f), 16 * PAGE); + } } } @@ -374,6 +546,34 @@ mod tests { assert_eq!(d, LockDecision::Attempt { raise_soft_to: Some(55 * G) }); } + #[test] + fn spans_are_checked_summed_and_walked_in_compact_space() { + let p = PAGE; + let spans = [(2 * p, 3 * p), (10 * p, 2 * p), (20 * p, p + 100)]; + assert_eq!(spans_bytes(&spans), 6 * p + 100); + assert!(check_spans(&spans, 21 * p + 100).is_ok()); + assert!(check_spans(&spans, 21 * p + 99).is_err(), "the last span ends past the mapping"); + assert!(check_spans(&[], 0).is_ok()); + assert!(check_spans(&[(1, p)], 10 * p).is_err() && check_spans(&[(0, 0)], p).is_err()); + assert!(check_spans(&[(0, 2 * p), (p, p)], 10 * p).is_err() && check_spans(&[(4 * p, p), (0, p)], 10 * p).is_err()); + // compact space: positions 0..3p are the first span, 3p..5p the second, 5p.. the third + assert_eq!(compact_piece(&spans, 0, u64::MAX), Some((2 * p, 3 * p))); + assert_eq!(compact_piece(&spans, p, p), Some((3 * p, p))); + assert_eq!(compact_piece(&spans, 3 * p - 10, 100), Some((5 * p - 10, 10)), "never across the end of a span"); + assert_eq!(compact_piece(&spans, 3 * p, 5 * p), Some((10 * p, 2 * p))); + assert_eq!(compact_piece(&spans, 5 * p, 1), Some((20 * p, 1))); + assert_eq!(compact_piece(&spans, 6 * p + 100, 1), None); + assert_eq!(compact_piece(&spans, 0, 0), None); + // walking the whole compact space with a small step visits every byte exactly once and nothing outside the spans + let (mut pos, mut seen) = (0u64, 0u64); + while let Some((offset, n)) = compact_piece(&spans, pos, 3000) { + assert!(spans.iter().any(|&(o, l)| offset >= o && offset + n <= o + l), "{offset}+{n} left the spans"); + pos += n; + seen += n; + } + assert_eq!(seen, spans_bytes(&spans)); + } + #[test] fn off_never_locks() { assert_eq!(plan_lock(LockMode::Off, 1, Some((u64::MAX, u64::MAX)), &status(None, 0)), LockDecision::Off); diff --git a/crates/leleka-memory/src/plan.rs b/crates/leleka-memory/src/plan.rs index 65b77fa3..0ba46621 100644 --- a/crates/leleka-memory/src/plan.rs +++ b/crates/leleka-memory/src/plan.rs @@ -395,6 +395,15 @@ pub fn auto_prefix_budget(available: Option, policy: &Policy, complement_pi if bytes < policy.min_useful_cache { 0 } else { bytes } } +/// An explicit `--prefix-cache-mib N` at stack open: the wish, clamped to what the host has now, **never above the wish**. +/// Unlike [`auto_prefix_budget`] the result does not depend on how much memory is free beyond the wish: freeing RAM +/// elsewhere (a smaller archive copy, a smaller expert bank) cannot make the store bigger than the operator's number. +/// Returns the granted bytes and the elastic memory it was clamped against. +pub fn explicit_prefix_budget(wish: u64, available: Option, policy: &Policy, complement_pending: u64) -> (u64, u64) { + let elastic = available.map_or(0, |a| a.saturating_sub(policy.soft_floor + policy.reserve).saturating_sub(complement_pending)); + (wish.min(elastic) / MIB * MIB, elastic) +} + #[cfg(test)] mod tests { use super::*; @@ -583,4 +592,44 @@ mod tests { assert_eq!(big.soft_floor, g(32)); assert_eq!(big.hard_floor, g(16)); } + + #[test] + fn an_explicit_cap_never_grows_when_ram_is_freed_but_auto_does() { + let p = Policy::for_host(g(121), false); + let cap = 6144 * MIB; + // the 5090 at turn 5 today (MemAvailable 8.6 GiB after the stack opened is the PLAN's view of the open-time figure ~14 GiB) + let before = 14_064 * MIB; + // the sparse memfd frees ~36.6 GiB of shmem: MemAvailable at open rises by that much + let after = before + 36_600 * MIB; + let (granted_before, _) = explicit_prefix_budget(cap, Some(before), &p, 0); + let (granted_after, elastic_after) = explicit_prefix_budget(cap, Some(after), &p, 0); + assert_eq!(granted_before, cap - cap % MIB, "inside the cap today: the cap is the budget (auto would give {} MiB)", auto_prefix_budget(Some(before), &p, 0) >> 20); + assert_eq!(granted_after, cap, "freed RAM does not grow an explicit cap"); + assert!(elastic_after > 40 * GIB); + // the hazard the cap exists for: auto would hand the freed memory to the cache + assert!(auto_prefix_budget(Some(after), &p, 0) > 30 * GIB); + // the same for the startup plan: 37 GiB more available, the same explicit cap, a bigger auto cache + let mut small_input = server_input(75); + small_input.prefix = CacheWish::Bytes(cap); + let mut big_input = server_input(75 + 37); + big_input.prefix = CacheWish::Bytes(cap); + assert_eq!((plan(&small_input).unwrap().prefix_bytes, plan(&big_input).unwrap().prefix_bytes), (cap, cap)); + small_input.prefix = CacheWish::Auto; + big_input.prefix = CacheWish::Auto; + assert!(plan(&big_input).unwrap().prefix_bytes > plan(&small_input).unwrap().prefix_bytes + 20 * GIB); + } + + #[test] + fn an_explicit_cap_is_clamped_to_the_host_and_fails_closed_without_telemetry() { + let p = Policy::for_host(g(121), false); + // 5 GiB available: below soft floor + reserve (6 GiB), nothing elastic + assert_eq!(explicit_prefix_budget(6144 * MIB, Some(g(5)), &p, 0).0, 0); + // 9 GiB available: 3 GiB elastic + assert_eq!(explicit_prefix_budget(6144 * MIB, Some(g(9)), &p, 0), (g(3), g(3))); + // pinned complement pending comes off first + assert_eq!(explicit_prefix_budget(6144 * MIB, Some(g(9)), &p, g(2)).0, g(1)); + assert_eq!(explicit_prefix_budget(6144 * MIB, None, &p, 0), (0, 0)); + // the grant is whole MiB + assert_eq!(explicit_prefix_budget(MIB + 1, Some(g(100)), &p, 0).0, MIB); + } } diff --git a/crates/leleka-memory/tests/sparse_archive.rs b/crates/leleka-memory/tests/sparse_archive.rs new file mode 100644 index 00000000..3b813012 --- /dev/null +++ b/crates/leleka-memory/tests/sparse_archive.rs @@ -0,0 +1,88 @@ +//! The residency guard over a sparse sealed memfd: it locks the extents and nothing else, judges the lock limit by the +//! extents, and leaves every hole a hole. Linux only (memfd, mlock). +#![cfg(all(target_os = "linux", target_pointer_width = "64"))] +#![allow(unsafe_code)] + +use leleka_memory::{Governor, GovernorConfig, governor::LockReport, lock::LockOutcome}; +use std::os::fd::{AsFd, FromRawFd}; +use std::os::unix::fs::{FileExt, MetadataExt}; + +const PAGE: u64 = 4096; + +fn sparse_memfd(pages: u64, data: &[(u64, u64)]) -> std::fs::File { + // SAFETY: memfd_create returns a fresh descriptor that nothing else owns; File takes ownership of it. + let f = unsafe { + let fd = libc::memfd_create(c"leleka-sparse-archive-test".as_ptr(), 0); + assert!(fd >= 0, "memfd_create failed"); + std::fs::File::from_raw_fd(fd) + }; + f.set_len(pages * PAGE).unwrap(); + for &(first, count) in data { + for page in first..first + count { + f.write_all_at(&vec![0x5Au8; PAGE as usize], page * PAGE).unwrap(); + } + } + f +} + +fn allocated(f: &std::fs::File) -> u64 { + f.metadata().unwrap().blocks() * 512 +} + +fn governor() -> Governor { + let mut cfg = GovernorConfig::from_env(64 << 30, false, &|_| None).expect("default configuration"); + cfg.lock_mode = leleka_memory::lock::LockMode::Try; + cfg.heal = true; + cfg.log = false; + Governor::real(cfg) +} + +fn report(r: &Result) -> &LockReport { + r.as_ref().unwrap_or_else(|e| panic!("guard refused: {e}")) +} + +#[test] +fn the_guard_locks_the_extents_of_a_sparse_archive_and_instantiates_no_hole() { + let data = [(3u64, 5u64), (60, 2), (200, 9)]; + let spans: Vec<(u64, u64)> = data.iter().map(|&(first, n)| (first * PAGE, n * PAGE)).collect(); + let extent_bytes: u64 = spans.iter().map(|s| s.1).sum(); + let f = sparse_memfd(512, &data); + assert_eq!(allocated(&f), extent_bytes); + let g = governor(); + let result = g.guard_archive_extents(f.as_fd(), 512 * PAGE, Some(&spans)); + let r = report(&result); + assert_eq!(r.mapping_bytes, 512 * PAGE); + assert_eq!(r.extent_bytes, Some(extent_bytes), "the report speaks of the extents"); + println!("lock outcome: {:?}", r.outcome); + match &r.outcome { + LockOutcome::Locked { bytes } => assert_eq!(*bytes, extent_bytes), + // a host that refuses mlock (RLIMIT_MEMLOCK) still must not have touched a hole + LockOutcome::NotAttempted { .. } | LockOutcome::Partial { .. } => {} + } + assert_eq!(allocated(&f), extent_bytes, "locking the extents of a sparse memfd allocated a hole"); + // the residency tick (swap detection and heal) is safe on it too + assert_eq!(g.residency_tick(), 0); + assert_eq!(allocated(&f), extent_bytes); +} + +#[test] +fn the_full_archive_form_is_unchanged_and_reports_no_extents() { + let f = sparse_memfd(64, &[(0, 64)]); + let g = governor(); + let result = g.guard_archive(f.as_fd(), 64 * PAGE); + let r = report(&result); + assert_eq!(r.extent_bytes, None); + assert_eq!(r.mapping_bytes, 64 * PAGE); + assert_eq!(allocated(&f), 64 * PAGE); +} + +#[test] +fn extents_that_do_not_fit_the_descriptor_are_refused_before_any_mapping() { + let f = sparse_memfd(16, &[(0, 1)]); + let g = governor(); + for bad in [vec![(1u64, PAGE)], vec![(15 * PAGE, 2 * PAGE)], vec![(0, 2 * PAGE), (PAGE, PAGE)]] { + let e = g.guard_archive_extents(f.as_fd(), 16 * PAGE, Some(&bad)).err().unwrap_or_else(|| panic!("{bad:?} accepted")); + assert!(e.to_string().contains("extents are invalid"), "{e}"); + } + assert_eq!(allocated(&f), PAGE); +} diff --git a/crates/leleka-runtime/src/backend.rs b/crates/leleka-runtime/src/backend.rs index 6aaa94c2..1d8986d3 100644 --- a/crates/leleka-runtime/src/backend.rs +++ b/crates/leleka-runtime/src/backend.rs @@ -1208,6 +1208,7 @@ fn serve_load( kv_resident: options.kv_resident.unwrap_or(leleka_cuda_driver::KV_RESIDENT_DEFAULT_CELLS), gpu_budget_bytes: config.gpu_budget_bytes, kar_file_backed: config.kar_ple_inherited.as_ref().map(InheritedKarArchive::file_backed), + kar_sparse_bytes: config.kar_ple_inherited.as_ref().and_then(InheritedKarArchive::sparse_extents).map(|spans| leleka_memory::lock::spans_bytes(&spans)), expert_source_mapped: options.expert_source == original_serve::ExpertSource::Mapped, prefix: options.prefix_cache.as_ref().map(|p| p.budget_bytes), prompt_cache: options.prompt_cache, diff --git a/crates/leleka-runtime/src/backend_original_serve.rs b/crates/leleka-runtime/src/backend_original_serve.rs index 7802d525..427034fd 100644 --- a/crates/leleka-runtime/src/backend_original_serve.rs +++ b/crates/leleka-runtime/src/backend_original_serve.rs @@ -772,6 +772,18 @@ mod runner { })]); publish_prefix_summary(&stack, shared); crate::load_clock::lap("serve_stack_open_total"); + // The first release (right after the expert bank was copied) cannot see what the stack open reads next: the dense tensors of shard 0 and the + // MTP pack go through the page cache (4-5 GiB measured at idle on the 5090), and the resident copies are in the engine's own memory. Give + // those pages back too, so that no model byte is held twice (clean pages only, POSIX_FADV_DONTNEED, never drop_caches; best effort). + #[cfg(target_os = "linux")] + if options.expert_source == crate::backend::ExpertSource::Resident { + let mut files: Vec = model_files.clone(); + if let Some(dir) = options.mtp_rt_directory.as_ref() { + files.extend(["experts.bin", "dense.bin"].map(|name| dir.join(name))); + } + let paths: Vec<&std::path::Path> = files.iter().map(PathBuf::as_path).collect(); + crate::memory_governor::drop_file_cache(&paths); + } leleka_memory::telemetry::set_settings(crate::serve_tuning::describe(&options, context_tokens, workers, None)); // operator telemetry: GPU/RAM/CPU once a second, throughput and cache hits recorded per request leleka_memory::telemetry::set_context_max(u64::from(context_tokens)); diff --git a/crates/leleka-runtime/src/backend_original_serve_memory_smoke.rs b/crates/leleka-runtime/src/backend_original_serve_memory_smoke.rs index f6953d6d..0f7c947b 100644 --- a/crates/leleka-runtime/src/backend_original_serve_memory_smoke.rs +++ b/crates/leleka-runtime/src/backend_original_serve_memory_smoke.rs @@ -164,6 +164,7 @@ fn original_serve_memory_smoke() { kv_resident: resident, gpu_budget_bytes: (budget_gib as u64) << 30, kar_file_backed: Some(inherited.file_backed()), + kar_sparse_bytes: None, expert_source_mapped: experts_mapped, prefix: prefix_arg, prompt_cache: 6, diff --git a/crates/leleka-runtime/src/backend_original_serve_replay.rs b/crates/leleka-runtime/src/backend_original_serve_replay.rs index 8925a6d5..19305d64 100644 --- a/crates/leleka-runtime/src/backend_original_serve_replay.rs +++ b/crates/leleka-runtime/src/backend_original_serve_replay.rs @@ -60,7 +60,16 @@ fn original_serve_replay_smoke() { let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 verification failed"); let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); let eos = *artifact.tokenizer().special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); - let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited KAR admission failed"); + // LELEKA_KAR_SPARSE_EXTENTS_SHA256=<64 hex>: the descriptor is a sparse memfd (`leleka seal-exec --sparse-ple`, docs/kar-sparse-memfd.md); it is verified against the + // pinned digest of its extents instead of the archive's SHA-256. Unset: the full archive, as always. + let inherited = match env::var("LELEKA_KAR_SPARSE_EXTENTS_SHA256") { + Ok(text) => { + assert_eq!(text.len(), 64, "LELEKA_KAR_SPARSE_EXTENTS_SHA256 must be 64 hex digits"); + let digest: [u8; 32] = std::array::from_fn(|i| u8::from_str_radix(&text[2 * i..2 * i + 2], 16).expect("LELEKA_KAR_SPARSE_EXTENTS_SHA256 must be hex")); + InheritedKarArchive::open_sparse(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE"), digest).expect("sparse inherited KAR admission failed") + } + Err(_) => InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited KAR admission failed"), + }; let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( artifact, &inherited, diff --git a/crates/leleka-runtime/src/memory_governor.rs b/crates/leleka-runtime/src/memory_governor.rs index 39d73ad4..89f3180f 100644 --- a/crates/leleka-runtime/src/memory_governor.rs +++ b/crates/leleka-runtime/src/memory_governor.rs @@ -33,6 +33,8 @@ pub(crate) struct StartArgs { pub gpu_budget_bytes: u64, /// `None`: no inherited archive (the Original path refuses that elsewhere). pub kar_file_backed: Option, + /// Bytes the sealed memfd really holds when it is sparse (`None`: the whole pinned archive). + pub kar_sparse_bytes: Option, pub expert_source_mapped: bool, /// `None`: no prefix cache; `Some(None)`: auto; `Some(Some(bytes))`: explicit (0 = off). pub prefix: Option>, @@ -109,7 +111,7 @@ pub(crate) fn startup(args: &StartArgs) -> Result<&'static Governor, BackendErro )); let kar = match args.kar_file_backed { Some(true) => KarForm::File { bytes: crate::model_binding::qwen4exp_kar_ple::PINNED_ARCHIVE_BYTES }, - _ => KarForm::MemfdInherited { bytes: crate::model_binding::qwen4exp_kar_ple::PINNED_ARCHIVE_BYTES }, + _ => KarForm::MemfdInherited { bytes: args.kar_sparse_bytes.unwrap_or(crate::model_binding::qwen4exp_kar_ple::PINNED_ARCHIVE_BYTES) }, }; let host = g.probe(); let resident_complement = std::env::var("LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB") @@ -145,12 +147,25 @@ pub(crate) fn guard_archive(g: &Governor, archive: &crate::model_binding::qwen4e if archive.file_backed() { return Ok(()); } - g.guard_archive(archive.archive_handle().as_fd(), crate::model_binding::qwen4exp_kar_ple::PINNED_ARCHIVE_BYTES) + // A sparse memfd (`--kar-sparse-extents-sha256`) holds only the extents the serve path reads: lock, heal and count those, never a hole + // (locking a hole allocates zero pages for it). + let extents = archive.sparse_extents(); + g.guard_archive_extents(archive.archive_handle().as_fd(), crate::model_binding::qwen4exp_kar_ple::PINNED_ARCHIVE_BYTES, extents.as_deref()) .map(|_| ()) .map_err(|r| refusal_error(r.to_string()))?; + let (bytes, what) = match &extents { + Some(spans) => ( + leleka_memory::lock::spans_bytes(spans), + "the pinned level-2 archive as a SPARSE sealed memfd: only the extents the serve path reads (PLE rows, header, directory); the rest is a hole", + ), + None => ( + crate::model_binding::qwen4exp_kar_ple::PINNED_ARCHIVE_BYTES, + "the pinned level-2 archive, sealed memfd (55,295,529,472 B), shared with the holder", + ), + }; g.inventory().set( - Entry::new("kar", "memfd", Space::HostShmem, When::Startup, "the pinned level-2 archive, sealed memfd (55,295,529,472 B), shared with the holder") - .bytes(crate::model_binding::qwen4exp_kar_ple::PINNED_ARCHIVE_BYTES) + Entry::new("kar", "memfd", Space::HostShmem, When::Startup, what) + .bytes(bytes) .swappable(g.report()["archive"]["lock"]["outcome"]["outcome"] != "locked"), ); Ok(()) @@ -233,10 +248,7 @@ pub(crate) fn resolve_prefix_budget(budget: crate::qwen_forward::original_serve_ View::Off => 0, View::Auto => leleka_memory::plan::auto_prefix_budget(available, &policy, complement_pending), View::Bytes(wish) => { - let elastic = available - .map(|a| a.saturating_sub(policy.soft_floor + policy.reserve).saturating_sub(complement_pending)) - .unwrap_or(0); - let granted = wish.min(elastic) / leleka_memory::MIB * leleka_memory::MIB; + let (granted, elastic) = leleka_memory::plan::explicit_prefix_budget(wish, available, &policy, complement_pending); if granted < wish { g.log(&format!( "note: prefix cache clamped from {} MiB to {} MiB: only {} MiB are elastic above the {} MiB soft floor", @@ -249,6 +261,18 @@ pub(crate) fn resolve_prefix_budget(budget: crate::qwen_forward::original_serve_ granted } }; + g.log(&format!( + "prefix cache budget: {} MiB ({}; {} MiB available at open, {} MiB soft floor, {} MiB reserve)", + bytes >> 20, + match budget { + View::Off => "off".to_owned(), + View::Auto => "auto: 75 % of what is elastic".to_owned(), + View::Bytes(wish) => format!("explicit cap {} MiB, never grown by free memory", wish >> 20), + }, + available.map_or(0, |a| a >> 20), + policy.soft_floor >> 20, + policy.reserve >> 20 + )); g.set_prefix_budget(bytes); Some(bytes) } diff --git a/crates/leleka-runtime/src/model_binding/qwen4exp_kar_ple.rs b/crates/leleka-runtime/src/model_binding/qwen4exp_kar_ple.rs index 5122b13e..22f6b254 100644 --- a/crates/leleka-runtime/src/model_binding/qwen4exp_kar_ple.rs +++ b/crates/leleka-runtime/src/model_binding/qwen4exp_kar_ple.rs @@ -19,6 +19,16 @@ pub struct InheritedKarArchive { provenance: File, /// `open_read_only_file`: an ordinary read-only file instead of a sealed memfd (see there). file_backed: bool, + /// `open_sparse`: the sealed memfd holds only the extents the serve path reads. + sparse: Option, +} + +/// A sealed memfd that holds only the byte ranges the serve path reads (`leleka_model_format::kar::Extent`); the rest is a hole. +struct SparseArchive { + /// Pinned SHA-256 of the extents (`digest_extents_with`): what the verifier checks instead of the archive's SHA-256. + extents_sha256: [u8; 32], + /// The page-aligned extents, derived from the header and directory of the memfd (metadata reads only). + extents: Vec, } impl InheritedKarArchive { #[cfg(target_os = "linux")] @@ -33,9 +43,41 @@ impl InheritedKarArchive { archive, provenance, file_backed: false, + sparse: None, }) } + /// `open` for a memfd that holds only the extents the serve path reads (`memfd_extents: ple_only`; **experimental**, off by + /// default). Admission is the same (a sealed, unlinked memfd of the pinned length); what changes is the verification + /// (`load_pinned_inherited_archive`): the digest of the extents stands in for the archive's SHA-256, and the memory governor + /// locks and heals the extents only. `extents_sha256` comes from the supervisor (`--kar-sparse-extents-sha256`); when the + /// binary carries a pinned digest the two must agree. + #[cfg(target_os = "linux")] + pub fn open_sparse(fd: u32, provenance: PathBuf, extents_sha256: [u8; 32]) -> Result { + let compiled = leleka_model_format::kar::PLE_EXTENTS_SHA256; + if extents_sha256 == [0u8; 32] || (compiled != [0u8; 32] && compiled != extents_sha256) { + return Err("sparse KAR extents digest is zero or differs from the pinned one"); + } + let mut opened = Self::open(fd, provenance)?; + let reader = open_sealed_archive_fd(fd, PINNED_ARCHIVE_BYTES) + .map_err(|_| "inherited KAR descriptor is not a pinned sealed archive")?; + let reads = leleka_model_format::kar::KarInspection::inspect(reader) + .and_then(|inspection| inspection.serve_reads(&leleka_model_format::kar::PLE_PART_NAMES)) + .map_err(|_| "the header and directory of the sparse KAR memfd are not readable")?; + opened.sparse = Some(SparseArchive { extents_sha256, extents: reads.extents }); + Ok(opened) + } + + #[cfg(not(target_os = "linux"))] + pub fn open_sparse(_fd: u32, _provenance: PathBuf, _extents_sha256: [u8; 32]) -> Result { + Err("a sparse sealed KAR archive requires Linux") + } + + /// The `(offset, len)` ranges a sparse memfd holds, for the residency guard; `None` for a full archive. + pub fn sparse_extents(&self) -> Option> { + self.sparse.as_ref().map(|s| s.extents.iter().map(|e| (e.offset, e.len)).collect()) + } + /// The low-RAM form of the same pinned archive: the archive stays an ordinary file on the SSD and only the /// rows a request reads pass through the OS file cache, like the Original's `PleTable::open_kar` (ngram.cpp: /// `kar_open` with payload verification, then a read-only mapping of the file). A sealed memfd copy keeps @@ -57,6 +99,7 @@ impl InheritedKarArchive { archive, provenance, file_backed: true, + sparse: None, }) } @@ -72,6 +115,7 @@ impl InheritedKarArchive { archive, provenance, file_backed: true, + sparse: None, }) } @@ -228,8 +272,38 @@ pub(crate) fn load_pinned_inherited_archive( let inspection = leleka_model_format::kar::KarInspection::inspect(reader) .map_err(|e| kar_failure(LoadPhase::Inspect, e))?; // Only an independently owned, detached, fully sealed inode reaches this boundary. - VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), profile) - .map_err(|e| kar_failure(LoadPhase::Verify, e)) + let Some(sparse) = source.sparse.as_ref() else { + let artifact = VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), profile) + .map_err(|e| kar_failure(LoadPhase::Verify, e))?; + log_startup_read(source, &artifact); + return Ok(artifact); + }; + // A sparse memfd: the digest of its extents, not the archive's SHA-256. The extents the governor locks must be exactly the + // ones the verifier hashed and the row reader reads. + let artifact = VerifiedKarPleArtifact::verify_sparse(inspection.into_owner_controlled(), profile, &sparse.extents_sha256) + .map_err(|e| kar_failure(LoadPhase::Verify, e))?; + if artifact.serve_extents() != sparse.extents.as_slice() { + return Err(input_failure(LoadPhase::Verify, InputBindingError::Metadata)); + } + log_startup_read(source, &artifact); + Ok(artifact) +} + +/// One line in the engine log of what opening the archive read from it: the header, directory and books, and whether the whole archive +/// was hashed (a stamp or the parent's attestation makes that 0). The rows a request reads later are not in it; they pass through the +/// page cache of an ordinary file one 4 KiB page at a time. +fn log_startup_read(source: &InheritedKarArchive, artifact: &VerifiedKarPleArtifact) { + let read = artifact.startup_read(); + eprintln!( + "leleka-kar-startup source={} verify={} metadata_bytes={} book_bytes={} hashed_bytes={} total_read_bytes={} identity_recheck={}", + if source.file_backed { "file" } else { "memfd" }, + read.trust.as_str(), + read.metadata_bytes, + read.book_bytes, + read.hashed_bytes, + read.total_bytes(), + artifact.rechecks_file_identity() + ); } /// Windows: only the file-backed form exists (`open_read_only_file`); the archive is shared read-only while open. @@ -247,8 +321,10 @@ pub(crate) fn load_pinned_inherited_archive( .map_err(|e| input_failure(LoadPhase::Provenance, e))?; let inspection = leleka_model_format::kar::KarInspection::inspect(reader) .map_err(|e| kar_failure(LoadPhase::Inspect, e))?; - VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), profile) - .map_err(|e| kar_failure(LoadPhase::Verify, e)) + let artifact = VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), profile) + .map_err(|e| kar_failure(LoadPhase::Verify, e))?; + log_startup_read(source, &artifact); + Ok(artifact) } #[cfg(not(any(target_os = "linux", target_os = "windows")))] @@ -560,6 +636,7 @@ fn kar_diagnostic(sink: &mut W, phase: LoadPhase, failure: &K KarError::Integrity("KAR full archive SHA-256 mismatch") => "ArchiveSha", KarError::Integrity("KAR payload CRC-32 mismatch") => "PayloadCrc", KarError::Integrity("KAR archive length changed") => "ArchiveLength", + KarError::Integrity("KAR sparse extents SHA-256 mismatch") => "ExtentsSha", KarError::Integrity(_) => "Integrity", KarError::Profile("KAR PLE partition missing") => "PartitionMissing", KarError::Profile("KAR PLE partition/source mapping mismatch") => "PartitionMapping", diff --git a/crates/model-format/examples/kar_census.rs b/crates/model-format/examples/kar_census.rs new file mode 100644 index 00000000..ebb56d28 --- /dev/null +++ b/crates/model-format/examples/kar_census.rs @@ -0,0 +1,110 @@ +//! Read-only census of a KAR archive: every record with its kind, size and offset, which of them the serve path reads, +//! and the totals per kind. Reads the 256-byte header, the names and the directory (about a megabyte) and nothing +//! of the payload, so it is safe to run against the 55 GB archive on a host whose disk is struggling. +//! +//! kar_census ARCHIVE full table + totals +//! kar_census ARCHIVE --summary totals and the PLE partitions only +//! kar_census ARCHIVE --extents also list the page-aligned extents of a sparse copy +//! kar_census ARCHIVE --hash-extents [--throttle-mib-s N] +//! ALSO read the extents (about 16 GB) and print their pinned SHA-256 +//! (default throttle 200 MiB/s). Heavy I/O: only when the host is steady, +//! and only for an archive that has matched its full pinned SHA-256. +//! +//! Nothing is written, nothing needs a GPU. +use leleka_model_format::kar::{KarInspection, PLE_PART_NAMES, digest_extents}; +use std::{fs::File, process::ExitCode, time::{Duration, Instant}}; + +fn main() -> ExitCode { + let mut path = None; + let (mut summary, mut list_extents, mut hash) = (false, false, false); + let mut throttle_mib_s = 200u64; + let mut args = std::env::args().skip(1); + while let Some(arg) = args.next() { + match arg.as_str() { + "--summary" => summary = true, + "--extents" => list_extents = true, + "--hash-extents" => hash = true, + "--throttle-mib-s" => match args.next().and_then(|v| v.parse().ok()).filter(|v| *v > 0) { + Some(v) => throttle_mib_s = v, + None => return usage("--throttle-mib-s needs a positive number"), + }, + "-h" | "--help" => return usage(""), + other if other.starts_with('-') => return usage(&format!("unknown option {other}")), + other => { + if path.replace(other.to_owned()).is_some() { + return usage("one archive path only"); + } + } + } + } + let Some(path) = path else { return usage("an archive path is required") }; + let file = match File::open(&path) { + Ok(file) => file, + Err(error) => { + eprintln!("cannot open {path}: {error}"); + return ExitCode::FAILURE; + } + }; + let inspection = match KarInspection::inspect(file) { + Ok(inspection) => inspection, + Err(error) => { + eprintln!("not a valid KAR archive: {error}"); + return ExitCode::FAILURE; + } + }; + let census = match inspection.census(&PLE_PART_NAMES) { + Ok(census) => census, + Err(error) => { + eprintln!("census failed: {error}"); + return ExitCode::FAILURE; + } + }; + print!("{}", census.render(!summary)); + if list_extents { + println!("\n# extents of a sparse copy (page-aligned, offset len)"); + for e in &census.serve.extents { + println!("extent {} {}", e.offset, e.len); + } + } + if hash { + let file = match File::open(&path) { + Ok(file) => file, + Err(error) => { + eprintln!("cannot reopen {path}: {error}"); + return ExitCode::FAILURE; + } + }; + let total = census.serve.extent_bytes(); + eprintln!("hashing {} MiB of extents at <= {throttle_mib_s} MiB/s", total >> 20); + let started = Instant::now(); + let mut done = 0u64; + let digest = digest_extents(&file, &census.serve.extents, |n| { + done += n; + let due = Duration::from_secs_f64(done as f64 / (throttle_mib_s as f64 * 1_048_576.0)); + if let Some(wait) = due.checked_sub(started.elapsed()) { + std::thread::sleep(wait); + } + }); + match digest { + Ok(digest) => { + let hex: String = digest.iter().map(|b| format!("{b:02x}")).collect(); + println!("\nple_extents_sha256={hex}"); + println!("extent_bytes_hashed={done} in {:.1}s", started.elapsed().as_secs_f64()); + println!("const_line: pub const PLE_EXTENTS_SHA256: [u8; 32] = {digest:?};"); + } + Err(error) => { + eprintln!("hashing failed: {error}"); + return ExitCode::FAILURE; + } + } + } + ExitCode::SUCCESS +} + +fn usage(problem: &str) -> ExitCode { + if !problem.is_empty() { + eprintln!("{problem}"); + } + eprintln!("usage: kar_census ARCHIVE [--summary] [--extents] [--hash-extents [--throttle-mib-s N]]"); + if problem.is_empty() { ExitCode::SUCCESS } else { ExitCode::from(2) } +} diff --git a/crates/model-format/src/kar.rs b/crates/model-format/src/kar.rs index 7a15edea..074c6635 100644 --- a/crates/model-format/src/kar.rs +++ b/crates/model-format/src/kar.rs @@ -218,6 +218,9 @@ pub struct KarInspection { sections: Vec
, sources: Vec, directory: Vec, + /// Offset of the first tensor section (header, directory and names lie before it). + payload_offset: u64, + metadata_bytes: u64, } pub struct KarImmutableSource { inspection: KarInspection, @@ -230,6 +233,8 @@ impl KarInspection { sections, sources, directory, + payload_offset, + metadata_bytes, } = inspect_file(file).map_err(typed)?; Ok(Self { summary, @@ -237,6 +242,8 @@ impl KarInspection { sections, sources, directory, + payload_offset, + metadata_bytes, }) } pub fn summary(&self) -> &KarSummary { @@ -448,6 +455,9 @@ struct Parsed { sections: Vec
, sources: Vec, directory: Vec, + payload_offset: u64, + /// Header + name table + directory: everything `inspect` reads of the file. + metadata_bytes: u64, } fn inspect_file(mut file: File) -> Result { let file_bytes = file.metadata().map_err(|error| error.to_string())?.len(); @@ -726,6 +736,8 @@ fn inspect_file(mut file: File) -> Result { sections, sources, directory, + payload_offset, + metadata_bytes: HEADER_BYTES as u64 + string_bytes + directory_bytes, }) } @@ -986,6 +998,10 @@ impl KarPleProfile { /// Bounds validation does not authenticate the manifest's origin. Only the /// admitted model-binding loader may supply its trusted pinned expectations. pub fn new(spec: KarPleProfileSpec) -> Result { + Self::with_total_rows(spec, PLE_ROWS) + } + /// `new` for a table of `total_rows` rows: the pinned table has `PLE_ROWS`; tests build miniature archives. + fn with_total_rows(spec: KarPleProfileSpec, total_rows: u64) -> Result { if spec.archive_bytes < 256 || spec.virtual_f32_bytes == 0 || spec.parts.is_empty() @@ -1015,7 +1031,7 @@ impl KarPleProfile { } next = next .checked_add(p.row_count) - .filter(|n| *n <= PLE_ROWS) + .filter(|n| *n <= total_rows) .ok_or(KarError::Range("KAR PLE row count overflow"))?; p.row_count .checked_mul(640) @@ -1023,7 +1039,7 @@ impl KarPleProfile { .filter(|n| *n <= spec.virtual_f32_bytes) .ok_or(KarError::Range("KAR PLE virtual source range"))?; } - if next != PLE_ROWS { + if next != total_rows { return Err(KarError::Profile("KAR PLE table extent mismatch")); } Ok(Self { spec }) @@ -1064,6 +1080,46 @@ fn is_unlinked(_file: &File) -> bool { false } +/// How the content of the archive was vouched for when it was opened. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum KarTrust { + /// The whole archive was read once and matched its pinned SHA-256 and every section CRC-32. + FullPass, + /// A verification stamp for exactly this file in exactly this state (device, inode, size, mtime, ctime) stood in for the pass. + Stamp, + /// The parent process copied this unlinked memfd from a stamped file and said so (`--kar-attested-by-stamp`). + AttestedMemfd, + /// A sparse memfd (`verify_sparse`): the bytes of its extents matched the pinned digest of the extents; the rest is a hole. + SparseExtents, +} +impl KarTrust { + pub fn as_str(self) -> &'static str { + match self { + KarTrust::FullPass => "full-pass", + KarTrust::Stamp => "stamp", + KarTrust::AttestedMemfd => "attested-memfd", + KarTrust::SparseExtents => "sparse-extents", + } + } +} + +/// What opening the archive read from it (not what a request reads later): the figures behind the startup log line. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct KarStartupRead { + pub trust: KarTrust, + /// Header, name table and directory (`inspect`). + pub metadata_bytes: u64, + /// The partition books (8 bytes each). + pub book_bytes: u64, + /// Bytes hashed by the verification: the whole archive for `FullPass`, the extents for `SparseExtents`, otherwise 0. + pub hashed_bytes: u64, +} +impl KarStartupRead { + pub fn total_bytes(&self) -> u64 { + self.metadata_bytes + self.book_bytes + self.hashed_bytes + } +} + pub struct VerifiedKarPleArtifact { reader: KarInspection, profile: KarPleProfile, @@ -1071,9 +1127,29 @@ pub struct VerifiedKarPleArtifact { books: Vec<[u16; 4]>, /// Handles with their own file objects for the parallel row reads (`independent_handles`), opened on first use. handles: std::sync::OnceLock>, + /// Every range the serve path reads (page-aligned, merged): the metadata, the books and the PLE rows. + serve_extents: Vec, + /// Verified against a pinned digest of `serve_extents` instead of the whole archive (a sparse memfd). + sparse: bool, + startup: KarStartupRead, + /// The state of an ordinary archive file when it was verified (`None` for a sealed memfd, which cannot change, and where the + /// platform has no such fields). Every row read compares the open file with it: a write, `touch`, `chmod` or rename of the + /// file after verification refuses the read instead of serving bytes nobody checked. See `identity_recheck_enabled`. + identity: Option, } impl VerifiedKarPleArtifact { pub fn verify(source: KarImmutableSource, profile: KarPleProfile) -> Result { + Self::verify_with(source, profile, None) + } + /// `verify` for a sealed memfd that holds only the bytes the serve path reads (holes elsewhere, same file offsets and + /// length): the full-archive SHA-256 and the payload CRCs cannot be computed, so the pinned `extents_sha256` + /// ([`digest_extents_with`] over `serve_extents`, measured once from the archive that matched its full pin) stands + /// in for them, and the directory digest in the header (checked by `inspect`, inside the extents) covers the rest. + /// Fails closed: a wrong digest, a read range outside the extents or a changed length is an error. + pub fn verify_sparse(source: KarImmutableSource, profile: KarPleProfile, extents_sha256: &[u8; 32]) -> Result { + Self::verify_with(source, profile, Some(extents_sha256)) + } + fn verify_with(source: KarImmutableSource, profile: KarPleProfile, sparse_pin: Option<&[u8; 32]>) -> Result { let mut reader = source.inspection; if reader.file.metadata().map_err(KarError::Io)?.len() != profile.spec.archive_bytes || reader.summary.archive_bytes != profile.spec.archive_bytes @@ -1094,9 +1170,19 @@ impl VerifiedKarPleArtifact { let stamps = crate::verify_stamp::global(); // An unlinked sealed memfd: only if the parent attested the copy (see `set_attested_archive`). let attested_memfd = identity.is_none() && crate::verify_stamp::attested_archive() && is_unlinked(&reader.file); - let trusted = attested_memfd - || matches!((stamps, identity.as_ref()), (Some(s), Some(id)) if s.trusts("kar", &profile.spec.archive_sha256, id)); - if !trusted { + let stamped = matches!((stamps, identity.as_ref()), (Some(s), Some(id)) if s.trusts("kar", &profile.spec.archive_sha256, id)); + let trusted = attested_memfd || stamped; + let trust = if sparse_pin.is_some() { + KarTrust::SparseExtents + } else if attested_memfd { + KarTrust::AttestedMemfd + } else if stamped { + KarTrust::Stamp + } else { + KarTrust::FullPass + }; + // A sparse copy never takes a stamp or an attestation: those speak for the whole archive, which it does not hold. + if sparse_pin.is_none() && !trusted { reader.verify_integrity(profile.spec.archive_bytes, &profile.spec.archive_sha256)?; if let (Some(stamps), Some(before)) = (stamps, identity) && reader @@ -1111,6 +1197,7 @@ impl VerifiedKarPleArtifact { } let mut parts = Vec::new(); let mut books = Vec::new(); + let mut book_at_list = Vec::new(); parts .try_reserve_exact(profile.spec.parts.len()) .map_err(|_| KarError::Allocation)?; @@ -1158,18 +1245,75 @@ impl VerifiedKarPleArtifact { stride, }); books.push(book); + book_at_list.push(book_at); } - if reader.file.metadata().map_err(KarError::Io)?.len() != profile.spec.archive_bytes { + let serve_extents = normalize_extents( + &extents::exact_reads(reader.payload_offset, &parts, &book_at_list)?, + profile.spec.archive_bytes, + )?; + if let Some(pin) = sparse_pin { + // Every byte a row read can touch lies inside the extents (a row read is bounded by its partition), so no + // read can land in a hole; then the bytes of the extents must be the pinned ones. + for part in &parts { + for read in part.reads()? { + if !extents_cover(&serve_extents, read.offset, read.len) { + return Err(KarError::Range("KAR PLE read outside the sparse extents")); + } + } + } + let digest = digest_extents(&reader.file, &serve_extents, |_| {})?; + if &digest != pin { + return Err(KarError::Integrity("KAR sparse extents SHA-256 mismatch")); + } + } + let after = reader.file.metadata().map_err(KarError::Io)?; + if after.len() != profile.spec.archive_bytes { return Err(KarError::Integrity("KAR archive length changed")); } + // An ordinary file must be in the very state that was verified (or stamped) at the start of this call. + if identity.is_some() && crate::verify_stamp::FileIdentity::of(&after) != identity { + return Err(KarError::Integrity("KAR archive file changed while it was verified")); + } + let startup = KarStartupRead { + trust, + metadata_bytes: reader.metadata_bytes, + book_bytes: 8 * parts.len() as u64, + hashed_bytes: if sparse_pin.is_some() { + extents_bytes(&serve_extents) + } else if trusted { + 0 + } else { + profile.spec.archive_bytes + }, + }; Ok(Self { reader, profile, parts, books, handles: std::sync::OnceLock::new(), + serve_extents, + sparse: sparse_pin.is_some(), + startup, + identity: if identity_recheck_enabled() { identity } else { None }, }) } + /// The ranges of the archive the serve path reads (page-aligned, sorted, merged). + pub fn serve_extents(&self) -> &[Extent] { + &self.serve_extents + } + /// Verified as a sparse copy (by the digest of its extents, not the whole archive). + pub fn is_sparse(&self) -> bool { + self.sparse + } + /// What opening this archive read from it, for the startup log (`KarStartupRead`). + pub fn startup_read(&self) -> KarStartupRead { + self.startup + } + /// True when row reads compare the open file with its verified state (an ordinary file, not a memfd). + pub fn rechecks_file_identity(&self) -> bool { + self.identity.is_some() + } pub fn archive_sha256(&self) -> &[u8; 32] { &self.profile.spec.archive_sha256 } @@ -1193,14 +1337,11 @@ impl VerifiedKarPleArtifact { if rows.iter().any(|r| *r >= PLE_ROWS) { return Err(KarError::Range("KAR PLE row outside table")); } - if self.reader.file.metadata().map_err(KarError::Io)?.len() != self.archive_bytes() { - return Err(KarError::Integrity("KAR archive length changed")); - } // 16 rows are 48 random reads of a cold file: eight threads on handles of their own, two rows each. A file the page cache // holds answers each read in about a microsecond, and eight thread starts and joins then cost more than the reads // (about 0.1 ms per token of a decode window); `warm_probe` reads the first row on this thread, times it, and reads the // other fifteen here too when it was served from memory. - let packets = read_rows_parallel(self.row_handles(), &self.parts, self.archive_bytes(), rows, 8, 2, true)?; + let packets = read_rows_parallel(self.row_handles(), &self.parts, self.archive_bytes(), self.identity.as_ref(), rows, 8, 2, true)?; let mut out = [KarPleRowPacket { payload: [0; 50], partition: 0, @@ -1217,7 +1358,7 @@ impl VerifiedKarPleArtifact { /// scale refusals, but positional (`pread`, no seek) and split over a few threads, because the batched prefill /// reads every row of a chunk the cache does not hold at once (tens of thousands on a cold chunk). pub fn read_rows_batch(&self, rows: &[u64]) -> Result, KarError> { - read_rows_parallel(self.row_handles(), &self.parts, self.archive_bytes(), rows, 32, 512, false) + read_rows_parallel(self.row_handles(), &self.parts, self.archive_bytes(), self.identity.as_ref(), rows, 32, 512, false) } /// An owned reader of the same rows (handles of its own and a copy of the partition table) that another thread /// can use while this artifact is busy: the prefill reads the rows of the next chunk ahead. @@ -1226,6 +1367,7 @@ impl VerifiedKarPleArtifact { files: independent_handles(&self.reader.file, ROW_HANDLES), parts: self.parts.clone(), archive_bytes: self.archive_bytes(), + identity: self.identity, }) } } @@ -1263,11 +1405,12 @@ pub struct KarPleRowReader { files: Vec, parts: Vec, archive_bytes: u64, + identity: Option, } impl KarPleRowReader { /// `max_threads` positional-read threads at most (one per 512 rows). pub fn read_rows(&self, rows: &[u64], max_threads: usize) -> Result, KarError> { - read_rows_parallel(&self.files, &self.parts, self.archive_bytes, rows, max_threads, 512, false) + read_rows_parallel(&self.files, &self.parts, self.archive_bytes, self.identity.as_ref(), rows, max_threads, 512, false) } } /// A row read (three positional reads) that a warm file serves in this many nanoseconds or less takes the single-thread path. @@ -1276,10 +1419,12 @@ const WARM_ROW_NS: u128 = 20_000; /// After a cold verdict the next calls read in parallel without probing (a cold file would pay the probe's latency each time). const COLD_SKIP_CALLS: u32 = 256; static COLD_SKIP: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); +#[allow(clippy::too_many_arguments)] fn read_rows_parallel( files: &[File], parts: &[VerifiedPart], archive_bytes: u64, + identity: Option<&crate::verify_stamp::FileIdentity>, rows: &[u64], max_threads: usize, min_rows_per_thread: usize, @@ -1291,9 +1436,7 @@ fn read_rows_parallel( if rows.iter().any(|r| *r >= PLE_ROWS) { return Err(KarError::Range("KAR PLE row outside table")); } - if first.metadata().map_err(KarError::Io)?.len() != archive_bytes { - return Err(KarError::Integrity("KAR archive length changed")); - } + check_archive_state(first, archive_bytes, identity)?; let mut packets = Vec::new(); packets .try_reserve_exact(rows.len()) @@ -1349,6 +1492,38 @@ fn read_rows_parallel( } Ok(packets) } +/// The per-read guard of the archive: the pinned length, and for an ordinary file the state it had when it was verified. One `fstat` (the +/// length check always did one); a different size, modification time or change time (any write, `touch`, `chmod`, rename or hard link made +/// after verification) is refused rather than served. +fn check_archive_state( + file: &File, + archive_bytes: u64, + identity: Option<&crate::verify_stamp::FileIdentity>, +) -> Result<(), KarError> { + let meta = file.metadata().map_err(KarError::Io)?; + if meta.len() != archive_bytes { + return Err(KarError::Integrity("KAR archive length changed")); + } + if let Some(expected) = identity + && crate::verify_stamp::FileIdentity::of(&meta).as_ref() != Some(expected) + { + return Err(KarError::Integrity("KAR archive file changed since it was verified")); + } + Ok(()) +} + +/// `LELEKA_KAR_IDENTITY_RECHECK=off` (or `0`) turns the per-read comparison with the verified file state off (a file system that does not +/// keep `ctime` stable, for example). Read once; the default is on. +fn identity_recheck_enabled() -> bool { + static ENABLED: std::sync::OnceLock = std::sync::OnceLock::new(); + *ENABLED.get_or_init(|| { + !matches!( + std::env::var("LELEKA_KAR_IDENTITY_RECHECK").as_deref().map(str::trim), + Ok("off" | "0" | "no" | "false") + ) + }) +} + fn read_rows_chunk( file: &File, parts: &[VerifiedPart], @@ -1424,6 +1599,15 @@ fn read_at(file: &File, offset: u64, buffer: &mut [u8]) -> Result<(), KarError> mod nested; pub use nested::{KarNestedRecord, NESTING_TOPDOWN}; +#[path = "kar_extents.rs"] +mod extents; +pub use extents::{ + CensusRecord, EXTENT_ALIGN, Extent, KarCensus, PLE_EXTENTS_SHA256, PLE_PART_NAMES, PLE_PLANES, + PLE_ROW_PLANE_BYTES, PLE_ROW_SCALE_BYTES, PartReads, + RecordClass, ServeReads, digest_extents, digest_extents_with, extents_bytes, extents_cover, + extents_overlap, normalize_extents, +}; + #[cfg(test)] #[path = "../tests/kar_ple/mod.rs"] mod tests; @@ -1432,6 +1616,10 @@ mod tests; #[path = "../tests/kar_crc_slicing.rs"] mod crc_slicing_tests; +#[cfg(test)] +#[path = "../tests/kar_extents.rs"] +mod extents_tests; + #[cfg(test)] mod row_read_tests { use super::*; @@ -1457,7 +1645,10 @@ mod row_read_tests { (x % 0x70) as u8 }) .collect(); - let path = std::env::temp_dir().join(format!("leleka-kar-rows-{}-{:x}", std::process::id(), x)); + // one file per call: the tests run in parallel and several of them touch, chmod or remove theirs + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let unique = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let path = std::env::temp_dir().join(format!("leleka-kar-rows-{}-{:x}-{unique}", std::process::id(), x)); File::create(&path).unwrap().write_all(&bytes).unwrap(); let parts = vec![ VerifiedPart { row_base: 0, row_count: n0, scales: scales0, planes: planes0, stride: stride0 }, @@ -1488,25 +1679,73 @@ mod row_read_tests { // the file is in the page cache: the probe takes the single-thread path (or, on a loaded machine, falls back to threads; // the packets are the same either way) COLD_SKIP.store(0, Ordering::Relaxed); - let probed = read_rows_parallel(&files, &parts, total, &rows, 8, 2, true).unwrap(); + let probed = read_rows_parallel(&files, &parts, total, None, &rows, 8, 2, true).unwrap(); assert!(same(&probed, &reference), "case {case}: probing read"); // after a cold verdict the next calls skip the probe and read in parallel COLD_SKIP.store(3, Ordering::Relaxed); - let parallel = read_rows_parallel(&files, &parts, total, &rows, 8, 2, true).unwrap(); + let parallel = read_rows_parallel(&files, &parts, total, None, &rows, 8, 2, true).unwrap(); assert!(same(¶llel, &reference), "case {case}: parallel read after a cold verdict"); assert_eq!(COLD_SKIP.load(Ordering::Relaxed), 2, "a skipped probe uses up one of the skip calls"); - let unprobed = read_rows_parallel(&files, &parts, total, &rows, 8, 2, false).unwrap(); + let unprobed = read_rows_parallel(&files, &parts, total, None, &rows, 8, 2, false).unwrap(); assert!(same(&unprobed, &reference), "case {case}: no probe"); } COLD_SKIP.store(0, Ordering::Relaxed); // the refusals are the same as before: a row outside the table, a changed archive length let bad = vec![PLE_ROWS; 16]; - assert!(matches!(read_rows_parallel(&files, &parts, total, &bad, 8, 2, true), Err(KarError::Range(_)))); - assert!(matches!(read_rows_parallel(&files, &parts, total + 1, &[1, 2], 8, 2, true), Err(KarError::Integrity(_)))); + assert!(matches!(read_rows_parallel(&files, &parts, total, None, &bad, 8, 2, true), Err(KarError::Range(_)))); + assert!(matches!(read_rows_parallel(&files, &parts, total + 1, None, &[1, 2], 8, 2, true), Err(KarError::Integrity(_)))); // a row beyond the partitions' last row is a range error on the probe path as well let beyond: Vec = (0..16).map(|i| 1500 + i).collect(); - assert!(read_rows_parallel(&files, &parts, total, &beyond, 8, 2, true).is_err()); + assert!(read_rows_parallel(&files, &parts, total, None, &beyond, 8, 2, true).is_err()); drop(files); let _ = std::fs::remove_file(path); } + + #[cfg(unix)] + #[test] + fn an_ordinary_archive_file_must_still_be_in_the_state_that_was_verified() { + use std::os::unix::fs::PermissionsExt; + let (file, parts, total, path) = synthetic(); + let id = crate::verify_stamp::FileIdentity::of(&file.metadata().unwrap()).unwrap(); + let files = vec![file.try_clone().unwrap()]; + let rows: Vec = vec![3, 999, 1000, 1400]; + let ok = read_rows_parallel(&files, &parts, total, Some(&id), &rows, 8, 2, false).unwrap(); + let reference = read_rows_parallel(&files, &parts, total, None, &rows, 8, 2, false).unwrap(); + assert!(same(&ok, &reference), "the check changes no byte that is returned"); + // a sealed memfd has no identity to compare: the length check alone + assert!(check_archive_state(&file, total, None).is_ok()); + assert!(matches!(check_archive_state(&file, total + 1, Some(&id)), Err(KarError::Integrity(m)) if m.contains("length"))); + // the file is touched (mtime and ctime move, size and bytes do not): refused, on every entry point + std::thread::sleep(std::time::Duration::from_millis(30)); + let handle = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); + handle.set_modified(std::time::SystemTime::now()).unwrap(); + drop(handle); + let refused = read_rows_parallel(&files, &parts, total, Some(&id), &rows, 8, 2, false); + assert!(matches!(refused, Err(KarError::Integrity(m)) if m.contains("changed since it was verified"))); + assert!(matches!(check_archive_state(&file, total, Some(&id)), Err(KarError::Integrity(_)))); + // the new state is a new identity: verifying again (and stamping) is how the service goes on + let id2 = crate::verify_stamp::FileIdentity::of(&file.metadata().unwrap()).unwrap(); + assert_ne!(id, id2); + assert!(read_rows_parallel(&files, &parts, total, Some(&id2), &rows, 8, 2, false).is_ok()); + // chmod alone moves ctime and is refused too + std::thread::sleep(std::time::Duration::from_millis(30)); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o400)).unwrap(); + assert!(matches!(check_archive_state(&file, total, Some(&id2)), Err(KarError::Integrity(_)))); + // the reader a prefill thread owns carries the same state + let reader = KarPleRowReader { files: vec![file.try_clone().unwrap()], parts: parts.clone(), archive_bytes: total, identity: Some(id2) }; + assert!(matches!(reader.read_rows(&rows, 4), Err(KarError::Integrity(_)))); + let reader = KarPleRowReader { files, parts, archive_bytes: total, identity: None }; + assert!(same(&reader.read_rows(&rows, 4).unwrap(), &reference)); + let _ = std::fs::remove_file(path); + } + + #[test] + fn the_startup_figures_add_up() { + let read = KarStartupRead { trust: KarTrust::Stamp, metadata_bytes: 1_000, book_bytes: 16, hashed_bytes: 0 }; + assert_eq!(read.total_bytes(), 1_016); + assert_eq!(read.trust.as_str(), "stamp"); + let full = KarStartupRead { trust: KarTrust::FullPass, hashed_bytes: 55_295_529_472, ..read }; + assert_eq!(full.total_bytes(), 55_295_529_472 + 1_016); + assert_eq!((KarTrust::AttestedMemfd.as_str(), KarTrust::FullPass.as_str()), ("attested-memfd", "full-pass")); + } } diff --git a/crates/model-format/src/kar_extents.rs b/crates/model-format/src/kar_extents.rs new file mode 100644 index 00000000..bdf86054 --- /dev/null +++ b/crates/model-format/src/kar_extents.rs @@ -0,0 +1,530 @@ +//! Which bytes of the pinned KAR archive the serve path reads, as a list of extents. +//! +//! Child module of `kar`. The Original serve path reads exactly one thing from the 55.3 GB archive: the rows of the +//! PLE n-gram table (`read_rows_chunk`: 10 bytes of scales and two 20-byte plane rows per row), plus the header, the +//! directory and the two small books it needs at load. Everything else (the level-2 re-encoding of the other shard-0 +//! tensors) is never read. This module names the read bytes: +//! +//! * [`KarInspection::serve_reads`] derives them from the directory alone (header, names and directory are read; no +//! payload byte is), from the same [`VerifiedPart`] geometry the row reader uses, so the list cannot drift from +//! what `read_rows_chunk` touches (a test reads every row of a synthetic archive through a copy that holds *only* +//! the extents); +//! * [`normalize_extents`] widens them to whole 4 KiB pages (a sparse memfd allocates pages, never bytes) and merges; +//! * [`digest_extents_with`] is the pinned hash of a sparse copy: SHA-256 over a domain tag, the extent list and the +//! bytes of the extents, in order; +//! * [`KarCensus`] is the read-only report `examples/kar_census.rs` prints. + +use super::{ + KarError, KarInspection, KarNestedRecord, PLE_ROWS, Sha256, VerifiedPart, read_at, round_up, +}; +use sha2::Digest; +use std::fmt::Write as _; + +/// Granularity of a sparse copy: the page size of the memfd (and of `mlock`). +pub const EXTENT_ALIGN: u64 = 4096; + +/// The two partitions of the pinned `per_layer_token_embd.weight` (order = row order). +pub const PLE_PART_NAMES: [&str; 2] = [ + "per_layer_token_embd.weight#strata-part-001-of-002", + "per_layer_token_embd.weight#strata-part-002-of-002", +]; + +/// Bytes the serve path reads per PLE row: scales (5 f16 words) and two bit-plane rows (5 words each). +pub const PLE_ROW_SCALE_BYTES: u64 = 10; +pub const PLE_ROW_PLANE_BYTES: u64 = 20; +/// Planes the serve path reads (level 2). +pub const PLE_PLANES: u64 = 2; + +/// SHA-256 of the extents of the pinned archive (see [`digest_extents_with`]): 2 extents, 16,000,348,672 bytes, measured on the +/// real archive file on the 5090 server (2026-11-02, `kar_census ARCHIVE --hash-extents`, 161.9 s at <= 300 MiB/s) -- the file +/// that every holder job copies and whose full SHA-256 the engine checks on each of those copies. Hex: +/// 7568b1211419a7c10a9b39a86230f75b7fa9c02839e36c9b5f2494ec7af72143. While it is all zero a sparse copy is refused unless the +/// operator supplies the digest explicitly. +pub const PLE_EXTENTS_SHA256: [u8; 32] = [ + 117, 104, 177, 33, 20, 25, 167, 193, 10, 155, 57, 168, 98, 48, 247, 91, 127, 169, 192, 40, 57, 227, 108, 155, 95, 36, 148, 236, 122, + 247, 33, 67, +]; + +const DOMAIN: &[u8] = b"leleka-kar-extents-v1\0"; +const HASH_CHUNK: usize = 8 << 20; + +/// A byte range of the archive. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Extent { + pub offset: u64, + pub len: u64, +} + +impl Extent { + pub fn new(offset: u64, len: u64) -> Self { + Self { offset, len } + } + pub fn end(&self) -> u64 { + self.offset + self.len + } +} + +/// Total bytes of a list of extents. +pub fn extents_bytes(extents: &[Extent]) -> u64 { + extents.iter().map(|e| e.len).sum() +} + +/// Page-align (outwards) and merge. The result is sorted, disjoint and non-adjacent; the last extent is clamped to +/// `archive_bytes`. A range beyond the archive is an error; empty ranges are dropped. +pub fn normalize_extents(raw: &[Extent], archive_bytes: u64) -> Result, KarError> { + let mut ranges = Vec::new(); + ranges + .try_reserve_exact(raw.len()) + .map_err(|_| KarError::Allocation)?; + for e in raw.iter().filter(|e| e.len > 0) { + let end = e + .offset + .checked_add(e.len) + .filter(|end| *end <= archive_bytes) + .ok_or(KarError::Range("KAR extent outside the archive"))?; + let start = e.offset / EXTENT_ALIGN * EXTENT_ALIGN; + let end = round_up(end, EXTENT_ALIGN) + .ok_or(KarError::Range("KAR extent overflow"))? + .min(archive_bytes); + ranges.push((start, end)); + } + ranges.sort_unstable(); + let mut out: Vec = Vec::with_capacity(ranges.len()); + for (start, end) in ranges { + match out.last_mut() { + Some(last) if start <= last.end() => { + if end > last.end() { + last.len = end - last.offset; + } + } + _ => out.push(Extent::new(start, end - start)), + } + } + Ok(out) +} + +/// Is `[offset, offset + len)` inside one extent of the sorted, disjoint list? +pub fn extents_cover(extents: &[Extent], offset: u64, len: u64) -> bool { + if len == 0 { + return true; + } + let Some(end) = offset.checked_add(len) else { return false }; + let index = extents.partition_point(|e| e.offset <= offset); + index > 0 && extents[index - 1].end() >= end +} + +/// Bytes of `extents` that fall inside `[offset, offset + len)`. +pub fn extents_overlap(extents: &[Extent], offset: u64, len: u64) -> u64 { + let end = offset.saturating_add(len); + extents + .iter() + .map(|e| e.end().min(end).saturating_sub(e.offset.max(offset))) + .sum() +} + +/// The pinned hash of a sparse copy: SHA-256 over the domain tag, the number of extents, `(offset, len)` of each, and +/// then the bytes of each extent in order. `read(offset, buffer)` must fill the buffer from the archive (or its sparse +/// copy); `progress(bytes)` is called after each chunk and may sleep to throttle the pass. +pub fn digest_extents_with( + extents: &[Extent], + mut read: impl FnMut(u64, &mut [u8]) -> Result<(), KarError>, + mut progress: impl FnMut(u64), +) -> Result<[u8; 32], KarError> { + let mut hash = Sha256::new(); + hash.update(DOMAIN); + hash.update((extents.len() as u64).to_le_bytes()); + for e in extents { + hash.update(e.offset.to_le_bytes()); + hash.update(e.len.to_le_bytes()); + } + let mut buffer = Vec::new(); + buffer + .try_reserve_exact(HASH_CHUNK) + .map_err(|_| KarError::Allocation)?; + buffer.resize(HASH_CHUNK, 0); + for e in extents { + let mut done = 0u64; + while done < e.len { + let n = (e.len - done).min(HASH_CHUNK as u64) as usize; + read(e.offset + done, &mut buffer[..n])?; + hash.update(&buffer[..n]); + done += n as u64; + progress(n as u64); + } + } + Ok(hash.finalize().into()) +} + +/// [`digest_extents_with`] over a file (positional reads). +pub fn digest_extents( + file: &std::fs::File, + extents: &[Extent], + progress: impl FnMut(u64), +) -> Result<[u8; 32], KarError> { + digest_extents_with(extents, |offset, buffer| read_at(file, offset, buffer), progress) +} + +impl VerifiedPart { + /// The bytes `read_rows_chunk` reads for this partition: the scales, and the first [`PLE_PLANES`] planes. + pub(super) fn reads(&self) -> Result<[Extent; 3], KarError> { + let rows = self.row_count; + let plane_bytes = rows + .checked_mul(PLE_ROW_PLANE_BYTES) + .ok_or(KarError::Range("KAR PLE plane overflow"))?; + let scale_bytes = rows + .checked_mul(PLE_ROW_SCALE_BYTES) + .ok_or(KarError::Range("KAR PLE scale overflow"))?; + let plane = |k: u64| -> Result { + let at = k + .checked_mul(self.stride) + .and_then(|n| self.planes.checked_add(n)) + .ok_or(KarError::Range("KAR PLE plane overflow"))?; + Ok(Extent::new(at, plane_bytes)) + }; + Ok([Extent::new(self.scales, scale_bytes), plane(0)?, plane(1)?]) + } +} + +/// Every range the serve path reads, exactly (not page-aligned): the metadata `[0, payload_offset)`, the two-word +/// books the verifier reads, and the rows of the PLE partitions. +pub(super) fn exact_reads( + payload_offset: u64, + parts: &[VerifiedPart], + book_at: &[u64], +) -> Result, KarError> { + let mut out = vec![Extent::new(0, payload_offset)]; + for (part, book) in parts.iter().zip(book_at) { + out.extend(part.reads()?); + out.push(Extent::new(*book, 8)); + } + Ok(out) +} + +/// One partition of the PLE table as the census sees it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PartReads { + pub name: String, + pub rows: u64, + pub scales: Extent, + pub planes: [Extent; 2], + pub book: Extent, +} + +/// What the serve path reads of an archive. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ServeReads { + /// `[0, payload_offset)`: header, directory, names. + pub metadata: Extent, + pub parts: Vec, + /// Exactly the bytes read, sorted and merged where they touch. + pub exact: Vec, + /// The page-aligned form a sparse copy holds. + pub extents: Vec, +} + +impl ServeReads { + pub fn exact_bytes(&self) -> u64 { + extents_bytes(&self.exact) + } + pub fn extent_bytes(&self) -> u64 { + extents_bytes(&self.extents) + } +} + +fn merge_exact(mut raw: Vec) -> Vec { + raw.retain(|e| e.len > 0); + raw.sort_unstable(); + let mut out: Vec = Vec::with_capacity(raw.len()); + for e in raw { + match out.last_mut() { + Some(last) if e.offset <= last.end() => { + if e.end() > last.end() { + last.len = e.end() - last.offset; + } + } + _ => out.push(e), + } + } + out +} + +/// The `VerifiedPart` a PLE partition record yields (the same fields `VerifiedKarPleArtifact::verify` derives from the +/// raw directory bytes), plus the position of its first book. +pub(super) fn part_from_record(record: &KarNestedRecord, row_base: u64) -> Result<(VerifiedPart, u64), KarError> { + if record.dimensions.len() != 2 + || record.dimensions[0] != 160 + || record.group != 32 + || record.nesting != 0 + || record.planes_min > 2 + || record.planes_max < 2 + || record.planes_stored < 2 + { + return Err(KarError::Profile("KAR PLE partition/source mapping mismatch")); + } + let part = VerifiedPart { + row_base, + row_count: record.dimensions[1], + scales: record.scales_offset, + planes: record.planes_offset, + stride: u64::from(record.plane_stride_bytes), + }; + let book = record + .books_offset + .checked_add(4) + .ok_or(KarError::Range("KAR PLE book overflow"))?; + Ok((part, book)) +} + +impl KarInspection { + /// Offset of the first tensor section; everything before it is header, directory and names. + pub fn payload_offset(&self) -> u64 { + self.payload_offset + } + + /// What the serve path reads of this archive, derived from the directory alone. `part_names` are the PLE + /// partitions in row order ([`PLE_PART_NAMES`] for the pinned archive). + pub fn serve_reads(&self, part_names: &[&str]) -> Result { + let mut parts = Vec::new(); + let mut verified = Vec::new(); + let mut books = Vec::new(); + let mut row_base = 0u64; + for name in part_names { + let record = self.nested_record(name)?; + let (part, book) = part_from_record(&record, row_base)?; + row_base = row_base + .checked_add(part.row_count) + .ok_or(KarError::Range("KAR PLE row count overflow"))?; + let [scales, p0, p1] = part.reads()?; + parts.push(PartReads { + name: record.name.clone(), + rows: part.row_count, + scales, + planes: [p0, p1], + book: Extent::new(book, 8), + }); + verified.push(part); + books.push(book); + } + let archive_bytes = self.summary.archive_bytes; + let raw = exact_reads(self.payload_offset, &verified, &books)?; + let exact = merge_exact(raw.clone()); + let extents = normalize_extents(&raw, archive_bytes)?; + Ok(ServeReads { + metadata: Extent::new(0, self.payload_offset), + parts, + exact, + extents, + }) + } + + /// The read-only report of the directory: every record, the class of each, what the serve path reads of it. + pub fn census(&self, part_names: &[&str]) -> Result { + let serve = self.serve_reads(part_names)?; + let nested = self.nested_records()?; + let mut records = Vec::with_capacity(self.sources.len()); + for source in &self.sources { + let ple = serve.parts.iter().find(|p| p.name == source.name); + let stored = nested + .iter() + .find(|n| n.name == source.name) + .map(|n| n.planes_stored); + let class = match (ple.is_some(), source.storage_class) { + (true, _) => RecordClass::PleRows, + (false, 0) => RecordClass::NestedUnread, + (false, _) => RecordClass::RawUnread, + }; + let section = Extent::new(source.section_offset, source.section_bytes); + records.push(CensusRecord { + name: source.name.clone(), + class, + dimensions: source.dimensions.clone(), + dtype: source.dtype, + n_elements: source.n_elements, + planes_stored: stored, + section, + exact_read_bytes: extents_overlap(&serve.exact, section.offset, section.len), + extent_bytes: extents_overlap(&serve.extents, section.offset, section.len), + }); + } + Ok(KarCensus { + archive_bytes: self.summary.archive_bytes, + payload_offset: self.payload_offset, + records, + metadata_extent_bytes: extents_overlap(&serve.extents, 0, serve.metadata.len), + serve, + }) + } +} + +/// What the serve path does with a record. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RecordClass { + /// A PLE partition: `read_rows_chunk` reads its scales and two planes. + PleRows, + /// A nested (bit-plane) record the serve path never reads from the archive. + NestedUnread, + /// A raw record the serve path never reads from the archive. + RawUnread, +} + +impl RecordClass { + pub fn label(self) -> &'static str { + match self { + Self::PleRows => "ple-rows (read)", + Self::NestedUnread => "nested (never read)", + Self::RawUnread => "raw (never read)", + } + } +} + +#[derive(Clone, Debug)] +pub struct CensusRecord { + pub name: String, + pub class: RecordClass, + pub dimensions: Vec, + pub dtype: u8, + pub n_elements: u64, + /// Bit-planes physically stored (nested records). + pub planes_stored: Option, + pub section: Extent, + /// Bytes of this section the serve path reads (exact). + pub exact_read_bytes: u64, + /// Bytes of this section a page-aligned sparse copy holds. + pub extent_bytes: u64, +} + +#[derive(Clone, Debug)] +pub struct KarCensus { + pub archive_bytes: u64, + pub payload_offset: u64, + pub records: Vec, + pub serve: ServeReads, + /// Page-aligned bytes the sparse copy holds inside `[0, payload_offset)`. + pub metadata_extent_bytes: u64, +} + +/// Totals of one class. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ClassTotals { + pub records: u64, + pub elements: u64, + pub section_bytes: u64, + pub exact_read_bytes: u64, + pub extent_bytes: u64, +} + +impl KarCensus { + pub fn totals(&self, class: RecordClass) -> ClassTotals { + let mut t = ClassTotals::default(); + for r in self.records.iter().filter(|r| r.class == class) { + t.records += 1; + t.elements += r.n_elements; + t.section_bytes += r.section.len; + t.exact_read_bytes += r.exact_read_bytes; + t.extent_bytes += r.extent_bytes; + } + t + } + + /// Bytes of the archive that no sparse copy needs. + pub fn unread_extent_bytes(&self) -> u64 { + self.archive_bytes - self.serve.extent_bytes() + } + + /// Render the report. `all_records` lists every record (otherwise only the totals and the PLE partitions). + pub fn render(&self, all_records: bool) -> String { + let gib = |b: u64| b as f64 / (1u64 << 30) as f64; + let pct = |part: u64, whole: u64| 100.0 * part as f64 / whole.max(1) as f64; + let mut out = String::new(); + let _ = writeln!(out, "archive_bytes={}", self.archive_bytes); + let _ = writeln!(out, "tensor_records={}", self.records.len()); + let _ = writeln!( + out, + "metadata: header+directory+names = [0, {}) = {} bytes (page-aligned copy: {} bytes)", + self.payload_offset, self.payload_offset, self.metadata_extent_bytes + ); + if all_records { + let _ = writeln!(out, "\n# index class section_offset section_bytes elements planes read_exact in_sparse_copy name dims"); + for (i, r) in self.records.iter().enumerate() { + let _ = writeln!( + out, + "{i:>5} {:<20} {:>16} {:>15} {:>14} {:>6} {:>12} {:>14} {} {:?}", + r.class.label(), + r.section.offset, + r.section.len, + r.n_elements, + r.planes_stored.map_or("raw".to_owned(), |p| p.to_string()), + r.exact_read_bytes, + r.extent_bytes, + r.name, + r.dimensions + ); + } + } else { + for (i, r) in self.records.iter().enumerate().filter(|(_, r)| r.class == RecordClass::PleRows) { + let _ = writeln!( + out, + "ple record {i}: {} section [{}, +{}) read_exact={} in_sparse_copy={}", + r.name, r.section.offset, r.section.len, r.exact_read_bytes, r.extent_bytes + ); + } + } + let _ = writeln!(out, "\n# totals per kind"); + let _ = writeln!(out, "kind records elements section_bytes read_exact_bytes sparse_copy_bytes"); + for class in [RecordClass::PleRows, RecordClass::NestedUnread, RecordClass::RawUnread] { + let t = self.totals(class); + let _ = writeln!( + out, + "{:<20} {:>8} {:>14} {:>16} {:>17} {:>18}", + class.label(), + t.records, + t.elements, + t.section_bytes, + t.exact_read_bytes, + t.extent_bytes + ); + } + let _ = writeln!(out, "\n# serve path reads (derived from the same geometry as read_rows_chunk)"); + for p in &self.serve.parts { + let _ = writeln!( + out, + "part {}: rows={} scales=[{}, +{}) plane0=[{}, +{}) plane1=[{}, +{}) book=[{}, +8)", + p.name, + p.rows, + p.scales.offset, + p.scales.len, + p.planes[0].offset, + p.planes[0].len, + p.planes[1].offset, + p.planes[1].len, + p.book.offset + ); + } + let exact = self.serve.exact_bytes(); + let ext = self.serve.extent_bytes(); + let _ = writeln!(out, "serve_read_exact_bytes={exact} ({:.3} GiB, {:.2} % of the archive)", gib(exact), pct(exact, self.archive_bytes)); + let _ = writeln!(out, "sparse_copy_bytes={ext} ({:.3} GiB, {:.2} % of the archive) in {} extents", gib(ext), pct(ext, self.archive_bytes), self.serve.extents.len()); + let unread = self.unread_extent_bytes(); + let _ = writeln!(out, "never_read_bytes={unread} ({:.3} GiB, {:.2} % of the archive; archive minus the sparse copy)", gib(unread), pct(unread, self.archive_bytes)); + let nested = self.totals(RecordClass::NestedUnread); + let raw = self.totals(RecordClass::RawUnread); + let _ = writeln!( + out, + "unread_records_section_bytes={} (nested {} + raw {})", + nested.section_bytes + raw.section_bytes, + nested.section_bytes, + raw.section_bytes + ); + if let Some(first) = self.records.iter().find(|r| r.class == RecordClass::PleRows) { + let _ = writeln!( + out, + "bytes_before_first_ple_section={} ({:.2} % of the archive)", + first.section.offset, + pct(first.section.offset, self.archive_bytes) + ); + } + let _ = writeln!(out, "ple_rows_expected={PLE_ROWS}"); + let _ = writeln!(out, "ple_rows_found={}", self.serve.parts.iter().map(|p| p.rows).sum::()); + out + } +} diff --git a/crates/model-format/src/readahead.rs b/crates/model-format/src/readahead.rs index f728980e..75a8fc8d 100644 --- a/crates/model-format/src/readahead.rs +++ b/crates/model-format/src/readahead.rs @@ -103,6 +103,19 @@ fn advise_willneed(file: &File, offset: u64, len: u64) { #[cfg(not(target_os = "linux"))] fn advise_willneed(_file: &File, _offset: u64, _len: u64) {} +/// Drop the clean page-cache pages of a span that has been read and handed on (`POSIX_FADV_DONTNEED`, never `drop_caches`; +/// best effort, a no-op for a memfd). A hash pass reads each byte once: without this the 55 GB archive and the 84 GB of shards +/// would sit in the page cache after the pass as a second copy of what the process keeps (or does not need) in its own memory. +#[cfg(target_os = "linux")] +fn evict_span(file: &File, offset: u64, len: u64) { + if let Some(len) = std::num::NonZeroU64::new(len) { + let _ = rustix::fs::fadvise(file, offset, Some(len), rustix::fs::Advice::DontNeed); + } +} + +#[cfg(not(target_os = "linux"))] +fn evict_span(_file: &File, _offset: u64, _len: u64) {} + /// Run `body` with `fanout` receivers that each get every chunk of `file[start .. start + bytes]`, in order. /// The reader thread ends when the span is read, when a read fails (the error is the last item) or when every /// receiver is gone. `body` must drain or drop its receivers. @@ -150,6 +163,8 @@ pub(crate) fn with_read_ahead( } return; } + // The bytes are in `buffer` now; the cached pages behind them are not needed again by this pass. + evict_span(file, start + offset, count as u64); let chunk = Arc::new(Chunk { offset, data: buffer, diff --git a/crates/model-format/tests/kar_extents.rs b/crates/model-format/tests/kar_extents.rs new file mode 100644 index 00000000..0c63989d --- /dev/null +++ b/crates/model-format/tests/kar_extents.rs @@ -0,0 +1,531 @@ +//! Extents of the bytes the serve path reads, census and sparse verification over synthetic archives. +//! Miniature archives with the real layout rules (contiguous 256-aligned sections, nested bit-plane records, raw +//! records); no model bytes. They never qualify a serving capability. +use super::*; +use std::{ + os::unix::fs::FileExt, + path::PathBuf, + sync::atomic::{AtomicU64, Ordering}, +}; + +const PAGE: u64 = 4096; + +enum Kind { + /// A PLE partition: dims `[160, rows]`, `stored` planes. + Ple { rows: u64, stored: u8 }, + /// Another nested record (never read by the serve path). + Nested { elements: u64, stored: u8 }, + Raw { elements: u64 }, +} +struct Spec { + name: &'static str, + kind: Kind, +} + +const PART0: &str = "ple.part0"; +const PART1: &str = "ple.part1"; + +fn put16(b: &mut [u8], at: usize, v: u16) { + b[at..at + 2].copy_from_slice(&v.to_le_bytes()); +} +fn put32(b: &mut [u8], at: usize, v: u32) { + b[at..at + 4].copy_from_slice(&v.to_le_bytes()); +} +fn put64(b: &mut [u8], at: usize, v: u64) { + b[at..at + 8].copy_from_slice(&v.to_le_bytes()); +} + +/// Build an archive. Every payload byte is below 0x70, so no f16 word reads as non-finite whatever its alignment. +fn build(specs: &[Spec]) -> Vec { + let n = specs.len(); + let mut names = Vec::new(); + let mut name_at = Vec::new(); + for s in specs { + name_at.push(names.len()); + names.extend_from_slice(s.name.as_bytes()); + names.push(0); + } + let directory_offset = 256u64; + let string_offset = round_up(directory_offset + 192 * n as u64, 64).unwrap(); + let payload_offset = round_up(string_offset + names.len() as u64, 256).unwrap(); + // section sizes + struct Layout { + section: u64, + bytes: u64, + scales: u64, + scales_bytes: u64, + books: u64, + books_bytes: u64, + planes: u64, + stride: u64, + padded: u64, + elements: u64, + stored: u8, + nested: bool, + } + let mut layouts = Vec::new(); + let mut cursor = payload_offset; + for s in specs { + let (elements, stored, nested) = match s.kind { + Kind::Ple { rows, stored } => (rows * 160, stored, true), + Kind::Nested { elements, stored } => (elements, stored, true), + Kind::Raw { elements } => (elements, 0, false), + }; + let l = if nested { + let padded = round_up(elements, 32).unwrap(); + let scales_bytes = padded / 32 * 2; + let books = round_up(cursor + scales_bytes, 16).unwrap(); + let books_bytes = (1u64 << (u32::from(stored) + 2)) - 4; + let planes = round_up(books + books_bytes, 16).unwrap(); + let stride = round_up(padded / 32 * 4, 16).unwrap(); + let end = planes + u64::from(stored) * stride; + Layout { + section: cursor, + bytes: round_up(end - cursor, 256).unwrap(), + scales: cursor, + scales_bytes, + books, + books_bytes, + planes, + stride, + padded, + elements, + stored, + nested, + } + } else { + Layout { + section: cursor, + bytes: round_up(elements * 4, 256).unwrap(), + scales: 0, + scales_bytes: 0, + books: 0, + books_bytes: 0, + planes: 0, + stride: 0, + padded: elements, + elements, + stored: 0, + nested, + } + }; + cursor += l.bytes; + layouts.push(l); + } + let archive_bytes = cursor; + let mut b = vec![0u8; archive_bytes as usize]; + let mut x = 0x9E37_79B9_7F4A_7C15u64; + for byte in &mut b[payload_offset as usize..] { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + *byte = (x % 0x70) as u8; + } + b[..8].copy_from_slice(b"KARCHIV2"); + put32(&mut b, 8, 2); + put32(&mut b, 12, 0x0403_0201); + put32(&mut b, 16, 256); + put32(&mut b, 20, 192); + put64(&mut b, 24, directory_offset); + put32(&mut b, 32, n as u32); + put64(&mut b, 40, string_offset); + put64(&mut b, 48, names.len() as u64); + put64(&mut b, 56, payload_offset); + put64(&mut b, 64, archive_bytes); + b[string_offset as usize..string_offset as usize + names.len()].copy_from_slice(&names); + let (mut total, mut bits) = (0u64, 0u64); + let (mut min_planes, mut max_planes) = (u8::MAX, 0u8); + let mut f32_offset = 0u64; + for (i, (s, l)) in specs.iter().zip(&layouts).enumerate() { + let r = (directory_offset as usize) + i * 192; + put32(&mut b, r, name_at[i] as u32); + put16(&mut b, r + 4, s.name.len() as u16); + let dims: Vec = match s.kind { + Kind::Ple { rows, .. } => vec![160, rows], + _ => vec![l.elements], + }; + b[r + 6] = dims.len() as u8; + b[r + 7] = u8::from(!l.nested); + for d in 0..4 { + put64(&mut b, r + 8 + d * 8, dims.get(d).copied().unwrap_or(1)); + } + put64(&mut b, r + 48, l.elements); + put64(&mut b, r + 56, l.padded); + put32(&mut b, r + 108, 0); + put64(&mut b, r + 112, l.section); + put64(&mut b, r + 120, l.bytes); + b[r + 128..r + 160].fill(0x22 + i as u8); + put64(&mut b, r + 160, f32_offset); + f32_offset += l.elements * 4; + if l.nested { + b[r + 42] = l.stored; + b[r + 43] = 1; + b[r + 44] = l.stored; + b[r + 45] = 0; + put16(&mut b, r + 46, 32); + put64(&mut b, r + 64, l.scales); + put64(&mut b, r + 72, l.scales_bytes); + put64(&mut b, r + 80, l.books); + put64(&mut b, r + 88, l.books_bytes); + put64(&mut b, r + 96, l.planes); + put32(&mut b, r + 104, l.stride as u32); + bits += u64::from(l.stored) * l.padded + l.padded / 32 * 16; + min_planes = min_planes.min(1); + max_planes = max_planes.max(l.stored); + } + total += l.elements; + let crc = crc32(&b[l.section as usize..(l.section + l.bytes) as usize]); + put32(&mut b, r + 108, crc); + } + put64(&mut b, 72, total); + put64(&mut b, 80, bits); + put64(&mut b, 88, total); + b[96..104].copy_from_slice(&(archive_bytes as f64 * 8.0 / total as f64).to_le_bytes()); + b[104] = if min_planes == u8::MAX { 0 } else { min_planes }; + b[105] = max_planes; + b[106] = 1; + put64(&mut b, 120, f32_offset); + b[128..160].fill(0x11); + let mut hash = Sha256::new(); + hash.update(&b[string_offset as usize..string_offset as usize + names.len()]); + hash.update(&b[256..256 + 192 * n]); + let digest = hash.finalize(); + b[160..192].copy_from_slice(&digest); + let crc = crc32(&b[..192]); + put32(&mut b, 192, crc); + b +} + +fn standard() -> Vec { + vec![ + Spec { name: "dense.big", kind: Kind::Nested { elements: 60_000, stored: 2 } }, + Spec { name: "norm.raw", kind: Kind::Raw { elements: 5_000 } }, + Spec { name: PART0, kind: Kind::Ple { rows: 1000, stored: 3 } }, + Spec { name: PART1, kind: Kind::Ple { rows: 777, stored: 2 } }, + Spec { name: "tail.nested", kind: Kind::Nested { elements: 30_000, stored: 3 } }, + ] +} + +struct Temp(PathBuf); +impl Temp { + fn new(tag: &str) -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + Temp(std::env::temp_dir().join(format!("leleka-extents-{tag}-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)))) + } + fn file(tag: &str, bytes: &[u8]) -> Self { + let t = Self::new(tag); + std::fs::write(&t.0, bytes).unwrap(); + t + } + fn open(&self) -> File { + File::open(&self.0).unwrap() + } +} +impl Drop for Temp { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +/// A sparse copy of `bytes`: the final length, and only the extents written. +fn sparse_copy(tag: &str, bytes: &[u8], extents: &[Extent]) -> Temp { + let t = Temp::new(tag); + let f = std::fs::OpenOptions::new().write(true).create_new(true).open(&t.0).unwrap(); + f.set_len(bytes.len() as u64).unwrap(); + for e in extents { + f.write_all_at(&bytes[e.offset as usize..e.end() as usize], e.offset).unwrap(); + } + t +} + +fn inspect(t: &Temp) -> KarInspection { + KarInspection::inspect(t.open()).unwrap() +} + +fn spec_for(bytes: &[u8], parts: &[(&str, u64, u64)]) -> KarPleProfileSpec { + let mut row_base = 0; + let mut out = Vec::new(); + for (name, rows, f32_offset) in parts { + out.push(KarPlePartProvenance { + name: (*name).into(), + row_base, + row_count: *rows, + derived_f32_offset: *f32_offset, + derived_f32_sha256: [0; 32], + }); + row_base += rows; + } + KarPleProfileSpec { + archive_bytes: bytes.len() as u64, + archive_sha256: Sha256::digest(bytes).into(), + provenance_sha256: [0x33; 32], + virtual_f32_bytes: u64::from_le_bytes(bytes[120..128].try_into().unwrap()), + virtual_f32_sha256: [0x11; 32], + native_shard_sha256: [[0x44; 32], [0x55; 32]], + parts: out, + } +} + +/// Provenance of the standard archive: record i carries digest `0x22 + i` and the running F32 offset. +fn standard_profile(bytes: &[u8]) -> KarPleProfile { + let mut spec = spec_for(bytes, &[(PART0, 1000, 0), (PART1, 777, 0)]); + let elements = [60_000u64, 5_000, 160_000, 124_320, 30_000]; + let offset = |i: usize| elements[..i].iter().sum::() * 4; + spec.parts[0].derived_f32_offset = offset(2); + spec.parts[0].derived_f32_sha256 = [0x22 + 2; 32]; + spec.parts[1].derived_f32_offset = offset(3); + spec.parts[1].derived_f32_sha256 = [0x22 + 3; 32]; + KarPleProfile::with_total_rows(spec, 1777).unwrap() +} + +#[test] +fn the_builder_makes_archives_the_inspector_admits() { + let bytes = build(&standard()); + let t = Temp::file("admit", &bytes); + let i = inspect(&t); + assert_eq!(i.summary().tensor_count, 5); + assert_eq!(i.summary().archive_bytes, bytes.len() as u64); + assert!(i.payload_offset().is_multiple_of(256) && i.payload_offset() < bytes.len() as u64); +} + +#[test] +fn normalization_aligns_outwards_merges_and_clamps_to_the_archive() { + let e = |o, l| Extent::new(o, l); + // unaligned both ways + assert_eq!(normalize_extents(&[e(5000, 100)], 1 << 20).unwrap(), [e(4096, 4096)]); + // adjacent after alignment merge, overlapping merge, order does not matter, empty dropped + assert_eq!( + normalize_extents(&[e(9000, 3000), e(0, 4097), e(4096, 10), e(100, 0)], 1 << 20).unwrap(), + [e(0, 12288)] + ); + // a hole of at least one page keeps two extents + assert_eq!( + normalize_extents(&[e(0, 10), e(2 * PAGE, 10)], 1 << 20).unwrap(), + [e(0, PAGE), e(2 * PAGE, PAGE)] + ); + // the last page is clamped to the archive length + assert_eq!(normalize_extents(&[e(8192, 100)], 8192 + 512).unwrap(), [e(8192, 512)]); + // beyond the archive is refused + assert!(normalize_extents(&[e(8192, 1000)], 8192 + 512).is_err()); + assert!(normalize_extents(&[e(u64::MAX - 1, 10)], u64::MAX).is_err()); + // cover and overlap + let list = normalize_extents(&[e(0, 10), e(2 * PAGE, 10)], 1 << 20).unwrap(); + assert!(extents_cover(&list, 0, PAGE) && extents_cover(&list, 2 * PAGE + 5, 100) && extents_cover(&list, 7, 0)); + assert!(!extents_cover(&list, PAGE - 1, 2), "a range that crosses into the hole"); + assert!(!extents_cover(&list, PAGE, 1) && !extents_cover(&list, 3 * PAGE, 1) && !extents_cover(&[], 0, 1)); + assert_eq!(extents_overlap(&list, 100, 3 * PAGE), PAGE - 100 + PAGE); + assert_eq!(extents_bytes(&list), 2 * PAGE); +} + +#[test] +fn serve_reads_are_the_scales_and_two_planes_of_the_partitions_and_nothing_else() { + let bytes = build(&standard()); + let t = Temp::file("reads", &bytes); + let i = inspect(&t); + let reads = i.serve_reads(&[PART0, PART1]).unwrap(); + for (p, rows) in reads.parts.iter().zip([1000u64, 777]) { + let rec = i.nested_record(&p.name).unwrap(); + assert_eq!(p.rows, rows); + assert_eq!(p.scales, Extent::new(rec.scales_offset, rows * 10)); + let stride = u64::from(rec.plane_stride_bytes); + assert_eq!(p.planes[0], Extent::new(rec.planes_offset, rows * 20)); + assert_eq!(p.planes[1], Extent::new(rec.planes_offset + stride, rows * 20)); + assert_eq!(p.book, Extent::new(rec.books_offset + 4, 8)); + } + // page aligned, sorted, disjoint + assert!(reads.extents.iter().all(|e| e.offset % PAGE == 0 && (e.len % PAGE == 0 || e.end() == bytes.len() as u64))); + assert!(reads.extents.windows(2).all(|w| w[0].end() < w[1].offset)); + // the metadata is in, the unread records are out (a page of slack at the edges is allowed) + assert!(extents_cover(&reads.extents, 0, i.payload_offset())); + let dense = i.nested_record("dense.big").unwrap(); + let tail = i.nested_record("tail.nested").unwrap(); + assert!(extents_overlap(&reads.extents, dense.section_offset, dense.section_bytes) <= PAGE); + assert!(extents_overlap(&reads.extents, tail.section_offset, tail.section_bytes) <= PAGE); + // the third stored plane of part 0 is a hole + let p0 = i.nested_record(PART0).unwrap(); + let third = p0.planes_offset + 2 * u64::from(p0.plane_stride_bytes); + assert!(!extents_cover(&reads.extents, third + PAGE, 100)); + // exact is no larger than the aligned form, and what is read is covered by it + assert!(reads.exact_bytes() <= reads.extent_bytes()); + for e in &reads.exact { + assert!(extents_cover(&reads.extents, e.offset, e.len)); + } + // a missing partition or a non-PLE geometry is refused + assert!(i.serve_reads(&[PART0, "nope"]).is_err()); + assert!(i.serve_reads(&["dense.big"]).is_err(), "dense.big is not [160, rows]"); +} + +#[test] +fn every_row_reads_the_same_bytes_through_a_copy_that_holds_only_the_extents() { + let bytes = build(&standard()); + let full = Temp::file("full", &bytes); + let reads = inspect(&full).serve_reads(&[PART0, PART1]).unwrap(); + let sparse = sparse_copy("sparse", &bytes, &reads.extents); + // the copy really differs from the file in the holes + let (a, b) = (std::fs::read(&full.0).unwrap(), std::fs::read(&sparse.0).unwrap()); + assert_ne!(a, b); + let in_holes = (0..a.len() as u64).filter(|o| !extents_cover(&reads.extents, *o, 1)).count(); + assert!(in_holes > 50_000, "{in_holes}"); + assert!(a.iter().zip(&b).enumerate().all(|(o, (x, y))| x == y || !extents_cover(&reads.extents, o as u64, 1))); + // the partitions as the row reader sees them + let i = inspect(&full); + let mut parts = Vec::new(); + let mut base = 0; + for name in [PART0, PART1] { + let (p, _) = extents::part_from_record(&i.nested_record(name).unwrap(), base).unwrap(); + base += p.row_count; + parts.push(p); + } + let rows: Vec = (0..1777).collect(); + let mut want = vec![KarPleRowPacket { payload: [0; 50], partition: 0 }; rows.len()]; + let mut got = want.clone(); + read_rows_chunk(&full.open(), &parts, &rows, &mut want).unwrap(); + read_rows_chunk(&sparse.open(), &parts, &rows, &mut got).unwrap(); + assert!(want.iter().zip(&got).all(|(x, y)| x.payload == y.payload && x.partition == y.partition)); + assert_eq!((want[0].partition, want[1000].partition, want[999].partition, want[1776].partition), (0, 1, 0, 1), "the seam"); + assert!(want.iter().any(|p| p.payload.iter().any(|b| *b != 0))); +} + +#[test] +fn the_census_totals_every_record_once_and_matches_the_reads() { + let bytes = build(&standard()); + let t = Temp::file("census", &bytes); + let c = inspect(&t).census(&[PART0, PART1]).unwrap(); + assert_eq!(c.records.len(), 5); + let ple = c.totals(RecordClass::PleRows); + let nested = c.totals(RecordClass::NestedUnread); + let raw = c.totals(RecordClass::RawUnread); + assert_eq!((ple.records, nested.records, raw.records), (2, 2, 1)); + assert_eq!(ple.elements, 1777 * 160); + // sections tile the payload exactly + assert_eq!( + ple.section_bytes + nested.section_bytes + raw.section_bytes + c.payload_offset, + c.archive_bytes + ); + // exact bytes read: metadata + the rows of both partitions + two 8-byte books + let rows: u64 = 1777 * (10 + 40); + assert_eq!(ple.exact_read_bytes, rows + 16); + assert_eq!(c.serve.exact_bytes(), c.payload_offset + rows + 16); + assert_eq!(nested.exact_read_bytes + raw.exact_read_bytes, 0); + // the aligned copy holds the whole of both partitions' read ranges and a little slack, never a whole unread record + assert!(ple.extent_bytes >= ple.exact_read_bytes); + assert!(c.serve.extent_bytes() < c.archive_bytes); + assert_eq!(c.unread_extent_bytes(), c.archive_bytes - c.serve.extent_bytes()); + let text = c.render(true); + for needle in ["archive_bytes=", "ple-rows (read)", "nested (never read)", "raw (never read)", "serve_read_exact_bytes=", "sparse_copy_bytes=", "never_read_bytes=", "dense.big", "bytes_before_first_ple_section="] { + assert!(text.contains(needle), "{needle} missing in\n{text}"); + } + assert!(!c.render(false).contains("dense.big"), "the summary lists only the PLE records"); +} + +#[test] +fn a_sparse_copy_has_the_same_pinned_digest_as_the_archive_and_verifies() { + let bytes = build(&standard()); + let full = Temp::file("dfull", &bytes); + let i = inspect(&full); + let reads = i.serve_reads(&[PART0, PART1]).unwrap(); + let sparse = sparse_copy("dsparse", &bytes, &reads.extents); + let pin = digest_extents(&full.open(), &reads.extents, |_| {}).unwrap(); + assert_eq!(digest_extents(&sparse.open(), &reads.extents, |_| {}).unwrap(), pin, "holes are never hashed"); + // the digest binds the extent list, not only the bytes + let mut shorter = reads.extents.clone(); + shorter.pop(); + assert_ne!(digest_extents(&full.open(), &shorter, |_| {}).unwrap(), pin); + // progress reports every byte + let mut seen = 0; + digest_extents(&sparse.open(), &reads.extents, |n| seen += n).unwrap(); + assert_eq!(seen, reads.extent_bytes()); + + let ok = VerifiedKarPleArtifact::verify_sparse(inspect(&sparse).into_owner_controlled(), standard_profile(&bytes), &pin).unwrap(); + assert!(ok.is_sparse()); + assert_eq!(ok.serve_extents(), &reads.extents[..], "the artifact reads exactly the extents the census lists"); + // the full-archive verifier does not accept a sparse copy (its SHA-256 is different) + let refused = VerifiedKarPleArtifact::verify(inspect(&sparse).into_owner_controlled(), standard_profile(&bytes)).err().unwrap(); + assert!(refused.to_string().contains("full archive SHA"), "{refused}"); + // ... and it still accepts the full file + let full_ok = VerifiedKarPleArtifact::verify(inspect(&full).into_owner_controlled(), standard_profile(&bytes)).unwrap(); + assert!(!full_ok.is_sparse()); + assert_eq!(full_ok.serve_extents(), ok.serve_extents()); +} + +#[test] +fn a_sparse_copy_is_refused_for_a_wrong_pin_a_changed_extent_byte_or_a_changed_length() { + let bytes = build(&standard()); + let full = Temp::file("rfull", &bytes); + let i = inspect(&full); + let reads = i.serve_reads(&[PART0, PART1]).unwrap(); + let pin = digest_extents(&full.open(), &reads.extents, |_| {}).unwrap(); + let verify = |t: &Temp, pin: &[u8; 32]| VerifiedKarPleArtifact::verify_sparse(inspect(t).into_owner_controlled(), standard_profile(&bytes), pin); + // wrong pin + let sparse = sparse_copy("rs0", &bytes, &reads.extents); + let mut wrong = pin; + wrong[0] ^= 1; + assert!(matches!(verify(&sparse, &wrong).err().unwrap(), KarError::Integrity("KAR sparse extents SHA-256 mismatch"))); + assert!(verify(&sparse, &[0; 32]).is_err(), "the unpinned (all zero) digest never matches"); + // one flipped byte in each kind of extent: a scale, a plane of part 0, a plane of part 1, a book + let p0 = i.nested_record(PART0).unwrap(); + let p1 = i.nested_record(PART1).unwrap(); + for at in [ + p0.scales_offset + 7, + p0.planes_offset + 3, + p1.planes_offset + u64::from(p1.plane_stride_bytes) + 11, + p1.books_offset + 5, + p1.scales_offset + p1.scales_bytes - 1, + ] { + let mut changed = bytes.clone(); + changed[at as usize] ^= 0x01; + let t = sparse_copy("rs1", &changed, &reads.extents); + let e = verify(&t, &pin).err().unwrap_or_else(|| panic!("a change at {at} was accepted")); + assert!(matches!(e, KarError::Integrity(_)), "{at}: {e}"); + } + // a changed header byte is caught by the header CRC or the digest, never accepted + let mut changed = bytes.clone(); + changed[100] ^= 0x01; + let t = sparse_copy("rs2", &changed, &reads.extents); + assert!(KarInspection::inspect(t.open()).is_err()); + // a byte in a hole is by design not covered (nothing reads it): the copy is accepted + let hole = (0..bytes.len() as u64).rev().find(|o| !extents_cover(&reads.extents, *o, 1)).unwrap(); + let mut changed = bytes.clone(); + changed[hole as usize] ^= 0xff; + let t = sparse_copy("rs3", &changed, &reads.extents); + assert!(verify(&t, &pin).is_ok()); + // a longer or shorter copy is refused by the inspector (the length is part of the header) + for delta in [PAGE as i64, -(PAGE as i64)] { + let t = sparse_copy("rs4", &bytes, &reads.extents); + std::fs::OpenOptions::new() + .write(true) + .open(&t.0) + .unwrap() + .set_len((bytes.len() as i64 + delta) as u64) + .unwrap(); + assert!(KarInspection::inspect(t.open()).is_err(), "{delta}"); + } +} + +#[test] +fn an_extent_list_that_misses_a_read_range_is_refused_at_verification() { + // Cutting the last plane of part 1 out of the extents (as a buggy sparse writer would) must not verify, even when + // the pin was computed over that same short list: the artifact derives its own list and hashes that one. + let bytes = build(&standard()); + let full = Temp::file("mfull", &bytes); + let reads = inspect(&full).serve_reads(&[PART0, PART1]).unwrap(); + let mut short = reads.extents.clone(); + let last = short.pop().unwrap(); + let pin_short = digest_extents(&full.open(), &short, |_| {}).unwrap(); + let sparse = sparse_copy("mshort", &bytes, &short); + assert!(last.len > 0); + let e = VerifiedKarPleArtifact::verify_sparse(inspect(&sparse).into_owner_controlled(), standard_profile(&bytes), &pin_short).err().unwrap(); + assert!(matches!(e, KarError::Integrity(_)), "{e}"); +} + +/// `LELEKA_SYNTH_KAR=/path cargo test -- --ignored write_a_synthetic_archive`: a miniature archive for trying +/// `examples/kar_census.rs` (the PLE partition names are the pinned ones). +#[test] +#[ignore] +fn write_a_synthetic_archive_for_the_census_example() { + let path = std::env::var_os("LELEKA_SYNTH_KAR").expect("LELEKA_SYNTH_KAR"); + let mut specs = standard(); + specs[2].name = PLE_PART_NAMES[0]; + specs[3].name = PLE_PART_NAMES[1]; + std::fs::write(path, build(&specs)).unwrap(); +} diff --git a/deploy/rust-runtime/profiles/rtx5090-32g-file.json b/deploy/rust-runtime/profiles/rtx5090-32g-file.json new file mode 100644 index 00000000..ba48cb4b --- /dev/null +++ b/deploy/rust-runtime/profiles/rtx5090-32g-file.json @@ -0,0 +1,18 @@ +{ + "name": "rtx5090-32g-file", + "description": "RTX 5090 class server with the KAR archive served as an ordinary read-only FILE instead of a 55 GB sealed memfd (EXPERIMENTAL, not auto-selected: pass --profile rtx5090-32g-file; everything else is rtx5090-32g). Nothing is copied into RAM and no holder is needed: the engine reads only the PLE rows a request needs (3 positional reads of a few bytes per row) through the OS page cache, which keeps what was read across engine restarts while RAM allows and gives it back under pressure instead of failing. Start-up reads the header, directory and books (~1 MB) when the verification stamp of the archive is current; the first start after the file changed hashes it once (55 GB) and records the stamp. Immutability rests on the file system (regular file, mode 0400, one link, owner = service user) and on the engine comparing the file's inode, size, mtime and ctime with the state it verified on every row read; the sealed memfd cannot change at all. A cold first request pays random 4 KiB reads from the model volume. Prefix cache explicit 6144 MiB so the RAM that the memfd no longer holds is not handed to the cache. No quality claim and no speed claim: the A/B is scripts/e2e/decode/kar-file-ab.sh (docs/kar-file-source.md).", + "select": {"sm_min": 0, "sm_max": 0, "vram_mib_min": 0, "vram_mib_max": 0}, + "gpu_budget_bytes": 32819404800, + "spec_min_p": 0.0, + "expert_profile": "data/expert-profile.bin", + "context_tokens": 262144, + "prefill_capacity": 8192, + "kar_source": "file", + "expert_source": "resident", + "min_driver_major": 595, + "min_vram_total_mib": 30000, + "min_ram_total_bytes": 68719476736, + "min_ram_available_bytes": 62000000000, + "engine_env": {"LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER": "yes", "LELEKA_CHAIN": "all", "LELEKA_ORIGINAL_SERVE_SEED": "off", "LELEKA_SM120_ATTN_DAILY_MTP": "1"}, + "memory": {"prefix_cache_mib": "6144", "prefix_cache_tail": "reply", "prefix_cache_block": 8192, "soft_floor_mib": 4096, "hard_floor_mib": 2048, "reserve_mib": 2048, "lock": "off", "heal": false} +} diff --git a/deploy/rust-runtime/profiles/rtx5090-32g.json b/deploy/rust-runtime/profiles/rtx5090-32g.json index 883e0082..966e938a 100644 --- a/deploy/rust-runtime/profiles/rtx5090-32g.json +++ b/deploy/rust-runtime/profiles/rtx5090-32g.json @@ -1,6 +1,6 @@ { "name": "rtx5090-32g", - "description": "RTX 5090 class server (sm_120, 32 GB VRAM, >= 100 GiB RAM). The 55 GB level-2 KAR archive is copied once into a sealed memfd and the 50 GB routed-expert bank is a page-locked RAM copy (the bring-up smoke form). Reference-equivalent agent configuration (docs/e2e-run.md 7d; GPU budget 32,819,404,800 B (31,299 MiB) since the dense-slab commits, was 30 GiB: the slab saves physical bytes the Context never counted, so the budget must rise by about that much for the slot gain to appear, docs/experiments/vram-footprint-5090.md; expert tier auto-sized per layer from data/expert-profile.bin, adaptive speculative window with spec-min-p 0, MTP draft vocabulary, prefix cache auto with request-end checkpoints (reply), chain kernels): weighted decode 129-130 tok/s in the reference-equivalent real Codex sessions on the 5090, +5 % from the adaptive window in the CRM replay. Prompt chunk and prefix-cache grid 8192 (paired 256k session on the 5090: TTFT sum 131 s at 2048 against 55-60 s at 8192, docs/upstream-port-plan.md). Prompt-routing seed OFF (engine_env LELEKA_ORIGINAL_SERVE_SEED=off, placement class, owner to confirm; docs/experiments/decode-tail-5090.md: +27 % decode at 45k-247k prompts). MTP draft attention = upstream pre75 chunk + merge v2 (engine_env LELEKA_SM120_ATTN_DAILY_MTP=1, bitwise identical on the replay gate, draft round 0.29 ms and whole round 0.37 ms shorter at 245k, docs/experiments/draft-round-5090.md). Not a formally quality-gated profile.", + "description": "RTX 5090 class server (sm_120, 32 GB VRAM, >= 100 GiB RAM). Single copy of every model byte in host RAM: the 50 GB routed-expert bank is the one page-locked RAM copy (from GGUF shard 0), and of the 55 GB level-2 KAR archive only the 16.0 GB the serve path reads (the PLE rows, 2 extents) is copied once into a sealed sparse memfd (memfd_extents ple_only: holes elsewhere, verified against the pinned digest of the extents), read O_DIRECT so no page-cache copy remains. Reference-equivalent agent configuration (docs/e2e-run.md 7d; GPU budget 32,819,404,800 B (31,299 MiB) since the dense-slab commits, was 30 GiB: the slab saves physical bytes the Context never counted, so the budget must rise by about that much for the slot gain to appear, docs/experiments/vram-footprint-5090.md; expert tier auto-sized per layer from data/expert-profile.bin, adaptive speculative window with spec-min-p 0, MTP draft vocabulary, prefix cache 6144 MiB (explicit cap: what `auto` resolves to on this host, 5.7-6.1 GiB; unlike `auto` it cannot grow when RAM is freed) with request-end checkpoints (reply), chain kernels): weighted decode 129-130 tok/s in the reference-equivalent real Codex sessions on the 5090, +5 % from the adaptive window in the CRM replay. Prompt chunk and prefix-cache grid 8192 (paired 256k session on the 5090: TTFT sum 131 s at 2048 against 55-60 s at 8192, docs/upstream-port-plan.md). Prompt-routing seed OFF (engine_env LELEKA_ORIGINAL_SERVE_SEED=off, placement class, owner to confirm; docs/experiments/decode-tail-5090.md: +27 % decode at 45k-247k prompts). MTP draft attention = upstream pre75 chunk + merge v2 (engine_env LELEKA_SM120_ATTN_DAILY_MTP=1, bitwise identical on the replay gate, draft round 0.29 ms and whole round 0.37 ms shorter at 245k, docs/experiments/draft-round-5090.md). Not a formally quality-gated profile.", "select": {"sm_min": 120, "sm_max": 130, "vram_mib_min": 30000, "vram_mib_max": 1000000}, "gpu_budget_bytes": 32819404800, "spec_min_p": 0.0, @@ -8,11 +8,12 @@ "context_tokens": 262144, "prefill_capacity": 8192, "kar_source": "memfd", + "memfd_extents": "ple_only", "expert_source": "resident", "min_driver_major": 595, "min_vram_total_mib": 30000, "min_ram_total_bytes": 107374182400, "min_ram_available_bytes": 113000000000, "engine_env": {"LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER": "yes", "LELEKA_CHAIN": "all", "LELEKA_ORIGINAL_SERVE_SEED": "off", "LELEKA_SM120_ATTN_DAILY_MTP": "1"}, - "memory": {"prefix_cache_mib": "auto", "prefix_cache_tail": "reply", "prefix_cache_block": 8192, "soft_floor_mib": 4096, "hard_floor_mib": 2048, "reserve_mib": 2048, "lock": "try", "heal": true} + "memory": {"prefix_cache_mib": "6144", "prefix_cache_tail": "reply", "prefix_cache_block": 8192, "soft_floor_mib": 4096, "hard_floor_mib": 2048, "reserve_mib": 2048, "lock": "try", "heal": true} } diff --git a/desktop-core/src/bin/leleka-inference.rs b/desktop-core/src/bin/leleka-inference.rs index 818ed408..2b1ffd06 100644 --- a/desktop-core/src/bin/leleka-inference.rs +++ b/desktop-core/src/bin/leleka-inference.rs @@ -66,6 +66,11 @@ async fn main() -> Result<(), Box> { args.retain(|arg| arg != "--kar-attested-by-stamp"); set_archive_attested(); } + // `--kar-sparse-extents-sha256 HEX` (only `leleka run` passes it, `memfd_extents: ple_only`, the form of rtx5090-32g): the sealed memfd holds + // only the byte ranges the serve path reads, and is verified against the pinned digest of those ranges. + let sparse_extents = take_option(&mut args, "--kar-sparse-extents-sha256")? + .map(|text| parse_sha256(&text)) + .transpose()?; let verify_stamps = take_option(&mut args, "--verify-stamps")?; if let Some(directory) = verify_stamps { if directory.is_empty() { @@ -77,7 +82,7 @@ async fn main() -> Result<(), Box> { } if args.as_slice() == ["--help"] { println!( - "leleka-inference --listen IP:PORT --token-env NAME --shard0 PATH --shard1 PATH --gpu ORDINAL --gpu-budget BYTES --context-tokens COUNT [--kar-archive PATH --kar-staging PATH | --kar-archive-fd N --kar-provenance PATH | --kar-archive-file PATH --kar-provenance PATH (read-only regular file, no write bits, owned by the caller: the low-RAM form of the pinned archive)] [--mtp-pack PATH --mtp-staging PATH] [--experimental-native-integer-iq3-windowed256-retained-gr | --experimental-optimized-windowed256-mtp [--ranked-expert-profile PATH --expert-profile-sha256 DIGEST] | --experimental-optimized-windowed256-mtp-queued-owners --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-streamed-spill --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-retained-scratch --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-strata-adaptive-slots --ranked-expert-profile PATH --expert-profile-sha256 DIGEST] [--public-evaluation-output /PRIVATE/measurements.jsonl (adaptive slots only; LELEKA_PUBLIC_EVALUATION=yes and LELEKA_EVALUATION_NONCE required)] [--backend-mode auto|original|preview (default auto; an --experimental-* flag selects preview unless the mode is given)] [--original-prefill-capacity 256..8192] [--mtp-rt-dir PATH] [--spec-min-p 0..1] [--kv int8 (fp16|q4_0|k8v4 are refused)] [--kv-resident CELLS (default 32768, min 20480, 0 = all in VRAM)] [--prompt-cache N (conversation checkpoints, default 6 as in the Original, 0 = off)] [--prompt-cache-every N] [--prompt-cache-root N] [--turn-token ID (negative = none)] [--prefix-cache-mib auto|N|0 (cross-session prefix cache in host RAM, replaces the conversation cache; auto = a share of the memory available at start; default off)] [--prefix-cache-tail off|prompt|reply (also checkpoint where the next turn resumes: the end of the prompt, or of the reply too (experimental); default off)] [--prefix-cache-block TOKENS (block and chunk-grid size, a multiple of 256; default the prefill capacity)] [--verify-only (verify shards and archive, print timings, exit)] [--kar-attested-by-stamp (the parent verified the archive file's stamp; the sealed memfd is not hashed again)] [--verify-stamps DIR [--verify-rehash] (skip the hash of a file that is unchanged since it last matched its pin)] [--expert-source resident|mapped (default resident: a ~50 GB RAM copy of the routed experts; mapped: read-only mappings of shard 0, the low-RAM laptop form)]" + "leleka-inference --listen IP:PORT --token-env NAME --shard0 PATH --shard1 PATH --gpu ORDINAL --gpu-budget BYTES --context-tokens COUNT [--kar-archive PATH --kar-staging PATH | --kar-archive-fd N --kar-provenance PATH | --kar-archive-file PATH --kar-provenance PATH (read-only regular file, no write bits, owned by the caller: the low-RAM form of the pinned archive)] [--mtp-pack PATH --mtp-staging PATH] [--experimental-native-integer-iq3-windowed256-retained-gr | --experimental-optimized-windowed256-mtp [--ranked-expert-profile PATH --expert-profile-sha256 DIGEST] | --experimental-optimized-windowed256-mtp-queued-owners --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-streamed-spill --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-retained-scratch --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-strata-adaptive-slots --ranked-expert-profile PATH --expert-profile-sha256 DIGEST] [--public-evaluation-output /PRIVATE/measurements.jsonl (adaptive slots only; LELEKA_PUBLIC_EVALUATION=yes and LELEKA_EVALUATION_NONCE required)] [--backend-mode auto|original|preview (default auto; an --experimental-* flag selects preview unless the mode is given)] [--original-prefill-capacity 256..8192] [--mtp-rt-dir PATH] [--spec-min-p 0..1] [--kv int8 (fp16|q4_0|k8v4 are refused)] [--kv-resident CELLS (default 32768, min 20480, 0 = all in VRAM)] [--prompt-cache N (conversation checkpoints, default 6 as in the Original, 0 = off)] [--prompt-cache-every N] [--prompt-cache-root N] [--turn-token ID (negative = none)] [--prefix-cache-mib auto|N|0 (cross-session prefix cache in host RAM, replaces the conversation cache; auto = a share of the memory available at start; default off)] [--prefix-cache-tail off|prompt|reply (also checkpoint where the next turn resumes: the end of the prompt, or of the reply too (experimental); default off)] [--prefix-cache-block TOKENS (block and chunk-grid size, a multiple of 256; default the prefill capacity)] [--verify-only (verify shards and archive, print timings, exit)] [--kar-sparse-extents-sha256 HEX (with --kar-archive-fd: the sealed memfd holds only the byte ranges the serve path reads and is verified against the pinned SHA-256 of those ranges instead of the archive's)] [--kar-attested-by-stamp (the parent verified the archive file's stamp; the sealed memfd is not hashed again)] [--verify-stamps DIR [--verify-rehash] (skip the hash of a file that is unchanged since it last matched its pin)] [--expert-source resident|mapped (default resident: a ~50 GB RAM copy of the routed experts; mapped: read-only mappings of shard 0, the low-RAM laptop form)]" ); return Ok(()); } @@ -154,11 +159,17 @@ async fn main() -> Result<(), Box> { context_tokens: context.parse().map_err(|_| "invalid_context_bound")?, kar_ple_source: sources.kar, kar_ple_inherited: match (sources.inherited, sources.kar_file) { - (Some((fd, provenance)), None) => Some(InheritedKarArchive::open(fd, provenance)?), + (Some((fd, provenance)), None) => Some(match sparse_extents { + Some(digest) => InheritedKarArchive::open_sparse(fd, provenance, digest)?, + None => InheritedKarArchive::open(fd, provenance)?, + }), // Low-RAM form (docs/laptop-profile.md): an ordinary read-only file instead of a 55 GB sealed memfd. - (None, Some((file, provenance))) => { + (None, Some((file, provenance))) if sparse_extents.is_none() => { Some(InheritedKarArchive::open_read_only_file(&file, provenance)?) } + _ if sparse_extents.is_some() => { + return Err("kar_sparse_extents_requires_kar_archive_fd".into()); + } _ => None, }, mtp_source: sources.mtp, @@ -268,6 +279,13 @@ async fn stop_signal() { let _ = tokio::signal::ctrl_c().await; } +/// 64 hex digits as a SHA-256. +fn parse_sha256(text: &str) -> Result<[u8; 32], &'static str> { + let mut out = [0u8; 32]; + hex::decode_to_slice(text, &mut out).map_err(|_| "invalid_kar_sparse_extents_sha256")?; + Ok(out) +} + /// Remove `--name VALUE` from `args` and return the value (`None` if absent, an error if it is repeated or has none). fn take_option(args: &mut Vec, name: &str) -> Result, &'static str> { let Some(position) = args.iter().position(|arg| arg == name) else { @@ -574,6 +592,15 @@ mod queued_owner_operator_tests { mod inherited_source_tests { use super::*; + #[test] + fn the_sparse_extents_digest_is_exactly_64_hex_digits() { + assert_eq!(parse_sha256(&"ab".repeat(32)).unwrap(), [0xab; 32]); + assert_eq!(parse_sha256(&"0F".repeat(32)).unwrap(), [0x0f; 32]); + for bad in ["", "ab", &"ab".repeat(31), &"ab".repeat(33), &"zz".repeat(32), " abab"] { + assert!(parse_sha256(bad).is_err(), "{bad:?}"); + } + } + #[test] fn take_option_removes_one_value_and_refuses_repeats_and_missing_values() { let mut args: Vec = ["--a", "1", "--verify-stamps", "/s", "--b"] diff --git a/docs/deploy.md b/docs/deploy.md index 0066fa9c..c326ef74 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -86,7 +86,7 @@ Defaults: root gets `/opt/leleka`, `/var/lib/leleka/state`, `/var/lib/leleka/ass The engine accepts the archive only as a sealed memfd (regular, unlinked, pinned length, `WRITE|GROW|SHRINK|SEAL`). Until now an operator tool (`kar_holder.py` / `seal_exec.py`, outside the repository) did that. `leleka run` now does it natively: it copies the archive into a -sealed memfd once (about 10 s for 55 GB from a warm cache, minutes cold), keeps the descriptor close-on-exec in the supervisor, and hands a duplicate +sealed memfd once (the whole 55 GB, or for `rtx5090-32g` only the 16.0 GB extents the serve path reads; large O_DIRECT blocks on many threads, so the copy leaves nothing in the page cache), keeps the descriptor close-on-exec in the supervisor, and hands a duplicate to each engine start through `leleka exec-inherit` (standard input in, a descriptor number >= 3 out). An engine restart therefore does **not** copy 55 GB again, and the API, the gateway and the CLI never see the descriptor. `leleka-seal-exec` still ships for manual runs. `--kar-fd N` (on `up` and `run`) reuses a descriptor inherited from a parent that already holds one (a holder, a test harness): no second copy, and its RAM is not demanded. @@ -104,8 +104,9 @@ 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 | +| `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 **sparse** memfd (`memfd_extents: ple_only`): only the 16.0 GB of the archive the serve path reads (the PLE rows, 2 extents), holes elsewhere; read O_DIRECT, so no page-cache copy | `resident`: page-locked RAM copy (50.3 GB) | 100 GiB / 74 GB (113 GB for `memfd_extents: full`; 58 GB when `--kar-fd` supplies the archive) | one resident copy of every model byte in host RAM (`kar-sparse-memfd.md`) | | `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) | +| `rtx5090-32g-file` (experimental, never auto-selected: `--profile rtx5090-32g-file`) | none (explicit name only) | as `rtx5090-32g` | 262,144 | read-only file (`kar_source: file`; no memfd, no holder; start reads about 1 MB of it when its verification stamp is current) | `resident` | 64 GiB / 62 GB (the 55 GB archive is page cache, not a charge) | as `rtx5090-32g` except an explicit `prefix_cache_mib` 6144; [`kar-file-source.md`](kar-file-source.md): what the file form reads, its integrity guarantees, the A/B (`scripts/e2e/decode/kar-file-ab.sh`, not run) | 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. diff --git a/docs/design/memory-single-copy-and-elastic-state.md b/docs/design/memory-single-copy-and-elastic-state.md index e7d4c530..3ed364f6 100644 --- a/docs/design/memory-single-copy-and-elastic-state.md +++ b/docs/design/memory-single-copy-and-elastic-state.md @@ -9,6 +9,15 @@ Nothing here is a performance claim (AGENTS.md): every speed statement about a f Owner requirements this page answers: (1) "dual use of memory is stupid" on the 5090 profile; (2) session state that moves to RAM must not be reserved at full-window size: allocate on use, hard cap, evict under pressure, compress when parked. +## Update 2026-11-02 (claude/single-copy): census, decision, what is built + +* The census was run on the real archive (T1): a sparse copy is **16,000,348,672 B in 2 extents (14.901 GiB, 28.94 %)**; 39,295,180,800 B (36.596 GiB, 71.06 %) are never read. Section 0 and A.4 are confirmed, no longer E. + The 144 routed-expert records of the archive are 262,144,256 B each: 35.16 GiB for all 24,576 experts against 46.84 GiB in the GGUF bank (0.7506; 1.952 MiB -> 1.465 MiB per expert). +* B0 is built on top of the O_DIRECT bulk reader (`bulk_read`): the copy of the extents never enters the page cache, hash passes evict what they read (`readahead.rs`), `rtx5090-32g` has `memfd_extents: ple_only` + and the pinned extents digest `7568b121...af72143` is compiled in. The alternatives measured against it are in `scripts/e2e/decode/single-copy-ab.sh` (main with the full memfd / sparse memfd / `rtx5090-32g-file`). +* Candidate "KAR on the fly" (experts decoded from the compressed archive, no GGUF bank): not built. Reasons recorded in the task report: level-2 experts are lossy (relative L2 about 0.33 against 0.165 at level 3), + the only GPU path (`kar_expert_source`) decodes to an F32 scratch (18.75 MiB per expert against 1.95 MiB read today) and is refused together with the optimized MMQ owners, and the CPU leg consumes GGUF block layouts. + ## 0. Result in ten lines 1. **The two big host tables are not the same bytes, but the sealed memfd does hold a second copy of the model.** The 55.3 GB memfd is the pinned level-2 KAR archive. The engine reads diff --git a/docs/kar-file-source.md b/docs/kar-file-source.md new file mode 100644 index 00000000..2c810e25 --- /dev/null +++ b/docs/kar-file-source.md @@ -0,0 +1,164 @@ +# The KAR archive as a file on the 5090 (experimental profile `rtx5090-32g-file`) + +Date 2026-10-30, branch `claude/kar-file-source`. Owner requirement: at engine start do not load the 55 GB archive, load what is needed when it is needed (like a page cache); a slower cold start is +acceptable (the server has 128 GB, the model is ~50 GB, and models larger than RAM must work too). Today the 5090 profile seals the archive into a memfd (eager copy of 55.3 GB, ~162 s from this disk +(`holder2 ready ... in 162.4s`), 51.5 GiB of shmem for the life of the service, of which about 36.6 GiB is never read: `docs/design/memory-single-copy-and-elastic-state.md` A.4). + +Evidence labels: **S** read from source (paths named), **M** measured (log or command named), **E** estimate (derivation given), **U** not verified. Nothing here is a speed or quality result: the A/B in +section 6 has not been run (AGENTS.md). + +## 1. What `kar_source: file` does today (S) + +| step | what happens | reads of the archive | +| --- | --- | --- | +| supervisor (`crates/deploy/src/supervisor.rs`, `drive`) | `KarSource::File`: no copy, no seal, no descriptor; engine gets `--kar-archive-file PATH --kar-provenance PATH` (`config.rs` `engine_args`). `leleka up` makes the file mode 0400 (`steps.rs`). No holder. | none | +| admission (`qwen4exp_kar_ple.rs` `open_read_only_file`) | opens `O_NOFOLLOW`, requires regular file, exactly the pinned 55,295,529,472 bytes, one link, owned by the service user, **no write bit**; provenance JSON (403 KB) hashed against its pin | 403 KB provenance | +| verify (`load_pinned_inherited_archive`, `kar.rs` `VerifiedKarPleArtifact::verify`) | re-opens the same inode through `/proc/self/fd`; `inspect` reads header (256 B), name table and directory (about 1 MB, checked by the header's directory digest); the two partition books (8 B each). **Then, unless a stamp trusts the file: SHA-256 of all 55.3 GB plus every section CRC-32**, one read-ahead thread feeding two consumers | ~1 MB with a current stamp; **55.3 GB through the page cache without one** | +| governor (`memory_governor.rs` `guard_archive`) | returns at once for a file-backed archive: no `mlock`, no heal, no `MADV_POPULATE`, no mapping. `StartArgs.kar_file_backed` selects `KarForm::File` (plan charges 0 bytes) and the *laptop* policy flag (prefix cache cap 24 GiB instead of 96 GiB; `leleka-memory/src/plan.rs`) | none | +| serve (`kar.rs` `read_rows_chunk`) | **pread, not mmap**: per PLE row three positional reads, 10 B of scales at `scales+10*row`, 20 B at `planes+20*row`, 20 B at `planes+stride+20*row`. No `fadvise`/`madvise`. Decode: `read_rows` (16 rows = 48 preads; a first row timed, <= 20 us means page-cache warm and the other 15 are read on the calling thread, else 8 threads on cloned handles and the next 256 calls skip the probe). Prefill: `read_rows_batch` (32 threads, 512 rows each) and `row_reader` (read-ahead of the next chunk's rows on a thread of its own, `KarPleCache`) | only the 4 KiB pages that hold a requested row | +| anything else | the Original serve path reads no expert from the archive (`kar_expert_source` is `None`; the resident bank comes from GGUF shard 0). The 36.6 GiB the memfd holds beyond the PLE extents is read by nothing | none | + +A scattered small `pread` on a file nobody reads sequentially is served by the kernel as a standalone one-page read (`ondemand_readahead`, "small read: read as is"), so a cold row costs three 4 KiB +page reads (scale page, plane-0 page, plane-1 page) and a warm row three page-cache copies (~1 us each, `window.ple` 0.1-0.2 ms per window on the memfd). + +### Where the "20 s kar_inspect_verify" and "37 s shard sha256" came from (S, M) + +They are the engine's `leleka-load-time` spans in holder jobs. `scripts/e2e/run-e2e.sh` starts the engine with `--kar-archive-fd` and **neither** `--kar-attested-by-stamp` **nor** `--verify-stamps`, so the +engine hashes the memfd (55 GB from RAM, SHA-256 and CRC pipelined, 20 s = 2.7 GB/s) and both shards (83.6 GB in two threads, 37 s) at every start. The production supervisor (`leleka run`) skips both: +`--verify-stamps DIR` always (a stamp = device, inode, size, mtime, ctime of the file plus the pinned digest, recorded only after a full pass whose before/after identity matched; `ctime` cannot be set from +user space), and `--kar-attested-by-stamp` for a memfd copied from a stamped file. **For the file form the stamp is the whole mechanism**: with a current stamp the archive is not read at start beyond +the ~1 MB above; without one (first start, or after the file's ctime moved, for example by `chmod 0400`) that start hashes the 55.3 GB once, which also fills the page cache. + +The new log line `leleka-kar-startup source=file|memfd verify=stamp|full-pass|attested-memfd metadata_bytes=.. book_bytes=.. hashed_bytes=.. total_read_bytes=.. identity_recheck=..` is printed once per load +(`model-format` `KarStartupRead`); the A/B and the deploy status read it. + +## 2. What the sealed memfd guarantees that a file does not, and what we do about it + +| | sealed memfd | read-only file | +| --- | --- | --- | +| immutability | `WRITE|GROW|SHRINK|SEAL` seals: nobody can change a byte, not the owner, not root through the file API | mode 0400, one link, owner = service user; the owner or root can chmod and write; the disk can rot | +| identity | the memfd is the copy that was hashed (or attested); unlinked, so it cannot be swapped | the path can be replaced; the engine holds one open descriptor (reads follow the inode, not the path) | +| verification | full SHA-256 + CRC of the copy at start, or the supervisor's attestation | the same pass, or a stamp of the file's state | +| failure to change | n/a | a write after verification would be served unseen | + +What the code now does for the file form (S, tests in `kar.rs` `row_read_tests`): + +1. At start the identity (device, inode, size, mtime, ctime) of the opened file is taken before the verification, compared after it (`KAR archive file changed while it was verified`), and kept. +2. **Every row read compares the open file with that state** (`check_archive_state`: the `fstat` that already checked the length; size, mtime or ctime different, so a write, `touch`, `chmod`, rename or + hard link made after verification, refuses the read: `KAR archive file changed since it was verified`). A sealed memfd has no identity and keeps the length check only. The comparison is the lazy, + per-use form of the stamp: a start verifies once (or trusts the stamp), the service re-checks the same fields on each read batch, for one `fstat`. +3. Off switch for a file system whose `ctime` is not stable: `LELEKA_KAR_IDENTITY_RECHECK=off`. Default on. A refusal fails the request (not the process); a restart verifies again. + +Not covered (and not covered by the memfd either, where it is RAM instead of disk): bit rot of a page after the verification. The per-section CRC-32 cannot be used per row (a section is gigabytes). If +this must be closed for the file form, the follow-up is a sidecar of per-4-KiB-page digests of the PLE extents (16 GB / 4 KiB x 32 B = 128 MB, built once from a verified archive, checked at the first +read of each page); it is not built. + +## 3. The profile + +`deploy/rust-runtime/profiles/rtx5090-32g-file.json`, built in (`leleka profiles`), never auto-selected (empty `select` window, so `auto` still picks exactly one profile): identical to `rtx5090-32g` +(budget 32,819,404,800, 262,144 context, chunk and grid 8192, resident expert bank, seed off, `EXPERT_PER_LAYER`, chain `all`) except + +* `kar_source: file`; `min_ram_available_bytes` 62 GB and `min_ram_total_bytes` 64 GiB instead of 113 GB / 100 GiB (E: fixed footprint 54 GiB + floors; the archive is page cache, not a charge; preflight and + the resource planner (`resources.rs`) charge a file archive with a resident bank the engine only, and fall back to the mapped form below that); +* `memory.prefix_cache_mib: "6144"` explicit: with `auto` the freed RAM would be handed to the prefix cache (75 % of the elastic memory, capped at 24 GiB for a file archive), which is the hazard the + single-copy design page flags; 6144 MiB is what `auto` resolves to on the memfd profile today and the 245k session needs about 4 GiB; +* `lock: off`, `heal: false` (memfd-only switches). + +Where the archive lives is the existing mechanism: `leleka up --profile rtx5090-32g-file --assets ~/work/leleka/models/leleka-gates/assets` (the file is `ASSETS/qwen-iq3-s-l2-v4.kar`, provenance next to it; +`LELEKA_ASSETS` works too). `up` sets mode 0400 and `leleka run` passes `--verify-stamps STATE/stamps/engine`. The page cache keeps what was read across +engine restarts, `leleka reconfigure` and a supervisor restart, for as long as RAM allows; no holder exists in this form. + +## 4. Risks, quantified + +### 4.1 Cold random PLE reads on this disk (M for the device, E for the workload) + +Probe, read-only, 2026-10-30 14:00 UTC, server idle, holder up: 4 KiB `O_DIRECT` (page cache bypassed) random reads in the last 29 % of the archive file, Python threads (a lower bound for the device): + +| threads | reads | IOPS | MiB/s | latency p50 / p99 / max | +| ---: | ---: | ---: | ---: | --- | +| 1 | 1,000 | 4,639 | 18 | 0.20 / 0.59 / 0.61 ms | +| 4 | 4,000 | 16,952 | 66 | 0.20 / 0.63 / 2.9 ms | +| 16 | 20,000 | 61,506 | 240 | 0.24 / 0.65 / 1.4 ms | +| 32 | 32,000 | 84,203 | 329 | 0.36 / 0.85 / 1.8 ms | + +So the number that matters is not the 300-660 MB/s sequential figure but **0.2 ms per dependent read and ~60-85k reads/s with 16-32 in flight** (330 MB/s of 4 KiB pages). The probe read 0.2 GB in total; +no file was written. + +What a session asks of that (E, from the code in section 1 and `docs/experiments/decode-tail-5090.md`, 1M distinct rows after ~250k tokens, ~4 distinct rows per token): + +* **First decode tokens, cold:** 16 rows = 48 preads in 8 threads of 2 rows x 3 dependent reads: 2 x 3 x 0.2-0.35 ms = **1.2-2.1 ms added to a ~7.7 ms token (130 tok/s)** while the rows are not in the cache, i.e. + up to -15 to -21 % for such a token; rows repeat quickly (common n-grams), so the average over a reply is far smaller. After the first cold verdict the probe is skipped for 256 calls. +* **Prefill:** 1M distinct rows touch about 2.0M distinct pages (1M rows over 782k scale pages (72 %) and two plane tables of 1.56M pages each (47 %)): **~7.9 GiB read, ~2.0M random reads, 24-33 s of + aggregate device time** at 60-85k reads/s, spread over a 55-60 s prefill (5-turn session, M: TTFT sum 57.3 s) and done by the read-ahead thread one chunk early: a chunk of 8192 tokens is ~33k rows = ~98k preads = 1.2-1.6 s against a + 1.68 s chunk (M at 139k). So it is hidden while the disk has nothing else to do; **the first chunk of the first request is not** (+1.2-1.6 s) and anything else that reads this disk (shard reads, a + second job, the hang-prone sequential load) lands on the same queue. +* Net E for turn 1 (45.8k tokens, ~180k rows, ~0.4M pages): **+1 to +5 s TTFT cold, ~0 warm**; later turns less (the rows of the earlier prompt are cached, only the new tokens' rows are cold). The A/B + measures exactly this; do not quote the E as a result. + +### 4.2 Memory short (S, U) + +The archive pages are clean page cache: under pressure the kernel evicts them (LRU, oldest first) and the next touch of such a row re-reads three pages at ~0.2 ms each. It does **not** OOM and does not swap +anonymous memory because of them. What stays: the 46.84 GiB page-locked expert bank, the 3.09 GiB pinned K/V, the 6 GiB prefix store (anon), the CUDA pins and the engine heap (about 54 GiB fixed in +total) plus the host's own use; the 8-12 GiB the touched part of the archive needs (E) is the only elastic item, and it is the one given back first. Consequences to know: + +* `MemAvailable` counts that page cache as available, so the governor's soft/hard floors (4/2 GiB) and the `auto` sizing see it as free memory. It does not shed or refuse because the cache is full; it sheds the + prefix cache and refuses requests only when `MemAvailable` itself falls below the floors (the cache has been given back by then), or when memory PSI is high while `MemAvailable` is below 12 GiB + (`psi_guard_available`, `Policy::for_host`). +* A host with less RAM than the plan needs is refused at start with numbers (`host_ram`), or moved by the resource planner to `expert_source: mapped` (existing ladder), not by this form. +* With RAM exhausted by someone else the cost shows as decode/prefill time (re-reads at 0.2 ms), visible in `window.ple` and `/v1/status`, not as a crash. **U:** this was not exercised; the control is a + run under `systemd-run --scope -p MemoryMax=...` or a second reader that pushes the archive out of the cache, with `window.ple` and TTFT recorded. +* Eviction cannot corrupt: pages are clean and re-read from the same inode, and section 2's identity check applies to every read. + +### 4.3 Other + +* First start with the file form (stamp absent or voided): one full pass over both shards and the archive (about 138 GB sequential). That is the heaviest I/O this change involves; `kar-file-ab.sh` does it + once, up front, outside any arm. `chmod 0400` on the existing archive (needed for the file form) changes its ctime and voids its stamps, once. +* The identity check refuses reads if anything touches the file (`touch`, `chmod`, rename, hard link, backup tools that reset times): fail closed and loud. Switch: `LELEKA_KAR_IDENTITY_RECHECK=off`. +* There are two copies of the archive on the server (`~/leleka-gates/assets`, root disk, and `~/work/leleka/models/leleka-gates/assets`, `/data`); the holder and the A/B use the `/data` one. +* The 5090 profile keeps the memfd as default. The file form removes 51.5 GiB of shmem and the holder, and takes 8-12 GiB of reclaimable cache instead (E); it is not a RAM win for the page cache of a session that + fits, it is a start-up and elasticity win. + +## 5. Tests (CPU only, WSL, `--release --locked --no-fail-fast`) + +`leleka-model-format`: 141 passed, 3 failed (the known three /mnt/c retained-fd tests: `qwen_rows_sdet::retained_fd_and_chunked_streams...`, `sec_uc143_both_replaced_paths...`, +`sec_uc143_rank1_float_vectors...`); new: `an_ordinary_archive_file_must_still_be_in_the_state_that_was_verified` (touch, chmod, new identity, owned reader), `the_startup_figures_add_up`. +`leleka-deploy`: 127 + 6 passed; new: the profile variant differs from `rtx5090-32g` only where the archive form matters and is never auto-selected, the resource planner charges a file archive the engine only +and falls back correctly. `leleka-runtime`: 618 passed, 2 failed (the known two `backing::` tests). The release build of the four binaries was made from this branch's code on 2026-10-30 (WSL, 2m22s; `leleka-inference` sha256 `821110de1cc0b5df46656ac4b8458fa18c61efe166acad52f6e3fdd44d24c5a3`, 74,477,312 B, in `target/release/` of the worktree, not copied anywhere). + +## 6. The A/B: `scripts/e2e/decode/kar-file-ab.sh` (not run) + +Header of the script has the full protocol; summary here. Same binary for all arms (built from this branch; the memfd path is unchanged by it), frozen corpus +`/data/leleka-e2e/decode/corpus/src/crates`, `long_session.py` 5 turns / 245k tokens / 300 output tokens, upstream ranked profile, seed OFF, chunk 8192, `--prefix-cache-mib 6144` in both arms. +Arms alternate: `base-memfd` (this script seals its own memfd with the holder's copy loop; seal time reported separately), `new-file-cold` (archive page cache dropped with `posix_fadvise(DONTNEED)`, +`--kar-archive-file --verify-stamps`), `new-file-warm` (restart without dropping anything). Recorded every 5 s: MemAvailable, Shmem, Cached, AnonPages, SwapFree, PSI io/memory, pswpin, pgmajfault, the engine's +RssAnon/RssFile/RssShmem and `/proc/PID/io`; every 15 s the bytes of the archive and the shards resident in the page cache (`fincore`, a `mincore` walk, no I/O); one UTC timestamp per turn. Output: time to ready, +`leleka-kar-startup` line and load phases, per-turn TTFT, decode tok/s, input/cached tokens, `window.ple` per request, archive cache growth per turn, MemAvailable, swap, paired differences. + +Install and run (the holder must be stopped; this is not a holder job): + +```sh +# laptop, WSL, in the worktree: the four binaries (about 1-4 min incremental) +wsl -d Ubuntu -- bash -lc ". ~/.cargo/env; cd /mnt/c/Users/pavel/work/leleka/.git/wt/kar-file-source && export CARGO_TARGET_DIR=\$PWD/target && cargo build --release --locked -j 10 -p strata-desktop-core --bin leleka-inference --bin leleka-daemon --bin leleka-cli -p strata-control --bin strata-next" +# server (orchestrator): copy binaries + scripts; ~100 MB total, light I/O +ssh rnr5090 'mkdir -p /data/leleka-e2e/decode/dt/bin-karfile /data/leleka-e2e/decode/dt/jobs-manual' +scp target/release/{leleka-inference,leleka-daemon,leleka-cli,strata-next} rnr5090:/data/leleka-e2e/decode/dt/bin-karfile/ +scp scripts/e2e/run-e2e.sh rnr5090:/data/leleka-e2e/decode/dt/scripts/e2e/run-e2e-karfile.sh +scp scripts/e2e/decode/kar-file-ab.sh rnr5090:/data/leleka-e2e/decode/dt/jobs-manual/ +# server, once: file mode (voids the old stamps), stop the holder (frees 51.5 GiB and MODEL.lock), then run +chmod 0400 ~/work/leleka/models/leleka-gates/assets/qwen-iq3-s-l2-v4.kar +touch ~/work/gpu-runs/holder2/jobs/STOP # wait until `pgrep -f kar_holder2` prints nothing +nohup bash /data/leleka-e2e/decode/dt/jobs-manual/kar-file-ab.sh > /data/leleka-e2e/runs/kar-file-ab.job.log 2>&1 & +# afterwards: restart the holder cd ~/work/gpu-runs/holder2 && rm jobs/STOP && nohup bash run_holder2.sh > holder2.out 2>&1 & +``` + +Estimate (E, from the 12 min an arm of `speedtrain3-ab.sh` and the 162 s holder copy): `base-memfd` ~15 min (12 + seal 2.7), each new arm ~12 min; default six arms (two blocks of base, cold, warm) ~80 min; +4-arm minimum (`ARMS="base-memfd new-file-cold base-memfd new-file-cold"`) ~55 min; plus the one-time stamp seed (CPU only, up to ~138 GB sequential, 4-8 min at 300-660 MB/s, seconds when the stamps are current). +Heavy I/O per base arm: the 55 GB seal; per arm: the 47 GB shard-0 copy of the expert bank. Needs the GPU lock and MODEL.lock (taken by the script) and at least 100 GiB MemAvailable at start (the script refuses below that). + +## 7. Not verified + +* Everything on the server with the new binary: the engine with `--kar-archive-file` on the 5090, the `leleka-kar-startup` line, a stamp hit on the real 55 GB archive, the first-chunk and first-token cost of cold reads, + page-cache growth per turn, behaviour under memory pressure, the paired TTFT/decode comparison, greedy identity (the rows are the same bytes by construction; no logprob comparison was made). +* `kar-file-ab.sh`: `bash -n` and the summary on synthetic run directories only; the arm logic, the samplers and the `seal_exec` helper have not run. +* The disk figures are one 25-second probe of an otherwise idle server with Python threads; the workload figures are estimates from the code and earlier logs. +* Windows: the identity check is off there (no `FileIdentity`); `rtx5090-32g-file` is Linux-only in practice (the resident bank). diff --git a/docs/kar-sparse-memfd.md b/docs/kar-sparse-memfd.md new file mode 100644 index 00000000..065e1a3e --- /dev/null +++ b/docs/kar-sparse-memfd.md @@ -0,0 +1,82 @@ +# Sparse KAR memfd: only the bytes the serve path reads (the form of `rtx5090-32g`) + +Status (claude/single-copy, 2026-11-02): the census was run on the real archive (below), the extents digest is pinned in the binary (`PLE_EXTENTS_SHA256`), the copy reads the extents with +the O_DIRECT bulk reader (no page-cache duplicate) and `rtx5090-32g` has `memfd_extents: ple_only`. The identity and A/B jobs are `scripts/e2e/decode/single-copy-ab.sh` (arms: main with the full +memfd / sparse memfd / `rtx5090-32g-file`); their results are recorded in the task report, not here. Design and evidence: `docs/design/memory-single-copy-and-elastic-state.md` (section A.4, B0, T1-T4). + +Census of `qwen-iq3-s-l2-v4.kar` (2026-11-02, `kar_census`, reads about 1 MB): 1225 records, 2 PLE parts (16,000,077,312 B of sections, 16,000,076,816 B actually read per full sweep), 1223 nested records +never read (39,295,185,152 B); a sparse copy is **16,000,348,672 B (14.901 GiB, 28.94 %) in 2 extents**, `never_read_bytes` 39,295,180,800 (36.596 GiB, 71.06 %), PLE rows 320,001,536. Pinned digest of the +extents: `7568b1211419a7c10a9b39a86230f75b7fa9c02839e36c9b5f2494ec7af72143` (161.9 s at <= 300 MiB/s). The 144 routed-expert records of the archive are 262,144,256 B each (37.75 GB = 35.16 GiB in +all, 0.7506 of the 46.84 GiB the GGUF bank holds): see the report for why they are not a serve source. + +## What and why + +The 55,295,529,472-byte level-2 KAR archive is copied into a sealed memfd (shmem, 51.5 GiB) for the life of the service. The engine reads **one thing** from it: +the PLE n-gram rows (`read_rows_chunk`: 10 B of scales and two 20-byte plane rows per row; 320,001,536 rows = 16,000,076,800 B) plus the header, the directory and two 8-byte books at load. +The rest is a level-2 re-encoding of the shard-0 tensors that the resident expert bank was built from (from GGUF shard 0, not from the memfd) and nothing on the serve path reads it +(E until the census below prints it). + +`memfd_extents: ple_only` makes the supervisor copy only those byte ranges (page-aligned, merged) into a memfd of the **same length and the same file offsets**; everything else is a hole +(no page allocated, reads return zeros, nothing reads them). Readers need no change. + +## The census (task 1): what the archive holds and what the serve path reads + +`crates/model-format/examples/kar_census.rs` reads the 256-byte header, the names and the directory (about a megabyte) and **nothing of the payload**. It prints every record (index, kind, +section offset and size, elements, stored planes, bytes the serve path reads, bytes a sparse copy holds), the totals per kind (`ple-rows (read)`, `nested (never read)`, `raw (never read)`), +the per-partition read ranges, and these lines for the claim "71 % is never read": `serve_read_exact_bytes`, `sparse_copy_bytes`, `never_read_bytes` (with percentages of the archive), +`unread_records_section_bytes`, `bytes_before_first_ple_section`. + +Run it on the server (read-only, light I/O). Build once on the laptop in WSL (or on the server under `/data/leleka-e2e/sparse-memfd/`, never in `~/work`): + +```sh +# laptop, WSL, inside the worktree: a 650 KB dynamic binary (glibc, works on the server's Ubuntu 26.04) +cargo build --release --locked -p leleka-model-format --example kar_census # -> target/release/examples/kar_census +# copy that one small file to the server, e.g. /data/leleka-e2e/sparse-memfd/kar_census (the orchestrator does this) + +# server: the table, the totals and the extents (reads ~1 MB) +/data/leleka-e2e/sparse-memfd/kar_census /home/para/work/leleka/models/leleka-gates/assets/qwen-iq3-s-l2-v4.kar --extents > /data/leleka-e2e/sparse-memfd/census.txt +# only the totals and the PLE partitions: ... kar_census ARCHIVE --summary +``` + +`--hash-extents [--throttle-mib-s N]` additionally **reads the extents (about 16 GB, default 200 MiB/s, about 80 s)** and prints the pinned digest and the line to commit +(`const_line: pub const PLE_EXTENTS_SHA256 ...`). That is heavy I/O on the model volume: run it only when the host is steady, and only for an archive that has matched its full pinned SHA-256 +(`leleka verify` stamp). Without that digest a sparse copy cannot be verified, and the supervisor refuses to start one. + +## Mechanism + +* `kar_extents.rs` (model-format): `KarInspection::serve_reads(PLE_PART_NAMES)` derives the ranges from the directory with the same `VerifiedPart` geometry `read_rows_chunk` uses; + `normalize_extents` page-aligns and merges (the last extent is clamped to the archive length); `digest_extents` is the pinned hash (SHA-256 over a domain tag, the extent list, the extent bytes). +* `VerifiedKarPleArtifact::verify_sparse(source, profile, extents_sha256)`: same identity and partition checks as `verify`, no stamp or attestation (they speak for the whole archive), refuses a read + range outside the extents, hashes the extents and compares with the pin (`KAR sparse extents SHA-256 mismatch`). The directory digest in the header (checked by `inspect`, inside the extents) covers the rest. + The full-archive verifier does **not** accept a sparse copy (tested). +* Pin: `PLE_EXTENTS_SHA256` in `kar_extents.rs` is set (the value above). Had it been zero the operator supplies `LELEKA_KAR_EXTENTS_SHA256` (64 hex digits from the census) and the supervisor logs + that it is experimental; once it is committed the binary's value wins and an environment value is ignored. +* `leleka_deploy::sealed::seal_extents`: the parallel copy of the full fill restricted to the extents (final length first, holes elsewhere, same seals). `leleka seal-exec --file ARCHIVE --expect-bytes N [--sparse-ple] -- COMMAND {FD}` + is the Rust form of `leleka-seal-exec` with the sparse copy, for runs outside `leleka run`. +* Profile field `memfd_extents`: `full` (default, not serialized) or `ple_only`. Validation: needs `kar_source: memfd`, and an explicit `memory.prefix_cache_mib` (or `0`): `auto` is 75 % of the memory that is free when the + stack opens, so it would hand the freed ~36 GiB to the cache. `memfd_bytes()` (16.1 GB estimate until the census prints the exact figure) feeds the resource planner, the preflight RAM minimum and the inherited-descriptor credit. + A plan that falls back to the mapped form resets it to `full`. +* Supervisor: sparse seal, `--kar-sparse-extents-sha256 HEX` to every engine (also after a restart), no `--kar-attested-by-stamp`, no stamp of the archive recorded from the sparse memfd. +* Engine: `InheritedKarArchive::open_sparse` derives the extents from the memfd's own header and directory; `load_pinned_inherited_archive` verifies with `verify_sparse` and checks that the extents the governor locks are + exactly the ones the verifier hashed. +* Memory governor: `guard_archive_extents` locks (`FdMapping::lock_ranges`), heals (`compact_piece` walks the concatenation of the extents) and reports (`extent_bytes`) the extents only. **Locking or populating a hole + allocates a zero page for it**: tested with a negative control (`locking_the_whole_mapping_of_a_sparse_memfd_does_allocate_the_holes...`) next to the extents-only test that asserts `st_blocks` does not move. + +## Prefix hard cap (task 2) + +The 5090 profile carries `memory.prefix_cache_mib: "6144"` (what `auto` resolves to there today, 5.7-6.1 GiB; a 245k session needs about 4 GiB). An explicit value is clamped to the host and never grows +(`leleka_memory::plan::explicit_prefix_budget`; tests: +37 GiB available leaves it at 6144 MiB, `auto` grows by more than 20 GiB). The engine logs `prefix cache budget: N MiB (...)` for auto, explicit and off. + +## The A/B (not run) + +`scripts/e2e/decode/sparse-memfd-ab.sh` is **not a holder job** (the holder's 55 GB memfd and a second one do not fit): run it with the holder stopped. Prerequisites and arms are in its header. Acceptance gates G1-G4: +bitwise-identical top-16 rows (A/A and sparse against full), system `Shmem` lower by 36.6 GiB +- 1.5 and `MemAvailable` higher by >= 35 GiB at turn 5 with zero swap, decode and TTFT within the run-to-run noise, +the prefix store held at 6144 MiB. Until that passes, `ple_only` stays off. + +## Not verified + +* The census numbers of the real archive (the 36.6 GiB / 71 % are derived from two independent derivations in the design doc, not read from the directory). +* `PLE_EXTENTS_SHA256` of the real archive; the time of the 16 GB extents hash at engine start (E: about 10 s, single-threaded SHA-256 over memory). +* Everything on the GPU: identity of the logprobs, speed, the engine's behaviour with a sparse memfd end to end (`open_sparse` and the supervisor's `serve_extents` have only been exercised on synthetic + archives and a fake engine; the real directory has 700+ records and the pinned part names). +* `mlock` of 16 GB under the server's RLIMIT_MEMLOCK (8 MiB by default: the lock falls back to detect + heal exactly as for the full memfd). diff --git a/docs/memory-safety.md b/docs/memory-safety.md index c5ff951f..4f16c69a 100644 --- a/docs/memory-safety.md +++ b/docs/memory-safety.md @@ -175,7 +175,7 @@ the 3,168 MiB image that was allocated at open: the pinned K/V does not grow wit | Knob | Default | Meaning | | --- | --- | --- | -| `--prefix-cache-mib auto\|N\|0` (profile `memory.prefix_cache_mib`) | off (profiles: `auto`) | prefix cache budget; `auto` and an explicit value are sized/clamped by the governor | +| `--prefix-cache-mib auto\|N\|0` (profile `memory.prefix_cache_mib`) | off (profiles: `rtx5090-32g` 6144, `rtx3080-16g` `auto`) | prefix cache budget; `auto` is 75 % of what is elastic when the stack opens and **grows when RAM is freed elsewhere**; an explicit value is clamped to what the host has and never grows (`plan::explicit_prefix_budget`), which is why the dedicated 5090 profile carries one | | `LELEKA_MEMORY_SOFT_FLOOR_MIB` / `_HARD_FLOOR_MIB` | 4096 / 2048 (3% / 1.5% of RAM above 128 GiB) | shed / refuse thresholds; hard must be below soft | | `LELEKA_MEMORY_RESERVE_MIB` | 1024 | slack above the soft floor kept after the fixed footprint | | `LELEKA_MEMORY_HYSTERESIS_MIB` | 1024 | margin to leave a level | @@ -189,7 +189,8 @@ the 3,168 MiB image that was allocated at open: the pinned K/V does not grow wit An unparsable override is an error naming the variable (a typo must not silently keep the default of a safety setting). The profiles (`deploy/rust-runtime/profiles/*.json`) carry a `memory` section (`prefix_cache_mib`, floors, reserve, share, `lock`, `heal`, `resident_budget_gib`) that `leleka up` turns into the engine arguments and environment. -The server profile: `auto`, 4096/2048/1024 MiB, lock `try`, heal on. The laptop profile (file-backed archive, no memfd): `auto`, same floors, lock `off`. +The server profile: prefix cache `6144` MiB (an explicit cap, so RAM freed elsewhere cannot grow it), floors 4096/2048 MiB and reserve 2048 MiB, lock `try`, heal on. The laptop profile (file-backed archive, no memfd): `auto`, same floors, lock `off`. +The experimental `memfd_extents: ple_only` (a sealed memfd that holds only the ~16 GB the serve path reads, locked and healed by extents) is described in `docs/kar-sparse-memfd.md`; it is off by default. ## 5. Tests diff --git a/scripts/e2e/decode/kar-file-ab.sh b/scripts/e2e/decode/kar-file-ab.sh new file mode 100644 index 00000000..5970c93e --- /dev/null +++ b/scripts/e2e/decode/kar-file-ab.sh @@ -0,0 +1,364 @@ +#!/usr/bin/env bash +# KAR file source A/B: the 5090 profile with the level-2 KAR archive as a sealed memfd (today, 55.3 GB of shmem made by a holder) against the same archive as an ordinary +# READ-ONLY FILE served through the page cache (profile rtx5090-32g-file, engine flag --kar-archive-file; docs/kar-file-source.md). Same binary, same frozen corpus, same +# 5-turn ~245k session as speedtrain3-ab.sh, seed OFF, upstream ranked profile, alternating arms. +# +# NOT A HOLDER JOB. The file arms need the RAM that the holder's memfd pins, so the holder must be stopped first (and MODEL.lock free): this script takes MODEL.lock and gpu.lock +# itself and seals its own memfd for the base arms (the same copy loop as kar_holder2.py, 16 MiB chunks, ~160 s for 55 GB from this disk; its time is reported as seal_s and is +# NOT part of the engine's "model ready after"). Run it from a shell on the server (nohup/tmux), never queue it behind the holder. +# +# once, by the owner of the file (no data is rewritten; it changes ctime, so existing verification stamps of the archive become void): +# chmod 0400 ~/work/leleka/models/leleka-gates/assets/qwen-iq3-s-l2-v4.kar +# stop the holder: touch ~/work/gpu-runs/holder2/jobs/STOP (it exits between jobs, releasing its 51.5 GiB memfd and MODEL.lock); start it again afterwards with +# cd ~/work/gpu-runs/holder2 && rm jobs/STOP && nohup bash run_holder2.sh > holder2.out 2>&1 & +# install: cp scripts/e2e/decode/kar-file-ab.sh /data/leleka-e2e/decode/dt/jobs-manual/kar-file-ab.sh (any directory that is not the holder queue) +# cp scripts/e2e/run-e2e.sh /data/leleka-e2e/decode/dt/scripts/e2e/run-e2e-karfile.sh (a NEW name: the frozen run-e2e.sh stays untouched) +# mkdir -p /data/leleka-e2e/decode/dt/bin-karfile && cp /{leleka-inference,leleka-daemon,leleka-cli,strata-next} there, plus COMMIT.txt +# run: bash /data/leleka-e2e/decode/dt/jobs-manual/kar-file-ab.sh 2>&1 | tee -a /data/leleka-e2e/runs/kar-file-ab.job.log +# +# Arms (the order in ARMS is the run order; default two blocks of base, new-cold, new-warm; ARMS="base-memfd new-file-cold base-memfd new-file-cold" is the 4-arm minimum): +# base-memfd archive -> sealed memfd (this script, as the holder does) -> engine --kar-archive-fd; no verification stamps (the engine hashes the memfd and the shards at start, as in +# every holder job so far) +# new-file-cold engine --kar-archive-file ARCHIVE --verify-stamps DIR; the page cache of the ARCHIVE is dropped (posix_fadvise DONTNEED, clean pages, no root) just before the start, +# so the first requests pay every random PLE read from the disk +# new-file-warm the same, started right after a new-file-cold arm WITHOUT dropping anything: the pages the previous engine read are still in the page cache (the property that +# a memfd cannot have: it dies with the holder, the page cache survives an engine restart) +# Only the KAR source differs between base and new. Both get --prefix-cache-mib $PREFIX_MIB (6144, explicit: with `auto` the file arm would be handed the RAM the memfd no longer pins, +# a 24 GiB cache, which is a different experiment); the 245k session needs about 4 GiB of it either way. +# Stamps: before the first arm the script runs `leleka-inference --verify-only --verify-stamps` twice (CPU only, no GPU): the first pass hashes the two shards and the archive if their +# stamps are absent or stale (about 138 GB of sequential reads, minutes, the heaviest I/O of this job; skip it with SEED_STAMPS=0 only if the stamps are current), the second must +# print `leleka-kar-startup ... verify=stamp ... total_read_bytes=` of about a megabyte: that line is the "what is read at start" evidence. +# +# Per arm it records (all in $OUTR//): env-arm.txt (binaries, commit, hardware, kernel, file states), job.log (run-e2e output, seal_s, ready time), inference.log (engine: the +# leleka-kar-startup line, leleka-load-time phases, DBG window/profile lines), long-session.json (per-turn ttft_s, decode_tok_s, input_tokens), samples.txt (every 5 s: MemAvailable, +# Shmem, Cached, AnonPages, SwapFree, PSI io/memory, pswpin, pgmajfault, the engine's RssAnon/RssFile/RssShmem, rchar/read_bytes of the engine; every 15 s: bytes of the archive and of the +# two shards resident in the page cache, `fincore`), client.log (one UTC timestamp per turn line) and VALIDITY.txt. The summary at the end pairs each new arm with the base before it. +# Validity per run as in speedtrain3-ab.sh (5 turns, final-turn input >= 200000, turn-5 mean window.ple < 5 ms); a new arm whose engine hashed the archive in this start +# (verify=full-pass) is marked INVALID as a cold/warm measurement, because the hash fills the page cache. +# Quality is not decided here: the PLE rows are the same bytes by construction; greedy identity of the first turns is the cheap check (speedtrain3-id.sh shape, not part of this job). +set -uo pipefail +D=/data/leleka-e2e/decode/dt +BINDIR=${BINDIR:-$D/bin-karfile} +RUNNER=${RUNNER:-$D/scripts/e2e/run-e2e-karfile.sh} +LOCK=/data/leleka-e2e/gpu.lock +MODELLOCK=$HOME/work/gpu-runs/MODEL.lock +OUTR=${OUTR:-/data/leleka-e2e/runs/kar-file-ab} +CORPUS=/data/leleka-e2e/decode/corpus/src/crates +UP=/data/leleka-e2e/decode/assets/expert-profile-upstream.bin +ASSETS=${E2E_ASSETS:-$HOME/work/leleka/models/leleka-gates/assets} +ARCHIVE=$ASSETS/qwen-iq3-s-l2-v4.kar +SHARD0=$ASSETS/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf +SHARD1=$ASSETS/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf +STAMPS=${STAMPS:-$OUTR/stamps} +TOOLS=$OUTR/_tools +RUN_TAG=${RUN_TAG:-} +SEED_STAMPS=${SEED_STAMPS:-1} +PREFIX_MIB=${PREFIX_MIB:-6144} +GPU_BUDGET=${GPU_BUDGET:-32819404800} +ARMS=${ARMS:-"base-memfd new-file-cold new-file-warm base-memfd new-file-cold new-file-warm"} +SESSION_ARGS="--turns 5 --target-tokens 245000 --max-output 300 --min-final-tokens 200000" +export LD_LIBRARY_PATH=$HOME/cuda-toolkits/cublas-12.9.1.4/lib:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-} + +for f in "$UP" "$D/tools/long-session.py" "$RUNNER" "$BINDIR/leleka-inference" "$BINDIR/leleka-daemon" "$BINDIR/leleka-cli" "$BINDIR/strata-next" "$CORPUS/backend-api/src/lib.rs" \ + "$ARCHIVE" "$ASSETS/qwen-iq3-s-l2-v4.kar.provenance.json" "$SHARD0" "$SHARD1"; do + [ -r "$f" ] || { echo "missing $f" >&2; exit 3; } +done +command -v fincore >/dev/null || { echo "fincore (util-linux) is needed" >&2; exit 3; } +if pgrep -u "$USER" -f 'kar_holder2?\.py' >/dev/null; then + echo "the holder is running and pins 51.5 GiB of memfd: stop it first (touch ~/work/gpu-runs/holder2/jobs/STOP, wait until it exits)" >&2; exit 3 +fi +if [ "$(stat -c %h "$ARCHIVE")" != 1 ] || [ "$(( 0$(stat -c %a "$ARCHIVE") & 0222 ))" != 0 ]; then + echo "the archive must be a single-link file without write bits for the file source: chmod 0400 $ARCHIVE" >&2; exit 3 +fi +case "$ARMS" in *new-file*) ;; *) SEED_STAMPS=0 ;; esac +avail_mib=$(awk '/^MemAvailable:/{print int($2/1024)}' /proc/meminfo) +[ "$avail_mib" -ge 100000 ] || { echo "MemAvailable is only $avail_mib MiB: something still pins RAM (the holder?); the file arm needs about 60 GiB free besides the page cache" >&2; exit 3; } +mkdir -p "$OUTR" "$TOOLS" +mkdir -p -m 700 "$STAMPS"; chmod 700 "$STAMPS" + +# MODEL.lock for the whole job (the holder's start loop waits for it and takes it again afterwards) +mkdir "$MODELLOCK" 2>/dev/null || { echo "MODEL.lock is held: $(ls $MODELLOCK 2>&1)" >&2; exit 3; } +trap 'rmdir "$MODELLOCK" 2>/dev/null' EXIT + +cat >"$TOOLS/seal_exec.py" <<'PY' +# the holder's copy loop (kar_holder2.py), then the command with the sealed descriptor inherited: seal_exec.py ARCHIVE CMD... +import fcntl, os, subprocess, sys, time +src, cmd = sys.argv[1], sys.argv[2:] +fd = os.memfd_create("kar-archive", os.MFD_ALLOW_SEALING) +t = time.time(); n = 0 +with open(src, "rb", buffering=0) as f: + while chunk := f.read(16 << 20): + os.write(fd, chunk); n += len(chunk) +fcntl.fcntl(fd, fcntl.F_ADD_SEALS, fcntl.F_SEAL_WRITE | fcntl.F_SEAL_GROW | fcntl.F_SEAL_SHRINK | fcntl.F_SEAL_SEAL) +print(f"seal_s={time.time()-t:.1f} bytes={n} fd={fd} at={time.strftime('%T', time.gmtime())}Z", flush=True) +sys.exit(subprocess.run(cmd, pass_fds=[fd], env=dict(os.environ, LELEKA_STRA169_KAR_FD=str(fd))).returncode) +PY +cat >"$TOOLS/dropcache.py" <<'PY' +# posix_fadvise(DONTNEED) on a file: drops its clean page-cache pages (no root needed, no data is touched) +import os, sys +for path in sys.argv[1:]: + fd = os.open(path, os.O_RDONLY); os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED); os.close(fd) +PY + +resident() { fincore -b -n -o RES "$1" 2>/dev/null | tr -d ' '; } # bytes of the file in the page cache (mincore: no I/O) + +sampler() { # $1 output file + local i=0 pid line + while sleep 5; do + i=$((i + 1)) + pid=$(pgrep -u "$USER" -f 'leleka-inference --listen' | head -1) + line="$(date -u +%T) $(awk '/^(MemAvailable|MemFree|Cached|Shmem|AnonPages|Mapped|Dirty|SwapFree):/{printf "%s%d ", $1, $2/1024}' /proc/meminfo)" + line="$line io10=$(awk '/^some/{split($2,a,"=");print a[2]}' /proc/pressure/io) mem10=$(awk '/^some/{split($2,a,"=");print a[2]}' /proc/pressure/memory)" + line="$line $(awk '/^(pswpin|pswpout|pgmajfault|workingset_refault_file) /{printf "%s=%s ", $1, $2}' /proc/vmstat)" + if [ -n "$pid" ] && [ -r "/proc/$pid/smaps_rollup" ]; then + line="$line pid=$pid $(awk '/^(Rss|Pss_Anon|Pss_File|Pss_Shmem|Swap):/{printf "%s%d ", $1, $2/1024}' /proc/$pid/smaps_rollup)" + line="$line $(awk '/^(rchar|read_bytes):/{printf "%s%s ", $1, $2}' /proc/$pid/io 2>/dev/null)" + fi + if [ $((i % 3)) = 1 ]; then line="$line | archive_cached=$(resident "$ARCHIVE") shard0_cached=$(resident "$SHARD0") shard1_cached=$(resident "$SHARD1")"; fi + echo "$line" + done > "$1" 2>/dev/null +} + +seed_stamps() { # CPU-only verification of shards and archive that records the stamps; twice, the second must be a stamp hit + local pass + for pass in 1 2; do + ( export LELEKA_RUNTIME_TOKEN=$(head -c 24 /dev/urandom | base64 | tr -d '\n') + echo "=== seed pass $pass $(date -u +%FT%TZ)" + "$BINDIR/leleka-inference" --listen 127.0.0.1:18766 --token-env LELEKA_RUNTIME_TOKEN --shard0 "$SHARD0" --shard1 "$SHARD1" --gpu 0 --gpu-budget "$GPU_BUDGET" \ + --context-tokens 262144 --kar-archive-file "$ARCHIVE" --kar-provenance "$ASSETS/qwen-iq3-s-l2-v4.kar.provenance.json" --verify-only --verify-stamps "$STAMPS" 2>&1 + echo "rc=$? $(date -u +%FT%TZ)" ) | tee -a "$OUTR/seed-stamps.log" | grep -a -E "^===|leleka-kar-startup|leleka-load-time phase=(kar_inspect_verify|shard._sha256_and_index|sources_verified_in_parallel_wall|all_sources_verified)|^rc=|refus|rror" | cut -c1-300 + done +} + +ours() { # $1 tag, $2 arm + local tag=$1 arm=$2 + ( export E2E_BIN=$BINDIR E2E_OUT=$OUTR/$tag E2E_ASSETS=$ASSETS + mkdir -p "$E2E_OUT" + export LELEKA_BRINGUP_TRACE=1 LELEKA_PREFIX_TRACE=1 + export LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto E2E_GPU_BUDGET=$GPU_BUDGET + export E2E_SAMPLE_S=10 LELEKA_CHAIN=all + export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$UP + unset LELEKA_ORIGINAL_SERVE_SEED_MAX_ROWS LELEKA_SM120_ATTN_DAILY LELEKA_SM120_GU_SWIGLU LELEKA_SM120_SIDE_MIXER LELEKA_SM120_PERF LELEKA_SERVE_DRAFT_AFTER_COMMIT LELEKA_PROMPT_EMBED_ALIAS LELEKA_VRAM_LEDGER LELEKA_DENSE_SLAB LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB E2E_KAR_FILE + export LELEKA_ORIGINAL_SERVE_SEED=off + local engine_args="--prefix-cache-mib $PREFIX_MIB --prefix-cache-tail reply --original-prefill-capacity 8192 --prefix-cache-block 8192 --spec-min-p 0" + local cold_note="-" + case $arm in + base-memfd) + # the seal reads the whole archive: from a cold cache it costs what a holder start costs + python3 -I "$TOOLS/dropcache.py" "$ARCHIVE"; cold_note="archive page cache dropped before the seal: $(resident "$ARCHIVE") bytes resident" ;; + new-file-cold) + python3 -I "$TOOLS/dropcache.py" "$ARCHIVE"; cold_note="archive page cache dropped: $(resident "$ARCHIVE") bytes resident" + export E2E_KAR_FILE=$ARCHIVE; engine_args="$engine_args --verify-stamps $STAMPS" ;; + new-file-warm) + cold_note="archive page cache left as the previous engine made it: $(resident "$ARCHIVE") bytes resident" + export E2E_KAR_FILE=$ARCHIVE; engine_args="$engine_args --verify-stamps $STAMPS" ;; + *) echo "unknown arm $arm" >&2; exit 2 ;; + esac + export E2E_ENGINE_ARGS=$engine_args + { echo "arm=$arm tag=$tag"; date -u +%FT%TZ; echo "cache: $cold_note"; free -m | sed -n 2p + echo "kernel: $(uname -r)"; nvidia-smi --query-gpu=name,driver_version,memory.total --format=csv,noheader + echo "resident before start: archive=$(resident "$ARCHIVE") shard0=$(resident "$SHARD0") shard1=$(resident "$SHARD1")" + stat -c "%n mode=%a ino=%i size=%s mtime=%y ctime=%z" "$ARCHIVE" "$SHARD0" "$SHARD1" + echo "read_ahead_kb=$(cat /sys/block/nvme0n1/queue/read_ahead_kb) scheduler=$(cat /sys/block/nvme0n1/queue/scheduler) swappiness=$(cat /proc/sys/vm/swappiness)" + sha256sum "$UP" "$BINDIR"/leleka-inference "$BINDIR"/leleka-daemon "$BINDIR"/leleka-cli "$BINDIR"/strata-next "$RUNNER" + cat "$BINDIR/COMMIT.txt" 2>/dev/null; head -1 /data/leleka-e2e/decode/corpus/MANIFEST.txt + echo "engine args: $engine_args" + env | grep -E '^(LELEKA_|STRATA_|E2E_)' | sort; } >"$E2E_OUT/env-arm.txt" + export E2E_RUN_CMD='set -o pipefail; python3 -I '"$D"'/tools/long-session.py --src '"$CORPUS $SESSION_ARGS"' 2>&1 | while IFS= read -r l; do printf "%s %s\n" "$(date -u +%T)" "$l"; done' + sampler "$E2E_OUT/samples.txt" & SAMP=$! + if [ "$arm" = base-memfd ]; then + python3 -I "$TOOLS/seal_exec.py" "$ARCHIVE" bash "$RUNNER" 2>&1 | tee "$E2E_OUT/job.log" | grep -a -E "seal_s|^\{|^[0-9:]+ \{|expert cache|request outcome|ready after|rc=|refus|error|Error|long_session|client exit|leleka-kar-startup" | cut -c1-300 + else + bash "$RUNNER" 2>&1 | tee "$E2E_OUT/job.log" | grep -a -E "^\{|^[0-9:]+ \{|expert cache|request outcome|ready after|rc=|refus|error|Error|long_session|client exit|leleka-kar-startup" | cut -c1-300 + fi + kill $SAMP 2>/dev/null + echo "run-e2e done $tag $(date -u +%FT%TZ)" ) +} + +validity() { # $1 run dir, $2 arm + python3 -I - "$1" "$2" <<'PY' +import json, os, re, sys +d, arm = sys.argv[1], sys.argv[2] +f = os.path.join(d, "long-session.json") +verdict = "INVALID: no long-session.json" +if os.path.exists(f): + t = json.load(open(f)) + final = (t[-1].get("input_tokens") or 0) if t else 0 + if any("error" in r for r in t): + verdict = "INVALID: a turn failed" + elif len(t) < 5 or final < 200000: + verdict = "INVALID: %d turns, final-turn input tokens %d < 200000 (short corpus?)" % (len(t), final) + else: + verdict = "VALID: 5 turns, final-turn input tokens %d" % final + wins, last = [], [] + log = open(os.path.join(d, "inference.log"), errors="replace").read().splitlines() + for ln in log: + if ln.startswith("DBG window "): + last.append(dict((k, float(v)) for k, v in re.findall(r"(\w+)=([-\d.]+)", ln))) + elif "leleka-serve request outcome" in ln: + wins.append(last); last = [] + w = wins[-1] if wins else [] + ple = sum(x.get("ple", 0) for x in w) / max(len(w), 1) + verdict += "; turn-5 window.ple mean %.2f ms over %d windows" % (ple, len(w)) + if not w: + verdict = "INVALID: no turn-5 window lines (trace env missing?)" + elif ple >= 5: + verdict = "INVALID: turn-5 window.ple mean %.2f ms >= 5 ms (PLE scan back?)" % ple + start = [l for l in log if l.startswith("leleka-kar-startup")] + if not start: + verdict += "; NOTE: no leleka-kar-startup line (binary without the log line?)" + elif arm.startswith("new-file") and "source=file" not in start[0]: + verdict = "INVALID: new arm did not run with source=file: " + start[0] + elif arm.startswith("new-file") and "verify=stamp" not in start[0]: + verdict = "INVALID as a cold/warm measurement: the engine hashed the archive in this start (" + start[0] + ")" + elif arm == "base-memfd" and "source=memfd" not in start[0]: + verdict = "INVALID: base arm did not run with source=memfd: " + start[0] +open(os.path.join(d, "VALIDITY.txt"), "w").write(verdict + "\n") +print(os.path.basename(d), verdict) +PY +} + +{ echo "kar-file-ab $(date -u +%FT%TZ) arms: $ARMS"; echo "archive: $(stat -c '%n mode=%a ino=%i size=%s mtime=%y ctime=%z' "$ARCHIVE")"; free -m | sed -n 2p; } | tee -a "$OUTR/job-start.txt" +[ "$SEED_STAMPS" = 1 ] && seed_stamps + +n=0 +for arm in $ARMS; do + n=$((n + 1)); tag="$arm-r$n$RUN_TAG" + got=0 + for _ in $(seq 1 1080); do + if mkdir "$LOCK" 2>/dev/null; then echo "kar-file-ab $tag $(date -u +%FT%TZ)" >"$LOCK/owner"; got=1; break; fi + sleep 5 + done + [ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; exit 3; } + echo "=== $tag $(date -u +%FT%TZ)"; free -g | sed -n 2p + if [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader)" ]; then + echo "GPU busy, skipping $tag"; rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null; continue + fi + ours "$tag" "$arm" + validity "$OUTR/$tag" "$arm" + echo "arm done $tag $(date -u +%FT%TZ)" + rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null + sleep 15 +done + +# summary +python3 -I - "$OUTR" <<'PY' +import glob, json, os, re, statistics, sys +root = sys.argv[1] +def run_number(path): + tail = path.rsplit("-r", 1)[-1] + m = re.match(r"\d+", tail) + return int(m.group()) if m else 0 +def secs(t): + h, m, s = t.split(":"); return int(h) * 3600 + int(m) * 60 + int(s) +runs = [] +for d in sorted(glob.glob(os.path.join(root, "*-r[0-9]*")), key=run_number): + v = os.path.join(d, "VALIDITY.txt") + tag = os.path.basename(d) + if not os.path.exists(v): + print(tag, "not used: no VALIDITY.txt"); continue + verdict = open(v).read().strip() + arm = tag.rsplit("-r", 1)[0] + r = {"tag": tag, "arm": arm, "valid": verdict.startswith("VALID"), "verdict": verdict, "dir": d} + job = open(os.path.join(d, "job.log"), errors="replace").read() if os.path.exists(os.path.join(d, "job.log")) else "" + m = re.search(r"seal_s=([\d.]+)", job); r["seal_s"] = float(m.group(1)) if m else None + m = re.search(r"\[run-e2e (\d\d:\d\d:\d\d)\] model ready after (\d+)s", job) + r["ready_s"] = int(m.group(2)) if m else None; r["ready_at"] = secs(m.group(1)) if m else None + log = open(os.path.join(d, "inference.log"), errors="replace").read().splitlines() if os.path.exists(os.path.join(d, "inference.log")) else [] + r["startup"] = next((l for l in log if l.startswith("leleka-kar-startup")), "-") + r["phases"] = {} + for l in log: + m = re.match(r"leleka-load-time phase=(\S+) seconds=([\d.]+)", l) + if m and m.group(1) in ("kar_inspect_verify", "shard0_sha256_and_index", "shard1_sha256_and_index", "sources_verified_in_parallel_wall"): + r["phases"][m.group(1)] = float(m.group(2)) + cs = os.path.join(d, "long-session.json") + r["turns"] = json.load(open(cs)) if os.path.exists(cs) else [] + ends = [] + cl = os.path.join(d, "client.log") + if os.path.exists(cl): + for l in open(cl, errors="replace"): + m = re.match(r"(\d\d:\d\d:\d\d) \{", l) + if m and "ttft_s" in l: ends.append(secs(m.group(1))) + r["turn_ends"] = ends + samples = [] + sp = os.path.join(d, "samples.txt") + if os.path.exists(sp): + for l in open(sp, errors="replace"): + p = l.split() + if not p: continue + row = {"t": secs(p[0])} + for k in ("MemAvailable", "Shmem", "Cached", "AnonPages", "SwapFree", "Dirty", "Rss", "Pss_Anon", "Pss_File", "Pss_Shmem", "Swap"): + m = re.search(r"\b%s:?(\d+)" % k, l); row[k] = int(m.group(1)) if m else None + for k in ("io10", "mem10"): + m = re.search(r"%s=([\d.]+)" % k, l); row[k] = float(m.group(1)) if m else None + for k in ("pswpin", "pgmajfault", "rchar", "read_bytes"): + m = re.search(r"%s[:=]?(\d+)" % k, l); row[k] = int(m.group(1)) if m else None + m = re.search(r"archive_cached=(\d+)", l); row["arch"] = int(m.group(1)) if m and m.group(1) else None + samples.append(row) + r["samples"] = samples + runs.append(r) + +def at(r, t): + after = [s for s in r["samples"] if s["t"] >= t] + return after[0] if after else (r["samples"][-1] if r["samples"] else {}) +def arch_at(r, t): + after = [s for s in r["samples"] if s["t"] >= t and s.get("arch") is not None] + return after[0]["arch"] if after else None +GIB = 1024.0 ** 3 +print("== per run: start cost ==") +for r in runs: + total = (r["seal_s"] or 0) + (r["ready_s"] or 0) + print("%-26s %s | seal_s %s ready_s %s cold-start total %.0f s | verify %s | %s" % ( + r["tag"], "valid " if r["valid"] else "INVALID", r["seal_s"], r["ready_s"], total, + " ".join("%s=%.1f" % (k.replace("_sha256_and_index", ""), v) for k, v in r["phases"].items()), r["startup"][:200])) + if not r["valid"]: print(" ", r["verdict"]) +print("== per run: per-turn ttft_s | decode_tok_s | input_tokens | cached_tokens ==") +for r in runs: + t = r["turns"] + print(r["tag"], "|", " ".join("%.1f" % (x.get("ttft_s") or 0) for x in t), "|", " ".join("%.1f" % (x.get("decode_tok_s") or 0) for x in t), "|", + " ".join(str(x.get("input_tokens")) for x in t), "|", " ".join(str(x.get("cached_tokens")) for x in t)) +print("== per run: host memory (GiB). at ready / after each turn: MemAvailable, Shmem, page cache of the archive; run minimum MemAvailable, max swap used, max io PSI some, major faults ==") +for r in runs: + if not r["samples"]: continue + first = at(r, r["ready_at"] or 0) + swap0 = r["samples"][0].get("SwapFree") + row = ["ready: avail %.1f shmem %.1f arch %s" % ((first.get("MemAvailable") or 0) / 1024, (first.get("Shmem") or 0) / 1024, + "%.2f" % (arch_at(r, r["ready_at"] or 0) / GIB) if arch_at(r, r["ready_at"] or 0) is not None else "-")] + for i, e in enumerate(r["turn_ends"]): + s = at(r, e); a = arch_at(r, e) + row.append("t%d: avail %.1f arch %s" % (i + 1, (s.get("MemAvailable") or 0) / 1024, "%.2f" % (a / GIB) if a is not None else "-")) + mins = min((s["MemAvailable"] for s in r["samples"] if s.get("MemAvailable")), default=0) / 1024 + swapmax = max(((swap0 or 0) - s["SwapFree"]) for s in r["samples"] if s.get("SwapFree") is not None) / 1024 if swap0 is not None else 0 + io = max((s["io10"] or 0 for s in r["samples"]), default=0) + maj = [s["pgmajfault"] for s in r["samples"] if s.get("pgmajfault") is not None] + rb = [s["read_bytes"] for s in r["samples"] if s.get("read_bytes") is not None] + print(r["tag"], "|", "; ".join(row), "| min avail %.1f swap max %.2f io-psi max %.1f majfault +%d engine read_bytes %.1f GiB" % ( + mins, swapmax, io, (maj[-1] - maj[0]) if maj else 0, (max(rb) / GIB) if rb else 0)) +print("== per run: PLE time seen by the engine (DBG window ple mean/max ms per request; DBG profile request keys containing 'ple': total ms/calls) ==") +for r in runs: + log = open(os.path.join(r["dir"], "inference.log"), errors="replace").read().splitlines() if os.path.isdir(r["dir"]) else [] + reqs, last, prof, profs = [], [], None, [] + for ln in log: + if ln.startswith("DBG window "): + last.append(dict((k, float(v)) for k, v in re.findall(r"(\w+)=([-\d.]+)", ln))) + elif ln.startswith("DBG profile request:"): + prof = {m[0]: (float(m[1]), int(m[2])) for m in re.findall(r"(\S*ple\S*?)=([\d.]+)/(\d+)", ln)} + elif "leleka-serve request outcome" in ln: + reqs.append(last); profs.append(prof); last, prof = [], None + cells = [] + for i, (w, p) in enumerate(zip(reqs, profs)): + pl = [x.get("ple", 0) for x in w] + cells.append("r%d window.ple %.2f/%.2f%s" % (i + 1, statistics.mean(pl) if pl else 0, max(pl) if pl else 0, + (" " + ",".join("%s=%.0f/%d" % (k, v[0], v[1]) for k, v in sorted((p or {}).items()))) if p else "")) + print(r["tag"], "|", " ; ".join(cells)) +print("== paired: each new arm minus the base arm before it (valid runs only), per turn ==") +for i, r in enumerate(runs): + if not r["arm"].startswith("new-file") or not r["valid"]: continue + base = next((b for b in reversed(runs[:i]) if b["arm"] == "base-memfd" and b["valid"]), None) + if not base: continue + for key, unit in (("ttft_s", "s"), ("decode_tok_s", "tok/s")): + a = [x.get(key) or 0 for x in r["turns"]]; b = [x.get(key) or 0 for x in base["turns"]] + print("%-24s minus %-18s %-12s per turn: %s mean %+.2f %s (%+.2f %%)" % (r["tag"], base["tag"], key, " ".join("%+.2f" % (x - y) for x, y in zip(a, b)), + statistics.mean(a) - statistics.mean(b), unit, 100 * (statistics.mean(a) / statistics.mean(b) - 1) if statistics.mean(b) else 0)) + print("%-24s turn-1 ttft: base %.1f s, this arm %.1f s (the first-turn cost of the cold/warm page cache is the difference)" % (r["tag"], base["turns"][0].get("ttft_s") or 0, r["turns"][0].get("ttft_s") or 0)) +PY diff --git a/scripts/e2e/decode/ram-inventory.sh b/scripts/e2e/decode/ram-inventory.sh new file mode 100644 index 00000000..cd297cd6 --- /dev/null +++ b/scripts/e2e/decode/ram-inventory.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# Host RAM inventory of the serve stack: where every GiB is, per kernel class and per process, so that "the model bytes appear once" can be read off a table. +# Read-only (/proc and fincore only). One snapshot per call; the A/B job calls it at marks (idle after READY, after the last turn) and every 60 s. +# +# ram-inventory.sh LABEL [FILE...] prints a block starting with "== RAM-INVENTORY LABEL"; FILE... are the model files whose page-cache residency is reported +# +# Blocks: +# meminfo MemTotal MemFree MemAvailable Cached Shmem AnonPages Mlocked Unevictable AnonHugePages Buffers (GiB) +# process the engine (leleka-inference), the supervisor (leleka), the gateway/daemon (leleka-daemon, strata-next, leleka-cli), the lab holder (python kar_holder*), and the +# caller of this script (the shell that holds a `leleka seal-exec` memfd): Rss, Pss, anon/file/shmem Pss, Locked (smaps_rollup), VmLck. Shared pages (a memfd the +# supervisor and the engine both map) are split by Pss, so the sum over processes does not double count them. +# memfd every memfd descriptor of those processes: apparent size and ALLOCATED bytes (st_blocks), so a sparse memfd shows its holes (allocated << apparent) +# pagecache resident bytes of the model files (fincore, mincore based, no I/O). A model byte that is both in the engine's own memory and here is held twice. +# model the rollup: Pss of the stack, page cache of the model files, MemAvailable +set -uo pipefail +label=${1:-snapshot}; shift || true +gib() { awk -v b="$1" 'BEGIN{printf "%.2f", b/1073741824}'; } +cmdline() { tr '\000' ' ' < "/proc/$1/cmdline" 2>/dev/null | cut -c1-90; } +echo "== RAM-INVENTORY $label $(date -u +%FT%TZ)" +awk '/^(MemTotal|MemFree|MemAvailable|Buffers|Cached|SwapFree|Shmem|AnonPages|Mlocked|Unevictable|AnonHugePages):/{printf "meminfo %-14s %8.2f GiB\n", $1, $2/1048576}' /proc/meminfo +total_pss=0; total_anon=0; total_shm=0; total_file=0 +report_pid() { # pid name cmd + local pid=$1 name=$2 cmd=$3 rss pss panon pfile pshm locked vmlck fd tgt apparent blocks + [ -r "/proc/$pid/smaps_rollup" ] || return + read -r rss pss panon pfile pshm locked < <(awk ' + /^Rss:/{r=$2} /^Pss:/{p=$2} /^Pss_Anon:/{a=$2} /^Pss_File:/{f=$2} /^Pss_Shmem:/{s=$2} /^Locked:/{l=$2} + END{print r+0, p+0, a+0, f+0, s+0, l+0}' "/proc/$pid/smaps_rollup") + vmlck=$(awk '/^VmLck:/{print $2}' "/proc/$pid/status" 2>/dev/null) + printf "process pid=%-7s %-16s rss=%7s pss=%7s anon=%7s file=%7s shmem=%7s locked=%7s vmlck=%7s GiB %s\n" "$pid" "$name" \ + "$(gib $((rss*1024)))" "$(gib $((pss*1024)))" "$(gib $((panon*1024)))" "$(gib $((pfile*1024)))" "$(gib $((pshm*1024)))" "$(gib $((locked*1024)))" "$(gib $((${vmlck:-0}*1024)))" "$cmd" + total_pss=$((total_pss+pss)); total_anon=$((total_anon+panon)); total_shm=$((total_shm+pshm)); total_file=$((total_file+pfile)) + for fd in /proc/$pid/fd/*; do + tgt=$(readlink "$fd" 2>/dev/null) || continue + case "$tgt" in *memfd:*) + read -r apparent blocks < <(stat -L -c '%s %b %B' "$fd" 2>/dev/null | awk '{print $1, $2*$3}') + [ -n "${apparent:-}" ] && printf "memfd pid=%-7s fd=%-4s %s apparent=%8s allocated=%8s GiB\n" "$pid" "$(basename "$fd")" "$tgt" "$(gib "$apparent")" "$(gib "$blocks")" ;; + esac + done +} +seen=" " +for name in leleka-inferenc leleka leleka-daemon strata-next leleka-cli python3; do # comm is truncated to 15 chars: pgrep -x leleka-inference never matches + for pid in $(pgrep -u "$USER" -x "$name" 2>/dev/null); do + cmd=$(cmdline "$pid") + if [ "$name" = python3 ]; then case "$cmd" in *kar_holder*|*single-copy-holder*) ;; *) continue ;; esac; fi + seen="$seen$pid "; report_pid "$pid" "$name" "$cmd" + done +done +# the caller (a `leleka seal-exec` child shell that holds the memfd) and any pids named by the harness +for pid in $PPID ${INV_EXTRA_PIDS:-}; do + case "$seen" in *" $pid "*) continue ;; esac + seen="$seen$pid "; report_pid "$pid" "caller" "$(cmdline "$pid")" +done +printf "process-sum pss=%s GiB (anon %s, file %s, shmem %s)\n" "$(gib $((total_pss*1024)))" "$(gib $((total_anon*1024)))" "$(gib $((total_file*1024)))" "$(gib $((total_shm*1024)))" +cache_total=0 +if command -v fincore >/dev/null 2>&1; then + for f in "$@"; do + [ -r "$f" ] || continue + res=$(fincore -b -n -o RES "$f" 2>/dev/null | awk '{s+=$1} END{print s+0}') + printf "pagecache %-70s resident=%8s GiB of %8s GiB\n" "$(basename "$f")" "$(gib "$res")" "$(gib "$(stat -c %s "$f")")" + cache_total=$((cache_total+res)) + done +else + echo "pagecache fincore not installed" +fi +avail=$(awk '/^MemAvailable:/{print $2*1024}' /proc/meminfo) +printf "model stack-pss=%s GiB model-file-page-cache=%s GiB MemAvailable=%s GiB\n" "$(gib $((total_pss*1024)))" "$(gib "$cache_total")" "$(gib "$avail")" diff --git a/scripts/e2e/decode/routing-lead.py b/scripts/e2e/decode/routing-lead.py new file mode 100644 index 00000000..62e776b7 --- /dev/null +++ b/scripts/e2e/decode/routing-lead.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Prefetch lead-time probe for the in-GPU preparation scheduler (candidate C of the single-copy study). + +Input: the routing dump of a decode run (`LELEKA_ORIGINAL_SERVE_DUMP_ROUTING=FILE`, written by `single-copy-ab.sh PHASES=route`): records of +(layer i32, k i32, k expert ids i32, k weights f32), k = 10. A decode window is a batch of T rows (the verified draft tokens); the engine calls the +router layer by layer and writes T records per layer, so one window is: for layer 0..47: T records. A window starts when the layer number drops. + +Question answered: at the START of a window (when the previous window's routing is known) and at the moment layer L-1 of the CURRENT window has been routed, how many of the +experts that layer L will use can be named in advance, with how many candidates, and how much wall time is left before layer L runs +(L x window_ms / 48 for the start-of-window predictions; ~0 for the router result of the layer itself)? + +Predictors (all causal): + prev1 the experts of the last row of the previous window at the same layer (what the previous token used) + prev2 the union over the last two rows + prev4 the union over the last four rows + topN the N most frequent experts of that layer in the first half of the trace (the profile ranking idea), N = 8, 16, 32, 64 + prev1+top16 union + lastlayer experts of layer L-1 in the current window -> experts that co-occurred with them at layer L in the first half (a co-occurrence table); known one layer ahead +Metrics per predictor: recall = |pred & actual| / |actual| (actual = union of the window's rows at layer L), mean candidates per layer, lead ms. + +Second part (--profile expert-profile.bin): the share of expert uses that a STATIC tier of the top-N experts of the shipped ranking would serve from VRAM, for +N = today's slot counts and for the counts a compressed tier (level-2 KAR, 0.7506 of the IQ3_S bytes: 1.332x the slots) would hold. The adaptive tier and the lent +slots move this number; the static figure bounds the gain of "more slots" from below/above only roughly, and it is the same arithmetic for both sides. + +usage: routing-lead.py ROUTING.bin [--window-ms 11.0] [--profile expert-profile.bin] [--selftest] +""" +import struct, sys, collections, random + +K = 10 # TOP_K of the Original serve path + + +def records(path): + data = open(path, "rb").read() + off = 0 + while off + 8 <= len(data): + layer, k = struct.unpack_from(" len(data): + break + ids = struct.unpack_from("<%di" % k, data, off + 8) + yield layer, ids + off += 8 + 8 * k + + +def windows(path): + """list of windows; a window is {layer: [ids, ...rows]}""" + out, cur, last = [], collections.OrderedDict(), -1 + for layer, ids in records(path): + if layer < last and cur: + out.append(cur) + cur = collections.OrderedDict() + cur.setdefault(layer, []).append(ids) + last = layer + if cur: + out.append(cur) + return out + + +def analyse(wins, window_ms): + layers = sorted({l for w in wins for l in w}) + half = len(wins) // 2 + train, test = wins[:half], wins[half:] + freq = {l: collections.Counter() for l in layers} + cooc = {l: collections.defaultdict(collections.Counter) for l in layers} + for w in train: + for l in layers: + for ids in w.get(l, []): + freq[l].update(ids) + for l in layers[1:]: + prev = set(e for ids in w.get(l - 1, []) for e in ids) + for ids in w.get(l, []): + for a in prev: + cooc[l][a].update(ids) + tops = {n: {l: set(e for e, _ in freq[l].most_common(n)) for l in layers} for n in (8, 16, 32, 64)} + names = ["prev1", "prev2", "prev4", "top8", "top16", "top32", "top64", "prev1+top16", "lastlayer(16)"] + stat = {n: [0, 0, 0] for n in names} # hit, actual, candidates + per_layer = {n: collections.defaultdict(lambda: [0, 0]) for n in names} + rows_hist = collections.Counter() + history = [] # rows of previous windows, in order, as {layer: ids} + for wi, w in enumerate(wins): + rows_hist[len(w.get(layers[0], []))] += 1 + if wi >= half and history: + last = history[-4:] + for l in layers: + actual = set(e for ids in w.get(l, []) for e in ids) + if not actual: + continue + prev_rows = [r[l] for r in last if l in r] + preds = { + "prev1": set(prev_rows[-1]) if prev_rows else set(), + "prev2": set(e for r in prev_rows[-2:] for e in r), + "prev4": set(e for r in prev_rows for e in r), + "top8": tops[8][l], "top16": tops[16][l], "top32": tops[32][l], "top64": tops[64][l], + } + preds["prev1+top16"] = preds["prev1"] | preds["top16"] + if l - 1 in w: + prev_layer = set(e for ids in w[l - 1] for e in ids) + score = collections.Counter() + for a in prev_layer: + score.update(cooc[l].get(a, {})) + preds["lastlayer(16)"] = set(e for e, _ in score.most_common(16)) + else: + preds["lastlayer(16)"] = set() + for n in names: + s = stat[n] + s[0] += len(preds[n] & actual); s[1] += len(actual); s[2] += len(preds[n]) + p = per_layer[n][l]; p[0] += len(preds[n] & actual); p[1] += len(actual) + # one row per window position is enough for "previous rows": keep the rows of this window + rows = max((len(v) for v in w.values()), default=0) + for r in range(rows): + history.append({l: w[l][r] for l in w if r < len(w[l])}) + ntest = max(len(test) * len(layers), 1) + print("windows %d (train %d, test %d), layers %d, rows per window histogram %s" % (len(wins), half, len(test), len(layers), dict(sorted(rows_hist.items())))) + print("%-16s %8s %12s | recall by layer group (lead ms at the group's first layer, for start-of-window predictors)" % ("predictor", "recall", "candidates")) + t_layer = window_ms / 48.0 + groups = [(0, 11), (12, 23), (24, 35), (36, 47)] + for n in names: + s = stat[n] + rec = s[0] / s[1] if s[1] else float("nan") + line = "%-16s %7.1f%% %12.1f |" % (n, 100 * rec, s[2] / ntest) + for a, b in groups: + h = sum(per_layer[n][l][0] for l in range(a, b + 1) if l in per_layer[n]) + t = sum(per_layer[n][l][1] for l in range(a, b + 1) if l in per_layer[n]) + lead = "~0.2" if n == "lastlayer(16)" else "%.1f" % (a * t_layer) + line += " L%d-%d %5.1f%% (%s ms)" % (a, b, 100 * h / t if t else float("nan"), lead) + print(line) + print("lead time of a start-of-window prediction at layer L = L x %.3f ms (window %.1f ms / 48); the layer's own router result gives ~0 lead (the same layer runs next)." % (t_layer, window_ms)) + + +def tier_hit_rates(wins, profile_path): + d = open(profile_path, "rb").read() + magic, ver, layers, experts, n1, n2 = struct.unpack_from("<4sIIIII", d, 0) + assert magic == b"STRP" and n1 == layers * experts, (magic, n1) + flat = struct.unpack_from("<%dH" % (2 * n1), d, 24) + rank = {} + for i in range(n1): + rank[(flat[2 * i], flat[2 * i + 1])] = i + uses, uniq = [], [] + for w in wins: + seen = set() + for l, rows in w.items(): + for ids in rows: + for e in ids: + r = rank.get((l, e)) + uses.append(r if r is not None else n1) + for e in set(e for ids in rows for e in ids): + seen.add((l, e)) + uniq.extend(rank.get(k, n1) for k in seen) + print("static tier (top-N of the shipped ranking) over %d expert uses, %d window-unique (layer, expert) pairs:" % (len(uses), len(uniq))) + for n, label in ((8000, "replay shape"), (11280, "today, seed-off 245k slots"), (12192, "today, auto slots (product)"), (15028, "compressed, same VRAM as 11,280"), + (16243, "compressed, same VRAM as 12,192"), (20000, "")): + print(" N=%6d %-34s uses in tier %5.1f %% window-unique pairs in tier %5.1f %%" % ( + n, label, 100 * sum(1 for r in uses if r < n) / len(uses), 100 * sum(1 for r in uniq if r < n) / len(uniq))) + + +def selftest(): + import tempfile, os + rnd = random.Random(1) + path = os.path.join(tempfile.gettempdir(), "routing-selftest.bin") + with open(path, "wb") as f: + for _ in range(60): + t = rnd.choice((1, 4, 5)) + for layer in range(48): + for _r in range(t): + ids = rnd.sample(range(512), K) + f.write(struct.pack("&2; exit 3; } +done +case " $PHASES " in *" id "*) for f in "$RT_BASE" "$RT_NEW" "$D/tools/q_pair.py" "$D/tools/q_lib.py" "$CAP"; do [ -e "$f" ] || { echo "missing $f (id phase)" >&2; exit 3; }; done ;; esac +"$BIN_NEW/leleka" --help 2>&1 | grep -q "seal-exec" || { echo "$BIN_NEW/leleka has no seal-exec" >&2; exit 3; } +command -v fincore >/dev/null || { echo "fincore (util-linux) is needed" >&2; exit 3; } +[ "$(stat -c %s "$KAR")" = "$KAR_BYTES" ] || { echo "$KAR is not $KAR_BYTES bytes" >&2; exit 3; } +if pgrep -u "$USER" -f 'kar_holder2?\.py' >/dev/null || [ -d "$MODELLOCK" ]; then echo "refusing to start: the holder is running (MODEL.lock/kar_holder): stop it first, its 51.5 GiB memfd and the arms do not fit" >&2; exit 3; fi +shmem_gib=$(awk '/^Shmem:/{print int($2/1048576)}' /proc/meminfo) +[ "$shmem_gib" -lt 8 ] || { echo "refusing to start: Shmem is $shmem_gib GiB (a sealed memfd is still resident)" >&2; exit 3; } +EXTENTS_SHA256=${EXTENTS_SHA256:-7568b1211419a7c10a9b39a86230f75b7fa9c02839e36c9b5f2494ec7af72143} # the pin compiled into the binary (kar_census --hash-extents, 2026-11-02) +case " $ARMS_SET " in *" file "*) + if [ "$(stat -c %h "$KAR")" != 1 ] || [ "$(( 0$(stat -c %a "$KAR") & 0222 ))" != 0 ]; then + echo "the file arm needs the archive as a single-link file without write bits: chmod 0400 $KAR (changes its ctime: old verification stamps of it are void, once)" >&2; exit 3 + fi ;; +esac +mkdir "$MODELLOCK" 2>/dev/null || { echo "MODEL.lock is held" >&2; exit 3; } +take_gpu() { local got=0; for _ in $(seq 1 1080); do if mkdir "$LOCK" 2>/dev/null; then echo "single-copy-ab $1 $(date -u +%FT%TZ)" >"$LOCK/owner"; got=1; break; fi; sleep 5; done + [ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; return 3; } + if [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null)" ]; then echo "GPU busy, skipping $1"; rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null; return 4; fi; } +drop_gpu() { rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null; } +trap 'drop_gpu; rmdir "$MODELLOCK" 2>/dev/null' EXIT + +evict() { # posix_fadvise(DONTNEED) per file: clean pages only, no root + python3 -I - "$@" <<'PY' +import os, sys +for p in sys.argv[1:]: + try: + fd = os.open(p, os.O_RDONLY); os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED); os.close(fd) + except OSError as e: + print("evict failed", p, e) +PY +} +MODEL_FILES=("$KAR" "$SHARD0" "$SHARD1" "$MTPX" "$A/data/iq3_s/dense.bin") +resident() { fincore -b -n -o RES "$1" 2>/dev/null | tr -d ' '; } +sampler() { # $1 output prefix: memsample (5 s) and a full inventory every 60 s + local i=0 + while sleep 5; do + i=$((i + 1)) + pid=$(pgrep -u "$USER" -x leleka-inferenc | head -1) + eng=""; [ -n "$pid" ] && eng=$(awk '/^(RssAnon|RssShmem|RssFile|VmLck):/{printf "%s%s ", $1, $2}' /proc/$pid/status 2>/dev/null) + echo "$(date -u +%T) $(grep -E "SwapFree|MemAvailable|^Cached|^Shmem:|^AnonPages|^Mlocked|Dirty" /proc/meminfo | tr -s " " | tr "\n" " ") $(head -1 /proc/pressure/io) $(head -1 /proc/pressure/memory) $(awk '/pswpin|pswpout|pgmajfault/{printf "%s=%s ", $1, $2}' /proc/vmstat) ENGINE ${eng:-none}" >> "$1.memsample.txt" + if [ $((i % 12)) = 0 ]; then bash "$INV" "t+$((i*5))s" "${MODEL_FILES[@]}" >> "$1.inventory.txt" 2>&1; fi + done +} +record() { # $1 file $2 arm $3 tag + { echo "arm=$2 tag=$3"; date -u +%FT%TZ; uname -r; nvidia-smi --query-gpu=driver_version --format=csv,noheader + echo "uptime: $(uptime -p)"; echo "meminfo at start:"; grep -E "MemTotal|MemAvailable|^Cached|^Shmem:|SwapFree" /proc/meminfo; free -g | sed -n 2p + echo "resident before start: kar=$(resident "$KAR") shard0=$(resident "$SHARD0") shard1=$(resident "$SHARD1")" + echo "extents_sha256=$EXTENTS_SHA256"; sha256sum "$UP" "$BIN_BASE"/leleka-inference "$BIN_NEW"/leleka "$BIN_NEW"/leleka-inference ${RT_BASE:+"$RT_BASE"} ${RT_NEW:+"$RT_NEW"} 2>/dev/null + cat "$BIN_BASE/COMMIT.txt" "$BIN_NEW/COMMIT.txt" 2>/dev/null; head -1 /data/leleka-e2e/decode/corpus/MANIFEST.txt + env | grep -E '^(LELEKA_|STRATA_|E2E_)' | sort; } > "$1" +} +seal_cmd() { # $1 arm: prints the seal-exec prefix for base/sparse + local flag=""; [ "$1" = sparse ] && flag="--sparse-ple" + echo "$BIN_NEW/leleka seal-exec --file $KAR --expect-bytes $KAR_BYTES $flag --" +} + +# ---- phase cold --------------------------------------------------------------------------------------------------------------- +OC=$OUTR/cold$RUN_TAG +if [[ " $PHASES " == *" cold "* ]]; then + mkdir -p "$OC" + for arm in sparse full sparse full; do + flag=""; [ $arm = sparse ] && flag="--sparse-ple" + evict "${MODEL_FILES[@]}" + echo "== cold $arm $(date -u +%FT%TZ) resident before: kar=$(resident "$KAR")" | tee -a "$OC/cold.txt" + t0=$(date +%s.%N) + "$BIN_NEW/leleka" seal-exec --file "$KAR" --expect-bytes $KAR_BYTES $flag -- bash -c 'echo "sealed fd={FD} after $(echo "$(date +%s.%N) - '"$t0"'" | bc) s"; bash '"$INV"' "cold-'"$arm"'-held" '"$(printf '%q ' "${MODEL_FILES[@]}")"'; sleep 1' 2>&1 | tee -a "$OC/cold.txt" | tee -a "$OC/cold-$arm-inventory.txt" | grep -a -E "sealed fd|RAM-INVENTORY|memfd|pagecache|meminfo (Shmem|Cached|MemAvail)|process-sum" + sleep 5 + done +fi + +# ---- phase probe: cost of the existing KAR level-2 decode on the GPU (candidate B/C evidence; no model, a few seconds) ------------------------- +if [[ " $PHASES " == *" probe "* ]]; then + mkdir -p "$OUTR" + if take_gpu probe; then + { echo "== KAR decode cost probe $(date -u +%FT%TZ) $(sha256sum $SC/tools/kar-probe-test | cut -c1-16)"; nvidia-smi --query-gpu=name,clocks.sm,clocks.mem --format=csv,noheader + "$SC/tools/kar-probe-test" --ignored --nocapture kar_levels_expert_cost_probe 2>&1 | grep -a -E "KAR_PROBE|test result|panicked|error" ; } | tee -a "$OUTR/kar-probe.txt" + drop_gpu + fi +fi + +# ---- phase id: teacher-forced replay (bitwise identity) ---------------------------------------------------------------------------- +OI=$OUTR/id$RUN_TAG +id_env() { + export LELEKA_STRA169_KAR_PROVENANCE=$A/qwen-iq3-s-l2-v4.kar.provenance.json LELEKA_STRA169_IQ3S_SHARD0=$SHARD0 LELEKA_STRA169_IQ3S_SHARD1=$SHARD1 + export LELEKA_STRA169_MTP_PACK=$A/data/mtp-rt LELEKA_STRA169_MTP_STAGING=$G/mtp-staging-own LELEKA_ORIGINAL_SERVE_BUDGET_GIB=30 + export LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.45 + export LELEKA_SMOKE_PROMPT_CACHE=0 LELEKA_SERVE_PROFILE=1 LELEKA_GRAPH_EXEC_REUSE=off + export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$UP LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=8000 LELEKA_CHAIN=all + export LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=4 LELEKA_ORIGINAL_SERVE_SEED=off LELEKA_ORIGINAL_SERVE_CPU_WORKERS=1 LELEKA_SPEC=4 LELEKA_SPEC_SUFFIX=0 + export LELEKA_ORIGINAL_SERVE_RT_DIR=$A/data/mtp-rt + unset LELEKA_DRAFT_VOCAB LELEKA_SERVE_DRAFT_AFTER_COMMIT LELEKA_PROMPT_EMBED_ALIAS LELEKA_VRAM_LEDGER LELEKA_DENSE_SLAB LELEKA_KAR_SPARSE_EXTENTS_SHA256 LELEKA_SM120_ATTN_DAILY_MTP LELEKA_DRAFT_FUSED_COMMIT LELEKA_DRAFT_ROUND +} +id_run() { # $1 arm (base|sparse) + local arm=$1 label=id-$1 rt=$RT_NEW + [ "$arm" = base ] && rt=$RT_BASE + take_gpu "$label" || return $? + install -d -m 0700 "$G/mtp-staging-own" + echo "=== $label $(date -u +%FT%TZ)"; free -g | sed -n 2p + ( id_env + [ "$arm" = sparse ] && export LELEKA_KAR_SPARSE_EXTENTS_SHA256=$EXTENTS_SHA256 + shape="reply@8192/8192!orig!fast!nocluster!store!qpf!gpool!mspan" + export LELEKA_TRACE_DRAFT=1 LELEKA_ORIGINAL_SERVE_REPLAY=yes LELEKA_BRINGUP_TRACE=1 LELEKA_REPLAY_DIR=$CAP LELEKA_PREFIX_TRACE=1 LELEKA_REPLAY_PREFIX_MIB=6000 LELEKA_TRACE_PREFILL_R=1 LELEKA_TRACE_LOGPROBS=16 + export LELEKA_REPLAY_MAX_NEW=${MAX_NEW:-240} LELEKA_REPLAY_FORCE=1 LELEKA_REPLAY_ARMS="I1=$shape,I2=$shape" + record "$OI/$label.env" "$arm" "$label" + sampler "$OI/$label" & SAMP=$! + flag=""; [ "$arm" = sparse ] && flag="--sparse-ple" + "$BIN_NEW/leleka" seal-exec --file "$KAR" --expect-bytes $KAR_BYTES $flag -- bash -c 'LELEKA_STRA169_KAR_FD={FD} exec nice -n 5 "$0" --ignored --exact --test-threads=1 --nocapture backend::original_serve_replay::original_serve_replay_smoke' "$rt" > "$OI/$label.full" 2>&1 + echo "rc=$? label=$label"; kill $SAMP 2>/dev/null ) + grep -a -E "^REPLAY #|test result|panicked|FAILED|expert cache [0-9]+ slots|prefix cache budget|leleka-kar-startup" "$OI/$label.full" | cut -c1-300 | tail -14 + grep -a -c "^DRAFT " "$OI/$label.full" + drop_gpu; sleep 15 +} +if [[ " $PHASES " == *" id "* ]]; then + mkdir -p "$OI"; id_run base; id_run sparse +fi + +# ---- phase e2e ---------------------------------------------------------------------------------------------------------------- +orders=("0 1 2" "1 2 0" "2 0 1" "2 1 0" "1 0 2" "0 2 1") +e2e_run() { # $1 tag $2 arm + local tag=$1 arm=$2 + take_gpu "$tag" || return $? + echo "=== $tag $(date -u +%FT%TZ)"; free -g | sed -n 2p + ( export E2E_OUT=$OUTR/$tag E2E_ASSETS=$A + mkdir -p "$E2E_OUT" + export E2E_BIN=$BIN_NEW; [ "$arm" = base ] && export E2E_BIN=$BIN_BASE + export LELEKA_BRINGUP_TRACE=1 LELEKA_PREFIX_TRACE=1 + export LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto E2E_GPU_BUDGET=$GPU_BUDGET LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.45 + local engine_args="--prefix-cache-mib $CAP_MIB --prefix-cache-tail reply --original-prefill-capacity 8192 --prefix-cache-block 8192 --spec-min-p 0" + export E2E_SAMPLE_S=10 LELEKA_CHAIN=all LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$UP LELEKA_ORIGINAL_SERVE_SEED=off + unset LELEKA_ORIGINAL_SERVE_SEED_MAX_ROWS LELEKA_SM120_ATTN_DAILY LELEKA_SM120_GU_SWIGLU LELEKA_SM120_SIDE_MIXER LELEKA_SM120_PERF LELEKA_SERVE_DRAFT_AFTER_COMMIT LELEKA_PROMPT_EMBED_ALIAS LELEKA_VRAM_LEDGER LELEKA_DENSE_SLAB LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB LELEKA_DRAFT_VOCAB E2E_KAR_FILE LELEKA_SM120_ATTN_DAILY_MTP LELEKA_DRAFT_FUSED_COMMIT + [ "${ROUTE:-}" = 1 ] && export LELEKA_ORIGINAL_SERVE_DUMP_ROUTING=$E2E_OUT/routing.bin # routed experts of every decode window row (prefetch lead-time probe), not part of the A/B + # a cold start for every arm: the model files are not in the page cache when the arm begins + evict "${MODEL_FILES[@]}" + case $arm in + sparse) engine_args="$engine_args --kar-sparse-extents-sha256 $EXTENTS_SHA256" ;; + file) export E2E_KAR_FILE=$KAR; engine_args="$engine_args --verify-stamps $STAMPS" ;; + esac + export E2E_ENGINE_ARGS=$engine_args + local FILES; FILES=$(printf '%q ' "${MODEL_FILES[@]}") + export E2E_RUN_CMD="bash $INV idle $FILES >> $E2E_OUT/inventory-marks.txt 2>&1; python3 -I $D/tools/long-session.py --src $CORPUS $SESSION_ARGS; rc=\$?; bash $INV end $FILES >> $E2E_OUT/inventory-marks.txt 2>&1; exit \$rc" + record "$E2E_OUT/env-arm.txt" "$arm" "$tag"; echo "engine args: $engine_args" >> "$E2E_OUT/env-arm.txt" + sampler "$E2E_OUT/run" & SAMP=$! + t0=$(date +%s.%N); echo "t0=$t0" >> "$E2E_OUT/env-arm.txt" + runner() { while IFS= read -r l; do printf "%s %s\n" "$(date +%s.%N)" "$l"; done; } + if [ "$arm" = file ]; then + bash "$SC/tools/run-e2e.sh" 2>&1 | runner > "$E2E_OUT/job.log" + else + flag=""; [ "$arm" = sparse ] && flag="--sparse-ple" + "$BIN_NEW/leleka" seal-exec --file "$KAR" --expect-bytes $KAR_BYTES $flag -- bash -c 'LELEKA_STRA169_KAR_FD={FD} exec bash "$0"' "$SC/tools/run-e2e.sh" 2>&1 | runner > "$E2E_OUT/job.log" + fi + kill $SAMP 2>/dev/null + grep -a -E "^[0-9.]+ (\{|.*(expert cache|prefix cache budget|ready after|refus|rror|client exit|leleka-kar-startup))" "$E2E_OUT/job.log" | cut -c1-300 | tail -12 + echo "run-e2e done $tag $(date -u +%FT%TZ)" ) + drop_gpu; sleep 15 +} +validity() { # $1 run dir $2 arm + python3 -I - "$1" "$2" <<'PY' +import json, os, re, sys +d, arm = sys.argv[1], sys.argv[2] +f = os.path.join(d, "long-session.json") +verdict = "INVALID: no long-session.json" +if os.path.exists(f): + t = json.load(open(f)) + final = (t[-1].get("input_tokens") or 0) if t else 0 + p = os.path.join(d, "inference.log") + log = open(p, errors="replace").read() if os.path.exists(p) else "" + if any("error" in r for r in t): + verdict = "INVALID: a turn failed" + elif len(t) < 5 or final < 200000: + verdict = "INVALID: %d turns, final-turn input tokens %d < 200000" % (len(t), final) + elif arm != "base" and "prefix cache budget: 6144 MiB" not in log: + verdict = "INVALID: no 'prefix cache budget: 6144 MiB' in the engine log" + elif arm == "sparse" and "verify=sparse-extents" not in log: + verdict = "INVALID: the sparse arm's engine log has no leleka-kar-startup ... verify=sparse-extents line" + elif arm == "file" and "source=file" not in log: + verdict = "INVALID: the file arm did not run with source=file" + else: + wins, last = [], [] + for ln in log.splitlines(): + if ln.startswith("DBG window "): + last.append(dict((k, float(v)) for k, v in re.findall(r"(\w+)=([-\d.]+)", ln))) + elif "leleka-serve request outcome" in ln: + wins.append(last); last = [] + w = wins[-1] if wins else [] + ple = sum(x.get("ple", 0) for x in w) / max(len(w), 1) + verdict = "VALID: 5 turns, final-turn input tokens %d; turn-5 window.ple mean %.2f ms over %d windows" % (final, ple, len(w)) + if not w: + verdict = "INVALID: no turn-5 window lines" +open(os.path.join(d, "VALIDITY.txt"), "w").write(verdict + "\n") +print(os.path.basename(d), verdict) +PY +} +if [[ " $PHASES " == *" route "* ]]; then # one extra run that dumps the routing (docs: candidate C prefetch probe); never mixed into the A/B arms + ROUTE=1 e2e_run "route-sparse$RUN_TAG" sparse && validity "$OUTR/route-sparse$RUN_TAG" sparse +fi +if [[ " $PHASES " == *" e2e "* ]]; then + set -- $ARMS_SET; arms=("$@"); narms=${#arms[@]} + if [[ " $ARMS_SET " == *" file "* ]]; then + # one CPU-only pass that records the verification stamps of the shards and the archive (file arm: the start must not hash 138 GB); twice, the second is a stamp hit + for pass in 1 2; do + ( export LELEKA_RUNTIME_TOKEN=$(head -c 24 /dev/urandom | base64 | tr -d '\n') + echo "=== stamp seed pass $pass $(date -u +%FT%TZ)" + "$BIN_NEW/leleka-inference" --listen 127.0.0.1:18766 --token-env LELEKA_RUNTIME_TOKEN --shard0 "$SHARD0" --shard1 "$SHARD1" --gpu 0 --gpu-budget $GPU_BUDGET --context-tokens 262144 \ + --kar-archive-file "$KAR" --kar-provenance "$A/qwen-iq3-s-l2-v4.kar.provenance.json" --verify-only --verify-stamps "$STAMPS" 2>&1 + echo "rc=$? $(date -u +%FT%TZ)" ) | tee -a "$OUTR/seed-stamps.log" | grep -a -E "^===|leleka-kar-startup|^rc=|refus|rror" | cut -c1-300 + evict "${MODEL_FILES[@]}" + done + fi + n=0 + for b in $(seq 1 "$BLOCKS"); do + ord=(${orders[$(( (b - 1) % 6 ))]}) + for idx in "${ord[@]}"; do + [ "$idx" -lt "$narms" ] || continue + if [ -e "$SC/STOP" ]; then echo "STOP file present: ending the A/B early so that the queue can use the GPU"; break 2; fi + arm=${arms[$idx]}; n=$((n + 1)); tag="b$(printf %02d "$b")-$arm$RUN_TAG" + e2e_run "$tag" "$arm" || continue + validity "$OUTR/$tag" "$arm" + echo "arm done $tag $(date -u +%FT%TZ)" + done + done +fi + +# ---- summary ------------------------------------------------------------------------------------------------------------------ +OUTR=$OUTR OI=$OI OC=$OC PHASES="$PHASES" python3 -I - <<'PY' +import glob, json, os, re, statistics as st, sys +root, oi, oc, phases = os.environ["OUTR"], os.environ["OI"], os.environ["OC"], os.environ["PHASES"].split() +if "id" in phases: + print("== identity (teacher-forced replay night5-long-256k; top-16 rows; A/A = arm I2 against I1 of one process)") + sys.path.insert(0, "/data/leleka-e2e/decode/dt/tools") + try: + import q_pair + logs = {a: os.path.join(oi, "id-%s.full" % a) for a in ("base", "sparse")} + rows = {a: [q_pair.rows_of(logs[a], i) for i in (0, 1)] for a in logs if os.path.exists(logs[a])} + res = [] + def cmp(a, b, label): + n, bad, flips, _ = q_pair.compare(a, b, label); res.append((label, n, bad, flips)) + for a in rows: cmp(rows[a][0], rows[a][1], a + " A/A") + if len(rows) == 2: + cmp(rows["base"][0], rows["sparse"][0], "sparse vs base arm I1"); cmp(rows["base"][1], rows["sparse"][1], "sparse vs base arm I2") + ok = bool(res) and all(n > 0 and bad == 0 and flips == 0 for _, n, bad, flips in res) + print("IDENTITY rows %s: %s" % ("PASS" if ok else "FAIL or incomplete", "; ".join("%s: common %d different %d flips %d" % r for r in res))) + except Exception as e: + print("identity not computed:", e) +if "e2e" not in phases: sys.exit(0) +runs = {} +for d in sorted(glob.glob(os.path.join(root, "b[0-9][0-9]-*"))): + name = os.path.basename(d); v = os.path.join(d, "VALIDITY.txt") + if not os.path.exists(v) or not open(v).read().startswith("VALID"): + print(name, "not used:", open(v).read().strip() if os.path.exists(v) else "no VALIDITY.txt"); continue + t = json.load(open(os.path.join(d, "long-session.json"))) + r = dict(dec=[x.get("decode_tok_s") or 0.0 for x in t], ttft=[x.get("ttft_s") or 0.0 for x in t], arm=name.split("-", 1)[1].split("-")[0], block=name[1:3]) + env = open(os.path.join(d, "env-arm.txt")).read() + t0 = re.search(r"^t0=([0-9.]+)", env, re.M); jl = open(os.path.join(d, "job.log"), errors="replace").read().splitlines() + first = next((float(l.split()[0]) for l in jl if "[run-e2e" in l), None) + ready = next((float(l.split()[0]) for l in jl if "model ready after" in l), None) + r["seal_s"] = (first - float(t0.group(1))) if (t0 and first) else None + r["ready_s"] = (ready - float(t0.group(1))) if (t0 and ready) else None + m = re.search(r"model ready after (\d+)s", "\n".join(jl)); r["load_s"] = int(m.group(1)) if m else None + runs[name] = r +def mean_all(r): return st.mean(r["dec"]) +by = {} +for k, r in runs.items(): by.setdefault(r["arm"], []).append(k) +print("== per run: all-turn decode tok/s mean, decode per turn, ttft per turn, seal s (start to run-e2e's first line), engine load s, start to ready s") +for k, r in runs.items(): + print("%-16s %.1f | %s | ttft %s | seal %s load %s ready %s" % (k, mean_all(r), " ".join("%.1f" % x for x in r["dec"]), " ".join("%.1f" % x for x in r["ttft"]), + "%.0f" % r["seal_s"] if r["seal_s"] else "-", r["load_s"], "%.0f" % r["ready_s"] if r["ready_s"] else "-")) +print("== arm means (n, mean, sd) of the all-turn decode tok/s") +for a, ks in by.items(): + xs = [mean_all(runs[k]) for k in ks] + print("%-7s n=%d mean %.2f sd %.2f ttft(t1..t5 mean) %s" % (a, len(xs), st.mean(xs), st.stdev(xs) if len(xs) > 1 else 0, " ".join("%.1f" % st.mean(c) for c in zip(*[runs[k]["ttft"] for k in ks])))) +print("== block-paired differences (same block), tok/s and %") +for a in ("sparse", "file"): + diffs = [] + for b in sorted({r["block"] for r in runs.values()}): + x = [k for k in by.get(a, []) if runs[k]["block"] == b]; y = [k for k in by.get("base", []) if runs[k]["block"] == b] + if x and y: diffs.append(mean_all(runs[x[0]]) - mean_all(runs[y[0]])) + if diffs: + base = st.mean(mean_all(runs[k]) for k in by["base"]) + se = st.stdev(diffs) / len(diffs) ** 0.5 if len(diffs) > 1 else float("nan") + print("%s - base: %s | mean %+.2f tok/s (%+.2f %%) se %.2f, n=%d blocks, %d faster" % (a, " ".join("%+.1f" % x for x in diffs), st.mean(diffs), 100 * st.mean(diffs) / base, se, len(diffs), sum(1 for x in diffs if x > 0))) +print("== RAM: system Shmem / MemAvailable at the last sample with an engine, and the inventory marks (idle after READY, end after turn 5)") +for k in runs: + f = os.path.join(root, k, "run.memsample.txt") + if os.path.exists(f): + ls = [l for l in open(f, errors="replace") if "MemAvailable" in l] + if ls: + l = ls[-1]; g = lambda n: next((int(x) for x in re.findall(n + r":?\s*(\d+)", l)), 0) / 1048576 + sw = [int(x) for ln in (ls[0], l) for x in re.findall(r"pswp(?:in|out)=(\d+)", ln)] + print("%-16s Shmem %.2f MemAvailable %.2f Cached %.2f AnonPages %.2f Mlocked %.2f GiB swapped pages %s" % (k, g("Shmem"), g("MemAvailable"), g("Cached"), g("AnonPages"), g("Mlocked"), (sw[2]-sw[0]+sw[3]-sw[1]) if len(sw)==4 else "?")) + m = os.path.join(root, k, "inventory-marks.txt") + if os.path.exists(m): + for ln in open(m, errors="replace"): + if ln.startswith(("== RAM-INVENTORY", "process pid", "memfd ", "process-sum", "pagecache", "model ", "meminfo MemAvailable", "meminfo Shmem")): print(" " + ln.rstrip()[:200]) +PY +sha256sum "$OUTR"/*/long-session.json "$OI"/*.full 2>/dev/null | head -60 +date -u +%FT%TZ diff --git a/scripts/e2e/decode/single-copy-holder.py b/scripts/e2e/decode/single-copy-holder.py new file mode 100644 index 00000000..3a458cf4 --- /dev/null +++ b/scripts/e2e/decode/single-copy-holder.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Lab holder, v3: the same queue protocol as ~/work/gpu-runs/holder/kar_holder2.py, but the sealed memfd is NOT filled here. + +`single-copy-holder.sh` runs `leleka seal-exec --file ARCHIVE -- python3 single-copy-holder.py {FD} JOBS`: the Rust sealer copies the archive with large +O_DIRECT blocks on many threads (docs: unattended "fast cold load"; 600 MB/s and up against 8-35 MB/s for a buffered 16 MiB read loop on this NVMe) and never +leaves the 55 GB in the page cache, which kar_holder2.py's buffered read does (a second copy of the archive in RAM, ~50 GB, until something evicts it). +This process only inherits the descriptor and runs the job scripts exactly as kar_holder2.py does: + + * queue: names listed in JOBS/PRIORITY (top first), then the oldest *.sh first; the queue is re-read after every job; files younger than 3 s are skipped; + * a job runs as `bash JOB` with LELEKA_STRA169_KAR_FD= and the fd passed; JOB.running while it runs, JOB.done (rc) after; + * JOBS/STOP (checked between jobs) ends the holder; JOBS/READY holds the fd number. +""" +import glob, os, subprocess, sys, time + +fd = int(sys.argv[1]) +jobs = sys.argv[2] +st = os.fstat(fd) +print(f"holder3 ready fd={fd} bytes={st.st_size} allocated={st.st_blocks * 512}", flush=True) +open(os.path.join(jobs, "READY"), "w").write(str(fd)) + + +def pending(): + out = [] + for job in glob.glob(os.path.join(jobs, "*.sh")): + base = job[:-3] + if os.path.exists(base + ".done") or os.path.exists(base + ".running"): + continue + try: + if time.time() - os.path.getmtime(job) < 3: + continue + out.append((os.path.getmtime(job), job)) + except OSError: + pass + return out + + +def pick(): + p = pending() + if not p: + return None + try: + prio = [l.strip() for l in open(os.path.join(jobs, "PRIORITY")) if l.strip() and not l.startswith("#")] + except OSError: + prio = [] + byname = {os.path.basename(j)[:-3]: j for _, j in p} + for name in prio: + if name in byname: + return byname[name] + return min(p)[1] + + +while not os.path.exists(os.path.join(jobs, "STOP")): + job = pick() + if job is None: + time.sleep(2) + continue + base = job[:-3] + open(base + ".running", "w").close() + env = dict(os.environ, LELEKA_STRA169_KAR_FD=str(fd)) + with open(base + ".log", "wb") as log: + rc = subprocess.run(["bash", job], stdout=log, stderr=subprocess.STDOUT, env=env, pass_fds=[fd]).returncode + os.remove(base + ".running") + open(base + ".done", "w").write(str(rc)) diff --git a/scripts/e2e/decode/single-copy-holder.sh b/scripts/e2e/decode/single-copy-holder.sh new file mode 100644 index 00000000..55a20aa6 --- /dev/null +++ b/scripts/e2e/decode/single-copy-holder.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# Start the lab holder with the fast, page-cache-free seal (see single-copy-holder.py). Same MODEL.lock contract as run_holder2.sh. +# single-copy-holder.sh [BIN_DIR] BIN_DIR holds `leleka` (default /data/leleka-e2e/decode/dt/bin-singlecopy) +# Run it detached: cd ~/work/gpu-runs/holder2 && rm -f jobs/STOP && setsid nohup bash /data/leleka-e2e/single-copy/tools/single-copy-holder.sh > holder3.out 2>&1 & +set -u +BIN=${1:-/data/leleka-e2e/decode/dt/bin-singlecopy} +T=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +KAR=/home/para/work/leleka/models/leleka-gates/assets/qwen-iq3-s-l2-v4.kar +JOBS=$HOME/work/gpu-runs/holder2/jobs +until mkdir "$HOME/work/gpu-runs/MODEL.lock" 2>/dev/null; do sleep 20; done +trap 'rmdir "$HOME/work/gpu-runs/MODEL.lock"' EXIT +cd "$HOME/work/gpu-runs/holder2" || exit 1 +rm -f "$JOBS/READY" +exec_start=$(date +%s) +LELEKA_LOAD_THREADS=${LELEKA_LOAD_THREADS:-8} "$BIN/leleka" seal-exec --file "$KAR" --expect-bytes 55295529472 -- python3 "$T/single-copy-holder.py" '{FD}' "$JOBS" +echo "holder3 ended rc=$? after $(( $(date +%s) - exec_start )) s" diff --git a/scripts/e2e/decode/single-copy-window.sh b/scripts/e2e/decode/single-copy-window.sh new file mode 100644 index 00000000..99ab0497 --- /dev/null +++ b/scripts/e2e/decode/single-copy-window.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# A holder-free window for single-copy-ab.sh, started DETACHED by a holder job stub (the stub touches jobs/STOP, closes the holder's descriptor and launches this). +# single-copy-window.sh LABEL environment (PHASES, BLOCKS, ARMS_SET, RUN_TAG, OUTR) is passed through to single-copy-ab.sh +# 1. waits until the holder process has ended and its 51.5 GiB memfd is gone (the holder ends after the stub returns because jobs/STOP exists); +# 2. runs single-copy-ab.sh (it takes MODEL.lock and gpu.lock itself); +# 3. ALWAYS restarts the lab holder afterwards, with the fast seal (single-copy-holder.sh: O_DIRECT, no page cache), so the queue goes on. +# The A/B ends early (between runs) when /data/leleka-e2e/single-copy/STOP exists. +set -u +LABEL=${1:-window} +SC=/data/leleka-e2e/single-copy +H=$HOME/work/gpu-runs/holder2 +NOTES=/data/leleka-e2e/decode/notes.md +note() { echo "[$(date -u +%FT%TZ)] [DEV single-copy] $*" >> "$NOTES"; } +restart_holder() { + if pgrep -u "$USER" -f 'kar_holder2?\.py|single-copy-holder\.py' >/dev/null; then echo "a holder is already running"; return; fi + rmdir "$HOME/work/gpu-runs/MODEL.lock" 2>/dev/null # ours, if the A/B died holding it + rm -f "$H/jobs/STOP" "$H/jobs/READY" + ( cd "$H" && setsid nohup bash "$SC/tools/single-copy-holder.sh" > "$H/holder3.out" 2>&1 < /dev/null & ) + note "window $LABEL over: holder restarted with the fast seal (holder3.out); queue open again" +} +trap restart_holder EXIT +note "window $LABEL: waiting for the holder to end (jobs/STOP is set), then single-copy-ab.sh PHASES='${PHASES:-cold id e2e}' BLOCKS=${BLOCKS:-6}" +for _ in $(seq 1 240); do + if ! pgrep -u "$USER" -f 'kar_holder2?\.py|single-copy-holder\.py' >/dev/null && [ ! -d "$HOME/work/gpu-runs/MODEL.lock" ]; then break; fi + sleep 5 +done +if pgrep -u "$USER" -f 'kar_holder2?\.py|single-copy-holder\.py' >/dev/null; then note "window $LABEL: the holder did not end in 20 min, giving up (holder left as it is)"; trap - EXIT; exit 3; fi +# the file arm needs the archive as a read-only file (what `leleka up` does for kar_source=file: mode 0400; changes its ctime once) +KAR=$HOME/work/leleka/models/leleka-gates/assets/qwen-iq3-s-l2-v4.kar +if [ -w "$KAR" ]; then chmod 0400 "$KAR" && note "window $LABEL: chmod 0400 on the KAR archive (file arm; the product's own step; ctime moved once)"; fi +# the holder's 51.5 GiB must really be gone +sleep 5 +note "window $LABEL: holder gone, MemAvailable $(awk '/^MemAvailable:/{printf "%d GiB", $2/1048576}' /proc/meminfo); starting" +# gentler on the model volume than the default (32 threads, 8 MiB blocks): the server hung on 2026-11-02 while heavy O_DIRECT reads of that volume were around +LELEKA_LOAD_THREADS=${LELEKA_LOAD_THREADS:-8} LELEKA_LOAD_CHUNK_MIB=${LELEKA_LOAD_CHUNK_MIB:-8} bash "$SC/tools/${AB_SCRIPT:-single-copy-ab.sh}" > "$SC/window-$LABEL.out" 2>&1 +note "window $LABEL: single-copy-ab.sh ended rc=$?; outputs under ${OUTR:-/data/leleka-e2e/runs/single-copy-ab}, log $SC/window-$LABEL.out" diff --git a/scripts/e2e/decode/sparse-memfd-ab.sh b/scripts/e2e/decode/sparse-memfd-ab.sh new file mode 100644 index 00000000..d1767889 --- /dev/null +++ b/scripts/e2e/decode/sparse-memfd-ab.sh @@ -0,0 +1,348 @@ +#!/usr/bin/env bash +# Sparse-memfd A/B: the sealed KAR memfd that holds ONLY the byte ranges the serve path reads (the PLE rows, header, directory; about 16 GB of 55.3 GB, the rest is a hole) +# against the full memfd, SAME binaries in both arms, paired 5-turn ~245k session on the frozen corpus, counterbalanced arm order. Shape copied from draftvocab-ab.sh / +# speedtrain3-ab.sh (+ draftvocab-id.sh for the identity part). Design and the claims it tests: docs/kar-sparse-memfd.md, docs/design/memory-single-copy-and-elastic-state.md B0. +# THIS IS NOT A HOLDER JOB. It makes its own sealed memfd per arm (`leleka seal-exec`), and the holder's 55 GB memfd would not fit next to it (55.3 + 16 + 54 GiB of bank +# on a 121 GiB host). Run it with the holder STOPPED: it refuses to start while $G/MODEL.lock exists or while Shmem is above 8 GiB, and it takes MODEL.lock itself. +# It takes /data/leleka-e2e/gpu.lock per arm, one arm at a time, and skips an arm when something else uses the GPU. NOT QUEUED by its author: the orchestrator decides when. +# +# Install (laptop -> server, small files only): +# cp scripts/e2e/decode/sparse-memfd-ab.sh /data/leleka-e2e/decode/dt/jobs/sparse-memfd-ab.sh +# binaries, built once from claude/sparse-memfd in release mode and frozen read-only (record their sha256 in dt/BUILD.md): +# dt/bin-sparsememfd/{leleka,leleka-inference,leleka-daemon,leleka-cli,strata-next} the same five for both arms +# dt/rt-sparsememfd the leleka-runtime lib test binary (replay smoke) of the same commit +# EXTENTS_SHA256=<64 hex> the pinned digest of the archive's extents, from `kar_census ARCHIVE --hash-extents` on the archive that matched its full SHA-256 (docs/kar-sparse-memfd.md) +# +# EXTENTS_SHA256=... bash sparse-memfd-ab.sh # PHASES="id e2e": identity, then the 4-arm session A/B (about 90 GPU-min) +# PHASES=id EXTENTS_SHA256=... bash sparse-memfd-ab.sh # only the teacher-forced identity gate (2 processes, about 20 min) +# PHASES=e2e ARMS="full sparse sparse full full sparse" ... bash sparse-memfd-ab.sh # only the session A/B, 6 arms +# +# Arms. Every arm: the same binaries, seed OFF (LELEKA_ORIGINAL_SERVE_SEED=off), the ranked upstream profile, EXPERT_SLOTS auto (id: fixed 8000), GPU budget 32,819,404,800 (the product +# profile), prefix cache 6144 MiB (the explicit cap of the profile: `auto` would grow with the freed RAM and make the arms differ), tail reply, chunk and grid 8192. The ONLY variable: +# full `leleka seal-exec --file ARCHIVE` the whole 55.3 GB archive in the memfd, the engine verifies it against the archive SHA-256 (the pre-change form) +# sparse `leleka seal-exec --file ARCHIVE --sparse-ple` only the extents; the engine gets `--kar-sparse-extents-sha256 $EXTENTS_SHA256` (replay: LELEKA_KAR_SPARSE_EXTENTS_SHA256) and verifies the +# memfd against the pinned digest of the extents; the memory governor locks and heals the extents only +# Workload (the only valid one): the FROZEN corpus /data/leleka-e2e/decode/corpus/src/crates, 5 turns, target 245000 tokens, --max-output 300; identity: the 256k-class capture +# night5-long-256k, 5 requests, recorded replies, decode capped at 48 tokens each, teacher forced, top-16 logprobs of every row. +# Records per run (env-arm.txt): UTC time, binary sha256, extents digest, /proc/meminfo and `free -g` at start (page cache NOT dropped: this script may not write /proc/sys/vm), +# kernel, driver, the env; memsample.txt every 5 s: MemAvailable, Shmem, Cached, SwapFree, PSI, pswpin/pswpout/pgmajfault and, of the engine, RssAnon/RssShmem/VmLck. +# Validity per e2e run (VALIDITY.txt): 5 turns, no turn failed, final-turn input tokens >= 200000, turn-5 mean window.ple < 5 ms, "prefix cache budget: 6144 MiB" in the engine log, and for +# a sparse run the engine log shows no verification failure. An INVALID run is never used in a comparison. +# +# ACCEPTANCE (design doc T4; this script prints each line, it does not decide for the owner): +# G1 identity every forced row of every request: top-16 ids and logprobs BITWISE equal, sparse against full, and full against full (A/A) the same; 0 argmax flips. A lossless repack +# must be exactly equal, not "within tolerance". +# G2 memory system Shmem (/proc/meminfo, where a sealed memfd is counted) lower by 36.6 GiB +- 1.5 in the sparse arms at turn 5; MemAvailable at turn 5 higher by >= 35 GiB; swap in/out +# of the run zero in every arm. (The engine's own RssShmem is printed too, but a memfd that is not mlock-ed is not in its page tables, so it is not the gate.) +# G3 speed decode tok/s and TTFT per turn of sparse within the run-to-run noise of the full arms (decode-tail: 3-8 %); turn-5 window.ple unchanged. Reads hit the same pages, so no +# change is expected; a gain would be unexplained and a loss is a failure. +# G4 cap the prefix store stays at 6144 MiB in both arms (the engine log line) although the sparse arm has ~36 GiB more MemAvailable. +# NOT decided here: nothing about speed in other workloads, other hosts, the laptop (file-backed archive; no memfd there) or a different model. +set -uo pipefail +D=/data/leleka-e2e/decode/dt +LOCK=/data/leleka-e2e/gpu.lock +G=$HOME/work/gpu-runs +OUTR=/data/leleka-e2e/runs/sparsememfd-ab +CORPUS=/data/leleka-e2e/decode/corpus/src/crates +UP=/data/leleka-e2e/decode/assets/expert-profile-upstream.bin # ranked upstream profile; run-e2e.sh refuses any other digest +A=$HOME/work/leleka/models/leleka-gates/assets +KAR=${KAR:-$A/qwen-iq3-s-l2-v4.kar} +KAR_BYTES=55295529472 +BIN=$D/bin-sparsememfd +RT=$D/rt-sparsememfd +CAP=/data/leleka-e2e/sm120/capture/night5-long-256k +RUN_TAG=${RUN_TAG:-} # suffix of the run directories (a rerun next to earlier ones) +PHASES=${PHASES:-"id e2e"} +ARMS=${ARMS:-"full sparse sparse full"} +EXTENTS_SHA256=${EXTENTS_SHA256:-} +SESSION_ARGS="--turns 5 --target-tokens 245000 --max-output 300 --min-final-tokens 200000" +CAP_MIB=6144 +mkdir -p "$OUTR" + +# ---- guards -------------------------------------------------------------------------------------------------------------------- +for f in "$UP" "$D/tools/long-session.py" "$D/scripts/e2e/run-e2e.sh" "$BIN/leleka" "$BIN/leleka-inference" "$BIN/leleka-daemon" "$BIN/leleka-cli" "$BIN/strata-next" "$KAR" "$CORPUS/backend-api/src/lib.rs"; do + [ -r "$f" ] || { echo "missing $f" >&2; exit 3; } +done +case " $PHASES " in *" id "*) for f in "$RT" "$D/tools/q_pair.py" "$D/tools/q_lib.py" "$CAP"; do [ -e "$f" ] || { echo "missing $f (identity phase)" >&2; exit 3; }; done ;; esac +"$BIN/leleka" --help 2>&1 | grep -q "seal-exec" || { echo "$BIN/leleka has no seal-exec subcommand: build it from claude/sparse-memfd" >&2; exit 3; } +need_pin=0 +case " $ARMS " in *" sparse "*) need_pin=1 ;; esac +case " $PHASES " in *" id "*) need_pin=1 ;; esac +if [ $need_pin = 1 ]; then + echo "$EXTENTS_SHA256" | grep -Eq '^[0-9a-f]{64}$' || { echo "EXTENTS_SHA256 must be the 64 hex digits printed by 'kar_census ARCHIVE --hash-extents' (docs/kar-sparse-memfd.md)" >&2; exit 3; } +fi +[ "$(stat -c %s "$KAR")" = "$KAR_BYTES" ] || { echo "$KAR is not $KAR_BYTES bytes" >&2; exit 3; } +if [ -d "$G/MODEL.lock" ]; then echo "refusing to start: $G/MODEL.lock exists (the holder is running). This job makes its own memfd; stop the holder first, a second 55 GB memfd does not fit" >&2; exit 3; fi +shmem_gib=$(awk '/^Shmem:/{print int($2/1048576)}' /proc/meminfo) +if [ "$shmem_gib" -ge 8 ]; then echo "refusing to start: Shmem is $shmem_gib GiB (a sealed memfd is still resident; stop the holder)" >&2; exit 3; fi + +# ---- the environment of the processes (copied from run-e2e.sh / draftvocab-id.sh; nothing here differs between arms) ---------------------- +export LD_LIBRARY_PATH=$HOME/cuda-toolkits/cublas-12.9.1.4/lib:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-} + +take_locks() { # $1 label: gpu.lock, then MODEL.lock; 0 on success + local got=0 + for _ in $(seq 1 1080); do + if mkdir "$LOCK" 2>/dev/null; then echo "sparse-memfd-ab $1 $(date -u +%FT%TZ)" >"$LOCK/owner"; got=1; break; fi + sleep 5 + done + [ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; return 3; } + if [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null)" ]; then + echo "GPU busy, skipping $1"; rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null; return 4 + fi + if ! mkdir "$G/MODEL.lock" 2>/dev/null; then echo "MODEL.lock appeared ($G): the holder is back; skipping $1"; rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null; return 5; fi + return 0 +} +drop_locks() { rmdir "$G/MODEL.lock" 2>/dev/null; rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null; } +trap 'drop_locks' EXIT + +sampler() { # $1 output file; runs until killed + while sleep 5; do + pid=$(pgrep -u "$USER" -x leleka-inference | head -1) + eng=""; [ -n "$pid" ] && eng=$(awk '/^(RssAnon|RssShmem|VmLck):/{printf "%s%s ", $1, $2}' /proc/$pid/status 2>/dev/null) + echo "$(date +%T) $(grep -E "SwapFree|MemAvailable|^Cached|^Shmem:|Dirty" /proc/meminfo | tr -s " " | tr "\n" " ") $(head -1 /proc/pressure/io) $(head -1 /proc/pressure/memory) $(awk '/pswpin|pswpout|pgmajfault/{printf "%s=%s ", $1, $2}' /proc/vmstat) ENGINE ${eng:-none}" + done > "$1" 2>/dev/null +} + +record() { # $1 file, $2 arm, $3 tag + { echo "arm=$2 tag=$3"; date -u +%FT%TZ; uname -r; nvidia-smi --query-gpu=driver_version --format=csv,noheader + echo "page cache NOT dropped (no write access to /proc/sys/vm); meminfo at start:"; grep -E "MemTotal|MemAvailable|^Cached|^Shmem:|SwapFree" /proc/meminfo; free -g | sed -n 2p + echo "extents_sha256=${EXTENTS_SHA256:-none} (arm sparse only)"; sha256sum "$UP" "$BIN"/leleka "$BIN"/leleka-inference "$BIN"/leleka-daemon "$BIN"/leleka-cli "$BIN"/strata-next ${RT:+"$RT"} 2>/dev/null + cat "$BIN/COMMIT.txt" 2>/dev/null; head -1 /data/leleka-e2e/decode/corpus/MANIFEST.txt + env | grep -E '^(LELEKA_|STRATA_|E2E_)' | sort; } > "$1" +} + +# the sealed memfd of an arm, then the command: `{FD}` is the descriptor number (replaced by leleka seal-exec) +seal_run() { # $1 arm; rest: the command words (bash -c STRING ...) + local arm=$1; shift + local flag=""; [ "$arm" = sparse ] && flag="--sparse-ple" + "$BIN/leleka" seal-exec --file "$KAR" --expect-bytes $KAR_BYTES $flag -- "$@" +} + +# ---- phase id: teacher-forced replay, top-16 logprobs, equal fixed slot count ----------------------------------------------------------- +OI=$OUTR/id$RUN_TAG +id_env() { # the replay stack, as draftvocab-id.sh + export LELEKA_STRA169_KAR_PROVENANCE=$A/qwen-iq3-s-l2-v4.kar.provenance.json + export LELEKA_STRA169_IQ3S_SHARD0=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf + export LELEKA_STRA169_IQ3S_SHARD1=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf + export LELEKA_STRA169_MTP_PACK=$A/data/mtp-rt LELEKA_STRA169_MTP_STAGING=$G/mtp-staging-own LELEKA_ORIGINAL_SERVE_BUDGET_GIB=30 + export LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.55 + export LELEKA_SMOKE_PROMPT_CACHE=0 LELEKA_SERVE_PROFILE=1 LELEKA_GRAPH_EXEC_REUSE=off + export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$UP LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=8000 LELEKA_CHAIN=all + export LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0 LELEKA_ORIGINAL_SERVE_SEED=off LELEKA_ORIGINAL_SERVE_CPU_WORKERS=1 LELEKA_SPEC=4 LELEKA_SPEC_SUFFIX=0 + export LELEKA_ORIGINAL_SERVE_RT_DIR=$A/data/mtp-rt + unset LELEKA_DRAFT_VOCAB LELEKA_SERVE_DRAFT_AFTER_COMMIT LELEKA_PROMPT_EMBED_ALIAS LELEKA_VRAM_LEDGER LELEKA_DENSE_SLAB LELEKA_KAR_SPARSE_EXTENTS_SHA256 +} +id_run() { # $1 arm + local arm=$1 label=id-$1 + take_locks "$label" || return $? + install -d -m 0700 "$G/mtp-staging-own" + echo "=== $label $(date -u +%FT%TZ)"; free -g | sed -n 2p + ( id_env + [ "$arm" = sparse ] && export LELEKA_KAR_SPARSE_EXTENTS_SHA256=$EXTENTS_SHA256 + shape="reply@8192/8192!orig!fast!nocluster!store!qpf!gpool!mspan" + export LELEKA_ORIGINAL_SERVE_REPLAY=yes LELEKA_BRINGUP_TRACE=1 LELEKA_REPLAY_DIR=$CAP LELEKA_PREFIX_TRACE=1 LELEKA_REPLAY_PREFIX_MIB=6000 LELEKA_TRACE_PREFILL_R=1 LELEKA_TRACE_LOGPROBS=16 + export LELEKA_REPLAY_MAX_NEW=48 LELEKA_REPLAY_FORCE=1 LELEKA_REPLAY_ARMS="I1=$shape,I2=$shape" + record "$OI/$label.env" "$arm" "$label" + sampler "$OI/$label.memsample.txt" & SAMP=$! + seal_run "$arm" bash -c 'LELEKA_STRA169_KAR_FD={FD} exec nice -n 5 "$0" --ignored --exact --test-threads=1 --nocapture backend::original_serve_replay::original_serve_replay_smoke' "$RT" > "$OI/$label.full" 2>&1 + echo "rc=$? label=$label"; kill $SAMP 2>/dev/null ) + grep -a -E "leleka-seal-exec|leleka seal-exec|^REPLAY|test result|panicked|FAILED|expert cache [0-9]+ slots|prefix cache budget" "$OI/$label.full" | cut -c1-300 | tail -12 + drop_locks + sleep 15 +} + +# ---- phase e2e: the session A/B ------------------------------------------------------------------------------------------------- +e2e_run() { # $1 tag, $2 arm + local tag=$1 arm=$2 + take_locks "$tag" || return $? + echo "=== $tag $(date -u +%FT%TZ)"; free -g | sed -n 2p + ( export E2E_BIN=$BIN E2E_OUT=$OUTR/$tag + mkdir -p "$E2E_OUT" + export LELEKA_BRINGUP_TRACE=1 LELEKA_PREFIX_TRACE=1 + export LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto E2E_GPU_BUDGET=${GPU_BUDGET:-32819404800} + export E2E_ENGINE_ARGS="--prefix-cache-mib $CAP_MIB --prefix-cache-tail reply --original-prefill-capacity 8192 --prefix-cache-block 8192 --spec-min-p 0" + [ "$arm" = sparse ] && E2E_ENGINE_ARGS="$E2E_ENGINE_ARGS --kar-sparse-extents-sha256 $EXTENTS_SHA256" + export E2E_SAMPLE_S=10 LELEKA_CHAIN=all + export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$UP + unset LELEKA_ORIGINAL_SERVE_SEED_MAX_ROWS LELEKA_SM120_ATTN_DAILY LELEKA_SM120_GU_SWIGLU LELEKA_SM120_SIDE_MIXER LELEKA_SM120_PERF LELEKA_SERVE_DRAFT_AFTER_COMMIT LELEKA_PROMPT_EMBED_ALIAS LELEKA_VRAM_LEDGER LELEKA_DENSE_SLAB LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB LELEKA_DRAFT_VOCAB + export LELEKA_ORIGINAL_SERVE_SEED=off + export E2E_RUN_CMD="python3 -I $D/tools/long-session.py --src $CORPUS $SESSION_ARGS" + record "$E2E_OUT/env-arm.txt" "$arm" "$tag" + sampler "$E2E_OUT/memsample.txt" & SAMP=$! + seal_run "$arm" bash -c 'LELEKA_STRA169_KAR_FD={FD} exec bash "$0"' "$D/scripts/e2e/run-e2e.sh" 2>&1 | grep -a -E "^\{|leleka-seal-exec|leleka seal-exec|expert cache|prefix cache budget|request outcome|ready after|rc=|refus|error|Error|long_session|client exit" | cut -c1-300 + kill $SAMP 2>/dev/null + echo "run-e2e done $tag $(date -u +%FT%TZ)" ) + drop_locks + sleep 15 +} + +validity() { # $1 run dir, $2 arm + python3 -I - "$1" "$2" <<'PY' +import json, os, re, sys +d, arm = sys.argv[1], sys.argv[2] +f = os.path.join(d, "long-session.json") +verdict = "INVALID: no long-session.json" +if os.path.exists(f): + t = json.load(open(f)) + final = (t[-1].get("input_tokens") or 0) if t else 0 + log = open(os.path.join(d, "inference.log"), errors="replace").read() if os.path.exists(os.path.join(d, "inference.log")) else "" + if any("error" in r for r in t): + verdict = "INVALID: a turn failed" + elif len(t) < 5 or final < 200000: + verdict = "INVALID: %d turns, final-turn input tokens %d < 200000 (short corpus?)" % (len(t), final) + elif "prefix cache budget: 6144 MiB" not in log: + verdict = "INVALID: the engine log has no 'prefix cache budget: 6144 MiB' (cap not in force: the arms would differ)" + elif arm == "sparse" and re.search(r"leleka-kar phase=\w+ class=(ExtentsSha|ArchiveSha|Integrity|Range)", log): + verdict = "INVALID: the sparse memfd failed verification" + else: + verdict = "VALID: 5 turns, final-turn input tokens %d" % final + wins, last = [], [] + for ln in log.splitlines(): + if ln.startswith("DBG window "): + last.append(dict((k, float(v)) for k, v in re.findall(r"(\w+)=([-\d.]+)", ln))) + elif "leleka-serve request outcome" in ln: + wins.append(last); last = [] + w = wins[-1] if wins else [] + ple = sum(x.get("ple", 0) for x in w) / max(len(w), 1) + verdict += "; turn-5 window.ple mean %.2f ms over %d windows" % (ple, len(w)) + if not w: + verdict = "INVALID: no turn-5 window lines (trace env missing?)" + elif ple >= 5: + verdict = "INVALID: turn-5 window.ple mean %.2f ms >= 5 ms (PLE scan back?)" % ple +open(os.path.join(d, "VALIDITY.txt"), "w").write(verdict + "\n") +print(os.path.basename(d), verdict) +PY +} + +# ---- run ------------------------------------------------------------------------------------------------------------------------ +case " $PHASES " in + *" id "*) + mkdir -p "$OI" + id_run full; id_run sparse + ;; +esac +case " $PHASES " in + *" e2e "*) + n=0 + for arm in $ARMS; do + case $arm in full|sparse) ;; *) echo "unknown arm $arm" >&2; exit 2 ;; esac + n=$((n + 1)); tag="$arm-r$n$RUN_TAG" + e2e_run "$tag" "$arm" || continue + validity "$OUTR/$tag" "$arm" + echo "arm done $tag $(date -u +%FT%TZ)" + done + ;; +esac + +# ---- summary -------------------------------------------------------------------------------------------------------------------- +OUTR=$OUTR OI=$OI PHASES="$PHASES" python3 -I - <<'PY' +import glob, json, os, re, statistics as st, sys +root, oi, phases = os.environ["OUTR"], os.environ["OI"], os.environ["PHASES"].split() + +if "id" in phases: + print("== G1 identity: top-16 rows of the teacher-forced replay (night5-long-256k), arm I1 and I2 of each process") + sys.path.insert(0, "/data/leleka-e2e/decode/dt/tools") + try: + import q_pair + logs = {a: os.path.join(oi, "id-%s.full" % a) for a in ("full", "sparse")} + rows = {a: [q_pair.rows_of(logs[a], i) for i in (0, 1)] for a in logs if os.path.exists(logs[a])} + verdicts = [] + def cmp(a, b, label): + n, bad, flips, _ = q_pair.compare(a, b, label) + verdicts.append((label, n, bad, flips)) + if "full" in rows: + cmp(rows["full"][0], rows["full"][1], "full, arm1 against arm0 (A/A noise floor; must be 0 different)") + if "sparse" in rows: + cmp(rows["sparse"][0], rows["sparse"][1], "sparse, arm1 against arm0 (A/A)") + if "full" in rows and "sparse" in rows: + cmp(rows["full"][0], rows["sparse"][0], "sparse against full, arm0") + cmp(rows["full"][1], rows["sparse"][1], "sparse against full, arm1") + ok = bool(verdicts) and all(n > 0 and bad == 0 and flips == 0 for _, n, bad, flips in verdicts) + print("G1 %s: %s" % ("PASS" if ok else "FAIL or incomplete", "; ".join("%s: common %d different %d flips %d" % v for v in verdicts))) + except Exception as e: # the tools may be missing; the logs are still there + print("G1 not computed:", e) + +if "e2e" not in phases: + sys.exit(0) + +def run_number(path): + tail = path.rsplit("-r", 1)[-1] + return int(re.sub(r"\D.*", "", tail) or 0) + +runs, order = {}, [] +for d in sorted(glob.glob(os.path.join(root, "*-r*")), key=run_number): + name = os.path.basename(d) + v = os.path.join(d, "VALIDITY.txt") + if not os.path.exists(v) or not open(v).read().startswith("VALID"): + print(name, "not used:", open(v).read().strip() if os.path.exists(v) else "no VALIDITY.txt") + continue + t = json.load(open(os.path.join(d, "long-session.json"))) + runs[name] = dict(dec=[x.get("decode_tok_s") or 0.0 for x in t], ttft=[x.get("ttft_s") or 0.0 for x in t], tokens=[x.get("input_tokens") for x in t], cached=[x.get("cached_tokens") for x in t]) + order.append(name) + +def arm(name): + return name.rsplit("-r", 1)[0] + +def line(label, xs, fmt="%.1f"): + return "%s %s mean %.2f" % (label, " ".join(fmt % x for x in xs), st.mean(xs)) + +for k in order: + print(k, "tokens", runs[k]["tokens"], "cached", runs[k]["cached"]) + print(" " + line("decode tok/s", runs[k]["dec"])) + print(" " + line("ttft s ", runs[k]["ttft"])) + +by = {} +for k in order: + by.setdefault(arm(k), []).append(k) +if "full" in by and "sparse" in by: + print("== G3 speed: per-turn mean of the repeats, sparse minus full, against the spread of the full arms (the A/A noise)") + for metric in ("dec", "ttft"): + mean = {a: [st.mean(c) for c in zip(*[runs[k][metric] for k in ks])] for a, ks in by.items()} + diff = [100 * (s / f - 1) if f else float("nan") for s, f in zip(mean["sparse"], mean["full"])] + fulls = [runs[k][metric] for k in by["full"]] + spread = [100 * (max(c) - min(c)) / st.mean(c) if st.mean(c) else float("nan") for c in zip(*fulls)] if len(fulls) > 1 else [] + print("%s: full %s | sparse %s | sparse vs full per turn %s %%%s" % (metric, " ".join("%.1f" % x for x in mean["full"]), " ".join("%.1f" % x for x in mean["sparse"]), + " ".join("%+.1f" % x for x in diff), (" | full-vs-full spread %s %%" % " ".join("%.1f" % x for x in spread)) if spread else " | only one full run: no noise estimate")) + pairs = [] + for i, k in enumerate(order[:-1]): + n = order[i + 1] + if {arm(k), arm(n)} == {"full", "sparse"}: + f, s = (k, n) if arm(k) == "full" else (n, k) + pairs.append(100 * (st.mean(runs[s]["dec"]) / st.mean(runs[f]["dec"]) - 1)) + if pairs: + print("adjacent (full, sparse) pairs, all-turn mean decode tok/s, sparse over full: %s %% mean %+.2f %%" % (" ".join("%+.2f" % x for x in pairs), st.mean(pairs))) + +print("== G2 memory (from memsample.txt; MemAvailable and Shmem in GiB at the last sample before the engine stopped, engine RssShmem/RssAnon/VmLck in GiB)") +mem = {} +for k in order: + f = os.path.join(root, k, "memsample.txt") + if not os.path.exists(f): + continue + lines = [l for l in open(f, errors="replace") if "ENGINE" in l and "RssShmem" in l] + if not lines: + print(k, "no engine sample") + continue + pick = lambda l, name: next((int(m) for m in re.findall(r"(?= 35): %s" % (fa, sa, sa - fa, "PASS" if sa - fa >= 35 else "FAIL")) + print("G2 swap: %s" % ("PASS (zero pages swapped in every run)" if all((mem[k]["swap"] or 0) == 0 for k in order) else "FAIL or unknown: " + str({k: mem[k]["swap"] for k in order}))) +print("== G4 cap: the engine log line of every run") +for k in order: + log = os.path.join(root, k, "inference.log") + if os.path.exists(log): + got = [l.strip()[:200] for l in open(log, errors="replace") if "prefix cache budget:" in l][:1] + print(k, got or "NO LINE (cap unverified)") +PY +sha256sum "$OUTR"/*/long-session.json "$OI"/*.full 2>/dev/null | head -40 +date -u +%FT%TZ diff --git a/scripts/e2e/run-e2e.sh b/scripts/e2e/run-e2e.sh index eda18dd1..94016b4e 100644 --- a/scripts/e2e/run-e2e.sh +++ b/scripts/e2e/run-e2e.sh @@ -16,11 +16,16 @@ # E2E_SCENARIOS client scenarios, comma separated or all (default all) # E2E_CLIENT_ARGS extra client arguments (e.g. "--soak-n 40 --burst 20") # E2E_ENGINE_ARGS extra leleka-inference arguments (e.g. "--original-prefill-capacity 4096") +# E2E_ASSETS assets directory (default ~/leleka-gates/assets), e.g. ~/work/leleka/models/leleka-gates/assets +# E2E_KAR_FILE path of the KAR archive as an ORDINARY READ-ONLY FILE (regular, one link, no write bits, owned by this user): the engine gets +# --kar-archive-file instead of the holder's descriptor (the `file` KAR source, profile rtx5090-32g-file; nothing is copied to RAM). +# No holder descriptor is needed or used, but MODEL.lock must still be held by the calling job. Add `--verify-stamps DIR` to +# E2E_ENGINE_ARGS (DIR private, mode 0700) to skip the hash of the archive and the shards while their stamps are current. set -uo pipefail HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) W=$HOME/work/leleka-e2e G=$HOME/work/gpu-runs -A=/home/para/work/leleka/models/leleka-gates/assets +A=${E2E_ASSETS:-/home/para/work/leleka/models/leleka-gates/assets} # shards, archive provenance, MTP pack, expert profile; E2E_ASSETS selects another copy of the same assets BIN=${E2E_BIN:-$W/bin-sm120} OUT=${E2E_OUT:-$W/runs/$(date -u +%Y%m%dT%H%M%SZ)} CLIENT=${E2E_CLIENT:-$HERE/e2e_client.py} @@ -30,11 +35,22 @@ mkdir -p "$OUT" log() { echo "[run-e2e $(date -u +%T)] $*"; } # ---- guards ------------------------------------------------------------------------------------------------------- +KARFILE=${E2E_KAR_FILE:-} FD=${LELEKA_STRA169_KAR_FD:-} -if [ -z "$FD" ] || ! readlink "/proc/self/fd/$FD" 2>/dev/null | grep -q '^/memfd:'; then - echo "refusing to start: LELEKA_STRA169_KAR_FD is not a sealed memfd inherited from the holder; run this as a holder job" >&2 +if [ -n "$KARFILE" ]; then + # file source: no descriptor; the file must be the form the engine admits (it checks again: regular, one link, owner, no write bits, pinned length) + FD= + if [ ! -f "$KARFILE" ] || [ "$(stat -c %h "$KARFILE")" != 1 ] || [ "$(( 0$(stat -c %a "$KARFILE") & 0222 ))" != 0 ]; then + echo "refusing to start: E2E_KAR_FILE $KARFILE is not a single-link regular file without write bits (chmod 400)" >&2 + exit 3 + fi +elif [ -z "$FD" ] || ! readlink "/proc/self/fd/$FD" 2>/dev/null | grep -q '^/memfd:'; then + echo "refusing to start: LELEKA_STRA169_KAR_FD is not a sealed memfd inherited from the holder; run this as a holder job (or set E2E_KAR_FILE)" >&2 exit 3 fi +CLOSE_FD=; [ -n "$FD" ] && CLOSE_FD="$FD>&-" +KAR_ARG="--kar-archive-fd $FD"; [ -n "$KARFILE" ] && KAR_ARG="--kar-archive-file \"$KARFILE\"" + [ -d "$G/MODEL.lock" ] || { echo "refusing to start: $G/MODEL.lock is not held" >&2; exit 3; } for b in leleka-inference leleka-daemon leleka-cli strata-next; do [ -x "$BIN/$b" ] || { echo "missing $BIN/$b" >&2; exit 3; }; done if pgrep -u "$USER" -x 'leleka-inference|strata-next|leleka-daemon' >/dev/null; then @@ -147,14 +163,14 @@ eval "\"$BIN/leleka-inference\" --listen 127.0.0.1:18766 --token-env LELEKA_RUNT --shard0 \"$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf\" \ --shard1 \"$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf\" \ --gpu 0 --gpu-budget ${E2E_GPU_BUDGET:-25769803776} --context-tokens 262144 \ - --kar-archive-fd $FD --kar-provenance \"$A/qwen-iq3-s-l2-v4.kar.provenance.json\" \ + $KAR_ARG --kar-provenance \"$A/qwen-iq3-s-l2-v4.kar.provenance.json\" \ --mtp-pack \"$A/data/mtp-rt\" --mtp-staging \"$G/mtp-staging-own\" \ --backend-mode original $RT_ARG ${E2E_ENGINE_ARGS:-} >\"$OUT/inference.log\" 2>&1 &" PID_INF=$! unset CUDA_INJECTION64_PATH sleep 3 alive "$PID_INF" || { log "leleka-inference died at startup"; tail -20 "$OUT/inference.log"; exit 5; } -eval "\"$BIN/leleka-daemon\" --config \"$STATE/daemon.json\" $FD>&- >\"$OUT/daemon.log\" 2>&1 &" +eval "\"$BIN/leleka-daemon\" --config \"$STATE/daemon.json\" $CLOSE_FD >\"$OUT/daemon.log\" 2>&1 &" PID_DAE=$! sleep 2 alive "$PID_DAE" || { log "leleka-daemon died at startup"; tail -20 "$OUT/daemon.log"; exit 5; } @@ -177,7 +193,7 @@ log "model ready after ${LOAD_S}s" echo "load_seconds=$LOAD_S" >"$OUT/load.txt" # ---- API --------------------------------------------------------------------------------------------------------- -eval "\"$BIN/strata-next\" serve --config \"$STATE/strata.json\" $FD>&- >\"$OUT/strata-next.log\" 2>&1 &" +eval "\"$BIN/strata-next\" serve --config \"$STATE/strata.json\" $CLOSE_FD >\"$OUT/strata-next.log\" 2>&1 &" PID_STR=$! if ! "$BIN/strata-next" wait-ready --url http://127.0.0.1:8081 --model qwen-iq3 --key-file "$KEYFILE" --timeout-s 180 >"$OUT/wait-ready.log" 2>&1; then log "strata-next never became ready"; tail -20 "$OUT/wait-ready.log"; tail -30 "$OUT/strata-next.log"; exit 6