1use std::collections::BTreeMap;
2use std::path::Path;
3
4use serde::Serialize;
5use serde_json::Value;
6
7#[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 pub pending_install: MemoryEstimate,
97 pub exact_memo: MemoryEstimate,
98 pub compression_filters: MemoryEstimate,
99 #[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 #[serde(skip_serializing_if = "Option::is_none")]
119 pub standing: Option<bool>,
120 #[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 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 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 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 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 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 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
309pub 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 pub retained_slack_bytes: Option<u64>,
332 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 #[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 Cached,
384 Measure,
386}
387
388#[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 #[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 pub allocator: AllocatorMemorySnapshot,
426 pub allocator_slack_measured: bool,
428 pub allocator_observation_age_ms: Option<u64>,
431 pub total_attributed_bytes: u64,
432 pub embedding_sessions: u64,
434 pub embedding_model_bytes: u64,
437 #[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
448pub const RELIEF_ACCOUNTING_SOURCE_JEMALLOC: &str = "jemalloc_stats_resident_drop";
451pub const RELIEF_ACCOUNTING_SOURCE_MACOS: &str = "malloc_zone_pressure_relief_return";
456
457#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
459pub struct ResidentReading {
460 pub rss_bytes: Option<u64>,
461 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#[derive(Debug, Clone, PartialEq, Eq)]
479pub struct AllocatorPressureRelief {
480 pub allocator_accounting_bytes: u64,
483 pub allocator_accounting_source: &'static str,
485 pub rss_drop_bytes: Option<u64>,
490 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 #[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 #[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
569pub const MEMORY_SNAPSHOT_ROOT_DETAIL_CAP: usize = 8;
576
577pub const CENSUS_ALLOCATION_LABELS: usize = 5;
579
580#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
581pub struct MemorySnapshot {
582 pub roots_status: &'static str,
583 pub roots: BTreeMap<String, RootMemorySnapshot>,
587 pub roots_total: usize,
589 pub roots_omitted: usize,
591 pub roots_omitted_bytes: u64,
594 pub shared_semantic_bases: MemoryEstimate,
598 #[serde(skip_serializing_if = "Option::is_none")]
602 pub data_layer_block_cache: Option<MemoryEstimate>,
603 pub process: ProcessMemorySnapshot,
604 #[serde(skip_serializing_if = "Vec::is_empty")]
609 pub allocation_labels: Vec<crate::alloc_trace::LabelPeak>,
610}
611
612#[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
659pub 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 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#[cfg(target_os = "linux")]
763pub fn purge_allocator() -> std::io::Result<()> {
764 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
786fn 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 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 #[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
856pub const ALLOCATOR_SLACK_RELIEF_THRESHOLD_BYTES: u64 = 1024 * 1024 * 1024;
863
864pub const ALLOCATOR_SLACK_RELIEF_MIN_INTERVAL: std::time::Duration =
867 std::time::Duration::from_secs(300);
868
869const ALLOCATOR_WALK_COST_FACTOR: u64 = 200;
874
875const ALLOCATOR_WALK_MAX_REUSE_MS: u64 = 10 * 60 * 1000;
878
879pub 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")))]
891const ALLOCATOR_SLACK_SAMPLE_INTERVAL: std::time::Duration = std::time::Duration::from_secs(60);
897#[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 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
1040pub 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#[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#[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
1261pub 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
1275pub 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
1290pub 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
1305pub 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#[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#[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#[cfg(not(target_os = "linux"))]
1413pub fn spawn_allocator_slack_relief_if_due(_now: std::time::Instant) -> bool {
1414 false
1415}
1416
1417#[cfg(target_os = "macos")]
1421fn relieve_allocator_pressure_from_snapshot(
1422 allocator_before: AllocatorMemorySnapshot,
1423) -> AllocatorPressureRelief {
1424 let resident_before = ResidentReading::read();
1425 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#[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#[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 assert_eq!(allocator_reuse_window_ms(30_000, 0), 30_000);
1578 assert_eq!(allocator_reuse_window_ms(30_000, 150), 30_000);
1579 assert_eq!(allocator_reuse_window_ms(30_000, 1_000), 200_000);
1581 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 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 assert!(!sample_is_stale_after(0, 59_999, 20));
1594 assert!(sample_is_stale_after(0, 60_000, 20));
1595 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 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 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 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 assert!(!allocator_slack_relief_due(None, None, now));
1709 assert!(!allocator_slack_relief_due(
1711 Some(ALLOCATOR_SLACK_RELIEF_THRESHOLD_BYTES - 1),
1712 None,
1713 now
1714 ));
1715 assert!(allocator_slack_relief_due(big, None, now));
1717 let recent = now - Duration::from_secs(10);
1719 assert!(!allocator_slack_relief_due(big, Some(recent), now));
1720 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 #[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 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 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 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}