Skip to content

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

Go

fix(agent): MUL-7781 / MUL-7793 interrupt Codex turns after repeated Guardian 429s (#8934)

evan188199-tech8a2f518d5409
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index e168c38c0c..6951b03503 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -188,6 +188,59 @@ const CodexFirstTurnNoProgressMarker = "codex app-server no progress timeout"
// did not answer within the bounded handshake window.
const CodexHandshakeTimeoutMarker = "codex app-server handshake timeout"
+// CodexGuardianRateLimitMarker identifies an in-turn approval retry loop that
+// the adapter stopped after repeated reviewer failures.
+const CodexGuardianRateLimitMarker = "codex Guardian approval rate-limit circuit open"
+
+const codexGuardianRateLimitThreshold = 2
+const codexGuardianReviewDedupWindow = 32
+const codexGuardianRateLimitError = CodexGuardianRateLimitMarker + ": two consecutive Guardian approval reviews failed with 429 Too Many Requests; check completed work before continuing after the provider limit clears"
+
+type codexGuardianRateLimitCircuit struct {
+ consecutive int
+ recentReviewIDs [codexGuardianReviewDedupWindow]string
+ nextReviewIDSlot int
+ tripped bool
+}
+
+// observeReview consumes the Guardian-specific app-server notification. A
+// synthesized commandExecution item may have no output when approval fails,
+// so inspecting tool output would miss the failure we need to stop.
+func (c *codexGuardianRateLimitCircuit) observeReview(params map[string]any) bool {
+ reviewID, _ := params["reviewId"].(string)
+ review, _ := params["review"].(map[string]any)
+ if reviewID == "" || review == nil {
+ return false
+ }
+ status, _ := review["status"].(string)
+ if status == "" || status == "inProgress" {
+ return false
+ }
+ for _, recentID := range c.recentReviewIDs {
+ if reviewID == recentID {
+ return false
+ }
+ }
+ c.recentReviewIDs[c.nextReviewIDSlot] = reviewID
+ c.nextReviewIDSlot = (c.nextReviewIDSlot + 1) % len(c.recentReviewIDs)
+ rationale, _ := review["rationale"].(string)
+ lower := strings.ToLower(rationale)
+ // A policy denial carries a risk level; a reviewer failure does not. Keep
+ // the 429 signal as a narrow gate, without depending on Codex's English
+ // failure prefix (the review notification schema is unstable).
+ if status != "denied" || review["riskLevel"] != nil ||
+ (!strings.Contains(lower, "429") && !strings.Contains(lower, "too many requests")) {
+ c.consecutive = 0
+ return false
+ }
+ c.consecutive++
+ if c.consecutive < codexGuardianRateLimitThreshold || c.tripped {
+ return false
+ }
+ c.tripped = true
+ return true
+}
+
// codexResumeMarker and codexLineOverflowMarker are the two halves of the
// error text a resume-overflow produces: the method that failed (written by
// startOrResumeThread) and bufio's own ErrTooLong wording, which reaches the
@@ -1219,6 +1272,8 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
msgCh := make(chan Message, 256)
resCh := make(chan Result, 1)
semanticActivityCh := make(chan string, 256)
+ guardianRateLimitTrip := make(chan struct{}, 1)
+ var guardianRateLimitTripped atomic.Bool
var outputMu sync.Mutex
// Result.Output is "final user-facing output selected by the backend"
@@ -1250,17 +1305,25 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
}
c = &codexClient{
- cfg: b.cfg,
- stdin: stdin,
- pending: make(map[int]*pendingRPC),
- processDone: make(chan struct{}),
- handshakeTimeout: handshakeTimeout,
- threadHandshakeTimeout: threadHandshakeTimeout,
- pid: cmd.Process.Pid,
- attempt: attempt,
- activeLaunches: activeLaunches,
- notificationProtocol: "unknown",
- acceptNotification: turnNotificationGate.accept,
+ cfg: b.cfg,
+ stdin: stdin,
+ pending: make(map[int]*pendingRPC),
+ processDone: make(chan struct{}),
+ handshakeTimeout: handshakeTimeout,
+ threadHandshakeTimeout: threadHandshakeTimeout,
+ pid: cmd.Process.Pid,
+ attempt: attempt,
+ activeLaunches: activeLaunches,
+ notificationProtocol: "unknown",
+ acceptNotification: turnNotificationGate.accept,
+ guardianRateLimitCircuit: &codexGuardianRateLimitCircuit{},
+ onGuardianRateLimit: func() {
+ guardianRateLimitTripped.Store(true)
+ b.cfg.Logger.Warn("codex Guardian approval rate-limit circuit opened",
+ "task_id", b.cfg.TaskID, "runtime_id", b.cfg.RuntimeID,
+ "failure_count", codexGuardianRateLimitThreshold)
+ guardianRateLimitTrip <- struct{}{}
+ },
onDiscardedNotification: func(string, map[string]any) {
// Any app-server notification proves the process made semantic
// progress, even when it is intentionally excluded from the active
@@ -1720,6 +1783,14 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
select {
case aborted := <-turnDone:
finishTurn(aborted)
+ case <-guardianRateLimitTrip:
+ waitingForTurn = false
+ finishFirstItemWait("guardian_rate_limit")
+ finalStatus = "failed"
+ finalError = codexGuardianRateLimitError
+ if !interruptCodexTurn(c, threadID, turnDone, opts.TurnInterruptTimeout, b.cfg.Logger) {
+ stopProcess()
+ }
case activity := <-semanticActivityCh:
lastSemanticActivity = time.Now()
lastSemanticActivityDescription = activity
@@ -1804,6 +1875,12 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
}
}
}
+ // A turn/completed notification can race the circuit signal in the
+ // select above. The already-observed repeated failures still win.
+ if guardianRateLimitTripped.Load() {
+ finalStatus = "failed"
+ finalError = codexGuardianRateLimitError
+ }
duration := time.Since(startTime)
b.cfg.Logger.Info("codex finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())
@@ -2404,9 +2481,11 @@ type codexClient struct {
// onAgentMessage receives the authoritative completed text for one agent
// message. onAgentMessageChunk may deliver that text incrementally, so
// Result.Output fallbacks must use this callback rather than the last chunk.
- onAgentMessage func(text string)
- onSemanticActivity func(description string)
- onTurnDone func(aborted bool)
+ onAgentMessage func(text string)
+ onSemanticActivity func(description string)
+ onTurnDone func(aborted bool)
+ guardianRateLimitCircuit *codexGuardianRateLimitCircuit
+ onGuardianRateLimit func()
// onFinalAnswer fires only for an agent message the app-server itself
// labelled `phase: "final_answer"` — the turn's deliverable, as opposed to
// the intermediate agent messages that narrate work between tool calls.
@@ -3558,6 +3637,16 @@ func (c *codexClient) handleRawNotification(method string, params map[string]any
// Status changes are informational. Only turn/completed carries the
// authoritative terminal state for a raw-protocol turn.
+ case "item/autoApprovalReview/completed":
+ // This item notification also signals semantic progress. Preserve the
+ // existing watchdog behavior when handling it specially below.
+ c.handleItemNotification(method, params)
+ if c.guardianRateLimitCircuit != nil &&
+ c.guardianRateLimitCircuit.observeReview(params) &&
+ c.onGuardianRateLimit != nil {
+ c.onGuardianRateLimit()
+ }
+
default:
if strings.HasPrefix(method, "item/") {
c.handleItemNotification(method, params)
diff --git a/server/pkg/agent/codex_guardian_rate_limit_test.go b/server/pkg/agent/codex_guardian_rate_limit_test.go
new file mode 100644
index 0000000000..3ea2774ed7
--- /dev/null
+++ b/server/pkg/agent/codex_guardian_rate_limit_test.go
@@ -0,0 +1,128 @@
+package agent
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
+)
+
+func TestCodexGuardianRateLimitCircuitCountsDistinctParentReviews(t *testing.T) {
+ t.Parallel()
+ c, _, _ := newTestCodexClient(t)
+ c.notificationProtocol = "raw"
+ c.threadID = "parent"
+ gate := &codexTurnNotificationGate{}
+ gate.arm()
+ c.acceptNotification = gate.accept
+ c.guardianRateLimitCircuit = &codexGuardianRateLimitCircuit{}
+ trips := 0
+ c.onGuardianRateLimit = func() { trips++ }
+ activity := 0
+ c.onSemanticActivity = func(string) { activity++ }
+ c.handleLine(`{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"parent","turn":{"id":"turn-1"}}}`)
+
+ notify := func(threadID, reviewID, status, rationale string, riskLevel any) {
+ riskJSON, err := json.Marshal(riskLevel)
+ if err != nil {
+ t.Fatal(err)
+ }
+ c.handleLine(fmt.Sprintf(`{"jsonrpc":"2.0","method":"item/autoApprovalReview/completed","params":{"threadId":%q,"turnId":"turn-1","reviewId":%q,"review":{"status":%q,"rationale":%q,"riskLevel":%s}}}`,
+ threadID, reviewID, status, rationale, riskJSON))
+ }
+ limit := "Automatic approval review failed: exceeded retry limit, last status: 429 Too Many Requests"
+ notify("parent", "review-1", "denied", limit, nil)
+ notify("parent", "review-1", "denied", limit, nil) // replay of one review is one failure
+ notify("child", "review-2", "denied", limit, nil) // another thread cannot affect the parent
+ notify("parent", "review-3", "denied", "too risky: 429 requests found", "high")
+ notify("parent", "review-4", "denied", "reviewer unavailable: 429 Too Many Requests", nil)
+ if trips != 0 {
+ t.Fatalf("a policy denial must break the consecutive 429 sequence even when its rationale contains 429, got %d trips", trips)
+ }
+ notify("parent", "review-1", "denied", limit, nil) // nonadjacent replay must not count again
+ if trips != 0 {
+ t.Fatalf("a replayed review must not trip the circuit, got %d trips", trips)
+ }
+ notify("parent", "review-5", "denied", limit, nil)
+ notify("parent", "review-5", "denied", limit, nil)
+ if trips != 1 {
+ t.Fatalf("distinct parent review failures should trip exactly once, got %d", trips)
+ }
+ if activity != 7 {
+ t.Fatalf("parent review notifications should preserve semantic activity, got %d signals", activity)
+ }
+}
+
+func TestCodexGuardianRateLimitCircuitInterruptsRepeatedApprovalFailures(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ interruptMarker := filepath.Join(t.TempDir(), "interrupt")
+ fakePath := writeFakeCodexAppServer(t, ""+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"+
+ `read line`+"\n"+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-guardian"}}}'`+"\n"+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-guardian","turn":{"id":"turn-guardian"}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"item/autoApprovalReview/completed","params":{"threadId":"thr-guardian","turnId":"turn-guardian","reviewId":"review-1","review":{"status":"denied","rationale":"Automatic approval review failed: exceeded retry limit, last status: 429 Too Many Requests","riskLevel":null}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-guardian","turnId":"turn-guardian","item":{"type":"commandExecution","id":"cmd-1","status":"declined","aggregatedOutput":null}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"item/autoApprovalReview/completed","params":{"threadId":"thr-guardian","turnId":"turn-guardian","reviewId":"review-2","review":{"status":"denied","rationale":"Automatic approval review failed: exceeded retry limit, last status: 429 Too Many Requests","riskLevel":null}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-guardian","turnId":"turn-guardian","item":{"type":"commandExecution","id":"cmd-2","status":"declined","aggregatedOutput":null}}}'`+"\n"+
+ `read line`+"\n"+
+ `echo interrupted > `+interruptMarker+"\n"+
+ `echo '{"jsonrpc":"2.0","id":4,"result":{}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr-guardian","turn":{"id":"turn-guardian","status":"cancelled"}}}'`+"\n")
+
+ result, _ := executeFakeCodexCollectingMessages(t, fakePath, ExecOptions{
+ Timeout: 5 * time.Second,
+ TurnInterruptTimeout: 200 * time.Millisecond,
+ }, 3*time.Second)
+ if result.Status != "failed" || !strings.Contains(result.Error, "429") || !strings.Contains(result.Error, "Guardian") {
+ t.Fatalf("repeated approval failures must stop as a visible rate-limit failure, got %+v", result)
+ }
+ if !strings.Contains(result.Error, "check completed work before continuing") {
+ t.Fatalf("rate-limit failure must explain how to continue safely, got %q", result.Error)
+ }
+ if reason := taskfailure.Classify(result.Error); reason != taskfailure.ReasonAgentProviderCapacityOrRateLimit {
+ t.Fatalf("circuit result classified as %q, want provider rate limit", reason)
+ }
+ if _, err := os.Stat(interruptMarker); err != nil {
+ t.Fatalf("Codex turn was not interrupted after the second approval failure: %v", err)
+ }
+}
+
+func TestCodexGuardianRateLimitCircuitKeepsSingleFailureVisible(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ fakePath := writeFakeCodexAppServer(t, ""+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"+
+ `read line`+"\n"+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-single"}}}'`+"\n"+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-single","turn":{"id":"turn-single"}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"item/autoApprovalReview/completed","params":{"threadId":"thr-single","turnId":"turn-single","reviewId":"review-1","review":{"status":"denied","rationale":"Automatic approval review failed: exceeded retry limit, last status: 429 Too Many Requests","riskLevel":null}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"item/autoApprovalReview/completed","params":{"threadId":"thr-single","turnId":"turn-single","reviewId":"review-2","review":{"status":"approved","rationale":"safe","riskLevel":"low"}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"item/autoApprovalReview/completed","params":{"threadId":"thr-single","turnId":"turn-single","reviewId":"review-3","review":{"status":"denied","rationale":"Automatic approval review failed: exceeded retry limit, last status: 429 Too Many Requests","riskLevel":null}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-single","turnId":"turn-single","item":{"type":"agentMessage","id":"msg-1","text":"Done","phase":"final_answer"}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr-single","turn":{"id":"turn-single","status":"completed"}}}'`+"\n")
+
+ result := executeFakeCodex(t, fakePath, ExecOptions{Timeout: 5 * time.Second})
+ if result.Status != "completed" || result.Output != "Done" {
+ t.Fatalf("nonconsecutive Guardian failures must not stop a completed turn, got %+v", result)
+ }
+}