ic-host-process 0.8.4

Admitted host executable resolution, bounded execution and Git observations
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
use super::*;
use crate::child::OwnedChild;
use rustix::process::{Pid, WaitId, WaitIdOptions, waitid};
use std::{process::Stdio, time::Instant};

mod observe;

fn command(script: &str) -> Command {
    let mut command = Command::new("/bin/sh");
    command
        .args(["-c", script])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    command
}

fn assert_reaped(child: &OwnedChild) {
    let pid = Pid::from_raw(i32::try_from(child.id()).unwrap()).unwrap();
    assert_eq!(
        waitid(
            WaitId::Pid(pid),
            WaitIdOptions::EXITED | WaitIdOptions::NOHANG
        )
        .unwrap_err(),
        rustix::io::Errno::CHILD
    );
}

#[test]
fn full_duplex_io_is_bounded_fair_and_leaves_success_reserved() {
    let _fixture = Fixture::new();
    // Fill both output pipes before reading input larger than a pipe capacity.
    let mut command = command(
        "n=0; while [ \"$n\" -lt 10000 ]; do printf 0123456789abcdef; \
         printf fedcba9876543210 >&2; n=$((n + 1)); done; cat",
    );
    let mut child = OwnedChild::spawn(&mut command).unwrap();
    let input = vec![b'x'; 256 * 1024];
    let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
    let evidence = communicate_child_with_observer(
        &mut child,
        Some(&input),
        OutputLimits {
            stdout_bytes: 160_000 + input.len(),
            ..LIMITS
        },
        SuccessfulExit::Retain,
        || false,
        |stream, bytes| match stream {
            OutputStream::Stdout => stdout.extend_from_slice(bytes),
            OutputStream::Stderr => stderr.extend_from_slice(bytes),
        },
    )
    .unwrap();
    assert_eq!(
        &evidence.stdout[..160_000],
        b"0123456789abcdef".repeat(10_000)
    );
    assert_eq!(&evidence.stdout[160_000..], input);
    assert_eq!(evidence.stderr, b"fedcba9876543210".repeat(10_000));
    assert_eq!(stdout, evidence.stdout);
    assert_eq!(stderr, evidence.stderr);
    assert!(evidence.status.unwrap().success());
    let pid = Pid::from_raw(i32::try_from(child.id()).unwrap()).unwrap();
    assert!(
        waitid(
            WaitId::Pid(pid),
            WaitIdOptions::EXITED | WaitIdOptions::NOWAIT
        )
        .unwrap()
        .is_some()
    );
    assert!(child.wait().unwrap().success());
    assert_reaped(&child);
}

#[test]
fn absent_input_closes_piped_stdin_and_caller_io_is_preserved() {
    let fixture = Fixture::new();
    for input in [None, Some(&b""[..])] {
        let mut child = OwnedChild::spawn(&mut command("cat; printf eof")).unwrap();
        assert_eq!(
            communicate_child(&mut child, input, LIMITS, SuccessfulExit::Retain, || false)
                .unwrap()
                .stdout,
            b"eof"
        );
        child.wait().unwrap();
    }
    let input_path = fixture.root.join("input");
    let output_path = fixture.root.join("output");
    fs::write(&input_path, b"caller-selected input").unwrap();
    let mut command = command("cat >&2");
    command
        .stdin(fs::File::open(input_path).unwrap())
        .stdout(Stdio::inherit())
        .stderr(fs::File::create(&output_path).unwrap());
    let mut child = OwnedChild::spawn(&mut command).unwrap();
    let evidence = communicate_child(
        &mut child,
        None,
        OutputLimits {
            stdout_bytes: 0,
            stderr_bytes: 0,
            ..LIMITS
        },
        SuccessfulExit::Retain,
        || false,
    )
    .unwrap();
    child.wait().unwrap();
    assert!(evidence.stdout.is_empty() && evidence.stderr.is_empty());
    assert_eq!(fs::read(output_path).unwrap(), b"caller-selected input");
}

#[test]
fn early_stdin_close_preserves_command_status_and_diagnostics() {
    let _fixture = Fixture::new();
    for code in [0, 23] {
        let mut child = OwnedChild::spawn(&mut command(&format!(
            "exec 0<&-; printf diagnostic >&2; exit {code}"
        )))
        .unwrap();
        let input = vec![b'x'; 1024 * 1024];
        let result = communicate_child(
            &mut child,
            Some(&input),
            LIMITS,
            SuccessfulExit::Retain,
            || false,
        );
        let evidence = if code == 0 {
            let evidence = result.unwrap();
            child.wait().unwrap();
            evidence
        } else {
            let ToolError::Execution(error) = result.unwrap_err() else {
                panic!("execution failure")
            };
            assert!(matches!(error.failure, ExecutionFailure::ExitStatus));
            error.evidence
        };
        assert_eq!(evidence.stderr, b"diagnostic");
        assert_eq!(evidence.status.unwrap().code(), Some(code));
        assert_reaped(&child);
    }
}

