zebrad 7.1.0

The Zcash Foundation's independent, consensus-compatible implementation of a Zcash node
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
//! Records this process's memory use, so operators can see a node approaching its memory limit
//! before the kernel stops it.

use std::time::Duration;
#[cfg(target_os = "linux")]
use std::{
    collections::HashMap,
    path::{Component, Path, PathBuf},
};

#[cfg(target_os = "linux")]
use crate::components::zcashd_compat::parse_self_cgroup_paths;

/// How often [`record_process_memory`] samples memory use.
///
/// Shorter than the Prometheus scrape and Sentry flush intervals, so each one sees a recent value.
const SAMPLE_INTERVAL: Duration = Duration::from_secs(15);

/// Records this process's memory use every [`SAMPLE_INTERVAL`], until the task is aborted.
pub async fn record_process_memory() {
    let mut interval = tokio::time::interval(SAMPLE_INTERVAL);
    loop {
        interval.tick().await;
        record();
    }
}

/// Sets the `process.memory.rss_bytes` gauge to the resident set size of this process, and
/// `process.memory.rss_fraction` to that size as a fraction of the memory it can use: the cgroup
/// memory limit, or the machine's memory if no cgroup sets a lower limit.
///
/// Does nothing on platforms without `/proc`, or if the values can't be read.
pub(crate) fn record() {
    let Some(rss) = read("/proc/self/status").and_then(|status| kib_field(&status, "VmRSS:"))
    else {
        return;
    };
    // Memory sizes are far below the integers f64 represents exactly.
    metrics::gauge!("process.memory.rss_bytes").set(rss as f64);

    let machine = read("/proc/meminfo").and_then(|meminfo| kib_field(&meminfo, "MemTotal:"));
    #[cfg(target_os = "linux")]
    let cgroup = tightest_cgroup_limit(
        &read("/proc/self/cgroup").unwrap_or_default(),
        &read("/proc/self/mountinfo").unwrap_or_default(),
        |path| std::fs::read_to_string(path).ok(),
    );
    #[cfg(not(target_os = "linux"))]
    let cgroup = None;
    if let Some(available) = available_memory(machine, cgroup) {
        metrics::gauge!("process.memory.rss_fraction").set(rss as f64 / available as f64);
    }
}

fn read(path: &str) -> Option<String> {
    std::fs::read_to_string(path).ok()
}

/// Returns the value in bytes of a `name  <value> kB` line, as in `/proc/self/status` and
/// `/proc/meminfo`.
fn kib_field(contents: &str, name: &str) -> Option<u64> {
    contents
        .lines()
        .find_map(|line| line.strip_prefix(name))?
        .split_whitespace()
        .next()?
        .parse::<u64>()
        .ok()?
        .checked_mul(1024)
}

/// Returns the tightest memory limit on this process's cgroups, given the contents of
/// `/proc/self/cgroup` and `/proc/self/mountinfo`.
///
/// A service usually runs in a nested cgroup, such as a systemd unit under `system.slice`, and any
/// cgroup between it and the root can set the limit that applies. So this checks the process's
/// cgroup and every ancestor visible in a mount, under both the cgroup v2 and the v1 `memory`
/// hierarchies.
#[cfg(target_os = "linux")]
fn tightest_cgroup_limit(
    self_cgroup: &str,
    mountinfo: &str,
    read: impl Fn(&Path) -> Option<String>,
) -> Option<u64> {
    let (v2_path, v1_path) = parse_self_cgroup_paths(self_cgroup);
    let (mut v2_mounts, mut v1_mounts) = cgroup_mounts(mountinfo);
    if v2_mounts.is_empty() && v1_mounts.is_empty() {
        v2_mounts.push(CgroupMount::at_root("/sys/fs/cgroup"));
        v1_mounts.push(CgroupMount::at_root("/sys/fs/cgroup/memory"));
    }

    limit_files(&v2_mounts, v2_path.as_deref(), "memory.max")
        .into_iter()
        .chain(limit_files(
            &v1_mounts,
            v1_path.as_deref(),
            "memory.limit_in_bytes",
        ))
        .filter_map(|path| read(&path))
        .filter_map(|limit| cgroup_limit(&limit))
        .min()
}

