diff --git a/internal/server/run_reattach_test.go b/internal/server/run_reattach_test.go index 047170ca..1f330347 100644 --- a/internal/server/run_reattach_test.go +++ b/internal/server/run_reattach_test.go @@ -194,6 +194,40 @@ func TestStageRunWithHarnessGoneFallsBackWithReason(t *testing.T) { } } +// TestUninterruptibleStageSessionInterruptsOnlyItsRun: one stage session that +// start-up cannot confirm stopped (a crashed Pi owner, a missing Claude +// evidence directory) used to fail the whole runner, disabling every run. +// Now only its run is interrupted, naming why, and the runner starts. +func TestUninterruptibleStageSessionInterruptsOnlyItsRun(t *testing.T) { + seamRestartRecovery(t, nil) + interruptRecoveredSession = func(context.Context, pipeline.SessionOwner) error { + return fmt.Errorf("retained Pi owner: %w", stage.ErrStageCleanup) + } + f := stopMidStage(t, func(ctx context.Context, s *pipeline.Store, id int64) (stage.Result, error) { + if err := s.RunSession(context.Background(), id, 1, "ses_pi", true, "pi", "/nonexistent/pi-ref"); err != nil { + return stage.Result{}, err + } + <-ctx.Done() + return stage.Result{}, stage.ErrDetached + }) + r, s := f.restart(t, func(context.Context, *pipeline.Store, stage.Definition) (stage.Result, error) { + t.Error("an interrupted run executed again") + return stage.Result{}, nil + }) + r.reattachRuns() + r.wg.Wait() + d, err := s.GetRun(context.Background(), f.runID) + if err != nil { + t.Fatal(err) + } + if d.Status != "interrupted" || !strings.Contains(d.Diagnostic, "could not be confirmed stopped") || !strings.Contains(d.Diagnostic, "ses_pi") { + t.Fatalf("uninterruptible session's run lacks a clear reason: status=%s run=%q", d.Status, d.Diagnostic) + } + if owners, _ := s.ActiveSessionOwners(context.Background()); len(owners) != 0 { + t.Fatalf("the interrupted run's session still blocks recovery at the next start: %+v", owners) + } +} + // TestStageNotYetAdmittedStartsAgainAfterRestart: a visit the stopped server // had begun but not handed to any session is started again, nothing replayed. func TestStageNotYetAdmittedStartsAgainAfterRestart(t *testing.T) { diff --git a/internal/server/runner.go b/internal/server/runner.go index 6ea8e8e1..914560c8 100644 --- a/internal/server/runner.go +++ b/internal/server/runner.go @@ -152,7 +152,15 @@ func newRunnerReattaching(ctx context.Context, s *pipeline.Store, artifactsRoot cancel() } if err != nil { - return nil, fmt.Errorf("cannot interrupt previously active agent %s: %w", owner.ID, err) + // One session that cannot be confirmed stopped must not disable + // every run: interrupt only its run, saying why, and go on. + reason := fmt.Sprintf("its previous %s stage agent (session %s) could not be confirmed stopped (%v); check for a leftover agent process before reusing the workspace", owner.Backend, owner.ID, err) + if prior := reasons[owner.RunID]; prior != "" { + reason = prior + "; " + reason + } + reasons[owner.RunID] = reason + log.Printf("run %d: cannot interrupt previously active agent %s: %v; the run is marked interrupted", owner.RunID, owner.ID, err) + continue } if err := s.ConfirmRecoveredSession(ctx, owner); err != nil { return nil, err diff --git a/internal/stage/pi.go b/internal/stage/pi.go index 7f05b3e8..4adc94dd 100644 --- a/internal/stage/pi.go +++ b/internal/stage/pi.go @@ -608,7 +608,9 @@ func piResult(data []byte) (string, error) { } // InterruptPi expires the retained lease. The explicit extension aborts tools and -// marks quiescence before shutting down; without that receipt recovery fails closed. +// marks quiescence before shutting down. An owner whose process and process +// group are both gone (a crash, a reboot) has nothing left to stop, so it +// counts as interrupted without that receipt; otherwise recovery fails closed. func InterruptPi(ctx context.Context, reference string) error { if !filepath.IsAbs(reference) { return fmt.Errorf("invalid retained Pi reference") @@ -623,6 +625,12 @@ func InterruptPi(ctx context.Context, reference string) error { if json.Unmarshal(data, &owner) != nil || owner.PID <= 1 { return errors.Join(fmt.Errorf("invalid retained Pi owner"), ErrStageCleanup) } + gone := func() bool { + return errors.Is(syscall.Kill(owner.PID, 0), syscall.ESRCH) && errors.Is(syscall.Kill(-owner.PID, 0), syscall.ESRCH) + } + if gone() { + return nil + } old := time.Unix(0, 0) if err := os.Chtimes(filepath.Join(reference, "lease"), old, old); err != nil { return err @@ -630,7 +638,9 @@ func InterruptPi(ctx context.Context, reference string) error { ticker := time.NewTicker(100 * time.Millisecond) defer ticker.Stop() for { - if data, err := os.ReadFile(filepath.Join(reference, "quiescent")); err == nil && string(data) == "quiescent" && errors.Is(syscall.Kill(owner.PID, 0), syscall.ESRCH) && errors.Is(syscall.Kill(-owner.PID, 0), syscall.ESRCH) { + // The receipt is written just before a clean exit; a process that + // died without it is still gone. + if gone() { return nil } select { diff --git a/internal/stage/pi_cleanup_test.go b/internal/stage/pi_cleanup_test.go index 9f22cc59..e9ec181d 100644 --- a/internal/stage/pi_cleanup_test.go +++ b/internal/stage/pi_cleanup_test.go @@ -42,3 +42,31 @@ func TestPiReceiptRequiresProcessExit(t *testing.T) { t.Fatal("confirmed process exit not accepted", err) } } + +// A Pi owner that crashed never wrote its quiescence receipt; with its process +// and process group gone there is nothing left to stop, so recovery must not +// wait out its timeout and fail. +func TestPiOwnerGoneWithoutReceiptCountsAsInterrupted(t *testing.T) { + cmd := exec.Command("sleep", "5") + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + pid := cmd.Process.Pid + if err := cmd.Process.Kill(); err != nil { + t.Fatal(err) + } + cmd.Wait() + dir := t.TempDir() + owner, _ := json.Marshal(map[string]any{"pid": pid}) + for name, data := range map[string][]byte{"owner.json": owner, "lease": []byte("lease")} { + if err := os.WriteFile(filepath.Join(dir, name), data, 0600); err != nil { + t.Fatal(err) + } + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + if err := InterruptPi(ctx, dir); err != nil { + t.Fatal("a crashed owner was not accepted as gone:", err) + } +}