Skip to main content

mz_compute/
memory_limiter.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Utilities to limit memory usage.
11//!
12//! In the context of this module, "memory" refers to the sum of physical memory and swap space .
13//! Other parts of the code usually don't include swap space when talking about "memory".
14
15use std::sync::Mutex;
16use std::time::{Duration, Instant};
17
18use mz_compute_types::dyncfgs::{
19    MEMORY_LIMITER_BURST_FACTOR, MEMORY_LIMITER_INTERVAL, MEMORY_LIMITER_USAGE_BIAS,
20};
21use mz_dyncfg::ConfigSet;
22use mz_metrics::usage::ProcStatus;
23use mz_ore::cast::{CastFrom, CastLossy};
24use mz_ore::metric;
25use mz_ore::metrics::{MetricsRegistry, UIntGauge};
26use prometheus::Histogram;
27use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
28use tracing::{debug, error, info, warn};
29
30/// A handle to the active memory limiter.
31///
32/// The limiter is initialized by a call to [`start_limiter`]. It spawns a process-global task that
33/// runs for the lifetime of the process.
34static LIMITER: Mutex<Option<Limiter>> = Mutex::new(None);
35
36/// Start the process-global memory limiter.
37///
38/// # Panics
39///
40/// Panics if the limiter was already started previously.
41pub fn start_limiter(memory_limit: usize, metrics_registry: &MetricsRegistry) {
42    let mut limiter = LIMITER.lock().expect("poisoned");
43
44    if limiter.is_some() {
45        panic!("memory limiter is already running");
46    }
47
48    let metrics = LimiterMetrics::new(metrics_registry);
49    let (config_tx, config_rx) = mpsc::unbounded_channel();
50
51    mz_ore::task::spawn(|| "memory-limiter", LimiterTask::run(config_rx, metrics));
52
53    *limiter = Some(Limiter {
54        base_memory_limit: memory_limit,
55        effective_memory_limit: memory_limit,
56        config_tx,
57    });
58}
59
60/// Apply the given configuration to the active limiter.
61pub fn apply_limiter_config(config: &ConfigSet) {
62    if let Some(limiter) = LIMITER.lock().expect("poisoned").as_mut() {
63        limiter.apply_config(config);
64    }
65}
66
67/// Get the current effective memory limit.
68pub fn get_memory_limit() -> Option<usize> {
69    let limiter = LIMITER.lock().expect("poisoned");
70    limiter.as_ref().map(|l| l.effective_memory_limit)
71}
72
73/// A handle to a running memory limiter task.
74struct Limiter {
75    /// The base process memory limit.
76    base_memory_limit: usize,
77    /// The effective memory limit, obtained by applying dyncfgs to the base limit.
78    effective_memory_limit: usize,
79    /// A sender for limiter configuration updates.
80    config_tx: UnboundedSender<LimiterConfig>,
81}
82
83impl Limiter {
84    /// Apply the given configuration to the limiter.
85    fn apply_config(&mut self, config: &ConfigSet) {
86        let mut interval = MEMORY_LIMITER_INTERVAL.get(config);
87        // A zero duration means the limiter is disabled. Translate that into an ~infinite duration
88        // so the limiter doesn't have to worry about the special case.
89        if interval.is_zero() {
90            interval = Duration::MAX;
91        }
92
93        let memory_limit =
94            f64::cast_lossy(self.base_memory_limit) * MEMORY_LIMITER_USAGE_BIAS.get(config);
95        let memory_limit = usize::cast_lossy(memory_limit);
96
97        let burst_budget = f64::cast_lossy(memory_limit) * MEMORY_LIMITER_BURST_FACTOR.get(config);
98        let burst_budget = usize::cast_lossy(burst_budget);
99
100        self.effective_memory_limit = memory_limit;
101
102        self.config_tx
103            .send(LimiterConfig {
104                interval,
105                memory_limit,
106                burst_budget,
107            })
108            .expect("limiter task never shuts down");
109    }
110}
111
112/// Configuration for an memory limiter task.
113#[derive(Clone, Copy, Debug, PartialEq, Eq)]
114struct LimiterConfig {
115    /// The interval at which memory usage is checked against the memory limit.
116    interval: Duration,
117    /// The memory limit.
118    memory_limit: usize,
119    /// Budget to allow memory usage above the memory limit, in byte-seconds.
120    burst_budget: usize,
121}
122
123impl LimiterConfig {
124    /// Return a config that disables the memory limiter.
125    fn disabled() -> Self {
126        Self {
127            interval: Duration::MAX,
128            memory_limit: 0,
129            burst_budget: 0,
130        }
131    }
132}
133
134/// A task that enforces configured memory limits.
135///
136/// The task operates by performing limit checks at a configured interval. For each check it
137/// obtains the current memory utilization from proc stats. It then compares the utilization against
138/// the configured memory limit, and if it exceeds the limit, reduces the burst budget by the amount
139/// of memory utilization that exceeds the limit. If the burst budget is exhausted, the limiter
140/// terminates the process.
141struct LimiterTask {
142    /// The current limiter configuration.
143    config: LimiterConfig,
144    /// The amount of burst budget remaining.
145    burst_budget_remaining: usize,
146    /// The time of the last check.
147    last_check: Instant,
148    /// Metrics tracked by the limiter task.
149    metrics: LimiterMetrics,
150}
151
152impl LimiterTask {
153    async fn run(mut config_rx: UnboundedReceiver<LimiterConfig>, metrics: LimiterMetrics) {
154        info!("running memory limiter task");
155
156        let mut task = Self {
157            config: LimiterConfig::disabled(),
158            burst_budget_remaining: 0,
159            last_check: Instant::now(),
160            metrics,
161        };
162
163        loop {
164            tokio::select! {
165                _ = task.tick() => {
166                    let start = Instant::now();
167
168                    if let Err(err) = task.check() {
169                        error!("memory limit check failed: {err}");
170                    }
171
172                    let elapsed = start.elapsed();
173                    task.metrics.duration.observe(elapsed.as_secs_f64());
174                }
175                Some(config) = config_rx.recv() => task.apply_config(config),
176            }
177        }
178    }
179
180    /// Wait until the next check time.
181    async fn tick(&self) {
182        let elapsed = self.last_check.elapsed();
183        let duration = self.config.interval.saturating_sub(elapsed);
184        tokio::time::sleep(duration).await
185    }
186
187    fn current_utilization() -> anyhow::Result<ProcStatus> {
188        match ProcStatus::from_proc() {
189            Ok(status) => Ok(status),
190            #[cfg(target_os = "linux")]
191            Err(err) => {
192                error!("failed to read /proc/self/status: {err}");
193                Err(err)
194            }
195            #[cfg(not(target_os = "linux"))]
196            Err(_err) => Ok(ProcStatus::default()),
197        }
198    }
199
200    /// Perform a memory usage check, terminating the process if the configured limits are exceeded.
201    fn check(&mut self) -> Result<(), anyhow::Error> {
202        debug!("checking memory limits");
203
204        let ProcStatus {
205            vm_rss, vm_swap, ..
206        } = Self::current_utilization()?;
207
208        let memory_limit = self.config.memory_limit;
209        let burst_budget_remaining = self.burst_budget_remaining;
210
211        let memory_usage = vm_rss + vm_swap;
212
213        debug!(
214            memory_usage,
215            memory_limit, burst_budget_remaining, vm_rss, vm_swap, "memory utilization check",
216        );
217
218        self.metrics.vm_rss.set(u64::cast_from(vm_rss));
219        self.metrics.vm_swap.set(u64::cast_from(vm_swap));
220        self.metrics.memory_usage.set(u64::cast_from(memory_usage));
221        self.metrics
222            .burst_budget
223            .set(u64::cast_from(burst_budget_remaining));
224
225        if memory_usage > memory_limit {
226            // Calculate excess usage in byte-seconds.
227            let elapsed = self.last_check.elapsed().as_secs_f64();
228            let excess = memory_usage - memory_limit;
229            let excess_bs = usize::cast_lossy(f64::cast_lossy(excess) * elapsed);
230
231            if burst_budget_remaining >= excess_bs {
232                self.burst_budget_remaining -= excess_bs;
233            } else {
234                // Burst budget exhausted, terminate the process.
235                warn!(
236                    memory_usage,
237                    memory_limit, "memory utilization exceeded configured limits",
238                );
239                // We terminate with a recognizable exit code so the orchestrator knows the
240                // termination was caused by exceeding memory limits, as opposed to another,
241                // unexpected cause.
242                mz_ore::process::exit_thread_safe(167);
243            }
244        } else {
245            // Reset burst budget if under limit.
246            self.burst_budget_remaining = self.config.burst_budget;
247        }
248
249        self.last_check = Instant::now();
250        Ok(())
251    }
252
253    /// Apply a new limiter config.
254    fn apply_config(&mut self, config: LimiterConfig) {
255        if config == self.config {
256            return; // no-op config change
257        }
258
259        info!(?config, "applying memory limiter config");
260        self.config = config;
261        self.burst_budget_remaining = config.burst_budget;
262        // Reset `last_check` so the next `check` measures the excess interval
263        // against the new config, not against a stale checkpoint left over from
264        // a period when the limiter was disabled or running with a different
265        // interval. Without this, enabling the limiter at runtime can charge an
266        // arbitrarily large excess byte-second amount against the burst budget
267        // and immediately terminate the process.
268        self.last_check = Instant::now();
269
270        self.metrics
271            .memory_limit
272            .set(u64::cast_from(config.memory_limit));
273    }
274}
275
276struct LimiterMetrics {
277    duration: Histogram,
278    memory_limit: UIntGauge,
279    memory_usage: UIntGauge,
280    vm_rss: UIntGauge,
281    vm_swap: UIntGauge,
282    burst_budget: UIntGauge,
283}
284
285impl LimiterMetrics {
286    fn new(registry: &MetricsRegistry) -> Self {
287        Self {
288            duration: registry.register(metric!(
289                name: "mz_memory_limiter_duration_seconds",
290                help: "A histogram of the time it took to run the memory limiter.",
291                buckets: mz_ore::stats::histogram_seconds_buckets(0.000_500, 32.),
292            )),
293            memory_limit: registry.register(metric!(
294                name: "mz_memory_limiter_memory_limit_bytes",
295                help: "The configured memory limit.",
296            )),
297            memory_usage: registry.register(metric!(
298                name: "mz_memory_limiter_memory_usage_bytes",
299                help: "The current memory usage.",
300            )),
301            vm_rss: registry.register(metric!(
302                name: "mz_memory_limiter_vm_rss_bytes",
303                help: "The current VmRSS metric.",
304            )),
305            vm_swap: registry.register(metric!(
306                name: "mz_memory_limiter_vm_swap_bytes",
307                help: "The current VmSwap metric.",
308            )),
309            burst_budget: registry.register(metric!(
310                name: "mz_memory_limiter_burst_budget_byteseconds",
311                help: "The remaining memory burst budget.",
312            )),
313        }
314    }
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320
321    fn task_for_test() -> LimiterTask {
322        let registry = MetricsRegistry::new();
323        let metrics = LimiterMetrics::new(&registry);
324        LimiterTask {
325            config: LimiterConfig::disabled(),
326            burst_budget_remaining: 0,
327            last_check: Instant::now(),
328            metrics,
329        }
330    }
331
332    /// Regression test for an issue where enabling the limiter at runtime would
333    /// immediately terminate the process because `last_check` had not been
334    /// advanced since task startup. After `apply_config` the next `check` would
335    /// see a huge `elapsed`, multiply it with the over-limit memory amount, and
336    /// instantly exhaust the burst budget.
337    #[mz_ore::test]
338    fn apply_config_resets_last_check() {
339        let mut task = task_for_test();
340
341        // Simulate a long period during which the limiter was disabled and
342        // `last_check` was never refreshed.
343        let stale = Instant::now() - Duration::from_secs(3600);
344        task.last_check = stale;
345
346        let new_config = LimiterConfig {
347            interval: Duration::from_secs(1),
348            memory_limit: 1024,
349            burst_budget: 1024,
350        };
351        task.apply_config(new_config);
352
353        assert!(
354            task.last_check > stale,
355            "apply_config must refresh last_check to avoid charging stale elapsed time \
356             against the burst budget when the limiter is enabled at runtime"
357        );
358        assert!(
359            task.last_check.elapsed() < Duration::from_secs(60),
360            "last_check should be ~now after apply_config"
361        );
362    }
363
364    /// A no-op config change must not refresh `last_check`, otherwise repeated
365    /// no-op calls would silently delay the next limit check.
366    #[mz_ore::test]
367    fn apply_config_noop_keeps_last_check() {
368        let mut task = task_for_test();
369        let stale = Instant::now() - Duration::from_secs(60);
370        task.last_check = stale;
371
372        task.apply_config(LimiterConfig::disabled());
373
374        assert_eq!(task.last_check, stale);
375    }
376}