/// A mounted cgroup hierarchy.
#[cfg(target_os = "linux")]
#[derive(Clone, Debug, PartialEq, Eq)]
struct CgroupMount {
    /// The cgroup in the hierarchy that the mount shows at its mount point. Membership paths in
    /// `/proc/self/cgroup` are relative to the hierarchy, not to this cgroup.
    root: PathBuf,
    /// Where the cgroup at `root` appears in the filesystem.
    mount_point: PathBuf,
}

#[cfg(target_os = "linux")]
impl CgroupMount {
    fn at_root(mount_point: &str) -> Self {
        Self {
            root: PathBuf::from("/"),
            mount_point: PathBuf::from(mount_point),
        }
    }
}

/// Returns the cgroup v2 mounts and the cgroup v1 `memory` mounts listed in
/// `/proc/self/mountinfo` that no other mount hides.
#[cfg(target_os = "linux")]
fn cgroup_mounts(mountinfo: &str) -> (Vec<CgroupMount>, Vec<CgroupMount>) {
    /// The cgroup hierarchy a mount shows, if any.
    enum Hierarchy {
        V2,
        V1Memory,
        Other,
    }

    struct Mount {
        id: u64,
        parent_id: u64,
        hierarchy: Hierarchy,
        cgroup: CgroupMount,
    }

    let mut mounts = Vec::new();
    for line in mountinfo.lines() {
        // Optional fields come before the ` - ` separator, so the mount fields are counted from
        // the start and the filesystem fields from the separator.
        let Some((mount, filesystem)) = line.split_once(" - ") else {
            continue;
        };
        let mut mount = mount.split_whitespace();
        let (Some(id), Some(parent_id), Some(_device), Some(root), Some(mount_point)) = (
            mount.next().and_then(|id| id.parse().ok()),
            mount.next().and_then(|id| id.parse().ok()),
            mount.next(),
            mount.next(),
            mount.next(),
        ) else {
            continue;
        };
        let mut filesystem = filesystem.split_whitespace();
        let (Some(fs_type), Some(_source), super_options) =
            (filesystem.next(), filesystem.next(), filesystem.next())
        else {
            continue;
        };
        let hierarchy = if fs_type == "cgroup2" {
            Hierarchy::V2
        } else if fs_type == "cgroup"
            && super_options.is_some_and(|options| options.split(',').any(|o| o == "memory"))
        {
            Hierarchy::V1Memory
        } else {
            Hierarchy::Other
        };

        mounts.push(Mount {
            id,
            parent_id,
            hierarchy,
            cgroup: CgroupMount {
                root: PathBuf::from(unescape_mountinfo(root)),
                mount_point: PathBuf::from(unescape_mountinfo(mount_point)),
            },
        });
    }

    let parents: HashMap<u64, u64> = mounts
        .iter()
        .map(|mount| (mount.id, mount.parent_id))
        .collect();
    // Returns the mount that a lookup of `path` lands on, starting above the top of the mount
    // chain `id` is on. Like the kernel, the lookup goes down one directory at a time, and at
    // each one moves onto the last mount on that directory, repeatedly for stacked mounts. The
    // walks are bounded by the number of mounts, in case of a parent cycle.
    let lookup = |id: u64, path: &Path| {
        let mut current = std::iter::successors(Some(id), |id| parents.get(id).copied())
            .take(mounts.len() + 1)
            .last()
            .unwrap_or(id);
        let mut directories: Vec<_> = path.ancestors().collect();
        directories.reverse();
        for directory in directories {
            for _ in 0..mounts.len() {
                let Some(above) = mounts.iter().rev().find(|mount| {
                    mount.parent_id == current
                        && mount.id != current
                        && mount.cgroup.mount_point == directory
                }) else {
                    break;
                };
                current = above.id;
            }
        }
        current
    };
    // A mount is hidden when another mount covers its mount point or a directory above it. Its
    // paths would then lead into the other mount, and could read a different cgroup's limit.
    let is_visible = |mount: &Mount| lookup(mount.id, &mount.cgroup.mount_point) == mount.id;

    let mut v2 = Vec::new();
    let mut v1_memory = Vec::new();
    for mount in &mounts {
        match mount.hierarchy {
            Hierarchy::V2 if is_visible(mount) => v2.push(mount.cgroup.clone()),
            Hierarchy::V1Memory if is_visible(mount) => v1_memory.push(mount.cgroup.clone()),
            _ => {}
        }
    }

    (v2, v1_memory)
}

