xchecker 1.2.0

Spec pipeline with receipts and gateable JSON contracts
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
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
//! Tests for Unix process group termination (Task 5.9, FR-RUN-005)
//!
//! **WHITE-BOX TEST**: This test uses internal module APIs (`runner::Runner`) and may break
//! with internal refactors. These tests are intentionally white-box to validate internal
//! implementation details. See FR-TEST-4 for white-box test policy.
//!
//! This test validates that:
//! - Process groups are created correctly with setpgid(0, 0)
//! - killpg sends SIGTERM to the entire process group
//! - After 5 second grace period, SIGKILL is sent
//! - Child processes are terminated along with parent
//! - Timeout handling works correctly with process groups
//!
//! Requirements: FR-RUN-005

#![cfg(unix)]

use std::process::Stdio;
use std::time::Duration;
use tokio::time::sleep;
use xchecker::runner::{CommandSpec, Runner};

type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

// ============================================================================
// Helper Functions
// ============================================================================

/// Check if a process is still running
///
/// Note: This uses `kill(pid, 0)` which can succeed for zombie processes.
/// For reliable termination checks, prefer `wait_for_exit()` which reaps the child.
fn is_process_running(pid: u32) -> bool {
    use nix::sys::signal::kill;
    use nix::unistd::Pid;

    let pid = Pid::from_raw(pid as i32);
    // Signal 0 (None) doesn't send a signal but checks if the process exists
    kill(pid, None).is_ok()
}

/// Wait for a child process to exit with a timeout.
///
/// This properly reaps the child process (avoiding zombie issues) by awaiting
/// `child.wait()` with a timeout. The wait() call is the actual reap operation.
///
/// Returns `true` if the child exited within the timeout, `false` otherwise.
async fn wait_for_exit(child: &mut tokio::process::Child, timeout: Duration) -> bool {
    match tokio::time::timeout(timeout, child.wait()).await {
        Ok(Ok(_status)) => true, // Process exited and reaped
        Ok(Err(e)) => {
            // wait() failed: treat as failure, not success
            eprintln!("child.wait() failed: {e}");
            false
        }
        Err(_) => false, // Timed out
    }
}

/// Create a test script that spawns child processes
fn create_test_script(script_path: &str, duration_secs: u64) -> Result<()> {
    use std::fs;
    use std::os::unix::fs::PermissionsExt;

    let script_content = format!(
        r#"#!/bin/bash
# Test script that spawns child processes
sleep {} &
CHILD1=$!
sleep {} &
CHILD2=$!
sleep {} &
CHILD3=$!
echo "Parent PID: $$"
echo "Child PIDs: $CHILD1 $CHILD2 $CHILD3"
wait
"#,
        duration_secs, duration_secs, duration_secs
    );

    fs::write(script_path, script_content)?;

    // Make script executable
    let metadata = fs::metadata(script_path)?;
    let mut permissions = metadata.permissions();
    permissions.set_mode(0o755);
    fs::set_permissions(script_path, permissions)?;

    Ok(())
}

// ============================================================================
// Unit Tests: Process Group Creation
// ============================================================================

/// Test that process groups are created correctly
#[tokio::test]
async fn test_process_group_creation() -> Result<()> {
    // Create a simple command that will run long enough for us to check
    let mut cmd = CommandSpec::new("sleep").arg("10").to_tokio_command();
    cmd.stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());

    // Set up process group (same as in Runner)
    {
        #[allow(unused_imports)]
        use std::os::unix::process::CommandExt;
        unsafe {
            cmd.pre_exec(|| {
                libc::setpgid(0, 0);
                Ok(())
            });
        }
    }

    let mut child = cmd.spawn()?;
    let pid = child.id().expect("Failed to get child PID");

    // Check that the process is running
    assert!(is_process_running(pid), "Process should be running");

    // Get the process group ID
    let pgid = unsafe { libc::getpgid(pid as i32) };

    // The process should be its own process group leader
    assert_eq!(
        pgid, pid as i32,
        "Process should be its own process group leader"
    );

    // Clean up
    child.kill().await?;
    let _ = child.wait().await;

    println!("✓ Process group creation verified");
    Ok(())
}

// ============================================================================
// Integration Tests: SIGTERM and SIGKILL Sequence
// ============================================================================

