From 1414e6b5343e6f42b1944f288792ff91dd0a3adc Mon Sep 17 00:00:00 2001 From: "Brian L. Troutwine" Date: Thu, 26 Nov 2026 03:43:05 +0000 Subject: [PATCH 1/4] feat(core): add an opt-in cgroup-aware ByteBudget and idle-cache reclaim hook ADP runs without a memory bound by default and allows unbounded growth. Deployments that set `memory_mode` to `permissive` or `strict` expect ADP to stay within a limit. At base, DogStatsD has no shared byte headroom to reserve against. A flood of new contexts can grow until the kernel kills the process. This change adds `ByteBudget`, a shared atomic limit on allocation growth above resident memory. It attaches only in `permissive` or `strict` mode and uses the lower of the configured and finite cgroup limits. Under the default `disabled` mode, ADP attaches no budget, even inside a finite cgroup. A sampler refreshes resident usage every 25 ms. An idle-context reclaim hook lets caches free idle entries before a reservation fails. The configuration documentation now states when admission is available. Stripped `optimized-release` Tier 1 runs report `byte_budget_attached = false` on every default 1M and SMP run. Admission enforcement depends on this budget. - [ ] Bug fix - [x] New feature - [ ] Non-functional - [ ] Performance - `cargo check --locked --workspace --tests` - `cargo test --locked -p saluki-app --lib byte_budget_attaches_only_when_memory_bounding_is_configured` - `cargo test --locked -p saluki-app -p datadog-agent-config-overlay-model -p datadog-agent-config-docs` - Requires: `ContextCache` idle eviction. - Required by: memory admission enforcement through `ByteBudget`. - Release note: `releasenotes/notes/dogstatsd-opt-in-memory-admission-da62a19d01c48d79.yaml` - Context & Tag Density: pack contexts into one allocation and drop unused cache overhead. - Dense Aggregation: replace 177 B buckets with per-kind typed pages. - Resumable Flush: shrink metric buffers and interleave bounded flush chunks. - Idle Pipeline Bypass: skip inactive transforms and borrow client telemetry. - `300m` CPU: cut encoder, codec and worker-pool hot-path cost. - **Memory Admission:** enforce opt-in configured memory limits with idle reclaim and counted drops. - **Current:** add an opt-in cgroup-aware `ByteBudget` and idle-cache reclaim hook - PR TBD: enforce memory admission with storage growth estimates, idle reclaim and drop telemetry --- .../configuration/configuration.md | 2 +- .../config-overlay-model/src/saluki_keys.rs | 6 +- lib/saluki-app/src/accounting.rs | 79 +++- lib/saluki-core/src/accounting/byte_budget.rs | 365 ++++++++++++++++++ lib/saluki-core/src/accounting/cgroup.rs | 149 +++++++ lib/saluki-core/src/accounting/limiter.rs | 16 +- lib/saluki-core/src/accounting/mod.rs | 6 + .../event/metric/context/context_cache.rs | 94 ++++- .../event/metric/context/resolver.rs | 7 + ...-in-memory-admission-da62a19d01c48d79.yaml | 5 + 10 files changed, 718 insertions(+), 11 deletions(-) create mode 100644 lib/saluki-core/src/accounting/byte_budget.rs create mode 100644 lib/saluki-core/src/accounting/cgroup.rs create mode 100644 releasenotes/notes/dogstatsd-opt-in-memory-admission-da62a19d01c48d79.yaml diff --git a/docs/agent-data-plane/configuration/configuration.md b/docs/agent-data-plane/configuration/configuration.md index 82278020053..f9af3fb1f9b 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`. DogStatsD memory admission also applies only under `permissive` and `strict`, using the lower of `memory_limit` and the Linux cgroup v2 memory limit, even when `enable_global_limiter` is `false`. Under `disabled`, admission stays off, even in a memory-limited container. 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..30fa8d8092c 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,11 @@ 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`. DogStatsD memory \ + admission also applies only under `permissive` and `strict`, using the lower of \ + `memory_limit` and the Linux cgroup v2 memory limit, even when \ + `enable_global_limiter` is `false`. Under `disabled`, admission stays off, even in a \ + memory-limited container.", ), }, ]; diff --git a/lib/saluki-app/src/accounting.rs b/lib/saluki-app/src/accounting.rs index e52d9aa0cac..b8f8a10dfe3 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,11 @@ 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. /// +/// When memory bounding is configured ([`MemoryMode::Permissive`] or [`MemoryMode::Strict`]), DogStatsD byte-budget +/// admission uses the configured limit or the cgroup v2 limit, whichever is lower, independently of the bounds +/// verification and backpressure settings. Under [`MemoryMode::Disabled`], no byte budget is attached, even inside a +/// cgroup with a finite memory limit. +/// /// See [`MemoryMode`] for details on the behavior of each mode. /// /// # Errors @@ -90,7 +95,7 @@ pub fn initialize_memory_bounds( let limiter_grant = match configuration.memory_mode { MemoryMode::Disabled => { - info!("Memory limiting disabled."); + info!("Memory bounds verification and cooperative backpressure disabled."); None } mode @ (MemoryMode::Permissive | MemoryMode::Strict) => match configured_grant { @@ -111,7 +116,42 @@ pub fn initialize_memory_bounds( _ => MemoryLimiter::noop(), }; - Ok(limiter) + // Admission remains active even when the independently configured cooperative backoff is disabled, but only when + // memory bounding is configured: the default mode stays unbounded even inside a memory-limited cgroup. + let cgroup = match configuration.memory_mode { + MemoryMode::Disabled => None, + MemoryMode::Permissive | MemoryMode::Strict => CgroupMemory::detect(), + }; + let budget_limit = byte_budget_limit( + configuration.memory_mode, + memory_limit.map(|limit| limit.as_u64() as usize), + cgroup.as_ref().map(CgroupMemory::limit), + ); + let budget = match (budget_limit, cgroup) { + (None, _) => None, + (Some(limit), Some(cgroup)) => ByteBudget::for_memory_limit(limit, move || cgroup.current()) + .ok_or_else(|| generic_error!("Cgroup memory usage cannot be monitored for byte-budget admission."))? + .into(), + (Some(limit), None) => ByteBudget::for_process_memory_limit(limit) + .ok_or_else(|| generic_error!("Process memory usage cannot be monitored for byte-budget admission."))? + .into(), + }; + + Ok(limiter.with_byte_budget(budget)) +} + +/// Returns the byte-budget admission limit, or `None` when no budget should be attached. +/// +/// A budget is attached only when memory bounding is configured, using the lower of the configured limit and the +/// finite cgroup limit when both exist. +fn byte_budget_limit(mode: MemoryMode, configured: Option, cgroup: Option) -> Option { + match mode { + MemoryMode::Disabled => None, + MemoryMode::Permissive | MemoryMode::Strict => match (configured, cgroup) { + (Some(configured), Some(cgroup)) => Some(configured.min(cgroup)), + (configured, cgroup) => configured.or(cgroup), + }, + } } fn verify_bounds_for_mode( @@ -433,11 +473,34 @@ 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] + fn byte_budget_attaches_only_when_memory_bounding_is_configured() { + const GIB: usize = 1024 * 1024 * 1024; + + // The default unbounded mode never attaches a budget, even inside a finite cgroup. + for (configured, cgroup) in [(None, Some(GIB)), (Some(GIB / 2), Some(GIB)), (Some(GIB), None)] { + assert_eq!(byte_budget_limit(MemoryMode::Disabled, configured, cgroup), None); + } + + // Configured bounding uses the lower of the configured and finite cgroup limits. + for mode in [MemoryMode::Permissive, MemoryMode::Strict] { + assert_eq!(byte_budget_limit(mode, None, Some(GIB)), Some(GIB)); + assert_eq!(byte_budget_limit(mode, Some(GIB / 2), None), Some(GIB / 2)); + assert_eq!(byte_budget_limit(mode, Some(GIB / 2), Some(GIB)), Some(GIB / 2)); + assert_eq!(byte_budget_limit(mode, Some(2 * GIB), Some(GIB)), Some(GIB)); + assert_eq!(byte_budget_limit(mode, None, None), None); + } } #[test] @@ -459,11 +522,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..743bfcaee35 --- /dev/null +++ b/lib/saluki-core/src/accounting/byte_budget.rs @@ -0,0 +1,365 @@ +//! 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 cgroup usage when available, or process RSS otherwise. +//! 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 unmetered 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::{ + sync::{ + atomic::{ + AtomicUsize, + Ordering::{Acquire, Relaxed, Release}, + }, + Arc, Mutex, Weak, + }, + thread, + time::{Duration, Instant}, +}; + +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, +} + +struct Observation { + bytes: usize, + usage: Option, +} + +#[derive(Default)] +struct Pressure { + last_reclaim: Option, + 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 when no cgroup memory limit is available. + /// + /// 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()) + } + + 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()), + })) + } + + /// Starts observing resident bytes against a memory limit, holding back headroom for unmetered work. + /// + /// 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, mut usage: impl FnMut() -> Option + Send + 'static) -> Option { + let initial = usage()?; + let headroom = (limit / 8).min(128 * MIB); + let budget = Self::with_usage(limit - headroom, 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)); + pressure.last_reclaim = None; + 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 { + let mut pressure = self.0.pressure.lock().unwrap(); + if self.charge(bytes) { + return true; + } + if pressure + .last_reclaim + .is_none_or(|last| last.elapsed() >= RECLAIM_INTERVAL) + { + pressure.reclaimers.retain(|reclaim| { + let Some(reclaim) = reclaim.upgrade() else { return false }; + reclaim(); + true + }); + self.0.refresh_usage(); + pressure.last_reclaim = Some(Instant::now()); + } + self.charge(bytes) + } +} + +impl State { + 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 synchronously before spending more credits or dropping this batch. +/// Refilling or dropping the batch returns unused credits and marks 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.publish(); + 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 + } + + fn publish(&mut self) { + let remaining = std::mem::take(&mut self.remaining); + let spent = std::mem::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.publish(); + } +} + +/// 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; + + 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 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()); + } +} diff --git a/lib/saluki-core/src/accounting/cgroup.rs b/lib/saluki-core/src/accounting/cgroup.rs new file mode 100644 index 00000000000..f3b670d16f9 --- /dev/null +++ b/lib/saluki-core/src/accounting/cgroup.rs @@ -0,0 +1,149 @@ +#[cfg(target_os = "linux")] +use std::{ + fs::{self, File}, + os::unix::fs::FileExt as _, + path::{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, std::path::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..3287817bfb6 --- /dev/null +++ b/releasenotes/notes/dogstatsd-opt-in-memory-admission-da62a19d01c48d79.yaml @@ -0,0 +1,5 @@ +fixes: + - | + Apply DogStatsD memory admission only when ``memory_mode`` is ``permissive`` or ``strict``. Admission then uses + the lower of ``memory_limit`` and the Linux cgroup v2 memory limit. Under the default ``disabled`` mode, ADP no + longer refuses DogStatsD lines or reclaims idle contexts, even in a memory-limited container. From 2d31885c05ce7aa91b2294f94e9835ae1e3fd8bd Mon Sep 17 00:00:00 2001 From: "Brian L. Troutwine" Date: Thu, 26 Nov 2026 23:49:55 +0000 Subject: [PATCH 2/4] fix(accounting): enforce independent memory limits without blocking reclaim retries --- .../configuration/configuration.md | 2 +- .../config-overlay-model/src/saluki_keys.rs | 9 +- lib/saluki-app/src/accounting.rs | 80 ++++------- lib/saluki-core/src/accounting/byte_budget.rs | 128 +++++++++++++++--- lib/saluki-core/src/accounting/cgroup.rs | 7 +- ...-in-memory-admission-da62a19d01c48d79.yaml | 7 +- 6 files changed, 143 insertions(+), 90 deletions(-) diff --git a/docs/agent-data-plane/configuration/configuration.md b/docs/agent-data-plane/configuration/configuration.md index f9af3fb1f9b..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`. DogStatsD memory admission also applies only under `permissive` and `strict`, using the lower of `memory_limit` and the Linux cgroup v2 memory limit, even when `enable_global_limiter` is `false`. Under `disabled`, admission stays off, even in a memory-limited container. +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 30fa8d8092c..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,11 +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`. DogStatsD memory \ - admission also applies only under `permissive` and `strict`, using the lower of \ - `memory_limit` and the Linux cgroup v2 memory limit, even when \ - `enable_global_limiter` is `false`. Under `disabled`, admission stays off, even in a \ - memory-limited container.", + 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 b8f8a10dfe3..6e26fee1144 100644 --- a/lib/saluki-app/src/accounting.rs +++ b/lib/saluki-app/src/accounting.rs @@ -72,10 +72,9 @@ 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. /// -/// When memory bounding is configured ([`MemoryMode::Permissive`] or [`MemoryMode::Strict`]), DogStatsD byte-budget -/// admission uses the configured limit or the cgroup v2 limit, whichever is lower, independently of the bounds -/// verification and backpressure settings. Under [`MemoryMode::Disabled`], no byte budget is attached, even inside a -/// cgroup with a finite memory limit. +/// 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. /// @@ -116,44 +115,32 @@ pub fn initialize_memory_bounds( _ => MemoryLimiter::noop(), }; - // Admission remains active even when the independently configured cooperative backoff is disabled, but only when - // memory bounding is configured: the default mode stays unbounded even inside a memory-limited cgroup. - let cgroup = match configuration.memory_mode { - MemoryMode::Disabled => None, - MemoryMode::Permissive | MemoryMode::Strict => CgroupMemory::detect(), - }; - let budget_limit = byte_budget_limit( - configuration.memory_mode, - memory_limit.map(|limit| limit.as_u64() as usize), - cgroup.as_ref().map(CgroupMemory::limit), - ); - let budget = match (budget_limit, cgroup) { - (None, _) => None, - (Some(limit), Some(cgroup)) => ByteBudget::for_memory_limit(limit, move || cgroup.current()) - .ok_or_else(|| generic_error!("Cgroup memory usage cannot be monitored for byte-budget admission."))? - .into(), - (Some(limit), None) => ByteBudget::for_process_memory_limit(limit) - .ok_or_else(|| generic_error!("Process memory usage cannot be monitored for byte-budget admission."))? - .into(), + 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)) } -/// Returns the byte-budget admission limit, or `None` when no budget should be attached. -/// -/// A budget is attached only when memory bounding is configured, using the lower of the configured limit and the -/// finite cgroup limit when both exist. -fn byte_budget_limit(mode: MemoryMode, configured: Option, cgroup: Option) -> Option { - match mode { - MemoryMode::Disabled => None, - MemoryMode::Permissive | MemoryMode::Strict => match (configured, cgroup) { - (Some(configured), Some(cgroup)) => Some(configured.min(cgroup)), - (configured, cgroup) => configured.or(cgroup), - }, - } -} - fn verify_bounds_for_mode( mode: MemoryMode, initial_grant: MemoryGrant, component_registry: &ComponentRegistryHandle, ) -> Result<(), GenericError> { @@ -484,25 +471,6 @@ mod tests { ); } - #[test] - fn byte_budget_attaches_only_when_memory_bounding_is_configured() { - const GIB: usize = 1024 * 1024 * 1024; - - // The default unbounded mode never attaches a budget, even inside a finite cgroup. - for (configured, cgroup) in [(None, Some(GIB)), (Some(GIB / 2), Some(GIB)), (Some(GIB), None)] { - assert_eq!(byte_budget_limit(MemoryMode::Disabled, configured, cgroup), None); - } - - // Configured bounding uses the lower of the configured and finite cgroup limits. - for mode in [MemoryMode::Permissive, MemoryMode::Strict] { - assert_eq!(byte_budget_limit(mode, None, Some(GIB)), Some(GIB)); - assert_eq!(byte_budget_limit(mode, Some(GIB / 2), None), Some(GIB / 2)); - assert_eq!(byte_budget_limit(mode, Some(GIB / 2), Some(GIB)), Some(GIB / 2)); - assert_eq!(byte_budget_limit(mode, Some(2 * GIB), Some(GIB)), Some(GIB)); - assert_eq!(byte_budget_limit(mode, None, None), None); - } - } - #[test] fn strict_memory_mode_rejects_bounds_exceeding_the_limit() { let registry = registry_with_firm_bound(64 * 1024 * 1024); diff --git a/lib/saluki-core/src/accounting/byte_budget.rs b/lib/saluki-core/src/accounting/byte_budget.rs index 743bfcaee35..596194a333d 100644 --- a/lib/saluki-core/src/accounting/byte_budget.rs +++ b/lib/saluki-core/src/accounting/byte_budget.rs @@ -3,12 +3,12 @@ //! # 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 cgroup usage when available, or process RSS otherwise. +//! 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 unmetered work depend on the workload. +//! 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. @@ -20,9 +20,10 @@ //! another pass when more idle memory becomes available. //! use std::{ + mem::take, sync::{ atomic::{ - AtomicUsize, + AtomicU64, AtomicUsize, Ordering::{Acquire, Relaxed, Release}, }, Arc, Mutex, Weak, @@ -31,6 +32,8 @@ use std::{ 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); @@ -53,6 +56,8 @@ struct State { completed: AtomicUsize, observation: Mutex, pressure: Mutex, + origin: Instant, + last_reclaim_ms: AtomicU64, } struct Observation { @@ -62,7 +67,6 @@ struct Observation { #[derive(Default)] struct Pressure { - last_reclaim: Option, reclaimers: Vec>, } @@ -74,7 +78,7 @@ impl ByteBudget { Self::with_usage(ceiling, observed_bytes, None) } - /// Starts observing the process working set when no cgroup memory limit is available. + /// 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 { @@ -82,6 +86,35 @@ impl ByteBudget { 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, @@ -89,19 +122,24 @@ impl ByteBudget { 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, holding back headroom for unmetered work. + /// 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, mut usage: impl FnMut() -> Option + Send + 'static) -> Option { + 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 headroom = (limit / 8).min(128 * MIB); - let budget = Self::with_usage(limit - headroom, initial, Some(Box::new(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()) @@ -121,7 +159,7 @@ impl ByteBudget { let reclaim = Arc::new(reclaim) as Arc; let mut pressure = self.0.pressure.lock().unwrap(); pressure.reclaimers.push(Arc::downgrade(&reclaim)); - pressure.last_reclaim = None; + self.0.last_reclaim_ms.store(0, Relaxed); BudgetReclaimer { _reclaim: reclaim } } @@ -160,27 +198,43 @@ impl ByteBudget { #[cold] fn reclaim_and_charge(&self, bytes: usize) -> bool { - let mut pressure = self.0.pressure.lock().unwrap(); + 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 pressure - .last_reclaim - .is_none_or(|last| last.elapsed() >= RECLAIM_INTERVAL) - { + 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(); - pressure.last_reclaim = Some(Instant::now()); + 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 }; @@ -246,8 +300,8 @@ impl ByteBudgetBatch { } fn publish(&mut self) { - let remaining = std::mem::take(&mut self.remaining); - let spent = std::mem::take(&mut self.spent); + let remaining = take(&mut self.remaining); + let spent = take(&mut self.spent); if remaining != 0 { self.budget.0.used.fetch_sub(remaining, Relaxed); } @@ -283,7 +337,7 @@ impl Drop for ByteReservation<'_> { #[cfg(test)] mod tests { - use std::sync::atomic::AtomicBool; + use std::sync::{atomic::AtomicBool, mpsc}; use super::*; @@ -362,4 +416,40 @@ mod tests { 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 index f3b670d16f9..e757c875088 100644 --- a/lib/saluki-core/src/accounting/cgroup.rs +++ b/lib/saluki-core/src/accounting/cgroup.rs @@ -2,7 +2,7 @@ use std::{ fs::{self, File}, os::unix::fs::FileExt as _, - path::{Path, PathBuf}, + path::{Component, Path, PathBuf}, }; /// A finite cgroup v2 memory limit and the usage charged against it. @@ -78,10 +78,7 @@ fn cgroup_limits(groups: &str, mounts: &str, read: impl Fn(&Path) -> Option Path::new(""), Err(_) => continue, }; - if relative - .components() - .any(|part| matches!(part, std::path::Component::ParentDir)) - { + if relative.components().any(|part| matches!(part, Component::ParentDir)) { continue; } for directory in mountpoint diff --git a/releasenotes/notes/dogstatsd-opt-in-memory-admission-da62a19d01c48d79.yaml b/releasenotes/notes/dogstatsd-opt-in-memory-admission-da62a19d01c48d79.yaml index 3287817bfb6..87df0f0459d 100644 --- a/releasenotes/notes/dogstatsd-opt-in-memory-admission-da62a19d01c48d79.yaml +++ b/releasenotes/notes/dogstatsd-opt-in-memory-admission-da62a19d01c48d79.yaml @@ -1,5 +1,4 @@ -fixes: +features: - | - Apply DogStatsD memory admission only when ``memory_mode`` is ``permissive`` or ``strict``. Admission then uses - the lower of ``memory_limit`` and the Linux cgroup v2 memory limit. Under the default ``disabled`` mode, ADP no - longer refuses DogStatsD lines or reclaims idle contexts, even in a memory-limited container. + 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. From 46097eada71ff991bd10901aa71fb9bb3f66ae0f Mon Sep 17 00:00:00 2001 From: "Brian L. Troutwine" Date: Fri, 27 Nov 2026 00:12:53 +0000 Subject: [PATCH 3/4] fix(accounting): allow releasing an idle byte budget batch Return unused credits and publish spent credits for reconciliation without dropping the reusable batch. --- lib/saluki-core/src/accounting/byte_budget.rs | 29 +++++++++++++++---- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/lib/saluki-core/src/accounting/byte_budget.rs b/lib/saluki-core/src/accounting/byte_budget.rs index 596194a333d..1cb79ecb53a 100644 --- a/lib/saluki-core/src/accounting/byte_budget.rs +++ b/lib/saluki-core/src/accounting/byte_budget.rs @@ -265,8 +265,8 @@ pub struct BudgetReclaimer { /// Local credits reserved against a shared [`ByteBudget`]. /// -/// Finish each operation synchronously before spending more credits or dropping this batch. -/// Refilling or dropping the batch returns unused credits and marks spent credits complete for reconciliation. +/// 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, @@ -287,7 +287,7 @@ impl ByteBudgetBatch { #[cold] fn refill(&mut self, bytes: usize) -> bool { - self.publish(); + self.release(); let chunk = bytes.max(INGEST_CREDIT_BYTES); if self.budget.charge(chunk) { self.remaining = chunk; @@ -299,7 +299,10 @@ impl ByteBudgetBatch { true } - fn publish(&mut self) { + /// 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 { @@ -313,7 +316,7 @@ impl ByteBudgetBatch { impl Drop for ByteBudgetBatch { fn drop(&mut self) { - self.publish(); + self.release(); } } @@ -373,6 +376,22 @@ mod tests { 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)); From 164898b2d0407152dc58049d649c0e2506e22d37 Mon Sep 17 00:00:00 2001 From: "Brian L. Troutwine" Date: Fri, 27 Nov 2026 00:59:44 +0000 Subject: [PATCH 4/4] fix(saluki-app): keep disabled memory-mode log message for integration compatibility --- lib/saluki-app/src/accounting.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/saluki-app/src/accounting.rs b/lib/saluki-app/src/accounting.rs index 6e26fee1144..3e76130448c 100644 --- a/lib/saluki-app/src/accounting.rs +++ b/lib/saluki-app/src/accounting.rs @@ -94,7 +94,7 @@ pub fn initialize_memory_bounds( let limiter_grant = match configuration.memory_mode { MemoryMode::Disabled => { - info!("Memory bounds verification and cooperative backpressure disabled."); + info!("Memory limiting disabled."); None } mode @ (MemoryMode::Permissive | MemoryMode::Strict) => match configured_grant {