/// Decodes the octal escapes (such as `\040` for a space) that `/proc/self/mountinfo` uses in
/// paths.
#[cfg(target_os = "linux")]
fn unescape_mountinfo(field: &str) -> String {
    let bytes = field.as_bytes();
    let mut decoded = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        let escape = bytes.get(i + 1..i + 4).filter(|digits| {
            bytes[i] == b'\\' && digits.iter().all(|digit| (b'0'..=b'7').contains(digit))
        });
        match escape
            .and_then(|digits| u8::from_str_radix(std::str::from_utf8(digits).ok()?, 8).ok())
        {
            Some(byte) => {
                decoded.push(byte);
                i += 4;
            }
            None => {
                decoded.push(bytes[i]);
                i += 1;
            }
        }
    }
    String::from_utf8_lossy(&decoded).into_owned()
}

/// Returns the paths of `file_name` in the cgroup at `membership` and in each of its ancestors,
/// through every mount that shows them.
///
/// Mounts can overlap: a mount of a subtree shows the process's cgroup but not the ancestors above
/// the subtree, which a broader mount of the same hierarchy may still show. So this collects the
/// paths from every mount whose root contains the cgroup.
///
/// A membership path that leaves the hierarchy (`..`, seen when the cgroup is outside this cgroup
/// namespace) only checks the mount points.
#[cfg(target_os = "linux")]
fn limit_files(mounts: &[CgroupMount], membership: Option<&str>, file_name: &str) -> Vec<PathBuf> {
    let membership = Path::new(membership.unwrap_or("/"));
    if !membership
        .components()
        .all(|component| matches!(component, Component::RootDir | Component::Normal(_)))
    {
        return mounts
            .iter()
            .map(|mount| mount.mount_point.join(file_name))
            .collect();
    }

    mounts
        .iter()
        .filter_map(|mount| Some((mount, membership.strip_prefix(&mount.root).ok()?)))
        .flat_map(|(mount, relative_path)| {
            mount
                .mount_point
                .join(relative_path)
                .ancestors()
                .take_while(|dir| dir.starts_with(&mount.mount_point))
                .map(|dir| dir.join(file_name))
                .collect::<Vec<_>>()
        })
        .collect()
}

/// Returns a cgroup memory limit in bytes, or `None` if the cgroup has no limit.
///
/// cgroup v2 writes `max` for no limit. cgroup v1 writes a value near `i64::MAX`, which is larger
/// than any machine's memory, so [`available_memory`] ignores it.
fn cgroup_limit(contents: &str) -> Option<u64> {
    contents.trim().parse().ok()
}

