cosca 0.7.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
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
//! A failed spawn's answer to whether the program could have started.
//!
//! Every spawn, sync and tokio, fails with a [`SpawnFailure`], which the public entry points turn
//! into an [`Error`]: [`Error::MayHaveStarted`] around the cause, or the cause alone.
//!
//! There is deliberately no `From<Error>` (nor `From<io::Error>`) for [`SpawnFailure`], so a `?`
//! on a plain error does not compile in a function that returns one. Every failure point in a
//! spawn names its answer: [`Classify::not_started`] or [`SpawnFailure::started`].

use crate::error::{ChildFate, Error};
use crate::Unreaped;

/// A failed spawn's error, and whether the program could have started.
#[derive(Debug)]
pub(crate) enum SpawnFailure {
    /// The program did not start, and cosca has proved it.
    NotStarted(Error),
    /// As [`NotStarted`](Self::NotStarted), after the spawn forked a child it held and dealt with:
    /// `fate` is what became of it, so the leaf's abandonment, which runs after, can state it rather
    /// than hedge.
    #[cfg(target_os = "linux")]
    NotStartedWithChild {
        /// What failed.
        cause: Error,
        /// What the failed spawn did with the child it held.
        #[cfg_attr(
            not(feature = "tokio"),
            allow(dead_code, reason = "only the tokio spawn's abandonment reads it")
        )]
        fate: ChildFate,
    },
    /// As [`NotStarted`](Self::NotStarted), after tokio failed a spawn whose child was never told to
    /// go, and dropped it: the child never ran the program, but nothing held its pid or pidfd, so
    /// whether it was reaped, and by whom, is unknown. The cause says what failed.
    #[cfg(target_os = "linux")]
    NotStartedUnreaped(Error),
    /// The program may have started: the child reached `exec` (on Windows, `CreateProcess` or
    /// `ShellExecuteEx` succeeded), or cosca cannot prove it did not.
    MayHaveStarted {
        /// What failed. Never itself an [`Error::MayHaveStarted`].
        cause: Error,
        /// What the failed spawn did with the child.
        fate: ChildFate,
        /// Whether the child is an elevation backend (see [`Error::MayHaveStarted`]).
        wrapper_elevated: bool,
        /// The child, when the spawn hands it to the caller (see [`Error::MayHaveStarted`]).
        unreaped: Option<Box<Unreaped>>,
    },
}

impl SpawnFailure {
    /// A failure after which the program may have started, of a child that is not an elevation
    /// backend. `unreaped` is the child the spawn hands back, if it does; then `fate` is `Running`
    /// with its identity, or `Unknown` (the look at it failed), or `Killed` (the wait for it failed).
    pub(crate) fn started(cause: Error, fate: ChildFate, unreaped: Option<Unreaped>) -> SpawnFailure {
        SpawnFailure::MayHaveStarted {
            cause,
            fate,
            wrapper_elevated: false,
            unreaped: unreaped.map(Box::new),
        }
    }

    /// Applies `f` to the error, keeping the answer.
    #[cfg(any(test, unix))]
    pub(crate) fn map(self, f: impl FnOnce(Error) -> Error) -> SpawnFailure {
        match self {
            SpawnFailure::NotStarted(e) => SpawnFailure::NotStarted(f(e)),
            #[cfg(target_os = "linux")]
            SpawnFailure::NotStartedUnreaped(e) => SpawnFailure::NotStartedUnreaped(f(e)),
            #[cfg(target_os = "linux")]
            SpawnFailure::NotStartedWithChild { cause, fate } => {
                SpawnFailure::NotStartedWithChild { cause: f(cause), fate }
            }
            SpawnFailure::MayHaveStarted {
                cause,
                fate,
                wrapper_elevated,
                unreaped,
            } => SpawnFailure::MayHaveStarted {
                cause: f(cause),
                fate,
                wrapper_elevated,
                unreaped,
            },
        }
    }

    /// This failure, if it says the program may have started, marked as that of an elevation
    /// backend, whose elevated program may outlive its fate (see [`Error::MayHaveStarted`]).
    pub(crate) fn behind_wrapper(self) -> SpawnFailure {
        match self {
            SpawnFailure::MayHaveStarted {
                cause, fate, unreaped, ..
            } => SpawnFailure::MayHaveStarted {
                cause,
                fate,
                wrapper_elevated: true,
                unreaped,
            },
            not_started => not_started,
        }
    }

