Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent): make readOpenclawStdout's cut-short decision atomic (MUL-6024) (#6765)
Bohan Jiang6e6682539cc7
diff --git a/server/pkg/agent/openclaw_stdout.go b/server/pkg/agent/openclaw_stdout.goindex 0406e9716f..ab6b022bff 100644--- a/server/pkg/agent/openclaw_stdout.go+++ b/server/pkg/agent/openclaw_stdout.go@@ -79,19 +79,36 @@ func readOpenclawStdout(r io.Reader, idleGrace time.Duration) (buf []byte, cutShchunk := make([]byte, 32*1024)for {n, rerr := r.Read(chunk)- if n > 0 {+ // A terminating Read may carry data and its error at once:+ // io.Reader permits returning n > 0 with io.EOF, and this function+ // accepts any io.Reader. Publishing the bytes and the end of the+ // stream in one critical section keeps that a single observation —+ // split across two locks, a poll landing in between sees a buffer+ // that has just become parseable while atEOF is still false, and+ // reports a stream that in fact ended cleanly as cut short.+ //+ // os/exec's StdoutPipe is not one of those readers: *os.File+ // reports the final bytes and the EOF as two adjacent reads, since+ // only a zero-byte read is turned into io.EOF. Production+ // therefore reaches this seam through the wider gap between those+ // two reads, which still has to outlast idleGrace to fool the+ // poll. The narrower race that does not need starvation at all is+ // the one in the tick branch below.+ if n > 0 || rerr != nil {mu.Lock()- acc = append(acc, chunk[:n]...)- lastByte = time.Now()+ if n > 0 {+ acc = append(acc, chunk[:n]...)+ lastByte = time.Now()+ }+ if rerr != nil {+ if rerr != io.EOF {+ readErr = rerr+ }+ atEOF = true+ }mu.Unlock()}if rerr != nil {- mu.Lock()- if rerr != io.EOF {- readErr = rerr- }- atEOF = true- mu.Unlock()return}}@@ -111,27 +128,27 @@ func readOpenclawStdout(r io.Reader, idleGrace time.Duration) (buf []byte, cutShreturn out, false, rerrcase <-ticker.C:- // Check the cheap conditions under the lock first and only copy the- // buffer once the silence threshold is actually met. Copying on every- // tick would allocate the whole accumulated result ~20 times per wait- // window, which for a large result is pure waste.+ // Decide and copy in one critical section: the bytes returned must be+ // the same bytes the silence check was made about. Snapshotting the+ // conditions, releasing the lock and re-reading acc would let output+ // that arrived in between complete the buffer, so a stream that had+ // just ended cleanly would be reported as cut short.+ //+ // The cheap conditions are still checked first and the buffer copied+ // only once the silence threshold is met. Copying on every tick would+ // allocate the whole accumulated result ~20 times per wait window,+ // which for a large result is pure waste.mu.Lock()- size := len(acc)- last := lastByte- done := atEOF+ var out []byte+ // atEOF: let the <-finished branch report the final state.+ if !atEOF && len(acc) > 0 && time.Since(lastByte) >= idleGrace {+ out = append([]byte(nil), acc...)+ }mu.Unlock()- if done {- continue // let the <-finished branch report the final state- }- if size == 0 || time.Since(last) < idleGrace {+ if out == nil {continue}-- mu.Lock()- out := append([]byte(nil), acc...)- mu.Unlock()-if _, ok := parseWholeBufferOpenclawResult(out); !ok {continue}diff --git a/server/pkg/agent/openclaw_stdout_test.go b/server/pkg/agent/openclaw_stdout_test.goindex a12800ec4f..e6383d6cd3 100644--- a/server/pkg/agent/openclaw_stdout_test.go+++ b/server/pkg/agent/openclaw_stdout_test.go@@ -299,6 +299,75 @@ func (r *stagedOpenclawEOFReader) Read(p []byte) (int, error) {}}+// lingeringOpenclawReader delivers the whole result in one Read and then keeps+// the stream open until the test releases it — an openclaw that printed its+// complete blob and refused to exit, without spawning a process.+type lingeringOpenclawReader struct {+ body string+ release chan struct{}+ sent bool+}++func (r *lingeringOpenclawReader) Read(p []byte) (int, error) {+ if !r.sent {+ r.sent = true+ return copy(p, r.body), nil+ }+ <-r.release+ return 0, io.EOF+}++// TestReadOpenclawStdoutCutsShortWhenCLILingers pins the half of the mechanism+// the atomicity fix must not weaken: a complete result followed by silence on a+// stream that never reaches EOF still has to return cutShort, or the caller+// never cancels and the hang this whole file exists for comes back.+//+// The counterpart, TestReadOpenclawStdoutWaitsForCompleteResult, only proves+// that a clean EOF is *not* reported as cut short; on its own it would still+// pass if the shortcut stopped firing entirely.+func TestReadOpenclawStdoutCutsShortWhenCLILingers(t *testing.T) {+ r := &lingeringOpenclawReader{+ body: completeOpenclawResult,+ release: make(chan struct{}),+ }+ // Matches the documented contract: the read goroutine is still parked in+ // r.Read on the cutShort path and exits when the caller unblocks it, which+ // in production is Execute closing stdout on cancellation.+ defer close(r.release)++ // Off the test goroutine with a bound: a regression that stopped cutting+ // short would otherwise park here until the package timeout, reporting a+ // whole-package failure instead of this assertion.+ type outcome struct {+ buf string+ cutShort bool+ err error+ }+ done := make(chan outcome, 1)+ go func() {+ buf, cutShort, err := readOpenclawStdout(r, 100*time.Millisecond)+ done <- outcome{buf: string(buf), cutShort: cutShort, err: err}+ }()++ select {+ case got := <-done:+ if got.err != nil {+ t.Fatalf("readOpenclawStdout: %v", got.err)+ }+ if !got.cutShort {+ t.Error("cutShort = false for a complete result on a stream that " ++ "never ends, want true")+ }+ if got.buf != completeOpenclawResult {+ t.Errorf("buf = %q, want the full blob", got.buf)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("readOpenclawStdout never cut short on a complete result whose " ++ "stream stays open — the caller would wait forever on a process " ++ "that has already delivered its reply")+ }+}+// TestReadOpenclawStdoutWaitsForCompleteResult pins the safety half of the// shortcut: idle output alone is not enough. Cutting off a partial buffer would// throw away work the agent has already done, which is worse than the hang this@@ -347,10 +416,14 @@ func TestReadOpenclawStdoutWaitsForCompleteResult(t *testing.T) {default:}- // Complete the blob and report EOF in the same Read. The old os.Pipe test- // performed a write and close separately, allowing the idle ticker to win- // after the bytes became parseable but before the read goroutine observed- // EOF on a loaded CI runner.+ // Complete the blob and report EOF in the same Read: the strictest shape+ // io.Reader permits, and deliberately harsher than the os/exec StdoutPipe+ // production reads, which splits the final bytes and the EOF across two+ // adjacent reads. Collapsing them into one observation is what makes the+ // assertion below deterministic — readOpenclawStdout publishes those bytes+ // and that EOF in a single critical section, so no poll can catch the+ // buffer parseable-but-not-yet-ended, whatever the runner's scheduling+ // looks like.released = trueclose(r.releaseSuffix)