Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-7467 fix(agent): fail silent Pi provider errors (#8535)

Multica Eve7f8e4980abfd
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 42ed5e91d5..c9a93ed724 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -9604,6 +9604,48 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
}
}
}
+ // awaitTerminalResult gives a backend that advertises an authoritative
+ // terminal boundary one bounded chance to hand over its result after a
+ // cancellation won the outer select. Result delivery is the linearization
+ // point: TerminalObserved must be published before that send, so checking it
+ // afterwards preserves a provider outcome without racing a flag read. A
+ // delivered non-authoritative result is still returned to the idle-watchdog
+ // caller for re-tagging; ordinary upstream cancellation deliberately ignores
+ // it and keeps the existing generic cancelled disposition.
+ awaitTerminalResult := func(trigger string) (result agent.Result, delivered, authoritative bool) {
+ if !handsOverTerminal {
+ return agent.Result{}, false, false
+ }
+ if trigger == "idle_watchdog" {
+ // Keep this event stable: besides operator diagnostics, the terminal
+ // race regression uses it as the hand-off linearization probe.
+ taskLog.Info("idle watchdog fired; waiting for the backend to hand over its result",
+ "budget", terminalResultHandoffBudget.String())
+ } else {
+ taskLog.Info("waiting for the backend to hand over its result after cancellation",
+ "trigger", trigger,
+ "budget", terminalResultHandoffBudget.String())
+ }
+ timer := time.NewTimer(terminalResultHandoffBudget)
+ defer timer.Stop()
+ select {
+ case result, ok := <-session.Result:
+ if !ok {
+ return agent.Result{}, false, false
+ }
+ return result, true, terminalObserved()
+ case <-timer.C:
+ if trigger == "idle_watchdog" {
+ taskLog.Warn("backend did not hand over a result within the budget; classifying by liveness",
+ "budget", terminalResultHandoffBudget.String())
+ } else {
+ taskLog.Warn("backend did not hand over a result within the budget; classifying by cancellation trigger",
+ "trigger", trigger,
+ "budget", terminalResultHandoffBudget.String())
+ }
+ return agent.Result{}, false, false
+ }
+ }
select {
case result := <-session.Result:
@@ -9647,38 +9689,20 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
// Such a backend always closes Result, so a wedged one still ends
// this wait promptly through the closed channel rather than the
// budget.
- if handsOverTerminal {
- taskLog.Info("idle watchdog fired; waiting for the backend to hand over its result",
- "budget", terminalResultHandoffBudget.String())
- select {
- case result, ok := <-session.Result:
- if ok && terminalObserved() {
- // The backend had already read its authoritative
- // result, so this is the real outcome, not a hang.
- return result, toolCount.Load(), nil
- }
- if ok {
- // The backend's wait goroutine (e.g. claude.go)
- // translates the SIGKILL we delivered via agentCancel
- // into Status="aborted". Re-tag it as "idle_watchdog"
- // so runTask routes the disposition through a dedicated
- // failure_reason, not the generic "agent_error" bucket
- // the aborted path falls into.
- result.Status = "idle_watchdog"
- if result.Error == "" {
- result.Error = idleWatchdogReason(time.Duration(idleWatchdogThreshold.Load()))
- }
- return result, toolCount.Load(), nil
- }
- // Closed with no value: the backend gave up without an
- // outcome, so the liveness verdict is the only one left.
- case <-time.After(terminalResultHandoffBudget):
- // A backend that neither delivers nor closes is itself the
- // hang. Linearizing here keeps the branch bounded whatever
- // a backend does.
- taskLog.Warn("backend did not hand over a result within the budget; classifying by liveness",
- "budget", terminalResultHandoffBudget.String())
+ if result, delivered, authoritative := awaitTerminalResult("idle_watchdog"); authoritative {
+ // The backend had already read its authoritative result, so
+ // this is the real outcome, not a hang.
+ return result, toolCount.Load(), nil
+ } else if delivered {
+ // The backend's wait goroutine (e.g. claude.go) translates the
+ // SIGKILL we delivered via agentCancel into Status="aborted".
+ // Re-tag it so runTask routes the disposition through the
+ // dedicated liveness failure_reason.
+ result.Status = "idle_watchdog"
+ if result.Error == "" {
+ result.Error = idleWatchdogReason(time.Duration(idleWatchdogThreshold.Load()))
}
+ return result, toolCount.Load(), nil
}
return agent.Result{
Status: "idle_watchdog",
@@ -9691,6 +9715,9 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
// upstream runCtx fired runCancel(); context.DeadlineExceeded is the
// drain deadline expiring on its own.
if errors.Is(drainCtx.Err(), context.Canceled) {
+ if result, _, authoritative := awaitTerminalResult("upstream_context"); authoritative {
+ return result, toolCount.Load(), nil
+ }
return agent.Result{
Status: "cancelled",
Error: "task cancelled by upstream context (server cancel or daemon shutdown)",
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index 894a7a1607..faa6a03e0e 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -3862,6 +3862,283 @@ func TestExecuteAndDrain_IdleWatchdog_FiresOnInactivity(t *testing.T) {
}
}
+// waitForAgentMessageBackend holds Execute until the wrapped backend has
+// processed a selected protocol message, then hands the full stream to the
+// daemon. It makes watchdog cancellation tests deterministic without changing
+// the production watchdog window or relying on child-process scheduling speed.
+type waitForAgentMessageBackend struct {
+ agent.Backend
+ match func(agent.Message) bool
+ onMatch func()
+}
+
+func (b waitForAgentMessageBackend) Execute(ctx context.Context, prompt string, opts agent.ExecOptions) (*agent.Session, error) {
+ session, err := b.Backend.Execute(ctx, prompt, opts)
+ if err != nil {
+ return nil, err
+ }
+ messages := make(chan agent.Message, 256)
+ for {
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case msg, ok := <-session.Messages:
+ if !ok {
+ return nil, errors.New("wrapped backend closed before the expected message")
+ }
+ messages <- msg
+ if !b.match(msg) {
+ continue
+ }
+ if b.onMatch != nil {
+ b.onMatch()
+ }
+ go func() {
+ defer close(messages)
+ for msg := range session.Messages {
+ messages <- msg
+ }
+ }()
+ return &agent.Session{
+ ToolActivity: session.ToolActivity,
+ InterruptBackgroundTools: session.InterruptBackgroundTools,
+ TerminalObserved: session.TerminalObserved,
+ Messages: messages,
+ Result: session.Result,
+ }, nil
+ }
+ }
+}
+
+func TestExecuteAndDrain_PiTurnErrorOutranksIdleWatchdogCancellation(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ const providerError = "OpenAI API error (413): Failed to buffer the request body: length limit exceeded"
+ fakePath := filepath.Join(t.TempDir(), "pi")
+ script := "#!/bin/sh\n" +
+ "cat > /dev/null\n" +
+ `printf '%s\n' '{"type":"agent_start"}'` + "\n" +
+ `printf '%s\n' '{"type":"turn_start"}'` + "\n" +
+ `printf '%s\n' '{"type":"turn_end","message":{"role":"assistant","model":"test","stopReason":"error","errorMessage":"` + providerError + `"}}'` + "\n" +
+ `printf '%s\n' '{"type":"message_update","assistantMessageEvent":{"type":"thinking_delta","delta":"post-error activity"}}'` + "\n" +
+ `printf '%s\n' '{"type":"agent_end","messages":[],"willRetry":false}'` + "\n" +
+ "exec sleep 300\n"
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ backend, err := agent.New("pi", agent.Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new pi backend: %v", err)
+ }
+ backend = waitForAgentMessageBackend{
+ Backend: backend,
+ match: func(msg agent.Message) bool {
+ return msg.Type == agent.MessageThinking && msg.Content == "post-error activity"
+ },
+ }
+ d := newTestDaemon(t)
+ d.cfg.AgentIdleWatchdog = 50 * time.Millisecond
+
+ result, _, err := d.executeAndDrain(
+ context.Background(),
+ backend,
+ "prompt-ignored",
+ agent.ExecOptions{ResumeSessionID: filepath.Join(t.TempDir(), "session.jsonl")},
+ slog.Default(),
+ "t-pi-provider-error",
+ "",
+ new(atomic.Int32),
+ )
+ if err != nil {
+ t.Fatalf("executeAndDrain: %v", err)
+ }
+ if result.Status != "failed" {
+ t.Fatalf("status = %q, want provider failure rather than idle_watchdog (error=%q)", result.Status, result.Error)
+ }
+ if result.Error != providerError {
+ t.Fatalf("error = %q, want original provider error %q", result.Error, providerError)
+ }
+}
+
+func TestExecuteAndDrain_PiWithoutTurnErrorKeepsIdleWatchdogResult(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ fakePath := filepath.Join(t.TempDir(), "pi")
+ script := "#!/bin/sh\n" +
+ "cat > /dev/null\n" +
+ `printf '%s\n' '{"type":"agent_start"}'` + "\n" +
+ "exec sleep 300\n"
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ backend, err := agent.New("pi", agent.Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new pi backend: %v", err)
+ }
+ d := newTestDaemon(t)
+ d.cfg.AgentIdleWatchdog = 200 * time.Millisecond
+
+ result, _, err := d.executeAndDrain(
+ context.Background(),
+ backend,
+ "prompt-ignored",
+ agent.ExecOptions{ResumeSessionID: filepath.Join(t.TempDir(), "session.jsonl")},
+ slog.Default(),
+ "t-pi-no-provider-error",
+ "",
+ new(atomic.Int32),
+ )
+ if err != nil {
+ t.Fatalf("executeAndDrain: %v", err)
+ }
+ if result.Status != "idle_watchdog" {
+ t.Fatalf("result = %+v, want the existing idle_watchdog disposition", result)
+ }
+ if result.Error != "execution cancelled" {
+ t.Fatalf("error = %q, want the existing no-provider-error cancellation text", result.Error)
+ }
+}
+
+func TestExecuteAndDrain_PiTurnErrorOutranksUpstreamCancellation(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ const providerError = "OpenAI API error (413): Failed to buffer the request body: length limit exceeded"
+ fakePath := filepath.Join(t.TempDir(), "pi")
+ script := "#!/bin/sh\n" +
+ "cat > /dev/null\n" +
+ `printf '%s\n' '{"type":"agent_start"}'` + "\n" +
+ `printf '%s\n' '{"type":"turn_start"}'` + "\n" +
+ `printf '%s\n' '{"type":"turn_end","message":{"role":"assistant","model":"test","stopReason":"error","errorMessage":"` + providerError + `"}}'` + "\n" +
+ `printf '%s\n' '{"type":"message_update","assistantMessageEvent":{"type":"thinking_delta","delta":"cancel now"}}'` + "\n" +
+ "exec sleep 300\n"
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ backend, err := agent.New("pi", agent.Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new pi backend: %v", err)
+ }
+ matched := make(chan struct{})
+ backend = waitForAgentMessageBackend{
+ Backend: backend,
+ match: func(msg agent.Message) bool {
+ return msg.Type == agent.MessageThinking && msg.Content == "cancel now"
+ },
+ onMatch: func() { close(matched) },
+ }
+ d := newTestDaemon(t)
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ sessionPath := filepath.Join(t.TempDir(), "session.jsonl")
+
+ type outcome struct {
+ result agent.Result
+ err error
+ }
+ done := make(chan outcome, 1)
+ go func() {
+ result, _, err := d.executeAndDrain(
+ ctx,
+ backend,
+ "prompt-ignored",
+ agent.ExecOptions{ResumeSessionID: sessionPath},
+ slog.Default(),
+ "t-pi-provider-error-upstream-cancel",
+ "",
+ new(atomic.Int32),
+ )
+ done <- outcome{result: result, err: err}
+ }()
+
+ select {
+ case <-matched:
+ cancel()
+ case <-time.After(5 * time.Second):
+ t.Fatal("Pi never emitted the post-error activity")
+ }
+
+ select {
+ case got := <-done:
+ if got.err != nil {
+ t.Fatalf("executeAndDrain: %v", got.err)
+ }
+ if got.result.Status != "failed" || got.result.Error != providerError {
+ t.Fatalf("result = %+v, want original provider failure", got.result)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("executeAndDrain did not return after upstream cancellation")
+ }
+}
+
+func TestExecuteAndDrain_PiWithoutTurnErrorKeepsUpstreamCancellation(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ fakePath := filepath.Join(t.TempDir(), "pi")
+ script := "#!/bin/sh\n" +
+ "cat > /dev/null\n" +
+ `printf '%s\n' '{"type":"agent_start"}'` + "\n" +
+ "exec sleep 300\n"
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ backend, err := agent.New("pi", agent.Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new pi backend: %v", err)
+ }
+ matched := make(chan struct{})
+ backend = waitForAgentMessageBackend{
+ Backend: backend,
+ match: func(msg agent.Message) bool { return msg.Type == agent.MessageStatus },
+ onMatch: func() { close(matched) },
+ }
+ d := newTestDaemon(t)
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ sessionPath := filepath.Join(t.TempDir(), "session.jsonl")
+
+ type outcome struct {
+ result agent.Result
+ err error
+ }
+ done := make(chan outcome, 1)
+ go func() {
+ result, _, err := d.executeAndDrain(
+ ctx,
+ backend,
+ "prompt-ignored",
+ agent.ExecOptions{ResumeSessionID: sessionPath},
+ slog.Default(),
+ "t-pi-no-provider-error-upstream-cancel",
+ "",
+ new(atomic.Int32),
+ )
+ done <- outcome{result: result, err: err}
+ }()
+
+ select {
+ case <-matched:
+ cancel()
+ case <-time.After(5 * time.Second):
+ t.Fatal("Pi never started")
+ }
+
+ select {
+ case got := <-done:
+ if got.err != nil {
+ t.Fatalf("executeAndDrain: %v", got.err)
+ }
+ if got.result.Status != "cancelled" || !strings.Contains(got.result.Error, "task cancelled by upstream context") {
+ t.Fatalf("result = %+v, want existing upstream cancellation", got.result)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("executeAndDrain did not return after upstream cancellation")
+ }
+}
+
func TestExecuteAndDrain_IdleWatchdog_FiresWhenNoMessageEverArrives(t *testing.T) {
t.Parallel()
diff --git a/server/pkg/agent/pi.go b/server/pkg/agent/pi.go
index 716970519a..155a6324dc 100644
--- a/server/pkg/agent/pi.go
+++ b/server/pkg/agent/pi.go
@@ -33,12 +33,172 @@ type piBackend struct {
// strings ("pi" or "omp"). Defaults to "pi" when empty so existing callers
// that construct piBackend directly (tests) keep their original output.
providerLabel string
+ // turnErrorGrace overrides the silence window after a turn-level provider
+ // error. Production uses defaultPiTurnErrorGrace; tests shorten it without
+ // changing concurrent executions through package-global state.
+ turnErrorGrace time.Duration
}
var (
piControlTokenRE = regexp.MustCompile(`<\|[A-Za-z0-9_-]+>[A-Za-z0-9_-]*|<[A-Za-z0-9_-]+\|>`)
)
+// defaultPiTurnErrorGrace is the recovery window Pi gets after reporting a
+// provider error without exiting. Pi reports the same turn_end stopReason
+// before automatic retries, so the error cannot be treated as terminal at
+// once. Ten minutes matches the existing provider-specific semantic-idle
+// precedent while remaining far below the daemon's two-hour fallback.
+const defaultPiTurnErrorGrace = 10 * time.Minute
+
+// 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
+// never emits a Message, so observing the provider error cannot refresh the
+// daemon's independent lastActivityAt watchdog clock.
+type piTurnErrorGuard struct {
+ mu sync.Mutex
+ grace time.Duration
+ expireRun func()
+ timer *time.Timer
+ generation uint64
+ lastError string
+ inFlightTools int
+ graceExpired bool
+ terminal bool
+ stopped bool
+}
+
+func newPiTurnErrorGuard(grace time.Duration, expireRun func()) *piTurnErrorGuard {
+ return &piTurnErrorGuard{grace: grace, expireRun: expireRun}
+}
+
+// closePiReadPipe interrupts a scanner/copy blocked in Read before releasing
+// the adapter's descriptor. The deadline matters on Unix, where Close from a
+// different goroutine need not interrupt a syscall already in the kernel.
+func closePiReadPipe(pipe io.ReadCloser) {
+ if deadlinePipe, ok := pipe.(interface{ SetReadDeadline(time.Time) error }); ok {
+ _ = deadlinePipe.SetReadDeadline(time.Now())
+ }
+ _ = pipe.Close()
+}
+
+// observeEvent records a parseable Pi protocol event. Recovery events clear a
+// stale provider error; every other event gives an unresolved error a fresh
+// grace window. Tool accounting is kept inside the adapter so an error timer
+// can never terminate a tool that is still in flight.
+func (g *piTurnErrorGuard) observeEvent(eventType string) {
+ if eventType == "" {
+ return
+ }
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ if g.stopped {
+ return
+ }
+
+ switch eventType {
+ case "turn_start", "auto_retry_start":
+ g.clearErrorLocked()
+ return
+ case "tool_execution_start":
+ g.inFlightTools++
+ case "tool_execution_end":
+ if g.inFlightTools > 0 {
+ g.inFlightTools--
+ }
+ }
+ g.rearmLocked()
+}
+
+func (g *piTurnErrorGuard) record(errText string) {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ if g.stopped {
+ return
+ }
+ g.lastError = errText
+ g.rearmLocked()
+}
+
+func (g *piTurnErrorGuard) clear() {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ if g.stopped {
+ return
+ }
+ g.clearErrorLocked()
+}
+
+func (g *piTurnErrorGuard) clearErrorLocked() {
+ g.lastError = ""
+ g.generation++
+ if g.timer != nil {
+ g.timer.Stop()
+ g.timer = nil
+ }
+}
+
+func (g *piTurnErrorGuard) rearmLocked() {
+ if g.lastError == "" || g.stopped {
+ return
+ }
+ g.generation++
+ generation := g.generation
+ if g.timer != nil {
+ g.timer.Stop()
+ }
+ g.timer = time.AfterFunc(g.grace, func() {
+ g.expire(generation)
+ })
+}
+
+func (g *piTurnErrorGuard) expire(generation uint64) {
+ g.mu.Lock()
+ if g.stopped || generation != g.generation || g.lastError == "" {
+ g.mu.Unlock()
+ return
+ }
+ g.timer = nil
+ if g.inFlightTools > 0 {
+ g.mu.Unlock()
+ return
+ }
+ g.graceExpired = true
+ g.stopped = true
+ expireRun := g.expireRun
+ g.mu.Unlock()
+
+ // The callback owns both process-tree cancellation and the adapter's local
+ // pipes. terminal remains false until the result goroutine has escaped its
+ // scanner/Wait path and can publish a Result, so a liveness watcher can never
+ // mistake "we decided to stop" for "finalization is guaranteed to finish".
+ expireRun()
+}
+
+func (g *piTurnErrorGuard) finish() (lastError string, graceExpired bool) {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ g.stopped = true
+ g.generation++
+ if g.timer != nil {
+ g.timer.Stop()
+ g.timer = nil
+ }
+ return g.lastError, g.graceExpired
+}
+
+func (g *piTurnErrorGuard) markTerminal() {
+ g.mu.Lock()
+ g.terminal = true
+ g.mu.Unlock()
+}
+
+func (g *piTurnErrorGuard) terminalObserved() bool {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ return g.terminal
+}
+
func stripPiToolCallMarkup(s string) string {
s = stripPiStructuredToolMarkup(s)
return piControlTokenRE.ReplaceAllString(s, "")
@@ -239,9 +399,10 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
}
runCtx, cancel := runContext(ctx, timeout)
+ processCtx, cancelProcess := context.WithCancel(runCtx)
args := buildPiArgs(sessionPath, opts, b.cfg.Logger)
- cmd, _, _ := b.cfg.commandAt(execName).execVia(runCtx, choosePiInvocation, lookedUp, args, b.cfg.Logger)
+ cmd, _, _ := b.cfg.commandAt(execName).execVia(processCtx, choosePiInvocation, lookedUp, args, b.cfg.Logger)
hideAgentWindow(cmd)
b.cfg.logAgentCommand(cmd, newAgentCommandLogArgs(args))
cmd.WaitDelay = 10 * time.Second
@@ -253,6 +414,7 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
stdout, err := cmd.StdoutPipe()
if err != nil {
releasePiSessionFileLock(sessionLock)
+ cancelProcess()
cancel()
return nil, fmt.Errorf("%s stdout pipe: %w", label, err)
}
@@ -263,7 +425,9 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
// Pi has been observed to wait indefinitely when stdin never reaches EOF.
stdin, err := cmd.StdinPipe()
if err != nil {
+ closePiReadPipe(stdout)
releasePiSessionFileLock(sessionLock)
+ cancelProcess()
cancel()
return nil, fmt.Errorf("%s stdin pipe: %w", label, err)
}
@@ -271,21 +435,55 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
closeStdin := func() { closeStdinOnce.Do(func() { _ = stdin.Close() }) }
// Watch stderr as well as log it. When Pi refuses a resume it exits before
// emitting a single JSON event, so stderr is the only place the reason
- // exists and Result.ResumeRejected has nothing else to be built from.
+ // exists and Result.ResumeRejected has nothing else to be built from. Own the
+ // pipe directly instead of letting os/exec hide it behind a copy goroutine:
+ // an escaped descendant can inherit stderr too, and the error-grace path must
+ // be able to release every read that could hold Result finalization open.
+ stderrRead, err := cmd.StderrPipe()
+ if err != nil {
+ closeStdin()
+ closePiReadPipe(stdout)
+ releasePiSessionFileLock(sessionLock)
+ cancelProcess()
+ cancel()
+ return nil, fmt.Errorf("%s stderr pipe: %w", label, err)
+ }
stderrWatch := newPiStderrWatcher(newLogWriter(b.cfg.Logger, "["+label+":stderr] "))
- cmd.Stderr = stderrWatch
if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
closeStdin()
+ closePiReadPipe(stdout)
+ closePiReadPipe(stderrRead)
releasePiSessionFileLock(sessionLock)
+ cancelProcess()
cancel()
return nil, fmt.Errorf("start %s: %w", label, err)
}
+ stderrDone := make(chan struct{})
+ go func() {
+ _, _ = io.Copy(stderrWatch, stderrRead)
+ close(stderrDone)
+ }()
b.cfg.Logger.Info(label+" started", "pid", cmd.Process.Pid, "cwd", opts.Cwd, "model", opts.Model)
msgCh := make(chan Message, 256)
resCh := make(chan Result, 1)
+ turnErrorGrace := b.turnErrorGrace
+ if turnErrorGrace <= 0 {
+ turnErrorGrace = defaultPiTurnErrorGrace
+ }
+ turnErrors := newPiTurnErrorGuard(turnErrorGrace, func() {
+ b.cfg.Logger.Info(label + " turn error recovery grace expired; stopping runtime")
+ // CommandContext owns process-tree cancellation for every runtime
+ // command. An escaped descendant can nevertheless retain stdout/stderr
+ // write ends after that group dies, so close the adapter-owned pipes too:
+ // finalization must not depend on an unowned process eventually exiting.
+ cancelProcess()
+ closeStdin()
+ closePiReadPipe(stdout)
+ closePiReadPipe(stderrRead)
+ })
// Write concurrently with stdout consumption. A large prompt can fill the
// stdin pipe while the child fills stdout; serialising those operations can
@@ -297,17 +495,19 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
writeErrCh <- err
}()
- // Close both pipes when the context is cancelled. Closing stdin releases a
- // writer blocked on a child that stopped reading; closing stdout releases the
- // stream scanner.
+ // Close every adapter-owned pipe when the context is cancelled. Closing stdin
+ // releases a writer blocked on a child that stopped reading; closing the read
+ // pipes releases the stdout scanner and stderr copier.
go func() {
<-runCtx.Done()
closeStdin()
- _ = stdout.Close()
+ closePiReadPipe(stdout)
+ closePiReadPipe(stderrRead)
}()
go func() {
defer func() { releasePiSessionFileLock(sessionLock) }()
+ defer cancelProcess()
defer cancel()
defer close(msgCh)
defer close(resCh)
@@ -316,7 +516,6 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
var output strings.Builder
finalStatus := "completed"
var finalError string
- var lastTurnError string
usage := make(map[string]TokenUsage)
// Pi message_update events can be large (they embed the full message
@@ -333,6 +532,7 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
if err := json.Unmarshal([]byte(line), &evt); err != nil {
continue
}
+ turnErrors.observeEvent(evt.Type)
switch evt.Type {
case "agent_start":
@@ -341,7 +541,6 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
case "turn_start":
output.Reset()
textBuffer.Reset()
- lastTurnError = ""
case "message_update":
if evt.AssistantMessageEvent == nil {
@@ -403,10 +602,15 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
// retry, and turn_start clears this, so a later successful turn
// leaves nothing behind.
if msg.StopReason == "error" {
- lastTurnError = msg.ErrorMessage
- if lastTurnError == "" {
- lastTurnError = label + " ended the turn with an error"
+ turnError := msg.ErrorMessage
+ if turnError == "" {
+ turnError = label + " ended the turn with an error"
}
+ turnErrors.record(turnError)
+ } else {
+ // A successful terminal turn is positive recovery evidence even
+ // if a future Pi version omits the expected turn_start.
+ turnErrors.clear()
}
case "error":
@@ -418,7 +622,9 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
}
case "auto_retry_end":
- if !evt.Success && finalStatus == "completed" {
+ if evt.Success {
+ turnErrors.clear()
+ } else if finalStatus == "completed" {
finalStatus = "failed"
if evt.FinalError != "" {
finalError = evt.FinalError
@@ -433,21 +639,51 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
trySend(msgCh, Message{Type: MessageText, Content: d})
}
+ // Finish the user-owned stderr read before Wait closes StderrPipe. Normal
+ // exit gets the same 10s backstop cmd.WaitDelay used to provide when
+ // os/exec owned the copier. Cancellation and error-grace expiry close
+ // stderrRead above, so their finalization does not pay it.
+ stderrTimer := time.NewTimer(cmd.WaitDelay)
+ select {
+ case <-stderrDone:
+ stderrTimer.Stop()
+ case <-stderrTimer.C:
+ closePiReadPipe(stderrRead)
+ <-stderrDone
+ }
+
waitErr := cmd.Wait()
releaseProcessGroup(cmd)
duration := time.Since(startTime)
+ lastTurnError, turnErrorGraceExpired := turnErrors.finish()
// Wait closes the process pipes, so a prompt write still blocked when the
// child exited has returned by now. The writer sends exactly once.
writeErr := <-writeErrCh
+ authoritativeTerminal := false
if runCtx.Err() == context.DeadlineExceeded {
finalStatus = "timeout"
finalError = fmt.Sprintf("%s timed out after %s", label, timeout)
} else if runCtx.Err() == context.Canceled {
- finalStatus = "aborted"
- finalError = "execution cancelled"
+ if lastTurnError != "" {
+ // A daemon watchdog or user cancellation must not replace a
+ // provider failure Pi had already reported with a generic local
+ // cancellation. The daemon can then persist and classify the
+ // original provider message.
+ finalStatus = "failed"
+ finalError = lastTurnError
+ authoritativeTerminal = true
+ } else {
+ finalStatus = "aborted"
+ finalError = "execution cancelled"
+ }
+ } else if turnErrorGraceExpired {
+ finalStatus = "failed"
+ finalError = lastTurnError
+ authoritativeTerminal = true
} else if waitErr != nil && finalStatus == "completed" {
+ authoritativeTerminal = true
finalStatus = "failed"
// Prefer the turn's provider message over the process exit code.
// Pi (and pi-print-clean-exit) exits 1 after stopReason=error, so
@@ -464,17 +700,27 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
finalError = fmt.Sprintf("%s exited with error: %v", label, waitErr)
}
} else if writeErr != nil && finalStatus == "completed" {
+ authoritativeTerminal = true
finalStatus = "failed"
finalError = fmt.Sprintf("%s prompt write failed: %v", label, writeErr)
} else if lastTurnError != "" && finalStatus == "completed" {
+ authoritativeTerminal = true
// Pi exits 0 after a turn it could not complete and did not retry,
// and emits neither an `error` event nor `auto_retry_end`. Without
// this the run reports success with no output.
finalStatus = "failed"
finalError = lastTurnError
+ } else if runCtx.Err() == nil {
+ authoritativeTerminal = true
}
b.cfg.Logger.Info(label+" finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())
+ // Publish the authoritative terminal boundary before Result. The daemon
+ // uses this ordering to let an already-observed provider failure outrank
+ // a watchdog cancellation that raced with adapter finalization.
+ if authoritativeTerminal {
+ turnErrors.markTerminal()
+ }
// Publish the terminal result only after the transcript is available to
// a follow-up run. The result channel is buffered, so relying on a defer
@@ -497,7 +743,11 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
}
}()
- return &Session{Messages: msgCh, Result: resCh}, nil
+ return &Session{
+ Messages: msgCh,
+ Result: resCh,
+ TerminalObserved: turnErrors.terminalObserved,
+ }, nil
}
func piSessionBusyResult(label, sessionPath string) *Session {
diff --git a/server/pkg/agent/pi_test.go b/server/pkg/agent/pi_test.go
index 851a62451f..da8a4c80af 100644
--- a/server/pkg/agent/pi_test.go
+++ b/server/pkg/agent/pi_test.go
@@ -313,6 +313,242 @@ func piEventStreamScriptWithExit(events []string, exitCode int) string {
return b.String()
}
+func newPiTestBackend(t *testing.T, script string, turnErrorGrace time.Duration) *piBackend {
+ t.Helper()
+ fakePath := filepath.Join(t.TempDir(), "pi")
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ backend, err := New("pi", Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new pi backend: %v", err)
+ }
+ pi, ok := backend.(*piBackend)
+ if !ok {
+ t.Fatalf("New(pi) returned %T, want *piBackend", backend)
+ }
+ pi.turnErrorGrace = turnErrorGrace
+ return pi
+}
+
+func waitPiResult(t *testing.T, session *Session, timeout time.Duration) Result {
+ t.Helper()
+ select {
+ case result, ok := <-session.Result:
+ if !ok {
+ t.Fatal("result channel closed without a value")
+ }
+ return result
+ case <-time.After(timeout):
+ t.Fatal("timeout waiting for Pi result")
+ return Result{}
+ }
+}
+
+func TestPiExecutePreservesTurnErrorWhenCancelled(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ const providerError = "OpenAI API error (413): Failed to buffer the request body: length limit exceeded"
+ script := piEventStreamScript([]string{
+ `{"type":"agent_start"}`,
+ `{"type":"turn_start"}`,
+ `{"type":"turn_end","message":{"role":"assistant","model":"test","stopReason":"error","errorMessage":"` + providerError + `"}}`,
+ `{"type":"message_update","assistantMessageEvent":{"type":"thinking_delta","delta":"post-error activity"}}`,
+ }) + "exec sleep 300\n"
+ backend := newPiTestBackend(t, script, time.Minute)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{
+ ResumeSessionID: filepath.Join(t.TempDir(), "session.jsonl"),
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ for msg := range session.Messages {
+ if msg.Type == MessageThinking && msg.Content == "post-error activity" {
+ cancel()
+ break
+ }
+ }
+
+ result := waitPiResult(t, session, 5*time.Second)
+ if result.Status != "failed" {
+ t.Fatalf("status = %q, want failed (error=%q)", result.Status, result.Error)
+ }
+ if result.Error != providerError {
+ t.Fatalf("error = %q, want original provider error %q", result.Error, providerError)
+ }
+}
+
+func TestPiExecuteCancellationWithoutTurnErrorKeepsAbortedResult(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ script := piEventStreamScript([]string{`{"type":"agent_start"}`}) + "exec sleep 300\n"
+ backend := newPiTestBackend(t, script, 50*time.Millisecond)
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{
+ ResumeSessionID: filepath.Join(t.TempDir(), "session.jsonl"),
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ for msg := range session.Messages {
+ if msg.Type == MessageStatus {
+ cancel()
+ break
+ }
+ }
+
+ result := waitPiResult(t, session, 5*time.Second)
+ if result.Status != "aborted" || result.Error != "execution cancelled" {
+ t.Fatalf("result = %+v, want the existing no-error cancellation result", result)
+ }
+}
+
+func TestPiExecuteEndsSilentTurnErrorAfterGraceOnce(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ const providerError = "OpenAI API error (413): request body too large"
+ const grace = 80 * time.Millisecond
+ script := piEventStreamScript([]string{
+ `{"type":"agent_start"}`,
+ `{"type":"turn_start"}`,
+ `{"type":"turn_end","message":{"role":"assistant","model":"test","stopReason":"error","errorMessage":"` + providerError + `"}}`,
+ `{"type":"agent_end","messages":[],"willRetry":false}`,
+ }) + "exec sleep 300\n"
+ backend := newPiTestBackend(t, script, grace)
+
+ started := time.Now()
+ session, err := backend.Execute(context.Background(), "prompt-ignored", ExecOptions{
+ Timeout: 15 * time.Second,
+ ResumeSessionID: filepath.Join(t.TempDir(), "session.jsonl"),
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ result := waitPiResult(t, session, 20*time.Second)
+ if result.Status != "failed" || result.Error != providerError {
+ t.Fatalf("result = %+v, want one failed result with the provider error", result)
+ }
+ for msg := range session.Messages {
+ if msg.Type == MessageError {
+ t.Fatalf("turn-error grace emitted an error message and would refresh the daemon watchdog: %+v", msg)
+ }
+ }
+ if elapsed := time.Since(started); elapsed < grace/2 || elapsed > 10*time.Second {
+ t.Fatalf("error grace ended after %s, want approximately %s", elapsed, grace)
+ }
+ if _, ok := <-session.Result; ok {
+ t.Fatal("result channel produced more than one terminal result")
+ }
+}
+
+func TestPiExecuteTurnErrorActivityAndRetryRecoveryCancelTimer(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ const grace = 100 * time.Millisecond
+ script := "#!/bin/sh\n" +
+ "cat > /dev/null\n" +
+ `printf '%s\n' '{"type":"agent_start"}'` + "\n" +
+ `printf '%s\n' '{"type":"turn_start"}'` + "\n" +
+ `printf '%s\n' '{"type":"turn_end","message":{"role":"assistant","model":"test","stopReason":"error","errorMessage":"temporary provider error"}}'` + "\n" +
+ "sleep 0.06\n" +
+ `printf '%s\n' '{"type":"message_update","assistantMessageEvent":{"type":"thinking_delta","delta":"retrying"}}'` + "\n" +
+ "sleep 0.06\n" +
+ `printf '%s\n' '{"type":"auto_retry_start","attempt":1,"maxAttempts":3,"delayMs":1}'` + "\n" +
+ "sleep 0.15\n" +
+ `printf '%s\n' '{"type":"turn_start"}'` + "\n" +
+ `printf '%s\n' '{"type":"message_update","assistantMessageEvent":{"type":"text_delta","delta":"recovered"}}'` + "\n" +
+ `printf '%s\n' '{"type":"turn_end","message":{"role":"assistant","model":"test"}}'` + "\n"
+ backend := newPiTestBackend(t, script, grace)
+
+ session, err := backend.Execute(context.Background(), "prompt-ignored", ExecOptions{
+ Timeout: 15 * time.Second,
+ ResumeSessionID: filepath.Join(t.TempDir(), "session.jsonl"),
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ result := waitPiResult(t, session, 20*time.Second)
+ if result.Status != "completed" || result.Output != "recovered" || result.Error != "" {
+ t.Fatalf("result = %+v, want successful recovered turn", result)
+ }
+}
+
+func TestPiExecuteTurnErrorGraceWaitsForInFlightTool(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ const grace = 60 * time.Millisecond
+ script := "#!/bin/sh\n" +
+ "cat > /dev/null\n" +
+ `printf '%s\n' '{"type":"turn_start"}'` + "\n" +
+ `printf '%s\n' '{"type":"tool_execution_start","toolCallId":"call-1","toolName":"bash","args":{}}'` + "\n" +
+ `printf '%s\n' '{"type":"turn_end","message":{"role":"assistant","model":"test","stopReason":"error","errorMessage":"temporary provider error"}}'` + "\n" +
+ "sleep 0.15\n" +
+ `printf '%s\n' '{"type":"tool_execution_end","toolCallId":"call-1","toolName":"bash","result":"ok"}'` + "\n" +
+ `printf '%s\n' '{"type":"turn_start"}'` + "\n" +
+ `printf '%s\n' '{"type":"message_update","assistantMessageEvent":{"type":"text_delta","delta":"done"}}'` + "\n" +
+ `printf '%s\n' '{"type":"turn_end","message":{"role":"assistant","model":"test"}}'` + "\n"
+ backend := newPiTestBackend(t, script, grace)
+
+ session, err := backend.Execute(context.Background(), "prompt-ignored", ExecOptions{
+ Timeout: 15 * time.Second,
+ ResumeSessionID: filepath.Join(t.TempDir(), "session.jsonl"),
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ result := waitPiResult(t, session, 20*time.Second)
+ if result.Status != "completed" || result.Output != "done" {
+ t.Fatalf("result = %+v, want tool completion and recovered turn", result)
+ }
+}
+
+func TestPiExecuteNormalSilenceDoesNotArmTurnErrorGrace(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ const grace = 50 * time.Millisecond
+ script := "#!/bin/sh\n" +
+ "cat > /dev/null\n" +
+ `printf '%s\n' '{"type":"agent_start"}'` + "\n" +
+ "sleep 0.15\n" +
+ `printf '%s\n' '{"type":"turn_start"}'` + "\n" +
+ `printf '%s\n' '{"type":"message_update","assistantMessageEvent":{"type":"text_delta","delta":"healthy"}}'` + "\n" +
+ `printf '%s\n' '{"type":"turn_end","message":{"role":"assistant","model":"test"}}'` + "\n"
+ backend := newPiTestBackend(t, script, grace)
+
+ session, err := backend.Execute(context.Background(), "prompt-ignored", ExecOptions{
+ Timeout: 15 * time.Second,
+ ResumeSessionID: filepath.Join(t.TempDir(), "session.jsonl"),
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ result := waitPiResult(t, session, 20*time.Second)
+ if result.Status != "completed" || result.Output != "healthy" {
+ t.Fatalf("result = %+v, want normal silent run to complete", result)
+ }
+}
+
// TestPiExecuteRetainsOnlyLastTurnOutput verifies turn_start resets the
// output buffer so Result.Output keeps only the final turn's text.
func TestPiExecuteRetainsOnlyLastTurnOutput(t *testing.T) {
diff --git a/server/pkg/agent/pi_turn_error_unix_test.go b/server/pkg/agent/pi_turn_error_unix_test.go
new file mode 100644
index 0000000000..890f4148a2
--- /dev/null
+++ b/server/pkg/agent/pi_turn_error_unix_test.go
@@ -0,0 +1,133 @@
+//go:build unix
+
+package agent
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+)
+
+const (
+ piEscapedStdoutHelperEnv = "MULTICA_TEST_PI_ESCAPED_STDOUT_HELPER"
+ piEscapedStdoutPIDEnv = "MULTICA_TEST_PI_ESCAPED_STDOUT_PID_FILE"
+)
+
+// TestPiEscapedStdoutHolderProcess runs only in the subprocess launched by the
+// real regression below. The detached child inherits stdout, moves into its own
+// session, and therefore survives process-group cancellation of this helper.
+func TestPiEscapedStdoutHolderProcess(t *testing.T) {
+ if os.Getenv(piEscapedStdoutHelperEnv) != "1" {
+ return
+ }
+
+ holder := exec.Command("sleep", "30")
+ holder.Stdout = os.Stdout
+ holder.Stderr = os.Stderr
+ holder.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
+ if err := holder.Start(); err != nil {
+ t.Fatalf("start detached stdout holder: %v", err)
+ }
+ pidFile := os.Getenv(piEscapedStdoutPIDEnv)
+ if err := os.WriteFile(pidFile, []byte(strconv.Itoa(holder.Process.Pid)), 0o600); err != nil {
+ t.Fatalf("write detached stdout holder pid: %v", err)
+ }
+
+ for _, event := range []string{
+ `{"type":"agent_start"}`,
+ `{"type":"turn_start"}`,
+ `{"type":"turn_end","message":{"role":"assistant","model":"test","stopReason":"error","errorMessage":"OpenAI API error (413): request body too large"}}`,
+ `{"type":"agent_end","messages":[],"willRetry":false}`,
+ } {
+ fmt.Println(event)
+ }
+ time.Sleep(5 * time.Minute)
+}
+
+func TestPiExecuteTurnErrorGraceClosesStdoutHeldByEscapedDescendant(t *testing.T) {
+ const providerError = "OpenAI API error (413): request body too large"
+ const grace = 50 * time.Millisecond
+
+ testBinary, err := os.Executable()
+ if err != nil {
+ t.Fatalf("locate test executable: %v", err)
+ }
+ pidFile := filepath.Join(t.TempDir(), "escaped.pid")
+ t.Cleanup(func() {
+ data, err := os.ReadFile(pidFile)
+ if err != nil {
+ return
+ }
+ pid, err := strconv.Atoi(strings.TrimSpace(string(data)))
+ if err != nil {
+ return
+ }
+ if process, err := os.FindProcess(pid); err == nil {
+ _ = process.Kill()
+ }
+ })
+
+ // The wrapper consumes Pi's stdin contract and then execs this test binary
+ // as the fake runtime. The helper's detached child retains the exact stdout
+ // pipe returned by cmd.StdoutPipe.
+ fakePath := filepath.Join(t.TempDir(), "pi")
+ script := fmt.Sprintf("#!/bin/sh\ncat > /dev/null\nexec %q -test.v -test.run '^TestPiEscapedStdoutHolderProcess$'\n", testBinary)
+ writeTestExecutable(t, fakePath, []byte(script))
+ backend, err := New("pi", Config{
+ ExecutablePath: fakePath,
+ Env: map[string]string{
+ piEscapedStdoutHelperEnv: "1",
+ piEscapedStdoutPIDEnv: pidFile,
+ },
+ Logger: slog.Default(),
+ })
+ if err != nil {
+ t.Fatalf("new pi backend: %v", err)
+ }
+ pi := backend.(*piBackend)
+ pi.turnErrorGrace = grace
+
+ started := time.Now()
+ session, err := pi.Execute(context.Background(), "prompt-ignored", ExecOptions{
+ ResumeSessionID: filepath.Join(t.TempDir(), "session.jsonl"),
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ statusSeen := make(chan bool, 1)
+ go func() {
+ for msg := range session.Messages {
+ if msg.Type == MessageStatus {
+ statusSeen <- true
+ return
+ }
+ }
+ statusSeen <- false
+ }()
+ select {
+ case seen := <-statusSeen:
+ if !seen {
+ t.Fatal("fake Pi closed messages before agent_start")
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("fake Pi never emitted agent_start")
+ }
+ result := waitPiResult(t, session, 3*time.Second)
+ if result.Status != "failed" || result.Error != providerError {
+ t.Fatalf("result = %+v, want the provider failure", result)
+ }
+ if elapsed := time.Since(started); elapsed > 2*time.Second {
+ t.Fatalf("result took %s after %s grace; escaped stdout holder blocked finalization", elapsed, grace)
+ }
+ if _, ok := <-session.Result; ok {
+ t.Fatal("result channel produced more than one terminal result")
+ }
+}