/// Test that SIGTERM is sent first, followed by SIGKILL after grace period
#[tokio::test]
async fn test_sigterm_then_sigkill_sequence() -> Result<()> {
    use nix::errno::Errno;
    use nix::sys::signal::{Signal, killpg};
    use nix::unistd::Pid;

    // Spawn a process that ignores SIGTERM (to test SIGKILL)
    let mut cmd = CommandSpec::new("sh")
        .arg("-c")
        .arg("trap '' TERM; sleep 30") // Ignore SIGTERM, sleep for 30 seconds
        .to_tokio_command();
    cmd.stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());

    {
        #[allow(unused_imports)]
        use std::os::unix::process::CommandExt;
        unsafe {
            cmd.pre_exec(|| {
                libc::setpgid(0, 0);
                Ok(())
            });
        }
    }

    let mut child = cmd.spawn()?;
    let pid = child.id().expect("Failed to get child PID");
    let pgid = Pid::from_raw(pid as i32);

    // Verify process is running
    assert!(
        is_process_running(pid),
        "Process should be running initially"
    );

    // Send SIGTERM (process will ignore it)
    // Some CI environments (notably macOS runners) restrict process group
    // signal delivery, returning EPERM. Skip the test in that case.
    if let Err(e) = killpg(pgid, Signal::SIGTERM) {
        if e == Errno::EPERM {
            eprintln!("Skipping: killpg returned EPERM (restricted CI environment)");
            let _ = child.kill().await;
            return Ok(());
        }
        return Err(e.into());
    }

    // Wait a short time
    sleep(Duration::from_millis(500)).await;

    // Process should still be running (it ignored SIGTERM)
    assert!(
        is_process_running(pid),
        "Process should still be running after SIGTERM"
    );

    // Send SIGKILL (cannot be ignored)
    killpg(pgid, Signal::SIGKILL)?;

    // Wait for the process to exit and be reaped (avoids zombie false positives)
    assert!(
        wait_for_exit(&mut child, Duration::from_secs(3)).await,
        "Process should exit promptly after SIGKILL"
    );

    println!("✓ SIGTERM then SIGKILL sequence verified");
    Ok(())
}

/// Test that graceful termination works with SIGTERM
#[tokio::test]
async fn test_graceful_termination_with_sigterm() -> Result<()> {
    use nix::sys::signal::{Signal, killpg};
    use nix::unistd::Pid;

    // Spawn a process that handles SIGTERM gracefully
    let mut cmd = CommandSpec::new("sleep").arg("30").to_tokio_command();
    cmd.stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());

    {
        #[allow(unused_imports)]
        use std::os::unix::process::CommandExt;
        unsafe {
            cmd.pre_exec(|| {
                libc::setpgid(0, 0);
                Ok(())
            });
        }
    }

    let mut child = cmd.spawn()?;
    let pid = child.id().expect("Failed to get child PID");
    let pgid = Pid::from_raw(pid as i32);

    // Verify process is running
    assert!(
        is_process_running(pid),
        "Process should be running initially"
    );

    // Send SIGTERM
    killpg(pgid, Signal::SIGTERM)?;

    // Wait for the process to exit and be reaped (avoids zombie false positives)
    assert!(
        wait_for_exit(&mut child, Duration::from_secs(3)).await,
        "Process should exit promptly after SIGTERM"
    );

    println!("✓ Graceful termination with SIGTERM verified");
    Ok(())
}

// ============================================================================
// Integration Tests: Process Group Termination
// ============================================================================

/// Test that killpg terminates all processes in the group
#[tokio::test]
async fn test_process_group_termination() -> Result<()> {
    use tempfile::TempDir;

    let temp_dir = TempDir::new()?;
    let script_path = temp_dir.path().join("test_script.sh");

    // Create a script that spawns multiple child processes
    create_test_script(script_path.to_str().unwrap(), 30)?;

    // Spawn the script
    let mut cmd = CommandSpec::new("bash")
        .arg(script_path.to_str().unwrap())
        .to_tokio_command();
    cmd.stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null());

    {
        #[allow(unused_imports)]
        use std::os::unix::process::CommandExt;
        unsafe {
            cmd.pre_exec(|| {
                libc::setpgid(0, 0);
                Ok(())
            });
        }
    }

    let mut child = cmd.spawn()?;
    let parent_pid = child.id().expect("Failed to get parent PID");

    // Wait a bit for child processes to spawn
    sleep(Duration::from_millis(500)).await;

    // Verify parent is running
    assert!(
        is_process_running(parent_pid),
        "Parent process should be running"
    );

    // Terminate the entire process group
    use nix::sys::signal::{Signal, killpg};
    use nix::unistd::Pid;
    let pgid = Pid::from_raw(parent_pid as i32);
    killpg(pgid, Signal::SIGKILL)?;

    // Wait for the process to exit and be reaped (avoids zombie false positives)
    assert!(
        wait_for_exit(&mut child, Duration::from_secs(3)).await,
        "Parent process should exit promptly after SIGKILL"
    );

    println!("✓ Process group termination verified");
    Ok(())
}

// ============================================================================
// Integration Tests: Runner Timeout with Process Groups
// ============================================================================

