Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent): drain Pi stderr before normal cleanup (#11070)
Frezcf4b51caddf54
diff --git a/server/pkg/agent/pi.go b/server/pkg/agent/pi.goindex 7d9f4f8ca2..19df469d33 100644--- a/server/pkg/agent/pi.go+++ b/server/pkg/agent/pi.go@@ -54,6 +54,8 @@ var (// precedent while remaining far below the daemon's two-hour fallback.const defaultPiTurnErrorGrace = 10 * time.Minute+const piExitPipeDrainGrace = 250 * time.Millisecond+// piTurnErrorGuard owns the only timer associated with a pending Pi turn// error. The stream goroutine records protocol activity; the timer callback// invokes the execution's bounded stop path after re-checking the state. It@@ -585,7 +587,7 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions// buffered protocol events to drain before ending that read. In-flight// tool accounting below decides whether termination is required.if pipe, ok := stdout.(interface{ SetReadDeadline(time.Time) error }); ok {- _ = pipe.SetReadDeadline(time.Now().Add(250 * time.Millisecond))+ _ = pipe.SetReadDeadline(time.Now().Add(piExitPipeDrainGrace))}select {case <-processCtx.Done():@@ -801,11 +803,22 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions// Do not reap the root before the cancellation owner releases its numeric// process group: an unreaped root prevents PGID reuse during cleanup.- if scanErr == nil && cleanup.tools.Load() == 0 && processCtx.Err() == nil && piCanObserveRuntimeExit && !piRuntimeExited(cmd) {+ if scanErr == nil && cleanup.tools.Load() == 0 && processCtx.Err() == nil {+ if piCanObserveRuntimeExit && !piRuntimeExited(cmd) {+ select {+ case <-cleanup.exited:+ case <-processCtx.Done():+ }+ }+ // Read any final stderr (including a resume refusal) before complete+ // closes the pipe. A descendant may still hold the write end.+ drain := time.NewTimer(piExitPipeDrainGrace)select {- case <-cleanup.exited:+ case <-stderrDone:case <-processCtx.Done():+ case <-drain.C:}+ drain.Stop()}var cleanupErr errorif scanErr != nil || cleanup.tools.Load() > 0 || processCtx.Err() != nil {diff --git a/server/pkg/agent/pi_resume_refused_unix_test.go b/server/pkg/agent/pi_resume_refused_unix_test.goindex 92020d02cd..e07fb02e6f 100644--- a/server/pkg/agent/pi_resume_refused_unix_test.go+++ b/server/pkg/agent/pi_resume_refused_unix_test.go@@ -8,6 +8,8 @@ import ("log/slog""os""path/filepath"+ "strconv"+ "strings""testing""time")@@ -85,6 +87,48 @@ func TestPiExecuteReportsRefusedResume(t *testing.T) {}}+func TestPiExecuteDrainsRefusalWithInheritedStderr(t *testing.T) {+ t.Parallel()+ base := t.TempDir()+ sessionPath := filepath.Join(base, "session.jsonl")+ if err := os.WriteFile(sessionPath, []byte(`{"type":"session","cwd":"/gone"}`+"\n"), 0o644); err != nil {+ t.Fatalf("create session: %v", err)+ }+ pidFile := filepath.Join(base, "stderr-holder.pid")+ t.Cleanup(func() {+ data, err := os.ReadFile(pidFile)+ if err != nil {+ return+ }+ pid, err := strconv.Atoi(strings.TrimSpace(string(data)))+ if err == nil && pid > 1 {+ if process, err := os.FindProcess(pid); err == nil {+ _ = process.Kill()+ }+ }+ })+ fakePath := filepath.Join(base, "pi")+ writeTestExecutable(t, fakePath, []byte(fmt.Sprintf(`#!/bin/sh+cat >/dev/null+sleep 30 >/dev/null &+printf '%%s\n' "$!" > %q+printf '%%s\n' %q >&2+exit 1+`, pidFile, piResumeRefusedMarker+": /gone")))+ backend, err := New("pi", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new pi backend: %v", err)+ }+ session, err := backend.Execute(t.Context(), "hello", ExecOptions{ResumeSessionID: sessionPath, Cwd: base, Timeout: 10 * time.Second})+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ result := waitPiResult(t, session, 3*time.Second)+ if result.Status != "failed" || !result.ResumeRejected || result.ResumeRejectedTransient {+ t.Fatalf("result = %+v, want permanent resume refusal", result)+ }+}+// TestPiStderrWatcherSpansWrites guards the one way the marker could be missed:// stderr arriving in fragments. A substring test over a single Write would pass// the test above and still fail in production on a split flush.