cosca 0.9.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
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
// The diagnostic types are pure data, so their formatting is tested on every host.

use std::path::PathBuf;

use crate::containment::cgroup::{log_degrade, LeafError, NotEntered, NotPlaced, PlacementReport};

/// Every `LeafError` names the step and path, and keeps the kernel's reason as its `source()`, not in
/// its text.
///
/// The same raw code renders differently per host (13 is "Permission denied" on Linux and macOS,
/// "The data is invalid." on Windows), so the code is asserted, not `strerror` text.
#[skuld::test]
fn leaf_error_names_step_and_path_and_keeps_the_reason_as_its_source() {
    let reason = |code: i32| std::io::Error::from_raw_os_error(code).to_string();
    let cases: Vec<(LeafError, &[&str], Option<i32>)> = vec![
        (
            LeafError::ReadProcSelfCgroup(std::io::Error::from_raw_os_error(13)),
            &["/proc/self/cgroup"],
            Some(13),
        ),
        (
            LeafError::NoUnifiedLine {
                line_count: 1,
                controllers: "9:memory".into(),
            },
            &["/proc/self/cgroup", "0::", "9:memory"],
            None,
        ),
        (
            LeafError::CreateLeafDir {
                path: PathBuf::from("/sys/fs/cgroup/slice/cosca-7-0"),
                source: std::io::Error::from_raw_os_error(13),
            },
            &["/sys/fs/cgroup/slice/cosca-7-0"],
            Some(13),
        ),
        (
            LeafError::KillUnsupported {
                path: PathBuf::from("/sys/fs/cgroup/slice/cosca-7-0"),
            },
            &["/sys/fs/cgroup/slice/cosca-7-0", "cgroup.kill"],
            None,
        ),
        (
            LeafError::CheckKill {
                path: PathBuf::from("/sys/fs/cgroup/slice/cosca-7-0/cgroup.kill"),
                source: std::io::Error::from_raw_os_error(13),
            },
            &["/sys/fs/cgroup/slice/cosca-7-0/cgroup.kill"],
            Some(13),
        ),
        (
            LeafError::OpenProcs {
                path: PathBuf::from("/sys/fs/cgroup/slice/cosca-7-0/cgroup.procs"),
                source: std::io::Error::from_raw_os_error(13),
            },
            &["cgroup.procs"],
            Some(13),
        ),
        (
            LeafError::OpenOwnCgroup {
                path: PathBuf::from("/sys/fs/cgroup/slice/cgroup.procs"),
                source: std::io::Error::from_raw_os_error(libc::EACCES),
            },
            &["/sys/fs/cgroup/slice/cgroup.procs"],
            Some(libc::EACCES),
        ),
        (
            LeafError::WatchDrain {
                path: PathBuf::from("/sys/fs/cgroup/slice/cosca-7-0/cgroup.events"),
                source: std::io::Error::from_raw_os_error(libc::ENOSPC),
            },
            &["cgroup.events"],
            Some(libc::ENOSPC),
        ),
    ];
    for (err, needles, code) in cases {
        let rendered = err.to_string();
        for needle in needles {
            assert!(
                rendered.contains(needle),
                "{err:?} renders as {rendered:?}, which does not mention {needle:?}"
            );
        }
        let source = std::error::Error::source(&err);
        assert_eq!(
            source
                .and_then(|s| s.downcast_ref::<std::io::Error>())
                .and_then(std::io::Error::raw_os_error),
            code,
            "{err:?}"
        );
        if let Some(code) = code {
            assert!(
                !rendered.contains(&reason(code)),
                "{err:?} renders its cause, which is its source: {rendered:?}"
            );
        }
    }
}

/// The child's own self-placement outcome is reported verbatim, errno included — the one
/// step whose reason lives in the forked child and is otherwise unobservable to the parent.
#[skuld::test]
fn placement_report_renders_the_childs_errno() {
    assert!(PlacementReport::WriteFailed(16).to_string().contains("errno 16"));
    let busy = std::io::Error::from_raw_os_error(16).to_string();
    assert!(PlacementReport::WriteFailed(16).to_string().contains(&busy));
    assert!(PlacementReport::Placed.to_string().contains("succeeded"));
    assert!(PlacementReport::NotReported
        .to_string()
        .contains("exited before reporting"));
}