#[test]
fn cancellation_interrupts_blocked_input_and_reaps_the_group() {
    let fixture = Fixture::new();
    let ready = fixture.root.join("ready");
    let go = fixture.root.join("go");
    let late = fixture.root.join("late");
    let mut command = command(
        "(printf ready > \"$READY\"; while ! test -f \"$GO\"; do sleep 0.01; done; \
         printf late > \"$LATE\") & wait",
    );
    command
        .env("READY", &ready)
        .env("GO", &go)
        .env("LATE", &late);
    let mut child = OwnedChild::spawn(&mut command).unwrap();
    let input = vec![b'x'; 1024 * 1024];
    let result = communicate_child(
        &mut child,
        Some(&input),
        LIMITS,
        SuccessfulExit::Cleanup,
        || ready.exists(),
    );
    fs::write(go, b"go").unwrap();
    let error = result.unwrap_err();
    let execution = error.execution_error().unwrap();
    assert!(matches!(execution.failure, ExecutionFailure::Cancelled));
    assert!(execution.evidence.status.is_some());
    assert!(
        execution.group_error.is_none()
            && execution.kill_error.is_none()
            && execution.wait_error.is_none()
    );
    assert_reaped(&child);
    std::thread::sleep(Duration::from_millis(100));
    assert!(!late.exists());
}

#[test]
fn successful_background_handoff_requires_explicit_post_io_admission() {
    let fixture = Fixture::new();
    for handoff in [false, true] {
        let ready = fixture.root.join(format!("ready-{handoff}"));
        let go = fixture.root.join(format!("go-{handoff}"));
        let late = fixture.root.join(format!("late-{handoff}"));
        let mut command = command(
            "(printf ready > \"$READY\"; while ! test -f \"$GO\"; do sleep 0.01; done; \
             printf late > \"$LATE\") >/dev/null 2>&1 & \
             while ! test -f \"$READY\"; do sleep 0.01; done; printf '\\377'",
        );
        command
            .env("READY", ready)
            .env("GO", &go)
            .env("LATE", &late);
        let mut child = OwnedChild::spawn(&mut command).unwrap();
        let evidence =
            communicate_child(&mut child, None, LIMITS, SuccessfulExit::Retain, || false).unwrap();
        assert!(std::str::from_utf8(&evidence.stdout).is_err());
        if handoff {
            // A binary-output consumer can admit these bytes and transfer lifecycle.
            child.handoff().unwrap();
        } else {
            // A text consumer rejects the same output with cleanup still armed.
            child.terminate().unwrap();
        }
        assert_reaped(&child);
        let error = communicate_child(&mut child, None, LIMITS, SuccessfulExit::Retain, || false)
            .unwrap_err();
        assert!(matches!(&error.execution_error().unwrap().failure,
            ExecutionFailure::Io { operation: ExecutionOperation::Wait, source }
            if source.kind() == io::ErrorKind::InvalidInput));
        drop(child);
        fs::write(go, b"go").unwrap();
        if handoff {
            let deadline = Instant::now() + Duration::from_secs(5);
            while !late.exists() {
                assert!(Instant::now() < deadline);
                std::thread::sleep(Duration::from_millis(2));
            }
        } else {
            std::thread::sleep(Duration::from_millis(100));
            assert!(!late.exists());
        }
    }
}

#[test]
fn held_pipe_deadline_and_overflow_keep_cleanup_armed_after_leader_exit() {
    let _fixture = Fixture::new();
    for (script, overflow) in [
        ("sleep 30 & exit 0", false),
        ("printf 12345; sleep 30 & exit 0", true),
    ] {
        let mut child = OwnedChild::spawn(&mut command(script)).unwrap();
        let error = communicate_child(
            &mut child,
            None,
            OutputLimits {
                stdout_bytes: 4,
                timeout: Duration::from_secs(1),
                ..LIMITS
            },
            SuccessfulExit::Retain,
            || false,
        )
        .unwrap_err();
        let execution = error.execution_error().unwrap();
        if overflow {
            assert!(matches!(
                execution.failure,
                ExecutionFailure::OutputLimit {
                    stream: OutputStream::Stdout
                }
            ));
            assert_eq!(execution.evidence.stdout, b"1234");
        } else {
            assert!(matches!(execution.failure, ExecutionFailure::TimedOut));
        }
        assert!(execution.group_error.is_none() && execution.wait_error.is_none());
        assert_reaped(&child);
    }
}

