Skip to main content

aft_base/
memory.rs

1use std::collections::BTreeMap;
2use std::path::Path;
3
4use serde::Serialize;
5use serde_json::Value;
6
7/// A cold-path estimate of memory AFT can attribute without allocator hooks.
8///
9/// `estimated_bytes` is `None` when a subsystem is busy or its resident bytes
10/// are not cheaply observable. Counts remain available in those cases so the
11/// status response never substitutes a fabricated byte estimate.
12#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
13pub struct MemoryEstimate {
14    pub status: &'static str,
15    pub bytes_status: &'static str,
16    pub estimated_bytes: Option<u64>,
17    #[serde(skip_serializing_if = "Vec::is_empty")]
18    pub not_estimated: Vec<String>,
19    #[serde(flatten)]
20    pub counts: BTreeMap<String, u64>,
21}
22
23impl MemoryEstimate {
24    pub fn estimated(bytes: u64) -> Self {
25        Self {
26            status: "ready",
27            bytes_status: "estimated",
28            estimated_bytes: Some(bytes),
29            not_estimated: Vec::new(),
30            counts: BTreeMap::new(),
31        }
32    }
33
34    pub fn partial(bytes: u64) -> Self {
35        Self {
36            status: "ready",
37            bytes_status: "partial",
38            estimated_bytes: Some(bytes),
39            not_estimated: Vec::new(),
40            counts: BTreeMap::new(),
41        }
42    }
43
44    pub fn not_estimated() -> Self {
45        Self {
46            status: "ready",
47            bytes_status: "not_estimated",
48            estimated_bytes: None,
49            not_estimated: Vec::new(),
50            counts: BTreeMap::new(),
51        }
52    }
53
54    pub fn busy() -> Self {
55        Self {
56            status: "busy",
57            bytes_status: "not_estimated",
58            estimated_bytes: None,
59            not_estimated: Vec::new(),
60            counts: BTreeMap::new(),
61        }
62    }
63
64    pub fn count(mut self, name: impl Into<String>, value: usize) -> Self {
65        self.counts.insert(name.into(), usize_to_u64(value));
66        self
67    }
68
69    pub fn count_u64(mut self, name: impl Into<String>, value: u64) -> Self {
70        self.counts.insert(name.into(), value);
71        self
72    }
73
74    pub fn gap(mut self, name: impl Into<String>) -> Self {
75        self.not_estimated.push(name.into());
76        self
77    }
78}
79
80#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
81pub struct RootMemorySnapshot {
82    pub status: &'static str,
83    pub attributed_bytes: u64,
84    pub semantic: MemoryEstimate,
85    pub trigram: MemoryEstimate,
86    pub symbols: MemoryEstimate,
87    pub callgraph: MemoryEstimate,
88    pub callgraph_projection: MemoryEstimate,
89    pub inspect: MemoryEstimate,
90    pub bash: MemoryEstimate,
91    pub lsp: MemoryEstimate,
92    pub parser_pool: MemoryEstimate,
93    /// Finished artifact loads handed off by their loader but not yet
94    /// installed. Zero almost always; it is a label of its own so a load that
95    /// waits is never invisible.
96    pub pending_install: MemoryEstimate,
97    pub exact_memo: MemoryEstimate,
98    pub compression_filters: MemoryEstimate,
99    /// What the root's checkout in the data layer holds that its planes
100    /// share: the checkout state lists, its open segments and its snapshot.
101    /// The bytes each plane holds alone are in `trigram` (text), `callgraph`
102    /// and `semantic` (meaning search), each as `data_layer_bytes`; the
103    /// block cache every checkout shares is counted once per process.
104    /// Present only while the data layer runs.
105    #[serde(skip_serializing_if = "Option::is_none")]
106    pub data_layer: Option<MemoryEstimate>,
107}
108
109#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
110pub struct RootMemoryRollup {
111    pub status: &'static str,
112    pub attributed_bytes: u64,
113    pub busy_subsystems: usize,
114    pub not_estimated_subsystems: usize,
115    /// Present only for roots declared as standing. Keeping the marker on the
116    /// existing row uses the same top-eight selection and one omitted-roots
117    /// rollup instead of creating a separate standing-memory table.
118    #[serde(skip_serializing_if = "Option::is_none")]
119    pub standing: Option<bool>,
120    /// How long ago the index walks behind this row were made, when the
121    /// health rollup reused an earlier walk (0 for a walk made now). Unset
122    /// outside the health rollup.
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub measured_age_ms: Option<u64>,
125}
126
127impl RootMemoryRollup {
128    pub fn from_estimates(estimates: &[&MemoryEstimate]) -> Self {
129        let attributed_bytes = estimates
130            .iter()
131            .filter_map(|estimate| estimate.estimated_bytes)
132            .fold(0u64, u64::saturating_add);
133        let busy_subsystems = estimates
134            .iter()
135            .filter(|estimate| estimate.status == "busy")
136            .count();
137        let not_estimated_subsystems = estimates
138            .iter()
139            .filter(|estimate| estimate.estimated_bytes.is_none())
140            .count();
141        Self {
142            status: if busy_subsystems > 0 { "busy" } else { "ready" },
143            attributed_bytes,
144            busy_subsystems,
145            not_estimated_subsystems,
146            standing: None,
147            measured_age_ms: None,
148        }
149    }
150
151    /// Record how old the index walks behind this row are.
152    pub fn with_measured_age_ms(mut self, age_ms: u64) -> Self {
153        self.measured_age_ms = Some(age_ms);
154        self
155    }
156
157    /// Attribute this existing per-root rollup to a configured standing entry.
158    pub fn with_standing(mut self) -> Self {
159        self.standing = Some(true);
160        self
161    }
162}
163
164impl RootMemorySnapshot {
165    pub fn new(
166        semantic: MemoryEstimate,
167        trigram: MemoryEstimate,
168        symbols: MemoryEstimate,
169        callgraph: MemoryEstimate,
170        callgraph_projection: MemoryEstimate,
171        inspect: MemoryEstimate,
172        bash: MemoryEstimate,
173        lsp: MemoryEstimate,
174        parser_pool: MemoryEstimate,
175    ) -> Self {
176        let rollup = RootMemoryRollup::from_estimates(&[
177            &semantic,
178            &trigram,
179            &symbols,
180            &callgraph,
181            &callgraph_projection,
182            &inspect,
183            &bash,
184            &lsp,
185            &parser_pool,
186        ]);
187        Self {
188            status: rollup.status,
189            attributed_bytes: rollup.attributed_bytes,
190            semantic,
191            trigram,
192            symbols,
193            callgraph,
194            callgraph_projection,
195            inspect,
196            bash,
197            lsp,
198            parser_pool,
199            pending_install: MemoryEstimate::estimated(0),
200            exact_memo: MemoryEstimate::estimated(0),
201            compression_filters: MemoryEstimate::estimated(0),
202            data_layer: None,
203        }
204    }
205
206    /// Attach the data layer's estimate for this root, when it runs, and
207    /// fold it into the root's status and attributed total.
208    pub fn with_data_layer(mut self, data_layer: Option<MemoryEstimate>) -> Self {
209        self.data_layer = data_layer;
210        let rollup = self.rollup();
211        self.status = rollup.status;
212        self.attributed_bytes = rollup.attributed_bytes;
213        self
214    }
215
216    /// Attach the finished-but-uninstalled load estimate and fold it into the
217    /// root's status and attributed total.
218    pub fn with_pending_install(mut self, pending_install: MemoryEstimate) -> Self {
219        self.pending_install = pending_install;
220        let rollup = self.rollup();
221        self.status = rollup.status;
222        self.attributed_bytes = rollup.attributed_bytes;
223        self
224    }
225
226    pub fn with_query_caches(
227        mut self,
228        exact_memo: MemoryEstimate,
229        compression_filters: MemoryEstimate,
230    ) -> Self {
231        self.exact_memo = exact_memo;
232        self.compression_filters = compression_filters;
233        let rollup = self.rollup();
234        self.status = rollup.status;
235        self.attributed_bytes = rollup.attributed_bytes;
236        self
237    }
238
239    pub fn rollup(&self) -> RootMemoryRollup {
240        let mut estimates = vec![
241            &self.semantic,
242            &self.trigram,
243            &self.symbols,
244            &self.callgraph,
245            &self.callgraph_projection,
246            &self.inspect,
247            &self.bash,
248            &self.lsp,
249            &self.parser_pool,
250            &self.pending_install,
251            &self.exact_memo,
252            &self.compression_filters,
253        ];
254        estimates.extend(self.data_layer.as_ref());
255        RootMemoryRollup::from_estimates(&estimates)
256    }
257
258    pub fn busy_subsystem_count(&self) -> usize {
259        self.rollup().busy_subsystems
260    }
261
262    pub fn not_estimated_subsystem_count(&self) -> usize {
263        self.rollup().not_estimated_subsystems
264    }
265
266    /// Bytes released when the root goes idle: retained index handles,
267    /// symbol data, inspect caches, and the data layer's checkout, which the
268    /// idle reaper's release drops (its planes' bytes are in `trigram`,
269    /// `semantic` and `callgraph`, what they share in `data_layer`). This
270    /// deliberately shares the already-collected estimates instead of taking
271    /// a second estimate on the reply path.
272    pub fn evictable_bytes(&self) -> u64 {
273        [
274            &self.trigram,
275            &self.semantic,
276            &self.symbols,
277            &self.callgraph,
278            &self.inspect,
279            &self.exact_memo,
280        ]
281        .into_iter()
282        .chain(self.data_layer.as_ref())
283        .filter_map(|estimate| estimate.estimated_bytes)
284        .fold(0, u64::saturating_add)
285    }
286}
287
288#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
289pub struct SqliteMemorySnapshot {
290    pub status: &'static str,
291    pub memory_used_bytes: u64,
292    pub memory_highwater_bytes: u64,
293}
294
295impl SqliteMemorySnapshot {
296    pub fn measure() -> Self {
297        // SQLite's allocator counters are process-wide and internally synchronized.
298        // They intentionally replace per-connection guesses in root estimates.
299        let memory_used = unsafe { rusqlite::ffi::sqlite3_memory_used() };
300        let memory_highwater = unsafe { rusqlite::ffi::sqlite3_memory_highwater(0) };
301        Self {
302            status: "measured",
303            memory_used_bytes: nonnegative_i64_to_u64(memory_used),
304            memory_highwater_bytes: nonnegative_i64_to_u64(memory_highwater),
305        }
306    }
307}
308
309/// What `retained_slack_bytes` / `allocator_slack_bytes` measure, shown next to
310/// the number wherever it is reported so nobody reads it as resident memory.
311pub const ALLOCATOR_SLACK_LABEL: &str = "address-space slack: allocator-mapped bytes minus in-use bytes; includes free pages already returned to the OS, so it is not resident memory";
312
313#[cfg(target_os = "linux")]
314#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
315pub struct JemallocMemorySnapshot {
316    pub accounting_source: &'static str,
317    pub allocated: u64,
318    pub active: u64,
319    pub resident: u64,
320    pub retained: u64,
321}
322
323#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
324pub struct AllocatorMemorySnapshot {
325    pub status: &'static str,
326    pub bytes_in_use: Option<u64>,
327    pub size_allocated: Option<u64>,
328    /// Address-space slack: `size_allocated - bytes_in_use`. This is NOT
329    /// resident memory. Allocators can return free pages without releasing the
330    /// address space. Slack can therefore exceed RSS.
331    pub retained_slack_bytes: Option<u64>,
332    /// Always `ALLOCATOR_SLACK_LABEL`; serialized so status readers see what
333    /// `retained_slack_bytes` means.
334    pub retained_slack_label: &'static str,
335    #[serde(skip_serializing_if = "Option::is_none")]
336    pub not_estimated: Option<&'static str>,
337    #[cfg(target_os = "linux")]
338    #[serde(skip_serializing_if = "Option::is_none")]
339    pub jemalloc: Option<JemallocMemorySnapshot>,
340}
341
342impl AllocatorMemorySnapshot {
343    #[cfg(any(target_os = "macos", target_os = "linux"))]
344    fn measured(bytes_in_use: u64, size_allocated: u64) -> Self {
345        Self {
346            status: "measured",
347            bytes_in_use: Some(bytes_in_use),
348            size_allocated: Some(size_allocated),
349            retained_slack_bytes: Some(size_allocated.saturating_sub(bytes_in_use)),
350            retained_slack_label: ALLOCATOR_SLACK_LABEL,
351            not_estimated: None,
352            #[cfg(target_os = "linux")]
353            jemalloc: None,
354        }
355    }
356
357    // A supported allocator can also fail to provide a measurement at runtime.
358    #[cfg_attr(target_os = "macos", allow(dead_code))]
359    fn not_estimated(reason: &'static str) -> Self {
360        Self {
361            status: "not_estimated_on_this_platform",
362            bytes_in_use: None,
363            size_allocated: None,
364            retained_slack_bytes: None,
365            retained_slack_label: ALLOCATOR_SLACK_LABEL,
366            not_estimated: Some(reason),
367            #[cfg(target_os = "linux")]
368            jemalloc: None,
369        }
370    }
371
372    fn unavailable(reason: &'static str) -> Self {
373        Self {
374            status: "unavailable",
375            ..Self::not_estimated(reason)
376        }
377    }
378}
379
380#[derive(Debug, Clone, Copy, PartialEq, Eq)]
381pub enum AllocatorSource {
382    /// Use the process-wide observation published by a sampler or health refresh.
383    Cached,
384    /// Walk allocator statistics now and publish the result for future cached reads.
385    Measure,
386}
387
388/// One allocator reading shared by all memory surfaces in a health refresh.
389#[derive(Clone)]
390pub struct AllocatorObservation {
391    pub snapshot: AllocatorMemorySnapshot,
392    pub age_ms: Option<u64>,
393}
394
395impl AllocatorObservation {
396    pub fn from_source(source: AllocatorSource) -> Self {
397        let (snapshot, age_ms) = allocator_observation(source);
398        Self { snapshot, age_ms }
399    }
400
401    pub fn measure() -> Self {
402        Self::from_source(AllocatorSource::Measure)
403    }
404}
405
406#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
407pub struct ProcessMemorySnapshot {
408    pub rss_status: &'static str,
409    pub rss_bytes: Option<u64>,
410    /// Kernel physical footprint (macOS `phys_footprint`): dirty + compressed +
411    /// IOKit pages, excluding clean/reclaimable ones. This is the number
412    /// Activity Monitor's "Real Memory" and the OOM killer use. RSS counts
413    /// MADV_FREE pages the allocator has already surrendered (the kernel
414    /// reclaims them lazily), so RSS can read gigabytes above what the process
415    /// actually holds — observed 5.1 GB RSS over a 610 MB footprint. None on
416    /// non-macOS platforms (Linux RSS does not have this skew; MADV_FREE'd
417    /// pages leave Linux RSS on reclaim, not on advice).
418    #[serde(skip_serializing_if = "Option::is_none")]
419    pub phys_footprint_bytes: Option<u64>,
420    #[serde(skip_serializing_if = "Option::is_none")]
421    pub rss_not_estimated: Option<&'static str>,
422    pub sqlite: SqliteMemorySnapshot,
423    /// Allocator bytes overlap the attributed subsystem totals and are an
424    /// allocation envelope, not another amount to subtract from RSS.
425    pub allocator: AllocatorMemorySnapshot,
426    /// Whether allocator slack came from an available allocator measurement.
427    pub allocator_slack_measured: bool,
428    /// Age of the cached allocator observation. A direct measurement is age zero;
429    /// a request-path read is null until the first process-wide observation exists.
430    pub allocator_observation_age_ms: Option<u64>,
431    pub total_attributed_bytes: u64,
432    /// Live local ONNX embedding sessions, shared across roots and query/build workers.
433    pub embedding_sessions: u64,
434    /// Serialized weight bytes for those sessions, counted once per session.
435    /// This estimates model storage, not ORT's transient tensors or allocator slack.
436    pub embedding_model_bytes: u64,
437    /// Bytes resident in the data layer's block cache, shared by every
438    /// checkout and counted once here. Included in `total_attributed_bytes`.
439    /// Present only once a checkout of this process has bound.
440    #[serde(skip_serializing_if = "Option::is_none")]
441    pub data_layer_block_cache_bytes: Option<u64>,
442    pub unattributed_bytes: Option<i64>,
443    pub root_count: usize,
444    pub busy_subsystems: usize,
445    pub not_estimated_subsystems: usize,
446}
447
448/// Source label for `AllocatorPressureRelief::allocator_accounting_bytes` on
449/// Linux: the drop in jemalloc's `stats.resident`, not the kernel's RSS.
450pub const RELIEF_ACCOUNTING_SOURCE_JEMALLOC: &str = "jemalloc_stats_resident_drop";
451/// Source label for `AllocatorPressureRelief::allocator_accounting_bytes` on
452/// macOS: the byte count `malloc_zone_pressure_relief` returns, i.e. what
453/// libmalloc says it handed back. It is the allocator's own claim, not a
454/// measurement of resident memory.
455pub const RELIEF_ACCOUNTING_SOURCE_MACOS: &str = "malloc_zone_pressure_relief_return";
456
457/// Resident-memory readings taken on each side of a relief pass.
458#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
459pub struct ResidentReading {
460    pub rss_bytes: Option<u64>,
461    /// macOS only; `None` elsewhere.
462    pub phys_footprint_bytes: Option<u64>,
463}
464
465impl ResidentReading {
466    #[cfg_attr(not(any(target_os = "macos", target_os = "linux")), allow(dead_code))]
467    fn read() -> Self {
468        Self {
469            rss_bytes: process_rss_bytes(),
470            phys_footprint_bytes: process_phys_footprint_bytes(),
471        }
472    }
473}
474
475/// What one allocator relief pass observed. There is deliberately no single
476/// "released" number: the allocator's accounting and the process's resident
477/// memory measure different things and disagree in practice.
478#[derive(Debug, Clone, PartialEq, Eq)]
479pub struct AllocatorPressureRelief {
480    /// Bytes the allocator's own accounting says the pass returned. What it
481    /// measures depends on the platform; see `allocator_accounting_source`.
482    pub allocator_accounting_bytes: u64,
483    /// Names the allocator counter used, independently of the kernel readings.
484    pub allocator_accounting_source: &'static str,
485    /// Observed RSS drop across the pass (`rss_before - rss_after`, floored at
486    /// zero). `None` when either reading is unavailable. Other threads can
487    /// allocate or free during the pass, so this is an observation of the
488    /// process, not an exact attribution to the allocator.
489    pub rss_drop_bytes: Option<u64>,
490    /// Observed physical-footprint drop across the pass (macOS only). macOS
491    /// relief marks pages reusable, which lowers the footprint right away but
492    /// can leave them counted in RSS until the kernel reclaims them, so on
493    /// macOS this is the better observable than `rss_drop_bytes`.
494    pub phys_footprint_drop_bytes: Option<u64>,
495    pub rss_before_bytes: Option<u64>,
496    pub rss_after_bytes: Option<u64>,
497    pub phys_footprint_before_bytes: Option<u64>,
498    pub phys_footprint_after_bytes: Option<u64>,
499    pub allocator_before: AllocatorMemorySnapshot,
500    pub allocator_after: AllocatorMemorySnapshot,
501}
502
503impl AllocatorPressureRelief {
504    /// Assemble a relief record from the readings around the pass. The
505    /// resident drops come only from the resident readings; the allocator
506    /// figure comes only from the allocator. Keeping them apart is the point.
507    #[cfg_attr(not(any(target_os = "macos", target_os = "linux")), allow(dead_code))]
508    fn from_observations(
509        allocator_accounting_bytes: u64,
510        allocator_accounting_source: &'static str,
511        resident_before: ResidentReading,
512        resident_after: ResidentReading,
513        allocator_before: AllocatorMemorySnapshot,
514        allocator_after: AllocatorMemorySnapshot,
515    ) -> Self {
516        let drop = |before: Option<u64>, after: Option<u64>| {
517            before
518                .zip(after)
519                .map(|(before, after)| before.saturating_sub(after))
520        };
521        Self {
522            allocator_accounting_bytes,
523            allocator_accounting_source,
524            rss_drop_bytes: drop(resident_before.rss_bytes, resident_after.rss_bytes),
525            phys_footprint_drop_bytes: drop(
526                resident_before.phys_footprint_bytes,
527                resident_after.phys_footprint_bytes,
528            ),
529            rss_before_bytes: resident_before.rss_bytes,
530            rss_after_bytes: resident_after.rss_bytes,
531            phys_footprint_before_bytes: resident_before.phys_footprint_bytes,
532            phys_footprint_after_bytes: resident_after.phys_footprint_bytes,
533            allocator_before,
534            allocator_after,
535        }
536    }
537
538    /// Linux form: the allocator figure is the drop in `stats.resident`.
539    #[cfg(target_os = "linux")]
540    fn from_jemalloc_resident_drop(
541        resident_before: ResidentReading,
542        resident_after: ResidentReading,
543        allocator_before: AllocatorMemorySnapshot,
544        allocator_after: AllocatorMemorySnapshot,
545    ) -> Self {
546        let accounting = allocator_before
547            .jemalloc
548            .as_ref()
549            .map(|stats| stats.resident)
550            .zip(
551                allocator_after
552                    .jemalloc
553                    .as_ref()
554                    .map(|stats| stats.resident),
555            )
556            .map(|(before, after)| before.saturating_sub(after))
557            .unwrap_or(0);
558        Self::from_observations(
559            accounting,
560            RELIEF_ACCOUNTING_SOURCE_JEMALLOC,
561            resident_before,
562            resident_after,
563            allocator_before,
564            allocator_after,
565        )
566    }
567}
568
569/// Cap on per-root detail entries in serialized snapshots. Process totals
570/// always cover every root; only the per-root breakdown is capped so a
571/// many-root daemon process cannot balloon the status payload past
572/// downstream consumers' size limits (the daemon metrics cache truncates
573/// around 27 KB, and JSON keys serialize alphabetically, so an oversized
574/// `memory.roots` map pushes later sections past the cut).
575pub const MEMORY_SNAPSHOT_ROOT_DETAIL_CAP: usize = 8;
576
577/// Operations the census names by their allocation high-water mark.
578pub const CENSUS_ALLOCATION_LABELS: usize = 5;
579
580#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
581pub struct MemorySnapshot {
582    pub roots_status: &'static str,
583    /// Top roots by attributed bytes, capped at
584    /// [`MEMORY_SNAPSHOT_ROOT_DETAIL_CAP`]; the remainder is summarized by
585    /// `roots_omitted` / `roots_omitted_bytes`.
586    pub roots: BTreeMap<String, RootMemorySnapshot>,
587    /// Total roots attributed (including omitted ones).
588    pub roots_total: usize,
589    /// Roots summarized out of the detail map.
590    pub roots_omitted: usize,
591    /// Attributed bytes carried by the omitted roots (already included in
592    /// `process.total_attributed_bytes`).
593    pub roots_omitted_bytes: u64,
594    /// Immutable shared semantic bases, attributed once process-wide: the
595    /// snapshots borrowed loads share and the indexes owner roots froze when
596    /// they installed them. Root rows count zero for a view of such a base.
597    pub shared_semantic_bases: MemoryEstimate,
598    /// The data layer's block cache, shared by every checkout and attributed
599    /// once process-wide (`process.data_layer_block_cache_bytes`). Present
600    /// only once a checkout of this process has bound.
601    #[serde(skip_serializing_if = "Option::is_none")]
602    pub data_layer_block_cache: Option<MemoryEstimate>,
603    pub process: ProcessMemorySnapshot,
604    /// The operations whose live heap bytes peaked highest since the
605    /// previous census, highest first, as the `aft` binary's allocation
606    /// tracer counts them. Only the uncapped census carries them, and only
607    /// when an operation allocated since the last one.
608    #[serde(skip_serializing_if = "Vec::is_empty")]
609    pub allocation_labels: Vec<crate::alloc_trace::LabelPeak>,
610}
611
612/// Memory attributed once for the whole process rather than to any root:
613/// shared semantic bases and the data layer's block cache.
614#[derive(Debug, Clone)]
615pub struct SharedProcessMemory {
616    pub shared_semantic_bases: MemoryEstimate,
617    pub data_layer_block_cache: Option<MemoryEstimate>,
618}
619
620#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
621pub struct MemoryRollupSnapshot {
622    pub roots_status: &'static str,
623    pub roots: BTreeMap<String, RootMemoryRollup>,
624    pub roots_total: usize,
625    pub roots_omitted: usize,
626    pub roots_omitted_bytes: u64,
627    pub process: ProcessMemorySnapshot,
628}
629
630fn cap_roots<T>(
631    roots: BTreeMap<String, T>,
632    cap: usize,
633    attributed_bytes: impl Fn(&T) -> u64,
634) -> (BTreeMap<String, T>, usize, u64) {
635    if roots.len() <= cap {
636        return (roots, 0, 0);
637    }
638    let mut entries: Vec<_> = roots.into_iter().collect();
639    entries.sort_by(|a, b| {
640        attributed_bytes(&b.1)
641            .cmp(&attributed_bytes(&a.1))
642            .then_with(|| a.0.cmp(&b.0))
643    });
644    let omitted = entries.split_off(cap);
645    let omitted_bytes = omitted
646        .iter()
647        .map(|(_, snapshot)| attributed_bytes(snapshot))
648        .fold(0u64, u64::saturating_add);
649    (entries.into_iter().collect(), omitted.len(), omitted_bytes)
650}
651
652pub fn cap_root_rollups(
653    roots: BTreeMap<String, RootMemoryRollup>,
654    cap: usize,
655) -> (BTreeMap<String, RootMemoryRollup>, usize, u64) {
656    cap_roots(roots, cap, |snapshot| snapshot.attributed_bytes)
657}
658
659/// Keep the `cap` roots with the highest attributed bytes; report the rest
660/// as an omitted-count + omitted-bytes rollup.
661pub fn cap_root_detail(
662    roots: BTreeMap<String, RootMemorySnapshot>,
663    cap: usize,
664) -> (BTreeMap<String, RootMemorySnapshot>, usize, u64) {
665    cap_roots(roots, cap, |snapshot| snapshot.attributed_bytes)
666}
667
668pub fn path_bytes(path: &Path) -> u64 {
669    #[cfg(unix)]
670    {
671        use std::os::unix::ffi::OsStrExt;
672        usize_to_u64(path.as_os_str().as_bytes().len())
673    }
674    #[cfg(windows)]
675    {
676        use std::os::windows::ffi::OsStrExt;
677        usize_to_u64(path.as_os_str().encode_wide().count())
678            .saturating_mul(std::mem::size_of::<u16>() as u64)
679    }
680    #[cfg(not(any(unix, windows)))]
681    {
682        usize_to_u64(path.to_string_lossy().len())
683    }
684}
685
686pub fn usize_to_u64(value: usize) -> u64 {
687    u64::try_from(value).unwrap_or(u64::MAX)
688}
689
690pub fn estimated_json_bytes(value: &Value) -> u64 {
691    match value {
692        Value::Null => 0,
693        Value::Bool(_) => std::mem::size_of::<bool>() as u64,
694        Value::Number(_) => std::mem::size_of::<serde_json::Number>() as u64,
695        Value::String(value) => usize_to_u64(value.len()),
696        Value::Array(values) => values
697            .iter()
698            .map(estimated_json_bytes)
699            .fold(0u64, u64::saturating_add),
700        Value::Object(values) => values.iter().fold(0u64, |bytes, (key, value)| {
701            bytes
702                .saturating_add(usize_to_u64(key.len()))
703                .saturating_add(estimated_json_bytes(value))
704        }),
705    }
706}
707
708pub fn signed_difference(lhs: u64, rhs: u64) -> i64 {
709    let difference = i128::from(lhs) - i128::from(rhs);
710    difference.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64
711}
712
713fn nonnegative_i64_to_u64(value: i64) -> u64 {
714    u64::try_from(value).unwrap_or(0)
715}
716
717#[cfg(target_os = "macos")]
718fn allocator_memory_snapshot_impl() -> AllocatorMemorySnapshot {
719    let mut statistics = std::mem::MaybeUninit::<libc::malloc_statistics_t>::zeroed();
720    unsafe {
721        libc::malloc_zone_statistics(libc::malloc_default_zone(), statistics.as_mut_ptr());
722    }
723    let statistics = unsafe { statistics.assume_init() };
724    AllocatorMemorySnapshot::measured(
725        usize_to_u64(statistics.size_in_use),
726        usize_to_u64(statistics.size_allocated),
727    )
728}
729
730#[cfg(target_os = "linux")]
731fn allocator_memory_snapshot_impl() -> AllocatorMemorySnapshot {
732    let read = || -> Result<_, tikv_jemalloc_ctl::Error> {
733        tikv_jemalloc_ctl::epoch::advance()?;
734        Ok((
735            tikv_jemalloc_ctl::stats::allocated::read()? as u64,
736            tikv_jemalloc_ctl::stats::active::read()? as u64,
737            tikv_jemalloc_ctl::stats::resident::read()? as u64,
738            tikv_jemalloc_ctl::stats::retained::read()? as u64,
739            tikv_jemalloc_ctl::stats::mapped::read()? as u64,
740        ))
741    };
742    let Ok((allocated, active, resident, retained, mapped)) = read() else {
743        return AllocatorMemorySnapshot::unavailable("jemalloc_statistics_unavailable");
744    };
745    // Preserve the existing envelope: bytes_in_use is stats.allocated;
746    // size_allocated is mapped + retained virtual address space, not residency;
747    // retained_slack_bytes is that envelope minus allocated, not stats.retained.
748    let mut snapshot =
749        AllocatorMemorySnapshot::measured(allocated, mapped.saturating_add(retained));
750    snapshot.jemalloc = Some(JemallocMemorySnapshot {
751        accounting_source: "jemalloc",
752        allocated,
753        active,
754        resident,
755        retained,
756    });
757    snapshot
758}
759
760/// Return unused Linux allocator pages without measuring counters or RSS.
761/// Call-graph build phases use the same purge as the measured idle-relief path.
762#[cfg(target_os = "linux")]
763pub fn purge_allocator() -> std::io::Result<()> {
764    // MALLCTL_ARENAS_ALL is 4096 in jemalloc 5.3.0. This command takes no value.
765    let result = unsafe {
766        tikv_jemalloc_sys::mallctl(
767            c"arena.4096.purge".as_ptr(),
768            std::ptr::null_mut(),
769            std::ptr::null_mut(),
770            std::ptr::null_mut(),
771            0,
772        )
773    };
774    if result == 0 {
775        Ok(())
776    } else {
777        Err(std::io::Error::from_raw_os_error(result))
778    }
779}
780
781#[cfg(not(any(target_os = "macos", target_os = "linux")))]
782fn allocator_memory_snapshot_impl() -> AllocatorMemorySnapshot {
783    AllocatorMemorySnapshot::not_estimated("platform_allocator_statistics_unavailable")
784}
785
786/// Read allocator-wide statistics. Callers on the dispatch path must use the
787/// cached slack scheduler below instead: macOS walks allocator zones under
788/// their locks while producing this snapshot.
789fn allocator_memory_snapshot() -> AllocatorMemorySnapshot {
790    #[cfg(any(test, feature = "test-support"))]
791    {
792        THREAD_ALLOCATOR_SNAPSHOT_CALLS.with(|calls| calls.set(calls.get() + 1));
793        let name = std::thread::current()
794            .name()
795            .unwrap_or("unnamed")
796            .to_string();
797        ALLOCATOR_SNAPSHOT_THREADS
798            .lock()
799            .expect("allocator snapshot test thread log")
800            .push(name);
801    }
802    #[cfg(any(target_os = "macos", target_os = "linux"))]
803    let started = std::time::Instant::now();
804    let snapshot = allocator_memory_snapshot_impl();
805    #[cfg(any(target_os = "macos", target_os = "linux"))]
806    LAST_ALLOCATOR_WALK_MS.store(
807        started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64,
808        std::sync::atomic::Ordering::Relaxed,
809    );
810    snapshot
811}
812
813fn allocator_observation(source: AllocatorSource) -> (AllocatorMemorySnapshot, Option<u64>) {
814    match source {
815        AllocatorSource::Cached => cached_allocator_observation()
816            .map(|(snapshot, age_ms)| (snapshot, Some(age_ms)))
817            .unwrap_or_else(|| {
818                // A cold cache is not evidence that the allocator lacks counters.
819                // Keep the request path cheap while the first sample is pending.
820                let snapshot = if cfg!(any(target_os = "macos", target_os = "linux")) {
821                    AllocatorMemorySnapshot::unavailable("allocator_observation_unavailable")
822                } else {
823                    AllocatorMemorySnapshot::not_estimated("allocator_observation_unavailable")
824                };
825                (snapshot, None)
826            }),
827        AllocatorSource::Measure => measure_allocator_observation(),
828    }
829}
830
831fn measure_allocator_observation() -> (AllocatorMemorySnapshot, Option<u64>) {
832    // Only the platforms that publish an observation stamp its start; the
833    // Windows deny-warnings lane rejects the unused binding otherwise.
834    #[cfg(any(target_os = "macos", target_os = "linux"))]
835    let sampled_at = std::time::Instant::now();
836    let snapshot = allocator_memory_snapshot();
837    #[cfg(any(target_os = "macos", target_os = "linux"))]
838    {
839        let sampled_at_ms = allocator_slack_elapsed_ms(sampled_at);
840        publish_allocator_slack(&snapshot, sampled_at_ms);
841        let age_ms =
842            allocator_slack_elapsed_ms(std::time::Instant::now()).saturating_sub(sampled_at_ms);
843        (snapshot, Some(age_ms))
844    }
845    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
846    {
847        (snapshot, None)
848    }
849}
850
851#[cfg(target_os = "macos")]
852unsafe extern "C" {
853    fn malloc_zone_pressure_relief(zone: *mut libc::malloc_zone_t, goal: usize) -> usize;
854}
855
856/// Address-space allocator slack above which opportunistic pressure relief is
857/// worth the zone-lock contention it briefly causes. Slack includes free pages
858/// the allocator already returned to the OS (it cannot tell which free pages
859/// are resident), so it stays above this line after a successful pass and the
860/// pass repeats at `ALLOCATOR_SLACK_RELIEF_MIN_INTERVAL`. That is intended: a
861/// repeat pass is cheap and returns whatever has been freed since the last one.
862pub const ALLOCATOR_SLACK_RELIEF_THRESHOLD_BYTES: u64 = 1024 * 1024 * 1024;
863
864/// Minimum spacing between opportunistic relief passes so a workload that
865/// legitimately cycles through large allocations does not thrash the allocator.
866pub const ALLOCATOR_SLACK_RELIEF_MIN_INTERVAL: std::time::Duration =
867    std::time::Duration::from_secs(300);
868
869/// Periodic allocator readers wait at least this many times the last walk's
870/// own duration before walking again, so walks take at most 0.5% of the time.
871/// Allocator walks can contend with allocations, so their measured cost bounds
872/// sampling frequency even when a fragmented heap makes a walk expensive.
873const ALLOCATOR_WALK_COST_FACTOR: u64 = 200;
874
875/// The longest an expensive walk can stretch a periodic reader's reuse window,
876/// so a slow allocator still gets a fresh reading every ten minutes.
877const ALLOCATOR_WALK_MAX_REUSE_MS: u64 = 10 * 60 * 1000;
878
879/// How long a periodic reader may reuse an allocator observation whose walk
880/// took `walk_ms`: `floor_ms` for a cheap walk, stretched to
881/// `ALLOCATOR_WALK_COST_FACTOR` times the walk's duration for an expensive
882/// one, and never past `ALLOCATOR_WALK_MAX_REUSE_MS` (or `floor_ms`, if that
883/// is larger).
884pub fn allocator_reuse_window_ms(floor_ms: u64, walk_ms: u64) -> u64 {
885    walk_ms
886        .saturating_mul(ALLOCATOR_WALK_COST_FACTOR)
887        .clamp(floor_ms, ALLOCATOR_WALK_MAX_REUSE_MS.max(floor_ms))
888}
889
890#[cfg(any(target_os = "linux", all(test, target_os = "macos")))]
891/// The Linux module loop ticks every 250ms. Reuse its process-wide jemalloc
892/// observation for at least 60s to bound telemetry work, longer when walks
893/// are expensive (see `allocator_reuse_window_ms`).
894/// This bounds allocator statistics walks to one per idle minute, or two for a
895/// relief pass that uses its before/after snapshots.
896const ALLOCATOR_SLACK_SAMPLE_INTERVAL: std::time::Duration = std::time::Duration::from_secs(60);
897/// Wall-clock duration of the most recent allocator statistics walk, on any
898/// thread, in milliseconds.
899#[cfg(any(target_os = "macos", target_os = "linux"))]
900static LAST_ALLOCATOR_WALK_MS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
901#[cfg(any(target_os = "macos", target_os = "linux"))]
902const UNKNOWN_ALLOCATOR_SLACK: u64 = u64::MAX;
903#[cfg(any(target_os = "macos", target_os = "linux"))]
904const UNSAMPLED_AT_MS: u64 = u64::MAX;
905#[cfg(any(target_os = "macos", target_os = "linux"))]
906const ALLOCATOR_OBSERVATION_UNSAMPLED: u8 = 0;
907#[cfg(any(target_os = "macos", target_os = "linux"))]
908const ALLOCATOR_OBSERVATION_MEASURED: u8 = 1;
909#[cfg(any(target_os = "macos", target_os = "linux"))]
910const ALLOCATOR_OBSERVATION_NOT_ESTIMATED: u8 = 2;
911#[cfg(any(target_os = "macos", target_os = "linux"))]
912static ALLOCATOR_SLACK_CACHE_ORIGIN: std::sync::OnceLock<std::time::Instant> =
913    std::sync::OnceLock::new();
914#[cfg(any(target_os = "macos", target_os = "linux"))]
915static LAST_OBSERVED_ALLOCATOR_SLACK_BYTES: std::sync::atomic::AtomicU64 =
916    std::sync::atomic::AtomicU64::new(UNKNOWN_ALLOCATOR_SLACK);
917#[cfg(any(target_os = "macos", target_os = "linux"))]
918static LAST_OBSERVED_ALLOCATOR_BYTES_IN_USE: std::sync::atomic::AtomicU64 =
919    std::sync::atomic::AtomicU64::new(UNKNOWN_ALLOCATOR_SLACK);
920#[cfg(any(target_os = "macos", target_os = "linux"))]
921static LAST_OBSERVED_ALLOCATOR_SIZE_ALLOCATED: std::sync::atomic::AtomicU64 =
922    std::sync::atomic::AtomicU64::new(UNKNOWN_ALLOCATOR_SLACK);
923#[cfg(target_os = "linux")]
924static LAST_OBSERVED_JEMALLOC: [std::sync::atomic::AtomicU64; 3] =
925    [const { std::sync::atomic::AtomicU64::new(UNKNOWN_ALLOCATOR_SLACK) }; 3];
926#[cfg(any(target_os = "macos", target_os = "linux"))]
927static LAST_ALLOCATOR_OBSERVATION_STATUS: std::sync::atomic::AtomicU8 =
928    std::sync::atomic::AtomicU8::new(ALLOCATOR_OBSERVATION_UNSAMPLED);
929#[cfg(any(target_os = "macos", target_os = "linux"))]
930static LAST_ALLOCATOR_OBSERVATION_AT_MS: std::sync::atomic::AtomicU64 =
931    std::sync::atomic::AtomicU64::new(UNSAMPLED_AT_MS);
932#[cfg(any(target_os = "macos", target_os = "linux"))]
933static ALLOCATOR_OBSERVATION_SEQUENCE: std::sync::atomic::AtomicU64 =
934    std::sync::atomic::AtomicU64::new(0);
935#[cfg(any(target_os = "macos", target_os = "linux"))]
936static ALLOCATOR_OBSERVATION_PUBLISH_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
937#[cfg(any(target_os = "macos", target_os = "linux"))]
938static LAST_ALLOCATOR_SLACK_SAMPLE_AT_MS: std::sync::atomic::AtomicU64 =
939    std::sync::atomic::AtomicU64::new(UNSAMPLED_AT_MS);
940#[cfg(any(target_os = "macos", target_os = "linux"))]
941static LAST_ALLOCATOR_SLACK_RELIEF_AT_MS: std::sync::atomic::AtomicU64 =
942    std::sync::atomic::AtomicU64::new(UNSAMPLED_AT_MS);
943#[cfg(any(target_os = "macos", target_os = "linux"))]
944static LAST_ALLOCATOR_SLACK_RELIEF_ACCOUNTING_BYTES: std::sync::atomic::AtomicU64 =
945    std::sync::atomic::AtomicU64::new(0);
946#[cfg(any(target_os = "macos", target_os = "linux"))]
947static LAST_ALLOCATOR_SLACK_RELIEF_RSS_DROP_BYTES: std::sync::atomic::AtomicU64 =
948    std::sync::atomic::AtomicU64::new(UNKNOWN_ALLOCATOR_SLACK);
949#[cfg(any(target_os = "macos", target_os = "linux"))]
950static LAST_ALLOCATOR_SLACK_RELIEF_FOOTPRINT_DROP_BYTES: std::sync::atomic::AtomicU64 =
951    std::sync::atomic::AtomicU64::new(UNKNOWN_ALLOCATOR_SLACK);
952
953#[cfg(any(test, feature = "test-support"))]
954pub static ALLOCATOR_SNAPSHOT_THREADS: std::sync::Mutex<Vec<String>> =
955    std::sync::Mutex::new(Vec::new());
956
957#[cfg(any(test, feature = "test-support"))]
958thread_local! {
959    /// Per-thread count of allocator statistics walks. Tests that assert a
960    /// synchronous render path took no walk read this: the walk, if it
961    /// happened, ran on the calling thread. A process-global counter is
962    /// wrong for that assertion - sibling tests and the health thread walk
963    /// concurrently, and a parallel run read a delta of 1 for a render that
964    /// walked nothing. Which-thread questions use the thread-name log.
965    static THREAD_ALLOCATOR_SNAPSHOT_CALLS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
966}
967
968#[cfg(any(test, feature = "test-support"))]
969pub fn allocator_snapshot_calls_for_test() -> u64 {
970    THREAD_ALLOCATOR_SNAPSHOT_CALLS.with(|calls| calls.get())
971}
972
973#[cfg(any(test, feature = "test-support"))]
974fn allocator_observation_test_mutex() -> &'static std::sync::Mutex<()> {
975    static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
976    LOCK.get_or_init(|| std::sync::Mutex::new(()))
977}
978
979#[cfg(any(test, feature = "test-support"))]
980pub fn allocator_observation_test_lock() -> std::sync::MutexGuard<'static, ()> {
981    allocator_observation_test_mutex()
982        .lock()
983        .unwrap_or_else(std::sync::PoisonError::into_inner)
984}
985
986#[cfg(any(test, feature = "test-support"))]
987pub fn reset_allocator_observation_for_test() {
988    #[cfg(any(target_os = "macos", target_os = "linux"))]
989    {
990        ALLOCATOR_OBSERVATION_SEQUENCE.store(0, std::sync::atomic::Ordering::Release);
991        LAST_ALLOCATOR_OBSERVATION_STATUS.store(
992            ALLOCATOR_OBSERVATION_UNSAMPLED,
993            std::sync::atomic::Ordering::Release,
994        );
995        LAST_OBSERVED_ALLOCATOR_BYTES_IN_USE.store(
996            UNKNOWN_ALLOCATOR_SLACK,
997            std::sync::atomic::Ordering::Release,
998        );
999        LAST_OBSERVED_ALLOCATOR_SIZE_ALLOCATED.store(
1000            UNKNOWN_ALLOCATOR_SLACK,
1001            std::sync::atomic::Ordering::Release,
1002        );
1003        LAST_OBSERVED_ALLOCATOR_SLACK_BYTES.store(
1004            UNKNOWN_ALLOCATOR_SLACK,
1005            std::sync::atomic::Ordering::Release,
1006        );
1007        LAST_ALLOCATOR_OBSERVATION_AT_MS
1008            .store(UNSAMPLED_AT_MS, std::sync::atomic::Ordering::Release);
1009        LAST_ALLOCATOR_SLACK_SAMPLE_AT_MS
1010            .store(UNSAMPLED_AT_MS, std::sync::atomic::Ordering::Release);
1011    }
1012}
1013
1014#[cfg(any(target_os = "macos", target_os = "linux"))]
1015fn allocator_slack_elapsed_ms(now: std::time::Instant) -> u64 {
1016    let origin = ALLOCATOR_SLACK_CACHE_ORIGIN.get_or_init(|| now);
1017    now.duration_since(*origin)
1018        .as_millis()
1019        .min(u128::from(u64::MAX)) as u64
1020}
1021
1022#[cfg(target_os = "linux")]
1023fn cached_allocator_slack() -> Option<u64> {
1024    let slack = LAST_OBSERVED_ALLOCATOR_SLACK_BYTES.load(std::sync::atomic::Ordering::Acquire);
1025    (slack != UNKNOWN_ALLOCATOR_SLACK).then_some(slack)
1026}
1027
1028#[cfg(any(target_os = "macos", target_os = "linux"))]
1029fn cached_allocator_not_estimated_reason() -> &'static str {
1030    #[cfg(target_os = "linux")]
1031    {
1032        "jemalloc_statistics_unavailable"
1033    }
1034    #[cfg(not(target_os = "linux"))]
1035    {
1036        "platform_allocator_statistics_unavailable"
1037    }
1038}
1039
1040/// Return the last process-wide allocator observation without walking allocator
1041/// zones. The observation timestamp is separate from the sampler reservation so
1042/// a status request never mistakes an in-progress sample for a fresh reading.
1043pub fn cached_allocator_observation() -> Option<(AllocatorMemorySnapshot, u64)> {
1044    #[cfg(any(target_os = "macos", target_os = "linux"))]
1045    {
1046        loop {
1047            let sequence =
1048                ALLOCATOR_OBSERVATION_SEQUENCE.load(std::sync::atomic::Ordering::Acquire);
1049            if sequence % 2 != 0 {
1050                std::hint::spin_loop();
1051                continue;
1052            }
1053            let sampled_at_ms =
1054                LAST_ALLOCATOR_OBSERVATION_AT_MS.load(std::sync::atomic::Ordering::Acquire);
1055            if sampled_at_ms == UNSAMPLED_AT_MS {
1056                return None;
1057            }
1058            let status =
1059                LAST_ALLOCATOR_OBSERVATION_STATUS.load(std::sync::atomic::Ordering::Acquire);
1060            let bytes_in_use =
1061                LAST_OBSERVED_ALLOCATOR_BYTES_IN_USE.load(std::sync::atomic::Ordering::Acquire);
1062            let size_allocated =
1063                LAST_OBSERVED_ALLOCATOR_SIZE_ALLOCATED.load(std::sync::atomic::Ordering::Acquire);
1064            let retained_slack =
1065                LAST_OBSERVED_ALLOCATOR_SLACK_BYTES.load(std::sync::atomic::Ordering::Acquire);
1066            #[cfg(target_os = "linux")]
1067            let jemalloc_counters = LAST_OBSERVED_JEMALLOC
1068                .each_ref()
1069                .map(|value| value.load(std::sync::atomic::Ordering::Acquire));
1070            let sequence_after =
1071                ALLOCATOR_OBSERVATION_SEQUENCE.load(std::sync::atomic::Ordering::Acquire);
1072            if sequence != sequence_after || sequence_after % 2 != 0 {
1073                continue;
1074            }
1075            let snapshot = match status {
1076                ALLOCATOR_OBSERVATION_MEASURED
1077                    if bytes_in_use != UNKNOWN_ALLOCATOR_SLACK
1078                        && size_allocated != UNKNOWN_ALLOCATOR_SLACK
1079                        && retained_slack != UNKNOWN_ALLOCATOR_SLACK =>
1080                {
1081                    AllocatorMemorySnapshot {
1082                        status: "measured",
1083                        bytes_in_use: Some(bytes_in_use),
1084                        size_allocated: Some(size_allocated),
1085                        retained_slack_bytes: Some(retained_slack),
1086                        retained_slack_label: ALLOCATOR_SLACK_LABEL,
1087                        not_estimated: None,
1088                        #[cfg(target_os = "linux")]
1089                        jemalloc: (!jemalloc_counters.contains(&UNKNOWN_ALLOCATOR_SLACK))
1090                            .then_some(JemallocMemorySnapshot {
1091                                accounting_source: "jemalloc",
1092                                allocated: bytes_in_use,
1093                                active: jemalloc_counters[0],
1094                                resident: jemalloc_counters[1],
1095                                retained: jemalloc_counters[2],
1096                            }),
1097                    }
1098                }
1099                ALLOCATOR_OBSERVATION_NOT_ESTIMATED => {
1100                    AllocatorMemorySnapshot::not_estimated(cached_allocator_not_estimated_reason())
1101                }
1102                _ => return None,
1103            };
1104            let age_ms =
1105                allocator_slack_elapsed_ms(std::time::Instant::now()).saturating_sub(sampled_at_ms);
1106            return Some((snapshot, age_ms));
1107        }
1108    }
1109    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
1110    {
1111        None
1112    }
1113}
1114
1115#[cfg(any(target_os = "macos", target_os = "linux"))]
1116fn publish_allocator_slack(snapshot: &AllocatorMemorySnapshot, sampled_at_ms: u64) {
1117    let _publish_guard = ALLOCATOR_OBSERVATION_PUBLISH_LOCK
1118        .lock()
1119        .unwrap_or_else(std::sync::PoisonError::into_inner);
1120    ALLOCATOR_OBSERVATION_SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1121    LAST_ALLOCATOR_OBSERVATION_STATUS.store(
1122        if snapshot.status == "measured" {
1123            ALLOCATOR_OBSERVATION_MEASURED
1124        } else {
1125            ALLOCATOR_OBSERVATION_NOT_ESTIMATED
1126        },
1127        std::sync::atomic::Ordering::Relaxed,
1128    );
1129    LAST_OBSERVED_ALLOCATOR_BYTES_IN_USE.store(
1130        snapshot.bytes_in_use.unwrap_or(UNKNOWN_ALLOCATOR_SLACK),
1131        std::sync::atomic::Ordering::Relaxed,
1132    );
1133    LAST_OBSERVED_ALLOCATOR_SIZE_ALLOCATED.store(
1134        snapshot.size_allocated.unwrap_or(UNKNOWN_ALLOCATOR_SLACK),
1135        std::sync::atomic::Ordering::Relaxed,
1136    );
1137    LAST_OBSERVED_ALLOCATOR_SLACK_BYTES.store(
1138        snapshot
1139            .retained_slack_bytes
1140            .unwrap_or(UNKNOWN_ALLOCATOR_SLACK),
1141        std::sync::atomic::Ordering::Relaxed,
1142    );
1143    LAST_ALLOCATOR_OBSERVATION_AT_MS.store(sampled_at_ms, std::sync::atomic::Ordering::Relaxed);
1144    #[cfg(target_os = "linux")]
1145    for (counter, value) in LAST_OBSERVED_JEMALLOC.iter().zip(
1146        snapshot
1147            .jemalloc
1148            .as_ref()
1149            .map_or([UNKNOWN_ALLOCATOR_SLACK; 3], |stats| {
1150                [stats.active, stats.resident, stats.retained]
1151            }),
1152    ) {
1153        counter.store(value, std::sync::atomic::Ordering::Relaxed);
1154    }
1155    ALLOCATOR_OBSERVATION_SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::Release);
1156    LAST_ALLOCATOR_SLACK_SAMPLE_AT_MS.store(sampled_at_ms, std::sync::atomic::Ordering::Release);
1157}
1158
1159#[cfg(target_os = "linux")]
1160fn sample_is_stale(now_ms: u64) -> bool {
1161    sample_is_stale_after(
1162        LAST_ALLOCATOR_SLACK_SAMPLE_AT_MS.load(std::sync::atomic::Ordering::Acquire),
1163        now_ms,
1164        LAST_ALLOCATOR_WALK_MS.load(std::sync::atomic::Ordering::Relaxed),
1165    )
1166}
1167
1168/// Whether a sample taken at `sampled_at` is due for replacement at `now_ms`
1169/// when the last walk took `walk_ms`.
1170#[cfg(any(target_os = "linux", all(test, target_os = "macos")))]
1171fn sample_is_stale_after(sampled_at: u64, now_ms: u64, walk_ms: u64) -> bool {
1172    sampled_at == UNSAMPLED_AT_MS
1173        || now_ms.saturating_sub(sampled_at)
1174            >= allocator_reuse_window_ms(
1175                ALLOCATOR_SLACK_SAMPLE_INTERVAL.as_millis() as u64,
1176                walk_ms,
1177            )
1178}
1179
1180#[cfg(target_os = "linux")]
1181fn reserve_sample(now_ms: u64) -> Option<u64> {
1182    let previous = LAST_ALLOCATOR_SLACK_SAMPLE_AT_MS.load(std::sync::atomic::Ordering::Acquire);
1183    if !sample_is_stale(now_ms) {
1184        return None;
1185    }
1186    LAST_ALLOCATOR_SLACK_SAMPLE_AT_MS
1187        .compare_exchange(
1188            previous,
1189            now_ms,
1190            std::sync::atomic::Ordering::AcqRel,
1191            std::sync::atomic::Ordering::Acquire,
1192        )
1193        .ok()
1194}
1195
1196#[cfg(target_os = "linux")]
1197fn reserve_relief(now_ms: u64) -> Option<u64> {
1198    let previous = LAST_ALLOCATOR_SLACK_RELIEF_AT_MS.load(std::sync::atomic::Ordering::Acquire);
1199    let due = cached_allocator_slack().is_some_and(|slack| {
1200        slack >= ALLOCATOR_SLACK_RELIEF_THRESHOLD_BYTES
1201            && (previous == UNSAMPLED_AT_MS
1202                || now_ms.saturating_sub(previous)
1203                    >= ALLOCATOR_SLACK_RELIEF_MIN_INTERVAL.as_millis() as u64)
1204    });
1205    due.then(|| {
1206        LAST_ALLOCATOR_SLACK_RELIEF_AT_MS
1207            .compare_exchange(
1208                previous,
1209                now_ms,
1210                std::sync::atomic::Ordering::AcqRel,
1211                std::sync::atomic::Ordering::Acquire,
1212            )
1213            .ok()
1214    })?
1215}
1216
1217#[cfg(target_os = "linux")]
1218fn log_allocator_relief(relief: AllocatorPressureRelief) {
1219    log::info!(
1220        "allocator slack relief: allocator_accounting_bytes={} allocator_accounting_source={} rss_drop_bytes={:?} phys_footprint_drop_bytes={:?} rss_bytes_before={:?} rss_bytes_after={:?} address_space_slack_bytes_before={:?} address_space_slack_bytes_after={:?}",
1221        relief.allocator_accounting_bytes,
1222        relief.allocator_accounting_source,
1223        relief.rss_drop_bytes,
1224        relief.phys_footprint_drop_bytes,
1225        relief.rss_before_bytes,
1226        relief.rss_after_bytes,
1227        relief.allocator_before.retained_slack_bytes,
1228        relief.allocator_after.retained_slack_bytes,
1229    );
1230}
1231
1232/// Record the latest periodic relief pass for the memory census.
1233#[cfg(target_os = "linux")]
1234fn record_last_allocator_relief(relief: &AllocatorPressureRelief) {
1235    let ordering = std::sync::atomic::Ordering::Release;
1236    LAST_ALLOCATOR_SLACK_RELIEF_ACCOUNTING_BYTES.store(relief.allocator_accounting_bytes, ordering);
1237    LAST_ALLOCATOR_SLACK_RELIEF_RSS_DROP_BYTES.store(
1238        relief.rss_drop_bytes.unwrap_or(UNKNOWN_ALLOCATOR_SLACK),
1239        ordering,
1240    );
1241    LAST_ALLOCATOR_SLACK_RELIEF_FOOTPRINT_DROP_BYTES.store(
1242        relief
1243            .phys_footprint_drop_bytes
1244            .unwrap_or(UNKNOWN_ALLOCATOR_SLACK),
1245        ordering,
1246    );
1247}
1248
1249pub fn last_allocator_relief_at_ms() -> Option<u64> {
1250    #[cfg(any(target_os = "macos", target_os = "linux"))]
1251    {
1252        let value = LAST_ALLOCATOR_SLACK_RELIEF_AT_MS.load(std::sync::atomic::Ordering::Acquire);
1253        return (value != UNSAMPLED_AT_MS).then_some(value);
1254    }
1255    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
1256    {
1257        None
1258    }
1259}
1260
1261/// Allocator-accounting figure from the latest periodic relief pass; see
1262/// `allocator_relief_accounting_source` for what it measures on this platform.
1263pub fn last_allocator_relief_accounting_bytes() -> u64 {
1264    #[cfg(any(target_os = "macos", target_os = "linux"))]
1265    {
1266        return LAST_ALLOCATOR_SLACK_RELIEF_ACCOUNTING_BYTES
1267            .load(std::sync::atomic::Ordering::Acquire);
1268    }
1269    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
1270    {
1271        0
1272    }
1273}
1274
1275/// Observed RSS drop across the latest periodic relief pass, if one ran and
1276/// both RSS readings were available.
1277pub fn last_allocator_relief_rss_drop_bytes() -> Option<u64> {
1278    #[cfg(any(target_os = "macos", target_os = "linux"))]
1279    {
1280        let value =
1281            LAST_ALLOCATOR_SLACK_RELIEF_RSS_DROP_BYTES.load(std::sync::atomic::Ordering::Acquire);
1282        return (value != UNKNOWN_ALLOCATOR_SLACK).then_some(value);
1283    }
1284    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
1285    {
1286        None
1287    }
1288}
1289
1290/// Observed physical-footprint drop across the latest periodic relief pass
1291/// (macOS only).
1292pub fn last_allocator_relief_phys_footprint_drop_bytes() -> Option<u64> {
1293    #[cfg(any(target_os = "macos", target_os = "linux"))]
1294    {
1295        let value = LAST_ALLOCATOR_SLACK_RELIEF_FOOTPRINT_DROP_BYTES
1296            .load(std::sync::atomic::Ordering::Acquire);
1297        return (value != UNKNOWN_ALLOCATOR_SLACK).then_some(value);
1298    }
1299    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
1300    {
1301        None
1302    }
1303}
1304
1305/// What `last_allocator_relief_accounting_bytes` measures on this platform,
1306/// or `None` where no relief pass exists.
1307pub fn allocator_relief_accounting_source() -> Option<&'static str> {
1308    #[cfg(target_os = "macos")]
1309    {
1310        Some(RELIEF_ACCOUNTING_SOURCE_MACOS)
1311    }
1312    #[cfg(target_os = "linux")]
1313    {
1314        Some(RELIEF_ACCOUNTING_SOURCE_JEMALLOC)
1315    }
1316    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
1317    {
1318        None
1319    }
1320}
1321
1322/// Decide whether an opportunistic allocator relief pass is due.
1323#[cfg(any(target_os = "macos", target_os = "linux"))]
1324pub fn allocator_slack_relief_due(
1325    retained_slack_bytes: Option<u64>,
1326    last_relief: Option<std::time::Instant>,
1327    now: std::time::Instant,
1328) -> bool {
1329    let Some(slack) = retained_slack_bytes else {
1330        return false;
1331    };
1332    if slack < ALLOCATOR_SLACK_RELIEF_THRESHOLD_BYTES {
1333        return false;
1334    }
1335    match last_relief {
1336        None => true,
1337        Some(at) => now.duration_since(at) >= ALLOCATOR_SLACK_RELIEF_MIN_INTERVAL,
1338    }
1339}
1340
1341/// On Linux, opportunistically return unused allocator pages without reading allocator
1342/// statistics on the module loop. The loop only reads cached atomics. When the
1343/// cached observation is stale, one sampler takes an initial snapshot; if it
1344/// finds enough slack, the page-return operation reuses it and takes only one
1345/// additional after snapshot, limiting the pass to two statistics walks.
1346///
1347/// `phys_footprint_bytes` cannot make this decision: it includes file mappings
1348/// and other resident memory, so it cannot identify mapped-but-unused allocator
1349/// arenas without allocator-zone statistics.
1350#[cfg(target_os = "linux")]
1351pub fn spawn_allocator_slack_relief_if_due(now: std::time::Instant) -> bool {
1352    let now_ms = allocator_slack_elapsed_ms(now);
1353    if sample_is_stale(now_ms) {
1354        let Some(previous_sample) = reserve_sample(now_ms) else {
1355            return false;
1356        };
1357        let spawned = std::thread::Builder::new()
1358            .name("aft-mem-slack-sample".to_string())
1359            .spawn(move || {
1360                let before = allocator_memory_snapshot();
1361                publish_allocator_slack(&before, now_ms);
1362                if reserve_relief(now_ms).is_some() {
1363                    let relief = relieve_allocator_pressure_from_snapshot(before);
1364                    publish_allocator_slack(
1365                        &relief.allocator_after,
1366                        allocator_slack_elapsed_ms(std::time::Instant::now()),
1367                    );
1368                    record_last_allocator_relief(&relief);
1369                    log_allocator_relief(relief);
1370                }
1371            })
1372            .is_ok();
1373        if !spawned {
1374            let _ = LAST_ALLOCATOR_SLACK_SAMPLE_AT_MS.compare_exchange(
1375                now_ms,
1376                previous_sample,
1377                std::sync::atomic::Ordering::AcqRel,
1378                std::sync::atomic::Ordering::Acquire,
1379            );
1380        }
1381        return false;
1382    }
1383
1384    let Some(previous_relief) = reserve_relief(now_ms) else {
1385        return false;
1386    };
1387    let spawned = std::thread::Builder::new()
1388        .name("aft-mem-relief".to_string())
1389        .spawn(move || {
1390            let relief = relieve_allocator_pressure();
1391            publish_allocator_slack(
1392                &relief.allocator_after,
1393                allocator_slack_elapsed_ms(std::time::Instant::now()),
1394            );
1395            record_last_allocator_relief(&relief);
1396            log_allocator_relief(relief);
1397        })
1398        .is_ok();
1399    if !spawned {
1400        let _ = LAST_ALLOCATOR_SLACK_RELIEF_AT_MS.compare_exchange(
1401            now_ms,
1402            previous_relief,
1403            std::sync::atomic::Ordering::AcqRel,
1404            std::sync::atomic::Ordering::Acquire,
1405        );
1406    }
1407    spawned
1408}
1409
1410/// macOS statistics take every allocator-zone lock; sampling and relief there
1411/// are explicit-only. Other non-Linux targets have no automatic sampler.
1412#[cfg(not(target_os = "linux"))]
1413pub fn spawn_allocator_slack_relief_if_due(_now: std::time::Instant) -> bool {
1414    false
1415}
1416
1417/// Ask the platform allocator to return unused pages after a process-wide idle
1418/// gate. Callers own that gate because allocator pressure relief can add
1419/// latency. Linux purges all jemalloc arenas; macOS asks libmalloc for relief.
1420#[cfg(target_os = "macos")]
1421fn relieve_allocator_pressure_from_snapshot(
1422    allocator_before: AllocatorMemorySnapshot,
1423) -> AllocatorPressureRelief {
1424    let resident_before = ResidentReading::read();
1425    // The return value is libmalloc's own count of bytes it handed back. It is
1426    // reported as the allocator's claim; the footprint and RSS drops recorded
1427    // alongside it are what the process was actually seen to give up.
1428    let reported = unsafe { malloc_zone_pressure_relief(std::ptr::null_mut(), 0) };
1429    let allocator_after = allocator_memory_snapshot();
1430    let resident_after = ResidentReading::read();
1431    AllocatorPressureRelief::from_observations(
1432        usize_to_u64(reported),
1433        RELIEF_ACCOUNTING_SOURCE_MACOS,
1434        resident_before,
1435        resident_after,
1436        allocator_before,
1437        allocator_after,
1438    )
1439}
1440
1441#[cfg(target_os = "macos")]
1442pub fn relieve_allocator_pressure() -> AllocatorPressureRelief {
1443    relieve_allocator_pressure_from_snapshot(allocator_memory_snapshot())
1444}
1445
1446/// Hands the allocator's free pages back to the system without measuring
1447/// anything, for callers that would throw the measurement away. On macOS the
1448/// measured `relieve_allocator_pressure` reads zone statistics before and after
1449/// the relief, which takes every allocator-zone lock and stalls every thread
1450/// that allocates meanwhile; a call-graph build calls this between stages.
1451#[cfg(target_os = "macos")]
1452pub fn return_free_pages() {
1453    unsafe { malloc_zone_pressure_relief(std::ptr::null_mut(), 0) };
1454}
1455
1456#[cfg(target_os = "linux")]
1457pub fn return_free_pages() {
1458    let _ = purge_allocator();
1459}
1460
1461#[cfg(target_os = "linux")]
1462fn relieve_allocator_pressure_from_snapshot(
1463    allocator_before: AllocatorMemorySnapshot,
1464) -> AllocatorPressureRelief {
1465    let resident_before = ResidentReading::read();
1466    let _ = purge_allocator();
1467    let allocator_after = allocator_memory_snapshot();
1468    let resident_after = ResidentReading::read();
1469    AllocatorPressureRelief::from_jemalloc_resident_drop(
1470        resident_before,
1471        resident_after,
1472        allocator_before,
1473        allocator_after,
1474    )
1475}
1476
1477#[cfg(target_os = "linux")]
1478pub fn relieve_allocator_pressure() -> AllocatorPressureRelief {
1479    relieve_allocator_pressure_from_snapshot(allocator_memory_snapshot())
1480}
1481
1482#[cfg(target_os = "macos")]
1483pub fn process_rss_bytes() -> Option<u64> {
1484    let mut info = std::mem::MaybeUninit::<libc::proc_taskinfo>::zeroed();
1485    let size = std::mem::size_of::<libc::proc_taskinfo>();
1486    let written = unsafe {
1487        libc::proc_pidinfo(
1488            libc::getpid(),
1489            libc::PROC_PIDTASKINFO,
1490            0,
1491            info.as_mut_ptr().cast(),
1492            i32::try_from(size).ok()?,
1493        )
1494    };
1495    if written != i32::try_from(size).ok()? {
1496        return None;
1497    }
1498    Some(unsafe { info.assume_init() }.pti_resident_size)
1499}
1500
1501/// Kernel physical footprint via `proc_pid_rusage` (`ri_phys_footprint`).
1502/// See `phys_footprint_bytes` for why this, not RSS, is the headline number.
1503#[cfg(target_os = "macos")]
1504pub fn process_phys_footprint_bytes() -> Option<u64> {
1505    let mut usage = std::mem::MaybeUninit::<libc::rusage_info_v4>::zeroed();
1506    let rc = unsafe {
1507        libc::proc_pid_rusage(
1508            libc::getpid(),
1509            libc::RUSAGE_INFO_V4,
1510            usage.as_mut_ptr().cast(),
1511        )
1512    };
1513    if rc != 0 {
1514        return None;
1515    }
1516    Some(unsafe { usage.assume_init() }.ri_phys_footprint)
1517}
1518
1519#[cfg(not(target_os = "macos"))]
1520pub fn process_phys_footprint_bytes() -> Option<u64> {
1521    None
1522}
1523
1524#[cfg(target_os = "linux")]
1525pub fn process_rss_bytes() -> Option<u64> {
1526    let statm = std::fs::read_to_string("/proc/self/statm").ok()?;
1527    let resident_pages = statm.split_whitespace().nth(1)?.parse::<u64>().ok()?;
1528    let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
1529    if page_size <= 0 {
1530        return None;
1531    }
1532    resident_pages.checked_mul(page_size as u64)
1533}
1534
1535#[cfg(not(any(target_os = "macos", target_os = "linux")))]
1536pub fn process_rss_bytes() -> Option<u64> {
1537    None
1538}
1539
1540pub fn rss_bytes() -> Option<u64> {
1541    process_rss_bytes()
1542}
1543
1544#[cfg(any(test, feature = "test-support"))]
1545#[cfg_attr(not(test), allow(dead_code, unused_imports))]
1546pub mod snapshot_cap_tests {
1547    use super::*;
1548
1549    pub fn root_with_bytes(bytes: u64) -> RootMemorySnapshot {
1550        let estimate = MemoryEstimate::estimated;
1551        RootMemorySnapshot::new(
1552            estimate(bytes),
1553            estimate(0),
1554            estimate(0),
1555            estimate(0),
1556            estimate(0),
1557            estimate(0),
1558            estimate(0),
1559            estimate(0),
1560            estimate(0),
1561        )
1562    }
1563}
1564
1565#[cfg(test)]
1566mod tests {
1567    use super::*;
1568
1569    #[test]
1570    fn process_snapshot_preserves_negative_residuals() {
1571        assert_eq!(signed_difference(5, 8), -3);
1572    }
1573
1574    #[test]
1575    fn allocator_reuse_window_stretches_with_walk_cost() {
1576        // A cheap walk keeps the floor.
1577        assert_eq!(allocator_reuse_window_ms(30_000, 0), 30_000);
1578        assert_eq!(allocator_reuse_window_ms(30_000, 150), 30_000);
1579        // An expensive walk waits 200 times its own duration...
1580        assert_eq!(allocator_reuse_window_ms(30_000, 1_000), 200_000);
1581        // ...but never more than ten minutes.
1582        assert_eq!(allocator_reuse_window_ms(30_000, 6_500), 600_000);
1583        assert_eq!(allocator_reuse_window_ms(30_000, u64::MAX), 600_000);
1584        // A floor above the cap still wins.
1585        assert_eq!(allocator_reuse_window_ms(900_000, 6_500), 900_000);
1586    }
1587
1588    #[cfg(any(target_os = "macos", target_os = "linux"))]
1589    #[test]
1590    fn slack_sample_waits_longer_after_an_expensive_walk() {
1591        assert!(sample_is_stale_after(UNSAMPLED_AT_MS, 0, 0));
1592        // A cheap walk: due once a minute.
1593        assert!(!sample_is_stale_after(0, 59_999, 20));
1594        assert!(sample_is_stale_after(0, 60_000, 20));
1595        // A one-second walk: due after 200 seconds, not after one minute.
1596        assert!(!sample_is_stale_after(0, 60_000, 1_000));
1597        assert!(!sample_is_stale_after(0, 199_999, 1_000));
1598        assert!(sample_is_stale_after(0, 200_000, 1_000));
1599        // A multi-second glibc walk: capped at ten minutes.
1600        assert!(!sample_is_stale_after(0, 599_999, 6_500));
1601        assert!(sample_is_stale_after(0, 600_000, 6_500));
1602    }
1603
1604    #[cfg(any(target_os = "macos", all(target_os = "linux", target_env = "gnu")))]
1605    #[test]
1606    fn cached_allocator_before_first_publication_is_unavailable_not_unsupported() {
1607        let _test_guard = allocator_observation_test_lock();
1608        let publish_guard = ALLOCATOR_OBSERVATION_PUBLISH_LOCK
1609            .lock()
1610            .unwrap_or_else(std::sync::PoisonError::into_inner);
1611        reset_allocator_observation_for_test();
1612        let calls_before = allocator_snapshot_calls_for_test();
1613
1614        // Hold publication at startup: a request can arrive before the sampler
1615        // publishes its first reading, even on a measurable allocator.
1616        let (allocator, age_ms) = allocator_observation(AllocatorSource::Cached);
1617        assert_eq!(allocator.status, "unavailable");
1618        assert_eq!(
1619            allocator.not_estimated,
1620            Some("allocator_observation_unavailable")
1621        );
1622        assert_eq!(allocator.bytes_in_use, None);
1623        assert_eq!(allocator.size_allocated, None);
1624        assert_eq!(allocator.retained_slack_bytes, None);
1625        assert_eq!(age_ms, None);
1626        assert_eq!(allocator_snapshot_calls_for_test(), calls_before);
1627
1628        drop(publish_guard);
1629        publish_allocator_slack(&measured_allocator(100, 140), 0);
1630        let (allocator, age_ms) = allocator_observation(AllocatorSource::Cached);
1631        assert_eq!(allocator.status, "measured");
1632        assert_eq!(allocator.not_estimated, None);
1633        assert_eq!(allocator.bytes_in_use, Some(100));
1634        assert_eq!(allocator.retained_slack_bytes, Some(40));
1635        assert!(age_ms.is_some());
1636        assert_eq!(allocator_snapshot_calls_for_test(), calls_before);
1637    }
1638
1639    #[cfg(target_os = "linux")]
1640    #[test]
1641    fn loop_slack_decision_never_reads_allocator_statistics() {
1642        LAST_OBSERVED_ALLOCATOR_SLACK_BYTES.store(
1643            UNKNOWN_ALLOCATOR_SLACK,
1644            std::sync::atomic::Ordering::Release,
1645        );
1646        LAST_ALLOCATOR_SLACK_SAMPLE_AT_MS
1647            .store(UNSAMPLED_AT_MS, std::sync::atomic::Ordering::Release);
1648        LAST_ALLOCATOR_SLACK_RELIEF_AT_MS
1649            .store(UNSAMPLED_AT_MS, std::sync::atomic::Ordering::Release);
1650        ALLOCATOR_SNAPSHOT_THREADS
1651            .lock()
1652            .expect("clear allocator snapshot thread log")
1653            .clear();
1654
1655        for _ in 0..1_000 {
1656            assert!(!spawn_allocator_slack_relief_if_due(
1657                std::time::Instant::now()
1658            ));
1659        }
1660        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
1661        let sampler_ran = || {
1662            ALLOCATOR_SNAPSHOT_THREADS
1663                .lock()
1664                .expect("read allocator snapshot thread log")
1665                .iter()
1666                .any(|name| name == "aft-mem-slack-sample")
1667        };
1668        while !sampler_ran() {
1669            assert!(std::time::Instant::now() < deadline, "sampler did not run");
1670            std::thread::yield_now();
1671        }
1672        // The thread log is process-global and other tests in the parallel suite
1673        // read allocator statistics on their own threads; the property under
1674        // test is only that THIS thread (the loop stand-in) never did.
1675        let loop_thread = std::thread::current()
1676            .name()
1677            .unwrap_or("unnamed")
1678            .to_string();
1679        let threads = ALLOCATOR_SNAPSHOT_THREADS
1680            .lock()
1681            .expect("read allocator snapshot thread log")
1682            .clone();
1683        assert!(
1684            !threads.iter().any(|name| *name == loop_thread),
1685            "the loop-side decision must never read allocator statistics: {threads:?}"
1686        );
1687    }
1688
1689    #[cfg(target_os = "macos")]
1690    #[test]
1691    fn macos_automatic_slack_sampling_and_relief_are_explicit_only() {
1692        let before = allocator_snapshot_calls_for_test();
1693        for seconds in [0, 30, 300, 3_600] {
1694            assert!(!spawn_allocator_slack_relief_if_due(
1695                std::time::Instant::now() + std::time::Duration::from_secs(seconds)
1696            ));
1697        }
1698        assert_eq!(allocator_snapshot_calls_for_test(), before);
1699    }
1700
1701    #[cfg(any(target_os = "macos", target_os = "linux"))]
1702    #[test]
1703    fn slack_relief_fires_on_large_slack_and_respects_spacing() {
1704        use std::time::{Duration, Instant};
1705        let now = Instant::now();
1706        let big = Some(ALLOCATOR_SLACK_RELIEF_THRESHOLD_BYTES);
1707        // Unknown slack (allocator stats unavailable) never fires.
1708        assert!(!allocator_slack_relief_due(None, None, now));
1709        // Below threshold never fires.
1710        assert!(!allocator_slack_relief_due(
1711            Some(ALLOCATOR_SLACK_RELIEF_THRESHOLD_BYTES - 1),
1712            None,
1713            now
1714        ));
1715        // At threshold with no prior pass fires.
1716        assert!(allocator_slack_relief_due(big, None, now));
1717        // A recent pass suppresses the next one...
1718        let recent = now - Duration::from_secs(10);
1719        assert!(!allocator_slack_relief_due(big, Some(recent), now));
1720        // ...until the minimum spacing has elapsed.
1721        let stale = now - ALLOCATOR_SLACK_RELIEF_MIN_INTERVAL;
1722        assert!(allocator_slack_relief_due(big, Some(stale), now));
1723    }
1724
1725    #[test]
1726    fn json_estimator_scales_with_payload_content() {
1727        let empty = estimated_json_bytes(&serde_json::json!({}));
1728        let populated = estimated_json_bytes(&serde_json::json!({"message": "hello"}));
1729        assert_eq!(empty, 0);
1730        assert!(populated >= 12);
1731    }
1732
1733    #[cfg(any(target_os = "macos", target_os = "linux"))]
1734    #[test]
1735    fn allocator_snapshot_reports_measured_slack() {
1736        let allocator = allocator_memory_snapshot();
1737        if allocator.status == "measured" {
1738            let in_use = allocator.bytes_in_use.expect("allocator bytes in use");
1739            let allocated = allocator.size_allocated.expect("allocator size allocated");
1740            assert_eq!(
1741                allocator.retained_slack_bytes,
1742                Some(allocated.saturating_sub(in_use))
1743            );
1744        } else {
1745            assert_eq!(allocator.status, "not_estimated_on_this_platform");
1746            assert_eq!(allocator.bytes_in_use, None);
1747            assert_eq!(allocator.size_allocated, None);
1748            assert_eq!(allocator.retained_slack_bytes, None);
1749            assert_eq!(
1750                allocator.not_estimated,
1751                Some("jemalloc_statistics_unavailable")
1752            );
1753        }
1754    }
1755
1756    fn measured_allocator(bytes_in_use: u64, size_allocated: u64) -> AllocatorMemorySnapshot {
1757        AllocatorMemorySnapshot {
1758            status: "measured",
1759            bytes_in_use: Some(bytes_in_use),
1760            size_allocated: Some(size_allocated),
1761            retained_slack_bytes: Some(size_allocated.saturating_sub(bytes_in_use)),
1762            retained_slack_label: ALLOCATOR_SLACK_LABEL,
1763            not_estimated: None,
1764            #[cfg(target_os = "linux")]
1765            jemalloc: Some(JemallocMemorySnapshot {
1766                accounting_source: "jemalloc",
1767                allocated: bytes_in_use,
1768                active: bytes_in_use,
1769                resident: size_allocated,
1770                retained: 0,
1771            }),
1772        }
1773    }
1774
1775    #[cfg(target_os = "linux")]
1776    const GIB: u64 = 1024 * 1024 * 1024;
1777    const MIB: u64 = 1024 * 1024;
1778
1779    /// Kernel RSS can fall independently of the allocator's resident estimate.
1780    /// The record must carry both figures, each labelled.
1781    #[cfg(target_os = "linux")]
1782    #[test]
1783    fn relief_reports_rss_drop_when_allocator_accounting_is_unchanged() {
1784        let in_use = 2 * GIB;
1785        let size_allocated = in_use + 7560 * MIB;
1786        let before = ResidentReading {
1787            rss_bytes: Some(6440 * MIB),
1788            phys_footprint_bytes: None,
1789        };
1790        let after = ResidentReading {
1791            rss_bytes: Some(4910 * MIB),
1792            phys_footprint_bytes: None,
1793        };
1794        let relief = AllocatorPressureRelief::from_jemalloc_resident_drop(
1795            before,
1796            after,
1797            measured_allocator(in_use, size_allocated),
1798            measured_allocator(in_use, size_allocated),
1799        );
1800        assert_eq!(relief.allocator_accounting_bytes, 0);
1801        assert_eq!(
1802            relief.allocator_accounting_source,
1803            RELIEF_ACCOUNTING_SOURCE_JEMALLOC
1804        );
1805        assert_eq!(relief.rss_drop_bytes, Some(1530 * MIB));
1806        assert_eq!(relief.rss_before_bytes, Some(6440 * MIB));
1807        assert_eq!(relief.rss_after_bytes, Some(4910 * MIB));
1808        assert_eq!(relief.phys_footprint_drop_bytes, None);
1809        // Slack is unchanged even though memory went back to the OS: it is
1810        // address space, not residency.
1811        assert_eq!(
1812            relief.allocator_before.retained_slack_bytes,
1813            relief.allocator_after.retained_slack_bytes
1814        );
1815    }
1816
1817    #[cfg(target_os = "linux")]
1818    #[test]
1819    fn relief_keeps_allocator_accounting_and_resident_drops_independent() {
1820        // jemalloc's resident estimate fell by 64 MiB while RSS fell by 300 MiB.
1821        let relief = AllocatorPressureRelief::from_jemalloc_resident_drop(
1822            ResidentReading {
1823                rss_bytes: Some(1000 * MIB),
1824                phys_footprint_bytes: None,
1825            },
1826            ResidentReading {
1827                rss_bytes: Some(700 * MIB),
1828                phys_footprint_bytes: None,
1829            },
1830            measured_allocator(100 * MIB, 500 * MIB),
1831            measured_allocator(100 * MIB, 436 * MIB),
1832        );
1833        assert_eq!(relief.allocator_accounting_bytes, 64 * MIB);
1834        assert_eq!(relief.rss_drop_bytes, Some(300 * MIB));
1835
1836        // RSS growth during the pass floors the drop at zero; a missing
1837        // reading yields no drop rather than a guessed one.
1838        let grew = AllocatorPressureRelief::from_jemalloc_resident_drop(
1839            ResidentReading {
1840                rss_bytes: Some(700 * MIB),
1841                phys_footprint_bytes: Some(500 * MIB),
1842            },
1843            ResidentReading {
1844                rss_bytes: Some(900 * MIB),
1845                phys_footprint_bytes: None,
1846            },
1847            measured_allocator(100 * MIB, 500 * MIB),
1848            measured_allocator(100 * MIB, 500 * MIB),
1849        );
1850        assert_eq!(grew.rss_drop_bytes, Some(0));
1851        assert_eq!(grew.phys_footprint_drop_bytes, None);
1852    }
1853
1854    #[test]
1855    fn macos_style_relief_reports_allocator_return_and_footprint_drop() {
1856        let relief = AllocatorPressureRelief::from_observations(
1857            40 * MIB,
1858            RELIEF_ACCOUNTING_SOURCE_MACOS,
1859            ResidentReading {
1860                rss_bytes: Some(900 * MIB),
1861                phys_footprint_bytes: Some(600 * MIB),
1862            },
1863            ResidentReading {
1864                rss_bytes: Some(900 * MIB),
1865                phys_footprint_bytes: Some(520 * MIB),
1866            },
1867            measured_allocator(100 * MIB, 500 * MIB),
1868            measured_allocator(100 * MIB, 500 * MIB),
1869        );
1870        assert_eq!(relief.allocator_accounting_bytes, 40 * MIB);
1871        assert_eq!(
1872            relief.allocator_accounting_source,
1873            RELIEF_ACCOUNTING_SOURCE_MACOS
1874        );
1875        assert_eq!(relief.rss_drop_bytes, Some(0));
1876        assert_eq!(relief.phys_footprint_drop_bytes, Some(80 * MIB));
1877    }
1878
1879    #[test]
1880    fn allocator_snapshot_labels_slack_as_address_space() {
1881        let value = serde_json::to_value(measured_allocator(1, 3)).unwrap();
1882        assert_eq!(value["retained_slack_bytes"], 2);
1883        assert_eq!(value["retained_slack_label"], ALLOCATOR_SLACK_LABEL);
1884        assert!(ALLOCATOR_SLACK_LABEL.starts_with("address-space slack"));
1885    }
1886
1887    #[cfg(target_os = "linux")]
1888    #[test]
1889    fn linux_allocator_pressure_relief_smoke() {
1890        let mut allocation = vec![0u8; 32 * 1024 * 1024];
1891        for byte in allocation.iter_mut().step_by(4096) {
1892            *byte = 1;
1893        }
1894        std::hint::black_box(&allocation);
1895        drop(allocation);
1896
1897        let relief = relieve_allocator_pressure();
1898        assert_eq!(
1899            relief.allocator_accounting_source,
1900            RELIEF_ACCOUNTING_SOURCE_JEMALLOC
1901        );
1902        assert!(relief.allocator_before.jemalloc.is_some());
1903        assert!(relief.allocator_after.jemalloc.is_some());
1904        purge_allocator().expect("jemalloc all-arena purge must succeed");
1905    }
1906
1907    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
1908    #[test]
1909    fn allocator_snapshot_is_honest_when_platform_counters_are_unavailable() {
1910        let allocator = allocator_memory_snapshot();
1911        assert_eq!(allocator.status, "not_estimated_on_this_platform");
1912        assert_eq!(allocator.bytes_in_use, None);
1913        assert_eq!(allocator.size_allocated, None);
1914        assert_eq!(allocator.retained_slack_bytes, None);
1915        assert_eq!(
1916            allocator.not_estimated,
1917            Some("platform_allocator_statistics_unavailable")
1918        );
1919    }
1920
1921    #[cfg(target_os = "macos")]
1922    #[test]
1923    #[ignore = "bounded live RSS experiment; run explicitly after allocator changes"]
1924    fn allocator_pressure_relief_warm_then_idle_measurement() {
1925        let warm_pages = (0..16 * 1024)
1926            .map(|seed| {
1927                let mut page = Box::new([0u8; 4096]);
1928                page[0] = seed as u8;
1929                page
1930            })
1931            .collect::<Vec<_>>();
1932        std::hint::black_box(&warm_pages);
1933        drop(warm_pages);
1934
1935        let relief = relieve_allocator_pressure();
1936        let sqlite = SqliteMemorySnapshot::measure();
1937        eprintln!(
1938            "warm-then-idle pressure relief: rss_before={:?} rss_after={:?} footprint_before={:?} footprint_after={:?} allocator_in_use_before={:?} allocator_in_use_after={:?} allocator_allocated_before={:?} allocator_allocated_after={:?} address_space_slack_before={:?} address_space_slack_after={:?} allocator_accounting={} ({}) sqlite_used={} sqlite_highwater={}",
1939            relief.rss_before_bytes,
1940            relief.rss_after_bytes,
1941            relief.phys_footprint_before_bytes,
1942            relief.phys_footprint_after_bytes,
1943            relief.allocator_before.bytes_in_use,
1944            relief.allocator_after.bytes_in_use,
1945            relief.allocator_before.size_allocated,
1946            relief.allocator_after.size_allocated,
1947            relief.allocator_before.retained_slack_bytes,
1948            relief.allocator_after.retained_slack_bytes,
1949            relief.allocator_accounting_bytes,
1950            relief.allocator_accounting_source,
1951            sqlite.memory_used_bytes,
1952            sqlite.memory_highwater_bytes,
1953        );
1954        assert_eq!(relief.allocator_before.status, "measured");
1955        assert_eq!(relief.allocator_after.status, "measured");
1956    }
1957}