diff --git a/apps/backend/internal/agent/acpdbg/ops.go b/apps/backend/internal/agent/acpdbg/ops.go index c0cf70af62..8c19bbb6d9 100644 --- a/apps/backend/internal/agent/acpdbg/ops.go +++ b/apps/backend/internal/agent/acpdbg/ops.go @@ -9,6 +9,10 @@ import ( "time" ) +// methodSessionUpdate is the ACP notification an agent streams for every +// message chunk, tool call, and replayed history entry. +const methodSessionUpdate = "session/update" + // IsAuthErrorMessage is a coarse substring heuristic mirroring // hostutility.isAuthError. ACP auth failures bubble up as plain-text // JSON-RPC errors without a distinct code, so we match obvious markers so @@ -283,45 +287,82 @@ func sendPromptAndCollect(ctx context.Context, r *Runner, sessionID, prompt stri return "", err } - respCh := make(chan Frame, 1) - r.mu.Lock() - r.pending[promptID] = respCh - r.mu.Unlock() - - if err := r.framer.Write(req); err != nil { + respCh, err := r.registerPending(promptID) + if err != nil { return "", err } + // Every exit path drops the waiter, including the ones that give up before + // a response arrives, so the map does not accumulate dead entries. + defer func() { + r.mu.Lock() + delete(r.pending, promptID) + r.mu.Unlock() + }() var text strings.Builder - for { - select { - case resp := <-respCh: - if errMap, ok := resp["error"].(map[string]any); ok { - return text.String(), fmt.Errorf("%v", errMap["message"]) - } - return text.String(), nil - case frame, ok := <-r.oob: + + // drain consumes everything currently queued. Frames that arrived before + // the prompt was written are answered but never collected: a session/load + // replay leaves the whole conversation history queued, and folding that + // into the prompt's text would return the transcript instead of the reply. + drain := func(collect bool) { + for { + frame, ok, _ := r.popOOB() if !ok { - return text.String(), io.EOF + return } - // Agent-initiated request during a prompt: auto-reply so it - // doesn't hang. + // Agent-initiated request: auto-reply so it doesn't hang. if frame.Method() != "" && frame.ID() != nil { reply := NewMethodNotFound(frame.ID(), frame.Method()) _ = r.rec.Sent(reply) _ = r.framer.Write(reply) continue } - // Notification: extract text chunks from session/update if - // present. - if frame.Method() == "session/update" { + if collect && frame.Method() == methodSessionUpdate { if chunk := extractTextChunk(frame); chunk != "" { text.WriteString(chunk) } } + } + } + + drain(false) + if err := r.framer.Write(req); err != nil { + return "", err + } + + for { + drain(true) + + select { + case resp, ok := <-respCh: + if !ok { + // The read loop closed our waiter: the child died or the + // runner is shutting down. Without this check the nil frame + // would read as a successful, empty response. + r.mu.Lock() + readErr := r.readLoopEr + r.mu.Unlock() + if readErr == nil { + readErr = io.EOF + } + return text.String(), fmt.Errorf("read loop exited: %w", readErr) + } + // The read loop is serial and the agent emits every chunk before + // the response, so anything left queued belongs to this prompt. + drain(true) + if errMap, ok := resp["error"].(map[string]any); ok { + return text.String(), fmt.Errorf("%v", errMap["message"]) + } + return text.String(), nil + case <-r.oobWake: case <-ctx.Done(): return text.String(), ctx.Err() } + + if r.oobFinished() { + return text.String(), io.EOF + } } } diff --git a/apps/backend/internal/agent/acpdbg/runner.go b/apps/backend/internal/agent/acpdbg/runner.go index 5956cf650c..cd5f14cff9 100644 --- a/apps/backend/internal/agent/acpdbg/runner.go +++ b/apps/backend/internal/agent/acpdbg/runner.go @@ -49,10 +49,18 @@ type Runner struct { stderrWG sync.WaitGroup - // Frames received that aren't responses to our outstanding request. - // The protocol callback reads from this channel to process - // notifications and agent-initiated requests. - oob chan Frame + // Frames received that aren't responses to our outstanding request: + // notifications and agent-initiated requests. The queue is unbounded + // because nothing drains it while Request waits for a response, and a + // session/load replay emits one notification per history entry. With a + // bounded queue the read loop blocks on the first frame past the limit + // and never reaches the response that follows the replay, so the request + // hangs until its deadline. Memory is bounded in practice by the size of + // the session being replayed. + oobMu sync.Mutex + oobBuf []Frame + oobClosed bool + oobWake chan struct{} // responses[id] is closed by the read loop when a response with that // id is recorded; the mu-protected map stores the frame itself. mu sync.Mutex @@ -126,7 +134,7 @@ func NewRunner(ctx context.Context, jsonlPath string, cfg RunConfig) (*Runner, e stdin: stdin, stdout: stdout, framer: NewFramer(stdin, stdout), - oob: make(chan Frame, 32), + oobWake: make(chan struct{}, 1), pending: map[int]chan Frame{}, shutdownCh: make(chan struct{}), watchStopCh: make(chan struct{}), @@ -206,10 +214,10 @@ func (r *Runner) Request(ctx context.Context, frame Frame) (Frame, error) { if !ok { return nil, fmt.Errorf("request frame has no integer id") } - ch := make(chan Frame, 1) - r.mu.Lock() - r.pending[idNum] = ch - r.mu.Unlock() + ch, err := r.registerPending(idNum) + if err != nil { + return nil, err + } if err := r.rec.Sent(frame); err != nil { return nil, err @@ -246,43 +254,112 @@ func (r *Runner) Request(ctx context.Context, frame Frame) (Frame, error) { // method-not-found so the session doesn't hang. func (r *Runner) DrainOOBUntil(ctx context.Context, handler func(Frame) bool) error { for { - select { - case frame, ok := <-r.oob: - if !ok { - return io.EOF - } - // If this is an agent-initiated request, auto-reply so it - // doesn't block waiting for us. - if frame.Method() != "" && frame.ID() != nil { - reply := NewMethodNotFound(frame.ID(), frame.Method()) - _ = r.rec.Sent(reply) - _ = r.framer.Write(reply) - } - if handler != nil && handler(frame) { - return nil - } - case <-ctx.Done(): - return ctx.Err() + // NextOOB already auto-replies to agent-initiated requests so the + // session does not hang waiting on us. + frame, err := r.NextOOB(ctx) + if err != nil { + return err } + if handler != nil && handler(frame) { + return nil + } + } +} + +// pushOOB appends a frame to the unbounded out-of-band queue. It never blocks, +// so the read loop always stays free to reach the response that follows a +// replay burst. +func (r *Runner) pushOOB(frame Frame) { + r.oobMu.Lock() + if r.oobClosed { + r.oobMu.Unlock() + return + } + r.oobBuf = append(r.oobBuf, frame) + r.oobMu.Unlock() + signal(r.oobWake) +} + +// popOOB removes the oldest queued frame. ok is false when the queue is empty; +// closed reports that no further frames will arrive. +func (r *Runner) popOOB() (frame Frame, ok bool, closed bool) { + r.oobMu.Lock() + defer r.oobMu.Unlock() + if len(r.oobBuf) == 0 { + return nil, false, r.oobClosed + } + frame = r.oobBuf[0] + // Release the popped slot. Re-slicing alone keeps the whole backing array + // reachable, so a drained replay burst would stay pinned for the Runner's + // lifetime; a channel receive used to zero the slot for us. + r.oobBuf[0] = nil + r.oobBuf = r.oobBuf[1:] + if len(r.oobBuf) == 0 { + r.oobBuf = nil + } + return frame, true, false +} + +// closeOOB marks the queue drained-and-finished and wakes any waiter. Frames +// already queued stay readable, matching what a closed channel used to offer. +func (r *Runner) closeOOB() { + r.oobMu.Lock() + r.oobClosed = true + r.oobMu.Unlock() + signal(r.oobWake) +} + +// oobFinished reports that the child is gone and every queued frame has been +// consumed, so a caller waiting for more will wait forever. +func (r *Runner) oobFinished() bool { + r.oobMu.Lock() + defer r.oobMu.Unlock() + return r.oobClosed && len(r.oobBuf) == 0 +} + +// wakeNextOOBWaiter passes the wake token on when work remains. oobWake holds a +// single coalesced token, so a consumer that takes it has to re-arm or a second +// waiter sleeps with frames still queued (or misses the close entirely). +func (r *Runner) wakeNextOOBWaiter() { + r.oobMu.Lock() + pending := len(r.oobBuf) > 0 || r.oobClosed + r.oobMu.Unlock() + if pending { + signal(r.oobWake) + } +} + +// signal delivers a non-blocking wake token, dropping it when one is pending. +func signal(ch chan struct{}) { + select { + case ch <- struct{}{}: + default: } } // NextOOB returns the next out-of-band frame, blocking until one is // available or the context is cancelled. func (r *Runner) NextOOB(ctx context.Context) (Frame, error) { - select { - case frame, ok := <-r.oob: - if !ok { + for { + frame, ok, closed := r.popOOB() + if ok { + r.wakeNextOOBWaiter() + if frame.Method() != "" && frame.ID() != nil { + reply := NewMethodNotFound(frame.ID(), frame.Method()) + _ = r.rec.Sent(reply) + _ = r.framer.Write(reply) + } + return frame, nil + } + if closed { + r.wakeNextOOBWaiter() return nil, io.EOF } - if frame.Method() != "" && frame.ID() != nil { - reply := NewMethodNotFound(frame.ID(), frame.Method()) - _ = r.rec.Sent(reply) - _ = r.framer.Write(reply) + select { + case <-r.oobWake: + case <-ctx.Done(): + return nil, ctx.Err() } - return frame, nil - case <-ctx.Done(): - return nil, ctx.Err() } } @@ -324,7 +401,7 @@ func (r *Runner) Close(reason string) { r.readLoopWG.Wait() r.stderrWG.Wait() - close(r.oob) + r.closeOOB() meta := map[string]any{"exit_code": exitCode} if reason != "" { @@ -374,13 +451,7 @@ func (r *Runner) readLoop() { if err != nil { // Fail any outstanding request waiters so Request() returns // rather than blocking forever when the child dies. - r.mu.Lock() - r.readLoopEr = err - for id, ch := range r.pending { - close(ch) - delete(r.pending, id) - } - r.mu.Unlock() + r.failPending(err) return } _ = r.rec.Received(frame) @@ -391,23 +462,58 @@ func (r *Runner) readLoop() { } // Anything else (notifications, agent-initiated requests, - // orphaned responses) goes out of band. Block rather than drop, - // so session/update chunks and agent-initiated requests are - // never lost — this is a debug tool, correctness beats throughput. + // orphaned responses) goes out of band. The queue is unbounded and + // never drops, so session/update chunks and agent-initiated requests + // survive a replay burst without stalling this loop. + // + // Stop once shutdown starts, though: nobody will read what we queue + // from here on, and a wedged child that floods stdout through the + // grace period would otherwise make us allocate everything it writes. select { - case r.oob <- frame: case <-r.shutdownCh: - r.mu.Lock() - for id, ch := range r.pending { - close(ch) - delete(r.pending, id) - } - r.mu.Unlock() + r.failPending(errShutdown) return + default: } + r.pushOOB(frame) } } +// errShutdown is what outstanding requests see when the read loop stops because +// the runner is shutting down rather than because the child died. +var errShutdown = errors.New("runner shutting down") + +// registerPending claims the response channel for a request id, refusing once +// the read loop is terminal. failPending only closes the waiters that exist +// when it runs, so a registration racing past it would never be woken: writing +// the request can still succeed against a child holding stdin open, and the +// caller would then block until its deadline. The check shares r.mu with +// failPending so the two cannot interleave. +func (r *Runner) registerPending(id int) (chan Frame, error) { + ch := make(chan Frame, 1) + r.mu.Lock() + defer r.mu.Unlock() + if r.readLoopEr != nil { + return nil, fmt.Errorf("read loop exited: %w", r.readLoopEr) + } + r.pending[id] = ch + return ch, nil +} + +// failPending closes every outstanding request waiter so callers return instead +// of blocking on a child nobody is reading any more. +func (r *Runner) failPending(err error) { + r.mu.Lock() + if r.readLoopEr == nil { + r.readLoopEr = err + } + for id, ch := range r.pending { + close(ch) + delete(r.pending, id) + } + r.mu.Unlock() +} + func (r *Runner) drainStderr(rc io.ReadCloser) { defer r.stderrWG.Done() sc := bufio.NewScanner(rc) diff --git a/apps/backend/internal/agent/acpdbg/runner_burst_test.go b/apps/backend/internal/agent/acpdbg/runner_burst_test.go new file mode 100644 index 0000000000..e81891575f --- /dev/null +++ b/apps/backend/internal/agent/acpdbg/runner_burst_test.go @@ -0,0 +1,347 @@ +package acpdbg + +import ( + "bufio" + "context" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" +) + +// The deadlock these tests pin is pure Go, so they must run everywhere kandev +// runs. They live outside runner_test.go, which is //go:build !windows because +// its process-group assertions need POSIX signals, and drive the agent through +// the re-executed-test-binary helper that ops_test.go already uses rather than +// through `sh`. + +const burstHelperEnv = "ACPDBG_BURST_HELPER" + +// burstHelperCommand returns the spawn command for the scripted agent below. +// The path has to be absolute: the runner gives the child its own working +// directory, so a relative os.Args[0] (what `go test -c` produces when the +// binary is invoked as ./pkg.test) would not resolve there. +func burstHelperCommand(t *testing.T) []string { + t.Helper() + self, err := os.Executable() + if err != nil { + self, err = filepath.Abs(os.Args[0]) + if err != nil { + t.Fatalf("locate test binary: %v", err) + } + } + return []string{self, "-test.run=^TestACPDBGBurstHelperProcess$"} +} + +// TestACPDBGBurstHelperProcess is not a test: when the env var is set it is the +// scripted ACP agent the burst tests talk to. It stays silent on stdout apart +// from protocol frames, because anything else corrupts the JSON-RPC stream. +func TestACPDBGBurstHelperProcess(t *testing.T) { + mode := os.Getenv(burstHelperEnv) + if mode == "" { + return + } + notifications, _ := strconv.Atoi(os.Getenv(burstHelperEnv + "_COUNT")) + + // A broken agent: kills the framer with unparseable stdout, then keeps + // stdin open forever so writes to it still succeed. + if mode == "garbage" { + _, _ = fmt.Fprintln(os.Stdout, "this is not a JSON-RPC frame") + _, _ = io.Copy(io.Discard, os.Stdin) + return + } + + // A wedged agent: never reads stdin, just writes notifications forever. + if mode == "flood" { + w := bufio.NewWriter(os.Stdout) + for { + _, _ = fmt.Fprintln(w, `{"jsonrpc":"2.0","method":"session/update"}`) + if err := w.Flush(); err != nil { + return + } + } + } + + // emit flushes every line, so there is no deferred flush to lose when a + // scripted death calls os.Exit. + out := bufio.NewWriter(os.Stdout) + emit := func(line string) { + _, _ = fmt.Fprintln(out, line) + _ = out.Flush() + } + chunk := func(text string) string { + return fmt.Sprintf(`{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":%q}}}}`, text) + } + + scanner := bufio.NewScanner(os.Stdin) + scanner.Buffer(make([]byte, 0, 64*1024), 8*1024*1024) + for scanner.Scan() { + var req map[string]any + if err := json.Unmarshal(scanner.Bytes(), &req); err != nil { + continue + } + id := req["id"] + method, _ := req["method"].(string) + + switch method { + case "initialize": + emit(fmt.Sprintf(`{"jsonrpc":"2.0","id":%v,"result":{"protocolVersion":1}}`, id)) + case "session/load": + // Replay every history entry, then answer the request that is + // waiting behind them. + for i := 0; i < notifications; i++ { + emit(chunk("HISTORY")) + } + emit(fmt.Sprintf(`{"jsonrpc":"2.0","id":%v,"result":{}}`, id)) + case "session/prompt": + emit(chunk("ANSWER")) + if mode == "die-mid-prompt" { + // Die after accepting the prompt and streaming part of the + // answer, so the caller is waiting on a response that will + // never come. Exiting is what closes the pipe: returning would + // leave the test binary finishing its own run with stdout still + // open, and the caller would hit its deadline instead. + os.Exit(0) + } + emit(fmt.Sprintf(`{"jsonrpc":"2.0","id":%v,"result":{"stopReason":"end_turn"}}`, id)) + default: + emit(fmt.Sprintf(`{"jsonrpc":"2.0","id":%v,"result":{}}`, id)) + } + } +} + +// TestRequestSurvivesReplayBurst is the regression for a deadlock that made +// session/load look like an agent that never answers. The out-of-band queue was +// a channel of 32; a replay emitting more than that blocked the read loop on the +// send, so the response queued behind the notifications was never read and the +// request hung until its deadline. Nothing drains the queue while Request waits, +// so the queue has to be unbounded. +func TestRequestSurvivesReplayBurst(t *testing.T) { + // Incident scale. No finite number proves the queue is unbounded, but this + // is far past any capacity someone would plausibly reintroduce (256, 1024, + // 4096) while "bounding memory", which is the regression to catch. + const notifications = 5000 + t.Setenv(burstHelperEnv, "replay") + t.Setenv(burstHelperEnv+"_COUNT", strconv.Itoa(notifications)) + + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + runner, err := NewRunner(ctx, filepath.Join(t.TempDir(), "frames.jsonl"), RunConfig{ + AgentID: "burst-helper", + Command: burstHelperCommand(t), + }) + if err != nil { + t.Fatalf("NewRunner: %v", err) + } + t.Cleanup(func() { runner.Close("test cleanup") }) + + req, _ := runner.Framer().NewRequest("session/load", map[string]any{"sessionId": "s1"}) + if _, err := runner.Request(ctx, req); err != nil { + t.Fatalf("Request did not complete behind a %d-notification replay: %v", notifications, err) + } + + // Every notification must still be retrievable through the public API: the + // queue buffers, it never drops, because this is a debug tool and the + // frames are the evidence. + for i := 0; i < notifications; i++ { + frame, err := runner.NextOOB(ctx) + if err != nil { + t.Fatalf("NextOOB after %d of %d frames: %v", i, notifications, err) + } + if frame.Method() != methodSessionUpdate { + t.Fatalf("frame %d method = %q, want session/update", i, frame.Method()) + } + } + runner.oobMu.Lock() + left := len(runner.oobBuf) + runner.oobMu.Unlock() + if left != 0 { + t.Fatalf("%d frames left queued after draining all %d", left, notifications) + } +} + +// TestPromptReportsChildDeathInsteadOfSuccess pins that a prompt whose agent +// dies mid-stream returns an error. The read loop closes the waiter, and a +// receive from a closed channel yields a nil frame; without checking ok that +// nil reads as a successful, empty response and the caller is told the prompt +// worked. +func TestPromptReportsChildDeathInsteadOfSuccess(t *testing.T) { + t.Setenv(burstHelperEnv, "die-mid-prompt") + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + runner, err := NewRunner(ctx, filepath.Join(t.TempDir(), "frames.jsonl"), RunConfig{ + AgentID: "dying-helper", + Command: burstHelperCommand(t), + }) + if err != nil { + t.Fatalf("NewRunner: %v", err) + } + t.Cleanup(func() { runner.Close("test cleanup") }) + + if _, err := sendInitialize(ctx, runner); err != nil { + t.Fatalf("initialize: %v", err) + } + _, err = sendPromptAndCollect(ctx, runner, "s1", "are you there?") + if err == nil { + t.Fatal("prompt reported success after the agent died mid-stream") + } + // Must fail because the read loop closed the waiter, not because the + // caller's deadline expired — the latter would pass without the fix. + if !strings.Contains(err.Error(), "read loop exited") { + t.Fatalf("error = %v, want it to report the read loop exiting", err) + } + + runner.mu.Lock() + pending := len(runner.pending) + runner.mu.Unlock() + if pending != 0 { + t.Fatalf("%d pending waiters left behind, want 0", pending) + } +} + +// TestRequestsRejectedOnceReadLoopIsTerminal pins that a caller arriving after +// the read loop has already failed gets the read-loop error promptly instead of +// waiting out its own deadline. failPending only closes the waiters that exist +// when it runs, and the child here keeps stdin open, so writing the request +// still succeeds — nothing would ever wake a waiter registered past that point. +func TestRequestsRejectedOnceReadLoopIsTerminal(t *testing.T) { + t.Setenv(burstHelperEnv, "garbage") + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + runner, err := NewRunner(ctx, filepath.Join(t.TempDir(), "frames.jsonl"), RunConfig{ + AgentID: "garbage-helper", + Command: burstHelperCommand(t), + }) + if err != nil { + t.Fatalf("NewRunner: %v", err) + } + t.Cleanup(func() { runner.Close("test cleanup") }) + + waitForReadLoopDone(t, runner) + + // Both entry points must refuse, must say why, and must not simply run out + // the clock. Accepting any error would let an unrelated immediate failure — + // or the caller's own deadline — stand in for the rejection being tested. + start := time.Now() + req, _ := runner.Framer().NewRequest("session/new", map[string]any{}) + _, reqErr := runner.Request(ctx, req) + if reqErr == nil { + t.Fatal("Request accepted a waiter after the read loop went terminal") + } + if !strings.Contains(reqErr.Error(), "read loop exited") { + t.Fatalf("Request error = %v, want it to name the read loop", reqErr) + } + _, promptErr := sendPromptAndCollect(ctx, runner, "s1", "anyone home?") + if promptErr == nil { + t.Fatal("sendPromptAndCollect accepted a waiter after the read loop went terminal") + } + if !strings.Contains(promptErr.Error(), "read loop exited") { + t.Fatalf("sendPromptAndCollect error = %v, want it to name the read loop", promptErr) + } + if elapsed := time.Since(start); elapsed > 5*time.Second { + t.Fatalf("took %s to refuse; expected to fail immediately, not on the deadline", elapsed) + } +} + +// waitForReadLoopDone blocks until the read loop goroutine has finished, not +// merely until readLoopEr is set: the two are separated by the teardown that +// closes existing waiters, and the race under test lives in that gap. +func waitForReadLoopDone(t *testing.T, r *Runner) { + t.Helper() + done := make(chan struct{}) + go func() { + r.readLoopWG.Wait() + close(done) + }() + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatal("timed out waiting for the read loop to exit on malformed stdout") + } +} + +// TestReadLoopStopsQueueingAfterShutdown pins that a wedged agent flooding +// stdout cannot make us allocate indefinitely once shutdown starts. The queue +// is unbounded, so the read loop has to stop on its own: nothing will ever +// consume what it queues from that point. +func TestReadLoopStopsQueueingAfterShutdown(t *testing.T) { + t.Setenv(burstHelperEnv, "flood") + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + runner, err := NewRunner(ctx, filepath.Join(t.TempDir(), "frames.jsonl"), RunConfig{ + AgentID: "flood-helper", + Command: burstHelperCommand(t), + }) + if err != nil { + t.Fatalf("NewRunner: %v", err) + } + // Registered immediately: both assertions below can t.Fatalf, and without + // this the flooding child would outlive the test. + t.Cleanup(func() { runner.Close("test cleanup") }) + + // Let the flood get going, then start shutting down. + waitForOOBFrames(t, runner, 100) + runner.signalShutdown() + + // The read loop should stop; the queue settles instead of growing without + // bound. Sample twice with a gap the flood would easily fill. + settled := oobLen(runner) + time.Sleep(300 * time.Millisecond) + if grown := oobLen(runner); grown != settled { + t.Fatalf("queue kept growing after shutdown: %d -> %d", settled, grown) + } +} + +func oobLen(r *Runner) int { + r.oobMu.Lock() + defer r.oobMu.Unlock() + return len(r.oobBuf) +} + +func waitForOOBFrames(t *testing.T, r *Runner, want int) { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for time.Now().Before(deadline) { + if oobLen(r) >= want { + return + } + time.Sleep(10 * time.Millisecond) + } + t.Fatalf("timed out waiting for %d queued frames, got %d", want, oobLen(r)) +} + +// TestSessionLoadPromptExcludesReplayedHistory pins that a prompt issued after +// session/load returns only the new reply. The replay leaves the whole +// conversation queued out of band, and collecting it would hand the caller the +// transcript instead of the answer. +func TestSessionLoadPromptExcludesReplayedHistory(t *testing.T) { + t.Setenv(burstHelperEnv, "history") + t.Setenv(burstHelperEnv+"_COUNT", "50") + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + runner, err := NewRunner(ctx, filepath.Join(t.TempDir(), "frames.jsonl"), RunConfig{ + AgentID: "history-helper", + Command: burstHelperCommand(t), + }) + if err != nil { + t.Fatalf("NewRunner: %v", err) + } + t.Cleanup(func() { runner.Close("test cleanup") }) + + res, err := SessionLoad(ctx, runner, SessionLoadOptions{SessionID: "s1", Prompt: "what now?"}) + if err != nil { + t.Fatalf("SessionLoad: %v", err) + } + if res.Text != "ANSWER" { + t.Fatalf("collected text = %q, want %q (replayed history must not be collected)", res.Text, "ANSWER") + } +} diff --git a/apps/backend/internal/agent/acpdbg/runner_test.go b/apps/backend/internal/agent/acpdbg/runner_test.go index 47736034a2..015ab14596 100644 --- a/apps/backend/internal/agent/acpdbg/runner_test.go +++ b/apps/backend/internal/agent/acpdbg/runner_test.go @@ -53,7 +53,11 @@ func TestRunnerContextCancellationKillsProcessTree(t *testing.T) { waitForProcessGone(t, pid) } -func TestRunnerCloseUnblocksFullOOBQueue(t *testing.T) { +// TestRunnerCloseFailsPendingRequest pins that shutdown returns promptly and +// hands every waiting caller an error, with out-of-band frames still queued. +// It was written when a bounded queue could block the read loop; the queue is +// unbounded now, so what it still guards is the pending-request teardown. +func TestRunnerCloseFailsPendingRequest(t *testing.T) { const frame = `{"jsonrpc":"2.0","method":"session/update"}` cmd := fmt.Sprintf("for i in $(seq 1 40); do printf '%%s\\n' '%s'; done; sleep 30", frame) ctx, cancel := context.WithCancel(context.Background()) @@ -68,9 +72,6 @@ func TestRunnerCloseUnblocksFullOOBQueue(t *testing.T) { t.Cleanup(func() { cancel() runner.tree.kill(runner.cmd) - for len(runner.oob) > 0 { - <-runner.oob - } runner.Close("test cleanup") }) @@ -84,7 +85,7 @@ func TestRunnerCloseUnblocksFullOOBQueue(t *testing.T) { requestDone <- err }() waitForPendingRequest(t, runner) - waitForOOBQueue(t, runner) + waitForOOBQueue(t, runner, 40) cancel() closed := make(chan struct{}) go func() { @@ -95,7 +96,7 @@ func TestRunnerCloseUnblocksFullOOBQueue(t *testing.T) { select { case <-closed: case <-time.After(3 * time.Second): - t.Fatal("Runner.Close remained blocked on a full OOB queue") + t.Fatal("Runner.Close did not return after cancellation with OOB frames queued") } select { case err := <-requestDone: @@ -129,16 +130,25 @@ func waitForPIDFile(t *testing.T, path string) int { } } -func waitForOOBQueue(t *testing.T, runner *Runner) { +// waitForOOBQueue blocks until at least want frames are queued out of band. The +// queue is unbounded, so there is no "full" state to wait for; callers pass the +// number of frames the fixture emits, which also proves none were dropped. +func waitForOOBQueue(t *testing.T, runner *Runner, want int) { t.Helper() deadline := time.NewTimer(3 * time.Second) defer deadline.Stop() ticker := time.NewTicker(10 * time.Millisecond) defer ticker.Stop() - for len(runner.oob) < cap(runner.oob) { + for { + runner.oobMu.Lock() + queued := len(runner.oobBuf) + runner.oobMu.Unlock() + if queued >= want { + return + } select { case <-deadline.C: - t.Fatalf("timed out waiting for OOB queue to fill: %d/%d", len(runner.oob), cap(runner.oob)) + t.Fatalf("timed out waiting for %d OOB frames, got %d", want, queued) case <-ticker.C: } }