    /// This failure, if it says the program may have started, with the error and fate `f` makes of
    /// its cause: for an answer that comes after the failure, from a leaf's abandonment.
    #[cfg(all(feature = "tokio", target_os = "linux"))]
    pub(crate) fn answered_by(self, f: impl FnOnce(Error) -> (Error, ChildFate)) -> SpawnFailure {
        match self {
            SpawnFailure::MayHaveStarted {
                cause,
                wrapper_elevated,
                unreaped,
                ..
            } => {
                let (cause, fate) = f(cause);
                SpawnFailure::MayHaveStarted {
                    cause,
                    fate,
                    wrapper_elevated,
                    unreaped,
                }
            }
            not_started => not_started,
        }
    }

    /// The error itself, whatever the answer.
    #[cfg(all(feature = "tokio", target_os = "linux"))]
    pub(crate) fn error(&self) -> &Error {
        match self {
            SpawnFailure::NotStarted(e)
            | SpawnFailure::NotStartedUnreaped(e)
            | SpawnFailure::MayHaveStarted { cause: e, .. } => e,
            SpawnFailure::NotStartedWithChild { cause, .. } => cause,
        }
    }

    /// Whether this failure is [`NotStartedUnreaped`](Self::NotStartedUnreaped).
    #[cfg(all(feature = "tokio", target_os = "linux"))]
    pub(crate) fn left_child_unreaped(&self) -> bool {
        matches!(self, SpawnFailure::NotStartedUnreaped(_))
    }

    /// What the failed spawn did with a child it held, when that ended it: the child is reaped, or
    /// was found reaped. `None` for any other failure, and for a child the spawn left as it was.
    #[cfg(all(feature = "tokio", target_os = "linux"))]
    pub(crate) fn ended_child(&self) -> Option<ChildFate> {
        match self {
            SpawnFailure::NotStartedWithChild { fate, .. } | SpawnFailure::MayHaveStarted { fate, .. }
                if matches!(fate, ChildFate::Reaped | ChildFate::Killed | ChildFate::Gone) =>
            {
                Some(*fate)
            }
            _ => None,
        }
    }
}

/// The error of a run-to-completion helper (`output`, `status`, `read`) that failed after its spawn
/// succeeded: the program may have started, and `fate` says what became of its child.
/// `unreaped` is the child its teardown could not end, handed back. `behind_wrapper` is whether the
/// child is an elevation backend.
pub(crate) fn after_the_spawn(
    cause: Error,
    fate: ChildFate,
    unreaped: Option<Unreaped>,
    behind_wrapper: bool,
) -> Error {
    Error::from(failed_after_the_spawn(cause, fate, unreaped, behind_wrapper))
}

/// [`after_the_spawn`], as the [`SpawnFailure`] a spawn returns.
pub(crate) fn failed_after_the_spawn(
    cause: Error,
    fate: ChildFate,
    unreaped: Option<Unreaped>,
    behind_wrapper: bool,
) -> SpawnFailure {
    let failure = SpawnFailure::started(cause, fate, unreaped);
    if behind_wrapper {
        failure.behind_wrapper()
    } else {
        failure
    }
}

// Only the Unix tests take a `SpawnFailure` apart; the rest read the public `Error`.
#[cfg(all(test, unix))]
impl SpawnFailure {
    /// The error and fate of a failure that answered that the program may have started; panics
    /// otherwise.
    #[track_caller]
    pub(crate) fn expect_may_have_started_with(self) -> (Error, ChildFate) {
        let (cause, fate, unreaped) = self.parts();
        // Dropping a handed-back child would wait for it; a test that gets one takes it apart with
        // `test_child::SpawnFailure::expect_may_have_started_parts`.
        if let Some(unreaped) = unreaped {
            unreaped.leak();
            panic!("the spawn handed a child back ({fate:?}): {cause:?}");
        }
        (cause, fate)
    }

