perf(startup): verify shards and archive in parallel with read-ahead, verification stamps, attested sealed archive, parallel memfd fill, leleka verify

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-24 01:28:11 +02:00
co-authored by Claude Sonnet 5.5
parent cceb4b4032
commit f96074c360
22 changed files with 1308 additions and 80 deletions
Generated
+1
View File
@@ -1030,6 +1030,7 @@ name = "leleka-deploy"
version = "0.1.0"
dependencies = [
"hex",
"leleka-model-format",
"rustix",
"serde",
"serde_json",
+1
View File
@@ -28,6 +28,7 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.11"
hex = "0.4"
leleka-model-format = { path = "../model-format" }
tokio = { version = "1", features = ["rt", "macros", "process", "io-util", "time", "sync", "net", "signal", "fs"] }
[target.'cfg(target_os = "linux")'.dependencies]
+115
View File
@@ -69,6 +69,7 @@ pub async fn main_with(args: Vec<String>) -> i32 {
Command::Up(opts) => up(opts).await,
Command::Status(opts) => status(opts).await,
Command::Down(opts) => down(opts).await,
Command::Verify(opts) => verify(opts).await,
Command::Run { config, kar_fd } => {
supervisor::run(supervisor::Options { config, kar_fd }).await
}
@@ -394,6 +395,120 @@ async fn status(opts: UpOptions) -> i32 {
i32::from(!ready)
}
/// `leleka verify`: full hashing of both shards and the archive, in parallel, against the pinned digests; renews the
/// stamps (`STATE/stamps/engine`) that let the next start skip the hashing. Nothing is loaded and no GPU is touched.
async fn verify(opts: UpOptions) -> i32 {
use crate::{config::RUNTIME_TOKEN_ENV, facts::parse_env_file, profile::KarSource};
use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps, sha256_of_file};
let paths = opts.dirs.paths();
let config = match crate::config::RunConfig::read(&paths.run_config()) {
Ok(config) => config,
Err(message) => {
eprintln!("leleka: {message}");
return 2;
}
};
let stamp_dir = paths.engine_stamps();
if let Err(error) = std::fs::create_dir_all(&stamp_dir) {
eprintln!("leleka: cannot create {}: {error}", stamp_dir.display());
return 1;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&stamp_dir, std::fs::Permissions::from_mode(0o700));
}
let env = std::fs::read_to_string(paths.env_file())
.map(|text| parse_env_file(&text))
.unwrap_or_default();
let Some(token) = env.get(RUNTIME_TOKEN_ENV).cloned() else {
eprintln!(
"leleka: {} has no {RUNTIME_TOKEN_ENV}; run `leleka up`",
paths.env_file().display()
);
return 2;
};
let started = std::time::Instant::now();
say(
"hashing both shards (and the archive, when it is a file) in full, in parallel; this renews the stamps",
);
let engine = tokio::process::Command::new(paths.bin("leleka-inference"))
.args(config.verify_args())
.env(RUNTIME_TOKEN_ENV, token)
.env_remove("HF_TOKEN")
.stdin(std::process::Stdio::null())
.status();
// A sealed-memfd profile cannot hand the engine the file (it must be read-only and owned); the archive file is
// hashed here instead, against the pinned digest, and stamped for the supervisor (kind `kar-source`).
let archive = tokio::task::spawn_blocking({
let kar = paths.kar();
let memfd = config.profile.kar_source == KarSource::Memfd;
let stamps = VerifyStamps::new(stamp_dir.clone(), true);
move || -> Result<Option<f64>, String> {
if !memfd {
return Ok(None);
}
let begun = std::time::Instant::now();
let file = std::fs::File::open(&kar)
.map_err(|e| format!("cannot open {}: {e}", kar.display()))?;
let before = file.metadata().ok().and_then(|m| FileIdentity::of(&m));
let digest =
sha256_of_file(&file).map_err(|e| format!("cannot read {}: {e}", kar.display()))?;
if digest != crate::profile::archive_sha256() {
return Err(format!(
"{} does not match the pinned archive digest",
kar.display()
));
}
let after = file.metadata().ok().and_then(|m| FileIdentity::of(&m));
if let (Some(before), true) = (before, before == after) {
stamps
.record("kar-source", &crate::profile::archive_sha256(), &before)
.map_err(|e| format!("cannot record the archive stamp: {e}"))?;
}
Ok(Some(begun.elapsed().as_secs_f64()))
}
});
let (engine, archive) = tokio::join!(engine, archive);
let mut code = 0;
match engine {
Ok(status) if status.success() => {}
Ok(status) => {
eprintln!(
"leleka: the engine's verification failed ({status}); a file does not match its pinned digest"
);
code = 1;
}
Err(error) => {
eprintln!(
"leleka: cannot run {}: {error}",
paths.bin("leleka-inference").display()
);
code = 1;
}
}
match archive {
Ok(Ok(Some(seconds))) => say(&format!(
"archive file matches the pinned SHA-256 ({seconds:.1}s); stamped"
)),
Ok(Ok(None)) => {}
Ok(Err(message)) => {
eprintln!("leleka: {message}");
code = 1;
}
Err(error) => {
eprintln!("leleka: archive verification failed to run: {error}");
code = 1;
}
}
say(&format!(
"verification {} in {:.1}s",
if code == 0 { "passed" } else { "FAILED" },
started.elapsed().as_secs_f32()
));
code
}
async fn down(opts: UpOptions) -> i32 {
let paths = opts.dirs.paths();
match installed_scope(&paths) {
+4
View File
@@ -11,6 +11,8 @@ USAGE
leleka run --config FILE the foreground supervisor that systemd starts (engine + gateway + API)
leleka status [OPTIONS] service state and readiness
leleka down [OPTIONS] stop the systemd service
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)
leleka profiles [show NAME] list the memory profiles, or print one as JSON
leleka version
@@ -95,6 +97,7 @@ pub enum Command {
ExecInherit(Vec<String>),
Status(UpOptions),
Down(UpOptions),
Verify(UpOptions),
Profiles(Option<String>),
Version,
Help,
@@ -339,6 +342,7 @@ pub fn parse(args: &[String], env: &Environment) -> Result<Command, String> {
"preflight" => up_options(rest, env).map(Command::Preflight),
"status" => up_options(rest, env).map(Command::Status),
"down" => up_options(rest, env).map(Command::Down),
"verify" => up_options(rest, env).map(Command::Verify),
"profiles" => match rest {
[] => Ok(Command::Profiles(None)),
[show, name] if show == "show" => Ok(Command::Profiles(Some(name.clone()))),
+40
View File
@@ -50,6 +50,14 @@ pub struct RunConfig {
pub load_timeout_s: u64,
pub shutdown_grace_s: u64,
pub restart: RestartPolicy,
/// Do not hash a shard or the archive again when it is unchanged since it last matched its pinned digest
/// (`docs/deploy.md`, "Fast restarts"). `leleka verify` hashes everything and renews the stamps.
#[serde(default = "default_true")]
pub verify_stamps: bool,
}
fn default_true() -> bool {
true
}
/// How the engine receives the archive on its command line.
@@ -87,6 +95,7 @@ impl RunConfig {
max_engine_restarts: 2,
stable_after_s: 600,
},
verify_stamps: true,
}
}
@@ -198,6 +207,37 @@ impl RunConfig {
args.extend(["--prompt-cache".into(), value.to_string()]);
}
args.extend(profile.memory.args());
if self.verify_stamps {
args.extend([
"--verify-stamps".into(),
paths.engine_stamps().display().to_string(),
]);
}
args
}
/// Arguments of `leleka-inference --verify-only --verify-rehash`: both shards hashed in full and the stamps renewed.
/// A file-backed archive is verified by the engine too; a sealed-memfd profile has no archive here (the
/// supervisor-side hash of the archive file is `leleka verify`'s other half).
pub fn verify_args(&self) -> Vec<String> {
let paths = self.paths();
let mut args = self.engine_args(KarArg::File);
// Keep the seven fixed pairs, drop the archive, pack and backend switches the verification does not use.
args.truncate(14);
if self.profile.kar_source == KarSource::File {
args.extend([
"--kar-archive-file".into(),
paths.kar().display().to_string(),
"--kar-provenance".into(),
paths.kar_provenance().display().to_string(),
]);
}
args.extend([
"--verify-only".into(),
"--verify-rehash".into(),
"--verify-stamps".into(),
paths.engine_stamps().display().to_string(),
]);
args
}
+5
View File
@@ -112,6 +112,11 @@ impl Paths {
pub fn stamps(&self) -> PathBuf {
self.dirs.state.join("stamps")
}
/// Verification stamps of the engine (`leleka-inference --verify-stamps`) and of the archive file
/// (`kar-source`, written by the supervisor). Private to the service account.
pub fn engine_stamps(&self) -> PathBuf {
self.stamps().join("engine")
}
pub fn mtp_staging(&self) -> PathBuf {
self.dirs.state.join("mtp-staging")
}
+44 -8
View File
@@ -10,6 +10,17 @@ use std::{collections::BTreeMap, path::Path};
/// Bytes of the pinned level-2 KAR archive (`InheritedKarArchive` admits exactly this length).
pub const ARCHIVE_BYTES: u64 = 55_295_529_472;
/// SHA-256 of the pinned level-2 archive (`qwen4exp_kar_ple.rs` `ARCHIVE_DIGEST`): what the verification stamp of the
/// archive file is keyed by.
pub const ARCHIVE_SHA256_HEX: &str =
"536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5";
/// [`ARCHIVE_SHA256_HEX`] as bytes.
pub fn archive_sha256() -> [u8; 32] {
let mut out = [0u8; 32];
hex::decode_to_slice(ARCHIVE_SHA256_HEX, &mut out).expect("the pinned digest is 64 hex digits");
out
}
/// Bytes of the two pinned IQ3_S GGUF shards.
pub const SHARD_BYTES: [u64; 2] = [54_817_524_224, 28_800_138_432];
@@ -138,13 +149,31 @@ impl MemoryBudget {
env.insert(key.to_owned(), value);
}
};
put("LELEKA_MEMORY_SOFT_FLOOR_MIB", self.soft_floor_mib.map(|v| v.to_string()));
put("LELEKA_MEMORY_HARD_FLOOR_MIB", self.hard_floor_mib.map(|v| v.to_string()));
put("LELEKA_MEMORY_RESERVE_MIB", self.reserve_mib.map(|v| v.to_string()));
put("LELEKA_MEMORY_CACHE_SHARE_PERCENT", self.cache_share_percent.map(|v| v.to_string()));
put(
"LELEKA_MEMORY_SOFT_FLOOR_MIB",
self.soft_floor_mib.map(|v| v.to_string()),
);
put(
"LELEKA_MEMORY_HARD_FLOOR_MIB",
self.hard_floor_mib.map(|v| v.to_string()),
);
put(
"LELEKA_MEMORY_RESERVE_MIB",
self.reserve_mib.map(|v| v.to_string()),
);
put(
"LELEKA_MEMORY_CACHE_SHARE_PERCENT",
self.cache_share_percent.map(|v| v.to_string()),
);
put("LELEKA_MEMORY_LOCK", self.lock.clone());
put("LELEKA_MEMORY_HEAL", self.heal.map(|v| if v { "1" } else { "0" }.to_owned()));
put("LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB", self.resident_budget_gib.map(|v| v.to_string()));
put(
"LELEKA_MEMORY_HEAL",
self.heal.map(|v| if v { "1" } else { "0" }.to_owned()),
);
put(
"LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB",
self.resident_budget_gib.map(|v| v.to_string()),
);
env
}
}
@@ -426,13 +455,20 @@ mod tests {
#[test]
fn the_builtin_profiles_carry_the_memory_budget_into_engine_arguments_and_environment() {
let server = Profile::builtin("rtx5090-32g").unwrap();
assert_eq!(server.memory.args(), vec!["--prefix-cache-mib".to_owned(), "auto".to_owned()]);
assert_eq!(
server.memory.args(),
vec!["--prefix-cache-mib".to_owned(), "auto".to_owned()]
);
let env = server.memory.env();
assert_eq!(env["LELEKA_MEMORY_SOFT_FLOOR_MIB"], "4096");
assert_eq!(env["LELEKA_MEMORY_HARD_FLOOR_MIB"], "2048");
assert_eq!(env["LELEKA_MEMORY_LOCK"], "try");
let laptop = Profile::builtin("rtx3080-16g").unwrap();
assert_eq!(laptop.memory.env()["LELEKA_MEMORY_LOCK"], "off", "the laptop archive is a file, not a memfd");
assert_eq!(
laptop.memory.env()["LELEKA_MEMORY_LOCK"],
"off",
"the laptop archive is a file, not a memfd"
);
for profile in Profile::builtins() {
profile.validate().unwrap();
}
+126 -22
View File
@@ -18,6 +18,21 @@ pub fn seal_file(
Err("sealed memfd archives require Linux".into())
}
#[cfg(not(target_os = "linux"))]
pub fn seal_file_with_identity(
_path: &std::path::Path,
_expect_bytes: Option<u64>,
_progress: &mut dyn FnMut(u64, u64),
) -> Result<
(
std::fs::File,
Option<leleka_model_format::verify_stamp::FileIdentity>,
),
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())
@@ -45,17 +60,21 @@ pub fn substitute(args: &[String], number: i32) -> Vec<String> {
#[cfg(target_os = "linux")]
mod linux {
use super::substitute;
use leleka_model_format::verify_stamp::FileIdentity;
use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, fcntl_get_seals, memfd_create};
use std::{
convert::Infallible,
fs::File,
io::{Read, Write},
os::{
fd::{AsFd, IntoRawFd},
unix::process::CommandExt,
unix::{fs::FileExt, process::CommandExt},
},
path::Path,
process::Command,
sync::{
Mutex,
atomic::{AtomicU64, AtomicUsize, Ordering},
},
};
pub const SEALS: SealFlags = SealFlags::from_bits_truncate(
@@ -64,7 +83,8 @@ mod linux {
| SealFlags::SHRINK.bits()
| SealFlags::SEAL.bits(),
);
const CHUNK: usize = 16 << 20;
/// Bytes per positional read/write of the parallel fill.
const COPY_CHUNK: usize = 32 << 20;
/// Copy `path` into a new sealed, close-on-exec memfd. `expect_bytes` pins the exact length. `progress` gets
/// (copied, total) about every 4 GiB.
@@ -73,7 +93,20 @@ mod linux {
expect_bytes: Option<u64>,
progress: &mut dyn FnMut(u64, u64),
) -> Result<File, String> {
let mut source =
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
/// 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(
path: &Path,
expect_bytes: Option<u64>,
progress: &mut dyn FnMut(u64, u64),
) -> Result<(File, Option<FileIdentity>), String> {
let source =
File::open(path).map_err(|e| format!("cannot open {}: {e}", path.display()))?;
let metadata = source
.metadata()
@@ -89,32 +122,79 @@ mod linux {
metadata.len()
));
}
let identity_before = FileIdentity::of(&metadata);
let fd = memfd_create(
"leleka-sealed-archive",
MemfdFlags::ALLOW_SEALING | MemfdFlags::CLOEXEC,
)
.map_err(|e| format!("memfd_create failed: {e}"))?;
let mut memory = File::from(fd);
let mut buffer = vec![0u8; CHUNK];
let memory = File::from(fd);
let total = metadata.len();
let (mut copied, mut reported) = (0u64, 0u64);
loop {
let count = source
.read(&mut buffer)
.map_err(|e| format!("read failed: {e}"))?;
if count == 0 {
break;
// 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}"))?;
let workers = std::thread::available_parallelism()
.map_or(4, |n| n.get())
.clamp(2, 8);
let next = AtomicU64::new(0);
let copied = AtomicU64::new(0);
let finished = AtomicUsize::new(0);
let failure: Mutex<Option<String>> = Mutex::new(None);
std::thread::scope(|scope| {
for _ in 0..workers {
scope.spawn(|| {
let mut buffer = vec![0u8; COPY_CHUNK];
loop {
if failure.lock().is_ok_and(|f| f.is_some()) {
break;
}
let offset = next.fetch_add(COPY_CHUNK as u64, Ordering::Relaxed);
if offset >= total {
break;
}
let count = (total - offset).min(COPY_CHUNK as u64) as usize;
let step = source
.read_exact_at(&mut buffer[..count], offset)
.map_err(|e| format!("read failed at {offset}: {e}"))
.and_then(|()| {
memory.write_all_at(&buffer[..count], offset).map_err(|e| {
format!("write to memfd failed (out of memory?): {e}")
})
});
match step {
Ok(()) => {
copied.fetch_add(count as u64, Ordering::Relaxed);
}
Err(message) => {
if let Ok(mut f) = failure.lock() {
f.get_or_insert(message);
}
break;
}
}
}
finished.fetch_add(1, Ordering::Release);
});
}
memory
.write_all(&buffer[..count])
.map_err(|e| format!("write to memfd failed (out of memory?): {e}"))?;
copied += count as u64;
if copied - reported >= 4 << 30 {
reported = copied;
progress(copied, total);
let mut reported = 0u64;
while finished.load(Ordering::Acquire) < workers {
std::thread::sleep(std::time::Duration::from_millis(100));
let now = copied.load(Ordering::Relaxed);
if now - reported >= 4 << 30 {
reported = now;
progress(now, total);
}
}
});
if let Some(message) = failure.into_inner().ok().flatten() {
return Err(message);
}
if copied != total {
if copied.load(Ordering::Relaxed) != total {
return Err("the archive changed while it was being copied".into());
}
let identity_after = source.metadata().ok().and_then(|m| FileIdentity::of(&m));
if identity_before != identity_after {
return Err("the archive changed while it was being copied".into());
}
fcntl_add_seals(&memory, SEALS).map_err(|e| format!("sealing failed: {e}"))?;
@@ -125,7 +205,7 @@ mod linux {
return Err("the kernel did not apply every seal".into());
}
progress(total, total);
Ok(memory)
Ok((memory, identity_before))
}
/// A descriptor inherited from the parent (a holder, for example), reopened through `/proc/self/fd/N` as an
@@ -192,6 +272,7 @@ mod linux {
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use std::os::unix::fs::MetadataExt;
#[test]
@@ -227,6 +308,29 @@ mod linux {
std::fs::remove_file(path).unwrap();
}
#[test]
fn parallel_fill_is_byte_exact_across_chunks_and_reports_the_source_identity() {
let path = std::env::temp_dir().join(format!("leleka-fill-{}", std::process::id()));
// Three full chunks and a ragged tail, with a pattern that differs per chunk.
let size = COPY_CHUNK * 3 + 4097;
let payload: Vec<u8> = (0..size)
.map(|n| ((n / 4096) as u8).wrapping_mul(31) ^ (n as u8))
.collect();
std::fs::write(&path, &payload).unwrap();
let (sealed, identity) =
seal_file_with_identity(&path, Some(size as u64), &mut |_, _| {}).unwrap();
let identity = identity.expect("a regular file has an identity");
assert_eq!(identity.size, size as u64);
let mut copy = vec![0u8; size];
sealed.read_exact_at(&mut copy, 0).unwrap();
assert!(
copy == payload,
"the memfd must equal the source byte for byte"
);
assert!(fcntl_get_seals(&sealed).unwrap().contains(SEALS));
std::fs::remove_file(path).unwrap();
}
#[test]
fn exec_inherit_needs_a_command() {
assert!(exec_inherit(&[]).is_err());
+1
View File
@@ -354,6 +354,7 @@ pub fn make_dirs(ctx: &Context) -> Result<(), String> {
paths.logs(),
paths.run_dir(),
paths.stamps(),
paths.engine_stamps(),
paths.mtp_staging(),
];
for dir in private.iter().chain(
+73 -13
View File
@@ -10,9 +10,10 @@ use crate::{
facts::parse_env_file,
http,
layout::{MTP_PROFILE, Paths},
profile::{ARCHIVE_BYTES, KarSource},
profile::{ARCHIVE_BYTES, KarSource, archive_sha256},
sealed,
};
use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps};
use serde::Serialize;
use std::{
collections::BTreeMap,
@@ -255,6 +256,12 @@ struct Supervisor {
status_path: PathBuf,
shutdown: watch::Receiver<bool>,
archive: Option<File>,
/// Identity of the file the sealed archive was copied from (device, inode, size, mtime, ctime), when stable.
source_identity: Option<FileIdentity>,
/// 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,
stamps: VerifyStamps,
api_addr: SocketAddr,
engine_addr: SocketAddr,
daemon_addr: SocketAddr,
@@ -277,7 +284,13 @@ async fn run_inner(options: Options) -> Result<(), Failure> {
let config =
RunConfig::read(&options.config).map_err(|message| Failure { code: 2, message })?;
let paths = config.paths();
for dir in [paths.logs(), paths.run_dir(), paths.mtp_staging()] {
let stamps_dir = paths.engine_stamps();
for dir in [
paths.logs(),
paths.run_dir(),
paths.mtp_staging(),
stamps_dir.clone(),
] {
std::fs::create_dir_all(&dir).map_err(|e| Failure {
code: 2,
message: format!("cannot create {}: {e}", dir.display()),
@@ -286,8 +299,9 @@ async fn run_inner(options: Options) -> Result<(), Failure> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ =
std::fs::set_permissions(paths.mtp_staging(), std::fs::Permissions::from_mode(0o700));
for private in [paths.mtp_staging(), stamps_dir.clone()] {
let _ = std::fs::set_permissions(private, std::fs::Permissions::from_mode(0o700));
}
}
let env_text = std::fs::read_to_string(paths.env_file()).map_err(|e| Failure {
code: 2,
@@ -363,6 +377,9 @@ async fn run_inner(options: Options) -> Result<(), Failure> {
},
shutdown: stop_rx,
archive: None,
source_identity: None,
archive_attested: false,
stamps: VerifyStamps::new(stamps_dir, false),
api_addr,
engine_addr,
daemon_addr,
@@ -520,20 +537,39 @@ impl Supervisor {
kar.display()
));
let started = Instant::now();
// A stamp of the archive file (written after a start whose engine hashed the copy) lets the engine
// skip the hash of the memfd; it applies only if the file is still in the stamped state before
// AND after the copy.
let before = std::fs::File::open(&kar)
.and_then(|f| f.metadata())
.ok()
.and_then(|m| FileIdentity::of(&m));
let stamped = self.config.verify_stamps
&& before
.is_some_and(|id| self.stamps.trusts("kar-source", &archive_sha256(), &id));
let log = &self.log;
let sealed = sealed::seal_file(&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 sealed = sealed::seal_file_with_identity(
&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
));
},
);
match sealed {
Ok(file) => {
Ok((file, identity)) => {
self.log.line(&format!(
"sealed memfd ready in {:.1}s",
started.elapsed().as_secs_f32()
));
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");
}
Some(file)
}
Err(message) => return fail(1, format!("cannot seal the archive: {message}")),
@@ -689,7 +725,10 @@ impl Supervisor {
),
None => (KarArg::File, None),
};
let engine_args = self.config.engine_args(kar_arg);
let mut engine_args = self.config.engine_args(kar_arg);
if self.archive_attested && stdin.is_some() {
engine_args.push("--kar-attested-by-stamp".into());
}
let mut engine = if stdin.is_some() {
let mut args = vec![
"exec-inherit".to_owned(),
@@ -713,6 +752,27 @@ impl Supervisor {
self.pids[0] = None;
return Err(flow);
}
// 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.archive_attested
&& let Some(identity) = self.source_identity
{
match self
.stamps
.record("kar-source", &archive_sha256(), &identity)
{
Ok(()) => self
.log
.line("recorded the verification stamp of the archive file"),
Err(error) => self
.log
.line(&format!("could not record the archive stamp: {error}")),
}
}
self.archive_attested = true;
}
Ok(engine)
}
+21
View File
@@ -287,6 +287,27 @@ fn lifecycle(source: KarSource) {
let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap();
assert_eq!(calls.matches("leleka-inference ").count(), 2, "{calls}");
assert_eq!(calls.matches("load-mtp").count(), 2, "{calls}");
// The first engine hashed the sealed archive; the restarted one is told the same memfd was verified already
// (stamps are on by default), and both get the stamp directory.
let starts: Vec<&str> = calls
.lines()
.filter(|l| l.starts_with("leleka-inference "))
.collect();
assert!(
starts.iter().all(|l| l.contains("--verify-stamps")),
"{calls}"
);
assert!(
!starts[0].contains("--kar-attested-by-stamp"),
"{}",
starts[0]
);
assert_eq!(
starts[1].contains("--kar-attested-by-stamp"),
source == KarSource::Memfd,
"{}",
starts[1]
);
// The sealed descriptor was reused, not copied again (one process held it the whole time).
assert!(!supervisor.try_wait().unwrap().is_some());
+10
View File
@@ -113,6 +113,16 @@ fn the_cublas_pin_matches_the_tool_and_the_documentation() {
}
}
#[test]
fn the_pinned_archive_digest_of_the_stamps_is_the_one_the_engine_pins() {
let engine = read("crates/leleka-runtime/src/model_binding/qwen4exp_kar_ple.rs");
assert!(
engine.contains(leleka_deploy::profile::ARCHIVE_SHA256_HEX),
"the archive digest the supervisor stamps differs from the engine's pin"
);
assert_eq!(leleka_deploy::profile::archive_sha256().len(), 32);
}
#[cfg(unix)]
#[test]
fn install_script_is_valid_sh_and_verifies_before_it_runs() {
+97 -20
View File
@@ -274,25 +274,79 @@ pub fn spawn_backend_experimental_optimized_windowed256_streamed_spill(
}),
})
}
/// What the three source verifications returned. Errors are reduced to text because the verifying threads hand
/// them over; the callers map each to the same fixed refusal as before.
struct VerifiedSources {
shard0: Result<VerifiedGgufFile, String>,
shard1: Result<VerifiedGgufFile, String>,
/// `None` when no inherited archive is configured.
kar: Option<InputResultKar>,
}
type InputResultKar = Result<leleka_model_format::kar::VerifiedKarPleArtifact, InputBindingError>;
/// Verify shard 0, shard 1 and the inherited KAR archive at the same time. They are independent files; the
/// SHA-256 of each is sequential, so the wall time is the slowest one instead of their sum. Each verification
/// is the very function the sequential load used (full hash, strict index, pinned profile), and the results are
/// consumed in the original order, so every refusal is the same as before.
fn verify_sources_parallel(config: &NativeBackendConfig, want_kar: bool) -> VerifiedSources {
use std::time::Instant;
let begun = Instant::now();
let result = std::thread::scope(|scope| {
let shard1 = scope.spawn(|| {
let started = Instant::now();
let result = VerifiedGgufFile::open(&config.shard1, SHARD1).map_err(|e| e.to_string());
crate::load_clock::span("shard1_sha256_and_index", started);
result
});
let kar = config.kar_ple_inherited.as_ref().filter(|_| want_kar).map(|archive| {
scope.spawn(move || {
let started = Instant::now();
let result = crate::model_binding::qwen4exp_kar_ple::load_pinned_inherited_archive(archive);
crate::load_clock::span("kar_inspect_verify", started);
result
})
});
let started = Instant::now();
let shard0 = VerifiedGgufFile::open(&config.shard0, SHARD0).map_err(|e| e.to_string());
crate::load_clock::span("shard0_sha256_and_index", started);
VerifiedSources {
shard0,
shard1: shard1.join().unwrap_or_else(|_| Err("verification thread failed".into())),
kar: kar.map(|handle| handle.join().unwrap_or(Err(InputBindingError::Busy))),
}
});
crate::load_clock::span("sources_verified_in_parallel_wall", begun);
result
}
/// `leleka-inference --verify-only`: the load-time verification of the sources (both shards, the KAR archive)
/// and nothing else: no CUDA, no GPU, no model state. Prints the `leleka-load-time` lines and returns.
/// It uses exactly the functions of `serve_load`, so what it measures is what a start spends.
pub fn verify_sources_only(config: NativeBackendConfig) -> Result<(), BackendError> {
crate::load_clock::begin();
VerifiedGgufFile::open(&config.shard0, SHARD0)
.map_err(|_| invalid("pinned shard 0 verification failed"))?;
crate::load_clock::lap("shard0_sha256_and_index");
VerifiedGgufFile::open(&config.shard1, SHARD1)
.map_err(|_| invalid("pinned shard 1 verification failed"))?;
crate::load_clock::lap("shard1_sha256_and_index");
if let Some(archive) = config.kar_ple_inherited.as_ref() {
crate::model_binding::qwen4exp_kar_ple::load_pinned_inherited_archive(archive)
.map_err(|_| invalid("pinned KAR archive verification failed"))?;
crate::load_clock::lap("kar_inspect_verify");
let sources = verify_sources_parallel(&config, true);
sources.shard0.map_err(|_| invalid("pinned shard 0 verification failed"))?;
sources.shard1.map_err(|_| invalid("pinned shard 1 verification failed"))?;
if let Some(kar) = sources.kar {
kar.map_err(|_| invalid("pinned KAR archive verification failed"))?;
}
crate::load_clock::lap("all_sources_verified");
Ok(())
}
/// `leleka-inference --kar-attested-by-stamp`: the parent copied the sealed archive from a file whose verification
/// stamp matched and was unchanged while it was copied; skip hashing the memfd again. Never implied.
pub fn set_archive_attested() {
leleka_model_format::verify_stamp::set_attested_archive();
}
/// Operator switch of `leleka-inference --verify-stamps DIR [--verify-rehash]`: a file that matched its pinned
/// digest before and is unchanged (device, inode, size, mtime, ctime) is not hashed again. Set once, before Load.
pub fn set_verify_stamps(directory: PathBuf, rehash: bool) -> bool {
leleka_model_format::verify_stamp::set_global(leleka_model_format::verify_stamp::VerifyStamps::new(directory, rehash))
}
/// The path an operator configuration resolves to for `mode` (see `OriginalServeMode`): pure over the
/// configuration and the build's asset probe. `Auto` picks the Original path only when it can start;
/// `Original` returns a precise refusal instead of falling back; `Preview` never starts it. The caller
@@ -1132,11 +1186,22 @@ fn serve_load(
let retained_scratch = optimized.is_some_and(|options| matches!(options.policy, OptimizedOwnerPolicy::RetainedScratch | OptimizedOwnerPolicy::ResidentOwners | OptimizedOwnerPolicy::AdaptiveSlots));
let adaptive_slots = optimized.is_some_and(|options| options.policy == OptimizedOwnerPolicy::AdaptiveSlots);
let resident_owners = optimized.is_some_and(|options| matches!(options.policy, OptimizedOwnerPolicy::ResidentOwners | OptimizedOwnerPolicy::AdaptiveSlots));
let (shard0, expert_capture) = (if resident_owners {
// The Original path (no capture variants) verifies shard 0, shard 1 and the inherited archive at once;
// the capture variants of the optimized modes read shard 0 incrementally and keep the sequential order.
let parallel_sources = !resident_owners && !streamed_spill;
let archive_wanted = matches!(&requested.inference_mode, InferenceMode::ExperimentalMtp { profile_id } if profile_id == KAR_MTP_PROFILE);
let mut prefetched = if parallel_sources {
Some(verify_sources_parallel(&config, archive_wanted))
} else {
None
};
let (shard0, expert_capture) = (if let Some(sources) = prefetched.as_mut() {
std::mem::replace(&mut sources.shard0, Err(String::new())).map(|shard| (shard, None)).map_err(|_| ())
} else if resident_owners {
Qwen4ExpArtifact::open_shard0_with_expert_capture_incremental(
&config.shard0, SHARD0,
config.kar_ple_inherited.as_ref().map(InheritedKarArchive::expert_capture_observation),
).map(|(shard, capture)| (shard, Some(capture)))
).map(|(shard, capture)| (shard, Some(capture))).map_err(|_| ())
} else if streamed_spill {
// Borrow metadata only from the operator's actual owned sealed archive.
// Capture's provisional errors remain deferred to the old bank boundary;
@@ -1144,18 +1209,23 @@ fn serve_load(
Qwen4ExpArtifact::open_shard0_with_expert_capture(
&config.shard0, SHARD0,
config.kar_ple_inherited.as_ref().map(InheritedKarArchive::expert_capture_observation),
).map(|(shard, capture)| (shard, Some(capture)))
).map(|(shard, capture)| (shard, Some(capture))).map_err(|_| ())
} else {
VerifiedGgufFile::open(&config.shard0, SHARD0).map(|shard| (shard, None))
VerifiedGgufFile::open(&config.shard0, SHARD0).map(|shard| (shard, None)).map_err(|_| ())
}).map_err(|_| load_failure(LoadPhase::Shard0, invalid("pinned shard 0 verification failed")))?;
crate::load_clock::lap("shard0_sha256_and_index");
let shard1 = VerifiedGgufFile::open(&config.shard1, SHARD1).map_err(|_| {
crate::load_clock::lap("shard0_result");
let shard1 = (if let Some(sources) = prefetched.as_mut() {
std::mem::replace(&mut sources.shard1, Err(String::new())).map_err(|_| ())
} else {
VerifiedGgufFile::open(&config.shard1, SHARD1).map_err(|_| ())
}).map_err(|_| {
load_failure(
LoadPhase::Shard1,
invalid("pinned shard 1 verification failed"),
)
})?;
crate::load_clock::lap("shard1_sha256_and_index");
crate::load_clock::lap("shard1_result");
let mut prefetched_kar = prefetched.and_then(|sources| sources.kar);
let artifact = Qwen4ExpArtifact::bind(shard0, shard1)
.map_err(|_| load_failure(LoadPhase::Artifact, invalid("pinned model binding failed")))?;
let metadata = artifact.tokenizer();
@@ -1207,9 +1277,16 @@ fn serve_load(
.ok_or_else(|| unsupported("MTP operator source is absent"))?;
if profile_id == KAR_MTP_PROFILE {
if let Some(kar) = config.kar_ple_inherited.as_ref() {
ModelBinding::from_artifact_with_inherited_kar_mtp(
artifact, kar, source, staging,
)
match prefetched_kar.take() {
Some(verified) => verified.and_then(|verified| {
ModelBinding::from_artifact_with_verified_kar_mtp(
artifact, verified, source, staging,
)
}),
None => ModelBinding::from_artifact_with_inherited_kar_mtp(
artifact, kar, source, staging,
),
}
} else {
let (kar, kar_staging) = config
.kar_ple_source
@@ -338,6 +338,22 @@ impl ModelBinding {
crate::load_clock::lap("mtp_pack_verify_and_bind");
Ok(binding)
}
/// As `from_artifact_with_inherited_kar_mtp`, for an archive that was verified earlier (on another thread,
/// at the same time as the shards): the archive is still fully verified, only not here.
pub(crate) fn from_artifact_with_verified_kar_mtp(
artifact: Qwen4ExpArtifact,
kar: leleka_model_format::kar::VerifiedKarPleArtifact,
mtp_source: &std::path::Path,
mtp_root: &std::path::Path,
) -> InputResult<Self> {
let mut binding = Self::from_artifact_with_kar_ple(artifact, kar)?;
crate::load_clock::lap("kar_bind");
let weights = MtpWeights::load_pinned(&binding, mtp_source, mtp_root)?;
weights.validate_binding(&binding)?;
binding.mtp = Some(weights);
crate::load_clock::lap("mtp_pack_verify_and_bind");
Ok(binding)
}
pub(crate) fn expert_used_count(&self) -> u32 {
self.expert_used_count
}
+1 -1
View File
@@ -11,7 +11,7 @@ autotests = false
sha2 = "0.11"
[target.'cfg(target_os = "linux")'.dependencies]
rustix = { version = "=1.1.5", features = ["mm", "param"] }
rustix = { version = "=1.1.5", features = ["mm", "param", "fs"] }
# The workspace forbids unsafe code; this crate denies it instead so that exactly one owner, the read-only
# shared mapping of a verified GGUF tensor (gguf_resident.rs `FileSpan`, the low-RAM expert source), can
+34 -6
View File
@@ -190,18 +190,28 @@ impl VerifiedGgufFile {
return Err("GGUF source must be a regular file".into());
}
let size = metadata.len();
let mut digest = Sha256::new();
stream_file_span(&mut file, 0, size, |chunk| {
digest.update(chunk);
Ok(())
})?;
let actual: [u8; 32] = digest.finalize().into();
let identity = crate::verify_stamp::FileIdentity::of(&metadata);
let stamps = crate::verify_stamp::global();
// A stamp skips the hash only for this very file in this very state, keyed by the pinned digest.
let trusted = matches!((stamps, identity.as_ref()), (Some(s), Some(id)) if s.trusts("gguf", &expected, id));
let actual: [u8; 32] = if trusted {
expected
} else {
sha256_pipelined(&file, size)?
};
if actual != expected {
return Err("GGUF artifact SHA256 mismatch".into());
}
if file.metadata()?.len() != size {
return Err("GGUF source size changed during verification".into());
}
if !trusted
&& let (Some(stamps), Some(before)) = (stamps, identity)
&& crate::verify_stamp::FileIdentity::of(&file.metadata()?) == Some(before)
{
// Only a file that did not change while it was hashed can vouch for itself next time.
let _ = stamps.record("gguf", &expected, &before);
}
let index = read_index_file(&mut file, size, true)?;
if file.metadata()?.len() != size {
return Err("GGUF source size changed during indexing".into());
@@ -407,6 +417,24 @@ fn parse_artifact_digest(value: &str) -> Result<[u8; 32]> {
Ok(digest)
}
/// SHA-256 of the first `size` bytes, hashing while a reader thread keeps the next chunks coming.
fn sha256_pipelined(file: &File, size: u64) -> Result<[u8; 32]> {
crate::readahead::with_read_ahead(file, 0, size, 1, |mut receivers| -> Result<[u8; 32]> {
let receiver = receivers.remove(0);
let mut digest = Sha256::new();
let mut total = 0u64;
for item in receiver {
let chunk = item?;
digest.update(&chunk[..]);
total += chunk.len() as u64;
}
if total != size {
return Err("GGUF source ended early during verification".into());
}
Ok(digest.finalize().into())
})
}
fn stream_file_span(
file: &mut File,
absolute: u64,
+110 -8
View File
@@ -272,13 +272,7 @@ impl KarInspection {
Ok(())
}
fn verify_integrity(&mut self, bytes: u64, pin: &[u8; 32]) -> Result<(), KarError> {
let mut buffer = Vec::new();
buffer
.try_reserve_exact(8 * 1024 * 1024)
.map_err(|_| KarError::Allocation)?;
buffer.resize(8 * 1024 * 1024, 0);
self.file.seek(SeekFrom::Start(0)).map_err(KarError::Io)?;
verify_integrity_stream(&mut self.file, &self.sections, bytes, pin, &mut buffer)
verify_integrity_pipelined(&self.file, &self.sections, bytes, pin)
}
pub fn decode_range(
&mut self,
@@ -835,6 +829,79 @@ fn integrity_sections(sections: &[Section], bytes: u64) -> Result<(), KarError>
Ok(())
}
/// The production form of [`verify_integrity_stream`]: one reader thread keeps chunks coming, SHA-256 of the
/// whole archive runs on the calling thread and the per-section CRC-32 on a second one, so the pass costs the
/// slower of the two instead of the read plus both. Same verdicts, same precedence: a SHA mismatch (or a short
/// archive) is reported before a CRC failure, and a CRC failure never shortcuts the full hash.
fn verify_integrity_pipelined(
file: &File,
sections: &[Section],
bytes: u64,
pin: &[u8; 32],
) -> Result<(), KarError> {
integrity_sections(sections, bytes)?;
let (digest, total, crc) = crate::readahead::with_read_ahead(file, 0, bytes, 2, |mut receivers| {
let crc_rx = receivers.pop().expect("two receivers");
let sha_rx = receivers.pop().expect("two receivers");
std::thread::scope(|scope| {
let crc_thread = scope.spawn(move || -> std::io::Result<(bool, usize)> {
let (mut index, mut total, mut crc, mut failed) = (0usize, 0u64, !0u32, false);
for item in crc_rx {
let chunk = item?;
let end = total + chunk.len() as u64;
while let Some(section) = sections.get(index) {
if section.offset >= end {
break;
}
let section_end = section.offset + section.bytes; // Checked by integrity_sections.
let start = total.max(section.offset);
let stop = end.min(section_end);
crc = crc32_step(crc, &chunk[(start - total) as usize..(stop - total) as usize]);
if stop != section_end {
break;
}
failed |= !crc != section.crc32;
crc = !0u32;
index += 1;
}
total = end;
}
Ok((failed, index))
});
let mut digest = Sha256::new();
let mut total = 0u64;
let mut read_error = None;
for item in sha_rx {
match item {
Ok(chunk) => {
digest.update(&chunk[..]);
total += chunk.len() as u64;
}
Err(error) => {
read_error = Some(error);
break;
}
}
}
let crc = crc_thread.join().expect("the CRC thread does not panic");
match read_error {
Some(error) => Err(KarError::Io(error)),
None => crc.map(|c| (digest, total, c)).map_err(KarError::Io),
}
})
})?;
let (crc_failed, index) = crc;
if total != bytes || digest.finalize().as_slice() != pin {
return Err(KarError::Integrity("KAR full archive SHA-256 mismatch"));
}
if crc_failed || index != sections.len() {
return Err(KarError::Integrity("KAR payload CRC-32 mismatch"));
}
Ok(())
}
/// The reference scan (kept for the tests that pin its verdicts; production uses the pipelined form above).
#[cfg_attr(not(test), allow(dead_code))]
fn verify_integrity_stream(
file: &mut impl Read,
sections: &[Section],
@@ -985,6 +1052,17 @@ struct VerifiedPart {
planes: u64,
stride: u64,
}
#[cfg(unix)]
fn is_unlinked(file: &File) -> bool {
use std::os::unix::fs::MetadataExt;
file.metadata().is_ok_and(|m| m.is_file() && m.nlink() == 0)
}
#[cfg(not(unix))]
fn is_unlinked(_file: &File) -> bool {
false
}
pub struct VerifiedKarPleArtifact {
reader: KarInspection,
profile: KarPleProfile,
@@ -1003,7 +1081,31 @@ impl VerifiedKarPleArtifact {
"KAR archive/provenance identity mismatch",
));
}
reader.verify_integrity(profile.spec.archive_bytes, &profile.spec.archive_sha256)?;
// A stamp for exactly this file in exactly this state (see verify_stamp.rs) stands in for the full
// SHA-256 + CRC pass; a sealed memfd has no stable identity and always takes the full pass.
let identity = reader
.file
.metadata()
.ok()
.and_then(|m| crate::verify_stamp::FileIdentity::of(&m));
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 {
reader.verify_integrity(profile.spec.archive_bytes, &profile.spec.archive_sha256)?;
if let (Some(stamps), Some(before)) = (stamps, identity)
&& reader
.file
.metadata()
.ok()
.and_then(|m| crate::verify_stamp::FileIdentity::of(&m))
== Some(before)
{
let _ = stamps.record("kar", &profile.spec.archive_sha256, &before);
}
}
let mut parts = Vec::new();
let mut books = Vec::new();
parts
+2
View File
@@ -7,6 +7,8 @@
//! Its only direct dependency is the Rust SHA-256 implementation in `sha2`.
pub mod gguf;
pub(crate) mod readahead;
pub mod verify_stamp;
pub mod qwen4exp;
pub mod kar;
+233
View File
@@ -0,0 +1,233 @@
//! Sequential read-ahead for whole-file verification.
//!
//! A verification hashes a file that is tens of gigabytes long. Doing `read` and `update` in one thread alternates
//! I/O and hashing, so the wall time is their sum. Here one reader thread keeps `DEPTH` chunks ahead of the
//! consumers (positional reads, so the shared cursor is untouched), and the consumers hash while the next chunks
//! are read. The same chunk can go to several consumers (SHA-256 and CRC-32 of one archive). Buffers are
//! recycled, so a multi-gigabyte pass allocates about `DEPTH` chunks, not one per chunk.
//!
//! Nothing here decides what a digest means: a short read, a failed read or a file that ends early is an error,
//! as with `read_exact`.
use std::{
fs::File,
io,
ops::Deref,
sync::{
Arc, Mutex,
mpsc::{Receiver, SyncSender, sync_channel},
},
thread,
};
/// Bytes per chunk. Large enough to keep syscalls and channel hops negligible, small enough to stay in cache
/// between the read and the hash.
pub(crate) const CHUNK_BYTES: usize = 8 << 20;
/// Chunks the reader may run ahead of the slowest consumer.
pub(crate) const DEPTH: usize = 6;
type Pool = Arc<Mutex<Vec<Vec<u8>>>>;
/// One chunk of the stream: `offset` is relative to the start of the span.
pub(crate) struct Chunk {
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) offset: u64,
data: Vec<u8>,
pool: Pool,
}
impl Deref for Chunk {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.data
}
}
impl Drop for Chunk {
fn drop(&mut self) {
let buffer = std::mem::take(&mut self.data);
if let Ok(mut pool) = self.pool.lock() {
pool.push(buffer);
}
}
}
#[cfg(unix)]
fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result<usize> {
use std::os::unix::fs::FileExt;
file.read_at(buffer, offset)
}
#[cfg(windows)]
fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result<usize> {
use std::os::windows::fs::FileExt;
file.seek_read(buffer, offset)
}
fn read_exact_at(file: &File, mut buffer: &mut [u8], mut offset: u64) -> io::Result<()> {
while !buffer.is_empty() {
match read_at(file, buffer, offset) {
Ok(0) => return Err(io::ErrorKind::UnexpectedEof.into()),
Ok(count) => {
buffer = &mut buffer[count..];
offset += count as u64;
}
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
Err(error) => return Err(error),
}
}
Ok(())
}
/// Tell the kernel the file is read once, front to back (a larger read-ahead window).
#[cfg(target_os = "linux")]
fn advise_sequential(file: &File) {
let _ = rustix::fs::fadvise(file, 0, None, rustix::fs::Advice::Sequential);
}
#[cfg(not(target_os = "linux"))]
fn advise_sequential(_file: &File) {}
/// 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.
pub(crate) fn with_read_ahead<R>(
file: &File,
start: u64,
bytes: u64,
fanout: usize,
body: impl FnOnce(Vec<Receiver<io::Result<Arc<Chunk>>>>) -> R,
) -> R {
let pool: Pool = Arc::new(Mutex::new(Vec::new()));
let mut senders: Vec<SyncSender<io::Result<Arc<Chunk>>>> = Vec::with_capacity(fanout);
let mut receivers = Vec::with_capacity(fanout);
for _ in 0..fanout {
let (tx, rx) = sync_channel(DEPTH);
senders.push(tx);
receivers.push(rx);
}
advise_sequential(file);
thread::scope(|scope| {
scope.spawn(move || {
let mut offset = 0u64;
while offset < bytes {
let count = (bytes - offset).min(CHUNK_BYTES as u64) as usize;
let mut buffer = pool
.lock()
.ok()
.and_then(|mut p| p.pop())
.unwrap_or_default();
buffer.resize(count, 0);
if let Err(error) = read_exact_at(file, &mut buffer, start + offset) {
for tx in &senders {
let _ = tx.send(Err(io::Error::new(error.kind(), error.to_string())));
}
return;
}
let chunk = Arc::new(Chunk {
offset,
data: buffer,
pool: Arc::clone(&pool),
});
let mut any = false;
for tx in &senders {
any |= tx.send(Ok(Arc::clone(&chunk))).is_ok();
}
if !any {
return;
}
offset += count as u64;
}
});
body(receivers)
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
fn temp_file(name: &str, bytes: &[u8]) -> (std::path::PathBuf, File) {
let path =
std::env::temp_dir().join(format!("leleka-readahead-{}-{name}", std::process::id()));
let mut file = File::create(&path).unwrap();
file.write_all(bytes).unwrap();
drop(file);
(path.clone(), File::open(path).unwrap())
}
fn pattern(len: usize) -> Vec<u8> {
(0..len)
.map(|i| (i.wrapping_mul(31) ^ (i >> 7)) as u8)
.collect()
}
#[test]
fn every_consumer_sees_the_whole_span_in_order() {
let data = pattern(CHUNK_BYTES * 2 + 12345);
let (path, file) = temp_file("span", &data);
let collected: Vec<Vec<u8>> =
with_read_ahead(&file, 100, data.len() as u64 - 100, 2, |receivers| {
thread::scope(|scope| {
let handles: Vec<_> = receivers
.into_iter()
.map(|rx| {
scope.spawn(move || {
let mut out = Vec::new();
let mut expected = 0u64;
for item in rx {
let chunk = item.unwrap();
assert_eq!(chunk.offset, expected);
expected += chunk.len() as u64;
out.extend_from_slice(&chunk);
}
out
})
})
.collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
})
});
for out in collected {
assert_eq!(out, data[100..]);
}
std::fs::remove_file(path).unwrap();
}
#[test]
fn a_file_shorter_than_the_span_is_an_unexpected_eof() {
let data = pattern(1000);
let (path, file) = temp_file("short", &data);
let last = with_read_ahead(&file, 0, 5000, 1, |mut receivers| {
let rx = receivers.remove(0);
let mut last = None;
for item in rx {
last = Some(item.map(|c| c.len()));
}
last
});
let error = last.unwrap().unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof);
std::fs::remove_file(path).unwrap();
}
#[test]
fn dropping_the_receivers_early_stops_the_reader() {
let data = pattern(CHUNK_BYTES * 3);
let (path, file) = temp_file("early", &data);
let value = with_read_ahead(&file, 0, data.len() as u64, 1, |receivers| {
drop(receivers);
7
});
assert_eq!(value, 7);
std::fs::remove_file(path).unwrap();
}
#[test]
fn an_empty_span_yields_no_chunks() {
let (path, file) = temp_file("empty", b"abc");
let count = with_read_ahead(&file, 3, 0, 1, |mut r| r.remove(0).into_iter().count());
assert_eq!(count, 0);
std::fs::remove_file(path).unwrap();
}
}
+297
View File
@@ -0,0 +1,297 @@
//! Verification stamps: "this exact file already matched this pinned digest".
//!
//! A restart that hashes 140 GB again to learn what it learned an hour ago is the largest avoidable cost of a
//! cold start. A stamp records, after a *full* verification, the identity of the verified file:
//! `(device, inode, size, mtime, ctime)` of the opened descriptor, and the digest it matched. A later start
//! that opens the same file and finds the same identity may skip the hash. Fail closed, always:
//!
//! * any difference in any field, a missing, unreadable, malformed or unexpectedly shaped stamp, or a stamp
//! directory that is not private (owned by this user, no group/other write) means "hash it fully";
//! * `ctime` changes on every write, truncate, chmod, chown and rename and cannot be set from user space, so
//! rewriting the file (even restoring its `mtime`) invalidates the stamp;
//! * the stamp is recorded only if the identity before and after the full hash is the same file in the same state;
//! * a stamp never replaces the digest pin: it is keyed by the pinned digest and the kind of file.
//!
//! What a stamp does not defend against: someone who can write both the stamp directory and the model file and
//! forge the identity fields. That actor already owns the service account, which also owns the archive the engine
//! maps; the stamp directory is created 0700 by the same account. See `docs/deploy.md`.
use std::{
fmt::Write as _,
fs::{self, File, Metadata},
io::{self, Write},
path::{Path, PathBuf},
};
const MAGIC: &str = "leleka-verify-stamp v1";
/// What identifies a file's contents for a stamp.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FileIdentity {
pub device: u64,
pub inode: u64,
pub size: u64,
pub mtime_ns: i128,
pub ctime_ns: i128,
}
impl FileIdentity {
/// `None` on platforms without the needed fields: no stamps there.
#[cfg(unix)]
pub fn of(metadata: &Metadata) -> Option<Self> {
use std::os::unix::fs::MetadataExt;
// An unlinked file (a sealed memfd) has no identity worth trusting across starts.
if !metadata.is_file() || metadata.nlink() == 0 {
return None;
}
Some(Self {
device: metadata.dev(),
inode: metadata.ino(),
size: metadata.size(),
mtime_ns: i128::from(metadata.mtime()) * 1_000_000_000 + i128::from(metadata.mtime_nsec()),
ctime_ns: i128::from(metadata.ctime()) * 1_000_000_000 + i128::from(metadata.ctime_nsec()),
})
}
#[cfg(not(unix))]
pub fn of(_metadata: &Metadata) -> Option<Self> {
None
}
}
static GLOBAL: std::sync::OnceLock<VerifyStamps> = std::sync::OnceLock::new();
/// Process-wide stamps, set once by the operator binary (`leleka-inference --verify-stamps DIR`). Without it
/// nothing is ever skipped.
pub fn set_global(stamps: VerifyStamps) -> bool {
GLOBAL.set(stamps).is_ok()
}
pub fn global() -> Option<&'static VerifyStamps> {
GLOBAL.get()
}
static ATTESTED_ARCHIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// `leleka-inference --kar-attested-by-stamp`: the parent process (`leleka run`) copied the sealed archive from a
/// file whose stamp (device, inode, size, mtime, ctime of the source, kind `kar-source`) matched, and checked that
/// the source did not change while it was copied. An unlinked sealed memfd has no identity of its own, so the
/// engine takes the parent's word for the content instead of hashing 55 GB again. Never set by default.
pub fn set_attested_archive() {
ATTESTED_ARCHIVE.store(true, std::sync::atomic::Ordering::Release);
}
pub fn attested_archive() -> bool {
ATTESTED_ARCHIVE.load(std::sync::atomic::Ordering::Acquire)
}
/// SHA-256 of a whole file, read ahead by a second thread while the first hashes.
pub fn sha256_of_file(file: &File) -> io::Result<[u8; 32]> {
use sha2::{Digest, Sha256};
let size = file.metadata()?.len();
let digest = crate::readahead::with_read_ahead(file, 0, size, 1, |mut receivers| -> io::Result<Sha256> {
let receiver = receivers.remove(0);
let mut digest = Sha256::new();
for item in receiver {
digest.update(&item?[..]);
}
Ok(digest)
})?;
Ok(digest.finalize().into())
}
/// A directory of stamps, one small file per (kind, pinned digest).
#[derive(Clone, Debug)]
pub struct VerifyStamps {
dir: PathBuf,
/// Ignore existing stamps (verify fully) but still record the result: `leleka verify`.
rehash: bool,
}
fn hex(bytes: &[u8; 32]) -> String {
let mut out = String::with_capacity(64);
for byte in bytes {
let _ = write!(out, "{byte:02x}");
}
out
}
impl VerifyStamps {
pub fn new(dir: impl Into<PathBuf>, rehash: bool) -> Self {
Self { dir: dir.into(), rehash }
}
fn path(&self, kind: &str, digest: &[u8; 32]) -> PathBuf {
self.dir.join(format!("{kind}-{}.stamp", &hex(digest)[..16]))
}
fn line(kind: &str, digest: &[u8; 32], id: &FileIdentity) -> String {
format!(
"{MAGIC} kind={kind} sha256={} dev={} ino={} size={} mtime_ns={} ctime_ns={}\n",
hex(digest),
id.device,
id.inode,
id.size,
id.mtime_ns,
id.ctime_ns
)
}
/// The stamp directory must be ours and closed to others, or no stamp is believed or written.
#[cfg(unix)]
fn private(&self) -> bool {
use std::os::unix::fs::MetadataExt;
let Ok(dir) = fs::symlink_metadata(&self.dir) else { return false };
if !dir.is_dir() || dir.mode() & 0o022 != 0 {
return false;
}
// The effective user owns /proc/self.
fs::metadata("/proc/self").map(|me| me.uid() == dir.uid()).unwrap_or(false)
}
#[cfg(not(unix))]
fn private(&self) -> bool {
false
}
/// True only if a stamp for exactly this kind, pinned digest and file identity exists.
pub fn trusts(&self, kind: &str, digest: &[u8; 32], id: &FileIdentity) -> bool {
if self.rehash || !self.private() {
return false;
}
let path = self.path(kind, digest);
let Ok(meta) = fs::symlink_metadata(&path) else { return false };
if !meta.is_file() || meta.len() > 1024 {
return false;
}
fs::read_to_string(&path).is_ok_and(|text| text == Self::line(kind, digest, id))
}
/// Record a full verification of the file now described by `id`. Best effort: a failure only costs the
/// next start a full hash.
pub fn record(&self, kind: &str, digest: &[u8; 32], id: &FileIdentity) -> io::Result<()> {
if !self.private() {
return Err(io::Error::new(io::ErrorKind::PermissionDenied, "stamp directory is not private"));
}
let path = self.path(kind, digest);
let mut temp = path.clone().into_os_string();
temp.push(format!(".tmp{}", std::process::id()));
let temp = PathBuf::from(temp);
{
let mut options = fs::OpenOptions::new();
options.create(true).truncate(true).write(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file: File = options.open(&temp)?;
file.write_all(Self::line(kind, digest, id).as_bytes())?;
file.sync_all()?;
}
fs::rename(temp, path)
}
pub fn dir(&self) -> &Path {
&self.dir
}
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use std::os::unix::fs::PermissionsExt;
fn setup(name: &str) -> (PathBuf, PathBuf, VerifyStamps) {
let root = std::env::temp_dir().join(format!("leleka-stamp-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(root.join("stamps")).unwrap();
fs::set_permissions(root.join("stamps"), fs::Permissions::from_mode(0o700)).unwrap();
let file = root.join("shard.gguf");
fs::write(&file, b"contents").unwrap();
let stamps = VerifyStamps::new(root.join("stamps"), false);
(root, file, stamps)
}
fn identity(path: &Path) -> FileIdentity {
FileIdentity::of(&fs::metadata(path).unwrap()).unwrap()
}
#[test]
fn a_recorded_file_is_trusted_until_anything_about_it_changes() {
let (root, file, stamps) = setup("roundtrip");
let digest = [7u8; 32];
let before = identity(&file);
assert!(!stamps.trusts("gguf", &digest, &before), "no stamp yet");
stamps.record("gguf", &digest, &before).unwrap();
assert!(stamps.trusts("gguf", &digest, &before));
// another digest or another kind is another stamp
assert!(!stamps.trusts("gguf", &[8u8; 32], &before));
assert!(!stamps.trusts("kar", &digest, &before));
// a rewrite of the same length changes ctime (and usually mtime)
std::thread::sleep(std::time::Duration::from_millis(20));
fs::write(&file, b"CONTENTS").unwrap();
let after = identity(&file);
assert_ne!(before, after);
assert!(!stamps.trusts("gguf", &digest, &after));
// restoring the old mtime does not restore the old ctime
let handle = fs::OpenOptions::new().write(true).open(&file).unwrap();
handle.set_modified(std::time::UNIX_EPOCH + std::time::Duration::from_nanos(u64::try_from(before.mtime_ns).unwrap())).unwrap();
let restored = identity(&file);
assert_eq!(restored.mtime_ns, before.mtime_ns);
assert!(!stamps.trusts("gguf", &digest, &restored), "ctime must still differ");
fs::remove_dir_all(root).unwrap();
}
#[test]
fn damaged_or_misshapen_stamps_and_open_directories_are_not_believed() {
let (root, file, stamps) = setup("damaged");
let digest = [1u8; 32];
let id = identity(&file);
stamps.record("gguf", &digest, &id).unwrap();
let stamp = stamps.path("gguf", &digest);
let good = fs::read_to_string(&stamp).unwrap();
for bad in [
good.replace("size=8", "size=9"),
good.trim_end().to_owned(),
format!("{good}{good}"),
good.replace("v1", "v2"),
String::new(),
] {
fs::write(&stamp, bad).unwrap();
assert!(!stamps.trusts("gguf", &digest, &id));
}
fs::write(&stamp, &good).unwrap();
assert!(stamps.trusts("gguf", &digest, &id));
// a group/other-writable directory voids every stamp
fs::set_permissions(stamps.dir(), fs::Permissions::from_mode(0o770)).unwrap();
assert!(!stamps.trusts("gguf", &digest, &id));
assert!(stamps.record("gguf", &digest, &id).is_err());
fs::set_permissions(stamps.dir(), fs::Permissions::from_mode(0o700)).unwrap();
// a symlinked stamp is not a regular file
fs::remove_file(&stamp).unwrap();
std::os::unix::fs::symlink(root.join("shard.gguf"), &stamp).unwrap();
assert!(!stamps.trusts("gguf", &digest, &id));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn rehash_ignores_existing_stamps_but_still_records() {
let (root, file, stamps) = setup("rehash");
let digest = [3u8; 32];
let id = identity(&file);
stamps.record("gguf", &digest, &id).unwrap();
let rehash = VerifyStamps::new(stamps.dir(), true);
assert!(!rehash.trusts("gguf", &digest, &id));
rehash.record("gguf", &digest, &id).unwrap();
assert!(stamps.trusts("gguf", &digest, &id));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn a_missing_directory_means_no_stamps() {
let stamps = VerifyStamps::new("/nonexistent/leleka/stamps", false);
let id = FileIdentity { device: 1, inode: 2, size: 3, mtime_ns: 4, ctime_ns: 5 };
assert!(!stamps.trusts("gguf", &[0u8; 32], &id));
assert!(stamps.record("gguf", &[0u8; 32], &id).is_err());
}
}
+31
View File
@@ -609,6 +609,37 @@ fn fused_integrity_scan_preserves_crc_bits_boundaries_and_sha_precedence() {
KarError::Integrity("KAR full archive SHA-256 mismatch")
));
}
// The file-backed (read-ahead) scan agrees with the stream scan on every verdict: a changed payload byte
// is a SHA mismatch even though the section CRC fails too, and a longer or shorter file is refused.
for at in [800usize, 1100] {
let mut changed = bytes.clone();
changed[at] ^= 1;
let changed_fixture = Fixture::new(&changed);
let mut changed_inspection = changed_fixture.inspect();
let error = changed_inspection
.verify_integrity(bytes.len() as u64, &pin)
.unwrap_err();
assert!(matches!(
error,
KarError::Integrity("KAR full archive SHA-256 mismatch")
));
}
let mut short_inspection = Fixture::new(&bytes).inspect();
let error = short_inspection
.verify_integrity(bytes.len() as u64 + 1, &pin)
.unwrap_err();
assert!(
matches!(error, KarError::Io(_) | KarError::Range(_)),
"{error:?}"
);
let mut bad_crc_inspection = bad_fixture.inspect();
let error = bad_crc_inspection
.verify_integrity(bad_crc.len() as u64, &bad_pin)
.unwrap_err();
assert!(matches!(
error,
KarError::Integrity("KAR payload CRC-32 mismatch")
));
// The public verifier still goes through the combined scan before mapping;
// no successful serving capability can be minted from this miniature file.
let error = VerifiedKarPleArtifact::verify(
+46 -2
View File
@@ -2,7 +2,7 @@
use leleka_runtime::backend::{
InheritedKarArchive, NativeBackendConfig, OriginalServeChoice, OriginalServeMode,
OriginalServeOptions, RankedExpertProfileSource, original_serve_choice, spawn_backend,
verify_sources_only,
set_archive_attested, set_verify_stamps, verify_sources_only,
spawn_backend_experimental_native_integer_iq3_windowed256_retained_gr,
spawn_backend_experimental_optimized_windowed256,
spawn_backend_experimental_optimized_windowed256_adaptive_slots,
@@ -55,9 +55,28 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// `--verify-only`: run the load-time source verification (shards, KAR archive) and exit; no CUDA is touched.
let verify_only = args.iter().any(|arg| arg == "--verify-only");
args.retain(|arg| arg != "--verify-only");
// `--verify-stamps DIR [--verify-rehash]`: a file that already matched its pinned digest and is unchanged
// (device, inode, size, mtime, ctime) is not hashed again; `--verify-rehash` hashes everything and renews
// the stamps. Without `--verify-stamps` every start verifies in full.
let verify_rehash = args.iter().any(|arg| arg == "--verify-rehash");
args.retain(|arg| arg != "--verify-rehash");
if args.iter().any(|arg| arg == "--kar-attested-by-stamp") {
// Only `leleka run` passes this, after matching the stamp of the archive file it copied the memfd from.
args.retain(|arg| arg != "--kar-attested-by-stamp");
set_archive_attested();
}
let verify_stamps = take_option(&mut args, "--verify-stamps")?;
if let Some(directory) = verify_stamps {
if directory.is_empty() {
return Err("invalid_verify_stamps".into());
}
set_verify_stamps(PathBuf::from(directory), verify_rehash);
} else if verify_rehash {
return Err("verify_rehash_requires_verify_stamps".into());
}
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-block TOKENS (block and chunk-grid size, a multiple of 256; default the prefill capacity)] [--verify-only (verify shards and archive, print timings, exit)] [--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-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)]"
);
return Ok(());
}
@@ -236,6 +255,19 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
/// 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<String>, name: &str) -> Result<Option<String>, &'static str> {
let Some(position) = args.iter().position(|arg| arg == name) else {
return Ok(None);
};
let value = args.get(position + 1).cloned().ok_or("option_value_required")?;
args.drain(position..position + 2);
if args.iter().any(|arg| arg == name) {
return Err("duplicate_option");
}
Ok(Some(value))
}
/// Closed adapter reuses the existing optimized profile parser. Only an actual
/// standalone new flag selects it; tuple operands remain opaque. The legacy
/// parser marker is internal and never changes the process's observed argv.
@@ -526,6 +558,18 @@ mod queued_owner_operator_tests {
mod inherited_source_tests {
use super::*;
#[test]
fn take_option_removes_one_value_and_refuses_repeats_and_missing_values() {
let mut args: Vec<String> = ["--a", "1", "--verify-stamps", "/s", "--b"].map(String::from).to_vec();
assert_eq!(take_option(&mut args, "--verify-stamps").unwrap().as_deref(), Some("/s"));
assert_eq!(args, ["--a", "1", "--b"].map(String::from));
assert_eq!(take_option(&mut args, "--verify-stamps").unwrap(), None);
let mut repeated: Vec<String> = ["--verify-stamps", "/a", "--verify-stamps", "/b"].map(String::from).to_vec();
assert!(take_option(&mut repeated, "--verify-stamps").is_err());
let mut missing: Vec<String> = ["--verify-stamps"].map(String::from).to_vec();
assert!(take_option(&mut missing, "--verify-stamps").is_err());
}
#[test]
fn read_only_file_form_is_exclusive_with_the_fd_and_the_staged_forms() {
let file = ["--kar-archive-file", "/assets/a.kar", "--kar-provenance", "/assets/a.json"].map(String::from);