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()); + } +}