Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7869: fix(agent): fail kimi runs whose wire log records a failed turn (#9057)
小七5063fc90794f
diff --git a/server/pkg/agent/kimi.go b/server/pkg/agent/kimi.goindex 154334a629..92cb5d66d1 100644--- a/server/pkg/agent/kimi.go+++ b/server/pkg/agent/kimi.go@@ -1,9 +1,11 @@package agentimport (+ "bufio""bytes""context""encoding/json"+ "errors""fmt""io""os"@@ -520,6 +522,31 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio}}+ // kimi's own wire log is authoritative on turn outcome: its ACP+ // adapter can answer session/prompt successfully while the turn's+ // `agent.turn.ended` record says failed — a bare+ // "OAuthConnectionError: ..." carries none of the stderr sniffer's+ // terminal signatures (#9054). Without this flip the run publishes+ // its partial narration as a successfully delivered result and the+ // retry/continuation policy never sees the failure. Only a+ // completed run is promoted: timeout/abort/already-failed keep+ // their own terminal semantics.+ if finalStatus == "completed" {+ if turnErr, failed := scanKimiMainTurnFailure(kimiUsageScan{+ startTime: startTime,+ kimiHome: b.cfg.Env["KIMI_CODE_HOME"],+ sessionID: sessionID,+ resumed: opts.ResumeSessionID != "",+ fallbackModel: fallbackModel,+ }); failed {+ finalStatus = "failed"+ finalError = "kimi turn failed"+ if turnErr != "" {+ finalError = fmt.Sprintf("kimi turn failed: %s", turnErr)+ }+ }+ }+resCh <- Result{Status: finalStatus,Output: finalOutput,@@ -759,6 +786,93 @@ func kimiWireRecordInTurn(recordTimeMillis int64, startTime time.Time, resumed breturn recordTimeMillis >= startTime.UnixMilli()}+// kimiTurnEndedRecordType is the wire record kimi-code appends when a turn+// terminates, with its own verdict in `outcome`.+const kimiTurnEndedRecordType = "agent.turn.ended"++// kimiWireTurnEnd is the parsed shape of one `agent.turn.ended` record.+// Turn ids alternate between number and string across kimi builds, so they+// are deliberately not modeled — only the outcome and diagnostic matter.+type kimiWireTurnEnd struct {+ Type string `json:"type"`+ Outcome string `json:"outcome"`+ ErrorMessage string `json:"errorMessage"`+ Time int64 `json:"time"`+}++// scanKimiMainTurnFailure reports whether the main agent's wire log recorded+// a failed turn for this run, carrying kimi's own diagnostic message. It+// reads the same wire logs with the same turn-boundary rules as+// scanKimiSessionUsage, and only the structured `outcome:"failed"` verdict+// counts — conversation text merely echoing failure words must not flip a+// healthy run (see the anchoring lesson in #7920). A delegated agent's+// failed turn is that agent's own task path; only the main agent's terminal+// event fails this run.+func scanKimiMainTurnFailure(scan kimiUsageScan) (string, bool) {+ root := kimiSessionRoot(scan.kimiHome)+ if root == "" {+ return "", false+ }+ for _, path := range kimiSessionWireLogs(root, scan.sessionID) {+ if filepath.Base(filepath.Dir(path)) != "main" {+ continue+ }+ if detail, failed := kimiWireTurnFailure(path, scan); failed {+ return detail, true+ }+ }+ return "", false+}++// kimiWireTurnFailure walks one wire log for a failed main turn. A malformed+// or truncated line is skipped: the log is appended to live, so reporting+// what is readable beats failing the scan (same policy as the usage scan).+// A record beyond the scan bound is discarded rather than ending the walk —+// an oversized context.append ahead of the terminal event must not hide the+// failed outcome (review on #9057).+func kimiWireTurnFailure(path string, scan kimiUsageScan) (string, bool) {+ file, err := os.Open(path)+ if err != nil {+ return "", false+ }+ defer file.Close()++ detail := ""+ found := false+ reader := bufio.NewReaderSize(file, agentStreamInitialBufferBytes)+ for {+ line, err := readAgentStreamLine(reader)+ if err != nil && !errors.Is(err, bufio.ErrTooLong) && !errors.Is(err, io.EOF) {+ // Any other read failure ends the walk; the records read so+ // far are the answer (same best-effort policy as a truncated+ // tail above).+ break+ }+ if line != nil && bytes.Contains(line, []byte(kimiTurnEndedRecordType)) {+ var record kimiWireTurnEnd+ if err := json.Unmarshal(line, &record); err != nil || record.Type != kimiTurnEndedRecordType {+ continue+ }+ if !kimiWireRecordInTurn(record.Time, scan.startTime, scan.resumed) {+ continue+ }+ if record.Outcome == "failed" {+ // kimi's diagnostic is provider-authored text: a JSON+ // credential in it (request={"api_key":...}) survives both+ // the raw string and the shared redact.Text, so it takes+ // the same sanitize pass as every child-process diagnostic+ // before this reaches Result.Error (review on #9057).+ detail = sanitizeAgentDiagnostic(record.ErrorMessage)+ found = true+ }+ }+ if errors.Is(err, io.EOF) {+ break+ }+ }+ return detail, found+}+// kimiSessionRoot resolves kimi's session directory: an explicitly configured// home first, then the ambient KIMI_CODE_HOME, then ~/.kimi-code. Mirrors// codexSessionRoot.diff --git a/server/pkg/agent/kimi_test.go b/server/pkg/agent/kimi_test.goindex 7bcb365040..aeed36adda 100644--- a/server/pkg/agent/kimi_test.go+++ b/server/pkg/agent/kimi_test.go@@ -1587,3 +1587,290 @@ func TestKimiSessionWireLogsRejectsTraversal(t *testing.T) {}}}++// kimiWireTurnEndedLine builds an `agent.turn.ended` wire record like the ones+// kimi-code appends to agents/main/wire.jsonl when a turn terminates.+func kimiWireTurnEndedLine(outcome, errorMessage string, at time.Time) string {+ return fmt.Sprintf(`{"turnId":0,"outcome":%q,"errorMessage":%q,"type":"agent.turn.ended","time":%d,"kind":"event"}`,+ outcome, errorMessage, at.UnixMilli())+}++// TestScanKimiMainTurnFailureFlipsOnFailedTerminalEvent covers #9054: kimi's+// ACP adapter answered session/prompt successfully while its own wire log+// recorded the main turn as failed (a bare OAuthConnectionError no stderr+// sniffer signature matches). The persisted outcome is authoritative.+func TestScanKimiMainTurnFailureFlipsOnFailedTerminalEvent(t *testing.T) {+ t.Parallel()++ home := t.TempDir()+ now := time.Now()+ writeKimiWireLog(t, home, "session_kf", "main",+ `{"type":"metadata","protocol_version":"1"}`,+ kimiWireTurnEndedLine("failed",+ "OAuthConnectionError: OAuth request to https://auth.kimi.com/api/oauth/token failed: fetch failed: Connect Timeout Error",+ now),+ )++ detail, failed := scanKimiMainTurnFailure(kimiUsageScan{+ startTime: now.Add(-time.Minute), kimiHome: home,+ sessionID: "session_kf", fallbackModel: "unknown",+ })+ if !failed {+ t.Fatal("expected the failed main-agent terminal event to be reported")+ }+ if !strings.Contains(detail, "OAuthConnectionError") {+ t.Errorf("detail should carry kimi's diagnostic, got %q", detail)+ }+}++// TestScanKimiMainTurnFailureSanitizesWireDiagnostic covers the review on+// #9057: kimi's diagnostic is provider-authored text, and a JSON credential+// embedded in it (request={"api_key":...}) survives both the raw string and+// the shared redact.Text — the diagnostic must take the same+// sanitizeAgentDiagnostic pass as every child-process diagnostic that+// reaches Result.Error.+func TestScanKimiMainTurnFailureSanitizesWireDiagnostic(t *testing.T) {+ t.Parallel()++ home := t.TempDir()+ now := time.Now()+ const fakeSecret = "review-only-fake-secret"+ writeKimiWireLog(t, home, "session_secret", "main",+ kimiWireTurnEndedLine("failed",+ `request={"api_key":"`+fakeSecret+`"} while calling https://api.kimi.com`,+ now),+ )++ detail, failed := scanKimiMainTurnFailure(kimiUsageScan{+ startTime: now.Add(-time.Minute), kimiHome: home,+ sessionID: "session_secret", fallbackModel: "unknown",+ })+ if !failed {+ t.Fatal("expected the failed main-agent terminal event to be reported")+ }+ if strings.Contains(detail, fakeSecret) {+ t.Errorf("secret leaked through the wire diagnostic: %q", detail)+ }+ if !strings.Contains(detail, `api_key":"[REDACTED]"`) {+ t.Errorf("expected the JSON secret field redacted, got %q", detail)+ }+}++// TestScanKimiMainTurnFailureIgnoresHealthyStaleAndDelegated guards the flip+// against false positives: a successful main turn stays completed, a failed+// record from a previous task on a resumed session is outside the turn+// boundary, and a delegated agent's failure is that agent's own task path —+// only the main agent's terminal event fails the run.+func TestScanKimiMainTurnFailureIgnoresHealthyStaleAndDelegated(t *testing.T) {+ t.Parallel()++ home := t.TempDir()+ now := time.Now()++ writeKimiWireLog(t, home, "session_ok", "main", kimiWireTurnEndedLine("success", "", now))+ writeKimiWireLog(t, home, "session_del", "main", kimiWireTurnEndedLine("success", "", now))+ writeKimiWireLog(t, home, "session_del", "researcher", kimiWireTurnEndedLine("failed", "delegated boom", now))+ writeKimiWireLog(t, home, "session_stale", "main", kimiWireTurnEndedLine("failed", "stale boom", now.Add(-time.Hour)))++ for _, tc := range []struct {+ sessionID string+ resumed bool+ }{+ {sessionID: "session_ok"},+ {sessionID: "session_del"},+ {sessionID: "session_stale", resumed: true},+ } {+ if _, failed := scanKimiMainTurnFailure(kimiUsageScan{+ startTime: now.Add(-time.Minute), kimiHome: home,+ sessionID: tc.sessionID, resumed: tc.resumed, fallbackModel: "unknown",+ }); failed {+ t.Errorf("session %q: expected no main-turn failure", tc.sessionID)+ }+ }+}++// TestScanKimiMainTurnFailureReadsPastOversizedRecord covers the review on+// #9057: newAgentStreamScanner stops for good at a line beyond+// agentStreamMaxLineBytes and the old scan loop never checked scanner.Err(),+// so a valid but oversized context.append record ahead of the terminal event+// hid the failed outcome and kept the run completed. The scan must discard+// the oversized record and keep reading.+func TestScanKimiMainTurnFailureReadsPastOversizedRecord(t *testing.T) {+ t.Parallel()++ home := t.TempDir()+ now := time.Now()+ oversized := `{"type":"context.append","content":"` + strings.Repeat("x", agentStreamMaxLineBytes) + `"}`+ writeKimiWireLog(t, home, "session_big", "main",+ oversized,+ kimiWireTurnEndedLine("failed", "boom after the oversized record", now),+ )++ detail, failed := scanKimiMainTurnFailure(kimiUsageScan{+ startTime: now.Add(-time.Minute), kimiHome: home,+ sessionID: "session_big", fallbackModel: "unknown",+ })+ if !failed {+ t.Fatal("expected the failed terminal event past the oversized record to be reported")+ }+ if !strings.Contains(detail, "boom after the oversized record") {+ t.Errorf("detail should carry the diagnostic, got %q", detail)+ }+}++// TestScanKimiMainTurnFailureWithoutWireLog: no session directory (scan ran+// before kimi wrote anything, or the home is unset) must be a no-op.+func TestScanKimiMainTurnFailureWithoutWireLog(t *testing.T) {+ t.Parallel()++ if _, failed := scanKimiMainTurnFailure(kimiUsageScan{+ startTime: time.Now().Add(-time.Minute), kimiHome: t.TempDir(),+ sessionID: "session_absent", fallbackModel: "unknown",+ }); failed {+ t.Fatal("expected no failure without a wire log")+ }+}++// fakeKimiWireTurnFailureScript mimics the #9054 incident shape: the ACP+// layer answers session/prompt successfully (end_turn) after emitting real+// narration, while kimi's own wire log records the main turn as failed with+// a bare OAuthConnectionError that matches no stderr sniffer signature.+func fakeKimiWireTurnFailureScript(sessionID string) string {+ script := `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"+ ;;+ *'"method":"session/new"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_wirefail"}}\n' "$id"+ ;;+ *'"method":"session/prompt"'*)+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_wirefail","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"partial narration before the failure"}}}}\n'+ dir="$KIMI_CODE_HOME/sessions/wd_test_abc123/ses_wirefail/agents/main"+ mkdir -p "$dir"+ # time:0 = untimed record; kimiWireRecordInTurn counts those on fresh+ # runs, and a shell cannot produce millisecond timestamps portably.+ printf '{"turnId":0,"outcome":"failed","errorMessage":"OAuthConnectionError: OAuth request to https://auth.kimi.com/api/oauth/token failed: fetch failed: Connect Timeout Error","type":"agent.turn.ended","time":0,"kind":"event"}\n' >> "$dir/wire.jsonl"+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"+ exit 0+ ;;+ esac+done+`+ return strings.ReplaceAll(script, "ses_wirefail", sessionID)+}++// TestKimiBackendWireTurnFailureFailsCompletedRun is the end-to-end guard for+// #9054: a successful ACP prompt response with nonempty narration must not+// publish the run as completed when kimi's wire log says the main turn+// failed. The partial narration stays in the transcript; the status and the+// sanitized diagnostic must reach the daemon so retry policy sees the truth.+func TestKimiBackendWireTurnFailureFailsCompletedRun(t *testing.T) {+ t.Parallel()++ home := t.TempDir()+ fakePath := filepath.Join(t.TempDir(), "kimi")+ writeTestExecutable(t, fakePath, []byte(fakeKimiWireTurnFailureScript("ses_wirefail")))++ backend, err := New("kimi", Config{+ ExecutablePath: fakePath,+ Logger: slog.Default(),+ Env: map[string]string{"KIMI_CODE_HOME": home},+ })+ if err != nil {+ t.Fatalf("new kimi backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{Timeout: 5 * time.Second})+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ select {+ case result, ok := <-session.Result:+ if !ok {+ t.Fatal("result channel closed without a value")+ }+ if result.Status != "failed" {+ t.Fatalf("expected status=failed from the wire turn outcome, got %q (error=%q)", result.Status, result.Error)+ }+ if !strings.Contains(result.Error, "OAuthConnectionError") {+ t.Errorf("expected kimi's diagnostic in the error, got %q", result.Error)+ }+ if !strings.Contains(result.Output, "partial narration") {+ t.Errorf("partial narration should stay in the transcript, got %q", result.Output)+ }+ if result.ResumeRejected {+ t.Error("an OAuth transport failure is not a poisoned history; ResumeRejected must stay false")+ }+ case <-time.After(10 * time.Second):+ t.Fatal("timeout waiting for result")+ }+}++// TestKimiBackendWireTurnFailurePastOversizedRecord reproduces the review's+// offline repro on #9057: a valid context.append record at the scan's 32 MiB+// bound sits ahead of the failed agent.turn.ended record. With the old+// scanner loop — which stops for good at an over-bound line and never checks+// scanner.Err() — the backend reported Status="completed", Error="".+func TestKimiBackendWireTurnFailurePastOversizedRecord(t *testing.T) {+ t.Parallel()++ home := t.TempDir()+ dir := filepath.Join(home, "sessions", "wd_test_abc123", "ses_big", "agents", "main")+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatalf("mkdir wire log dir: %v", err)+ }+ oversized := `{"type":"context.append","content":"` + strings.Repeat("x", agentStreamMaxLineBytes) + `"}`+ if err := os.WriteFile(filepath.Join(dir, "wire.jsonl"), []byte(oversized+"\n"), 0o644); err != nil {+ t.Fatalf("write oversized record: %v", err)+ }++ fakePath := filepath.Join(t.TempDir(), "kimi")+ writeTestExecutable(t, fakePath, []byte(fakeKimiWireTurnFailureScript("ses_big")))++ backend, err := New("kimi", Config{+ ExecutablePath: fakePath,+ Logger: slog.Default(),+ Env: map[string]string{"KIMI_CODE_HOME": home},+ })+ if err != nil {+ t.Fatalf("new kimi backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{Timeout: 5 * time.Second})+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ select {+ case result, ok := <-session.Result:+ if !ok {+ t.Fatal("result channel closed without a value")+ }+ if result.Status != "failed" {+ t.Fatalf("expected status=failed past the oversized record, got %q (error=%q)", result.Status, result.Error)+ }+ if !strings.Contains(result.Error, "OAuthConnectionError") {+ t.Errorf("expected kimi's diagnostic in the error, got %q", result.Error)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("timeout waiting for result")+ }+}diff --git a/server/pkg/agent/stream_scanner.go b/server/pkg/agent/stream_scanner.goindex ec94e2d79e..f8f87a4710 100644--- a/server/pkg/agent/stream_scanner.go+++ b/server/pkg/agent/stream_scanner.go@@ -2,6 +2,7 @@ package agentimport ("bufio"+ "errors""io")@@ -34,3 +35,58 @@ func newAgentStreamScanner(r io.Reader) *bufio.Scanner {scanner.Buffer(make([]byte, 0, agentStreamInitialBufferBytes), agentStreamMaxLineBytes)return scanner}++// readAgentStreamLine reads the next newline-delimited record from r and+// returns it without the newline (a single trailing '\r' is dropped, like+// bufio.Scanner's line splitting). It is the log-walking companion to+// newAgentStreamScanner for scans that read a session's persisted stream+// after the fact: where the Scanner ends its scan for good once a line+// passes agentStreamMaxLineBytes, readAgentStreamLine consumes and discards+// that record whole and returns bufio.ErrTooLong with r positioned after it,+// so later records stay readable — an oversized record must not hide the+// records behind it. A final unterminated line (a live log's partial-write+// tail) is returned whole, like Scanner does. The returned line is non-nil+// only when err is nil; an exhausted reader returns io.EOF. Any other read+// error is returned as-is.+func readAgentStreamLine(r *bufio.Reader) ([]byte, error) {+ var line []byte+ discard := false+ for {+ chunk, err := r.ReadSlice('\n')+ if err == bufio.ErrBufferFull {+ if !discard {+ line = append(line, chunk...)+ if discard = len(line) > agentStreamMaxLineBytes; discard {+ line = nil // one record must not pin the bound in memory+ }+ }+ continue+ }+ if err != nil {+ if !errors.Is(err, io.EOF) {+ return nil, err+ }+ if discard {+ return nil, bufio.ErrTooLong+ }+ if tail := append(line, chunk...); len(tail) > 0 {+ if len(tail) > agentStreamMaxLineBytes {+ return nil, bufio.ErrTooLong+ }+ return tail, nil+ }+ return nil, io.EOF+ }+ if discard {+ return nil, bufio.ErrTooLong+ }+ line = append(line, chunk[:len(chunk)-1]...)+ if len(line) > agentStreamMaxLineBytes {+ return nil, bufio.ErrTooLong+ }+ if n := len(line); n > 0 && line[n-1] == '\r' {+ line = line[:n-1]+ }+ return line, nil+ }+}diff --git a/server/pkg/agent/stream_scanner_test.go b/server/pkg/agent/stream_scanner_test.goindex e073717b03..584bada394 100644--- a/server/pkg/agent/stream_scanner_test.go+++ b/server/pkg/agent/stream_scanner_test.go@@ -3,6 +3,7 @@ package agentimport ("bufio""errors"+ "io""strings""testing")@@ -51,3 +52,44 @@ func TestAgentStreamScannerStillFailsClosedAboveCap(t *testing.T) {t.Fatalf("expected bufio.ErrTooLong, got %v", err)}}++// TestReadAgentStreamLineSkipsOversizedAndContinues covers the review on+// #9057: the log-walking companion to newAgentStreamScanner must do what+// the Scanner cannot — discard a record beyond agentStreamMaxLineBytes and+// keep the later records readable.+func TestReadAgentStreamLineSkipsOversizedAndContinues(t *testing.T) {+ t.Parallel()++ oversized := strings.Repeat("x", agentStreamMaxLineBytes+16)+ r := bufio.NewReaderSize(strings.NewReader(oversized+"\nafter\n"), agentStreamInitialBufferBytes)++ line, err := readAgentStreamLine(r)+ if line != nil || !errors.Is(err, bufio.ErrTooLong) {+ t.Fatalf("expected ErrTooLong with no line, got %d bytes err=%v", len(line), err)+ }+ line, err = readAgentStreamLine(r)+ if err != nil || string(line) != "after" {+ t.Fatalf("expected the record after the oversized one, got %q err=%v", line, err)+ }+ if _, err := readAgentStreamLine(r); !errors.Is(err, io.EOF) {+ t.Fatalf("expected io.EOF after the last record, got %v", err)+ }+}++// TestReadAgentStreamLineReturnsUnterminatedTail: a live log can end+// mid-write; the final unterminated line is still returned, matching+// bufio.Scanner's behavior, and an exhausted reader reports io.EOF.+func TestReadAgentStreamLineReturnsUnterminatedTail(t *testing.T) {+ t.Parallel()++ r := bufio.NewReaderSize(strings.NewReader("first\npartial-tail"), agentStreamInitialBufferBytes)+ if line, err := readAgentStreamLine(r); err != nil || string(line) != "first" {+ t.Fatalf("expected the first line, got %q err=%v", line, err)+ }+ if line, err := readAgentStreamLine(r); err != nil || string(line) != "partial-tail" {+ t.Fatalf("expected the unterminated tail, got %q err=%v", line, err)+ }+ if _, err := readAgentStreamLine(r); !errors.Is(err, io.EOF) {+ t.Fatalf("expected io.EOF, got %v", err)+ }+}