From 1be955bb3763636c55501cffb22c1191d4d0c79b Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 23 Nov 2026 12:16:17 +0100 Subject: [PATCH 1/5] leleka-memory: the governor owns its inventory and published report; MemoryServices replaces Governor::global and Inventory::global The process-wide cells (GLOBAL governor, the global inventory, the published-report static) become state of one Governor value. MemoryServices is the one handle a composition root creates per engine: it holds the governor once installed (first install wins), starts its sampler once and answers the status surface. A test builds its own governor, inventory and services (STRA-338 S13/S14 follow-up). --- crates/leleka-memory/src/governor.rs | 18 ++- .../src/governor/governor_config.rs | 7 +- .../leleka-memory/src/governor/operations.rs | 8 +- .../src/governor/operations/setup.rs | 26 ++-- .../src/governor/operations/status_report.rs | 12 +- crates/leleka-memory/src/governor/tests.rs | 2 +- crates/leleka-memory/src/inventory.rs | 8 +- crates/leleka-memory/src/lib.rs | 5 +- crates/leleka-memory/src/services.rs | 111 ++++++++++++++++++ 9 files changed, 152 insertions(+), 45 deletions(-) create mode 100644 crates/leleka-memory/src/services.rs diff --git a/crates/leleka-memory/src/governor.rs b/crates/leleka-memory/src/governor.rs index e8584a3e..4bbf684b 100644 --- a/crates/leleka-memory/src/governor.rs +++ b/crates/leleka-memory/src/governor.rs @@ -3,7 +3,8 @@ //! //! Threads: the engine's owner thread calls [`Governor::admit`], [`Governor::directive`] and the `note_*` methods //! (cheap, lock-light); one sampler thread ([`Governor::spawn_sampler`]) reads the host every `sample_interval`, -//! updates the level and publishes the report; status queries read the published text from [`published_report`]. +//! updates the level and publishes the report; status queries read the published text from +//! [`Governor::published_report`]. use crate::census::Census; use crate::host::{HostFacts, ProcSource}; @@ -20,7 +21,7 @@ use serde::Serialize; use serde_json::json; use std::collections::VecDeque; use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; -use std::sync::{Arc, Mutex, MutexGuard, OnceLock}; +use std::sync::{Arc, Mutex, MutexGuard}; use std::time::{Duration, Instant}; const NONE: u64 = u64::MAX; @@ -142,6 +143,15 @@ impl TrimStats { } } +/// What the governor keeps to tell about itself: the census of live mappings and pinned regions (filled by the +/// loaders and the stack's owners) and the last report [`Governor::publish`] rendered (JSON text, for the status +/// surface). +#[derive(Default)] +struct Reports { + inventory: Inventory, + published: Mutex>, +} + struct Inner { cfg: GovernorConfig, src: Arc, @@ -163,6 +173,7 @@ struct Inner { transitions: Mutex>, counters: Counters, ledger: Ledger, + reports: Reports, vram: Mutex>, /// (predicted available after the fixed footprint, available measured after the stack opened) post_load: Mutex>, @@ -180,9 +191,6 @@ pub struct Governor { pages: Option, } -static GLOBAL: OnceLock = OnceLock::new(); -static PUBLISHED: Mutex> = Mutex::new(None); - /// Stops the sampler thread when dropped. pub struct SamplerGuard { inner: Arc, diff --git a/crates/leleka-memory/src/governor/governor_config.rs b/crates/leleka-memory/src/governor/governor_config.rs index f873d5b2..b769c151 100644 --- a/crates/leleka-memory/src/governor/governor_config.rs +++ b/crates/leleka-memory/src/governor/governor_config.rs @@ -1,7 +1,7 @@ //! Governor configuration: GovernorConfig defaults, the LELEKA_MEMORY_* environment overrides (validated, a typo is an //! error rather than a silent default) and the Policy floors/PSI overrides; also the published report and lock helpers. -use super::{GIB, GovernorConfig, LockMode, MIB, Mutex, MutexGuard, PUBLISHED, Policy}; +use super::{GIB, GovernorConfig, LockMode, MIB, Mutex, MutexGuard, Policy}; /// The `LELEKA_MEMORY_*` overrides over any lookup `Fn(&str) -> Option`. trait EnvLookup { @@ -145,11 +145,6 @@ impl GovernorConfig { } } -/// The last report the sampler published (JSON text), for the status surface. -pub fn published_report() -> Option { - PUBLISHED.lock().unwrap_or_else(|p| p.into_inner()).clone() -} - pub(super) fn lock(m: &Mutex) -> MutexGuard<'_, T> { m.lock().unwrap_or_else(|p| p.into_inner()) } diff --git a/crates/leleka-memory/src/governor/operations.rs b/crates/leleka-memory/src/governor/operations.rs index b8bc37cf..baccd910 100644 --- a/crates/leleka-memory/src/governor/operations.rs +++ b/crates/leleka-memory/src/governor/operations.rs @@ -2,10 +2,10 @@ //! One impl split over files so each stays under the line limit and has one responsibility. use super::{ - Admission, AnyClock, Arc, AtomicBool, AtomicU8, AtomicU64, Census, Clock, Counters, Duration, GIB, GLOBAL, - Governor, GovernorConfig, HostFacts, Inner, Instant, Inventory, Ledger, Level, LockDecision, LockMode, LockOutcome, - LockReport, MIB, MemoryPressure, Monitor, Mutex, NONE, Ordering, PUBLISHED, Plan, Policy, ProcPressure, ProcSource, - Refusal, Refuse, RequestShape, Sample, SamplerGuard, ShedDirective, Transition, TransitionRecord, TrimStats, + Admission, AnyClock, Arc, AtomicBool, AtomicU8, AtomicU64, Census, Clock, Counters, Duration, GIB, Governor, + GovernorConfig, HostFacts, Inner, Instant, Inventory, Ledger, Level, LockDecision, LockMode, LockOutcome, + LockReport, MIB, MemoryPressure, Monitor, Mutex, NONE, Ordering, Plan, Policy, ProcPressure, ProcSource, Refusal, + Refuse, Reports, RequestShape, Sample, SamplerGuard, ShedDirective, Transition, TransitionRecord, TrimStats, VecDeque, WORKING_SET_TRIM_EVERY, gib, json, lock, }; #[cfg(all(target_os = "linux", target_pointer_width = "64"))] diff --git a/crates/leleka-memory/src/governor/operations/setup.rs b/crates/leleka-memory/src/governor/operations/setup.rs index 6e22347c..f43bd877 100644 --- a/crates/leleka-memory/src/governor/operations/setup.rs +++ b/crates/leleka-memory/src/governor/operations/setup.rs @@ -1,23 +1,23 @@ -//! Construction of `Governor` (inventory, ledger, plan, host source), the process-wide instance, the startup budget log +//! Construction of `Governor` (inventory, ledger, plan, host source), the startup budget log //! and the read accessors of its state. //! Apart from `admission`, which holds what runs per request. use super::{ - AnyClock, Arc, AtomicBool, AtomicU8, AtomicU64, Census, Clock, Counters, GLOBAL, Governor, GovernorConfig, - HostFacts, Inner, Inventory, Ledger, Level, MIB, MemoryPressure, Monitor, Mutex, NONE, Ordering, Plan, Policy, - ProcPressure, ProcSource, Refusal, Sample, Transition, TransitionRecord, TrimStats, VecDeque, gib, lock, + AnyClock, Arc, AtomicBool, AtomicU8, AtomicU64, Census, Clock, Counters, Governor, GovernorConfig, HostFacts, + Inner, Inventory, Ledger, Level, MIB, MemoryPressure, Monitor, Mutex, NONE, Ordering, Plan, Policy, ProcPressure, + ProcSource, Refusal, Reports, Sample, Transition, TransitionRecord, TrimStats, VecDeque, gib, lock, }; impl Inner { fn new(cfg: GovernorConfig, src: impl MemoryPressure + 'static, clock: AnyClock) -> Self { - let policy0 = cfg.policy; Self { - monitor: Mutex::new(Monitor::new(policy0)), - policy: Mutex::new(policy0), + monitor: Mutex::new(Monitor::new(cfg.policy)), + policy: Mutex::new(cfg.policy), cfg, src: Arc::new(src), epoch: clock.now(), ledger: Ledger::with_clock(clock.clone()), + reports: Reports::default(), clock, plan: Mutex::new(None), level: AtomicU8::new(Level::Normal as u8), @@ -71,14 +71,6 @@ impl Governor { Self { pages: Some(pages), ..Self::with_parts(cfg, pressure, clock) } } - /// Make this the process-wide governor (the first install wins; later ones are returned unchanged). - pub fn install(self) -> &'static Governor { - GLOBAL.get_or_init(|| self) - } - pub fn global() -> Option<&'static Governor> { - GLOBAL.get() - } - /// Replace the pressure floors at run time (diagnostics and the shed tests: move the thresholds next to the memory /// the host has now, so the whole shed path runs without ever approaching the real limit). `hard < soft` is /// required. @@ -101,8 +93,8 @@ impl Governor { pub fn policy(&self) -> Policy { *lock(&self.inner.policy) } - pub fn inventory(&self) -> &'static Inventory { - Inventory::global() + pub fn inventory(&self) -> &Inventory { + &self.inner.reports.inventory } pub fn ledger(&self) -> &Ledger { &self.inner.ledger diff --git a/crates/leleka-memory/src/governor/operations/status_report.rs b/crates/leleka-memory/src/governor/operations/status_report.rs index 51e445b5..cedbfb16 100644 --- a/crates/leleka-memory/src/governor/operations/status_report.rs +++ b/crates/leleka-memory/src/governor/operations/status_report.rs @@ -2,8 +2,7 @@ //! Apart from `admission`: observation of the state the other files change. use super::{ - Counters, Duration, Governor, HostFacts, Inner, Level, Monitor, NONE, Ordering, PUBLISHED, Policy, SamplerGuard, - json, lock, + Counters, Duration, Governor, HostFacts, Inner, Level, Monitor, NONE, Ordering, Policy, SamplerGuard, json, lock, }; impl Governor { @@ -84,13 +83,18 @@ impl Governor { }) } - /// Render the report into the cell [`published_report`] reads. + /// Render the report into the cell [`Self::published_report`] reads. pub fn publish(&self) { if let Ok(text) = serde_json::to_string(&self.report()) { - *PUBLISHED.lock().unwrap_or_else(|p| p.into_inner()) = Some(text); + *lock(&self.inner.reports.published) = Some(text); } } + /// The last report the sampler published (JSON text), for the status surface. + pub fn published_report(&self) -> Option { + lock(&self.inner.reports.published).clone() + } + // ---- sampler ----------------------------------------------------------------------------------------------- /// Run `round` every `every` on a named thread until the governor is told to stop. A panic in one round (a diff --git a/crates/leleka-memory/src/governor/tests.rs b/crates/leleka-memory/src/governor/tests.rs index b0906615..add2588e 100644 --- a/crates/leleka-memory/src/governor/tests.rs +++ b/crates/leleka-memory/src/governor/tests.rs @@ -136,7 +136,7 @@ fn counters_and_report_json_describe_the_decisions() { assert_eq!(j["transitions"].as_array().unwrap().len(), 1); assert_eq!(j["policy"]["soft_floor"], 4 * GIB); g.publish(); - assert!(published_report().unwrap().contains("\"gate\"")); + assert!(g.published_report().unwrap().contains("\"gate\"")); } #[test] diff --git a/crates/leleka-memory/src/inventory.rs b/crates/leleka-memory/src/inventory.rs index ba256f74..6d44d3b5 100644 --- a/crates/leleka-memory/src/inventory.rs +++ b/crates/leleka-memory/src/inventory.rs @@ -9,7 +9,7 @@ use serde::Serialize; use std::collections::BTreeMap; -use std::sync::{Mutex, MutexGuard, OnceLock}; +use std::sync::{Mutex, MutexGuard}; /// Where the bytes live. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)] @@ -118,7 +118,7 @@ impl Entry { } } -/// The registry. `Inventory::global()` is the process-wide one; tests make their own. +/// The registry. Each governor owns one; a test makes its own. #[derive(Debug, Default)] pub struct Inventory { entries: Mutex>, @@ -128,10 +128,6 @@ impl Inventory { pub fn new() -> Self { Self::default() } - pub fn global() -> &'static Inventory { - static GLOBAL: OnceLock = OnceLock::new(); - GLOBAL.get_or_init(Inventory::new) - } fn lock(&self) -> MutexGuard<'_, BTreeMap> { // A panic while holding the lock cannot leave a half-written entry (each update is one assignment). self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) diff --git a/crates/leleka-memory/src/lib.rs b/crates/leleka-memory/src/lib.rs index 9d48223e..f0f65807 100644 --- a/crates/leleka-memory/src/lib.rs +++ b/crates/leleka-memory/src/lib.rs @@ -4,7 +4,7 @@ //! tests. //! //! Model-free and CUDA-free by design: the runtime feeds it numbers (what it will allocate, what the device reports) -//! and acts on its decisions (evict, refuse, lock). +//! and acts on its decisions (evict, refuse, lock). pub mod census; pub mod governor; @@ -16,6 +16,7 @@ pub mod plan; pub mod pressure; pub mod pressure_port; pub mod procfs; +mod services; mod settings; pub mod smi; pub mod telemetry; @@ -23,7 +24,6 @@ pub mod winproc; pub use governor::{ Admission, Governor, GovernorConfig, LockReport, Refuse, RequestShape, SamplerGuard, ShedDirective, - published_report, }; pub use host::{FakeProc, HostFacts, ProcSource, RealProc}; pub use inventory::{Entry, Inventory, Space, When}; @@ -32,3 +32,4 @@ pub use plan::{ }; pub use pressure::Level; pub use pressure_port::{MemoryPressure, ProcPressure, ScriptedPressure}; +pub use services::MemoryServices; diff --git a/crates/leleka-memory/src/services.rs b/crates/leleka-memory/src/services.rs new file mode 100644 index 00000000..770e41eb --- /dev/null +++ b/crates/leleka-memory/src/services.rs @@ -0,0 +1,111 @@ +//! The memory services of one engine: the governor (with its inventory and the report it publishes) and the sampler +//! threads that drive it. The composition root creates one `MemoryServices` per engine and hands the same handle to +//! every owner that accounts or asks for memory, so nothing reaches the governor through a process-wide cell and a test +//! builds its own. + +use crate::governor::{Governor, SamplerGuard}; +use std::fmt; +use std::sync::{Arc, Mutex}; + +#[derive(Default)] +struct Slot { + governor: Option, + /// Stops the sampler threads when the last handle of the services is dropped. + sampler: Option, +} + +/// The governor of one engine, empty until the engine's start installs it. Cheap to clone: every clone is the same +/// services. +#[derive(Clone, Default)] +pub struct MemoryServices { + slot: Arc>, +} + +impl MemoryServices { + /// Services with no governor yet: every owner that asks sees "no governor", as a process that never installed one. + pub fn new() -> Self { + Self::default() + } + + /// Services that already hold `governor`, without a sampler thread: a test's own governor. + pub fn with_governor(governor: Governor) -> Self { + let services = Self::new(); + services.slot().governor = Some(governor); + services + } + + fn slot(&self) -> std::sync::MutexGuard<'_, Slot> { + self.slot.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + /// The governor, once installed (a handle to the one governor of these services). + pub fn governor(&self) -> Option { + self.slot().governor.clone() + } + + /// Make `governor` the governor of these services (the first install wins; later ones are returned unchanged) and + /// start the sampler of the installed one, once. Returns the installed governor. + pub fn install(&self, governor: Governor) -> Governor { + let mut slot = self.slot(); + let installed = slot.governor.get_or_insert(governor).clone(); + if slot.sampler.is_none() { + slot.sampler = Some(installed.spawn_sampler()); + } + installed + } + + /// The last report the sampler published (JSON text), for the status surface; `None` before a governor exists. + pub fn published_report(&self) -> Option { + self.governor()?.published_report() + } +} + +impl fmt::Debug for MemoryServices { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MemoryServices").field("governor_installed", &self.slot().governor.is_some()).finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::governor::GovernorConfig; + use crate::host::FakeProc; + use crate::inventory::{Entry, Space, When}; + use crate::plan::Policy; + + fn governor() -> Governor { + Governor::new(GovernorConfig::new(Policy::for_host(16 << 30, false)), Arc::new(FakeProc::default())) + } + + fn rows(governor: &Governor) -> usize { + governor.inventory().to_json()["entries"].as_array().unwrap().len() + } + + fn one_class() -> Entry { + Entry::new("kv", "host", Space::HostPinned, When::Startup, "formula").bytes(7) + } + + #[test] + fn services_start_empty_and_the_first_install_wins() { + let services = MemoryServices::new(); + assert!(services.governor().is_none()); + assert!(services.published_report().is_none()); + let first = services.install(governor()); + first.inventory().set(one_class()); + let second = services.install(governor()); + assert_eq!(rows(&second), 1, "the second install returns the first governor"); + assert_eq!(rows(&services.governor().expect("installed")), 1); + } + + #[test] + fn two_services_hold_two_governors_with_their_own_inventory_and_report() { + let (a, b) = (MemoryServices::with_governor(governor()), MemoryServices::with_governor(governor())); + let (ga, gb) = (a.governor().unwrap(), b.governor().unwrap()); + ga.inventory().set(one_class()); + assert_eq!((rows(&ga), rows(&gb)), (1, 0)); + ga.publish(); + assert!(a.published_report().is_some()); + assert!(b.published_report().is_none()); + } +} From 7088fd772f346dcd749522cb2a20ebff36517deb Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 23 Nov 2026 12:16:22 +0100 Subject: [PATCH 2/5] model-format: VerifyPolicy (stamp directory and archive attestation) replaces the process-wide stamp registry verify_stamp::set_global/global and set_attested_archive/attested_archive are gone. The operator binary builds a VerifyPolicy from its flags and the loaders receive it: VerifiedGgufFile::open_with and VerifiedKarPleArtifact::verify_under take it; open, verify and verify_sparse keep their signatures and hash in full (the default policy vouches for nothing), which is what a process that never set the globals did (STRA-338 S13). --- crates/model-format/src/gguf/tests.rs | 1 + .../stamp_policy_stands_in_for_the_hash.rs | 47 +++++++++++++++ .../src/gguf/verified_gguf_file.rs | 19 +++++-- .../src/kar/verified_kar_ple_artifact.rs | 20 +++++-- .../kar/verified_kar_ple_artifact/verify.rs | 19 ++++--- crates/model-format/src/verify_stamp.rs | 57 ++++++++++++------- 6 files changed, 125 insertions(+), 38 deletions(-) create mode 100644 crates/model-format/src/gguf/tests/stamp_policy_stands_in_for_the_hash.rs diff --git a/crates/model-format/src/gguf/tests.rs b/crates/model-format/src/gguf/tests.rs index a3dd3c11..769fc785 100644 --- a/crates/model-format/src/gguf/tests.rs +++ b/crates/model-format/src/gguf/tests.rs @@ -82,3 +82,4 @@ mod admits_flash_metadata_and_rejects; mod buffered_cursor_preserves_offsets_parsin; mod empty_owned_tensor_validation_preserves; mod original_first_source_fence_retains; +mod stamp_policy_stands_in_for_the_hash; diff --git a/crates/model-format/src/gguf/tests/stamp_policy_stands_in_for_the_hash.rs b/crates/model-format/src/gguf/tests/stamp_policy_stands_in_for_the_hash.rs new file mode 100644 index 00000000..156c7978 --- /dev/null +++ b/crates/model-format/src/gguf/tests/stamp_policy_stands_in_for_the_hash.rs @@ -0,0 +1,47 @@ +//! The verification stamps are an injected `VerifyPolicy`, not a process-wide registry: the same open hashes the file +//! under the default policy and trusts a stamp of the policy it is given. +#![cfg(unix)] + +use super::{OwnedFixture, VerifiedGgufFile}; +use crate::verify_stamp::{FileIdentity, VerifyPolicy, VerifyStamps}; +use sha2::Digest; +use std::os::unix::fs::PermissionsExt; + +/// A stamp for `digest` on the fixture file as it stands now, in a private directory of its own. +fn stamped(fixture: &OwnedFixture, digest: &[u8; 32]) -> VerifyPolicy { + let dir = fixture.directory.join("stamps"); + std::fs::create_dir(&dir).unwrap(); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap(); + let stamps = VerifyStamps::new(&dir, false); + let identity = FileIdentity::of(&std::fs::metadata(&fixture.path).unwrap()).unwrap(); + stamps.record("gguf", digest, &identity).unwrap(); + VerifyPolicy::new(Some(stamps), false) +} + +#[test] +fn a_stamp_of_the_policy_stands_in_for_the_hash_and_the_default_policy_hashes() { + let fixture = OwnedFixture::new(); + // not the digest of the file: only a stamp can make this open succeed + let digest = [0xab; 32]; + let pinned = format!("sha256:{}", "ab".repeat(32)); + let policy = stamped(&fixture, &digest); + assert!(VerifiedGgufFile::open_with(&fixture.path, &pinned, &policy).is_ok(), "the stamp is trusted"); + for hashed in [VerifiedGgufFile::open(&fixture.path, &pinned), { + VerifiedGgufFile::open_with(&fixture.path, &pinned, &VerifyPolicy::default()) + }] { + assert!(hashed.unwrap_err().to_string().contains("SHA256 mismatch"), "no policy: the file is hashed"); + } +} + +#[test] +fn a_full_hash_records_a_stamp_in_the_policy_it_was_given() { + let fixture = OwnedFixture::new(); + let dir = fixture.directory.join("stamps"); + std::fs::create_dir(&dir).unwrap(); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap(); + let policy = VerifyPolicy::new(Some(VerifyStamps::new(&dir, false)), false); + VerifiedGgufFile::open_with(&fixture.path, &fixture.digest(), &policy).unwrap(); + let identity = FileIdentity::of(&std::fs::metadata(&fixture.path).unwrap()).unwrap(); + let digest: [u8; 32] = sha2::Sha256::digest(&fixture.bytes).into(); + assert!(policy.stamps().unwrap().trusts("gguf", &digest, &identity)); +} diff --git a/crates/model-format/src/gguf/verified_gguf_file.rs b/crates/model-format/src/gguf/verified_gguf_file.rs index aff38499..ca5c546b 100644 --- a/crates/model-format/src/gguf/verified_gguf_file.rs +++ b/crates/model-format/src/gguf/verified_gguf_file.rs @@ -6,18 +6,25 @@ use super::{ VerifiedGgufFile, ensure_size, open_regular_file, parse_artifact_digest, read_file_span_into, read_index_file, read_metadata_snapshot, read_split_metadata_snapshot, sha256_pipelined, stream_file_span, }; +use crate::verify_stamp::VerifyPolicy; /// `VerifiedGgufFile` as a `WeightSource` (private fields: the impl must live below `gguf`). mod port; impl VerifiedGgufFile { - /// Verify `sha256:<64 hex digits>` and strictly index the same opened file. + /// Verify `sha256:<64 hex digits>` and strictly index the same opened file; the whole file is hashed. /// The opened file's contents must remain stable until this handle is dropped. pub fn open(path: &Path, expected_digest: &str) -> Result { + Self::open_with(path, expected_digest, &VerifyPolicy::default()) + } + + /// [`Self::open`], except that a verification stamp of `policy` for this very file in this very state stands in + /// for the hash (and a full hash records one). + pub fn open_with(path: &Path, expected_digest: &str, policy: &VerifyPolicy) -> Result { let expected = parse_artifact_digest(expected_digest)?; let (mut file, metadata) = open_regular_file(path)?; let size = metadata.len(); - let actual = verify_digest(&file, &metadata, &expected)?; + let actual = verify_digest(&file, &metadata, (&expected, policy))?; let index = read_index_file(&mut file, size, true)?; ensure_size(&file, size, "GGUF source size changed during indexing")?; Ok(Self { file, index, artifact_sha256: actual, resident_source_id: None }) @@ -161,10 +168,14 @@ impl VerifiedGgufFile { } /// Hash the whole file against `expected`, or trust a verification stamp for this very file in this very state. -fn verify_digest(file: &File, metadata: &std::fs::Metadata, expected: &[u8; 32]) -> Result<[u8; 32]> { +fn verify_digest( + file: &File, + metadata: &std::fs::Metadata, + (expected, policy): (&[u8; 32], &VerifyPolicy), +) -> Result<[u8; 32]> { let size = metadata.len(); let identity = crate::verify_stamp::FileIdentity::of(metadata); - let stamps = crate::verify_stamp::global(); + let stamps = policy.stamps(); // 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)? }; diff --git a/crates/model-format/src/kar/verified_kar_ple_artifact.rs b/crates/model-format/src/kar/verified_kar_ple_artifact.rs index faf4b0ff..3aef2d6c 100644 --- a/crates/model-format/src/kar/verified_kar_ple_artifact.rs +++ b/crates/model-format/src/kar/verified_kar_ple_artifact.rs @@ -10,11 +10,21 @@ use super::{ }; mod verify; +use crate::verify_stamp::VerifyPolicy; use verify::verify_archive; impl VerifiedKarPleArtifact { pub fn verify(source: KarImmutableSource, profile: KarPleProfile) -> Result { - Self::verify_with(source, profile, None) + Self::verify_with(source, profile, (None, &VerifyPolicy::default())) + } + /// [`Self::verify`], except that a stamp of `policy` for this very file in this very state, or the parent's + /// attestation of an unlinked sealed memfd, stands in for the whole-archive SHA-256 and payload CRC pass. + pub fn verify_under( + source: KarImmutableSource, + profile: KarPleProfile, + policy: &VerifyPolicy, + ) -> Result { + Self::verify_with(source, profile, (None, policy)) } /// `verify` for a sealed memfd that holds only the bytes the serve path reads (holes elsewhere, same file offsets /// and @@ -27,15 +37,17 @@ impl VerifiedKarPleArtifact { profile: KarPleProfile, extents_sha256: &[u8; 32], ) -> Result { - Self::verify_with(source, profile, Some(extents_sha256)) + Self::verify_with(source, profile, (Some(extents_sha256), &VerifyPolicy::default())) } + /// `how`: the pinned digest of a sparse copy's extents (`None`: a whole archive) and what vouches for the file. pub(super) fn verify_with( source: KarImmutableSource, profile: KarPleProfile, - sparse_pin: Option<&[u8; 32]>, + how: (Option<&[u8; 32]>, &VerifyPolicy), ) -> Result { + let (sparse_pin, policy) = how; let mut reader = source.inspection; - let checked = verify_archive(&mut reader, &profile, sparse_pin)?; + let checked = verify_archive(&mut reader, &profile, (sparse_pin, policy))?; Ok(Self { reader, profile, diff --git a/crates/model-format/src/kar/verified_kar_ple_artifact/verify.rs b/crates/model-format/src/kar/verified_kar_ple_artifact/verify.rs index cbbd7012..0394dc45 100644 --- a/crates/model-format/src/kar/verified_kar_ple_artifact/verify.rs +++ b/crates/model-format/src/kar/verified_kar_ple_artifact/verify.rs @@ -7,6 +7,7 @@ use super::{ }; type FileIdentity = crate::verify_stamp::FileIdentity; +type VerifyPolicy = crate::verify_stamp::VerifyPolicy; /// What a successful verification leaves behind. pub(super) struct Checked { @@ -18,9 +19,9 @@ pub(super) struct Checked { } /// How the archive is vouched for: a stamp for this very file, or the parent's attestation of a memfd. -struct Admission { +struct Admission<'p> { identity: Option, - stamps: Option<&'static crate::verify_stamp::VerifyStamps>, + stamps: Option<&'p crate::verify_stamp::VerifyStamps>, attested_memfd: bool, stamped: bool, } @@ -29,14 +30,14 @@ fn current_identity(reader: &KarInspection) -> Option { reader.file.metadata().ok().and_then(|m| FileIdentity::of(&m)) } -impl Admission { - fn decide(reader: &KarInspection, profile: &KarPleProfile) -> Self { +impl<'p> Admission<'p> { + fn decide(reader: &KarInspection, profile: &KarPleProfile, policy: &'p VerifyPolicy) -> Self { // 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 = current_identity(reader); - 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 stamps = policy.stamps(); + // An unlinked sealed memfd: only if the parent attested the copy (see `VerifyPolicy::new`). + let attested_memfd = identity.is_none() && policy.archive_attested() && is_unlinked(&reader.file); let stamped = match (stamps, identity.as_ref()) { (Some(s), Some(id)) => s.trusts("kar", &profile.spec.archive_sha256, id), _ => false, @@ -89,10 +90,10 @@ impl Admission { pub(super) fn verify_archive( reader: &mut KarInspection, profile: &KarPleProfile, - sparse_pin: Option<&[u8; 32]>, + (sparse_pin, policy): (Option<&[u8; 32]>, &VerifyPolicy), ) -> Result { check_archive_identity(reader, profile)?; - let admission = Admission::decide(reader, profile); + let admission = Admission::decide(reader, profile, policy); admission.full_pass(reader, profile, sparse_pin.is_some())?; let (parts, books, book_at_list) = verified_parts(reader, profile)?; let serve_extents = normalize_extents( diff --git a/crates/model-format/src/verify_stamp.rs b/crates/model-format/src/verify_stamp.rs index d6ed5b91..eaf0b626 100644 --- a/crates/model-format/src/verify_stamp.rs +++ b/crates/model-format/src/verify_stamp.rs @@ -14,7 +14,7 @@ //! //! 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. +//! maps; the stamp directory is created 0700 by the same account. use std::{ fmt::Write as _, fs::{self, File, Metadata}, @@ -58,30 +58,33 @@ impl FileIdentity { } } -static GLOBAL: std::sync::OnceLock = 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() +/// How a start vouches for the files it verifies: the stamp directory (`leleka-inference --verify-stamps DIR`) and the +/// parent's attestation of the sealed archive (`--kar-attested-by-stamp`). The operator binary builds it from its +/// flags once and hands it to the loaders with the sources; `Default` vouches for nothing, so every file is hashed in +/// full. +#[derive(Clone, Debug, Default)] +pub struct VerifyPolicy { + stamps: Option, + archive_attested: bool, } -pub fn global() -> Option<&'static VerifyStamps> { - GLOBAL.get() -} +impl VerifyPolicy { + /// `archive_attested`: 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 new(stamps: Option, archive_attested: bool) -> Self { + Self { stamps, archive_attested } + } -static ATTESTED_ARCHIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + /// The stamps that may stand in for a full hash; `None`: nothing is ever skipped. + pub fn stamps(&self) -> Option<&VerifyStamps> { + self.stamps.as_ref() + } -/// `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) + pub fn archive_attested(&self) -> bool { + self.archive_attested + } } /// SHA-256 of a whole file, read ahead by a second thread while the first hashes. @@ -291,6 +294,18 @@ mod tests { fs::remove_dir_all(root).unwrap(); } + #[test] + fn the_default_policy_vouches_for_nothing() { + let policy = VerifyPolicy::default(); + assert!(policy.stamps().is_none()); + assert!(!policy.archive_attested()); + let (root, _file, stamps) = setup("policy"); + let policy = VerifyPolicy::new(Some(stamps), true); + assert_eq!(policy.stamps().map(VerifyStamps::dir), Some(root.join("stamps").as_path())); + assert!(policy.archive_attested()); + fs::remove_dir_all(root).unwrap(); + } + #[test] fn a_missing_directory_means_no_stamps() { let stamps = VerifyStamps::new("/nonexistent/leleka/stamps", false); From 82c306b49e76c47ecc1ca8eb6aa07054901b362f Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 23 Nov 2026 12:16:30 +0100 Subject: [PATCH 3/5] engine: one MemoryServices and one VerifyPolicy per engine, injected from the composition root; no process-global governor, inventory or stamp registry spawn_backend_configured creates the MemoryServices (the first Load installs the governor into it, at the same moment as before) and hands it to the owner thread (LoadEnv), the Original runner (Run, ReopenEnv, GenerateEnv), the stack (StackConfig.memory) and the status proxy. The prefix cache, the conversation device, the expert tier, the inventory classes and the page-cache release ask it instead of Governor::global. NativeBackendConfig.verification carries the stamp policy of leleka-inference (--verify-stamps, --verify-rehash, --kar-attested-by-stamp) to the shard and archive verification. The nine Governor::global exceptions of architecture.json and the three singleton exceptions of leleka-memory and leleka-model-format are deleted; the smokes and probes make their own services. --- architecture.json | 12 --- crates/engine-qwen35-cuda/src/backend.rs | 1 + .../src/backend/clock_tests.rs | 1 + .../combined_changed_boundary_proof/rig.rs | 1 + .../engine-qwen35-cuda/src/backend/config.rs | 3 + crates/engine-qwen35-cuda/src/backend/load.rs | 2 + .../src/backend/load_admit.rs | 7 +- .../src/backend/load_bind.rs | 7 +- .../src/backend/load_cuda.rs | 3 +- .../src/backend/load_sources.rs | 21 +++-- .../adaptive_slots.rs | 1 + .../native_down_candidate_only/pair_owner.rs | 1 + .../native_down_public_pair/pair_run.rs | 1 + .../src/backend/original_serve/runner.rs | 2 + .../original_serve/runner/command_loop.rs | 1 + .../original_serve/runner/owner_run.rs | 8 +- .../original_serve/runner/owner_run_steps.rs | 28 ++++--- .../runner/reconfigure_command.rs | 10 ++- .../original_serve/runner/stack_reports.rs | 13 ++- .../src/backend/original_serve_laptop.rs | 1 + .../backend/original_serve_memory_smoke.rs | 12 +-- .../original_serve_memory_smoke/inventory.rs | 4 +- .../original_serve_memory_smoke/leak.rs | 2 +- .../original_serve_memory_smoke/load.rs | 69 ++++++++------- .../original_serve_memory_smoke/probe.rs | 15 ++-- .../original_serve_memory_smoke/reader.rs | 4 +- .../original_serve_memory_smoke/shed.rs | 22 ++--- .../original_serve_memory_smoke/soak.rs | 2 +- .../backend/original_serve_prefix_smoke.rs | 2 +- .../original_serve_prefix_smoke/run.rs | 1 + .../src/backend/original_serve_replay/load.rs | 1 + .../original_serve_smoke/smoke_stack.rs | 1 + .../src/backend/original_serve_ttft.rs | 1 + .../engine-qwen35-cuda/src/backend/owner.rs | 3 + .../engine-qwen35-cuda/src/backend/proxy.rs | 4 +- .../engine-qwen35-cuda/src/backend/sources.rs | 25 ++---- .../engine-qwen35-cuda/src/backend/spawn.rs | 13 ++- .../engine-qwen35-cuda/src/backend/tests.rs | 2 + .../src/conversation/memory.rs | 6 +- .../src/conversation/original.rs | 4 +- .../engine-qwen35-cuda/src/memory_governor.rs | 84 ++++++++++--------- .../src/memory_governor/page_cache.rs | 9 +- .../load_pinned_inherited_archive.rs | 25 ++++-- .../kar_ple_source/pinned_profile.rs | 20 +++-- .../weight_binding/model_binding.rs | 22 ++--- .../executor/reset_replay_proof.rs | 4 +- .../src/qwen_forward/mtp_decode/batch_gpu.rs | 1 + .../src/qwen_forward/oracle_capture.rs | 8 +- .../original_serve_residency/open_tier.rs | 16 ++-- .../src/qwen_forward/original_serve_stack.rs | 7 +- .../original_serve_stack/conversation.rs | 6 +- .../original_serve_stack_device_ports.rs | 3 + .../original_serve_stack/prefix.rs | 6 +- .../prefix/prefix_config.rs | 9 +- .../prefix_serve_after_phase_parking.rs | 8 +- .../prefix/prefix_serve/store_control.rs | 8 ++ .../original_serve_stack/prompt_chunk.rs | 3 + .../original_serve_stack/stack_config.rs | 1 + .../stack_phases/open_cache_steps.rs | 67 ++++++++++----- .../stack_phases/open_phase_steps.rs | 7 +- .../original_serve_stack_memory_classes.rs | 47 +++++------ .../stack_phases/original_serve_stack_open.rs | 4 +- .../original_serve_stack_open/open_phases.rs | 30 ++++--- .../src/bin/leleka-inference-evaluation.rs | 1 + desktop-core/src/bin/leleka-inference/main.rs | 8 +- .../src/bin/leleka-inference/startup.rs | 51 ++++++----- 66 files changed, 463 insertions(+), 309 deletions(-) diff --git a/architecture.json b/architecture.json index e790e13a..04c45b08 100644 --- a/architecture.json +++ b/architecture.json @@ -72,8 +72,6 @@ {"crate": "leleka-native-parity-bench", "file": "src/lib.rs", "ratchet": "env-read", "reason": "benchmark host (L4): reads the operator's STRATA_IQ_MT_MIN override to report which value it measured"}, {"crate": "leleka-npu-worker", "file": "src/main.rs", "ratchet": "env-read", "reason": "worker binary (composition root): reads LELEKA_OPENVINO_ROOT into its configuration"}, {"crate": "leleka-memory", "file": "src/settings.rs", "ratchet": "process-global", "reason": "the cached LELEKA_NO_TRIM_FILE path: an immutable operator setting read once by the crate's one environment reader"}, - {"crate": "leleka-memory", "file": "src/governor.rs", "ratchet": "process-global", "reason": "Governor::global(): the process-wide memory governor installed once at engine start; its injection through the engine stack (S13/S14) belongs to the engine crate"}, - {"crate": "leleka-memory", "file": "src/inventory.rs", "ratchet": "process-global", "reason": "Inventory::global(): the process-wide census of live mappings and pinned regions, filled by the loaders; injected with the governor (S13/S14)"}, {"crate": "leleka-memory", "file": "src/governor.rs", "ratchet": "dyn-trait", "reason": "port boundary: the Governor holds its MemoryPressure adapter as Arc, chosen at start-up (hexagonal.md, ports table)"}, {"crate": "leleka-memory", "file": "src/governor/operations/setup.rs", "ratchet": "dyn-trait", "reason": "port boundary: Governor::new takes the host as Arc (the adapter is chosen by the composition root) and source() hands it back"}, {"crate": "leleka-memory", "file": "src/lock/page_locking.rs", "ratchet": "dyn-trait", "reason": "port boundary: SharedPageLocking = Arc, the OS adapter of mmap/mlock chosen by the composition root"}, @@ -130,7 +128,6 @@ {"crate": "leleka-model-format", "file": "src/kar/independent_handles.rs", "ratchet": "process-global", "reason": "the identity-recheck switch is an operator setting parsed once and cached for the process"}, {"crate": "leleka-model-format", "file": "src/kar.rs", "ratchet": "process-global", "reason": "a per-instance lazily opened set of file handles (a OnceLock field of the archive), not a process global"}, {"crate": "leleka-model-format", "file": "src/kar/verified_kar_ple_artifact.rs", "ratchet": "process-global", "reason": "constructs the per-instance lazy handle cell of kar.rs, not a process global"}, - {"crate": "leleka-model-format", "file": "src/verify_stamp.rs", "ratchet": "process-global", "reason": "the process-wide registry of verified-file stamps, written by the loaders and read by the identity re-checks; its injection belongs to the loader stack (S13)"}, {"crate": "leleka-control-plane", "file": "src/env_settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment of the crate: every variable is parsed here into a typed value (number, path, flag, mode)"}, {"crate": "leleka-deploy", "file": "src/env_settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment of the crate: every variable is parsed here into a typed value (path, flag, text)"}, {"crate": "leleka-engine-host", "file": "src/env_settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment of the crate and its binaries: credentials by name, the evaluation switches, the inherited child variables"}, @@ -177,12 +174,7 @@ {"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/spawn_preview.rs", "ratchet": "dyn-trait", "reason": "Box is the process boundary: the factory hands the composed engine to the host, which holds one Backend per process (startup composition only, never per round)"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/measurement.rs", "ratchet": "dyn-trait", "reason": "the evaluation measurement sink is a stored callback handed in by the host (observer port, called once per request)"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/original_serve/runner.rs", "ratchet": "dyn-trait", "reason": "the GPU telemetry probe is a stored callback handed in by the host at load (port, sampled by the telemetry tick, not per token)"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/original_serve/runner/owner_run_steps.rs", "ratchet": "process-global", "reason": "reaches the process-wide memory governor through Governor::global(); the governor is one per process by design (host RAM is process-wide) and the handle is threaded through StackConfig and the request environment in the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/original_serve/runner/reconfigure_command.rs", "ratchet": "process-global", "reason": "reaches the process-wide memory governor through Governor::global(); the governor is one per process by design (host RAM is process-wide) and the handle is threaded through StackConfig and the request environment in the S13/S14 injection"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/session.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/conversation/memory.rs", "ratchet": "process-global", "reason": "reaches the process-wide memory governor through Governor::global(); the governor is one per process by design (host RAM is process-wide) and the handle is threaded through StackConfig and the request environment in the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/memory_governor.rs", "ratchet": "process-global", "reason": "reaches the process-wide memory governor through Governor::global(); the governor is one per process by design (host RAM is process-wide) and the handle is threaded through StackConfig and the request environment in the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/memory_governor/page_cache.rs", "ratchet": "process-global", "reason": "reaches the process-wide memory governor through Governor::global(); the governor is one per process by design (host RAM is process-wide) and the handle is threaded through StackConfig and the request environment in the S13/S14 injection"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding/binding_identity.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding/model_binding.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"}, @@ -198,12 +190,8 @@ {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/mtp_decode/mtp_window_spec.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/split_group_pcie.rs", "ratchet": "process-global", "reason": "the adaptive-tier tuning constants, derived once from the settings capture (immutable after the first read)"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack.rs", "ratchet": "process-global", "reason": "the epoch of the bring-up trace timestamps (DBG_T0), set once; diagnostics only"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack/stack_phases/open_cache_steps.rs", "ratchet": "process-global", "reason": "reaches the process-wide memory governor through Governor::global(); the governor is one per process by design (host RAM is process-wide) and the handle is threaded through StackConfig and the request environment in the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_memory_classes.rs", "ratchet": "process-global", "reason": "reaches the process-wide memory governor through Governor::global(); the governor is one per process by design (host RAM is process-wide) and the handle is threaded through StackConfig and the request environment in the S13/S14 injection"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_open/assemble.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_prefill_phase.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack/prefix/prefix_config.rs", "ratchet": "process-global", "reason": "reaches the process-wide memory governor through Governor::global(); the governor is one per process by design (host RAM is process-wide) and the handle is threaded through StackConfig and the request environment in the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack/prefix/prefix_serve/prefix_serve_after_phase_parking.rs", "ratchet": "process-global", "reason": "reaches the process-wide memory governor through Governor::global(); the governor is one per process by design (host RAM is process-wide) and the handle is threaded through StackConfig and the request environment in the S13/S14 injection"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack/stack_config.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_spec_controller/trace_enabled.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_spec_draft.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, diff --git a/crates/engine-qwen35-cuda/src/backend.rs b/crates/engine-qwen35-cuda/src/backend.rs index 5960364a..6a0cb522 100644 --- a/crates/engine-qwen35-cuda/src/backend.rs +++ b/crates/engine-qwen35-cuda/src/backend.rs @@ -6,6 +6,7 @@ use crate::experimental::{self as experimental_modes, ExperimentalConfig}; use crate::model_binding::kar_expert_source::KarExpertSource; pub use crate::model_binding::kar_expert_source::{KarArchiveRef, KarExpertLevels, KarExpertSourceConfig}; pub use crate::model_binding::kar_ple_source::InheritedKarArchive; +pub use leleka_model_format::verify_stamp::{VerifyPolicy, VerifyStamps}; pub use original_serve::{ ExpertSource, OriginalServeChoice, OriginalServeMode, OriginalServeOptions, PrefixCacheOptions, PrefixTail, }; diff --git a/crates/engine-qwen35-cuda/src/backend/clock_tests.rs b/crates/engine-qwen35-cuda/src/backend/clock_tests.rs index 4b520367..9a7ff66a 100644 --- a/crates/engine-qwen35-cuda/src/backend/clock_tests.rs +++ b/crates/engine-qwen35-cuda/src/backend/clock_tests.rs @@ -132,6 +132,7 @@ fn source_verification_reads_the_clock_once_per_phase_and_reports_missing_files_ mtp_source: None, kar_expert_source: None, experimental: Default::default(), + verification: Default::default(), }; let clock = ManualClock::ticking(Duration::from_secs(1)); let before = clock.now(); diff --git a/crates/engine-qwen35-cuda/src/backend/combined_changed_boundary_proof/rig.rs b/crates/engine-qwen35-cuda/src/backend/combined_changed_boundary_proof/rig.rs index 3126edcd..12bb433f 100644 --- a/crates/engine-qwen35-cuda/src/backend/combined_changed_boundary_proof/rig.rs +++ b/crates/engine-qwen35-cuda/src/backend/combined_changed_boundary_proof/rig.rs @@ -49,6 +49,7 @@ fn bind_inherited( &inherited, &required_path("LELEKA_STRA169_MTP_PACK"), &required_path("LELEKA_STRA169_MTP_STAGING"), + &leleka_model_format::verify_stamp::VerifyPolicy::default(), ) .expect("actual pinned KAR+MTP binding failed"); (binding, inherited) diff --git a/crates/engine-qwen35-cuda/src/backend/config.rs b/crates/engine-qwen35-cuda/src/backend/config.rs index 6a7c01bc..4dddb602 100644 --- a/crates/engine-qwen35-cuda/src/backend/config.rs +++ b/crates/engine-qwen35-cuda/src/backend/config.rs @@ -55,6 +55,9 @@ pub struct NativeBackendConfig { /// `Default` is all-off and changes nothing; an enabled mode is admitted, digest-mixed and probed, and is /// refused at Load until the forward pass consumes it (`experimental::FORWARD_CONSUMER_WIRED`). pub experimental: ExperimentalConfig, + /// What vouches for the pinned files at Load (`--verify-stamps`, `--kar-attested-by-stamp`): a stamp or the + /// parent's attestation stands in for hashing a file again. `Default` vouches for nothing: every file is hashed. + pub verification: leleka_model_format::verify_stamp::VerifyPolicy, } /// Operator-owned immutable metadata; no file path or policy enters RPCs. diff --git a/crates/engine-qwen35-cuda/src/backend/load.rs b/crates/engine-qwen35-cuda/src/backend/load.rs index 79637a8a..685ab65c 100644 --- a/crates/engine-qwen35-cuda/src/backend/load.rs +++ b/crates/engine-qwen35-cuda/src/backend/load.rs @@ -23,6 +23,8 @@ pub(super) struct LoadEnv<'a> { pub(super) optimized: Option<&'a OptimizedBackendConfig>, pub(super) original: Option<&'a original_serve::OriginalServeOptions>, pub(super) settings: &'a crate::settings::Settings, + /// The engine's memory services: the governor the first Load installs, and what every owner asks it. + pub(super) memory: &'a leleka_memory::MemoryServices, /// The time of this load and of every request it serves; the composition root picks the type. pub(super) clock: SystemClock, } diff --git a/crates/engine-qwen35-cuda/src/backend/load_admit.rs b/crates/engine-qwen35-cuda/src/backend/load_admit.rs index 4bd4ca42..3446c81c 100644 --- a/crates/engine-qwen35-cuda/src/backend/load_admit.rs +++ b/crates/engine-qwen35-cuda/src/backend/load_admit.rs @@ -161,7 +161,7 @@ fn check_memory_ceiling(config: &NativeBackendConfig, requested: &RuntimeConfig) /// What the memory governor hands back at startup; nothing off the CUDA platforms. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -pub(super) type Governed = Option<&'static leleka_memory::Governor>; +pub(super) type Governed = Option; #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] pub(super) type Governed = (); @@ -173,9 +173,10 @@ pub(super) fn start_governor(env: &LoadEnv<'_>) -> Result BackendError { #[cfg(any(target_os = "linux", target_os = "windows"))] fn drop_shard_page_cache(env: &LoadEnv<'_>) { if env.original.is_some_and(|options| options.expert_source == original_serve::ExpertSource::Resident) { - crate::memory_governor::drop_file_cache(&[env.config.shard0.as_path(), env.config.shard1.as_path()]); + crate::memory_governor::drop_file_cache( + env.memory, + &[env.config.shard0.as_path(), env.config.shard1.as_path()], + ); } } #[cfg(not(any(target_os = "linux", target_os = "windows")))] diff --git a/crates/engine-qwen35-cuda/src/backend/load_cuda.rs b/crates/engine-qwen35-cuda/src/backend/load_cuda.rs index 2ae66141..18c4668a 100644 --- a/crates/engine-qwen35-cuda/src/backend/load_cuda.rs +++ b/crates/engine-qwen35-cuda/src/backend/load_cuda.rs @@ -48,7 +48,7 @@ pub(super) fn open_checked_context<'d>( fn check_vram(governed: Governed, context: &Context<'_>, budget: u64) -> Result<(), BackendError> { match governed { Some(g) => { - crate::memory_governor::check_vram(g, context, budget).map_err(|e| load_failure(LoadPhase::Context, e)) + crate::memory_governor::check_vram(&g, context, budget).map_err(|e| load_failure(LoadPhase::Context, e)) } None => Ok(()), } @@ -96,6 +96,7 @@ pub(super) fn launch_original<'d>( reply: env.reply, options, model_files: vec![env.config.shard0.clone(), env.config.shard1.clone()], + memory: env.memory, clock: env.clock, gpu_ordinal: env.config.gpu_device_ordinal, }) diff --git a/crates/engine-qwen35-cuda/src/backend/load_sources.rs b/crates/engine-qwen35-cuda/src/backend/load_sources.rs index 1228b8b8..5ada236e 100644 --- a/crates/engine-qwen35-cuda/src/backend/load_sources.rs +++ b/crates/engine-qwen35-cuda/src/backend/load_sources.rs @@ -6,6 +6,7 @@ use super::{ load_failure, selected_binding_failure, unsupported, verify_sources_parallel, }; use leleka_model_format::qwen4exp::ProvisionalExpertSource; +use leleka_model_format::verify_stamp::VerifyPolicy; use std::path::Path; /// The two verified shards, plus what the capture variants of the optimized modes took from shard 0 and the @@ -62,7 +63,7 @@ fn open_shard0(config: &NativeBackendConfig, prefetched: Option<&mut VerifiedSou if flags.streamed_spill { return captured_shard0(config, false); } - VerifiedGgufFile::open(&config.shard0, SHARD0).map(|shard| (shard, None)).map_err(|_| ()) + VerifiedGgufFile::open_with(&config.shard0, SHARD0, &config.verification).map(|shard| (shard, None)).map_err(|_| ()) } // Borrow metadata only from the operator's actual owned sealed archive. @@ -81,7 +82,7 @@ fn captured_shard0(config: &NativeBackendConfig, incremental: bool) -> Shard0 { fn open_shard1(config: &NativeBackendConfig, prefetched: Option<&mut VerifiedSources>) -> Result { match prefetched { Some(sources) => std::mem::replace(&mut sources.shard1, Err(String::new())).map_err(|_| ()), - None => VerifiedGgufFile::open(&config.shard1, SHARD1).map_err(|_| ()), + None => VerifiedGgufFile::open_with(&config.shard1, SHARD1, &config.verification).map_err(|_| ()), } } @@ -152,11 +153,11 @@ pub(super) fn bind_selected( fn bind_kar_ple(config: &NativeBackendConfig, artifact: Qwen4ExpArtifact) -> Result { if let Some(source) = config.kar_ple_inherited.as_ref() { - return Ok(ModelBinding::from_artifact_with_inherited_kar_ple(artifact, source)); + return Ok(ModelBinding::from_artifact_with_inherited_kar_ple(artifact, source, &config.verification)); } let (source, staging) = config.kar_ple_source.as_ref().ok_or_else(|| unsupported("KAR PLE operator source is absent"))?; - Ok(ModelBinding::from_artifact_with_pinned_kar_ple(artifact, source, staging)) + Ok(ModelBinding::from_artifact_with_pinned_kar_ple(artifact, (source, staging), &config.verification)) } fn bind_mtp( @@ -179,11 +180,16 @@ fn bind_kar_mtp( (source, staging): (&Path, &Path), ) -> Result { if let Some(inherited) = config.kar_ple_inherited.as_ref() { - return Ok(bind_inherited_kar_mtp(artifact, inherited, kar, (source, staging))); + return Ok(bind_inherited_kar_mtp(artifact, inherited, kar, (source, staging), &config.verification)); } let (kar_source, kar_staging) = config.kar_ple_source.as_ref().ok_or_else(|| unsupported("KAR PLE operator source is absent"))?; - Ok(ModelBinding::from_artifact_with_pinned_kar_mtp(artifact, kar_source, kar_staging, source, staging)) + Ok(ModelBinding::from_artifact_with_pinned_kar_mtp( + artifact, + (kar_source, kar_staging), + (source, staging), + &config.verification, + )) } /// The archive verified at the same time as the shards when it was, otherwise verified by the binding itself. @@ -192,12 +198,13 @@ fn bind_inherited_kar_mtp( inherited: &InheritedKarArchive, prefetched: Option, (source, staging): (&Path, &Path), + verify: &VerifyPolicy, ) -> Binding { match prefetched { 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, inherited, source, staging), + None => ModelBinding::from_artifact_with_inherited_kar_mtp(artifact, inherited, source, staging, verify), } } diff --git a/crates/engine-qwen35-cuda/src/backend/native_down_candidate_only/adaptive_slots.rs b/crates/engine-qwen35-cuda/src/backend/native_down_candidate_only/adaptive_slots.rs index 6adda8f2..ea430007 100644 --- a/crates/engine-qwen35-cuda/src/backend/native_down_candidate_only/adaptive_slots.rs +++ b/crates/engine-qwen35-cuda/src/backend/native_down_candidate_only/adaptive_slots.rs @@ -118,6 +118,7 @@ fn bind_model(root: &Path, baseline: &Baseline) -> Bound { &inherited, &path("LELEKA_STRA169_MTP_PACK"), &path("LELEKA_STRA169_MTP_STAGING"), + &leleka_model_format::verify_stamp::VerifyPolicy::default(), ) .expect("actual KAR MTP binding failed"); Bound { binding, inherited, tokenizer, eos, capture, capture_ns } diff --git a/crates/engine-qwen35-cuda/src/backend/native_down_candidate_only/pair_owner.rs b/crates/engine-qwen35-cuda/src/backend/native_down_candidate_only/pair_owner.rs index 401ea479..538c73ca 100644 --- a/crates/engine-qwen35-cuda/src/backend/native_down_candidate_only/pair_owner.rs +++ b/crates/engine-qwen35-cuda/src/backend/native_down_candidate_only/pair_owner.rs @@ -141,6 +141,7 @@ fn bind_model(artifact: Qwen4ExpArtifact, inherited: &InheritedKarArchive) -> Mo inherited, &path("LELEKA_STRA169_MTP_PACK"), &path("LELEKA_STRA169_MTP_STAGING"), + &leleka_model_format::verify_stamp::VerifyPolicy::default(), ) .expect("actual KAR MTP binding failed") } diff --git a/crates/engine-qwen35-cuda/src/backend/native_down_public_pair/pair_run.rs b/crates/engine-qwen35-cuda/src/backend/native_down_public_pair/pair_run.rs index f11c8353..81524d22 100644 --- a/crates/engine-qwen35-cuda/src/backend/native_down_public_pair/pair_run.rs +++ b/crates/engine-qwen35-cuda/src/backend/native_down_public_pair/pair_run.rs @@ -97,6 +97,7 @@ fn bind_model(fd: u32, artifact: Qwen4ExpArtifact) -> (InheritedKarArchive, Mode &inherited, &path("LELEKA_STRA169_MTP_PACK"), &path("LELEKA_STRA169_MTP_STAGING"), + &leleka_model_format::verify_stamp::VerifyPolicy::default(), ) .expect("actual KAR MTP binding failed"); (inherited, binding) diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve/runner.rs b/crates/engine-qwen35-cuda/src/backend/original_serve/runner.rs index 6d8cd566..2006299a 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve/runner.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve/runner.rs @@ -47,6 +47,8 @@ pub(in super::super) struct Run<'a, 'd> { pub(in super::super) options: &'a OriginalServeOptions, /// The model files, for the start-up report only (size and mtime are read; the content never is). pub(in super::super) model_files: Vec, + /// The engine's memory services (the governor the load installed). + pub(in super::super) memory: &'a leleka_memory::MemoryServices, pub(in super::super) clock: SystemClock, pub(in super::super) gpu_ordinal: u32, // for the telemetry sampler (NVML indexes the same physical order) } diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve/runner/command_loop.rs b/crates/engine-qwen35-cuda/src/backend/original_serve/runner/command_loop.rs index 6c62bc7e..9e51ab8c 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve/runner/command_loop.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve/runner/command_loop.rs @@ -29,6 +29,7 @@ impl<'r> LoopCtx<'r, '_, '_> { clock: self.clock, spec_min_p: live.options.spec_min_p, context_tokens: *live.context_tokens, + memory: self.reopen.memory, } } } diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve/runner/owner_run.rs b/crates/engine-qwen35-cuda/src/backend/original_serve/runner/owner_run.rs index 87138849..450edd75 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve/runner/owner_run.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve/runner/owner_run.rs @@ -12,13 +12,13 @@ use leleka_memory_os::HostProc; pub(in super::super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError> { #[rustfmt::skip] let Run { mut context_tokens, rx, shared, binding, context, tokenizer, eos, loaded, reply, options, model_files, - clock, gpu_ordinal } = args; + memory, clock, gpu_ordinal } = args; // the settings can change at run time (`Command::Reconfigure`): this thread owns the current copy let mut options = options.clone(); options.validate()?; let model = RecordedModel { artifact_digest: &loaded.descriptor.artifact_digest, files: &model_files }; - let (stack, mut workers) = open_run_stack(&binding, &context, &options, context_tokens, model)?; - publish_open(&stack, shared, (&options, &model_files), (context_tokens, workers)); + let (stack, mut workers) = open_run_stack(&binding, &context, (&options, context_tokens), model, memory)?; + publish_open(&stack, shared, (&options, &model_files), (context_tokens, workers), memory); let _telemetry = telemetry::start(gpu_probe(gpu_ordinal), Duration::from_secs(1), HostProc::default()); let mut stack = Some(stack); if !announce(shared, reply, &loaded, &mut stack)? { @@ -28,7 +28,7 @@ pub(in super::super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError } #[rustfmt::skip] let ctx = LoopCtx { rx, shared, loaded: &loaded, tokenizer: &tokenizer, eos, clock: &clock, - reopen: ReopenEnv { binding: &binding, context: &context, shared, clock: &clock } }; + reopen: ReopenEnv { binding: &binding, context: &context, shared, clock: &clock, memory } }; let mut live = Live { options: &mut options, context_tokens: &mut context_tokens, workers: &mut workers, stack: &mut stack }; let unload_reply = command_loop(&ctx, &mut live)?; diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve/runner/owner_run_steps.rs b/crates/engine-qwen35-cuda/src/backend/original_serve/runner/owner_run_steps.rs index e95d15bd..b898c099 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve/runner/owner_run_steps.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve/runner/owner_run_steps.rs @@ -10,6 +10,7 @@ use super::{ }; use leleka_backend_api::GenerationStream; use leleka_cuda_driver::Context; +use leleka_memory::MemoryServices; use std::sync::Arc; type Stack<'a, 'ctx> = OriginalServeStack<'a, 'ctx>; @@ -25,12 +26,12 @@ pub(super) struct RecordedModel<'a> { pub(super) fn open_run_stack<'a, 'ctx>( binding: &'a ModelBinding, context: &'ctx Rc>, - options: &OriginalServeOptions, - context_tokens: u32, + (options, context_tokens): (&OriginalServeOptions, u32), model: RecordedModel<'_>, + memory: &MemoryServices, ) -> Result<(Stack<'a, 'ctx>, i32), BackendError> { let RecordedModel { artifact_digest, files: model_files } = model; - let config = stack_config(options, context_tokens)?; + let config = stack_config(options, context_tokens, memory)?; let workers = config.cpu_workers; // STRA-325: build id, recorded model digest and effective tuning, once, before the stack opens (operator log only; // reads nothing the stack uses) @@ -76,14 +77,14 @@ pub(super) fn emit_cache_line(stack: &Stack<'_, '_>) { /// 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")] -pub(super) fn drop_model_page_cache(options: &OriginalServeOptions, model_files: &[PathBuf]) { +pub(super) fn drop_model_page_cache(memory: &MemoryServices, options: &OriginalServeOptions, model_files: &[PathBuf]) { if options.expert_source == crate::backend::ExpertSource::Resident { let mut files: Vec = model_files.to_vec(); 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); + crate::memory_governor::drop_file_cache(memory, &paths); } } @@ -126,6 +127,7 @@ pub(super) struct GenerateEnv<'r> { pub(super) clock: &'r SystemClock, pub(super) spec_min_p: f32, pub(super) context_tokens: u32, + pub(super) memory: &'r MemoryServices, } impl<'r> GenerateEnv<'r> { @@ -141,8 +143,13 @@ impl<'r> GenerateEnv<'r> { /// Memory admission: refuse before the first byte of work when the host is under pressure (the front end /// answers 503 `memory_pressure` with Retry-After; the text is the contract: `: retry_after=: `) -fn memory_refusal(prompt_tokens: usize, request: &GenerationRequest, context_tokens: u32) -> Option { - let governor = leleka_memory::Governor::global()?; +fn memory_refusal( + memory: &MemoryServices, + prompt_tokens: usize, + request: &GenerationRequest, + context_tokens: u32, +) -> Option { + let governor = memory.governor()?; let shape = leleka_memory::RequestShape { prompt_tokens: prompt_tokens as u64, max_new_tokens: u64::from(request.max_output_tokens), @@ -174,7 +181,7 @@ fn admit_generate( if !context_fits(prompt.len(), request.max_output_tokens as usize, env.context_tokens) { return Err(exhausted("prompt and output exceed configured context")); } - match memory_refusal(prompt.len(), request, env.context_tokens) { + match memory_refusal(env.memory, prompt.len(), request, env.context_tokens) { Some(refusal) => Err(refusal), None => Ok(prompt), } @@ -284,6 +291,7 @@ pub(super) fn publish_open( shared: &Shared, state: (&OriginalServeOptions, &[PathBuf]), sizes: (u32, i32), + memory: &MemoryServices, ) { let (options, model_files) = state; let (context_tokens, workers) = sizes; @@ -291,9 +299,9 @@ pub(super) fn publish_open( publish_prefix_summary(stack, shared); crate::load_clock::lap("serve_stack_open_total"); #[cfg(target_os = "linux")] - drop_model_page_cache(options, model_files); + drop_model_page_cache(memory, options, model_files); #[cfg(not(target_os = "linux"))] - let _ = model_files; + let _ = (model_files, memory); 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/engine-qwen35-cuda/src/backend/original_serve/runner/reconfigure_command.rs b/crates/engine-qwen35-cuda/src/backend/original_serve/runner/reconfigure_command.rs index 7a3cbd62..d1caa621 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve/runner/reconfigure_command.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve/runner/reconfigure_command.rs @@ -7,6 +7,7 @@ use super::{ unavailable, }; use leleka_cuda_driver::Context; +use leleka_memory::MemoryServices; use std::time::Instant; type Stack<'a, 'ctx> = OriginalServeStack<'a, 'ctx>; @@ -25,14 +26,15 @@ pub(super) struct ReopenEnv<'a, 'ctx, 'r> { pub(super) context: &'ctx Rc>, pub(super) shared: &'r Shared, pub(super) clock: &'r SystemClock, + pub(super) memory: &'r MemoryServices, } /// The old stack is closed before the new one opens, so the new one's pinned host memory (K/V, rings, pools) must fit /// in /// what is free now. Refuse up front on a starved host instead of leaving the engine without a stack (live native run /// 2026-10-25). -fn refuse_starved_host() -> Result<(), BackendError> { - if let Some(governor) = leleka_memory::Governor::global() { +fn refuse_starved_host(memory: &MemoryServices) -> Result<(), BackendError> { + if let Some(governor) = memory.governor() { let need = governor.policy().soft_floor.saturating_add(RECONFIGURE_HEADROOM_BYTES); if let Some(available) = governor.probe().effective_available().filter(|available| *available < need) { return Err(starved_host_error(available, need)); @@ -60,7 +62,7 @@ fn open_stack<'a, 'ctx>( options: &OriginalServeOptions, tokens: u32, ) -> Result<(Stack<'a, 'ctx>, i32), BackendError> { - let config = stack_config(options, tokens)?; + let config = stack_config(options, tokens, env.memory)?; let workers = config.cpu_workers; let opened = OriginalServeStack::open(env.binding, env.context.as_ref(), Rc::clone(env.context), config) .map_err(|failure| open_error(&failure))?; @@ -152,7 +154,7 @@ pub(super) fn reconfigure<'a, 'ctx>( return Ok(crate::serve_tuning::describe(live.options, *live.context_tokens, *live.workers, None).to_string()); } use std::io::Write; - refuse_starved_host()?; + refuse_starved_host(env.memory)?; let _ = writeln!(std::io::stderr().lock(), "leleka-serve reconfigure: {changed:?}; reopening the serve stack"); let started = env.clock.now(); env.shared.ready.store(false, Ordering::Release); diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve/runner/stack_reports.rs b/crates/engine-qwen35-cuda/src/backend/original_serve/runner/stack_reports.rs index 1ba4fd2b..69373744 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve/runner/stack_reports.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve/runner/stack_reports.rs @@ -55,8 +55,17 @@ fn prefix_config(prefix: &super::super::PrefixCacheOptions) -> crate::qwen_forwa prefix_config } -/// The serve stack's configuration for these settings (everything except the weights, which stay loaded). -pub(super) fn stack_config(options: &OriginalServeOptions, context_tokens: u32) -> Result { +/// The serve stack's configuration for these settings (everything except the weights, which stay loaded), over the +/// engine's memory services. +pub(super) fn stack_config( + options: &OriginalServeOptions, + context_tokens: u32, + memory: &leleka_memory::MemoryServices, +) -> Result { + Ok(StackConfig { memory: memory.clone(), ..options_config(options, context_tokens)? }) +} + +fn options_config(options: &OriginalServeOptions, context_tokens: u32) -> Result { let mut config = StackConfig::new(i64::from(context_tokens)); if let Some(capacity) = options.prefill_capacity { config.capacity = capacity; diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_laptop.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_laptop.rs index 4418cab1..5337b909 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_laptop.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_laptop.rs @@ -116,6 +116,7 @@ fn bind_laptop(start: std::time::Instant) -> Loaded { &inherited, &required_path("LELEKA_STRA169_MTP_PACK"), &required_path("LELEKA_STRA169_MTP_STAGING"), + &leleka_model_format::verify_stamp::VerifyPolicy::default(), ) .expect("actual pinned KAR+MTP binding failed"); eprintln!( diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke.rs index 94e1a214..e45fcfd0 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke.rs @@ -33,7 +33,7 @@ use crate::qwen_forward::{ original_serve_stack::{OriginalServeStack, PrefixBudget, PrefixConfig, StackConfig}, }; use leleka_memory::census::{Census, Tolerances, check_flat}; -use leleka_memory::{Admission, Governor, Level, RequestShape}; +use leleka_memory::{Admission, Governor, Level, MemoryServices, RequestShape}; use leleka_memory_os::HostProc; use std::env; @@ -150,8 +150,8 @@ fn census(context: &leleka_cuda_driver::Context<'_>) -> Census { } /// Abort (never go on) when the host is short of memory: the operator's rule for this server. -fn guard(floor_gib: u64, what: &str) { - if let Some(avail) = crate::conversation::memory::available_memory() { +fn guard(memory: &MemoryServices, floor_gib: u64, what: &str) { + if let Some(avail) = crate::conversation::memory::available_memory(memory) { assert!( avail >= floor_gib << 30, "ABORT {what}: MemAvailable {} MiB is below the {floor_gib} GiB guard", @@ -160,11 +160,11 @@ fn guard(floor_gib: u64, what: &str) { } } -fn print_report(tag: &str) { - if let Some(text) = crate::memory_governor::report() { +fn print_report(memory: &MemoryServices, tag: &str) { + if let Some(text) = crate::memory_governor::report(memory) { eprintln!("MEM-REPORT {tag} {text}"); } - if let Some(g) = Governor::global() { + if let Some(g) = memory.governor() { eprintln!("MEM-TABLE {tag}\n{}", g.inventory().table()); eprintln!("MEM-LEDGER {tag}\n{}", g.ledger().table()); } diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/inventory.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/inventory.rs index d6862d4e..9dc4372a 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/inventory.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/inventory.rs @@ -13,7 +13,7 @@ impl Mem<'_, '_> { } self.fill_prefix_cache(); self.governor.sample_now(); - print_report("prefix-full"); + print_report(&self.memory, "prefix-full"); self.census_line("prefix-full"); } fn long_request(&mut self, target: usize) { @@ -31,7 +31,7 @@ impl Mem<'_, '_> { } self.governor.sample_now(); self.guard("after a long request"); - print_report(&format!("after-{target}")); + print_report(&self.memory, &format!("after-{target}")); self.census_line(&format!("after-{target}")); } /// Fills the prefix cache: distinct sessions until the store is at its budget. diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/leak.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/leak.rs index f7b0b69c..740a68e5 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/leak.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/leak.rs @@ -97,7 +97,7 @@ impl Mem<'_, '_> { let _ = std::fs::write(path, &run.tsv); } leak_fit(&run, plan.warm_frac); - print_report("leak-end"); + print_report(&self.memory, "leak-end"); } fn leak_request(&mut self, plan: &Leak, kind: &str, session: &mut Vec, run: &mut Run) { let (req, t) = (run.req, &mut run.tally); diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/load.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/load.rs index cac55044..8ae35a5d 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/load.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/load.rs @@ -1,9 +1,9 @@ //! Loads the pinned model under the memory governor, opens the serve stack as production starts it and runs the //! scenario of `LELEKA_MEM_SCENARIO` on it. use super::{ - CancelAt, Census, Driver, Governor, InheritedKarArchive, ModelBinding, OriginalServeStack, PathBuf, PrefixBudget, - PrefixConfig, Qwen4ExpArtifact, Rc, Rng, SHARD0, SHARD1, ServeError, StackConfig, Tokenizer, VerifiedGgufFile, - census, dbg_el, env, filler, guard, number, print_report, required_path, serve_one, text, + CancelAt, Census, Driver, Governor, InheritedKarArchive, MemoryServices, ModelBinding, OriginalServeStack, PathBuf, + PrefixBudget, PrefixConfig, Qwen4ExpArtifact, Rc, Rng, SHARD0, SHARD1, ServeError, StackConfig, Tokenizer, + VerifiedGgufFile, census, dbg_el, env, filler, guard, number, print_report, required_path, serve_one, text, }; /// What the operator asked for. @@ -42,7 +42,8 @@ struct Loaded { _inherited: InheritedKarArchive, tokenizer: Tokenizer, eos: u32, - governor: &'static Governor, + memory: MemoryServices, + governor: Governor, budget_gib: usize, } fn pinned_artifact() -> Qwen4ExpArtifact { @@ -80,8 +81,14 @@ fn open_archive() -> InheritedKarArchive { } } /// The production startup sequence: plan (or refuse), then lock/guard the memfd, before any model byte is read. -fn start_governor(plan: &Plan, inherited: &InheritedKarArchive, budget_gib: usize) -> &'static Governor { +fn start_governor( + memory: &MemoryServices, + plan: &Plan, + inherited: &InheritedKarArchive, + budget_gib: usize, +) -> Governor { let governor = crate::memory_governor::startup( + memory, &crate::memory_governor::StartArgs { kv_resident: plan.resident, gpu_budget_bytes: (budget_gib as u64) << 30, @@ -94,16 +101,17 @@ fn start_governor(plan: &Plan, inherited: &InheritedKarArchive, budget_gib: usiz crate::settings::process(), ) .unwrap_or_else(|e| panic!("memory plan refused: {}", e.message)); - crate::memory_governor::guard_archive(governor, inherited) + crate::memory_governor::guard_archive(&governor, inherited) .unwrap_or_else(|e| panic!("memory guard refused: {}", e.message)); governor } -fn load_bank(binding: &mut ModelBinding, mapped: bool) { - let bank_stage = crate::memory_governor::begin("expert bank (resident copy or mappings)", None); +fn load_bank(memory: &MemoryServices, binding: &mut ModelBinding, mapped: bool) { + let bank_stage = crate::memory_governor::begin(memory, "expert bank (resident copy or mappings)", None); let bank = if mapped { binding.load_mapped_expert_source() } else { binding.load_resident_expert_source() } .expect("expert source load failed"); crate::memory_governor::end(bank_stage, None); crate::memory_governor::account( + memory, crate::memory_governor::InventoryClass { component: "expert_bank", class: if mapped { "file_mapped" } else { "resident" }, @@ -114,28 +122,29 @@ fn load_bank(binding: &mut ModelBinding, mapped: bool) { bank.charged_bytes, ); if !mapped { - crate::memory_governor::drop_file_cache(&[ - &required_path("LELEKA_STRA169_IQ3S_SHARD0"), - &required_path("LELEKA_STRA169_IQ3S_SHARD1"), - ]); + crate::memory_governor::drop_file_cache( + memory, + &[&required_path("LELEKA_STRA169_IQ3S_SHARD0"), &required_path("LELEKA_STRA169_IQ3S_SHARD1")], + ); } } -fn load(plan: &Plan) -> Loaded { +fn load(plan: &Plan, memory: MemoryServices) -> Loaded { let artifact = pinned_artifact(); let (tokenizer, eos) = pinned_tokenizer(&artifact); let inherited = open_archive(); let budget_gib = number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 28); - let governor = start_governor(plan, &inherited, budget_gib); + let governor = start_governor(&memory, plan, &inherited, budget_gib); let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( artifact, &inherited, &required_path("LELEKA_STRA169_MTP_PACK"), &required_path("LELEKA_STRA169_MTP_STAGING"), + &leleka_model_format::verify_stamp::VerifyPolicy::default(), ) .expect("actual pinned KAR+MTP binding failed"); - load_bank(&mut binding, plan.experts_mapped); - guard(plan.abort_gib, "after the expert bank"); - Loaded { binding, _inherited: inherited, tokenizer, eos, governor, budget_gib } + load_bank(&memory, &mut binding, plan.experts_mapped); + guard(&memory, plan.abort_gib, "after the expert bank"); + Loaded { binding, _inherited: inherited, tokenizer, eos, memory, governor, budget_gib } } fn stack_config(plan: &Plan) -> StackConfig { let mut config = StackConfig::new(plan.max_context as i64); @@ -162,7 +171,8 @@ fn stack_config(plan: &Plan) -> StackConfig { pub(super) struct Mem<'a, 'ctx> { pub(super) stack: OriginalServeStack<'a, 'ctx>, pub(super) context: &'a Rc>, - pub(super) governor: &'static Governor, + pub(super) memory: MemoryServices, + pub(super) governor: Governor, tokenizer: &'a Tokenizer, pub(super) eos: u32, pub(super) abort_gib: u64, @@ -188,7 +198,7 @@ impl Mem<'_, '_> { serve_one(&mut self.stack, prompt, max_new, self.eos, CancelAt { probes: cancel_probes, rounds: cancel_rounds }) } pub(super) fn guard(&self, what: &str) { - guard(self.abort_gib, what); + guard(&self.memory, self.abort_gib, what); } pub(super) fn census(&self) -> Census { census(self.context.as_ref()) @@ -233,7 +243,8 @@ fn new_mem<'a, 'ctx>( let mut mem = Mem { stack, context, - governor: loaded.governor, + memory: loaded.memory.clone(), + governor: loaded.governor.clone(), tokenizer: &loaded.tokenizer, eos: loaded.eos, abort_gib: plan.abort_gib, @@ -251,22 +262,23 @@ fn new_mem<'a, 'ctx>( } /// Opens the stack, takes the idle measurements, runs the scenario and the closing measurements. fn measure(plan: &Plan, loaded: &Loaded, context: &Rc>) -> Vec { - let config = stack_config(plan); + let mut config = stack_config(plan); + config.memory = loaded.memory.clone(); let stack = match OriginalServeStack::open(&loaded.binding, context.as_ref(), Rc::clone(context), config) { Ok(stack) => stack, Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), }; - guard(plan.abort_gib, "after the stack opened"); - let governor = loaded.governor; + guard(&loaded.memory, plan.abort_gib, "after the stack opened"); + let governor = &loaded.governor; governor.sample_now(); - print_report("idle"); + print_report(&loaded.memory, "idle"); eprintln!("MEM-CENSUS idle {}", serde_json::to_string(&census(context.as_ref())).unwrap()); // the stack opens in the "plan -> open -> report" order production uses; also the residency of the memfd right now let swapped = governor.residency_tick(); eprintln!("MEM-ARCHIVE swapped_bytes={swapped}"); let mut mem = new_mem(plan, loaded, stack, context); mem.scenario(&plan.scenario); - guard(plan.abort_gib, "end"); + guard(&loaded.memory, plan.abort_gib, "end"); mem.census_line("end"); eprintln!("MEM-RESULT scenario={} failed={:?}", plan.scenario, mem.failed); mem.stack.close().expect("stack cleanup failed"); @@ -276,13 +288,14 @@ pub(super) fn run() { let _ = dbg_el(); assert!(env::var("LELEKA_MEM_SMOKE").is_ok_and(|v| v == "yes"), "explicit memory smoke opt-in required"); let plan = Plan::from_env(); - guard(plan.abort_gib, "before the load"); - let loaded = load(&plan); + let memory = MemoryServices::new(); + guard(&memory, plan.abort_gib, "before the load"); + let loaded = load(&plan, memory); let budget_gib = loaded.budget_gib; let driver = Driver::load().expect("CUDA driver load failed"); let device = driver.device(0).expect("CUDA device 0 unavailable"); let context = Rc::new(device.create_context(budget_gib << 30).expect("bounded Context unavailable")); - crate::memory_governor::check_vram(loaded.governor, context.as_ref(), (budget_gib as u64) << 30) + crate::memory_governor::check_vram(&loaded.governor, context.as_ref(), (budget_gib as u64) << 30) .unwrap_or_else(|e| panic!("vram refused: {}", e.message)); let failed = measure(&plan, &loaded, &context); Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/probe.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/probe.rs index 927c0a5f..3dcdb1a2 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/probe.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/probe.rs @@ -1,8 +1,8 @@ //! Model-free probe of the sealed KAR memfd under the governor's residency guard. -use super::{Governor, InheritedKarArchive, env, guard, number, required_path}; +use super::{Governor, InheritedKarArchive, MemoryServices, env, guard, number, required_path}; /// One second of the probe: the memfd's swapped bytes, the cost of looking, and the swap counters since the last. -fn probe_second(governor: &Governor, t: u64, last_in: &mut Option<(u64, u64)>) { +fn probe_second(memory: &MemoryServices, governor: &Governor, t: u64, last_in: &mut Option<(u64, u64)>) { let before = std::time::Instant::now(); let swapped = governor.residency_tick(); let facts = governor.probe(); @@ -18,7 +18,7 @@ fn probe_second(governor: &Governor, t: u64, last_in: &mut Option<(u64, u64)>) { facts.meminfo.shmem.unwrap_or(0) >> 20, (facts.meminfo.swap_total.unwrap_or(0) - facts.meminfo.swap_free.unwrap_or(0)) >> 20, ); - guard(number("LELEKA_MEM_ABORT_GIB", 15) as u64, "probe"); + guard(memory, number("LELEKA_MEM_ABORT_GIB", 15) as u64, "probe"); std::thread::sleep(std::time::Duration::from_secs(1)); } pub(super) fn run() { @@ -29,9 +29,10 @@ pub(super) fn run() { .expect("invalid descriptor"); let provenance = required_path("LELEKA_STRA169_KAR_PROVENANCE"); let inherited = InheritedKarArchive::open(fd, provenance).expect("inherited KAR admission failed"); - let governor = crate::memory_governor::install(false, crate::settings::process()).expect("governor"); + let memory = MemoryServices::new(); + let governor = crate::memory_governor::install(&memory, false, crate::settings::process()).expect("governor"); let started = std::time::Instant::now(); - let report = crate::memory_governor::guard_archive(governor, &inherited); + let report = crate::memory_governor::guard_archive(&governor, &inherited); eprintln!( "PROBE guard result: {:?} in {:.1} s", report.as_ref().map(|_| "ok").map_err(|e| e.message.clone()), @@ -40,7 +41,7 @@ pub(super) fn run() { let secs = number("LELEKA_MEM_PROBE_SECS", 60); let mut last_in = None; for t in 0..secs { - probe_second(governor, t as u64, &mut last_in); + probe_second(&memory, &governor, t as u64, &mut last_in); } - eprintln!("PROBE report {}", crate::memory_governor::report().unwrap_or_default()); + eprintln!("PROBE report {}", crate::memory_governor::report(&memory).unwrap_or_default()); } diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/reader.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/reader.rs index 4eee1020..156a4252 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/reader.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/reader.rs @@ -85,7 +85,7 @@ impl Mem<'_, '_> { self.reader_phase(ReaderPhase { label: "C-after", prompt: &prompt }, &cfg, &mut c, &|| true); NO_STOP.store(false, Ordering::Relaxed); print_means(&a, &b, &c); - print_report("reader-end"); + print_report(&self.memory, "reader-end"); } fn swap_counters(&self) -> (u64, u64) { let f = self.governor.probe(); @@ -122,7 +122,7 @@ impl Mem<'_, '_> { swapped >> 20, in1 - in0, out1 - out0, - crate::conversation::memory::available_memory().unwrap_or(0) >> 20 + crate::conversation::memory::available_memory(&self.memory).unwrap_or(0) >> 20 ); } Err(e) => self.failed.push(format!("reader {label} {i}: {e:?}")), diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/shed.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/shed.rs index 9932c0d2..3dea3892 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/shed.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/shed.rs @@ -3,10 +3,10 @@ use super::{Admission, Level, Mem, RequestShape, number, print_report}; use std::time::Duration; -fn available() -> u64 { - crate::conversation::memory::available_memory().unwrap_or(0) -} impl Mem<'_, '_> { + fn available(&self) -> u64 { + crate::conversation::memory::available_memory(&self.memory).unwrap_or(0) + } fn shape(&self, n: usize) -> RequestShape { RequestShape { prompt_tokens: n as u64, max_new_tokens: 8, max_context: self.max_context as u64 } } @@ -23,7 +23,7 @@ impl Mem<'_, '_> { /// Moves the floors next to the memory the host has now; the real limits are never approached. Returns the /// ballast to push the host with. fn shed_floors(&self) -> usize { - let a0 = crate::conversation::memory::available_memory().expect("MemAvailable unknown"); + let a0 = crate::conversation::memory::available_memory(&self.memory).expect("MemAvailable unknown"); let soft_below = (number("LELEKA_MEM_SOFT_BELOW_MIB", 1536) as u64) << 20; let hard_below = (number("LELEKA_MEM_HARD_BELOW_MIB", 3072) as u64) << 20; let ballast_mib = number("LELEKA_MEM_BALLAST_MIB", 3584); @@ -72,7 +72,7 @@ impl Mem<'_, '_> { "MEM-SHED grow i={i} level={} prefix_used_mib={} available_mib={}", level.as_str(), used >> 20, - available() >> 20 + self.available() >> 20 ); self.guard("growing the prefix cache"); Some((used, level)) @@ -84,10 +84,10 @@ impl Mem<'_, '_> { self.failed.push("shedding must still admit requests".into()); } let used_before = self.stack.prefix_bytes(); - let (avail_before, rss_before) = (available(), self.census().rss); + let (avail_before, rss_before) = (self.available(), self.census().rss); let _ = self.serve(&prompt, 4, None, None); let used_after = self.stack.prefix_bytes(); - let (avail_after, rss_after) = (available(), self.census().rss); + let (avail_after, rss_after) = (self.available(), self.census().rss); eprintln!( "MEM-SHED evicted: prefix {} MiB -> {} MiB (level {}); MemAvailable {} -> {} MiB, RSS {} -> {} MiB", used_before >> 20, @@ -121,7 +121,7 @@ impl Mem<'_, '_> { "MEM-SHED ballast {} MiB level={} available_mib={}", ballast.len() >> 20, self.governor.level().as_str(), - available() >> 20 + self.available() >> 20 ); ballast } @@ -137,14 +137,14 @@ impl Mem<'_, '_> { if self.stack.prefix_bytes() != 0 { self.failed.push(format!("the prefix cache still holds {} MiB at reject", self.stack.prefix_bytes() >> 20)); } - print_report("reject"); + print_report(&self.memory, "reject"); } /// The baseline drifted while the test ran (mapped expert pages warmed up): re-centre the floors on what the /// host has now, so the hysteresis margin (1 GiB above the soft floor) can be met; the recovery path itself is /// what is under test. fn recenter_floors(&self) { std::thread::sleep(Duration::from_millis(500)); - let a_now = crate::conversation::memory::available_memory().expect("MemAvailable unknown"); + let a_now = crate::conversation::memory::available_memory(&self.memory).expect("MemAvailable unknown"); self.governor.set_floors(a_now - (2048u64 << 20), a_now - (3584u64 << 20)).expect("floors"); } fn shed_recover(&mut self, prompt: &[u32]) { @@ -175,6 +175,6 @@ impl Mem<'_, '_> { if r.is_err() || restored < (1 << 30) { self.failed.push("the prefix budget was not restored".into()); } - print_report("recovered"); + print_report(&self.memory, "recovered"); } } diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/soak.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/soak.rs index 1df06f3f..fecf01a0 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/soak.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/soak.rs @@ -95,7 +95,7 @@ impl Mem<'_, '_> { t.served, t.cancelled, t.refused, t.bigs ); eprintln!("MEM-SOAK-SERIES {}", serde_json::to_string(series).unwrap()); - print_report("soak-end"); + print_report(&self.memory, "soak-end"); if !flat.ok { self.failed.push("process memory not flat after warm-up".into()); } diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_prefix_smoke.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_prefix_smoke.rs index b6620765..bd48d9d9 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_prefix_smoke.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_prefix_smoke.rs @@ -67,7 +67,7 @@ impl Rng { } fn mem_available_mib() -> u64 { - crate::conversation::memory::available_memory().map_or(0, |b| b >> 20) + crate::conversation::memory::available_memory(&leleka_memory::MemoryServices::new()).map_or(0, |b| b >> 20) } fn rss_mib() -> u64 { std::fs::read_to_string("/proc/self/status") diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_prefix_smoke/run.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_prefix_smoke/run.rs index 7d30d4cf..a9c22b26 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_prefix_smoke/run.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_prefix_smoke/run.rs @@ -66,6 +66,7 @@ fn load(laptop: bool) -> Pinned { &inherited, &required_path("LELEKA_STRA169_MTP_PACK"), &required_path("LELEKA_STRA169_MTP_STAGING"), + &leleka_model_format::verify_stamp::VerifyPolicy::default(), ) .expect("actual pinned KAR+MTP binding failed"); load_experts(&mut binding, laptop); diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_replay/load.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_replay/load.rs index d70e9d43..647395ac 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_replay/load.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_replay/load.rs @@ -53,6 +53,7 @@ fn bind_inherited(artifact: Qwen4ExpArtifact) -> ModelBinding { &inherited, &required_path("LELEKA_STRA169_MTP_PACK"), &required_path("LELEKA_STRA169_MTP_STAGING"), + &leleka_model_format::verify_stamp::VerifyPolicy::default(), ) .expect("actual pinned KAR+MTP binding failed") } diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_smoke/smoke_stack.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_smoke/smoke_stack.rs index 4b6a3cc2..2bdb48b5 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_smoke/smoke_stack.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_smoke/smoke_stack.rs @@ -85,6 +85,7 @@ pub(super) fn open_pinned(announce: bool) -> Pinned { &inherited, &required_path("LELEKA_STRA169_MTP_PACK"), &required_path("LELEKA_STRA169_MTP_STAGING"), + &leleka_model_format::verify_stamp::VerifyPolicy::default(), ) .expect("actual pinned KAR+MTP binding failed"); if announce { diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_ttft.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_ttft.rs index a7fc296c..29b1c076 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_ttft.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_ttft.rs @@ -79,6 +79,7 @@ fn load_sweep_binding() -> Loaded { &inherited, &required_path("LELEKA_STRA169_MTP_PACK"), &required_path("LELEKA_STRA169_MTP_STAGING"), + &leleka_model_format::verify_stamp::VerifyPolicy::default(), ) .expect("actual pinned KAR+MTP binding failed"); binding.load_resident_expert_source().expect("resident expert source load failed"); diff --git a/crates/engine-qwen35-cuda/src/backend/owner.rs b/crates/engine-qwen35-cuda/src/backend/owner.rs index 8d0f2a3d..06f75bea 100644 --- a/crates/engine-qwen35-cuda/src/backend/owner.rs +++ b/crates/engine-qwen35-cuda/src/backend/owner.rs @@ -60,6 +60,8 @@ pub(super) struct OwnerThread<'a> { pub(super) config: NativeBackendConfig, pub(super) shared: &'a Shared, pub(super) instance: u64, + /// The engine's memory services, created at spawn and dropped (the sampler stopped) with the owner thread. + pub(super) memory: leleka_memory::MemoryServices, } impl OwnerThread<'_> { /// Serve the commands of the owner thread until shutdown: every Load runs its generations until Unload. @@ -96,6 +98,7 @@ impl OwnerThread<'_> { optimized: self.selection.optimized.as_ref(), original: self.selection.original.as_ref(), settings: crate::settings::process(), + memory: &self.memory, clock: SystemClock, }; if let Err(error) = serve_load(&env, model, requested) { diff --git a/crates/engine-qwen35-cuda/src/backend/proxy.rs b/crates/engine-qwen35-cuda/src/backend/proxy.rs index f3054bdc..8cc43c00 100644 --- a/crates/engine-qwen35-cuda/src/backend/proxy.rs +++ b/crates/engine-qwen35-cuda/src/backend/proxy.rs @@ -21,6 +21,8 @@ pub(super) struct Shared { pub(super) struct Proxy { pub(super) tx: SyncSender, pub(super) shared: Arc, + /// The engine's memory services; the status surface reads the governor's published report from them. + pub(super) memory: leleka_memory::MemoryServices, pub(super) seen: RecentIds, pub(super) kar_configured: bool, pub(super) mtp_configured: bool, @@ -151,7 +153,7 @@ impl Backend for Proxy { if self.shared.shutdown.load(Ordering::Acquire) { return None; } - leleka_memory::published_report() + self.memory.published_report() } fn telemetry_report(&self) -> Option { if self.shared.shutdown.load(Ordering::Acquire) { diff --git a/crates/engine-qwen35-cuda/src/backend/sources.rs b/crates/engine-qwen35-cuda/src/backend/sources.rs index f1cd1ea8..c419fdde 100644 --- a/crates/engine-qwen35-cuda/src/backend/sources.rs +++ b/crates/engine-qwen35-cuda/src/backend/sources.rs @@ -4,6 +4,7 @@ use super::{ RANKED_EXPERT_PROFILE_BYTES, RANKED_EXPERT_PROFILE_SHA, RankedExpertProfileSource, SHARD0, SHARD1, Sha256, SystemClock, VerifiedGgufFile, exhausted, invalid, }; +use leleka_model_format::verify_stamp::VerifyPolicy; use leleka_model_format::weight_source::{BackingKind, FileWeightSource, WeightError, WeightSource}; /// What the three source verifications returned. Errors are reduced to text because the verifying threads hand @@ -19,14 +20,14 @@ pub(super) type InputResultKar = Result Result { let started = clock.now(); - let result = VerifiedGgufFile::open(&config.shard1, SHARD1).map_err(|e| e.to_string()); + let result = VerifiedGgufFile::open_with(&config.shard1, SHARD1, &config.verification).map_err(|e| e.to_string()); crate::load_clock::span("shard1_sha256_and_index", started); result } -fn verify_kar_archive(archive: &InheritedKarArchive, clock: &impl Clock) -> InputResultKar { +fn verify_kar_archive(archive: &InheritedKarArchive, verify: &VerifyPolicy, clock: &impl Clock) -> InputResultKar { let started = clock.now(); - let result = crate::model_binding::kar_ple_source::load_pinned_inherited_archive(archive); + let result = crate::model_binding::kar_ple_source::load_pinned_inherited_archive(archive, verify); crate::load_clock::span("kar_inspect_verify", started); result } @@ -47,9 +48,10 @@ pub(super) fn verify_sources_parallel( .kar_ple_inherited .as_ref() .filter(|_| want_kar) - .map(|archive| scope.spawn(move || verify_kar_archive(archive, clock))); + .map(|archive| scope.spawn(move || verify_kar_archive(archive, &config.verification, clock))); let started = clock.now(); - let shard0 = VerifiedGgufFile::open(&config.shard0, SHARD0).map_err(|e| e.to_string()); + let shard0 = + VerifiedGgufFile::open_with(&config.shard0, SHARD0, &config.verification).map_err(|e| e.to_string()); crate::load_clock::span("shard0_sha256_and_index", started); VerifiedSources { shard0, @@ -76,19 +78,6 @@ pub fn verify_sources_only(config: NativeBackendConfig) -> Result<(), BackendErr 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, - )) -} const PROFILE_UNAVAILABLE: &str = "ranked expert profile unavailable"; /// The pinned ranked expert profile: opened once through the `WeightSource` port, read into the one profile buffer diff --git a/crates/engine-qwen35-cuda/src/backend/spawn.rs b/crates/engine-qwen35-cuda/src/backend/spawn.rs index 983b3e35..d7411c82 100644 --- a/crates/engine-qwen35-cuda/src/backend/spawn.rs +++ b/crates/engine-qwen35-cuda/src/backend/spawn.rs @@ -1,5 +1,7 @@ //! The common owner-thread spawn of every backend (Original serve and preview alike). The preview factories //! (Native and evaluation-only backends) live in `spawn_preview.rs`, behind the `preview-path` feature. +use leleka_memory::MemoryServices; + use super::{ Arc, AtomicBool, Backend, BackendError, Command, ErrorCode, EvaluationExecution, EvaluationObserver, INSTANCE, MODE_DIGEST, Mutex, NativeBackendConfig, Ordering, OwnerExecution, OwnerGuard, OwnerThread, PolicyFlags, Proxy, @@ -58,10 +60,11 @@ fn proxy_facts(config: &NativeBackendConfig, selection: &OwnerExecution) -> Prox } impl ProxyFacts { - fn into_proxy(self, tx: SyncSender, shared: Arc) -> Proxy { + fn into_proxy(self, tx: SyncSender, shared: Arc, memory: MemoryServices) -> Proxy { Proxy { tx, shared, + memory, seen: RecentIds::default(), kar_configured: self.kar_configured, mtp_configured: self.mtp_configured, @@ -89,14 +92,16 @@ pub(super) fn spawn_backend_configured( let shared = Arc::new(Shared { ready: AtomicBool::new(false), shutdown: AtomicBool::new(false), active: Mutex::new(None) }); let facts = proxy_facts(&config, &selection); - let worker_shared = Arc::clone(&shared); + // The memory services of this engine: one governor, installed by the first Load, shared by every owner below. + let memory = MemoryServices::new(); + let (worker_shared, proxy_memory) = (Arc::clone(&shared), memory.clone()); let instance = INSTANCE.fetch_add(1, Ordering::Relaxed); thread::Builder::new() .name("leleka-cuda-owner".into()) .spawn(move || { let _guard = OwnerGuard(Arc::clone(&worker_shared)); - OwnerThread { selection, observer, commands: rx, config, shared: &worker_shared, instance }.run(); + OwnerThread { selection, observer, commands: rx, config, shared: &worker_shared, instance, memory }.run(); }) .map_err(|_| unavailable("native owner thread unavailable"))?; - Ok(Box::new(facts.into_proxy(tx, shared))) + Ok(Box::new(facts.into_proxy(tx, shared, proxy_memory))) } diff --git a/crates/engine-qwen35-cuda/src/backend/tests.rs b/crates/engine-qwen35-cuda/src/backend/tests.rs index 05cf4462..60f1cddd 100644 --- a/crates/engine-qwen35-cuda/src/backend/tests.rs +++ b/crates/engine-qwen35-cuda/src/backend/tests.rs @@ -258,6 +258,7 @@ fn native_proxy(tx: SyncSender, shared: Arc) -> Proxy { Proxy { tx, shared, + memory: leleka_memory::MemoryServices::new(), seen: RecentIds::default(), kar_configured: false, mtp_configured: false, @@ -337,6 +338,7 @@ fn preview_and_the_auto_fallback_are_refused_without_the_preview_path_feature() mtp_source: None, kar_expert_source: None, experimental: Default::default(), + verification: Default::default(), }; // No KAR/MTP source: `auto` cannot start the Original path and would have fallen back to the preview path. for mode in [OriginalServeMode::Preview, OriginalServeMode::Auto] { diff --git a/crates/engine-qwen35-cuda/src/conversation/memory.rs b/crates/engine-qwen35-cuda/src/conversation/memory.rs index 739c2013..cdf91c09 100644 --- a/crates/engine-qwen35-cuda/src/conversation/memory.rs +++ b/crates/engine-qwen35-cuda/src/conversation/memory.rs @@ -9,10 +9,10 @@ pub use leleka_engine_core::memory::{mem_available, memory_admit}; /// Available host physical memory right now; `None` when unknown (any /// non-Linux target, unreadable or malformed `/proc/meminfo`). -pub fn available_memory() -> Option { +pub fn available_memory(memory: &leleka_memory::MemoryServices) -> Option { // with the memory governor installed: MemAvailable limited by the cgroup headroom, the same number every guard // decides on - if let Some(governor) = leleka_memory::Governor::global() { + if let Some(governor) = memory.governor() { return governor.available_now(); } #[cfg(target_os = "linux")] @@ -106,7 +106,7 @@ mod tests { #[test] fn provider_returns_bytes_or_unknown() { - let available = available_memory(); + let available = available_memory(&leleka_memory::MemoryServices::new()); assert!(available.is_none() || memory_admit(available, 0, 0)); #[cfg(not(any(target_os = "linux", target_os = "windows")))] assert_eq!(available, None); diff --git a/crates/engine-qwen35-cuda/src/conversation/original.rs b/crates/engine-qwen35-cuda/src/conversation/original.rs index a6b5195e..b80a91c6 100644 --- a/crates/engine-qwen35-cuda/src/conversation/original.rs +++ b/crates/engine-qwen35-cuda/src/conversation/original.rs @@ -167,6 +167,8 @@ pub fn session_spec(facts: &OriginalSessionFacts) -> SessionSpec { /// A session whose bytes are reached through the CUDA-driver owners. pub struct OriginalDevice { pub session: T, + /// The memory services whose governor the free-memory reading follows. + pub memory: leleka_memory::MemoryServices, } fn text(e: leleka_cuda_driver::Error) -> String { @@ -213,7 +215,7 @@ impl SessionDevice for Origina } fn available_memory(&mut self) -> Option { - super::memory::available_memory() + super::memory::available_memory(&self.memory) } fn set_steering(&mut self, enabled: bool) { diff --git a/crates/engine-qwen35-cuda/src/memory_governor.rs b/crates/engine-qwen35-cuda/src/memory_governor.rs index 07f8bcf9..a88c785e 100644 --- a/crates/engine-qwen35-cuda/src/memory_governor.rs +++ b/crates/engine-qwen35-cuda/src/memory_governor.rs @@ -1,19 +1,19 @@ //! The runtime's side of `leleka-memory`: builds the startup plan from what this process is about to allocate, installs -//! the process-wide governor, locks/guards the sealed KAR memfd, brackets the stack's opening steps with the load -//! ledger, registers the allocation classes in the inventory and hands the report to the status surface. +//! the engine's governor (one per engine, held by its `MemoryServices`), locks/guards the sealed KAR memfd, brackets +//! the stack's opening steps with the load ledger, registers the allocation classes in the inventory and hands the +//! report to the status surface. //! //! The decisions live in `leleka-memory` (pure, tested on fixtures); this file only gathers the facts and applies the -//! answers. +//! answers. use crate::settings::{EnvSource, Settings}; use leleka_backend_api::BackendError; use leleka_memory::ledger::{DeviceSample, OpenStage}; use leleka_memory::{ - CacheWish, Entry, FixedItem, Governor, GovernorConfig, HostFacts, KarForm, PlanInput, SamplerGuard, Space, + CacheWish, Entry, FixedItem, Governor, GovernorConfig, HostFacts, KarForm, MemoryServices, PlanInput, Space, VramFacts, When, }; use leleka_memory_os::{HostProc, real_governor}; -use std::sync::Mutex; mod page_cache; pub(crate) use page_cache::drop_file_cache; @@ -49,7 +49,6 @@ pub(crate) struct StartArgs { pub prompt_cache: usize, } -static SAMPLER: Mutex> = Mutex::new(None); /// RAM kept for the hot part of a file-mapped expert bank (set by `startup`, read when the prefix budget is resolved at /// open). static MAPPED_WORKING_SET: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -66,9 +65,9 @@ fn refusal_error(text: String) -> BackendError { BackendError { code: leleka_backend_api::ErrorCode::ResourceExhausted, message: text, retryable: false } } -/// Create (once) and return the process-wide governor. -pub(crate) fn install(laptop: bool, settings: &Settings) -> Result<&'static Governor, BackendError> { - if let Some(g) = Governor::global() { +/// Create (once) and return the governor of `memory`, and start its sampler. +pub(crate) fn install(memory: &MemoryServices, laptop: bool, settings: &Settings) -> Result { + if let Some(g) = memory.governor() { return Ok(g); } let facts = HostFacts::probe(&HostProc::default()); @@ -78,12 +77,7 @@ pub(crate) fn install(laptop: bool, settings: &Settings) -> Result<&'static Gove message: e, retryable: false, })?; - let g = real_governor(cfg).install(); - let mut sampler = SAMPLER.lock().unwrap_or_else(|p| p.into_inner()); - if sampler.is_none() { - *sampler = Some(g.spawn_sampler()); - } - Ok(g) + Ok(memory.install(real_governor(cfg))) } /// The expert bank's line of the fixed footprint; also publishes the mapped working set the cache budgets subtract. @@ -157,21 +151,29 @@ fn prefix_wish(prefix: Option>) -> CacheWish { } /// Plan the host budget before a single model byte is read; refuse with numbers when the fixed footprint does not fit. -pub(crate) fn startup(args: &StartArgs, settings: &Settings) -> Result<&'static Governor, BackendError> { +pub(crate) fn startup( + memory: &MemoryServices, + args: &StartArgs, + settings: &Settings, +) -> Result { let laptop = args.expert_source_mapped || args.kar_file_backed == Some(true); - let g = install(laptop, settings)?; + let g = install(memory, laptop, settings)?; + g.startup(&plan_input(&g, args, settings)).map_err(|r| refusal_error(r.to_string()))?; + Ok(g) +} + +/// What the startup plan is made from: the fixed footprint, the host as it reads now and the operator's cache wishes. +fn plan_input(g: &Governor, args: &StartArgs, settings: &Settings) -> PlanInput { let fixed = fixed_items(g, args, settings); - let kar = kar_form(args); - let host = g.probe(); let resident_complement = settings .serve .resident_budget_gib .filter(|_| args.expert_source_mapped) .map(|v| (v * (1u64 << 30) as f64) as u64); - let input = PlanInput { - host, + PlanInput { + host: g.probe(), policy: g.policy(), - kar, + kar: kar_form(args), fixed, prefix: prefix_wish(args.prefix), conversation_checkpoints: if args.prefix.is_some_and(|p| p != Some(0)) { 0 } else { args.prompt_cache as u64 }, @@ -180,9 +182,7 @@ pub(crate) fn startup(args: &StartArgs, settings: &Settings) -> Result<&'static vram: None, vram_budget: args.gpu_budget_bytes, vram_fixed_estimate: None, - }; - g.startup(&input).map_err(|r| refusal_error(r.to_string()))?; - Ok(g) + } } /// Lock the sealed memfd (when the limits allow) and keep the residency guard on it; a no-op for the file-backed @@ -252,10 +252,13 @@ pub(crate) fn check_vram( } /// A ledger stage around one opening step of the stack (a no-op without a governor). -pub(crate) struct Stage(Option<(&'static Governor, OpenStage)>); +pub(crate) struct Stage(Option<(Governor, OpenStage)>); -pub(crate) fn begin(name: &str, context: Option<&leleka_cuda_driver::Context<'_>>) -> Stage { - Stage(Governor::global().map(|g| (g, g.ledger().begin(name, g.source(), context.and_then(device_sample))))) +pub(crate) fn begin(memory: &MemoryServices, name: &str, context: Option<&leleka_cuda_driver::Context<'_>>) -> Stage { + Stage(memory.governor().map(|g| { + let open = g.ledger().begin(name, g.source(), context.and_then(device_sample)); + (g, open) + })) } pub(crate) fn end(stage: Stage, context: Option<&leleka_cuda_driver::Context<'_>>) { @@ -283,24 +286,24 @@ pub(crate) struct InventoryClass<'a> { } /// Register or update one inventory class (a no-op without a governor). -pub(crate) fn account(class: InventoryClass<'_>, bytes: u64) { - if let Some(g) = Governor::global() { +pub(crate) fn account(memory: &MemoryServices, class: InventoryClass<'_>, bytes: u64) { + if let Some(g) = memory.governor() { let InventoryClass { component, class, space, when, formula } = class; g.inventory().set(Entry::new(component, class, space, when, formula).bytes(bytes)); } } /// Update the bytes of a registered class. -pub(crate) fn set_bytes(id: &str, bytes: u64) { - if let Some(g) = Governor::global() { +pub(crate) fn set_bytes(memory: &MemoryServices, id: &str, bytes: u64) { + if let Some(g) = memory.governor() { g.inventory().set_bytes(id, bytes); } } /// After the stack opened: compare the plan with the real post-load availability (logged, and in the report as /// `plan_check`). -pub(crate) fn post_open() { - if let Some(g) = Governor::global() { +pub(crate) fn post_open(memory: &MemoryServices) { + if let Some(g) = memory.governor() { g.note_post_load(g.available_now()); } } @@ -308,20 +311,21 @@ pub(crate) fn post_open() { /// The report, freshly rendered (`None` before the governor exists). The status surface serves the sampler's published /// copy; the smokes want the state at this very moment. #[allow(dead_code)] -pub(crate) fn report() -> Option { - let g = Governor::global()?; +pub(crate) fn report(memory: &MemoryServices) -> Option { + let g = memory.governor()?; g.publish(); - leleka_memory::published_report() + g.published_report() } /// The `auto` prefix budget at stack open, or the explicit one clamped to what the host has now. pub(crate) fn resolve_prefix_budget( + memory: &MemoryServices, budget: crate::qwen_forward::original_serve_stack::PrefixBudget, available: Option, complement_pending: u64, ) -> Option { use crate::qwen_forward::original_serve_stack::PrefixBudget as View; - let g = Governor::global()?; + let g = memory.governor()?; let policy = g.policy(); let complement_pending = complement_pending.saturating_add(MAPPED_WORKING_SET.load(std::sync::atomic::Ordering::Acquire)); @@ -374,8 +378,8 @@ fn budget_line( } /// Room for the page-locked resident complement: available memory less the soft floor and the reserve. -pub(crate) fn complement_room(available: u64) -> u64 { - match Governor::global() { +pub(crate) fn complement_room(memory: &MemoryServices, available: u64) -> u64 { + match memory.governor() { Some(g) => { let p = g.policy(); available.saturating_sub(p.soft_floor + p.reserve) diff --git a/crates/engine-qwen35-cuda/src/memory_governor/page_cache.rs b/crates/engine-qwen35-cuda/src/memory_governor/page_cache.rs index d99e075b..cab31a1d 100644 --- a/crates/engine-qwen35-cuda/src/memory_governor/page_cache.rs +++ b/crates/engine-qwen35-cuda/src/memory_governor/page_cache.rs @@ -1,13 +1,14 @@ //! Page-cache release after the load (`drop_file_cache`): the kernel gets the pages of the shard files back once the //! weights are on the device. -use super::{Governor, HostFacts, HostProc}; +use super::{HostFacts, HostProc}; +use leleka_memory::MemoryServices; /// Give back the page cache the load created: the shards were read once to verify and to copy the resident bank, and /// nothing reads those pages again (the bank is a RAM copy). Left in place they are the cache pressure that pushed the /// sealed memfd into swap. Clean pages only, `POSIX_FADV_DONTNEED`; best effort. #[cfg(target_os = "linux")] -pub(crate) fn drop_file_cache(paths: &[&std::path::Path]) { +pub(crate) fn drop_file_cache(memory: &MemoryServices, paths: &[&std::path::Path]) { let before = HostFacts::probe(&HostProc::default()).meminfo.cached; for path in paths { if let Ok(file) = std::fs::File::open(path) { @@ -15,7 +16,7 @@ pub(crate) fn drop_file_cache(paths: &[&std::path::Path]) { } } let after = HostFacts::probe(&HostProc::default()).meminfo.cached; - if let (Some(g), Some(b), Some(a)) = (Governor::global(), before, after) { + if let (Some(g), Some(b), Some(a)) = (memory.governor(), before, after) { g.log(&format!("page cache of the model shards released: {} MiB -> {} MiB cached", b >> 20, a >> 20)); } } @@ -23,4 +24,4 @@ pub(crate) fn drop_file_cache(paths: &[&std::path::Path]) { /// No `posix_fadvise(DONTNEED)` equivalent is used on Windows; the mapped form (the one Windows serves) never copies /// the shards. #[cfg(target_os = "windows")] -pub(crate) fn drop_file_cache(_paths: &[&std::path::Path]) {} +pub(crate) fn drop_file_cache(_memory: &MemoryServices, _paths: &[&std::path::Path]) {} diff --git a/crates/engine-qwen35-cuda/src/model_binding/kar_ple_source/load_pinned_inherited_archive.rs b/crates/engine-qwen35-cuda/src/model_binding/kar_ple_source/load_pinned_inherited_archive.rs index 2f47d3a4..dd65c96d 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/kar_ple_source/load_pinned_inherited_archive.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/kar_ple_source/load_pinned_inherited_archive.rs @@ -1,6 +1,10 @@ //! Loads the verified PLE artifact from the inherited archive: the read handle, the startup log line of what was read, //! and the row packets and readers the PLE cache takes its rows from. Windows keeps only the file-backed form. +#[cfg(target_os = "windows")] +use super::win_archive; +use leleka_model_format::verify_stamp::VerifyPolicy; + use super::{ BindingIdentity, File, InheritedKarArchive, InputBindingError, InputResult, KarError, KarPleBinding, KarRowPacket, KarRowReader, LoadPhase, NATIVE_DIGESTS, PINNED_ARCHIVE_BYTES, PLE_ROWS, PROVENANCE_DIGEST, RefCell, @@ -8,8 +12,6 @@ use super::{ }; #[cfg(target_os = "linux")] use super::{open_sealed_archive_fd, reopen_read_only_archive, verify_open_provenance}; -#[cfg(target_os = "windows")] -use super::win_archive; /// The read handle of the inherited archive: a read-only reopen of the file, or the sealed memfd itself. #[cfg(target_os = "linux")] @@ -24,7 +26,10 @@ fn open_archive_reader(source: &InheritedKarArchive) -> InputResult { } #[cfg(target_os = "linux")] -pub(crate) fn load_pinned_inherited_archive(source: &InheritedKarArchive) -> InputResult { +pub(crate) fn load_pinned_inherited_archive( + source: &InheritedKarArchive, + verify: &VerifyPolicy, +) -> InputResult { let profile = pinned_profile().map_err(|e| input_failure(LoadPhase::Profile, e))?; let reader = open_archive_reader(source)?; verify_open_provenance(&source.provenance, PROVENANCE_DIGEST) @@ -33,7 +38,7 @@ pub(crate) fn load_pinned_inherited_archive(source: &InheritedKarArchive) -> Inp 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. let Some(sparse) = source.sparse.as_ref() else { - let artifact = VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), profile) + let artifact = VerifiedKarPleArtifact::verify_under(inspection.into_owner_controlled(), profile, verify) .map_err(|e| kar_failure(LoadPhase::Verify, e))?; log_startup_read(source, &artifact); return Ok(artifact); @@ -70,7 +75,10 @@ pub(super) fn log_startup_read(source: &InheritedKarArchive, artifact: &Verified /// Windows: only the file-backed form exists (`open_read_only_file`); the archive is shared read-only while open. #[cfg(target_os = "windows")] -pub(crate) fn load_pinned_inherited_archive(source: &InheritedKarArchive) -> InputResult { +pub(crate) fn load_pinned_inherited_archive( + source: &InheritedKarArchive, + verify: &VerifyPolicy, +) -> InputResult { let profile = pinned_profile().map_err(|e| input_failure(LoadPhase::Profile, e))?; if !source.file_backed { return Err(input_failure(LoadPhase::Source, InputBindingError::UnsupportedKind)); @@ -81,14 +89,17 @@ pub(crate) fn load_pinned_inherited_archive(source: &InheritedKarArchive) -> Inp .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))?; - let artifact = VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), profile) + let artifact = VerifiedKarPleArtifact::verify_under(inspection.into_owner_controlled(), profile, verify) .map_err(|e| kar_failure(LoadPhase::Verify, e))?; log_startup_read(source, &artifact); Ok(artifact) } #[cfg(not(any(target_os = "linux", target_os = "windows")))] -pub(crate) fn load_pinned_inherited_archive(_source: &InheritedKarArchive) -> InputResult { +pub(crate) fn load_pinned_inherited_archive( + _source: &InheritedKarArchive, + _verify: &VerifyPolicy, +) -> InputResult { Err(InputBindingError::UnsupportedKind) } impl KarRowPacket { diff --git a/crates/engine-qwen35-cuda/src/model_binding/kar_ple_source/pinned_profile.rs b/crates/engine-qwen35-cuda/src/model_binding/kar_ple_source/pinned_profile.rs index d4414ba2..b8cc9152 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/kar_ple_source/pinned_profile.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/kar_ple_source/pinned_profile.rs @@ -1,13 +1,15 @@ //! The pinned KAR PLE profile: the conversion receipts it expects, the partition of the rows, and the verification of //! the archive against them. Linux freezes a private inode before inspection; other platforms refuse the path form. +#[cfg(any(target_os = "linux", all(test, target_os = "macos")))] +use super::private_copy; +use leleka_model_format::verify_stamp::VerifyPolicy; + use super::{ ARCHIVE_DIGEST, File, InheritedKarArchive, InputBindingError, InputResult, KarPlePartProvenance, KarPleProfile, KarPleProfileSpec, LoadPhase, NATIVE_DIGESTS, PART0_F32_DIGEST, PART1_F32_DIGEST, PROVENANCE_DIGEST, Path, VIRTUAL_F32_DIGEST, VerifiedKarPleArtifact, error, input_failure, kar_failure, }; -#[cfg(any(target_os = "linux", all(test, target_os = "macos")))] -use super::private_copy; /// Candidate expectations from independently verified v4 conversion receipts /// d51353be and 0d8a4a52. Construction reads no archive and grants no serving @@ -51,7 +53,11 @@ pub(super) fn pinned_profile_spec() -> InputResult { /// Freeze a fresh private inode before inspection; never admit the shared source /// inode as owner-controlled. Only the Linux provisioning path is supported. #[cfg(target_os = "linux")] -pub(crate) fn load_pinned_archive(source: &Path, owner_root: &Path) -> InputResult { +pub(crate) fn load_pinned_archive( + source: &Path, + owner_root: &Path, + verify: &VerifyPolicy, +) -> InputResult { let profile = pinned_profile().map_err(|e| input_failure(LoadPhase::Profile, e))?; let mut source_file = private_copy::open_regular(source, Some(55_295_529_472)).map_err(|e| input_failure(LoadPhase::Source, e))?; @@ -62,7 +68,7 @@ pub(crate) fn load_pinned_archive(source: &Path, owner_root: &Path) -> InputResu leleka_model_format::kar::KarInspection::inspect(reader).map_err(|e| kar_failure(LoadPhase::Inspect, e))?; // freeze() returns an owner-controlled immutable snapshot: Linux verifies // irrevocable seals; the macOS test path closes its writer and detaches names. - VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), profile) + VerifiedKarPleArtifact::verify_under(inspection.into_owner_controlled(), profile, verify) .map_err(|e| kar_failure(LoadPhase::Verify, e)) } @@ -106,7 +112,11 @@ fn hash_stream(file: &mut File, length: u64) -> InputResult<(sha2::Sha256, u64)> } #[cfg(not(target_os = "linux"))] -pub(crate) fn load_pinned_archive(_source: &Path, _owner_root: &Path) -> InputResult { +pub(crate) fn load_pinned_archive( + _source: &Path, + _owner_root: &Path, + _verify: &VerifyPolicy, +) -> InputResult { Err(InputBindingError::UnsupportedKind) } diff --git a/crates/engine-qwen35-cuda/src/model_binding/weight_binding/model_binding.rs b/crates/engine-qwen35-cuda/src/model_binding/weight_binding/model_binding.rs index 5b6817d3..7f268be3 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/weight_binding/model_binding.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/weight_binding/model_binding.rs @@ -6,6 +6,7 @@ use super::{ InputResult, ModelBinding, MtpWeights, PLE_ROW_VALUES, PLE_ROWS, Qwen4ExpArtifact, Rc, RefCell, TensorRole, VOCABULARY, bind_layers, decode, mtp, validate_ple_descriptor, }; +use leleka_model_format::verify_stamp::VerifyPolicy; impl ModelBinding { pub(crate) fn bind() -> Result { @@ -75,10 +76,10 @@ impl ModelBinding { /// The private loader retains an exclusively owned unnamed read-only inode. pub(crate) fn from_artifact_with_pinned_kar_ple( artifact: Qwen4ExpArtifact, - source: &std::path::Path, - owner_root: &std::path::Path, + (source, owner_root): (&std::path::Path, &std::path::Path), + verify: &VerifyPolicy, ) -> InputResult { - let kar = super::super::kar_ple_source::load_pinned_archive(source, owner_root)?; + let kar = super::super::kar_ple_source::load_pinned_archive(source, owner_root, verify)?; Self::from_artifact_with_kar_ple(artifact, kar) } pub(crate) fn expert_count(&self) -> u32 { @@ -88,8 +89,9 @@ impl ModelBinding { pub(crate) fn from_artifact_with_inherited_kar_ple( artifact: Qwen4ExpArtifact, source: &super::super::kar_ple_source::InheritedKarArchive, + verify: &VerifyPolicy, ) -> InputResult { - let kar = super::super::kar_ple_source::load_pinned_inherited_archive(source)?; + let kar = super::super::kar_ple_source::load_pinned_inherited_archive(source, verify)?; Self::from_artifact_with_kar_ple(artifact, kar) } @@ -120,12 +122,11 @@ impl ModelBinding { /// Both providers are admitted before this fresh binding is published. pub(crate) fn from_artifact_with_pinned_kar_mtp( artifact: Qwen4ExpArtifact, - kar_source: &std::path::Path, - kar_root: &std::path::Path, - mtp_source: &std::path::Path, - mtp_root: &std::path::Path, + kar: (&std::path::Path, &std::path::Path), + (mtp_source, mtp_root): (&std::path::Path, &std::path::Path), + verify: &VerifyPolicy, ) -> InputResult { - let mut binding = Self::from_artifact_with_pinned_kar_ple(artifact, kar_source, kar_root)?; + let mut binding = Self::from_artifact_with_pinned_kar_ple(artifact, kar, verify)?; let weights = MtpWeights::load_pinned(&binding, mtp_source, mtp_root)?; weights.validate_binding(&binding)?; binding.mtp = Some(weights); @@ -143,8 +144,9 @@ impl ModelBinding { source: &super::super::kar_ple_source::InheritedKarArchive, mtp_source: &std::path::Path, mtp_root: &std::path::Path, + verify: &VerifyPolicy, ) -> InputResult { - let mut binding = Self::from_artifact_with_inherited_kar_ple(artifact, source)?; + let mut binding = Self::from_artifact_with_inherited_kar_ple(artifact, source, verify)?; crate::load_clock::lap("kar_inspect_verify_and_bind"); let weights = MtpWeights::load_pinned(&binding, mtp_source, mtp_root)?; weights.validate_binding(&binding)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/reset_replay_proof.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/reset_replay_proof.rs index 44415ef3..f779ee97 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/reset_replay_proof.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/reset_replay_proof.rs @@ -279,8 +279,8 @@ fn pinned_model_binding() -> ModelBinding { let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned reset/replay artifact binding failed"); ModelBinding::from_artifact_with_pinned_kar_ple( artifact, - &path("LELEKA_STRA169_KAR_ARCHIVE"), - &path("LELEKA_STRA169_KAR_STAGING"), + (&path("LELEKA_STRA169_KAR_ARCHIVE"), &path("LELEKA_STRA169_KAR_STAGING")), + &leleka_model_format::verify_stamp::VerifyPolicy::default(), ) .expect("pinned reset/replay KAR binding failed") } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/batch_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/batch_gpu.rs index 64675498..47e7230e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/batch_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/batch_gpu.rs @@ -78,6 +78,7 @@ fn open_binding() -> (ModelBinding, InheritedKarArchive) { &inherited, &path("LELEKA_STRA169_MTP_PACK"), &path("LELEKA_STRA169_MTP_STAGING"), + &leleka_model_format::verify_stamp::VerifyPolicy::default(), ) .unwrap(); (binding, inherited) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/oracle_capture.rs b/crates/engine-qwen35-cuda/src/qwen_forward/oracle_capture.rs index b0a8dff7..aa62854a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/oracle_capture.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/oracle_capture.rs @@ -294,16 +294,18 @@ fn pinned_binding() -> ModelBinding { ) .expect("shard1"); let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact"); + let verify = leleka_model_format::verify_stamp::VerifyPolicy::default(); if let Some(fd) = std::env::var_os("LELEKA_STRA169_KAR_FD") { let fd = fd.to_str().expect("fd utf8").parse::().expect("operator fd"); let source = crate::backend::InheritedKarArchive::open(fd, operator_path("LELEKA_STRA169_KAR_PROVENANCE")) .expect("sealed source"); - ModelBinding::from_artifact_with_inherited_kar_ple(artifact, &source).expect("sealed pinned KAR") + ModelBinding::from_artifact_with_inherited_kar_ple(artifact, &source, &verify).expect("sealed pinned KAR") } else { + let archive = operator_path("LELEKA_STRA169_KAR_ARCHIVE"); ModelBinding::from_artifact_with_pinned_kar_ple( artifact, - &operator_path("LELEKA_STRA169_KAR_ARCHIVE"), - &operator_path("LELEKA_STRA169_KAR_STAGING"), + (&archive, &operator_path("LELEKA_STRA169_KAR_STAGING")), + &verify, ) .expect("pinned KAR") } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/open_tier.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/open_tier.rs index 7d4fb30d..0486b9b3 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/open_tier.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/open_tier.rs @@ -9,6 +9,7 @@ use super::{ VERIFIER_ASSEMBLY_MIB, driver_error, original_cache_startup, span_cache_enabled, }; use leleka_cuda_driver::RefillBatchOptions; +use leleka_memory::MemoryServices; /// generate.cpp startup of the tier for the serve stack: size and open the cache after every other owner, /// fill it from the profile through the registered bank (blocking, rank order; per-layer skips a full @@ -18,8 +19,8 @@ pub(in crate::qwen_forward) fn open_tier<'ctx>( binding: &ModelBinding, context: &'ctx Context<'ctx>, moe: &MoeWeightCache<'ctx>, - config: &ExpertTierConfig, - prefill_capacity: usize, + (config, prefill_capacity): (&ExpertTierConfig, usize), + memory: &MemoryServices, ) -> Result, usize)>> { config.validate()?; if !config.enabled() { @@ -33,7 +34,7 @@ pub(in crate::qwen_forward) fn open_tier<'ctx>( let Some(mut cache) = original_cache_startup::open(binding, context, options, profile.as_ref(), 0)? else { return Ok(None); }; - let filled = fill_and_pin(binding, moe, (&bank, &mut cache), (config, profile.as_ref()))?; + let filled = fill_and_pin(binding, moe, (&bank, &mut cache), (config, profile.as_ref()), memory)?; Ok(Some((cache, filled))) } /// Fills the opened cache from a non-empty profile and pins the complement within the resident budget. @@ -42,11 +43,12 @@ fn fill_and_pin<'ctx>( moe: &MoeWeightCache<'ctx>, (bank, cache): (&Rc>, &mut OriginalExpertCache<'ctx>), (config, profile): (&ExpertTierConfig, Option<&OriginalRankedExperts>), + memory: &MemoryServices, ) -> Result { let Some(profile) = profile.filter(|p| !p.is_empty()) else { return Ok(0) }; let filled = fill_from_profile(binding, moe, bank, cache, profile)?; if config.resident_budget_gib > 0.0 && bank.pageable() { - pin_resident_complement(bank, cache, profile, config.resident_budget_gib)?; + pin_resident_complement(memory, bank, cache, profile, config.resident_budget_gib)?; } Ok(filled) } @@ -125,19 +127,21 @@ fn fill_ranked<'ctx>( Ok(filled) } +const GIB: f64 = 1_073_741_824.0; + /// generate.cpp `--resident-budget-gib N` over the low-RAM (file-mapped) bank: the experts the VRAM cache does /// not hold, in profile order, page-locked in RAM while they fit N GiB, clamped like /// `FileExpertSource::pin_cache_complement` to `MemAvailable` less the 4 GiB headroom and a 0.25 GiB margin. pub(super) fn pin_resident_complement( + memory: &MemoryServices, bank: &leleka_cuda_driver::MappedExpertBank<'_>, cache: &OriginalExpertCache<'_>, profile: &OriginalRankedExperts, budget_gib: f64, ) -> Result<()> { - const GIB: f64 = 1_073_741_824.0; let available = mem_available_bytes(); // the governor's soft floor + reserve (4 GiB headroom and a 0.25 GiB margin without one) - let room = crate::memory_governor::complement_room(available); + let room = crate::memory_governor::complement_room(memory, available); let budget = ((budget_gib * GIB) as u64).min(room); let ranked = ranked_complement(cache, profile); let started = leleka_obs::time::Clock::now(&leleka_obs::time::SystemClock); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs index 0cf7d521..a77910c7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs @@ -67,8 +67,8 @@ use std::{path::PathBuf, rc::Rc, time::Instant}; /// One timed, measured step of opening the stack: the load ledger records what it cost in host and device memory. macro_rules! staged { - ($name:expr, $ctx:expr, $body:expr) => {{ - let __stage = crate::memory_governor::begin($name, Some($ctx)); + ($memory:expr, $name:expr, $ctx:expr, $body:expr) => {{ + let __stage = crate::memory_governor::begin($memory, $name, Some($ctx)); let __result = $body; crate::memory_governor::end(__stage, Some($ctx)); __result @@ -112,6 +112,9 @@ const VOCABULARY: u32 = 248_320; /// Operator-visible choices of the stack. #[derive(Clone, Debug)] pub(crate) struct StackConfig { + /// The engine's memory services (the governor, its inventory and ledger): every owner of the stack asks them. + /// Empty (no governor) for a stack that is opened without a memory-governed start, as in the smokes. + pub(crate) memory: leleka_memory::MemoryServices, pub(crate) capacity: usize, /// The request ceiling (`--max-context`): at most the process serving cell count. pub(crate) max_context: i64, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/conversation.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/conversation.rs index b35b2b30..4ee7cc74 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/conversation.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/conversation.rs @@ -102,6 +102,10 @@ pub(super) trait ResumeDevice { fn restore_draft(&mut self, point: &Self::Point, resume: usize) -> Result<(), Error>; /// Live continuation: the session's recurrent state is settled and the draft ring stands at its position. fn live_in_step(&self) -> bool; + /// Host memory available now; unknown (`None`) unless the device reads it, and an unknown reading fails closed. + fn available_memory(&self) -> Option { + None + } } struct Saved

