Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(openclaw): parse whole buffer instead of line-by-line scanner (MUL-1908) (#2292)
Joey Frasier (Boothe)76cd8275ffad
diff --git a/server/pkg/agent/openclaw.go b/server/pkg/agent/openclaw.goindex 7b341d1f9f..92fe5ec84c 100644--- a/server/pkg/agent/openclaw.go+++ b/server/pkg/agent/openclaw.go@@ -2,6 +2,7 @@ package agentimport ("bufio"+ "bytes""context""encoding/json""fmt"@@ -14,6 +15,12 @@ import ("time")+// openclawNoParseableOutput is the canonical error string surfaced when the+// adapter cannot extract any usable JSON from a run's stdout. The exact+// phrase is depended on by external log-grep / dashboard alerts; do not+// change it without also updating those consumers.+const openclawNoParseableOutput = "openclaw returned no parseable output"+// minOpenclawVersion is the lowest openclaw version that emits its// --json result on stdout. PR #2101 swapped the adapter from reading// stderr to stdout; older builds wrote JSON to stderr and now appear@@ -284,14 +291,46 @@ type openclawEventResult struct {// log overflow and is captured separately by the caller. The stream may// contain://+// - A final result JSON (with payloads + meta) — the format openclaw 2026.5.x+// emits today, typically pretty-printed across many lines// - NDJSON streaming events (type: "text", "tool_use", "tool_result", "error",-// "step_start", "step_finish") — emitted in real time as the agent works-// - A final result JSON (with payloads + meta) — the legacy single-blob format+// "step_start", "step_finish") — supported for forward compatibility and+// other backends sharing this code path; openclaw does not emit these today//-// We scan line-by-line, emitting messages as events arrive so streaming-// consumers get real-time feedback instead of waiting for the final blob.+// Implementation note (WOR-10 follow-up): we previously scanned line-by-line+// only, then tried a whole-buffer parse in a fallback path. Under load+// (daemon shutdown racing the scanner, partial chunked reads) the line+// scanner could see truncated input that never reassembled, surfacing the+// generic "openclaw returned no parseable output" error even though the+// agent's work succeeded. We now read the full buffer first and try a+// single whole-buffer parse against the final-result schema. Only if that+// fails do we fall through to the line-by-line NDJSON scanner. This makes+// the dominant happy path (one pretty-printed JSON blob) deterministic+// while keeping NDJSON event support intact.func (b *openclawBackend) processOutput(r io.Reader, ch chan<- Message) openclawEventResult {- scanner := bufio.NewScanner(r)+ buf, readErr := io.ReadAll(r)+ if readErr != nil {+ return openclawEventResult{status: "failed", errMsg: fmt.Sprintf("read stdout: %v", readErr)}+ }++ // Whole-buffer fast path: openclaw 2026.5.x emits a single pretty-printed+ // JSON result blob. Try parsing the entire buffer (after trimming whitespace+ // and any preceding non-JSON log lines) as the final-result schema. If it+ // matches, we're done — no need to involve the line scanner at all.+ if result, ok := parseWholeBufferOpenclawResult(buf); ok {+ var output strings.Builder+ return b.buildOpenclawEventResult(result, ch, &output)+ }++ // Fall-back path: NDJSON line scanner. Note that because we already+ // drained the full buffer with io.ReadAll above, this path is no longer+ // truly streaming — events accumulate until the subprocess closes+ // stdout, then drain all at once. OpenClaw 2026.5.x does not emit+ // streaming events, so this regression is invisible today; if a future+ // backend on this code path emits real NDJSON streams and needs live+ // progress updates, we'll need to split the fast path off a streaming+ // reader instead of io.ReadAll.+ scanner := bufio.NewScanner(bytes.NewReader(buf))scanner.Buffer(make([]byte, 0, 1024*1024), 10*1024*1024)var output strings.Builder@@ -395,30 +434,20 @@ func (b *openclawBackend) processOutput(r io.Reader, ch chan<- Message) openclawreturn openclawEventResult{status: "failed", errMsg: fmt.Sprintf("read stdout: %v", err)}}- // If we got no events at all, fall back to raw output.+ // If we got no events at all, fall back to raw output. The whole-buffer+ // fast path above already tried the structured-result parse — by the time+ // we reach here the buffer truly is unstructured (just log lines, plain+ // text, or empty). Surface the trimmed text as a completed run when we+ // have any, otherwise the canonical no-parseable-output failure.if !gotEvents {- // OpenClaw may output pretty-printed (multi-line) JSON. No single line- // would parse, so try parsing the accumulated output as a whole.- // Log lines may precede the JSON, so find the first '{' at line start.trimmed := strings.TrimSpace(strings.Join(rawLines, "\n"))if trimmed != "" {- if result, ok := tryParseOpenclawResult(trimmed); ok {- return b.buildOpenclawEventResult(result, ch, &output)- }- // Log lines may precede the JSON blob. Find the first line that- // starts with '{' and try parsing from there.- for i, line := range rawLines {- if len(line) > 0 && line[0] == '{' {- candidate := strings.TrimSpace(strings.Join(rawLines[i:], "\n"))- if result, ok := tryParseOpenclawResult(candidate); ok {- return b.buildOpenclawEventResult(result, ch, &output)- }- break- }- }return openclawEventResult{status: "completed", output: trimmed}}- return openclawEventResult{status: "failed", errMsg: "openclaw returned no parseable output"}+ return openclawEventResult{+ status: "failed",+ errMsg: openclawNoParseableOutput,+ }}return openclawEventResult{@@ -431,6 +460,38 @@ func (b *openclawBackend) processOutput(r io.Reader, ch chan<- Message) openclaw}}+// parseWholeBufferOpenclawResult attempts to parse the entire stdout buffer+// as a single openclaw final-result JSON blob (the format openclaw 2026.5.x+// emits today, almost always pretty-printed across multiple lines).+//+// It first tries the buffer as-is, then strips any leading non-JSON log+// lines (lines that don't start with '{' at column 0) so a daemon log+// preamble doesn't defeat the parse. It does NOT scan into the middle of+// log lines: only line starts that begin with '{' are considered candidate+// JSON entry points, mirroring the conservative behaviour of+// tryParseOpenclawResult.+func parseWholeBufferOpenclawResult(buf []byte) (openclawResult, bool) {+ trimmed := strings.TrimSpace(string(buf))+ if trimmed == "" {+ return openclawResult{}, false+ }+ if result, ok := tryParseOpenclawResult(trimmed); ok {+ return result, true+ }+ // Strip any leading log lines that precede the JSON blob.+ lines := strings.Split(trimmed, "\n")+ for i, line := range lines {+ if len(line) > 0 && line[0] == '{' {+ candidate := strings.TrimSpace(strings.Join(lines[i:], "\n"))+ if result, ok := tryParseOpenclawResult(candidate); ok {+ return result, true+ }+ return openclawResult{}, false+ }+ }+ return openclawResult{}, false+}+// tryParseOpenclawEvent attempts to parse a line as a streaming NDJSON event.// Returns the event and true if the line is a valid event with a known type.func tryParseOpenclawEvent(line string) (openclawEvent, bool) {diff --git a/server/pkg/agent/openclaw_test.go b/server/pkg/agent/openclaw_test.goindex 2e099f6f93..72cac9594a 100644--- a/server/pkg/agent/openclaw_test.go+++ b/server/pkg/agent/openclaw_test.go@@ -1158,6 +1158,142 @@ func TestOpenclawProcessOutputModelEmptyWhenAgentMetaOmitsIt(t *testing.T) {}}+// TestOpenclawProcessOutputWholeBufferPrettyJSON is the regression test for+// the WOR-10 follow-up. Before this fix, processOutput scanned line-by-line+// and only attempted a whole-buffer parse from a fragile fallback path that+// could fail under partial / chunked reads. This test feeds a heavily+// pretty-printed result blob (deeply indented, with nested objects and+// arrays spanning many lines) through processOutput and asserts it parses+// cleanly via the new whole-buffer fast path.+func TestOpenclawProcessOutputWholeBufferPrettyJSON(t *testing.T) {+ t.Parallel()++ b := &openclawBackend{cfg: Config{Logger: slog.Default()}}+ ch := make(chan Message, 256)++ // Hand-crafted, indented JSON that exercises the multi-line path+ // every byte: opening brace alone on a line, deeply indented inner+ // keys, multi-payload array, nested agentMeta with a usage map.+ input := `{+ "payloads": [+ {+ "text": "Pretty printed answer line 1.\n"+ },+ {+ "text": "Pretty printed answer line 2."+ }+ ],+ "meta": {+ "durationMs": 9501,+ "agentMeta": {+ "sessionId": "ses_pretty_printed",+ "provider": "openrouter",+ "model": "anthropic/claude-opus-4.7",+ "usage": {+ "input": 414,+ "output": 163,+ "cacheRead": 33280,+ "cacheWrite": 0+ }+ }+ }+}+`++ res := b.processOutput(strings.NewReader(input), ch)++ if res.status != "completed" {+ t.Errorf("status: got %q, want %q", res.status, "completed")+ }+ if res.errMsg != "" {+ t.Errorf("errMsg: got %q, want empty", res.errMsg)+ }+ wantOutput := "Pretty printed answer line 1.\nPretty printed answer line 2."+ if res.output != wantOutput {+ t.Errorf("output: got %q, want %q", res.output, wantOutput)+ }+ if res.sessionID != "ses_pretty_printed" {+ t.Errorf("sessionID: got %q, want %q", res.sessionID, "ses_pretty_printed")+ }+ if res.model != "anthropic/claude-opus-4.7" {+ t.Errorf("model: got %q, want %q", res.model, "anthropic/claude-opus-4.7")+ }+ if res.usage.InputTokens != 414 {+ t.Errorf("input tokens: got %d, want 414", res.usage.InputTokens)+ }+ if res.usage.OutputTokens != 163 {+ t.Errorf("output tokens: got %d, want 163", res.usage.OutputTokens)+ }+ if res.usage.CacheReadTokens != 33280 {+ t.Errorf("cache read: got %d, want 33280", res.usage.CacheReadTokens)+ }++ close(ch)+ var msgs []Message+ for m := range ch {+ msgs = append(msgs, m)+ }+ if len(msgs) != 2 {+ t.Fatalf("expected 2 text messages, got %d", len(msgs))+ }+}++// TestOpenclawProcessOutputDeeplyIndentedFixture re-runs the recorded+// stdout fixture from openclaw 2026.5.5 specifically through the+// whole-buffer fast path. The fixture is 1070 lines of pretty-printed+// JSON — exactly the shape that misfired in production when the daemon's+// line-by-line scanner saw partial reads. Asserts the result parses on+// the first attempt without falling through to NDJSON scanning.+func TestOpenclawProcessOutputDeeplyIndentedFixture(t *testing.T) {+ t.Parallel()++ data, err := os.ReadFile("testdata/openclaw-2026.5.5-stdout.json")+ if err != nil {+ t.Fatalf("read fixture: %v", err)+ }++ // Sanity-check we're actually exercising multi-line input. If someone+ // rewrites the fixture as a single-line blob, this test stops covering+ // the bug it was written for.+ if !strings.Contains(string(data), "\n ") {+ t.Fatalf("fixture is not pretty-printed; this test must run against multi-line JSON")+ }++ result, ok := parseWholeBufferOpenclawResult(data)+ if !ok {+ t.Fatalf("parseWholeBufferOpenclawResult failed; the whole-buffer fast path is broken")+ }+ if result.Payloads == nil {+ t.Errorf("expected payloads to populate from whole-buffer parse")+ }+ if result.Meta.DurationMs == 0 {+ t.Errorf("expected meta.durationMs to populate from whole-buffer parse")+ }+}++// TestOpenclawProcessOutputEmptyBufferCanonicalError pins the empty-buffer+// failure path: the canonical "openclaw returned no parseable output"+// string is preserved verbatim so existing dashboards and log-grep tooling+// keep matching. Any change to the wording must be coordinated with those+// consumers (see the openclawNoParseableOutput constant).+func TestOpenclawProcessOutputEmptyBufferCanonicalError(t *testing.T) {+ t.Parallel()++ b := &openclawBackend{cfg: Config{Logger: slog.Default()}}+ ch := make(chan Message, 256)++ res := b.processOutput(strings.NewReader(""), ch)++ if res.status != "failed" {+ t.Errorf("status: got %q, want %q", res.status, "failed")+ }+ if res.errMsg != "openclaw returned no parseable output" {+ t.Errorf("errMsg: got %q, want canonical empty-buffer message", res.errMsg)+ }++ close(ch)+}+func countOccurrences(args []string, s string) int {n := 0for _, a := range args {