返回 last30days-skill
proc_group_unix_test.go
根目录 / mcp / internal / engine / proc_group_unix_test.go
1 //go:build !windows
2
3 package engine
4
5 import (
6 "context"
7 "errors"
8 "os"
9 "os/exec"
10 "os/signal"
11 "path/filepath"
12 "slices"
13 "strconv"
14 "strings"
15 "sync"
16 "sync/atomic"
17 "syscall"
18 "testing"
19 "time"
20 )
21
22 func TestRunParentCancellationIsNotSuccess(t *testing.T) {
23 dir := t.TempDir()
24 ready := filepath.Join(dir, "ready")
25 stub := filepath.Join(dir, "python3-cancel-stub.sh")
26 script := `#!/bin/sh
27 trap 'printf "canceled cleanly\n" >&2; exit 0' TERM
28 printf 'partial research\n'
29 : > "$RUN_CANCEL_READY"
30 while :; do sleep 1; done
31 `
32 if err := os.WriteFile(stub, []byte(script), 0o755); err != nil {
33 t.Fatal(err)
34 }
35 ctx, cancel := context.WithCancel(context.Background())
36 defer cancel()
37 readyCh := make(chan error, 1)
38 go func() {
39 deadline := time.NewTimer(3 * time.Second)
40 defer deadline.Stop()
41 tick := time.NewTicker(10 * time.Millisecond)
42 defer tick.Stop()
43 for {
44 select {
45 case <-tick.C:
46 if _, err := os.Stat(ready); err == nil {
47 readyCh <- nil
48 cancel()
49 return
50 }
51 case <-deadline.C:
52 readyCh <- errors.New("child did not install its SIGTERM handler")
53 cancel()
54 return
55 }
56 }
57 }()
58
59 started := time.Now()
60 res, err := Run(ctx, RunOptions{
61 PythonPath: stub,
62 CacheDir: stageCache(t),
63 Timeout: 10 * time.Second,
64 ExtraEnv: []string{"RUN_CANCEL_READY=" + ready},
65 })
66 if readyErr := <-readyCh; readyErr != nil {
67 t.Fatal(readyErr)
68 }
69 if time.Since(started) > 4*time.Second {
70 t.Error("parent cancellation exceeded the bounded shutdown grace")
71 }
72 if !errors.Is(err, context.Canceled) {
73 t.Errorf("Run error = %v, want context.Canceled after clean child exit", err)
74 }
75 if res == nil {
76 t.Fatal("Run result is nil; want partial output alongside cancellation")
77 }
78 if res.ExitCode != 0 || res.TimedOut {
79 t.Errorf("Run result = %+v, want clean exit without timeout", res)
80 }
81 if string(res.Stdout) != "partial research\n" || !strings.Contains(string(res.Stderr), "canceled cleanly") {
82 t.Errorf("partial output lost: stdout=%q stderr=%q", res.Stdout, res.Stderr)
83 }
84 }
85
86 func TestRunTimeoutBoundsInheritedPipes(t *testing.T) {
87 executable, err := os.Executable()
88 if err != nil {
89 t.Fatal(err)
90 }
91 for _, mode := range []string{"signal-exit", "clean-exit", "clean-exit-without-child", "term-ignoring-in-group"} {
92 t.Run(mode, func(t *testing.T) {
93 dir := t.TempDir()
94 pidFile := filepath.Join(dir, "detached.pid")
95 stub := filepath.Join(dir, "python3-detached-stub.sh")
96 if err := os.WriteFile(stub, []byte("#!/bin/sh\nexec \"$CR012_TEST_BINARY\" -test.run='^TestRunDetachedPipeHelper$'\n"), 0o755); err != nil {
97 t.Fatal(err)
98 }
99 t.Cleanup(func() {
100 if raw, err := os.ReadFile(pidFile); err == nil {
101 if pid, err := strconv.Atoi(string(raw)); err == nil && pid > 0 {
102 _ = syscall.Kill(pid, syscall.SIGKILL)
103 }
104 }
105 })
106
107 started := time.Now()
108 res, err := Run(context.Background(), RunOptions{
109 PythonPath: stub,
110 CacheDir: stageCache(t),
111 Timeout: 200 * time.Millisecond,
112 ExtraEnv: []string{
113 "CR012_TEST_BINARY=" + executable,
114 "CR012_HELPER_MODE=" + mode,
115 "CR012_PID_FILE=" + pidFile,
116 },
117 })
118 elapsed := time.Since(started)
119 if elapsed > 4*time.Second {
120 t.Errorf("Run took %s for a 200ms timeout; detached pipes must not outlive the bounded shutdown grace", elapsed)
121 }
122 if err == nil || !strings.Contains(err.Error(), "timeout") {
123 t.Errorf("Run error = %v, want timeout", err)
124 }
125 if res == nil || !res.TimedOut {
126 t.Fatalf("Run result = %+v, want TimedOut", res)
127 }
128 if mode != "clean-exit-without-child" && (!strings.Contains(string(res.Stdout), "detached stdout") || !strings.Contains(string(res.Stderr), "detached stderr")) {
129 t.Fatalf("detached process did not inherit both pipes: stdout=%q stderr=%q", res.Stdout, res.Stderr)
130 }
131 if mode == "term-ignoring-in-group" {
132 assertPidDead(t, pidFile, "TERM-ignoring in-group grandchild")
133 }
134 })
135 }
136 }
137
138 func TestRunDetachedPipeHelper(t *testing.T) {
139 mode := os.Getenv("CR012_HELPER_MODE")
140 if mode == "" {
141 t.Skip("subprocess fixture")
142 }
143 if mode == "pipe-holder" || mode == "pipe-holder-ignore-term" {
144 if mode == "pipe-holder-ignore-term" {
145 signal.Ignore(syscall.SIGTERM)
146 }
147 _, _ = os.Stdout.WriteString("detached stdout\n")
148 _, _ = os.Stderr.WriteString("detached stderr\n")
149 time.Sleep(8 * time.Second)
150 os.Exit(0)
151 }
152 if mode == "clean-exit" || mode == "clean-exit-without-child" {
153 terminated := make(chan os.Signal, 1)
154 signal.Notify(terminated, syscall.SIGTERM)
155 go func() {
156 <-terminated
157 os.Exit(0)
158 }()
159 }
160 if mode == "clean-exit-without-child" {
161 time.Sleep(8 * time.Second)
162 os.Exit(0)
163 }
164 child := exec.Command(os.Args[0], "-test.run=^TestRunDetachedPipeHelper$")
165 if mode == "term-ignoring-in-group" {
166 child.Env = append(os.Environ(), "CR012_HELPER_MODE=pipe-holder-ignore-term")
167 } else {
168 child.Env = append(os.Environ(), "CR012_HELPER_MODE=pipe-holder")
169 child.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
170 }
171 child.Stdout = os.Stdout
172 child.Stderr = os.Stderr
173 if err := child.Start(); err != nil {
174 t.Fatal(err)
175 }
176 if err := os.WriteFile(os.Getenv("CR012_PID_FILE"), []byte(strconv.Itoa(child.Process.Pid)), 0o600); err != nil {
177 _ = child.Process.Kill()
178 t.Fatal(err)
179 }
180 time.Sleep(8 * time.Second)
181 os.Exit(0)
182 }
183
184 // TestSetProcessGroupSetsSetpgid guards the CR-013 fix: the engine child
185 // must lead its own process group so a timeout kill reaches grandchildren
186 // (node bird-search, yt-dlp, grok CLI) instead of SIGKILLing only the
187 // direct python child while its atexit SIGTERM cleanup never runs.
188 func TestSetProcessGroupSetsSetpgid(t *testing.T) {
189 cmd := exec.Command("true")
190 setProcessGroup(cmd)
191 if cmd.SysProcAttr == nil {
192 t.Fatal("SysProcAttr is nil; want Setpgid process-group attribute")
193 }
194 if !cmd.SysProcAttr.Setpgid {
195 t.Fatal("SysProcAttr.Setpgid = false, want true")
196 }
197 }
198
199 // TestRunTimeoutKillsGrandchild exercises the group-kill path end to end:
200 // a stub interpreter spawns a background sleep grandchild, Run hits its
201 // deadline, and the grandchild must be dead afterwards. With the old
202 // exec.CommandContext behavior only the direct child died and the
203 // grandchild kept running.
204 func TestRunTimeoutKillsGrandchild(t *testing.T) {
205 dir := t.TempDir()
206 stub := filepath.Join(dir, "python3-group-stub.sh")
207 inGroupPid := filepath.Join(dir, "grandchild.pid")
208 setsidPid := filepath.Join(dir, "setsid-grandchild.pid")
209 script := `#!/usr/bin/env bash
210 # Grandchildren redirect their fds away from the stub's stdout/stderr:
211 # otherwise a surviving orphan holds Go's exec pipe open and cmd.Wait()
212 # blocks until the orphan exits, masking the leak as a slow pass.
213 sleep 30 >/dev/null 2>&1 &
214 echo -n "$!" > "` + inGroupPid + `"
215 # True shape of the engine's descendants: lib/subproc.py spawns every
216 # child with os.setsid, so node bird-search / yt-dlp / digg each lead
217 # their own pgid that kill(-enginepid) can never reach. Only the
218 # engine's SIGTERM handler (killpg per registered child) kills them —
219 # modeled here by the trap, mirroring last30days._on_sigterm.
220 setsid sleep 30 >/dev/null 2>&1 &
221 SIDPID=$!
222 echo -n "$SIDPID" > "` + setsidPid + `"
223 trap 'kill -TERM "$SIDPID" 2>/dev/null; exit 143' TERM
224 sleep 30
225 `
226 if err := os.WriteFile(stub, []byte(script), 0o755); err != nil {
227 t.Fatalf("write stub: %v", err)
228 }
229 cache := stageCache(t)
230
231 res, err := Run(context.Background(), RunOptions{
232 PythonPath: stub,
233 CacheDir: cache,
234 Timeout: 500 * time.Millisecond,
235 })
236 if err == nil {
237 t.Fatal("expected timeout error")
238 }
239 if !res.TimedOut {
240 t.Fatal("TimedOut = false, want true")
241 }
242
243 assertPidDead(t, inGroupPid, "in-group grandchild")
244 assertPidDead(t, setsidPid, "setsid grandchild")
245 }
246
247 // TestTermProcessGroupSendsSigterm checks the first phase of the deadline
248 // path directly: a process in its own group must exit promptly after
249 // termProcessGroup (no SIGKILL backstop involved).
250 func TestTermProcessGroupSendsSigterm(t *testing.T) {
251 cmd := exec.Command("sleep", "30")
252 setProcessGroup(cmd)
253 if err := cmd.Start(); err != nil {
254 t.Fatalf("start sleep: %v", err)
255 }
256 termProcessGroup(cmd)
257 done := make(chan error, 1)
258 go func() { done <- cmd.Wait() }()
259 select {
260 case <-done:
261 case <-time.After(5 * time.Second):
262 killProcessGroup(cmd)
263 <-done
264 t.Fatal("process survived SIGTERM group kill; SIGKILL backstop fired")
265 }
266 }
267
268 // assertPidDead reads a pid from pidFile and polls until no process with
269 // that pid exists. A SIGKILL-only deadline path leaves the setsid
270 // grandchild alive (its pgid differs), so this fails without the
271 // SIGTERM-first discipline.
272 func assertPidDead(t *testing.T, pidFile, what string) {
273 t.Helper()
274 raw, readErr := os.ReadFile(pidFile)
275 if readErr != nil {
276 t.Fatalf("%s pid file missing: %v", what, readErr)
277 }
278 pid, convErr := strconv.Atoi(strings.TrimSpace(string(raw)))
279 if convErr != nil || pid <= 0 {
280 t.Fatalf("bad %s pid %q: %v", what, raw, convErr)
281 }
282
283 // Signal delivery is async; poll for the process to disappear.
284 deadline := time.Now().Add(5 * time.Second)
285 for {
286 if kerr := syscall.Kill(pid, 0); kerr != nil {
287 if !errors.Is(kerr, syscall.ESRCH) {
288 t.Logf("kill(pid, 0) = %v; treating as dead", kerr)
289 }
290 return
291 }
292 if time.Now().After(deadline) {
293 // Best-effort cleanup so a regression does not leak sleeps.
294 _ = syscall.Kill(pid, syscall.SIGKILL)
295 t.Fatalf("%s pid %d still alive 5s after timeout; group kill failed", what, pid)
296 }
297 time.Sleep(20 * time.Millisecond)
298 }
299 }
300
301 type signalLifecycleRecorder struct {
302 mu sync.Mutex
303 events []string
304 reapStarted atomic.Bool
305 postReapSig atomic.Bool
306 }
307
308 func installLifecycleHooks(t *testing.T) *signalLifecycleRecorder {
309 t.Helper()
310 rec := &signalLifecycleRecorder{}
311 origSignal := signalProcessGroupFunc
312 origDirect := signalDirectChildFunc
313 origWait := waitCmdFunc
314 origNoReap := waitChildNoReapFunc
315 t.Cleanup(func() {
316 signalProcessGroupFunc = origSignal
317 signalDirectChildFunc = origDirect
318 waitCmdFunc = origWait
319 waitChildNoReapFunc = origNoReap
320 })
321 signalProcessGroupFunc = func(pid int, sig syscall.Signal) error {
322 if rec.reapStarted.Load() {
323 rec.postReapSig.Store(true)
324 }
325 rec.mu.Lock()
326 rec.events = append(rec.events, "signal:"+sig.String())
327 rec.mu.Unlock()
328 return origSignal(pid, sig)
329 }
330 signalDirectChildFunc = func(cmd *exec.Cmd, sig syscall.Signal) error {
331 rec.mu.Lock()
332 rec.events = append(rec.events, "direct:"+sig.String())
333 rec.mu.Unlock()
334 return origDirect(cmd, sig)
335 }
336 waitCmdFunc = func(cmd *exec.Cmd) error {
337 rec.reapStarted.Store(true)
338 rec.mu.Lock()
339 rec.events = append(rec.events, "wait:start")
340 rec.mu.Unlock()
341 err := origWait(cmd)
342 rec.mu.Lock()
343 rec.events = append(rec.events, "wait:done")
344 rec.mu.Unlock()
345 return err
346 }
347 return rec
348 }
349
350 func (r *signalLifecycleRecorder) snapshot() []string {
351 r.mu.Lock()
352 defer r.mu.Unlock()
353 return slices.Clone(r.events)
354 }
355
356 // TestWaitCommandNeverSignalsAfterReap verifies that on cancellation/timeout
357 // every process-group signal (SIGTERM and SIGKILL) executes strictly before
358 // cmd.Wait() reaps the child leader, eliminating post-reap PID-reuse races.
359 func TestWaitCommandNeverSignalsAfterReap(t *testing.T) {
360 t.Run("clean exit during grace delivers SIGKILL before reap", func(t *testing.T) {
361 rec := installLifecycleHooks(t)
362 dir := t.TempDir()
363 ready := filepath.Join(dir, "ready")
364 stub := filepath.Join(dir, "trap-exit.sh")
365 script := "#!/bin/sh\ntrap 'exit 0' TERM\n: > \"$READY_FILE\"\nwhile :; do sleep 1; done\n"
366 if err := os.WriteFile(stub, []byte(script), 0o755); err != nil {
367 t.Fatal(err)
368 }
369
370 cmd := exec.Command(stub)
371 cmd.Env = append(os.Environ(), "READY_FILE="+ready)
372 setProcessGroup(cmd)
373 if err := cmd.Start(); err != nil {
374 t.Fatal(err)
375 }
376 waitForFile(t, ready)
377
378 ctx, cancel := context.WithCancel(context.Background())
379 cancel()
380 if err := waitCommand(ctx, cmd, 2*time.Second); err != nil {
381 t.Fatalf("waitCommand: %v", err)
382 }
383 if rec.postReapSig.Load() {
384 t.Fatalf("delivered process-group signal after cmd.Wait() started: %v", rec.snapshot())
385 }
386 want := []string{
387 "signal:" + syscall.SIGTERM.String(),
388 "signal:" + syscall.SIGKILL.String(),
389 "wait:start",
390 "wait:done",
391 }
392 if got := rec.snapshot(); !slices.Equal(got, want) {
393 t.Fatalf("lifecycle events = %v, want %v", got, want)
394 }
395 })
396
397 t.Run("TERM-ignoring leader escalates to SIGKILL before reap", func(t *testing.T) {
398 rec := installLifecycleHooks(t)
399 dir := t.TempDir()
400 ready := filepath.Join(dir, "ready")
401 stub := filepath.Join(dir, "ignore-term.sh")
402 script := "#!/bin/sh\ntrap '' TERM\n: > \"$READY_FILE\"\nwhile :; do sleep 1; done\n"
403 if err := os.WriteFile(stub, []byte(script), 0o755); err != nil {
404 t.Fatal(err)
405 }
406
407 cmd := exec.Command(stub)
408 cmd.Env = append(os.Environ(), "READY_FILE="+ready)
409 setProcessGroup(cmd)
410 if err := cmd.Start(); err != nil {
411 t.Fatal(err)
412 }
413 waitForFile(t, ready)
414
415 ctx, cancel := context.WithCancel(context.Background())
416 cancel()
417 err := waitCommand(ctx, cmd, 100*time.Millisecond)
418 if err == nil {
419 t.Fatal("expected non-nil error for SIGKILLed child")
420 }
421 if rec.postReapSig.Load() {
422 t.Fatalf("delivered process-group signal after cmd.Wait() started: %v", rec.snapshot())
423 }
424 want := []string{
425 "signal:" + syscall.SIGTERM.String(),
426 "signal:" + syscall.SIGKILL.String(),
427 "wait:start",
428 "wait:done",
429 }
430 if got := rec.snapshot(); !slices.Equal(got, want) {
431 t.Fatalf("lifecycle events = %v, want %v", got, want)
432 }
433 })
434
435 t.Run("concurrent immediate exit and cancel never signals post-reap", func(t *testing.T) {
436 for i := range 25 {
437 rec := installLifecycleHooks(t)
438 cmd := exec.Command("/bin/sh", "-c", "exit 0")
439 setProcessGroup(cmd)
440 if err := cmd.Start(); err != nil {
441 t.Fatalf("iter %d start: %v", i, err)
442 }
443 ctx, cancel := context.WithCancel(context.Background())
444 cancel()
445 _ = waitCommand(ctx, cmd, 200*time.Millisecond)
446 if rec.postReapSig.Load() {
447 t.Fatalf("iter %d: delivered signal after reap: %v", i, rec.snapshot())
448 }
449 }
450 })
451
452 t.Run("fallback path uses direct child signals only and never numeric group signals", func(t *testing.T) {
453 rec := installLifecycleHooks(t)
454 waitChildNoReapFunc = func(int) error { return errWaitNoReapUnsupported }
455
456 dir := t.TempDir()
457 ready := filepath.Join(dir, "ready")
458 stub := filepath.Join(dir, "fallback-trap.sh")
459 script := "#!/bin/sh\ntrap 'exit 0' TERM\n: > \"$READY_FILE\"\nwhile :; do sleep 1; done\n"
460 if err := os.WriteFile(stub, []byte(script), 0o755); err != nil {
461 t.Fatal(err)
462 }
463
464 cmd := exec.Command(stub)
465 cmd.Env = append(os.Environ(), "READY_FILE="+ready)
466 setProcessGroup(cmd)
467 if err := cmd.Start(); err != nil {
468 t.Fatal(err)
469 }
470 waitForFile(t, ready)
471
472 ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
473 defer cancel()
474 if err := waitCommand(ctx, cmd, 2*time.Second); err != nil {
475 t.Fatalf("waitCommand fallback: %v", err)
476 }
477 if rec.postReapSig.Load() {
478 t.Fatalf("fallback delivered numeric group signal after wait started: %v", rec.snapshot())
479 }
480 events := rec.snapshot()
481 for _, ev := range events {
482 if strings.HasPrefix(ev, "signal:") {
483 t.Fatalf("fallback unexpectedly used numeric group signal %q: %v", ev, events)
484 }
485 }
486 if !slices.Contains(events, "direct:"+syscall.SIGTERM.String()) {
487 t.Fatalf("fallback did not send direct SIGTERM: %v", events)
488 }
489 if slices.Contains(events, "direct:"+syscall.SIGKILL.String()) {
490 t.Fatalf("fallback unexpectedly sent direct SIGKILL after clean exit: %v", events)
491 }
492 })
493
494 t.Run("non-ENOSYS waitChildNoReap error falls back to direct child signals and honors grace", func(t *testing.T) {
495 for _, mode := range []string{"outer-select", "inner-select-grace"} {
496 t.Run(mode, func(t *testing.T) {
497 rec := installLifecycleHooks(t)
498 gate := make(chan struct{})
499 if mode == "outer-select" {
500 close(gate)
501 }
502 waitChildNoReapFunc = func(int) error {
503 <-gate
504 return syscall.EPERM
505 }
506
507 dir := t.TempDir()
508 ready := filepath.Join(dir, "ready")
509 stub := filepath.Join(dir, "eperm-ignore-term.sh")
510 script := "#!/bin/sh\ntrap '' TERM\n: > \"$READY_FILE\"\nwhile :; do sleep 1; done\n"
511 if err := os.WriteFile(stub, []byte(script), 0o755); err != nil {
512 t.Fatal(err)
513 }
514
515 cmd := exec.Command(stub)
516 cmd.Env = append(os.Environ(), "READY_FILE="+ready)
517 setProcessGroup(cmd)
518 if err := cmd.Start(); err != nil {
519 t.Fatal(err)
520 }
521 waitForFile(t, ready)
522
523 const grace = 120 * time.Millisecond
524 var ctx context.Context
525 var cancel context.CancelFunc
526 if mode == "outer-select" {
527 ctx, cancel = context.WithTimeout(context.Background(), 50*time.Millisecond)
528 } else {
529 ctx, cancel = context.WithCancel(context.Background())
530 cancel()
531 go func() {
532 time.Sleep(15 * time.Millisecond)
533 close(gate)
534 }()
535 }
536 defer cancel()
537
538 started := time.Now()
539 err := waitCommand(ctx, cmd, grace)
540 elapsed := time.Since(started)
541 if err == nil {
542 t.Fatal("expected error when TERM-ignoring child is killed after grace")
543 }
544 if elapsed < grace {
545 t.Fatalf("waitCommand returned in %s, shorter than grace %s (skipped grace)", elapsed, grace)
546 }
547 if elapsed > 3*time.Second {
548 t.Fatalf("waitCommand took %s; dropped cancellation/timeout on EPERM", elapsed)
549 }
550 if rec.postReapSig.Load() {
551 t.Fatalf("EPERM fallback sent numeric group signal concurrently with cmd.Wait(): %v", rec.snapshot())
552 }
553 events := rec.snapshot()
554 if mode == "outer-select" {
555 for _, ev := range events {
556 if strings.HasPrefix(ev, "signal:") {
557 t.Fatalf("outer-select fallback used numeric group signal %q: %v", ev, events)
558 }
559 }
560 if !slices.Contains(events, "direct:"+syscall.SIGTERM.String()) || !slices.Contains(events, "direct:"+syscall.SIGKILL.String()) {
561 t.Fatalf("expected direct SIGTERM then direct SIGKILL, got %v", events)
562 }
563 } else {
564 if slices.Contains(events, "signal:"+syscall.SIGKILL.String()) {
565 t.Fatalf("inner-select fallback used numeric group SIGKILL while cmd.Wait() ran: %v", events)
566 }
567 if !slices.Contains(events, "signal:"+syscall.SIGTERM.String()) || !slices.Contains(events, "direct:"+syscall.SIGKILL.String()) {
568 t.Fatalf("expected pre-reap group SIGTERM then direct SIGKILL escalation, got %v", events)
569 }
570 }
571 })
572 }
573 })
574 }
575
576 func waitForFile(t *testing.T, path string) {
577 t.Helper()
578 deadline := time.Now().Add(3 * time.Second)
579 for time.Now().Before(deadline) {
580 if _, err := os.Stat(path); err == nil {
581 return
582 }
583 time.Sleep(10 * time.Millisecond)
584 }
585 t.Fatalf("timed out waiting for readiness file %s", path)
586 }
587
588 // TestRunCancelKillsSameGroupHelperAfterLeaderExits guards against the race
589 // where the leader exits early while a same-group helper still holds stdout or
590 // stderr open and ctx cancels during draining: the leader must stay unreaped so
591 // group signals kill the helper before cmd.Wait() reaps the leader.
592 func TestRunCancelKillsSameGroupHelperAfterLeaderExits(t *testing.T) {
593 for _, ignoreTerm := range []bool{false, true} {
594 name := "term-accepting-helper"
595 trapLine := ""
596 if ignoreTerm {
597 name = "term-ignoring-helper"
598 trapLine = "trap '' TERM; "
599 }
600 t.Run(name, func(t *testing.T) {
601 rec := installLifecycleHooks(t)
602 leaderExited := make(chan struct{})
603 var exitedOnce sync.Once
604 origNoReap := waitChildNoReapFunc
605 waitChildNoReapFunc = func(pid int) error {
606 err := origNoReap(pid)
607 exitedOnce.Do(func() { close(leaderExited) })
608 return err
609 }
610
611 dir := t.TempDir()
612 helperPidFile := filepath.Join(dir, "helper.pid")
613 helperReady := filepath.Join(dir, "helper.ready")
614 stub := filepath.Join(dir, "leader-exits-early.sh")
615 script := `#!/bin/sh
616 /bin/sh -c '` + trapLine + `printf "%s" "$$" > "$HELPER_PID"; printf "helper stdout\n"; printf "helper stderr\n" >&2; : > "$HELPER_READY"; while :; do sleep 1; done' &
617 printf 'leader output\n'
618 exit 0
619 `
620 if err := os.WriteFile(stub, []byte(script), 0o755); err != nil {
621 t.Fatal(err)
622 }
623 t.Cleanup(func() {
624 if raw, err := os.ReadFile(helperPidFile); err == nil {
625 if pid, err := strconv.Atoi(strings.TrimSpace(string(raw))); err == nil && pid > 0 {
626 _ = syscall.Kill(pid, syscall.SIGKILL)
627 }
628 }
629 })
630
631 ctx, cancel := context.WithCancel(context.Background())
632 defer cancel()
633
634 triggerErr := make(chan error, 1)
635 go func() {
636 // Wait until BOTH the helper has installed its trap / written
637 // to both pipes AND waitChildNoReap has observed the leader's
638 // exit, guaranteeing ctx cancels during output draining.
639 deadline := time.NewTimer(3 * time.Second)
640 defer deadline.Stop()
641 select {
642 case <-leaderExited:
643 case <-deadline.C:
644 triggerErr <- errors.New("leader did not exit before deadline")
645 cancel()
646 return
647 }
648 tick := time.NewTicker(10 * time.Millisecond)
649 defer tick.Stop()
650 for {
651 select {
652 case <-tick.C:
653 if _, err := os.Stat(helperReady); err == nil {
654 triggerErr <- nil
655 cancel()
656 return
657 }
658 case <-deadline.C:
659 triggerErr <- errors.New("helper did not become ready")
660 cancel()
661 return
662 }
663 }
664 }()
665
666 started := time.Now()
667 res, err := Run(ctx, RunOptions{
668 PythonPath: stub,
669 CacheDir: stageCache(t),
670 Timeout: 10 * time.Second,
671 ExtraEnv: []string{
672 "HELPER_PID=" + helperPidFile,
673 "HELPER_READY=" + helperReady,
674 },
675 })
676 if terr := <-triggerErr; terr != nil {
677 t.Fatal(terr)
678 }
679 if time.Since(started) > 5*time.Second {
680 t.Fatalf("Run took %s; helper cleanup exceeded bounded grace", time.Since(started))
681 }
682 if !errors.Is(err, context.Canceled) {
683 t.Fatalf("Run error = %v, want context.Canceled", err)
684 }
685 if rec.postReapSig.Load() {
686 t.Fatalf("delivered group signal after cmd.Wait() started: %v", rec.snapshot())
687 }
688 assertPidDead(t, helperPidFile, name)
689 if res == nil {
690 t.Fatal("Run result is nil")
691 }
692 if !strings.Contains(string(res.Stdout), "leader output") || !strings.Contains(string(res.Stdout), "helper stdout") {
693 t.Fatalf("stdout missing expected output: %q", res.Stdout)
694 }
695 if !strings.Contains(string(res.Stderr), "helper stderr") {
696 t.Fatalf("stderr missing helper output: %q", res.Stderr)
697 }
698 })
699 }
700 }
701
702 // TestWaitCommandPipeGraceKillsStraySameGroupHelperBeforeReap verifies that
703 // when a leader exits normally while a same-group helper holds pipes open past
704 // pipeGrace, the stray helper is killed strictly before cmd.Wait() reaps the
705 // leader and exec.ErrWaitDelay is returned.
706 func TestWaitCommandPipeGraceKillsStraySameGroupHelperBeforeReap(t *testing.T) {
707 rec := installLifecycleHooks(t)
708 dir := t.TempDir()
709 helperPidFile := filepath.Join(dir, "stray.pid")
710 helperReady := filepath.Join(dir, "stray.ready")
711 stub := filepath.Join(dir, "stray-helper.sh")
712 script := `#!/bin/sh
713 /bin/sh -c 'trap "" TERM; printf "%s" "$$" > "$HELPER_PID"; printf "stray stdout\n"; : > "$HELPER_READY"; while :; do sleep 1; done' &
714 exit 0
715 `
716 if err := os.WriteFile(stub, []byte(script), 0o755); err != nil {
717 t.Fatal(err)
718 }
719 t.Cleanup(func() {
720 if raw, err := os.ReadFile(helperPidFile); err == nil {
721 if pid, err := strconv.Atoi(strings.TrimSpace(string(raw))); err == nil && pid > 0 {
722 _ = syscall.Kill(pid, syscall.SIGKILL)
723 }
724 }
725 })
726
727 cmd := exec.Command(stub)
728 cmd.Env = append(os.Environ(), "HELPER_PID="+helperPidFile, "HELPER_READY="+helperReady)
729 setProcessGroup(cmd)
730 pipes, err := newOutputPipes()
731 if err != nil {
732 t.Fatal(err)
733 }
734 cmd.Stdout = pipes.stdoutW
735 cmd.Stderr = pipes.stderrW
736 if err := cmd.Start(); err != nil {
737 pipes.closeAll()
738 t.Fatal(err)
739 }
740 stdout := newHeadBuffer(DefaultMaxStdoutBytes)
741 stderr := newTailBuffer(DefaultMaxStderrBytes)
742 pipes.startDraining(stdout, stderr)
743 waitForFile(t, helperReady)
744
745 err = waitCommandWithDrain(context.Background(), cmd, 100*time.Millisecond, 100*time.Millisecond, pipes.drainDone, pipes.closeReadPipes)
746 if !errors.Is(err, exec.ErrWaitDelay) {
747 t.Fatalf("waitCommandWithDrain error = %v, want exec.ErrWaitDelay", err)
748 }
749 if rec.postReapSig.Load() {
750 t.Fatalf("delivered group signal after cmd.Wait() started: %v", rec.snapshot())
751 }
752 assertPidDead(t, helperPidFile, "stray TERM-ignoring helper")
753 if !strings.Contains(string(stdout.Bytes()), "stray stdout") {
754 t.Fatalf("stdout = %q, want stray stdout", stdout.Bytes())
755 }
756 }
757
758 // TestRunCleanExitDrainsShortLivedHelperWithoutSignaling checks that a normal
759 // exit where a helper briefly flushes output before closing pipes captures all
760 // bytes cleanly and reaps without sending any process-group signals.
761 func TestRunCleanExitDrainsShortLivedHelperWithoutSignaling(t *testing.T) {
762 rec := installLifecycleHooks(t)
763 dir := t.TempDir()
764 stub := filepath.Join(dir, "clean-helper.sh")
765 script := `#!/bin/sh
766 /bin/sh -c 'sleep 0.05; printf "from-helper\n"' &
767 printf 'from-leader\n'
768 exit 0
769 `
770 if err := os.WriteFile(stub, []byte(script), 0o755); err != nil {
771 t.Fatal(err)
772 }
773
774 res, err := Run(context.Background(), RunOptions{
775 PythonPath: stub,
776 CacheDir: stageCache(t),
777 Timeout: 5 * time.Second,
778 })
779 if err != nil {
780 t.Fatalf("Run: %v", err)
781 }
782 if res.ExitCode != 0 {
783 t.Fatalf("ExitCode = %d, want 0", res.ExitCode)
784 }
785 out := string(res.Stdout)
786 if !strings.Contains(out, "from-leader\n") || !strings.Contains(out, "from-helper\n") {
787 t.Fatalf("stdout = %q, want both leader and helper output", out)
788 }
789 for _, ev := range rec.snapshot() {
790 if strings.HasPrefix(ev, "signal:") {
791 t.Fatalf("clean exit unexpectedly sent process-group signal %q: %v", ev, rec.snapshot())
792 }
793 }
794 }
795
796 // TestRunLeaderTrapsTermAndTermIgnoringHelperKilledBeforeReap verifies that
797 // when ctx cancels while the leader is alive, the leader traps SIGTERM and
798 // exits cleanly, and a same-group helper ignores SIGTERM while holding pipes
799 // open, SIGKILL kills the helper strictly before cmd.Wait() reaps the leader.
800 func TestRunLeaderTrapsTermAndTermIgnoringHelperKilledBeforeReap(t *testing.T) {
801 rec := installLifecycleHooks(t)
802 dir := t.TempDir()
803 helperPidFile := filepath.Join(dir, "helper.pid")
804 readyFile := filepath.Join(dir, "ready")
805 stub := filepath.Join(dir, "leader-trap-helper-ignore.sh")
806 script := `#!/bin/sh
807 trap 'printf "leader-trapped\n" >&2; exit 0' TERM
808 /bin/sh -c 'trap "" TERM; printf "%s" "$$" > "$HELPER_PID"; printf "helper-alive\n"; : > "$READY_FILE"; while :; do sleep 1; done' &
809 while :; do sleep 1; done
810 `
811 if err := os.WriteFile(stub, []byte(script), 0o755); err != nil {
812 t.Fatal(err)
813 }
814 t.Cleanup(func() {
815 if raw, err := os.ReadFile(helperPidFile); err == nil {
816 if pid, err := strconv.Atoi(strings.TrimSpace(string(raw))); err == nil && pid > 0 {
817 _ = syscall.Kill(pid, syscall.SIGKILL)
818 }
819 }
820 })
821
822 ctx, cancel := context.WithCancel(context.Background())
823 defer cancel()
824 go func() {
825 deadline := time.Now().Add(3 * time.Second)
826 for time.Now().Before(deadline) {
827 if _, err := os.Stat(readyFile); err == nil {
828 cancel()
829 return
830 }
831 time.Sleep(10 * time.Millisecond)
832 }
833 cancel()
834 }()
835
836 res, err := Run(ctx, RunOptions{
837 PythonPath: stub,
838 CacheDir: stageCache(t),
839 Timeout: 10 * time.Second,
840 ExtraEnv: []string{
841 "HELPER_PID=" + helperPidFile,
842 "READY_FILE=" + readyFile,
843 },
844 })
845 if !errors.Is(err, context.Canceled) {
846 t.Fatalf("Run error = %v, want context.Canceled", err)
847 }
848 if rec.postReapSig.Load() {
849 t.Fatalf("delivered group signal after cmd.Wait() started: %v", rec.snapshot())
850 }
851 assertPidDead(t, helperPidFile, "TERM-ignoring same-group helper")
852 if res == nil || !strings.Contains(string(res.Stdout), "helper-alive") || !strings.Contains(string(res.Stderr), "leader-trapped") {
853 t.Fatalf("unexpected output: %+v", res)
854 }
855 }
856
856 lines GO