/// Returns the memory this process can use: the smaller of the machine's memory and the cgroup
/// limit, ignoring values that are unknown or zero.
fn available_memory(machine: Option<u64>, cgroup: Option<u64>) -> Option<u64> {
    machine
        .into_iter()
        .chain(cgroup)
        .filter(|bytes| *bytes > 0)
        .min()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reads_kib_fields_as_bytes() {
        let status = "Name:\tzebrad\nVmHWM:\t 7067912 kB\nVmRSS:\t 6886020 kB\nThreads:\t34\n";

        assert_eq!(kib_field(status, "VmRSS:"), Some(6_886_020 * 1024));
        assert_eq!(
            kib_field("MemTotal:       8131200 kB\n", "MemTotal:"),
            Some(8_131_200 * 1024)
        );
        assert_eq!(kib_field(status, "MemTotal:"), None);
    }

    #[test]
    fn uses_the_smaller_of_the_machine_and_cgroup_limits() {
        let gib = 1024 * 1024 * 1024;

        assert_eq!(cgroup_limit("max\n"), None);
        assert_eq!(cgroup_limit("4294967296\n"), Some(4 * gib));

        assert_eq!(available_memory(Some(8 * gib), None), Some(8 * gib));
        assert_eq!(
            available_memory(Some(8 * gib), Some(4 * gib)),
            Some(4 * gib)
        );
        // cgroup v1 reports no limit as a value near i64::MAX.
        assert_eq!(
            available_memory(Some(8 * gib), Some(9_223_372_036_854_771_712)),
            Some(8 * gib)
        );
        assert_eq!(available_memory(None, Some(0)), None);
    }

    #[cfg(target_os = "linux")]
    const V2_MOUNTINFO: &str =
        "25 30 0:22 / /sys/fs/cgroup rw,nosuid shared:9 - cgroup2 cgroup2 rw,nsdelegate\n";

    #[cfg(target_os = "linux")]
    const V1_MOUNTINFO: &str = "\
        30 25 0:26 / /sys/fs/cgroup/cpu,cpuacct rw shared:10 - cgroup cgroup rw,cpu,cpuacct\n\
        31 25 0:27 / /sys/fs/cgroup/memory rw shared:11 - cgroup cgroup rw,memory\n";

    #[cfg(target_os = "linux")]
    #[test]
    fn finds_cgroup_mounts_in_mountinfo() {
        let mountinfo = "\
            22 1 8:1 / / rw,relatime shared:1 - ext4 /dev/sda1 rw\n\
            25 22 0:22 /tenant /mnt/tenant\\040cgroups rw shared:9 master:2 - cgroup2 cgroup2 rw\n\
            31 22 0:27 /docker /sys/fs/cgroup/memory rw - cgroup cgroup rw,memory\n\
            32 22 0:28 / /sys/fs/cgroup/pids rw - cgroup cgroup rw,pids\n";

        let (v2, v1_memory) = cgroup_mounts(mountinfo);

        assert_eq!(
            v2,
            vec![CgroupMount {
                root: PathBuf::from("/tenant"),
                mount_point: PathBuf::from("/mnt/tenant cgroups"),
            }]
        );
        assert_eq!(
            v1_memory,
            vec![CgroupMount {
                root: PathBuf::from("/docker"),
                mount_point: PathBuf::from("/sys/fs/cgroup/memory"),
            }]
        );
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn uses_the_mount_root_to_find_cgroups_in_a_subtree_mount() {
        let gib: u64 = 1024 * 1024 * 1024;
        // The mount shows the `/tenant` cgroup at `/sys/fs/cgroup`, so the process's `/tenant/zebrad`
        // cgroup is at `/sys/fs/cgroup/zebrad`, not `/sys/fs/cgroup/tenant/zebrad`.
        let mountinfo = "25 30 0:22 /tenant /sys/fs/cgroup rw shared:9 - cgroup2 cgroup2 rw\n";
        let files: std::collections::HashMap<_, _> = [
            (
                PathBuf::from("/sys/fs/cgroup/memory.max"),
                format!("{}\n", 8 * gib),
            ),
            (
                PathBuf::from("/sys/fs/cgroup/zebrad/memory.max"),
                format!("{}\n", 2 * gib),
            ),
        ]
        .into_iter()
        .collect();

        assert_eq!(
            tightest_cgroup_limit("0::/tenant/zebrad\n", mountinfo, |path| files
                .get(path)
                .cloned()),
            Some(2 * gib)
        );

        // A cgroup outside the mounted subtree can't be seen, so it has no visible limit.
        assert_eq!(
            tightest_cgroup_limit("0::/other/zebrad\n", mountinfo, |path| files
                .get(path)
                .cloned()),
            None
        );
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn uses_ancestor_limits_from_a_broader_overlapping_mount() {
        let gib: u64 = 1024 * 1024 * 1024;
        // The whole hierarchy is at `/sys/fs/cgroup`, and `/tenant/service` is also at
        // `/run/service-cgroup`. Only the broader mount shows the limit on `/tenant`.
        let mountinfo = "\
            25 22 0:22 / /sys/fs/cgroup rw shared:9 - cgroup2 cgroup2 rw\n\
            40 22 0:22 /tenant/service /run/service-cgroup rw shared:9 - cgroup2 cgroup2 rw\n";
        let files: std::collections::HashMap<_, _> = [
            ("/sys/fs/cgroup/memory.max", "max\n".to_string()),
            ("/sys/fs/cgroup/tenant/memory.max", format!("{}\n", 2 * gib)),
            (
                "/sys/fs/cgroup/tenant/service/memory.max",
                "max\n".to_string(),
            ),
            (
                "/sys/fs/cgroup/tenant/service/zebrad/memory.max",
                "max\n".to_string(),
            ),
            ("/run/service-cgroup/memory.max", "max\n".to_string()),
            ("/run/service-cgroup/zebrad/memory.max", "max\n".to_string()),
        ]
        .into_iter()
        .map(|(path, value)| (PathBuf::from(path), value))
        .collect();

        assert_eq!(
            tightest_cgroup_limit("0::/tenant/service/zebrad\n", mountinfo, |path| files
                .get(path)
                .cloned()),
            Some(2 * gib)
        );

        // The same applies to cgroup v1 `memory` mounts.
        let mountinfo = "\
            31 22 0:27 / /sys/fs/cgroup/memory rw - cgroup cgroup rw,memory\n\
            41 22 0:27 /tenant/service /run/service-memory rw - cgroup cgroup rw,memory\n";
        let files: std::collections::HashMap<_, _> = [(
            PathBuf::from("/sys/fs/cgroup/memory/tenant/memory.limit_in_bytes"),
            format!("{}\n", 2 * gib),
        )]
        .into_iter()
        .collect();

        assert_eq!(
            tightest_cgroup_limit("4:memory:/tenant/service/zebrad\n", mountinfo, |path| files
                .get(path)
                .cloned()),
            Some(2 * gib)
        );
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn ignores_cgroup_mounts_hidden_by_other_mounts() {
        let gib: u64 = 1024 * 1024 * 1024;
        // Mount 50 shows `/tenant` on top of mount 25, which showed the whole hierarchy at the same
        // place. Through mount 25, `/tenant` would map to `/sys/fs/cgroup/tenant`, which is now the
        // `/tenant/tenant` cgroup with a sibling's limit.
        let mountinfo = "\
            25 22 0:22 / /sys/fs/cgroup rw shared:9 - cgroup2 cgroup2 rw\n\
            50 25 0:22 /tenant /sys/fs/cgroup rw shared:9 - cgroup2 cgroup2 rw\n";
        let files: std::collections::HashMap<_, _> = [
            ("/sys/fs/cgroup/memory.max", "max\n".to_string()),
            ("/sys/fs/cgroup/tenant/memory.max", format!("{}\n", gib)),
            ("/sys/fs/cgroup/zebrad/memory.max", format!("{}\n", 3 * gib)),
        ]
        .into_iter()
        .map(|(path, value)| (PathBuf::from(path), value))
        .collect();

        assert_eq!(
            cgroup_mounts(mountinfo).0,
            vec![CgroupMount {
                root: PathBuf::from("/tenant"),
                mount_point: PathBuf::from("/sys/fs/cgroup"),
            }]
        );
        assert_eq!(
            tightest_cgroup_limit("0::/tenant/zebrad\n", mountinfo, |path| files
                .get(path)
                .cloned()),
            Some(3 * gib)
        );

        // A mount on a directory above a cgroup mount hides it too, unless the cgroup mount sits on
        // it. Mount 70 covers `/sys/fs/cgroup` after mount 31 was mounted inside it, but mount 32
        // was mounted on mount 70 and stays visible.
        let mountinfo = "\
            30 22 0:25 / /sys/fs/cgroup rw - tmpfs tmpfs rw\n\
            31 30 0:27 / /sys/fs/cgroup/memory rw - cgroup cgroup rw,memory\n\
            70 30 0:40 / /sys/fs/cgroup rw - tmpfs tmpfs rw\n\
            32 70 0:41 /docker /sys/fs/cgroup/memory rw - cgroup cgroup rw,memory\n";

        assert_eq!(
            cgroup_mounts(mountinfo).1,
            vec![CgroupMount {
                root: PathBuf::from("/docker"),
                mount_point: PathBuf::from("/sys/fs/cgroup/memory"),
            }]
        );
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn uses_the_tightest_limit_on_nested_cgroups() {
        let gib: u64 = 1024 * 1024 * 1024;
        let files = |entries: &[(&str, String)]| {
            entries
                .iter()
                .map(|(path, value)| (PathBuf::from(path), value.clone()))
                .collect::<std::collections::HashMap<_, _>>()
        };

        // cgroup v2: the service has no limit of its own, but its slice does.
        let v2 = files(&[
            ("/sys/fs/cgroup/memory.max", "max\n".into()),
            (
                "/sys/fs/cgroup/system.slice/memory.max",
                format!("{}\n", 4 * gib),
            ),
            (
                "/sys/fs/cgroup/system.slice/zebrad.service/memory.max",
                "max\n".into(),
            ),
        ]);
        let self_cgroup = "0::/system.slice/zebrad.service\n";
        assert_eq!(
            tightest_cgroup_limit(self_cgroup, V2_MOUNTINFO, |path| v2.get(path).cloned()),
            Some(4 * gib)
        );

        // A tighter limit on the service itself wins over its slice.
        let mut v2_service = v2.clone();
        v2_service.insert(
            PathBuf::from("/sys/fs/cgroup/system.slice/zebrad.service/memory.max"),
            format!("{}\n", 2 * gib),
        );
        assert_eq!(
            tightest_cgroup_limit(self_cgroup, V2_MOUNTINFO, |path| {
                v2_service.get(path).cloned()
            }),
            Some(2 * gib)
        );

        // cgroup v1: the limit is on the process's `memory` cgroup, not the hierarchy root.
        let v1 = files(&[
            (
                "/sys/fs/cgroup/memory/memory.limit_in_bytes",
                "9223372036854771712\n".into(),
            ),
            (
                "/sys/fs/cgroup/memory/docker/abcdef/memory.limit_in_bytes",
                format!("{}\n", 3 * gib),
            ),
        ]);
        let self_cgroup = "12:cpu,cpuacct:/docker/abcdef\n4:memory:/docker/abcdef\n";
        assert_eq!(
            tightest_cgroup_limit(self_cgroup, V1_MOUNTINFO, |path| v1.get(path).cloned()),
            Some(3 * gib)
        );

        // Without readable `/proc/self/cgroup` and `/proc/self/mountinfo`, or with a cgroup outside
        // this namespace, only the root limit is checked.
        let root = files(&[("/sys/fs/cgroup/memory.max", format!("{}\n", 6 * gib))]);
        assert_eq!(
            tightest_cgroup_limit("", "", |path| root.get(path).cloned()),
            Some(6 * gib)
        );
        assert_eq!(
            limit_files(
                &[CgroupMount::at_root("/sys/fs/cgroup")],
                Some("/../../user.slice"),
                "memory.max"
            ),
            vec![PathBuf::from("/sys/fs/cgroup/memory.max")]
        );
    }

    #[test]
    fn records_this_process_on_linux() {
        if cfg!(target_os = "linux") {
            let rss = read("/proc/self/status").and_then(|status| kib_field(&status, "VmRSS:"));
            assert!(rss.is_some_and(|rss| rss > 0));
        }
    }
}