/// A child whose write failed renders the pid, the leaf path, the file's actual contents, its
/// errno and its state — and never claims a membership that never began.
#[skuld::test]
fn placement_absent_renders_every_observed_fact() {
    let absent = NotPlaced::Absent {
        pid: 4242,
        path: PathBuf::from("/sys/fs/cgroup/slice/cosca-7-0/cgroup.procs"),
        procs: String::new(),
        report: NotEntered::WriteFailed(16),
        child_state: Some('Z'),
    };
    let rendered = absent.to_string();
    for needle in [
        "4242",
        "cosca-7-0/cgroup.procs",
        "empty",
        "errno 16",
        "is not in the leaf",
        "already exited",
    ] {
        assert!(
            rendered.contains(needle),
            "absent placement renders as {rendered:?}, which does not mention {needle:?}"
        );
    }
    assert!(
        !rendered.contains("membership ended"),
        "a child whose write failed was never a member: {rendered:?}"
    );
}

/// A child whose placement step never ran made no write at all, and is reported as such.
#[skuld::test]
fn placement_absent_renders_a_child_that_reported_nothing() {
    let rendered = NotPlaced::Absent {
        pid: 4242,
        path: PathBuf::from("/cg/cgroup.procs"),
        procs: String::new(),
        report: NotEntered::NotReported,
        child_state: Some('S'),
    }
    .to_string();
    assert!(rendered.contains("exited before reporting"), "got {rendered:?}");
    assert!(rendered.contains("is not in the leaf"), "got {rendered:?}");
}

/// A live child that is nonetheless not a member is a different diagnosis from a zombie one,
/// and must not be described as having exited.
#[skuld::test]
fn placement_absent_distinguishes_a_live_child() {
    let rendered = NotPlaced::Absent {
        pid: 4242,
        path: PathBuf::from("/cg/cgroup.procs"),
        procs: "99\n".into(),
        report: NotEntered::WriteFailed(16),
        child_state: Some('S'),
    }
    .to_string();
    assert!(rendered.contains("99"), "the file's real contents must be quoted");
    assert!(rendered.contains("errno 16"), "the child's errno must be carried");
    assert!(!rendered.contains("zombie"), "a live child must not be called a zombie");
}

/// An unreadable `cgroup.procs` is reported as unreadable, not as an empty file, and its text does
/// not repeat the OS error, which is the `source()`.
#[skuld::test]
fn placement_unreadable_says_it_could_not_be_read_and_not_the_io_error() {
    let rendered = NotPlaced::Unreadable {
        pid: 4242,
        path: PathBuf::from("/cg/cgroup.procs"),
        source: std::io::Error::from_raw_os_error(13),
        report: NotEntered::WriteFailed(16),
    }
    .to_string();
    assert!(rendered.contains("/cg/cgroup.procs"));
    assert!(rendered.contains("could not be read"), "{rendered}");
    assert!(
        !rendered.contains(&std::io::Error::from_raw_os_error(13).to_string()),
        "{rendered}"
    );
}

/// The `io::Error` of an unreadable `cgroup.procs` is the error's `source()`, so a report of the
/// chain keeps the OS error whatever the Display says.
#[skuld::test]
fn placement_unreadable_has_the_io_error_as_its_source() {
    let unreadable = NotPlaced::Unreadable {
        pid: 4242,
        path: PathBuf::from("/cg/cgroup.procs"),
        source: std::io::Error::from_raw_os_error(13),
        report: NotEntered::WriteFailed(16),
    };
    let source = std::error::Error::source(&unreadable).expect("an unreadable placement has a source");
    assert_eq!(
        source
            .downcast_ref::<std::io::Error>()
            .and_then(std::io::Error::raw_os_error),
        Some(13)
    );
}

