Repository navigation
fix(agent-core): bound runaway loops with turn/error-batch/idle-repeat guards (#120962) - #121063
Papilionidae wants to merge 1 commit into
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs real behavior proof before merge. What this changesThis PR adds opt-in limits on assistant turns, consecutive all-error tool batches, and repeated tool calls across native sessions and remote workers. Example: An operator sets maxIdleRepeatCalls to 3, and query_mam_status repeatedly returns HTTP 429 inside successful tool output.
Review scores
ProductKind: Feature · Worth it: Needs a maintainer decision · Fix scope: Complete Merge readiness⛔ Blocked before merge - 10 items remain Keep open: this PR contains distinct, maintainer-engaged work that current main does not fully replace, but five previously reported defects remain. Priority: P2 Decision needed
Before merge
Findings
Provenance
Tests
Agent review detailsHow this fits togetherAgent-core drives provider responses and tool execution; resolved operator settings enter through session factories or worker launch assignments, and guard termination leaves transcript events and a user-visible message. flowchart TD
A[Operator configuration] --> B[Loop configuration resolver]
B --> C[Native session factory]
B --> D[Worker capability fence]
D --> E[Worker launch assignment]
E --> C
C --> F[Agent core run loop]
F --> G[Transcript and terminal message]
Technical reviewBest possible solution: Have the loop-policy owner choose the remaining cutoff contract, then implement it through existing loop and queue owners with correct streamed-response accounting. Do we have a high-confidence way to reproduce the issue? Source establishes the missing general budgets and the introduced queue/accounting failures; no current-main execution of the historical masked-429 incident was performed. Is this the best way to solve the issue? Hard budgets can bound work, but the new policy needs owner sponsorship and the implementation must preserve single queue ownership and account for all streamed tool fragments. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 69eefd48c800. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +676, Tests +2476, Docs +136, Generated 0. Total +3288 across 43 files. Added test files: 7. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (53 earlier review cycles; latest 8 shown)
Reviewed October 17, 2026, 6:42 PM ET / 22:42 UTC (Revision 54). |
|
@clawsweeper re-review The P1 finding is resolved: Rebased on The CI failure on the previous head ( |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review Shiny media proof attached: focused test run output showing the idle-repeat guard terminating a real AgentSession transport run after 3 repeated calls (no 4th provider request), plus all 23 agent-loop guard tests passing. Rebased on The CI failure on the previous head was |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review Rebased on Proof artifact — focused test run output: The transport test exercises a real CI note: The failure on the previous head ( |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review P3 finding resolved: all stale "built-in default" / "200/3/3" wording replaced with the explicit configured-value activation rule across 6 files:
Rebased on |
|
🦞🧹 I asked ClawSweeper to review this item again. |
|
@clawsweeper re-review P2 finding resolved: removed the unsupported maintainer-approval assertion from Rebased on |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review Both findings resolved:
All tests pass. Format/lint clean. |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review Head
Rebased on |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
…t guards (openclaw#120962) Add opt-in runLoop guards (maxTurns, maxConsecutiveErrorBatches, maxIdleRepeatCalls) to the native agent loop, configuration resolver, session factories, and worker launch contract. Guards are opt-in: configless and enabled:false sessions preserve pre-guard behavior. The launch-time fence requires the loop-guard worker capability only for guard-enabled turns, so legacy bundles can still serve guard-off turns. Recovery does not reclaim workers solely for lacking the loop-guard capability — the launcher decides per turn. [AI-assisted]
|
@clawsweeper review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
LamplighterPaul
left a comment
There was a problem hiding this comment.
Tested this at head 077fc8a because it targets exactly the failure I reported in #110337 (comment: #110337 (comment)): one rejected sessions patch re-sent 223 times over 36 minutes with loop detection unset.
What I ran (isolated container, no network, Node 24, vitest 5, pnpm install --frozen-lockfile on the branch):
| Suite | Result |
|---|---|
packages/agent-core/src/agent-loop.guard.test.ts |
23/23 pass |
src/agents/tool-loop-detection-config.test.ts |
9/9 pass |
| added regression test mirroring the #110337 shape (below) | 3/3 pass |
The regression test drives Agent with a sessions tool that throws the real ToolInputError text and a stream that re-issues the identical call 25 times:
| Config | Tool executions | Provider requests | Ends with |
|---|---|---|---|
| no guard keys | 25 | 26 | model's own text |
maxIdleRepeatCalls: 5 |
5 | 5 | terminal "identical arguments 5 times in a row" |
maxConsecutiveErrorBatches: 4 |
4 | 4 | terminal "ended in errors" |
So the guards do stop this shape, and the unguarded row shows the baseline. Happy to push the test onto the branch if you enable maintainer edits, or open it against your fork.
CI is red for a reason inside the PR: check-prod-types fails on
src/worker/embedded-agent.runtime.ts(38,10): error TS6133: 'getProcessSupervisor' is declared but its value is never read.
That import is added by this PR and unused in the file. The other lanes look like the same run cascading. The branch is also ~2600 commits behind main, so a rebase is needed before maintainers can evaluate it.
One design comment, non-blocking: with only tools.loopDetection.enabled: true, none of the three guards engage (resolveLoopGuardRuntimeConfig returns all-undefined). I understand the upgrade-contract reasoning, but it means the #110337 shape still runs to exhaustion under this PR unless the operator knows to set a key. An identical call that returns an identical error is deterministic, so a conservative default for maxIdleRepeatCalls when enabled is true (or at least a documented recommended value) would make the fix reach the people it's for. Maintainers' call.
Regression test (packages/agent-core/src/agent-loop.guard.incident.test.ts)
// Reproduces openclaw/openclaw#110337 (comment 2026-09-11): a model re-sent one
// rejected `sessions` patch (ToolInputError) 223 times in a run. Checks the PR
// guards stop that shape, and shows the unguarded baseline for contrast.
import { Type } from "typebox";
import { describe, expect, it } from "vitest";
import { Agent } from "./agent.js";
import {
type AssistantMessage,
createAssistantMessageEventStream,
type Message,
type Model,
} from "./llm.js";
import type { AgentMessage, AgentTool, StreamFn } from "./types.js";
const model: Model = {
id: "test-model",
name: "Test Model",
api: "test-api",
provider: "test-provider",
baseUrl: "https://example.test",
reasoning: false,
input: ["text"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 1000,
maxTokens: 1000,
};
const TEST_USAGE = {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
totalTokens: 0,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
};
const REJECTION =
"targets is only valid for patch and cannot be combined with sessionKey or expectedSessionId";
// The exact shape the model sent (redacted ids): top-level session AND a
// one-entry targets array for the same session, every optional field emptied.
const INCIDENT_ARGS = {
action: "patch",
sessionKey: "agent:main:dashboard:11111111-1111-1111-1111-111111111111",
targets: [
{
sessionKey: "agent:main:dashboard:11111111-1111-1111-1111-111111111111",
expectedSessionId: "22222222-2222-2222-2222-222222222222",
},
],
expectedSessionId: "22222222-2222-2222-2222-222222222222",
deleteTranscript: true,
label: "OpenClaw Android",
icon: "",
color: "",
group: null,
statusNote: "",
attention: "clear",
ttlMinutes: 30,
pinned: false,
archived: false,
model: "",
thinkingLevel: "",
ownerType: "agent",
ownerId: "",
names: [],
name: "",
to: "",
};
function rejectingSessionsTool(calls: { count: number }): AgentTool {
return {
name: "sessions",
label: "Sessions",
description: "sessions",
parameters: Type.Any(),
execute: async () => {
calls.count += 1;
throw new Error(REJECTION);
},
};
}
function makeStream(turns: AssistantMessage["content"][], requests: Message[][]): StreamFn {
let turnIndex = 0;
return (_activeModel, context) => {
requests.push(context.messages.slice());
const content = turns[turnIndex];
turnIndex += 1;
if (!content) {
throw new Error(`unexpected provider request ${turnIndex}`);
}
const stream = createAssistantMessageEventStream();
queueMicrotask(() => {
const message: AssistantMessage = {
role: "assistant",
content,
api: "test-api",
provider: "test-provider",
model: "test-model",
usage: TEST_USAGE,
stopReason: content.some((item) => item.type === "toolCall") ? "toolUse" : "stop",
timestamp: 1,
};
stream.push({ type: "done", reason: message.stopReason === "toolUse" ? "toolUse" : "stop", message });
stream.end();
});
return stream;
};
}
function identicalRejectedTurns(n: number): AssistantMessage["content"][] {
const turns: AssistantMessage["content"][] = [];
for (let i = 1; i <= n; i += 1) {
turns.push([{ type: "toolCall", id: `call-${i}`, name: "sessions", arguments: INCIDENT_ARGS }]);
}
turns.push([{ type: "text", text: "gave up" }]);
return turns;
}
function lastAssistantText(messages: AgentMessage[]): string {
const last = messages.at(-1);
if (!last || last.role !== "assistant") {
return "";
}
return last.content
.filter((part): part is Extract<typeof part, { type: "text" }> => part.type === "text")
.map((part) => part.text)
.join("");
}
describe("incident #110337: identical rejected sessions patch", () => {
it("baseline without guards: every identical rejected call is executed", async () => {
const requests: Message[][] = [];
const calls = { count: 0 };
const agent = new Agent({
initialState: { model, systemPrompt: "", tools: [rejectingSessionsTool(calls)] },
streamFn: makeStream(identicalRejectedTurns(25), requests),
});
await agent.prompt("OpenClaw Android is enough");
expect(calls.count).toBe(25);
expect(requests).toHaveLength(26);
expect(lastAssistantText(agent.state.messages)).toBe("gave up");
});
it("maxIdleRepeatCalls stops the identical rejected call after N turns", async () => {
const requests: Message[][] = [];
const calls = { count: 0 };
const agent = new Agent({
initialState: { model, systemPrompt: "", tools: [rejectingSessionsTool(calls)] },
streamFn: makeStream(identicalRejectedTurns(25), requests),
maxIdleRepeatCalls: 5,
});
await agent.prompt("OpenClaw Android is enough");
expect(calls.count).toBe(5);
expect(requests).toHaveLength(5);
expect(agent.state.messages.at(-1)).toMatchObject({ role: "assistant", stopReason: "stop" });
expect(lastAssistantText(agent.state.messages)).toContain("identical arguments 5 times in a row");
});
it("maxConsecutiveErrorBatches also stops it, since every batch is all-error", async () => {
const requests: Message[][] = [];
const calls = { count: 0 };
const agent = new Agent({
initialState: { model, systemPrompt: "", tools: [rejectingSessionsTool(calls)] },
streamFn: makeStream(identicalRejectedTurns(25), requests),
maxConsecutiveErrorBatches: 4,
});
await agent.prompt("OpenClaw Android is enough");
expect(calls.count).toBe(4);
expect(requests).toHaveLength(4);
expect(lastAssistantText(agent.state.messages)).toContain("ended in errors");
});
});|
Merged #159864 repairs Code Mode repeated-work identity; it does not add this PR’s opt-in RunLoop turn, error-batch, or idle-repeat cutoffs. These are independent safeguards, so this PR is not superseded. |
|
Nice work on the runaway guards — we're building Tammo (tammo.ai) around the same problem from the budget side: pre-call budget gate (worst-case estimate vs remaining), hard deny, signed spend ledger for every decision. Complementary to turn/error guards. Running a free 30-day pilot — would love your take as someone building guards. — uu (operator, Tammo) |
|
This pull request has been automatically marked as stale due to inactivity. |
|
This pull request has been automatically marked as stale after 7 days without qualifying human activity. |
|
Thanks for the PR. We're closing older pull requests that have gone stale against current This XL PR has failing CI, still needs real behavior proof, and has had no commits since September 7; main already stops identical-error loops. If a specific runaway pattern still escapes current loop detection, please open a focused issue or a smaller PR. If this change is still needed, please open a fresh PR against current |
Closes #120962
[AI-assisted]
What Problem This Solves
Fixes an issue where a worker agent could enter an unbounded retry loop inside the native runLoop: an external service returning HTTP 429 (masked inside a "successful" tool output) drove 219 assistant turns / 177 tool calls / ~15M tokens over 6h42m, stopped only by the global
stuckSessionAbortMstimeout rather than by any active guardrail.Why This Change Was Made
Adds three opt-in hard cutoffs to the agent-core runLoop, each activating independently when set to a positive integer in
tools.loopDetection:turnLimit— max assistant turns per run; ends gracefully with a terminal message instead of another provider request.maxConsecutiveErrorBatches— max consecutive all-error tool batches; any success resets the streak.maxIdleRepeatCalls— max consecutive identical tool calls (same name + args); catches errors hidden inside successful output. Steering-skipped calls are excluded.enabled: truealone does not engage hard cutoffs (preserves upgrade contract).enabled: falsedisables both layers. Resolved config propagates through sessions, compaction, and worker launch descriptors. The launcher fences guard-enabled turns on worker bundles lacking theworker-loop-guard-v1capability; configless andenabled:falseturns are unaffected.User Impact
Operators who want the guardrails set at least one guard key (e.g.
turnLimit: 200) in atools.loopDetectionblock. Existing configurations gain no new hard termination behavior unless a guard key is explicitly set. Public package consumers see no change unless they opt in.Evidence
Focused tests (all pass):
packages/agent-core/src/agent-loop.guard.test.ts— 23 tests: maxTurns, error-batch, idle-repeat, steering-skip exclusion (sequential + parallel), steering requeuesrc/agents/sessions/agent-session-loop-guard-transport.test.ts— realAgentSessionthrough local HTTP/SSE transport, 3 repeated calls → graceful termination, no 4th requestsrc/agents/tool-loop-detection-config.test.ts— 9 tests: per-key activation,enabled:falsekill switch, per-agent cascadesrc/gateway/worker-environments/worker-turn-launcher.loop-guard.test.ts— 6 tests: launcher fence, serialization, guard-off compatibilitypackages/gateway-protocol/src/schema/worker-admission.test.ts— 25 tests: loop-guard capability in worker protocol features