#[test]
fn invalid_deadline_retains_owner_and_missing_input_pipe_cleans_it() {
    let _fixture = Fixture::new();
    let mut child = OwnedChild::spawn(&mut command("cat")).unwrap();
    for timeout in [Duration::ZERO, Duration::MAX] {
        assert!(matches!(
            communicate_child(
                &mut child,
                None,
                OutputLimits { timeout, ..LIMITS },
                SuccessfulExit::Retain,
                || { false }
            ),
            Err(ToolError::InvalidInvocation(InvalidInvocation::Deadline))
        ));
    }
    assert_eq!(
        communicate_child(
            &mut child,
            Some(b"still available"),
            LIMITS,
            SuccessfulExit::Retain,
            || false
        )
        .unwrap()
        .stdout,
        b"still available"
    );
    child.wait().unwrap();

    let mut command = command("sleep 30");
    command.stdin(Stdio::null());
    let mut child = OwnedChild::spawn(&mut command).unwrap();
    let error = communicate_child(
        &mut child,
        Some(b""),
        LIMITS,
        SuccessfulExit::Retain,
        || false,
    )
    .unwrap_err();
    assert!(matches!(
        error.execution_error().unwrap().failure,
        ExecutionFailure::Io {
            operation: ExecutionOperation::StdinPipe,
            ..
        }
    ));
    assert_reaped(&child);
}

#[test]
fn cancellation_is_checked_again_before_returning_reserved_success() {
    let _fixture = Fixture::new();
    let mut child = OwnedChild::spawn(&mut command("exit 0")).unwrap();
    let deadline = Instant::now() + Duration::from_secs(5);
    while child.poll_exit().unwrap().is_none() {
        assert!(Instant::now() < deadline);
        std::thread::sleep(Duration::from_millis(2));
    }
    let mut polls = 0;
    let error = communicate_child(&mut child, None, LIMITS, SuccessfulExit::Retain, || {
        polls += 1;
        polls > 1
    })
    .unwrap_err();
    assert!(matches!(
        error.execution_error().unwrap().failure,
        ExecutionFailure::Cancelled
    ));
    assert!(error.evidence().unwrap().status.unwrap().success());
    assert_reaped(&child);
    assert!(child.handoff().is_err());
}

#[test]
fn communication_uses_owned_term_grace_with_blocked_input_and_held_pipes() {
    let fixture = Fixture::new();
    for mode in ["timeout", "cancel", "exited-leader"] {
        let ready = fixture.root.join(mode);
        let mut command = command(
            "trap 'exit 0' TERM; \
             sh -c 'trap \"\" TERM; printf ready > \"$READY\"; exec sleep 30' & \
             printf prefix; if [ \"$MODE\" = exited-leader ]; then exit 0; fi; wait",
        );
        command.env("READY", &ready).env("MODE", mode);
        let grace = Duration::from_millis(50);
        let mut child = OwnedChild::spawn_with_cleanup(
            &mut command,
            crate::child::CleanupPolicy::TermThenKill {
                grace,
                reap_timeout: Duration::from_secs(2),
            },
        )
        .unwrap();
        let ready_deadline = Instant::now() + Duration::from_secs(5);
        while !ready.exists() {
            assert!(Instant::now() < ready_deadline);
            std::thread::sleep(Duration::from_millis(2));
        }
        let input = vec![b'x'; 1024 * 1024];
        let started = Instant::now();
        let error = communicate_child(
            &mut child,
            Some(&input),
            OutputLimits {
                timeout: Duration::from_millis(100),
                ..LIMITS
            },
            SuccessfulExit::Retain,
            || mode == "cancel",
        )
        .unwrap_err();
        let execution = error.execution_error().unwrap();
        if mode == "cancel" {
            assert!(matches!(execution.failure, ExecutionFailure::Cancelled));
        } else {
            assert!(matches!(execution.failure, ExecutionFailure::TimedOut));
            assert_eq!(execution.evidence.stdout, b"prefix");
        }
        assert!(started.elapsed() >= grace);
        assert!(
            execution.term_error.is_none()
                && execution.group_error.is_none()
                && execution.kill_error.is_none()
                && execution.wait_error.is_none()
        );
        assert_reaped(&child);
        assert!(child.handoff().is_err());
    }
}