/// The degrade is logged at `warn` with the reason attached — the single line a human reading
/// CI output needs to tell WHICH step failed from the bare fact that containment degraded.
#[skuld::test]
fn degrade_logs_the_reason_at_warn() {
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    log_degrade(&LeafError::KillUnsupported {
        path: PathBuf::from("/sys/fs/cgroup/slice/cosca-degrade-probe-a41f"),
    });
    assert_eq!(
        crate::log_capture::levels_since(mark, "cosca-degrade-probe-a41f"),
        vec![log::Level::Warn],
        "a spawn that did not get the containment it asked for is worth a warning"
    );
    let records = crate::log_capture::records_since(mark, "cosca-degrade-probe-a41f");
    assert!(
        records.iter().all(|record| record.contains("process group")),
        "the degrade log must say what containment degraded TO: {records:?}"
    );
}

/// The warn of an unreadable `cgroup.procs` carries the OS error.
#[skuld::test]
fn the_degrade_warn_of_an_unreadable_placement_says_the_os_error() {
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    log_degrade(&NotPlaced::Unreadable {
        pid: 4242,
        path: PathBuf::from("/cg/cosca-unreadable-probe-3d9e/cgroup.procs"),
        source: std::io::Error::from_raw_os_error(13),
        report: NotEntered::WriteFailed(16),
    });
    let records = crate::log_capture::records_since(mark, "cosca-unreadable-probe-3d9e");
    assert_eq!(records.len(), 1, "{records:?}");
    assert!(
        records[0].contains(&std::io::Error::from_raw_os_error(13).to_string()),
        "{records:?}"
    );
}

/// The warn of a failed step says the OS error once: the chain prints it, the step's own text does
/// not.
#[skuld::test]
fn the_degrade_warn_of_a_failed_step_says_the_os_error_once() {
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    log_degrade(&LeafError::CreateLeafDir {
        path: PathBuf::from("/cg/cosca-once-probe-5b2a"),
        source: std::io::Error::from_raw_os_error(13),
    });
    let records = crate::log_capture::records_since(mark, "cosca-once-probe-5b2a");
    assert_eq!(records.len(), 1, "{records:?}");
    let reason = std::io::Error::from_raw_os_error(13).to_string();
    assert_eq!(records[0].matches(&reason).count(), 1, "{records:?}");
}

/// A repeated reason warns each time; nothing remembers earlier reports.
#[skuld::test]
fn a_repeated_degrade_reason_warns_every_time() {
    crate::log_capture::install();
    let reason = || LeafError::KillUnsupported {
        path: PathBuf::from("/sys/fs/cgroup/slice/cosca-repeat-probe-7c13"),
    };

    let mark = crate::log_capture::mark();
    for _ in 0..3 {
        log_degrade(&reason());
    }

    assert_eq!(
        crate::log_capture::levels_since(mark, "cosca-repeat-probe-7c13"),
        vec![log::Level::Warn, log::Level::Warn, log::Level::Warn],
    );
}

// /proc/self/cgroup summary -----
// `/proc/self/cgroup` is a whole-system dump of every hierarchy the caller is in, read to look
// up one `0::` line. When there is no such line, none of its paths is one cosca touched, and
// none of them separates a v1-only host from an unmounted unified hierarchy from an empty
// file — so only the line count and controllers come back. The sibling variants keep their
// paths for the opposite reason, pinned by `leaf_error_names_step_path_and_reason` and by
// `the_leaf_path_reaches_the_record_verbatim` below.

