The cold start of the 5090 server is dominated by reading two things: the 55 GB KAR archive (copied into the sealed memfd) and the 50 GB of routed-expert tensors of shard 0 (copied into the page-locked bank). A plain read() loop asks the NVMe for one 128 KiB readahead window at a time (queue depth 1-2; the drive's max_sectors_kb is 128): 8-35 MB/s after a reboot, 2003.8 s for the first holder (docs/experiments/baseline-pair-5090.md section 9). * model-format/bulk_read.rs (new, no unsafe): N threads each read blocks of 8 MiB. Direct (default): O_DIRECT through the open file's /proc/self/fd entry (no path lookup) into 4 KiB-aligned bounce buffers, so the page cache is never touched and nothing has to be evicted; Advise: buffered pread with POSIX_FADV_WILLNEED ahead and DONTNEED behind (a bounded window); Plain: large pread + DONTNEED. Direct falls back to Advise where O_DIRECT is refused. Memory is threads x 8 MiB. Switches for A/B in one binary: LELEKA_LOAD_READ=direct|advise|plain, LELEKA_LOAD_THREADS, LELEKA_LOAD_CHUNK_MIB, LELEKA_LOAD_AHEAD_MIB; LELEKA_LOAD_READ=legacy keeps the old sequential loop for the bank. * deploy/sealed.rs: the memfd fill uses it (seal_file_report also returns how the file was read; seal_file_with_identity is unchanged). * gguf.rs read_file_span_into: spans of 64 MiB and more (the expert tensors) use it; smaller spans and every failure mode are as before. * readahead.rs (the SHA-256/CRC passes of a first verification): WILLNEED 512 MiB ahead of the reader thread. * examples/bulk_read_bench.rs + bulk_read_digest.py: offline cold-read measurement with a reproducible digest (SHA-256 over the SHA-256 of consecutive blocks), device-level read/write accounting so a shared disk shows. Measured on rnr5090 (Lexar NM610PRO, DRAM-less, HMB; kernel 7.0.0-38; another agent's jobs share the drive, so every figure carries its "other" volume; page cache of the span evicted first with posix_fadvise(DONTNEED), never drop_caches): * whole KAR file, 51.5 GiB, new default (direct, 32 x 8 MiB): 152.9 s (362 MB/s) and 159.8 s (346 MB/s, with the digest), nothing else on the drive; Cached 62 -> 59 GiB (no cache growth). Target < 5 min met. * old patterns, same day: one thread, 16-32 MiB reads (the holder's pattern) 65, 86, 105, 154 MB/s on 2-8 GiB cold slices (55 GB in 6-14 min); 8 threads x 32 MiB buffered (the old sealed.rs pattern) 240 MB/s while sharing the drive; the recorded cold-after-reboot holder 2003.8 s. * strategy matrix (4 rounds x 7 configs, fresh 2 GiB regions, MB/s per round, median of 4): advise 16x16 MiB 230 574 194 1126 (402); direct 32x8 185 554 1133 113 (369); advise 32x8 277 454 229 510 (365); plain 16x16 385 257 979 207 (321); direct 16x8 180 311 351 174 (245); direct 8x32 149 317 271 138 (210); one thread 65 201 123 86 (105). The drive's speed varies 10x between regions and moments whatever the strategy, so the multi-thread configs are indistinguishable here; every one of them beats one thread. Direct is the default because it leaves the page cache untouched (nothing to evict, the machine's free-memory state is not changed), not because it is faster. * identity: an 8 GiB slice read with the new code has the same block-digest chain as a plain sequential pass in Python (8b8b21b830cf938b1f0cec60a5a8127d2489e33e1f853cd792b18497b2b081a6, both); unit tests compare every strategy with the source for aligned and ragged spans. The engine's own SHA-256/CRC check of the sealed memfd and the replay gate are in the GPU run recorded in docs/unattended.md. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
390 lines
16 KiB
Rust
390 lines
16 KiB
Rust
//! The sealed KAR archive, made by the service itself (no helper process, no Python).
|
|
//!
|
|
//! `leleka run` copies the archive once into an irrevocably sealed `memfd` and keeps it for its whole life, so an
|
|
//! engine restart does not copy 55 GB again. The engine refuses anything but a regular, unlinked file of the
|
|
//! pinned length with `WRITE | GROW | SHRINK | SEAL` seals (`InheritedKarArchive::open`). The descriptor is
|
|
//! `CLOEXEC` in the supervisor and reaches only the engine: the supervisor hands a duplicate to `leleka
|
|
//! exec-inherit` as standard input, and that shim moves it to a descriptor number >= 3 without close-on-exec and
|
|
//! `exec`s the engine, which reopens it through `/proc/self/fd/N`.
|
|
#[cfg(target_os = "linux")]
|
|
pub use linux::*;
|
|
|
|
#[cfg(not(target_os = "linux"))]
|
|
pub fn seal_file(
|
|
_path: &std::path::Path,
|
|
_expect_bytes: Option<u64>,
|
|
_progress: &mut dyn FnMut(u64, u64),
|
|
) -> Result<std::fs::File, String> {
|
|
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 seal_file_report(
|
|
_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>,
|
|
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())
|
|
}
|
|
|
|
#[cfg(not(target_os = "linux"))]
|
|
pub fn open_inherited(_fd: u32) -> Result<std::fs::File, String> {
|
|
Err("inherited descriptors require Linux".into())
|
|
}
|
|
|
|
#[cfg(not(target_os = "linux"))]
|
|
pub fn exec_inherit(_args: &[String]) -> Result<std::convert::Infallible, String> {
|
|
Err("exec-inherit requires Linux".into())
|
|
}
|
|
|
|
pub const PLACEHOLDER: &str = "{FD}";
|
|
|
|
/// Replace every `{FD}` in `args`.
|
|
pub fn substitute(args: &[String], number: i32) -> Vec<String> {
|
|
args.iter()
|
|
.map(|arg| arg.replace(PLACEHOLDER, &number.to_string()))
|
|
.collect()
|
|
}
|
|
|
|
#[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,
|
|
os::{
|
|
fd::{AsFd, IntoRawFd},
|
|
unix::{fs::FileExt, process::CommandExt},
|
|
},
|
|
path::Path,
|
|
process::Command,
|
|
sync::{
|
|
Mutex,
|
|
atomic::{AtomicBool, AtomicU64, Ordering},
|
|
},
|
|
};
|
|
|
|
pub const SEALS: SealFlags = SealFlags::from_bits_truncate(
|
|
SealFlags::WRITE.bits()
|
|
| SealFlags::GROW.bits()
|
|
| SealFlags::SHRINK.bits()
|
|
| SealFlags::SEAL.bits(),
|
|
);
|
|
/// Block size the tests use to cover several blocks and a ragged tail.
|
|
#[cfg(test)]
|
|
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.
|
|
pub fn seal_file(
|
|
path: &Path,
|
|
expect_bytes: Option<u64>,
|
|
progress: &mut dyn FnMut(u64, u64),
|
|
) -> Result<File, String> {
|
|
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> {
|
|
seal_file_report(path, expect_bytes, progress).map(|(file, identity, _)| (file, identity))
|
|
}
|
|
|
|
/// As [`seal_file_with_identity`], also returning how the file was read (strategy, bytes, time) for the log.
|
|
pub fn seal_file_report(
|
|
path: &Path,
|
|
expect_bytes: Option<u64>,
|
|
progress: &mut dyn FnMut(u64, u64),
|
|
) -> Result<(File, Option<FileIdentity>, leleka_model_format::bulk_read::Report), String> {
|
|
let source =
|
|
File::open(path).map_err(|e| format!("cannot open {}: {e}", path.display()))?;
|
|
let metadata = source
|
|
.metadata()
|
|
.map_err(|e| format!("cannot inspect the archive: {e}"))?;
|
|
if !metadata.is_file() {
|
|
return Err("the archive must be a regular file".into());
|
|
}
|
|
if let Some(expected) = expect_bytes
|
|
&& metadata.len() != expected
|
|
{
|
|
return Err(format!(
|
|
"the archive has {} bytes, expected {expected}",
|
|
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 memory = File::from(fd);
|
|
let total = metadata.len();
|
|
let report: Mutex<Option<leleka_model_format::bulk_read::Report>> = 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.
|
|
let plan = leleka_model_format::bulk_read::Plan::from_env();
|
|
let copied = AtomicU64::new(0);
|
|
let finished = AtomicBool::new(false);
|
|
let failure: Mutex<Option<String>> = Mutex::new(None);
|
|
std::thread::scope(|scope| {
|
|
scope.spawn(|| {
|
|
// Set on every exit, a panic included, so that the progress loop below ends.
|
|
struct Finished<'a>(&'a AtomicBool);
|
|
impl Drop for Finished<'_> {
|
|
fn drop(&mut self) {
|
|
self.0.store(true, Ordering::Release);
|
|
}
|
|
}
|
|
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);
|
|
}
|
|
}
|
|
Err(e) => {
|
|
if let Ok(mut f) = failure.lock() {
|
|
f.get_or_insert(format!("read failed: {e}"));
|
|
}
|
|
}
|
|
}
|
|
});
|
|
let mut reported = 0u64;
|
|
while !finished.load(Ordering::Acquire) {
|
|
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.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}"))?;
|
|
if !fcntl_get_seals(&memory)
|
|
.map_err(|e| format!("cannot read seals: {e}"))?
|
|
.contains(SEALS)
|
|
{
|
|
return Err("the kernel did not apply every seal".into());
|
|
}
|
|
progress(total, total);
|
|
let report = report
|
|
.into_inner()
|
|
.ok()
|
|
.flatten()
|
|
.ok_or("the archive copy did not report")?;
|
|
Ok((memory, identity_before, report))
|
|
}
|
|
|
|
/// A descriptor inherited from the parent (a holder, for example), reopened through `/proc/self/fd/N` as an
|
|
/// independent read-only description. The original number stays open and untouched.
|
|
pub fn open_inherited(fd: u32) -> Result<File, String> {
|
|
if !(3..=1_048_576).contains(&fd) {
|
|
return Err("an inherited descriptor must be 3 or higher".into());
|
|
}
|
|
File::open(format!("/proc/self/fd/{fd}"))
|
|
.map_err(|e| format!("descriptor {fd} is not open in this process: {e}"))
|
|
}
|
|
|
|
/// The descriptor the parent passed with `--kar-fd` must be what the engine will accept: a regular, unlinked
|
|
/// file of the pinned length with every seal. Checked here so that the mistake surfaces before an engine start.
|
|
pub fn check_inherited_archive(fd: u32, expect_bytes: u64) -> Result<(), String> {
|
|
use std::os::unix::fs::MetadataExt;
|
|
let file = open_inherited(fd)?;
|
|
let meta = file
|
|
.metadata()
|
|
.map_err(|e| format!("cannot inspect descriptor {fd}: {e}"))?;
|
|
if !meta.is_file() || meta.nlink() != 0 || meta.len() != expect_bytes {
|
|
return Err(format!(
|
|
"descriptor {fd} is not an unlinked regular file of {expect_bytes} bytes (it has {} bytes, {} links)",
|
|
meta.len(),
|
|
meta.nlink()
|
|
));
|
|
}
|
|
if !fcntl_get_seals(&file)
|
|
.map_err(|e| format!("cannot read the seals of descriptor {fd}: {e}"))?
|
|
.contains(SEALS)
|
|
{
|
|
return Err(format!(
|
|
"descriptor {fd} lacks the WRITE, GROW, SHRINK and SEAL seals"
|
|
));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// `leleka exec-inherit -- COMMAND ARG...`: standard input is the sealed archive. Move it to a descriptor
|
|
/// number >= 3 (inheritable), give the command `/dev/null` as standard input, replace `{FD}` and `exec`.
|
|
pub fn exec_inherit(args: &[String]) -> Result<Infallible, String> {
|
|
let command = match args.split_first() {
|
|
Some((separator, rest)) if separator == "--" && !rest.is_empty() => rest,
|
|
_ => return Err(
|
|
"usage: leleka exec-inherit -- COMMAND ARG... ({FD} marks the sealed descriptor)"
|
|
.into(),
|
|
),
|
|
};
|
|
let stdin = std::io::stdin();
|
|
let moved = rustix::io::dup(stdin.as_fd())
|
|
.map_err(|e| format!("cannot duplicate standard input: {e}"))?;
|
|
let devnull = File::open("/dev/null").map_err(|e| format!("cannot open /dev/null: {e}"))?;
|
|
rustix::stdio::dup2_stdin(&devnull)
|
|
.map_err(|e| format!("cannot replace standard input: {e}"))?;
|
|
let number = moved.into_raw_fd();
|
|
if number < 3 {
|
|
return Err("the sealed descriptor landed on a standard stream".into());
|
|
}
|
|
let arguments = substitute(&command[1..], number);
|
|
let error = Command::new(&command[0]).args(arguments).exec();
|
|
Err(format!("cannot execute {:?}: {error}", command[0]))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::io::Write;
|
|
use std::os::unix::fs::MetadataExt;
|
|
|
|
#[test]
|
|
fn seal_is_exact_sealed_unlinked_and_cloexec() {
|
|
let path = std::env::temp_dir().join(format!("leleka-sealed-{}", std::process::id()));
|
|
let payload: Vec<u8> = (0..300_000u32).map(|n| (n % 251) as u8).collect();
|
|
std::fs::write(&path, &payload).unwrap();
|
|
let mut calls = Vec::new();
|
|
let mut sealed = seal_file(&path, Some(payload.len() as u64), &mut |a, b| {
|
|
calls.push((a, b))
|
|
})
|
|
.unwrap();
|
|
let meta = sealed.metadata().unwrap();
|
|
assert!(meta.is_file() && meta.nlink() == 0 && meta.len() == payload.len() as u64);
|
|
assert!(fcntl_get_seals(&sealed).unwrap().contains(SEALS));
|
|
assert!(sealed.write(b"x").is_err() && sealed.set_len(1).is_err());
|
|
assert!(
|
|
rustix::io::fcntl_getfd(&sealed)
|
|
.unwrap()
|
|
.contains(rustix::io::FdFlags::CLOEXEC)
|
|
);
|
|
assert_eq!(
|
|
calls.last(),
|
|
Some(&(payload.len() as u64, payload.len() as u64))
|
|
);
|
|
// A descriptor reopened through /proc keeps the properties the engine checks.
|
|
let number = std::os::fd::AsRawFd::as_raw_fd(&sealed) as u32;
|
|
let reopened = open_inherited(number).unwrap();
|
|
let meta = reopened.metadata().unwrap();
|
|
assert!(meta.nlink() == 0 && meta.len() == payload.len() as u64);
|
|
assert!(seal_file(&path, Some(1), &mut |_, _| {}).is_err());
|
|
assert!(open_inherited(1).is_err());
|
|
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());
|
|
assert!(exec_inherit(&["--".into()]).is_err());
|
|
assert!(exec_inherit(&["cmd".into()]).is_err());
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn placeholder_substitution() {
|
|
let args = vec![
|
|
"--kar-archive-fd".to_owned(),
|
|
"{FD}".to_owned(),
|
|
"x{FD}y".to_owned(),
|
|
];
|
|
assert_eq!(substitute(&args, 7), ["--kar-archive-fd", "7", "x7y"]);
|
|
}
|
|
}
|