/// Test that Runner timeout terminates process groups correctly
#[tokio::test]
#[ignore = "flaky in CI - timing-dependent timeout handling"]
async fn test_runner_timeout_terminates_process_group() -> Result<()> {
    use tempfile::TempDir;

    let temp_dir = TempDir::new()?;
    let script_path = temp_dir.path().join("long_running.sh");

    // Create a script that runs for a long time
    create_test_script(script_path.to_str().unwrap(), 60)?;

    // Create a runner with a short timeout
    let runner = Runner::native();

    // Execute with a very short timeout (1 second)
    let timeout_duration = Some(Duration::from_secs(1));

    let result = runner
        .execute_claude(
            &[script_path.to_str().unwrap().to_string()],
            "",
            timeout_duration,
        )
        .await;

    // Should timeout
    match result {
        Err(e) => {
            let error_str = format!("{:?}", e);
            assert!(
                error_str.contains("Timeout") || error_str.contains("timeout"),
                "Expected timeout error, got: {}",
                error_str
            );
            println!("✓ Runner timeout correctly triggered");
        }
        Ok(response) => {
            // If it didn't timeout, the command completed quickly
            println!(
                "✓ Command completed before timeout (exit code: {})",
                response.exit_code
            );
        }
    }

    Ok(())
}

/// Test that timeout with grace period works correctly
#[tokio::test]
async fn test_timeout_grace_period() -> Result<()> {
    use nix::sys::signal::{Signal, killpg};
    use nix::unistd::Pid;

    // Spawn a process
    let mut cmd = CommandSpec::new("sleep").arg("30").to_tokio_command();
    cmd.stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());

    {
        #[allow(unused_imports)]
        use std::os::unix::process::CommandExt;
        unsafe {
            cmd.pre_exec(|| {
                libc::setpgid(0, 0);
                Ok(())
            });
        }
    }

    let mut child = cmd.spawn()?;
    let pid = child.id().expect("Failed to get child PID");
    let pgid = Pid::from_raw(pid as i32);

    // Verify process is running
    assert!(is_process_running(pid), "Process should be running");

    // Simulate the timeout sequence from Runner
    // 1. Send SIGTERM
    let _ = killpg(pgid, Signal::SIGTERM);

    // 2. Wait grace period (5 seconds)
    let start = std::time::Instant::now();
    sleep(Duration::from_secs(5)).await;
    let elapsed = start.elapsed();

    // Verify we waited approximately 5 seconds
    assert!(
        elapsed >= Duration::from_secs(4) && elapsed <= Duration::from_secs(6),
        "Grace period should be approximately 5 seconds, was: {:?}",
        elapsed
    );

    // 3. Send SIGKILL
    let _ = killpg(pgid, Signal::SIGKILL);

    // Wait for the process to exit and be reaped (avoids zombie false positives)
    assert!(
        wait_for_exit(&mut child, Duration::from_secs(3)).await,
        "Process should exit promptly after SIGKILL"
    );

    println!("✓ Timeout grace period verified (5 seconds)");
    Ok(())
}

// ============================================================================
// Integration Tests: Edge Cases
// ============================================================================

/// Test termination of already-terminated process
#[tokio::test]
async fn test_terminate_already_dead_process() -> Result<()> {
    use nix::sys::signal::{Signal, killpg};
    use nix::unistd::Pid;

    // Spawn a process that exits immediately
    let mut cmd = CommandSpec::new("true").to_tokio_command();
    cmd.stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());

    {
        #[allow(unused_imports)]
        use std::os::unix::process::CommandExt;
        unsafe {
            cmd.pre_exec(|| {
                libc::setpgid(0, 0);
                Ok(())
            });
        }
    }

    let mut child = cmd.spawn()?;
    let pid = child.id().expect("Failed to get child PID");
    let pgid = Pid::from_raw(pid as i32);

    // Wait for process to exit
    let _ = child.wait().await;

    // Verify process is not running
    assert!(!is_process_running(pid), "Process should have exited");

    // Try to terminate (should not panic or error)
    let result = killpg(pgid, Signal::SIGTERM);

    // This may succeed or fail depending on timing, but should not panic
    match result {
        Ok(_) => println!("✓ Terminating dead process succeeded (no-op)"),
        Err(_) => println!("✓ Terminating dead process failed gracefully (expected)"),
    }

    Ok(())
}

/// Test termination with invalid PID
#[tokio::test]
async fn test_terminate_invalid_pid() -> Result<()> {
    use nix::sys::signal::{Signal, killpg};
    use nix::unistd::Pid;

    // Use a PID that's unlikely to exist (very high number)
    let invalid_pid = Pid::from_raw(999999);

    // Try to terminate (should fail gracefully)
    let result = killpg(invalid_pid, Signal::SIGTERM);

    // Should fail, but not panic
    assert!(result.is_err(), "Terminating invalid PID should fail");

    println!("✓ Terminating invalid PID failed gracefully");
    Ok(())
}

// ============================================================================
// Summary Test
// ============================================================================

/// Comprehensive test that validates all Unix process termination requirements
/// Note: Individual tests are run separately by the test framework.
/// This test is disabled to avoid duplicate test runs.
#[tokio::test]
#[ignore = "Individual tests are run separately; this is a summary test"]
async fn test_unix_process_termination_comprehensive() -> Result<()> {
    println!("\n=== Unix Process Termination Comprehensive Test ===\n");
    println!("Individual tests are run separately by the test framework.");
    println!("\n=== All Unix Process Termination Tests Passed ===\n");
    Ok(())
}