diff --git a/docs/agent-data-plane/configuration/configuration.md b/docs/agent-data-plane/configuration/configuration.md index 82278020053..4ceb41702b3 100644 --- a/docs/agent-data-plane/configuration/configuration.md +++ b/docs/agent-data-plane/configuration/configuration.md @@ -1423,7 +1423,7 @@ Controls whether the global memory limiter exerts backpressure as memory usage a ### `memory_mode` -Controls how the calculated memory bounds are reconciled against `memory_limit`. The default is `disabled`. Accepted values: `disabled` skips bounds validation and applies no memory limiting; `permissive` logs a warning when the bounds do not fit within the limit and starts anyway; `strict` refuses to start. Under `permissive` and `strict`, the global memory limiter is active only when a limit is in effect (configured or detected from cgroups) and `enable_global_limiter` is `true`. +Controls how the calculated memory bounds are reconciled against `memory_limit`. The default is `disabled`. Accepted values: `disabled` skips bounds validation and applies no memory limiting; `permissive` logs a warning when the bounds do not fit within the limit and starts anyway; `strict` refuses to start. Under `permissive` and `strict`, the global memory limiter is active only when a limit is in effect (configured or detected from cgroups) and `enable_global_limiter` is `true`. These modes also enable a byte budget for admission independently of the global limiter. It tracks the configured process limit and the Linux cgroup v2 limit separately when both exist. The `disabled` mode does not create a byte budget. diff --git a/lib/datadog-agent/config-overlay-model/src/saluki_keys.rs b/lib/datadog-agent/config-overlay-model/src/saluki_keys.rs index c48a55baab5..270f28b843a 100644 --- a/lib/datadog-agent/config-overlay-model/src/saluki_keys.rs +++ b/lib/datadog-agent/config-overlay-model/src/saluki_keys.rs @@ -347,7 +347,10 @@ pub static SALUKI_KEYS: &[SalukiKey] = &[ no memory limiting; `permissive` logs a warning when the bounds do not fit within the \ limit and starts anyway; `strict` refuses to start. Under `permissive` and `strict`, \ the global memory limiter is active only when a limit is in effect (configured or \ - detected from cgroups) and `enable_global_limiter` is `true`.", + detected from cgroups) and `enable_global_limiter` is `true`. These modes also \ + enable a byte budget for admission independently of the global limiter. It tracks \ + the configured process limit and the Linux cgroup v2 limit separately when both \ + exist. The `disabled` mode does not create a byte budget.", ), }, ]; diff --git a/lib/saluki-app/src/accounting.rs b/lib/saluki-app/src/accounting.rs index e52d9aa0cac..3e76130448c 100644 --- a/lib/saluki-app/src/accounting.rs +++ b/lib/saluki-app/src/accounting.rs @@ -8,7 +8,7 @@ use saluki_api::{DynamicRoute, EndpointType}; use saluki_common::resource_tracking::{ResourceGroupRegistry, ResourceStats, ResourceStatsSnapshot}; use saluki_common::{collections::FastHashMap, sync::shutdown::ShutdownHandle}; use saluki_core::accounting::{ - ComponentBounds, ComponentRegistry, ComponentRegistryHandle, MemoryGrant, MemoryLimiter, + ByteBudget, CgroupMemory, ComponentBounds, ComponentRegistry, ComponentRegistryHandle, MemoryGrant, MemoryLimiter, }; use saluki_core::{ diagnostic::DiagnosticsEmitter, @@ -23,7 +23,7 @@ use tracing::{error, info, warn}; /// Bounds validation and global memory limiter behavior. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub enum MemoryMode { - /// Bounds validation is skipped, and no memory limiting is applied. + /// Bounds verification, cooperative backpressure, and byte-budget admission are disabled. #[default] Disabled, @@ -72,6 +72,10 @@ pub struct MemoryBoundsConfiguration { /// When no memory limit is configured and `DOCKER_DD_AGENT` is set to a non-empty value, the limit is read from the /// process cgroup instead. /// +/// In permissive and strict modes, an opt-in byte budget tracks configured process and finite cgroup v2 limits +/// independently. The budget uses the smaller remaining allowance, even when cooperative backpressure is disabled. +/// Disabled mode does not create a byte budget. +/// /// See [`MemoryMode`] for details on the behavior of each mode. /// /// # Errors @@ -111,7 +115,30 @@ pub fn initialize_memory_bounds( _ => MemoryLimiter::noop(), }; - Ok(limiter) + let budget = if configuration.memory_mode == MemoryMode::Disabled { + None + } else { + match (configuration.memory_limit, CgroupMemory::detect()) { + (Some(limit), Some(cgroup)) => Some( + ByteBudget::for_process_and_cgroup_memory_limits(limit.as_u64() as usize, cgroup) + .ok_or_else(|| generic_error!("Process and cgroup memory usage cannot be monitored."))?, + ), + (None, Some(cgroup)) => Some( + ByteBudget::for_memory_limit(cgroup.limit(), move || cgroup.current()).ok_or_else(|| { + generic_error!("Cgroup memory usage cannot be monitored for byte-budget admission.") + })?, + ), + (_, None) => memory_limit + .map(|limit| { + ByteBudget::for_process_memory_limit(limit.as_u64() as usize).ok_or_else(|| { + generic_error!("Process memory usage cannot be monitored for byte-budget admission.") + }) + }) + .transpose()?, + } + }; + + Ok(limiter.with_byte_budget(budget)) } fn verify_bounds_for_mode( @@ -433,11 +460,15 @@ mod tests { fn disabled_memory_mode_skips_bounds_verification() { let registry = registry_with_firm_bound(64 * 1024 * 1024); - initialize_memory_bounds( + let limiter = initialize_memory_bounds( config_with_limit(ByteSize::b(1024), MemoryMode::Disabled), registry.root(), ) .expect("disabled mode should not verify bounds"); + assert!( + limiter.byte_budget().is_none(), + "disabled mode leaves admission unbounded even with an explicit limit" + ); } #[test] @@ -459,11 +490,15 @@ mod tests { fn permissive_memory_mode_tolerates_bounds_exceeding_the_limit() { let registry = registry_with_firm_bound(64 * 1024 * 1024); - initialize_memory_bounds( + let limiter = initialize_memory_bounds( config_with_limit(ByteSize::b(1024), MemoryMode::Permissive), registry.root(), ) .expect("bounds larger than the limit should be non-fatal in permissive mode"); + assert!( + limiter.byte_budget().is_some(), + "configured bounding attaches admission without backoff" + ); } #[test] diff --git a/lib/saluki-core/src/accounting/byte_budget.rs b/lib/saluki-core/src/accounting/byte_budget.rs new file mode 100644 index 00000000000..1cb79ecb53a --- /dev/null +++ b/lib/saluki-core/src/accounting/byte_budget.rs @@ -0,0 +1,474 @@ +//! Provides opt-in byte admission based on observed memory usage and estimated allocation growth. +//! +//! # Design +//! +//! A topology can enable a budget when it has a memory limit. Without a budget, callers do not reserve bytes or start +//! a sampler. The sampler reads process usage for a process limit and cgroup usage for a cgroup limit. +//! It waits 25 ms between samples to keep observation off the admission fast path at the cost of feedback delay. +//! +//! The admission ceiling reserves one eighth of the limit, up to 128 MiB, for work that does not reserve bytes. +//! This includes receive buffers, allocator rounding, and encoder workspaces. A budget reduces accepted growth under +//! pressure but cannot guarantee a process or cgroup memory cap. The estimates and other work depend on the workload. +//! +//! Reservations use a shared atomic total, so concurrent callers cannot spend the same headroom. +//! Each sample replaces the last observed usage and reconciles reservations that completed before the sample began. +//! Reservations still in progress stay charged. This can count bytes twice for one sample, but it avoids releasing +//! headroom while an allocation is still in progress. +//! +//! On pressure, a caller can reclaim idle memory, sample again, and retry before refusing the reservation. +//! Concurrent refusals share a reclaim pass. A 250 ms cooldown limits repeated cache scans at the cost of delaying +//! another pass when more idle memory becomes available. +//! +use std::{ + mem::take, + sync::{ + atomic::{ + AtomicU64, AtomicUsize, + Ordering::{Acquire, Relaxed, Release}, + }, + Arc, Mutex, Weak, + }, + thread, + time::{Duration, Instant}, +}; + +use super::cgroup::CgroupMemory; + +const MIB: usize = 1024 * 1024; +const INGEST_CREDIT_BYTES: usize = 16 * 1024; +const SAMPLE_INTERVAL: Duration = Duration::from_millis(25); +// Bound the cost of scanning big caches while the process is already shedding load. +const RECLAIM_INTERVAL: Duration = Duration::from_millis(250); + +type Usage = Box Option + Send>; +type Reclaimer = dyn Fn() + Send + Sync; + +/// A shared limit for allocation growth, on top of already resident memory. +/// +/// Reserve growth before allocating. Hold the reservation until the operation finishes. +/// The estimate stays charged until a successful observation can replace it with measured usage. +#[derive(Clone)] +pub struct ByteBudget(Arc); + +struct State { + ceiling: usize, + used: AtomicUsize, + completed: AtomicUsize, + observation: Mutex, + pressure: Mutex, + origin: Instant, + last_reclaim_ms: AtomicU64, +} + +struct Observation { + bytes: usize, + usage: Option, +} + +#[derive(Default)] +struct Pressure { + reclaimers: Vec>, +} + +impl ByteBudget { + /// Creates a budget with a fixed observation and no sampler. + /// + /// Without a sampler, completed reservations remain charged against the fixed ceiling. + pub fn new(ceiling: usize, observed_bytes: usize) -> Self { + Self::with_usage(ceiling, observed_bytes, None) + } + + /// Starts observing the process working set against a process memory limit. + /// + /// Returns `None` if the initial observation or sampler startup fails. + pub fn for_process_memory_limit(limit: usize) -> Option { + let mut querier = process_memory::Querier::default(); + Self::for_memory_limit(limit, move || querier.resident_set_size()) + } + + /// Starts observing process and cgroup usage against their respective limits. + /// + /// The smaller remaining allowance constrains growth. Returns `None` if an initial observation or sampler + /// startup fails. + pub fn for_process_and_cgroup_memory_limits(limit: usize, cgroup: CgroupMemory) -> Option { + let mut querier = process_memory::Querier::default(); + Self::for_independent_memory_limits( + limit, + cgroup.limit(), + move || querier.resident_set_size(), + move || cgroup.current(), + ) + } + + fn for_independent_memory_limits( + process_limit: usize, cgroup_limit: usize, mut process_usage: impl FnMut() -> Option + Send + 'static, + mut cgroup_usage: impl FnMut() -> Option + Send + 'static, + ) -> Option { + let process_ceiling = admission_ceiling(process_limit); + let cgroup_ceiling = admission_ceiling(cgroup_limit); + let ceiling = process_ceiling.min(cgroup_ceiling); + Self::observe(ceiling, move || { + // Express both observations against one ceiling. The higher charge leaves less headroom. + let process_charge = process_usage()?.saturating_sub(process_ceiling - ceiling); + let cgroup_charge = cgroup_usage()?.saturating_sub(cgroup_ceiling - ceiling); + Some(process_charge.max(cgroup_charge)) + }) + } + + fn with_usage(ceiling: usize, bytes: usize, usage: Option) -> Self { + Self(Arc::new(State { + ceiling, + used: AtomicUsize::new(bytes), + completed: AtomicUsize::new(0), + observation: Mutex::new(Observation { bytes, usage }), + pressure: Mutex::new(Pressure::default()), + origin: Instant::now(), + last_reclaim_ms: AtomicU64::new(0), + })) + } + + /// Starts observing resident bytes against a memory limit, leaving room for work without reservations. + /// + /// The caller supplies the usage observation, such as `memory.current` for a cgroup v2 limit. + /// The ceiling leaves one eighth of the limit, up to 128 MiB, outside admission accounting. + /// + /// Returns `None` if the initial observation or sampler startup fails. + pub fn for_memory_limit(limit: usize, usage: impl FnMut() -> Option + Send + 'static) -> Option { + Self::observe(admission_ceiling(limit), usage) + } + + fn observe(ceiling: usize, mut usage: impl FnMut() -> Option + Send + 'static) -> Option { + let initial = usage()?; + let budget = Self::with_usage(ceiling, initial, Some(Box::new(usage))); + let weak = Arc::downgrade(&budget.0); + thread::Builder::new() + .name("byte-budget-sampler".into()) + .spawn(move || loop { + thread::sleep(SAMPLE_INTERVAL); + let Some(state) = weak.upgrade() else { break }; + state.refresh_usage(); + }) + .ok()?; + Some(budget) + } + + /// Registers a reclamation callback while the returned handle remains live. + /// + /// Reclamation runs synchronously under the pressure lock. Do not reenter this budget from the callback. + pub fn register_reclaimer(&self, reclaim: impl Fn() + Send + Sync + 'static) -> BudgetReclaimer { + let reclaim = Arc::new(reclaim) as Arc; + let mut pressure = self.0.pressure.lock().unwrap(); + pressure.reclaimers.push(Arc::downgrade(&reclaim)); + self.0.last_reclaim_ms.store(0, Relaxed); + BudgetReclaimer { _reclaim: reclaim } + } + + /// Creates a local allowance for synchronous operations to avoid a shared atomic update per line. + /// + /// The batch requests credits in chunks of at least 16 KiB when space allows. Unused credits can temporarily + /// reduce available headroom for other callers. + pub fn batch(&self) -> ByteBudgetBatch { + ByteBudgetBatch { + budget: self.clone(), + remaining: 0, + spent: 0, + } + } + + /// Reserves an upper estimate of bytes to be allocated by the operation. + /// + /// Returns `None` if the reservation still cannot fit after any eligible idle-memory reclaim. + /// A zero-byte reservation succeeds without reclamation or an atomic charge. + #[inline] + pub fn try_reserve(&self, bytes: usize) -> Option> { + (self.charge(bytes) || self.reclaim_and_charge(bytes)).then(|| ByteReservation { state: &self.0, bytes }) + } + + #[inline] + fn charge(&self, bytes: usize) -> bool { + bytes == 0 + || self + .0 + .used + .fetch_update(Relaxed, Relaxed, |used| { + used.checked_add(bytes).filter(|next| *next <= self.0.ceiling) + }) + .is_ok() + } + + #[cold] + fn reclaim_and_charge(&self, bytes: usize) -> bool { + if self.0.reclaim_is_cooling_down() { + return self.charge(bytes); + } + let Ok(mut pressure) = self.0.pressure.try_lock() else { + return self.charge(bytes); + }; + if self.charge(bytes) { + return true; + } + if !self.0.reclaim_is_cooling_down() { + pressure.reclaimers.retain(|reclaim| { + let Some(reclaim) = reclaim.upgrade() else { return false }; + reclaim(); + true + }); + self.0.refresh_usage(); + self.0.last_reclaim_ms.store(self.0.reclaim_clock_ms(), Relaxed); + } + self.charge(bytes) + } +} + +fn admission_ceiling(limit: usize) -> usize { + limit - (limit / 8).min(128 * MIB) +} + +impl State { + fn reclaim_clock_ms(&self) -> u64 { + // Zero denotes that no reclaim has run yet. + (self.origin.elapsed().as_millis() as u64).saturating_add(1) + } + + fn reclaim_is_cooling_down(&self) -> bool { + let last = self.last_reclaim_ms.load(Relaxed); + last != 0 && self.reclaim_clock_ms().saturating_sub(last) < RECLAIM_INTERVAL.as_millis() as u64 + } + + fn refresh_usage(&self) { + let mut observation = self.observation.lock().unwrap(); + let Some(usage) = &mut observation.usage else { return }; + // Only reconcile operations that finish before the sample starts. Keep later completions for the next sample, + // even if the current observation already includes some of their bytes. + let completed = self.completed.swap(0, Acquire); + let Some(next) = usage() else { + self.completed.fetch_add(completed, Relaxed); + return; + }; + // Apply the change in the baseline without overwriting concurrent reservations in the shared total. + let previous = observation.bytes + completed; + if next >= previous { + self.used.fetch_add(next - previous, Relaxed); + } else { + self.used.fetch_sub(previous - next, Relaxed); + } + observation.bytes = next; + } +} + +/// Keeps one idle-memory reclamation callback registered. +#[derive(Clone)] +#[must_use] +pub struct BudgetReclaimer { + _reclaim: Arc, +} + +/// Local credits reserved against a shared [`ByteBudget`]. +/// +/// Finish each operation before spending more credits, releasing them, or dropping this batch. +/// Refill, release, and drop return unused credits and mark spent credits complete for reconciliation. +pub struct ByteBudgetBatch { + budget: ByteBudget, + remaining: usize, + spent: usize, +} + +impl ByteBudgetBatch { + /// Returns `true` if the synchronous operation can spend the requested credits. + #[inline] + pub fn try_spend(&mut self, bytes: usize) -> bool { + if bytes > self.remaining && !self.refill(bytes) { + return false; + } + self.remaining -= bytes; + self.spent += bytes; + true + } + + #[cold] + fn refill(&mut self, bytes: usize) -> bool { + self.release(); + let chunk = bytes.max(INGEST_CREDIT_BYTES); + if self.budget.charge(chunk) { + self.remaining = chunk; + } else if (chunk != bytes && self.budget.charge(bytes)) || self.budget.reclaim_and_charge(bytes) { + self.remaining = bytes; + } else { + return false; + } + true + } + + /// Returns unused credits and marks spent credits complete for reconciliation. + /// + /// Call this after the operations that spent the credits finish. The batch can then spend new credits. + pub fn release(&mut self) { + let remaining = take(&mut self.remaining); + let spent = take(&mut self.spent); + if remaining != 0 { + self.budget.0.used.fetch_sub(remaining, Relaxed); + } + if spent != 0 { + self.budget.0.completed.fetch_add(spent, Release); + } + } +} + +impl Drop for ByteBudgetBatch { + fn drop(&mut self) { + self.release(); + } +} + +/// Keeps an operation's estimated growth charged until that operation finishes. +/// +/// Dropping the reservation marks it complete. A later observation reconciles it with actual usage. +#[must_use] +pub struct ByteReservation<'a> { + state: &'a State, + bytes: usize, +} + +impl Drop for ByteReservation<'_> { + #[inline] + fn drop(&mut self) { + if self.bytes != 0 { + self.state.completed.fetch_add(self.bytes, Release); + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::{atomic::AtomicBool, mpsc}; + + use super::*; + + #[test] + fn concurrent_reservations_do_not_overspend() { + let budget = ByteBudget::new(100, 4); + let admitted = AtomicUsize::new(0); + thread::scope(|scope| { + for _ in 0..32 { + scope.spawn(|| { + if budget.try_reserve(8).is_some() { + admitted.fetch_add(1, Relaxed); + } + }); + } + }); + assert_eq!(admitted.load(Relaxed), 12); + assert!(budget.try_reserve(1).is_none()); + assert!(budget.try_reserve(usize::MAX).is_none()); + assert!(budget.try_reserve(0).is_some()); + } + + #[test] + fn batched_ingest_shares_the_limit_and_returns_unused_credit() { + let budget = ByteBudget::new(INGEST_CREDIT_BYTES + 10, 0); + let mut batch = budget.batch(); + assert!(batch.try_spend(6)); + assert!(batch.try_spend(4)); + assert!(budget.try_reserve(11).is_none()); + drop(batch); + assert!(budget.try_reserve(INGEST_CREDIT_BYTES).is_some()); + assert!(budget.try_reserve(1).is_none()); + assert_eq!(budget.0.completed.load(Relaxed), INGEST_CREDIT_BYTES + 10); + } + + #[test] + fn release_returns_unused_credits_and_completes_spent_credits() { + let budget = ByteBudget::new(INGEST_CREDIT_BYTES, 0); + let mut batch = budget.batch(); + assert!(batch.try_spend(10)); + assert!(budget.try_reserve(1).is_none()); + assert_eq!(budget.0.completed.load(Relaxed), 0); + + batch.release(); + batch.release(); + assert_eq!(budget.0.completed.load(Relaxed), 10); + assert!(budget.try_reserve(INGEST_CREDIT_BYTES - 9).is_none()); + assert!(batch.try_spend(INGEST_CREDIT_BYTES - 10)); + assert!(budget.try_reserve(1).is_none()); + } + + #[test] + fn observation_reconciles_only_completed_growth() { + let usage = Arc::new(AtomicUsize::new(40)); + let sample = Arc::clone(&usage); + let budget = ByteBudget::with_usage(100, 40, Some(Box::new(move || Some(sample.load(Relaxed))))); + let in_flight = budget.try_reserve(40).unwrap(); + drop(budget.try_reserve(20).unwrap()); + + usage.store(60, Relaxed); + budget.0.refresh_usage(); + assert!(budget.try_reserve(1).is_none()); + drop(in_flight); + + usage.store(75, Relaxed); + budget.0.refresh_usage(); + assert!(budget.try_reserve(26).is_none()); + assert!(budget.try_reserve(25).is_some()); + } + + #[test] + fn failed_sample_keeps_reservations() { + let budget = ByteBudget::with_usage(10, 0, Some(Box::new(|| None))); + drop(budget.try_reserve(10).unwrap()); + budget.0.refresh_usage(); + assert!(budget.try_reserve(1).is_none()); + assert_eq!(budget.0.completed.load(Relaxed), 10); + } + + #[test] + fn pressure_reclaims_before_retry_or_refusal() { + let reclaimed = Arc::new(AtomicBool::new(false)); + let sample = Arc::clone(&reclaimed); + let budget = ByteBudget::with_usage( + 100, + 95, + Some(Box::new(move || Some(if sample.load(Relaxed) { 80 } else { 95 }))), + ); + let flag = Arc::clone(&reclaimed); + let _reclaimer = budget.register_reclaimer(move || flag.store(true, Relaxed)); + assert!(budget.try_reserve(10).is_some()); + assert!(reclaimed.load(Relaxed)); + assert!(budget.try_reserve(11).is_none()); + } + + #[test] + fn independent_limits_charge_rss_and_cgroup_usage_against_their_own_limits() { + for (group_usage, available) in [(500, 124), (1900, 20)] { + let budget = ByteBudget::for_independent_memory_limits( + 256 * MIB, + 2048 * MIB, + || Some(100 * MIB), + move || Some(group_usage * MIB), + ) + .unwrap(); + assert!(budget.try_reserve(available * MIB + 1).is_none()); + assert!(budget.try_reserve(available * MIB).is_some()); + } + } + + #[test] + fn contended_reclaim_and_cooldown_retry_the_charge() { + let budget = ByteBudget::new(20, 0); + let pressure = budget.0.pressure.lock().unwrap(); + let (tx, rx) = mpsc::channel(); + thread::scope(|scope| { + let budget = &budget; + scope.spawn(move || { + let during_contention = budget.reclaim_and_charge(10); + budget.0.last_reclaim_ms.store(budget.0.reclaim_clock_ms(), Relaxed); + let during_cooldown = budget.reclaim_and_charge(10); + let over_limit = budget.reclaim_and_charge(1); + tx.send((during_contention, during_cooldown, over_limit)).unwrap(); + }); + // Release the lock even when the assertion would fail because a caller waited for it. + let result = rx.recv_timeout(Duration::from_secs(2)); + drop(pressure); + assert_eq!(result, Ok((true, true, false))); + }); + } +} diff --git a/lib/saluki-core/src/accounting/cgroup.rs b/lib/saluki-core/src/accounting/cgroup.rs new file mode 100644 index 00000000000..e757c875088 --- /dev/null +++ b/lib/saluki-core/src/accounting/cgroup.rs @@ -0,0 +1,146 @@ +#[cfg(target_os = "linux")] +use std::{ + fs::{self, File}, + os::unix::fs::FileExt as _, + path::{Component, Path, PathBuf}, +}; + +/// A finite cgroup v2 memory limit and the usage charged against it. +pub struct CgroupMemory { + limit: usize, + #[cfg(target_os = "linux")] + levels: Vec<(usize, File)>, +} + +impl CgroupMemory { + /// Finds the lowest finite memory limit in the process's visible cgroup v2 hierarchy. + pub fn detect() -> Option { + #[cfg(target_os = "linux")] + { + let groups = fs::read_to_string("/proc/self/cgroup").ok()?; + let mounts = fs::read_to_string("/proc/self/mountinfo").ok()?; + let levels = cgroup_limits(&groups, &mounts, |path| fs::read_to_string(path).ok()); + let limit = levels.iter().map(|(limit, _)| *limit).min()?; + let levels = levels + .into_iter() + .map(|(limit, directory)| Some((limit, File::open(directory.join("memory.current")).ok()?))) + .collect::>>()?; + Some(Self { limit, levels }) + } + #[cfg(not(target_os = "linux"))] + None + } + + /// The effective memory limit in bytes. + pub fn limit(&self) -> usize { + self.limit + } + + /// Reads the effective charge, including pressure from siblings in a bounded ancestor. + pub fn current(&self) -> Option { + #[cfg(target_os = "linux")] + { + let mut charge = 0; + for (limit, current) in &self.levels { + let mut buf = [0u8; 32]; + let len = current.read_at(&mut buf, 0).ok()?; + let current = String::from_utf8_lossy(&buf[..len]).trim().parse().ok()?; + charge = charge.max(charge_for_level(self.limit, *limit, current)); + } + Some(charge) + } + #[cfg(not(target_os = "linux"))] + None + } +} + +#[cfg(target_os = "linux")] +fn cgroup_limits(groups: &str, mounts: &str, read: impl Fn(&Path) -> Option) -> Vec<(usize, PathBuf)> { + let Some(group) = groups.lines().find_map(|line| line.strip_prefix("0::")).map(Path::new) else { + return Vec::new(); + }; + let mut limits = Vec::new(); + for mount in mounts.lines() { + let Some((fields, fs)) = mount.split_once(" - ") else { + continue; + }; + if !fs.starts_with("cgroup2 ") { + continue; + } + let mut fields = fields.split_ascii_whitespace().skip(3); + let (Some(root), Some(mountpoint)) = (fields.next(), fields.next()) else { + continue; + }; + let mountpoint = Path::new(mountpoint); + let relative = match group.strip_prefix(root) { + Ok(relative) => relative, + // A cgroup namespace can report its own root, relative to a mount of a delegated subtree. + Err(_) if group == Path::new("/") => Path::new(""), + Err(_) => continue, + }; + if relative.components().any(|part| matches!(part, Component::ParentDir)) { + continue; + } + for directory in mountpoint + .join(relative) + .ancestors() + .take_while(|dir| dir.starts_with(mountpoint)) + { + let Some(limit) = read(&directory.join("memory.max")).and_then(|value| value.trim().parse().ok()) else { + continue; + }; + limits.push((limit, directory.to_path_buf())); + } + } + limits +} + +#[cfg(target_os = "linux")] +fn charge_for_level(effective_limit: usize, limit: usize, current: usize) -> usize { + // Express the level's remaining bytes against the common effective limit. + current.saturating_sub(limit - effective_limit) +} + +#[cfg(all(test, target_os = "linux"))] +mod tests { + use super::*; + + #[test] + fn locates_nested_unified_hierarchy_and_uses_finite_ancestor() { + let groups = "2:cpu:/service\n0::/delegated/pod/leaf\n"; + let mounts = "27 44 0:23 /delegated /cgroups rw - cgroup2 cgroup2 rw\n"; + let result = cgroup_limits(groups, mounts, |path| match path.to_str()? { + "/cgroups/pod/leaf/memory.max" => Some("max\n".into()), + "/cgroups/pod/memory.max" => Some(" 1073741824\n".into()), + "/cgroups/memory.max" => Some("2147483648".into()), + _ => panic!("read outside the cgroup mount: {path:?}"), + }); + assert_eq!( + result, + vec![ + (1_073_741_824, PathBuf::from("/cgroups/pod")), + (2_147_483_648, PathBuf::from("/cgroups")), + ] + ); + } + + #[test] + fn detects_namespaced_root_and_ignores_unlimited_and_invalid_values() { + let mounts = "27 44 0:23 /delegated /cgroups rw - cgroup2 cgroup2 rw\n"; + for (raw, expected) in [("max", None), ("invalid", None), ("65536", Some(65536))] { + let result = cgroup_limits("0::/\n", mounts, |path| { + assert_eq!(path, Path::new("/cgroups/memory.max")); + Some(raw.into()) + }); + assert_eq!(result.first().map(|(limit, _)| *limit), expected); + } + assert!(cgroup_limits("1:memory:/unified\n", mounts, |_| panic!("not cgroup v2")).is_empty()); + } + + #[test] + fn larger_ancestor_limit_can_have_less_headroom() { + assert_eq!(charge_for_level(100, 100, 50), 50); + assert_eq!(charge_for_level(100, 200, 190), 90); + assert_eq!(charge_for_level(100, 200, 30), 0); + } +} diff --git a/lib/saluki-core/src/accounting/limiter.rs b/lib/saluki-core/src/accounting/limiter.rs index c17a7efa3d8..baff0b6de09 100644 --- a/lib/saluki-core/src/accounting/limiter.rs +++ b/lib/saluki-core/src/accounting/limiter.rs @@ -10,7 +10,7 @@ use metrics::{counter, gauge, Counter}; use process_memory::Querier; use tracing::{debug, info, warn}; -use super::MemoryGrant; +use super::{ByteBudget, MemoryGrant}; /// How often the checker thread samples the process's memory usage. const CHECK_INTERVAL: Duration = Duration::from_millis(250); @@ -37,6 +37,7 @@ const CHECK_INTERVAL: Duration = Duration::from_millis(250); pub struct MemoryLimiter { active_backoff_nanos: Arc, throttle_counters: Arc>, + byte_budget: Option, } /// Counters for the calls that the memory limiter throttles. @@ -92,6 +93,7 @@ impl MemoryLimiter { Some(Self { active_backoff_nanos, throttle_counters: Arc::new(OnceLock::new()), + byte_budget: None, }) } @@ -102,9 +104,21 @@ impl MemoryLimiter { Self { active_backoff_nanos: Arc::new(AtomicU64::new(0)), throttle_counters: Arc::new(OnceLock::new()), + byte_budget: None, } } + /// Sets the shared allocation budget independently of cooperative backpressure. + pub fn with_byte_budget(mut self, budget: Option) -> Self { + self.byte_budget = budget; + self + } + + /// Returns the shared allocation budget if memory is limited. + pub fn byte_budget(&self) -> Option<&ByteBudget> { + self.byte_budget.as_ref() + } + /// Waits a short period of time based on the available memory. /// /// If the used memory isn't within the threshold of the configured limit, no waiting will occur. Otherwise, the diff --git a/lib/saluki-core/src/accounting/mod.rs b/lib/saluki-core/src/accounting/mod.rs index eba50f1173d..f5f5bf2373b 100644 --- a/lib/saluki-core/src/accounting/mod.rs +++ b/lib/saluki-core/src/accounting/mod.rs @@ -25,6 +25,12 @@ use serde::Serialize; mod api; pub use self::api::ResourceAPIHandler; +mod byte_budget; +pub use self::byte_budget::{BudgetReclaimer, ByteBudget, ByteBudgetBatch, ByteReservation}; + +mod cgroup; +pub use self::cgroup::CgroupMemory; + mod grant; pub use self::grant::MemoryGrant; diff --git a/lib/saluki-core/src/data_model/event/metric/context/context_cache.rs b/lib/saluki-core/src/data_model/event/metric/context/context_cache.rs index 4b1fbe4f409..401634d064f 100644 --- a/lib/saluki-core/src/data_model/event/metric/context/context_cache.rs +++ b/lib/saluki-core/src/data_model/event/metric/context/context_cache.rs @@ -107,7 +107,7 @@ use std::{ num::NonZeroUsize, sync::{ atomic::{AtomicU32, Ordering::Relaxed}, - Arc, RwLock, + Arc, Mutex, RwLock, }, time::Duration, }; @@ -208,6 +208,7 @@ impl ContextCache { shards, start_secs: get_coarse_monotonic_seconds(), telemetry, + telemetry_update: Mutex::new(()), telemetry_enabled, }); @@ -294,6 +295,28 @@ impl ContextCache { } Some((context, existing)) } + + /// Removes every resident context whose only strong reference is the cache, and returns the number removed. + /// + /// The memory admission hook calls this method to free idle contexts under memory pressure. It also removes every + /// dead weak entry and shrinks each shard. Contexts that another owner holds stay resident. + pub(super) fn evict_idle_for_budget(&self) -> usize { + let state = &self.state; + let _telemetry = state.telemetry_update.lock().unwrap(); + let mut evicted = 0; + let mut remaining = 0; + for shard in &state.shards { + let mut shard = shard.0.write().unwrap(); + evicted += shard.evict_idle_for_budget(); + remaining += shard.resident.len(); + } + if state.telemetry_enabled { + state.telemetry.current_items().set(remaining as f64); + state.telemetry.current_weight().set(remaining as f64); + state.telemetry.items_evicted_total().increment(evicted as u64); + } + evicted + } } /// The state that all clones of a [`ContextCache`] and its background tasks share. @@ -307,6 +330,12 @@ struct State { /// The cache metrics. telemetry: Telemetry, + /// Serializes updates of the item gauges. + /// + /// The telemetry task and `ContextCache::evict_idle_for_budget` both count resident items and set the gauges. + /// Without this lock, a stale count from one of them can overwrite a newer count from the other. + telemetry_update: Mutex<()>, + /// Whether the cache reports telemetry. telemetry_enabled: bool, } @@ -361,6 +390,7 @@ impl State { _ = sleep(SWEEP_INTERVAL) => {} } + let _update = self.telemetry_update.lock().unwrap(); let items: usize = self .shards .iter() @@ -611,6 +641,35 @@ impl Shard { }); // Check at least a quarter of the leaving slots during each sweep. let leaving_scanned = self.reap_leaving(self.leaving.len().div_ceil(4).max(LEAVING_SWEEP_MINIMUM)); + self.trim(); + (expired, resident_scanned + leaving_scanned) + } + + /// Removes every resident context whose only strong reference is the cache, and returns the number removed. + /// + /// This method also reaps every dead leaving entry and shrinks the shard. + fn evict_idle_for_budget(&mut self) -> usize { + let before = self.resident.len(); + let mut i = 0; + while let Some(slot) = self.resident.get(i) { + // The write lock stops new strong references from this cache, so a count of 1 cannot rise. + if slot.context.inner.strong_count() == 1 { + self.remove(i); + } else { + i += 1; + } + } + self.reap_leaving(self.leaving.len()); + self.trim(); + before - self.resident.len() + } + + /// Shrinks each vector and the index when it uses a quarter or less of its capacity. + /// + /// The new capacity is twice the current length. The gap between the ¼ trigger and the 2× target is hysteresis: + /// a shard must lose half of its new capacity again before the next shrink. Thus, a shard that changes size a + /// little does not reallocate on each sweep. + fn trim(&mut self) { if self.resident.len() <= self.resident.capacity() / 4 { self.resident.shrink_to(self.resident.len() * 2); } @@ -622,7 +681,6 @@ impl Shard { index_hash(slot_key(&self.resident, &self.leaving, i)) }); } - (expired, resident_scanned + leaving_scanned) } /// Removes each resident slot whose last access epoch is older than `cutoff`, and returns the number removed. @@ -764,6 +822,38 @@ mod tests { assert!(get(&shard, "new").is_some()); } + #[test] + fn pressure_evicts_idle_and_dead_weak_slots_but_preserves_live_identity() { + let mut resolver = ContextResolverBuilder::for_tests() + .with_cached_contexts_limit(64) + .build(); + let held = resolver.resolve("held", ["env:prod"], None).unwrap(); + let idle = resolver.resolve("idle", ["env:prod"], None).unwrap(); + let idle_weak = idle.inner.downgrade(); + drop(idle); + for i in 0..10 { + resolver.resolve(format!("idle.{i}"), ["env:prod"], None).unwrap(); + } + assert_eq!(resolver.evict_idle_for_budget(), 11); + assert!(idle_weak.upgrade().is_none()); + assert!(held.ptr_eq(&resolver.resolve("held", ["env:prod"], None).unwrap())); + assert_eq!(resolver.evict_idle_for_budget(), 0); + drop(held); + assert_eq!(resolver.evict_idle_for_budget(), 1); + + let mut resolver = ContextResolverBuilder::for_tests() + .with_cached_contexts_limit(1) + .build(); + let held = resolver.resolve("weak", ["env:prod"], None).unwrap(); + resolver.resolve("resident", ["env:prod"], None).unwrap(); + drop(held); + assert_eq!(resolver.evict_idle_for_budget(), 1); + let cache = resolver.context_cache.as_ref().unwrap(); + let shard = cache.state.shards[0].0.read().unwrap(); + assert!(shard.leaving.is_empty()); + assert!(shard.index.is_empty()); + } + #[test] fn reuses_a_live_context_after_capacity_eviction() { let mut resolver = ContextResolverBuilder::for_tests() diff --git a/lib/saluki-core/src/data_model/event/metric/context/resolver.rs b/lib/saluki-core/src/data_model/event/metric/context/resolver.rs index 2fc6977df2f..b8e7c371e61 100644 --- a/lib/saluki-core/src/data_model/event/metric/context/resolver.rs +++ b/lib/saluki-core/src/data_model/event/metric/context/resolver.rs @@ -566,6 +566,13 @@ impl ContextResolver { Some(Context { inner }) } + /// Evicts all cached contexts that have no other strong owners. + pub fn evict_idle_for_budget(&self) -> usize { + self.context_cache + .as_ref() + .map_or(0, ContextCache::evict_idle_for_budget) + } + /// Resolves the given context. /// /// If the context hasn't yet been resolved, the name and tags are interned and a new context is created and diff --git a/releasenotes/notes/dogstatsd-opt-in-memory-admission-da62a19d01c48d79.yaml b/releasenotes/notes/dogstatsd-opt-in-memory-admission-da62a19d01c48d79.yaml new file mode 100644 index 00000000000..87df0f0459d --- /dev/null +++ b/releasenotes/notes/dogstatsd-opt-in-memory-admission-da62a19d01c48d79.yaml @@ -0,0 +1,4 @@ +features: + - | + Introduce an opt-in byte budget for DogStatsD admission under ``permissive`` and ``strict`` memory modes. + The budget tracks a configured process limit and a finite Linux cgroup v2 limit independently when both exist.