{ @@ -204,7 +208,7 @@ impl SessionEngine for Engine<'_, D> { } fn set_steering(&mut self, _enabled: bool) {} fn available_memory(&mut self) -> Option { - crate::conversation::memory::available_memory() + self.device.available_memory() } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_device_ports.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_device_ports.rs index 5ad70b4f..cf70c68c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_device_ports.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_device_ports.rs @@ -72,6 +72,9 @@ impl<'a, 'ctx> PrefixDevice for OriginalServeStack<'a, 'ctx> { } result } + fn available_memory(&self) -> Option { + crate::conversation::memory::available_memory(&self.config.memory) + } } impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/prefix.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/prefix.rs index adc7489b..9819ae35 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/prefix.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/prefix.rs @@ -98,9 +98,7 @@ pub(super) trait PrefixDevice { /// After `import`: re-anchor the draft ring at the state's snapshot and resynchronise the drafter. fn restore_draft(&mut self, state: &Self::State, resume: usize) -> Result<(), Error>; /// Host memory available now (`None` = unknown: insertion fails closed). - fn available_memory(&self) -> Option { - crate::conversation::memory::available_memory() - } + fn available_memory(&self) -> Option; } /// Where a request starts reading. @@ -154,6 +152,8 @@ struct Req { /// The policy, the store and the live-prefix bookkeeping, over the stack's payload types. pub(super) struct PrefixServe { cfg: PrefixConfig, + /// The engine's memory services: the governor whose shed directives and relief this cache follows. + memory: leleka_memory::MemoryServices, block_tokens: usize, namespace: u64, store: PrefixStore, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/prefix/prefix_config.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/prefix/prefix_config.rs index a293cd40..b69746f0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/prefix/prefix_config.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/prefix/prefix_config.rs @@ -54,14 +54,19 @@ impl PrefixConfig { /// 0.2 GiB, was refused at 8.9 GiB against a floor of 9.2 GiB, and turn 2 re-read 2,753 tokens from the last grid /// point). So a refusal is /// re-judged once after the governor hands the trimmable pages back. -pub(super) fn admission_reading(reading: Option, additional: u64, floor: u64) -> Option { +pub(super) fn admission_reading( + memory: &leleka_memory::MemoryServices, + reading: Option, + additional: u64, + floor: u64, +) -> Option { let needed = additional.saturating_add(floor); // unknown telemetry stays closed let Some(have) = reading else { return None }; if have >= needed { return reading; } - match leleka_memory::Governor::global() { + match memory.governor() { Some(governor) => governor.available_after_relief(needed).or(reading), None => reading, } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/prefix/prefix_serve/prefix_serve_after_phase_parking.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/prefix/prefix_serve/prefix_serve_after_phase_parking.rs index 99378cda..b4a1fd9f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/prefix/prefix_serve/prefix_serve_after_phase_parking.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/prefix/prefix_serve/prefix_serve_after_phase_parking.rs @@ -25,9 +25,9 @@ impl PrefixServe { ) -> Result { // a long prefill can outlast a change of memory pressure: follow the governor between chunks, not only // between requests - if let Some(governor) = leleka_memory::Governor::global() { + if let Some(governor) = self.memory.governor() { let directive = governor.directive(self.store.bytes() as u64); - self.apply_shed(directive.prefix_budget, governor); + self.apply_shed(directive.prefix_budget, &governor); } if self.live.len() <= end { let have = self.live.len(); @@ -58,7 +58,7 @@ impl PrefixServe { let verdict = self.timed(|store| store.consider(&prompt[..end], end == last_grid, est_state, est_block)); let candidate = self.resolve(verdict, Point::Grid(end))?; let additional = (est_state + candidate.missing.len() * est_block) as u64; - let available = admission_reading(device.available_memory(), additional, self.cfg.memory_floor); + let available = admission_reading(&self.memory, device.available_memory(), additional, self.cfg.memory_floor); if !budget::admit_growth(available, additional, self.cfg.memory_floor) { self.store.abort(candidate); self.note = Some(format!( @@ -257,7 +257,7 @@ impl PrefixServe { let verdict = self.timed(|store| store.consider_tail(tokens, true, est_state, est_block)); let candidate = self.resolve(verdict, Point::Tail(tokens.len()))?; let additional = (est_state + candidate.missing.len() * est_block + est_block) as u64; - let available = admission_reading(device.available_memory(), additional, self.cfg.memory_floor); + let available = admission_reading(&self.memory, device.available_memory(), additional, self.cfg.memory_floor); let missing = candidate.missing.len(); if !budget::admit_growth(available, additional, self.cfg.memory_floor) { self.store.abort(candidate); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/prefix/prefix_serve/store_control.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/prefix/prefix_serve/store_control.rs index 3710ff9f..a0aeb030 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/prefix/prefix_serve/store_control.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/prefix/prefix_serve/store_control.rs @@ -29,6 +29,7 @@ impl PrefixServe { let store = Self::new_store(&cfg, block_tokens, budget_bytes); Self { cfg, + memory: leleka_memory::MemoryServices::new(), block_tokens, namespace, store, @@ -64,6 +65,13 @@ impl PrefixServe { self } + /// The same cache under the memory services of the engine: its governor's directives shed it and its relief + /// re-judges a refused checkpoint. + pub(in super::super::super) fn with_memory(mut self, memory: leleka_memory::MemoryServices) -> Self { + self.memory = memory; + self + } + /// Milliseconds since this cache was built, on its clock (the store's wall-time scale for session retention). pub(in super::super::super) fn wall_ms(&self) -> u64 { self.clock.elapsed_ms() diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/prompt_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/prompt_chunk.rs index a31d10f5..483bd6ee 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/prompt_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/prompt_chunk.rs @@ -150,6 +150,9 @@ impl<'a, 'ctx> ResumeDevice for OriginalServeStack<'a, 'ctx> { && self.session.original_state_lag().is_none() && self.draft.in_step(self.binding, &self.session) } + fn available_memory(&self) -> Option { + crate::conversation::memory::available_memory(&self.config.memory) + } } impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_config.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_config.rs index ca1d59c7..74892860 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_config.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_config.rs @@ -33,6 +33,7 @@ impl StackConfig { pub(crate) fn new(max_context: i64) -> Self { let serve = &crate::settings::process().serve; Self { + memory: leleka_memory::MemoryServices::new(), capacity: DEFAULT_CAPACITY, max_context, rt_directory: None, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/open_cache_steps.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/open_cache_steps.rs index a37918c3..5b42aedb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/open_cache_steps.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/open_cache_steps.rs @@ -1,6 +1,8 @@ //! The caches `open` sizes from what the host has: the cross-session prefix cache (budget from the memory governor), //! the VRAM expert tier with its loan ladder, and the governor's startup inventory log. +use crate::qwen_forward::original_serve_stack::PrefixConfig; + use super::{ Context, LOAN_TIER_ROWS, LoanTier, ModelBinding, MoeWeightCache, OriginalExpertCache, PARKED_BYTES_PER_TOKEN, PARKED_STATE_ESTIMATE, PINNED_MODEL, PrefillLayoutOptions, PrefixServe, ServeFailure, StackBlock, StackConfig, @@ -11,18 +13,9 @@ use super::{ /// no budget. pub(super) fn open_prefix(config: &StackConfig) -> Option> { let prefix_config = config.prefix.as_ref()?; - let available = crate::conversation::memory::available_memory(); - // the budget comes from the memory governor (what is left above the floors), not from an independent default - let complement_pending = (config.expert_tier.resident_budget_gib.max(0.0) * (1u64 << 30) as f64) as u64; - let bytes = crate::memory_governor::resolve_prefix_budget(prefix_config.budget, available, complement_pending) - .unwrap_or_else(|| prefix_config.resolve_budget(available)); - let mut prefix_config = prefix_config.clone(); - if let Some(g) = leleka_memory::Governor::global() { - // stop admitting before anything has to be shed: soft floor + reserve (the real CRM session sat 4.4 GiB above - // a 3 GiB floor) - prefix_config.memory_floor = prefix_config.memory_floor.max(g.policy().admit_floor()); - } - let prefix_config = &prefix_config; + let available = crate::conversation::memory::available_memory(&config.memory); + let bytes = prefix_budget(config, prefix_config, available); + let prefix_config = &governed_floor(prefix_config, &config.memory); if bytes == 0 { operator_note(&format!( "prefix cache off (budget {:?}, available host memory {:?} MiB)", @@ -33,11 +26,31 @@ pub(super) fn open_prefix(config: &StackConfig) -> Option) -> u64 { + let complement_pending = (config.expert_tier.resident_budget_gib.max(0.0) * (1u64 << 30) as f64) as u64; + let memory = &config.memory; + crate::memory_governor::resolve_prefix_budget(memory, prefix_config.budget, available, complement_pending) + .unwrap_or_else(|| prefix_config.resolve_budget(available)) +} + +/// The prefix config with the floor the governor sets: stop admitting before anything has to be shed, at the soft +/// floor + reserve (the real CRM session sat 4.4 GiB above a 3 GiB floor). +fn governed_floor(prefix_config: &PrefixConfig, memory: &leleka_memory::MemoryServices) -> PrefixConfig { + let mut prefix_config = prefix_config.clone(); + if let Some(g) = memory.governor() { + prefix_config.memory_floor = prefix_config.memory_floor.max(g.policy().admit_floor()); + } + prefix_config +} + fn note_prefix_on(serve: &PrefixServe, bytes: u64, available: Option) { operator_note(&format!( "prefix cache on: block/grid {} tokens, budget {} MiB, state ~{} MiB + {} B per token, \ @@ -61,13 +74,7 @@ pub(super) fn open_expert_cache<'ctx>( layout: PrefillLayoutOptions, ) -> std::result::Result<(Option>, Option), ServeFailure> { let mut loan = None; - let tier_open = staged!( - "expert tier (VRAM slots + profile fill)", - context, - original_serve_residency::open_tier(binding, context, moe, &config.expert_tier, config.capacity) - .map_err(at("expert tier"))? - ); - let expert_cache = match tier_open { + let expert_cache = match open_tier_staged(binding, context, moe, config)? { Some((cache, filled)) => { if config.expert_tier.prefill_borrow && config.expert_tier.profile.is_some() { loan = @@ -84,6 +91,22 @@ pub(super) fn open_expert_cache<'ctx>( } /// The tier's adaptation settings on the operator log (an A/B arm that sets them can show the engine got them). +/// The tier's cache with its profile fill, as one measured opening step. +fn open_tier_staged<'ctx>( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + moe: &MoeWeightCache<'ctx>, + config: &StackConfig, +) -> std::result::Result, usize)>, ServeFailure> { + let tier = (&config.expert_tier, config.capacity); + Ok(staged!( + &config.memory, + "expert tier (VRAM slots + profile fill)", + context, + original_serve_residency::open_tier(binding, context, moe, tier, &config.memory).map_err(at("expert tier"))? + )) +} + fn note_tier_adaptation(tier: &original_serve_residency::ExpertTierConfig) { operator_note(&format!( "expert tier adaptation: every {} rounds, up to {} swaps", @@ -140,8 +163,8 @@ fn note_loan_ladder(loan_tiers: &[LoanTier], full: usize, capacity: usize) { } /// The governor's startup log: the inventory of allocation classes and the load ledger. -pub(super) fn log_open_inventory() { - if let Some(governor) = leleka_memory::Governor::global() { +pub(super) fn log_open_inventory(memory: &leleka_memory::MemoryServices) { + if let Some(governor) = memory.governor() { governor.log(&format!( "stack open; inventory of allocation classes (accounted by their owners): {}", diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/open_phase_steps.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/open_phase_steps.rs index cd6af9b2..74e37f21 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/open_phase_steps.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/open_phase_steps.rs @@ -111,14 +111,16 @@ pub(super) fn load_weights<'ctx>( ) -> std::result::Result, ServeFailure> { vram_note(context, "open begin"); let output = staged!( + &config.memory, "native head + embedding", context, OriginalNativeOutput::load(binding, context, NativeHeadDispatch::default(), true) .map_err(at("OriginalNativeOutput::load"))? ); - let embedding = staged!("embedding table", context, load_embedding(binding, context, &output)?); - let kar = staged!("KAR PLE cache", context, load_kar(binding, context)?); + let embedding = staged!(&config.memory, "embedding table", context, load_embedding(binding, context, &output)?); + let kar = staged!(&config.memory, "KAR PLE cache", context, load_kar(binding, context)?); let dense = staged!( + &config.memory, "dense weights", context, DenseWeightCache::new_original_prompt_capacity(binding, context, config.capacity) @@ -163,6 +165,7 @@ fn load_moe<'ctx>( layout: PrefillLayoutOptions, ) -> std::result::Result, ServeFailure> { let moe = staged!( + &config.memory, "MoE arena cache", context, MoeWeightCache::new_original_prompt_arena( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_memory_classes.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_memory_classes.rs index c68275e2..78ff2c3a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_memory_classes.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_memory_classes.rs @@ -6,6 +6,7 @@ use super::{ Result, SeedReport, ServeError, ServeOutcome, ServeRequest, TtftMarks, operator_note, original_serve_residency, original_serve_seed, prefill_bytes, run_request, }; +use crate::memory_governor::InventoryClass; // The formulas the inventory classes of `register_memory_classes` carry (reported next to their bytes). const KV_HOST_FORMULA: &str = @@ -48,12 +49,12 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { /// when the pressure is over), and the conversation checkpoints are dropped. Cheap: a few atomics when nothing /// changed. pub(in super::super) fn apply_memory_directive(&mut self) { - let Some(governor) = leleka_memory::Governor::global() else { return }; + let Some(governor) = self.config.memory.governor() else { return }; let used = self.prefix.as_ref().map_or(0, |p| p.bytes() as u64); let directive = governor.directive(used); if let Some(prefix) = self.prefix.as_mut() { let before = prefix.bytes(); - let freed = prefix.apply_shed(directive.prefix_budget, governor); + let freed = prefix.apply_shed(directive.prefix_budget, &governor); if freed > 0 { operator_note(&format!( "memory pressure ({}): prefix cache evicted {} MiB ({} -> {} MiB), budget {} MiB", @@ -76,17 +77,14 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { /// Keep the inventory's elastic classes current (the prefix store and the conversation checkpoints). pub(in super::super) fn note_memory(&self) { - if leleka_memory::Governor::global().is_none() { - return; - } + let Some(governor) = self.config.memory.governor() else { return }; if let Some(prefix) = self.prefix.as_ref() { - crate::memory_governor::set_bytes("prefix.store", prefix.bytes() as u64); - if let Some(g) = leleka_memory::Governor::global() { - g.note_prefix_used(prefix.bytes() as u64); - } + crate::memory_governor::set_bytes(&self.config.memory, "prefix.store", prefix.bytes() as u64); + governor.note_prefix_used(prefix.bytes() as u64); } if let Some(conversation) = self.conversation.as_ref() { crate::memory_governor::set_bytes( + &self.config.memory, "conversation.checkpoints", conversation.checkpoint_count() as u64 * crate::memory_governor::CHECKPOINT_BYTES, ); @@ -95,15 +93,19 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { /// Register the stack's allocation classes with the inventory (sizes from the owners' own formulas and counters). pub(in super::super) fn register_memory_classes(&self) { - let Some(governor) = leleka_memory::Governor::global() else { return }; - let _ = governor; + if self.config.memory.governor().is_none() { + return; + } self.register_kv_classes(); self.register_device_classes(); self.register_tier_classes(); self.register_elastic_classes(); } + /// Register or update one inventory class of the engine's governor (a no-op without one). + fn account(&self, class: InventoryClass<'_>, bytes: u64) { + crate::memory_governor::account(&self.config.memory, class, bytes); + } fn register_kv_classes(&self) { - use crate::memory_governor::{InventoryClass, account}; use leleka_memory::{Space, When}; if let Some(f) = self.config.kv_footprint() { let host_class = InventoryClass { @@ -113,7 +115,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { when: When::Startup, formula: KV_HOST_FORMULA, }; - account(host_class, f.pinned_host_bytes as u64); + self.account(host_class, f.pinned_host_bytes as u64); let window_class = InventoryClass { component: "kv", class: "vram_window", @@ -121,7 +123,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { when: When::Startup, formula: KV_WINDOW_FORMULA, }; - account(window_class, f.vram_bytes as u64); + self.account(window_class, f.vram_bytes as u64); let stage_class = InventoryClass { component: "kv", class: "prompt_stage", @@ -129,11 +131,10 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { when: When::Startup, formula: KV_STAGE_FORMULA, }; - account(stage_class, f.stage_bytes as u64); + self.account(stage_class, f.stage_bytes as u64); } } fn register_device_classes(&self) { - use crate::memory_governor::{InventoryClass, account}; use leleka_memory::{Space, When}; if let Ok(bytes) = prefill_bytes(self.tier.layout) { let (class, formula) = if self.tier.loan.is_some() { @@ -143,11 +144,10 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { }; let arena_class = InventoryClass { component: "prefill", class, space: Space::Device, when: When::Startup, formula }; - account(arena_class, if self.tier.loan.is_some() { 0 } else { bytes as u64 }); + self.account(arena_class, if self.tier.loan.is_some() { 0 } else { bytes as u64 }); } } fn register_tier_classes(&self) { - use crate::memory_governor::{InventoryClass, account}; use leleka_memory::{Space, When}; if let Some(cache) = self.expert_cache.as_ref() { let slots_class = InventoryClass { @@ -157,7 +157,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { when: When::Startup, formula: SLOTS_FORMULA, }; - account(slots_class, cache.bytes() as u64); + self.account(slots_class, cache.bytes() as u64); } let ple_class = InventoryClass { component: "ple", @@ -166,7 +166,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { when: When::Startup, formula: PLE_FORMULA, }; - account(ple_class, (PLE_HISTORY_BYTES + PLE_SCRATCH_BYTES) as u64); + self.account(ple_class, (PLE_HISTORY_BYTES + PLE_SCRATCH_BYTES) as u64); let total_class = InventoryClass { component: "context", class: "accounted_total", @@ -174,10 +174,9 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { when: When::Lazy, formula: TOTAL_FORMULA, }; - account(total_class, 0); + self.account(total_class, 0); } fn register_elastic_classes(&self) { - use crate::memory_governor::{InventoryClass, account}; use leleka_memory::{Space, When}; if let Some(prefix) = self.prefix.as_ref() { let store_class = InventoryClass { @@ -187,7 +186,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { when: When::Elastic, formula: STORE_FORMULA, }; - account(store_class, prefix.bytes() as u64); + self.account(store_class, prefix.bytes() as u64); } if self.conversation.is_some() { let checkpoints_class = InventoryClass { @@ -197,7 +196,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { when: When::Elastic, formula: CHECKPOINTS_FORMULA, }; - account(checkpoints_class, 0); + self.account(checkpoints_class, 0); } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_open.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_open.rs index 4f578b87..c0831ed9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_open.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_open.rs @@ -38,8 +38,8 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { let tier = open_tier(&ctx, &core.moe, &mut buffers.arena)?; let this = Self::assemble(Assembly { binding, context, config, prepared, core, buffers, tier }); this.register_memory_classes(); - crate::memory_governor::post_open(); - log_open_inventory(); + crate::memory_governor::post_open(&this.config.memory); + log_open_inventory(&this.config.memory); if let Some(line) = decode_graph_reuse::enabled_line(crate::settings::process().serve.decode_graph_reuse) { operator_text(line); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_open/open_phases.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_open/open_phases.rs index 365fc7cf..516f38bc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_open/open_phases.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_open/open_phases.rs @@ -64,7 +64,7 @@ pub(super) fn load_core<'a, 'ctx>( let (binding, context, config) = (ctx.binding, ctx.context, ctx.config); let weights = load_weights(binding, context, config, ctx.layout)?; let mut session = QwenSession::for_binding_on_shared_device(binding, shared); - let executor_stage = crate::memory_governor::begin("prompt executor + MTP drafter", Some(context)); + let executor_stage = crate::memory_governor::begin(&config.memory, "prompt executor + MTP drafter", Some(context)); let opening = ExecutorOpening::new(config, verifier.0, verifier.1); let opened = open_executor(binding, context, &opening, &weights, &mut session)?; let (executor, draft) = opened; @@ -82,24 +82,17 @@ pub(super) fn load_buffers<'a, 'ctx>( core: &mut Core<'ctx>, ) -> std::result::Result, ServeFailure> { let (binding, context, config) = (ctx.binding, ctx.context, ctx.config); - let tier = config.expert_tier.enabled(); - let arena = staged!( - "prefill arena", - context, - if tier { - None - } else { - Some(context.original_prefill_arena(ctx.layout).map_err(at("original_prefill_arena"))?) - } - ); + let arena = staged!(&config.memory, "prefill arena", context, prefill_arena(ctx)?); vram_note(context, "before cache"); let history = staged!( + &config.memory, "penalty history", context, OriginalNativePenaltyHistory::new(binding, context).map_err(at("OriginalNativePenaltyHistory::new"))? ); let (ple_history, ple_scratch) = ple_buffers(context)?; let pool = staged!( + &config.memory, "CPU expert pool", context, CpuExpertPool::new(binding, config.cpu_workers).map_err(at("CpuExpertPool::new"))? @@ -108,6 +101,16 @@ pub(super) fn load_buffers<'a, 'ctx>( Ok(Buffers { arena, history, ple_history, ple_scratch, pool, empty_session, empty_draft }) } +/// The prompt path's own arena; with the expert tier on it is opened after the tier instead. +fn prefill_arena<'ctx>( + ctx: &OpenCtx<'_, '_, 'ctx>, +) -> std::result::Result>, ServeFailure> { + if ctx.config.expert_tier.enabled() { + return Ok(None); + } + Ok(Some(ctx.context.original_prefill_arena(ctx.layout).map_err(at("original_prefill_arena"))?)) +} + fn ple_buffers<'ctx>( context: &'ctx Context<'ctx>, ) -> std::result::Result<(DeviceRef<'ctx>, DeviceRef<'ctx>), ServeFailure> { @@ -120,13 +123,15 @@ fn empty_checkpoints<'ctx>( ctx: &OpenCtx<'_, '_, 'ctx>, core: &mut Core<'ctx>, ) -> std::result::Result<(OriginalSessionCheckpoint<'ctx>, OriginalDraftCheckpoint), ServeFailure> { - let (binding, context) = (ctx.binding, ctx.context); + let (binding, context, memory) = (ctx.binding, ctx.context, &ctx.config.memory); let empty_session = staged!( + memory, "empty-prompt session checkpoint", context, core.executor.checkpoint_session(binding, &mut core.session).map_err(at("checkpoint_session"))? ); let empty_draft = staged!( + memory, "empty-prompt draft checkpoint", context, core.draft.checkpoint(binding, &core.session).map_err(at("draft.checkpoint"))? @@ -156,6 +161,7 @@ pub(super) fn open_tier<'ctx>( .unwrap_or_default(); if arena.is_none() && loan.is_none() { *arena = Some(staged!( + &config.memory, "prefill arena (after the expert tier)", context, context.original_prefill_arena(layout).map_err(at("original_prefill_arena"))? diff --git a/desktop-core/src/bin/leleka-inference-evaluation.rs b/desktop-core/src/bin/leleka-inference-evaluation.rs index e69d8e06..16832a71 100644 --- a/desktop-core/src/bin/leleka-inference-evaluation.rs +++ b/desktop-core/src/bin/leleka-inference-evaluation.rs @@ -105,6 +105,7 @@ fn native_config(base: &BaseArguments<'_>, sources: OperatorSources) -> Result; #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), Failure> { let mut args: Vec = std::env::args().skip(1).collect(); - let (verify_only, sparse_extents) = take_verification_flags(&mut args)?; + let flags = take_verification_flags(&mut args)?; if args.as_slice() == ["--help"] { println!("{HELP}"); return Ok(()); } - let operator = parse_operator(&args, sparse_extents)?; - if verify_only { + let operator = parse_operator(&args, &flags)?; + if flags.verify_only { return verify_sources(operator.config); } let (address, token) = (operator.address, operator.token.clone()); diff --git a/desktop-core/src/bin/leleka-inference/startup.rs b/desktop-core/src/bin/leleka-inference/startup.rs index 88cbd27e..b4c7ed35 100644 --- a/desktop-core/src/bin/leleka-inference/startup.rs +++ b/desktop-core/src/bin/leleka-inference/startup.rs @@ -2,8 +2,8 @@ use super::{ Failure, InheritedKarArchive, NativeBackendConfig, OperatorSources, OriginalServeMode, OriginalServeOptions, - PathBuf, Selection, SocketAddr, operator_original_serve, operator_sources_with_inherited, parse_sha256, - select_execution, set_archive_attested, set_verify_stamps, take_option, + PathBuf, Selection, SocketAddr, VerifyPolicy, VerifyStamps, operator_original_serve, + operator_sources_with_inherited, parse_sha256, select_execution, take_option, }; /// The operator's whole command line, parsed and checked; nothing is started yet. @@ -37,38 +37,42 @@ fn take_flag(args: &mut Vec, name: &str) -> bool { given } -/// `--verify-only`: run the load-time source verification (shards, KAR archive) and exit; no CUDA is touched. -/// -/// Also applies the verification flags of the process (`--kar-attested-by-stamp`, `--verify-stamps`) and returns -/// `--verify-only` and the digest of `--kar-sparse-extents-sha256`. -pub(super) fn take_verification_flags(args: &mut Vec) -> Result<(bool, Option<[u8; 32]>), Failure> { +/// What the verification flags of the command line decided. +pub(super) struct VerificationFlags { + /// `--verify-only`: run the load-time source verification (shards, KAR archive) and exit; no CUDA is touched. + pub(super) verify_only: bool, + /// `--kar-sparse-extents-sha256`: the digest of the extents a sparse sealed memfd holds. + pub(super) sparse_extents: Option<[u8; 32]>, + /// `--verify-stamps`, `--verify-rehash` and `--kar-attested-by-stamp`: what vouches for a pinned file at Load. + pub(super) policy: VerifyPolicy, +} + +/// Take the verification flags (`--verify-only`, `--kar-attested-by-stamp`, `--verify-stamps`, `--verify-rehash`, +/// `--kar-sparse-extents-sha256`) off the command line. +pub(super) fn take_verification_flags(args: &mut Vec) -> Result { let verify_only = take_flag(args, "--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 = take_flag(args, "--verify-rehash"); - if take_flag(args, "--kar-attested-by-stamp") { - // Only `leleka run` passes this, after matching the stamp of the archive file it copied the memfd from. - set_archive_attested(); - } + // Only `leleka run` passes `--kar-attested-by-stamp`, after matching the stamp of the archive file it copied the + // memfd from. + let archive_attested = take_flag(args, "--kar-attested-by-stamp"); // `--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(args, "--kar-sparse-extents-sha256")?.map(|text| parse_sha256(&text)).transpose()?; - configure_verify_stamps(args, verify_rehash)?; - Ok((verify_only, sparse_extents)) + let stamps = verify_stamps(args, verify_rehash)?; + Ok(VerificationFlags { verify_only, sparse_extents, policy: VerifyPolicy::new(stamps, archive_attested) }) } -fn configure_verify_stamps(args: &mut Vec, rehash: bool) -> Result<(), Failure> { +fn verify_stamps(args: &mut Vec, rehash: bool) -> Result, Failure> { match take_option(args, "--verify-stamps")? { Some(directory) if directory.is_empty() => Err("invalid_verify_stamps".into()), - Some(directory) => { - set_verify_stamps(PathBuf::from(directory), rehash); - Ok(()) - } + Some(directory) => Ok(Some(VerifyStamps::new(PathBuf::from(directory), rehash))), None if rehash => Err("verify_rehash_requires_verify_stamps".into()), - None => Ok(()), + None => Ok(None), } } @@ -78,7 +82,7 @@ pub(super) fn split_arguments(args: &[String]) -> Result<(&[String], &[String]), } /// Parse and check the whole command line (the part after the process flags). -pub(super) fn parse_operator(args: &[String], sparse_extents: Option<[u8; 32]>) -> Result { +pub(super) fn parse_operator(args: &[String], flags: &VerificationFlags) -> Result { let (base, extra) = split_arguments(args)?; let (requested_mode, original_options, extra) = operator_original_serve(extra)?; let (selection, source_args) = select_execution(&extra)?; @@ -86,7 +90,7 @@ pub(super) fn parse_operator(args: &[String], sparse_extents: Option<[u8; 32]>) let base = base_arguments(base)?; let address = listen_address(base.address)?; let token = runtime_credential(base.token_env)?; - let config = native_config(&base, sources, sparse_extents)?; + let config = native_config(&base, sources, flags)?; Ok(Operator { address, token, config, requested_mode, original_options, selection }) } @@ -133,7 +137,7 @@ fn runtime_credential(name: &str) -> Result { fn native_config( base: &BaseArguments<'_>, sources: OperatorSources, - sparse_extents: Option<[u8; 32]>, + flags: &VerificationFlags, ) -> Result { Ok(NativeBackendConfig { shard0: PathBuf::from(base.shard0), @@ -142,11 +146,12 @@ fn native_config( gpu_budget_bytes: base.budget.parse().map_err(|_| "invalid_gpu_budget")?, context_tokens: base.context.parse().map_err(|_| "invalid_context_bound")?, kar_ple_source: sources.kar, - kar_ple_inherited: inherited_archive(sources.inherited, sources.kar_file, sparse_extents)?, + kar_ple_inherited: inherited_archive(sources.inherited, sources.kar_file, flags.sparse_extents)?, mtp_source: sources.mtp, // The routed-expert KAR source has no operator flag in this binary yet. kar_expert_source: None, experimental: Default::default(), + verification: flags.policy.clone(), }) } From d4aba09cab72dddb1798891b08392893b635b7ce Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 23 Nov 2026 12:19:39 +0100 Subject: [PATCH 4/5] leleka-inference: tests of the verification flags (the policy belongs to its command line, not to the process) --- .../src/bin/leleka-inference/startup.rs | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/desktop-core/src/bin/leleka-inference/startup.rs b/desktop-core/src/bin/leleka-inference/startup.rs index b4c7ed35..e767cf9e 100644 --- a/desktop-core/src/bin/leleka-inference/startup.rs +++ b/desktop-core/src/bin/leleka-inference/startup.rs @@ -176,3 +176,33 @@ fn inherited_archive( _ => None, }) } + +#[cfg(test)] +mod verification_flag_tests { + use super::*; + + fn take(args: &[&str]) -> (Result, Vec) { + let mut args: Vec = args.iter().map(|arg| (*arg).to_owned()).collect(); + (take_verification_flags(&mut args), args) + } + + #[test] + fn the_stamp_directory_and_the_attestation_are_the_policy_of_this_command_line_only() { + let (flags, rest) = + take(&["--verify-only", "--verify-stamps", "/stamps", "--verify-rehash", "--kar-attested-by-stamp", "--x"]); + let flags = flags.unwrap(); + assert!(flags.verify_only && flags.policy.archive_attested()); + assert_eq!(flags.policy.stamps().map(|stamps| stamps.dir().to_owned()), Some(PathBuf::from("/stamps"))); + assert_eq!(rest, ["--x"]); + // another command line in the same process is not touched by the first one + let (plain, _) = take(&["--x"]); + let plain = plain.unwrap(); + assert!(!plain.verify_only && !plain.policy.archive_attested() && plain.policy.stamps().is_none()); + } + + #[test] + fn a_rehash_without_a_stamp_directory_and_an_empty_directory_are_refused() { + assert!(take(&["--verify-rehash"]).0.is_err()); + assert!(take(&["--verify-stamps", ""]).0.is_err()); + } +} From 3ec2bf192b50bfa14e869ee244e778ef6a0130b2 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 23 Nov 2026 12:32:46 +0100 Subject: [PATCH 5/5] Drop the glob re-export and the import the singleton removal left unused --- crates/engine-qwen35-cuda/src/backend/sources.rs | 2 +- crates/leleka-memory/src/governor.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/backend/sources.rs b/crates/engine-qwen35-cuda/src/backend/sources.rs index c419fdde..1789e975 100644 --- a/crates/engine-qwen35-cuda/src/backend/sources.rs +++ b/crates/engine-qwen35-cuda/src/backend/sources.rs @@ -1,6 +1,6 @@ //! Verification of the pinned sources (shards, KAR archive, ranked profile) at load time. use super::{ - BackendError, Clock, Digest, InheritedKarArchive, InputBindingError, NativeBackendConfig, PathBuf, + BackendError, Clock, Digest, InheritedKarArchive, InputBindingError, NativeBackendConfig, RANKED_EXPERT_PROFILE_BYTES, RANKED_EXPERT_PROFILE_SHA, RankedExpertProfileSource, SHARD0, SHARD1, Sha256, SystemClock, VerifiedGgufFile, exhausted, invalid, }; diff --git a/crates/leleka-memory/src/governor.rs b/crates/leleka-memory/src/governor.rs index 4bbf684b..101e33cd 100644 --- a/crates/leleka-memory/src/governor.rs +++ b/crates/leleka-memory/src/governor.rs @@ -203,6 +203,6 @@ mod pressure_tests; mod tests; mod governor_config; -pub use governor_config::*; +use governor_config::lock; mod operations; mod sampler_guard;