    /// The error, fate and handed-back child (if any) of a failure that answered that the program
    /// may have started; panics otherwise. For `test_child`, which wraps the child in its
    /// `HandedBack`.
    #[track_caller]
    pub(crate) fn parts(self) -> (Error, ChildFate, Option<Unreaped>) {
        match self {
            SpawnFailure::MayHaveStarted {
                cause, fate, unreaped, ..
            } => (cause, fate, unreaped.map(|unreaped| *unreaped)),
            SpawnFailure::NotStarted(e) => panic!("expected `may have started`, got `not started`: {e:?}"),
            #[cfg(target_os = "linux")]
            SpawnFailure::NotStartedUnreaped(e) => panic!("expected `may have started`, got `not started`: {e:?}"),
            #[cfg(target_os = "linux")]
            SpawnFailure::NotStartedWithChild { cause, .. } => {
                panic!("expected `may have started`, got `not started`: {cause:?}")
            }
        }
    }

    /// The error and fate of a failure that answered that the program did not start and that the
    /// spawn dealt with a child it held; panics otherwise.
    #[cfg(target_os = "linux")]
    #[track_caller]
    pub(crate) fn expect_not_started_with_child(self) -> (Error, ChildFate) {
        match self {
            SpawnFailure::NotStartedWithChild { cause, fate } => (cause, fate),
            other => panic!("expected `not started` with a child's fate, got {other:?}"),
        }
    }

    /// The error of a failure that answered that the program did not start; panics otherwise.
    #[cfg_attr(
        not(target_os = "linux"),
        allow(
            dead_code,
            reason = "only the Linux handshake's tests take a not-started failure apart"
        )
    )]
    #[track_caller]
    pub(crate) fn expect_not_started(self) -> Error {
        match self {
            SpawnFailure::NotStarted(e) => e,
            #[cfg(target_os = "linux")]
            SpawnFailure::NotStartedUnreaped(e) => e,
            #[cfg(target_os = "linux")]
            SpawnFailure::NotStartedWithChild { cause, .. } => cause,
            SpawnFailure::MayHaveStarted { cause, fate, .. } => {
                panic!("expected `not started`, got `may have started` ({fate:?}): {cause:?}")
            }
        }
    }
}

/// The cause and fate inside an error a public spawn returned, which must say the program may have
/// started.
#[cfg(test)]
#[track_caller]
pub(crate) fn expect_may_have_started_with(error: Error) -> (Error, ChildFate) {
    let (cause, fate, unreaped) = error_parts(error);
    if let Some(unreaped) = unreaped {
        unreaped.leak();
        panic!("the spawn handed a child back ({fate:?}): {cause:?}");
    }
    (cause, fate)
}

/// The cause, fate and handed-back child (if any) inside an error a public spawn returned, which
/// must say the program may have started. For `test_child`, which wraps the child in its
/// `HandedBack`.
#[cfg(test)]
#[track_caller]
pub(crate) fn error_parts(error: Error) -> (Error, ChildFate, Option<Unreaped>) {
    match error {
        Error::MayHaveStarted {
            fate, source, unreaped, ..
        } => (*source, fate, unreaped.map(|unreaped| *unreaped)),
        other => panic!("expected Error::MayHaveStarted, got {other:?}"),
    }
}

/// Whether `error` is an `Unsupported` refusal.
#[cfg(all(test, windows))]
pub(crate) fn unsupported(error: &Error) -> bool {
    matches!(error, Error::Unsupported { .. })
}

/// Whether `error` is an `Io(InvalidInput)` refusal.
#[cfg(all(test, windows))]
pub(crate) fn invalid_input(error: &Error) -> bool {
    matches!(error, Error::Io(e) if e.kind() == std::io::ErrorKind::InvalidInput)
}

/// An error a public spawn returned, which must say the program did not start.
#[cfg(test)]
#[track_caller]
pub(crate) fn expect_not_started(error: Error) -> Error {
    assert!(
        !matches!(error, Error::MayHaveStarted { .. }),
        "expected an error that says the program did not start, got {error:?}"
    );
    error
}