/// The summary keeps every fact that separates a v1-only host from an unmounted unified
/// hierarchy from an empty file, and drops every path.
#[skuld::test]
fn no_unified_line_reports_the_shape_of_the_file_not_its_paths() {
    let real = concat!(
        "12:freezer:/kubepods/burstable/pod4f8c1e2a-9d3b-11ee-b9d1-0242ac120002/\
         3dc1f9a06b8e4a1c9f2b7d5e8a0c6413\n",
        "11:memory:/user.slice/user-1000.slice\n",
        "1:name=systemd:/user.slice/user-1000.slice/session-3.scope\n",
    );
    let (line_count, controllers) = crate::containment::cgroup::summarize_cgroup_controllers(real);
    assert_eq!(line_count, 3);
    assert_eq!(controllers, "12:freezer, 11:memory, 1:name=systemd");

    let rendered = LeafError::NoUnifiedLine {
        line_count,
        controllers,
    }
    .to_string();
    for identifier in [
        "user-1000",
        "session-3",
        "pod4f8c1e2a",
        "3dc1f9a06b8e4a1c9f2b7d5e8a0c6413",
        "kubepods",
    ] {
        assert!(
            !rendered.contains(identifier),
            "{identifier:?} identifies the caller and must not reach an arbitrary sink; got \
             {rendered:?}"
        );
    }
    assert!(!rendered.contains('\n'), "one record, one line: {rendered:?}");
    for kept in ["0::", "freezer", "memory", "name=systemd", "3"] {
        assert!(rendered.contains(kept), "{kept:?} is the diagnosis; got {rendered:?}");
    }
}

/// An empty `/proc/self/cgroup` is its own diagnosis and must still read as one.
#[skuld::test]
fn no_unified_line_summarizes_an_empty_file() {
    let (line_count, controllers) = crate::containment::cgroup::summarize_cgroup_controllers("");
    assert_eq!(line_count, 0);
    let rendered = LeafError::NoUnifiedLine {
        line_count,
        controllers,
    }
    .to_string();
    assert!(rendered.contains('0'), "the line count is the fact here: {rendered:?}");
}

/// The asymmetry is deliberate, not an oversight in the summary's reach: a step that FAILED on
/// a path reports that path in full, identifiers and all. It is the one path the syscall
/// touched, it is the diagnosis, and a record without it says only that some mkdir somewhere
/// was refused.
#[skuld::test]
fn the_leaf_path_reaches_the_record_verbatim() {
    let leaf = "/sys/fs/cgroup/kubepods/pod4f8c1e2a-9d3b-11ee-b9d1-0242ac120002/cosca-7-0";
    let rendered = LeafError::CreateLeafDir {
        path: PathBuf::from(leaf),
        source: std::io::Error::from_raw_os_error(13),
    }
    .to_string();
    assert!(
        rendered.contains(leaf),
        "the failing mkdir's own path is the diagnosis and must not be summarized away: got \
         {rendered:?}"
    );
}

/// A line the kernel format does not explain is reported as unparseable, never quoted: an
/// unrecognized line is exactly the case where cosca cannot know which part is a path.
#[skuld::test]
fn no_unified_line_never_quotes_a_line_it_could_not_parse() {
    let (line_count, controllers) =
        crate::containment::cgroup::summarize_cgroup_controllers("nonsense-with-no-colons\n");
    assert_eq!(line_count, 1);
    assert!(
        !controllers.contains("nonsense"),
        "an unparsed line's content must not be echoed: {controllers:?}"
    );
}

/// The error of a `Strongest` spawn that could not have its cgroup names the cgroup and the step,
/// and keeps the kernel's refusal as its source.
#[skuld::test]
fn a_leaf_error_becomes_a_containment_error_that_keeps_the_os_error() {
    let leaf = PathBuf::from("/sys/fs/cgroup/slice/cosca-7-0");
    let error = LeafError::CreateLeafDir {
        path: leaf.clone(),
        source: std::io::Error::from_raw_os_error(13),
    }
    .into_containment();
    let crate::error::Error::Containment {
        detail,
        source: Some(source),
    } = &error
    else {
        panic!("{error:?}");
    };
    assert!(
        detail.contains("cgroup") && detail.contains(&*leaf.to_string_lossy()),
        "{detail:?}"
    );
    assert!(
        matches!(&**source, crate::error::Error::Io(e) if e.raw_os_error() == Some(13)),
        "{source:?}"
    );
}