impl From<SpawnFailure> for Error {
    fn from(failure: SpawnFailure) -> Error {
        match failure {
            SpawnFailure::NotStarted(error) => {
                debug_assert!(
                    !matches!(error, Error::MayHaveStarted { .. }),
                    "a spawn answered both `not started` and `may have started`: {error}"
                );
                error
            }
            #[cfg(target_os = "linux")]
            SpawnFailure::NotStartedUnreaped(error) => {
                debug_assert!(
                    !matches!(error, Error::MayHaveStarted { .. }),
                    "a spawn answered both `not started` and `may have started`: {error}"
                );
                error
            }
            #[cfg(target_os = "linux")]
            SpawnFailure::NotStartedWithChild { cause: error, .. } => {
                debug_assert!(
                    !matches!(error, Error::MayHaveStarted { .. }),
                    "a spawn answered both `not started` and `may have started`: {error}"
                );
                error
            }
            SpawnFailure::MayHaveStarted {
                cause,
                fate,
                wrapper_elevated,
                unreaped,
            } => {
                debug_assert!(
                    !matches!(cause, Error::MayHaveStarted { .. }),
                    "a `may have started` failure's cause is itself `may have started`: {cause}"
                );
                debug_assert!(
                    unreaped.as_ref().is_none_or(|child| match fate {
                        ChildFate::Running { id } => id == child.id(),
                        ChildFate::Unknown | ChildFate::Killed => true,
                        _ => false,
                    }),
                    "a child handed back is `Running` with its identity, `Unknown` or `Killed`, got {fate:?}"
                );
                Error::MayHaveStarted {
                    fate,
                    wrapper_elevated,
                    source: Box::new(cause),
                    unreaped,
                }
            }
        }
    }
}

/// The plain errors a spawn's failure points produce. Sealed: a [`SpawnFailure`] is not one, so an
/// answered failure cannot be answered again.
pub(crate) trait PlainError: Into<Error> + sealed::Sealed {}
impl PlainError for Error {}
impl PlainError for std::io::Error {}

mod sealed {
    pub trait Sealed {}
    impl Sealed for crate::error::Error {}
    impl Sealed for std::io::Error {}
}

/// Answers, for a failure point in a spawn, that its error leaves the program not started. A failure
/// that may have started is built with [`SpawnFailure::started`], which takes the fate of the child.
pub(crate) trait Classify<T> {
    /// This failure happens before the program can start.
    fn not_started(self) -> Result<T, SpawnFailure>;
}

impl<T, E: PlainError> Classify<T> for Result<T, E> {
    fn not_started(self) -> Result<T, SpawnFailure> {
        self.map_err(|e| SpawnFailure::NotStarted(e.into()))
    }
}

/// Test seams that fail a run-to-completion helper (`output`, `status`, `read`) after its spawn
/// succeeded, or make its child look like an elevation backend. Thread-local; the guard clears them.
#[cfg(test)]
pub(crate) mod seams {
    use std::cell::Cell;
    use std::thread::LocalKey;

    use crate::error::Error;

    thread_local! {
        static WAIT: Cell<bool> = const { Cell::new(false) };
        static PUMP: Cell<bool> = const { Cell::new(false) };
        static WRAPPER: Cell<bool> = const { Cell::new(false) };
    }

    /// The message of the error the seams fail with.
    pub(crate) const FAILURE: &str = "forced failure after the spawn (test seam)";

    #[must_use = "the seam is cleared as soon as the guard is dropped"]
    pub(crate) struct Armed(&'static LocalKey<Cell<bool>>);

    impl Drop for Armed {
        fn drop(&mut self) {
            self.0.with(|f| f.set(false));
        }
    }

    fn arm(flag: &'static LocalKey<Cell<bool>>) -> Armed {
        flag.with(|f| f.set(true));
        Armed(flag)
    }

    /// The next `Child::wait` on this thread fails, before it waits.
    pub(crate) fn fail_the_next_wait() -> Armed {
        arm(&WAIT)
    }

    /// The next `Child::communicate` on this thread fails, before it pumps.
    pub(crate) fn fail_the_next_pump() -> Armed {
        arm(&PUMP)
    }

    /// Every child on this thread looks like an elevation backend while the guard lives.
    pub(crate) fn pretend_wrapper() -> Armed {
        arm(&WRAPPER)
    }

    fn take(flag: &'static LocalKey<Cell<bool>>) -> Option<Error> {
        flag.with(|f| f.replace(false))
            .then(|| Error::Io(std::io::Error::other(FAILURE)))
    }

    pub(crate) fn take_wait_failure() -> Option<Error> {
        take(&WAIT)
    }

    pub(crate) fn take_pump_failure() -> Option<Error> {
        take(&PUMP)
    }

    pub(crate) fn wrapper() -> bool {
        WRAPPER.with(Cell::get)
    }
}

#[cfg(test)]
#[path = "failure_tests.rs"]
mod failure_tests;