Skip to content

Commit e92a98c

Browse files
steipetePeter Steinberger
andauthored
fix(agents): stop repeated equivalent terminal exec failures (#118071)
Co-authored-by: Peter Steinberger <[email protected]>
1 parent ea34515 commit e92a98c

5 files changed

Lines changed: 346 additions & 5 deletions

File tree

‎src/agents/agent-tools.before-tool-call.e2e.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,49 @@ describe("before_tool_call loop detection behavior", () => {
495495
expectToolLoopBlockedResult(result, "identical outcomes");
496496
});
497497

498+
it("blocks changing-argument terminal exec failures and escalates vetoes", async () => {
499+
const output = "Traceback: missing package\n\n(Command exited with code 1)";
500+
const execute = vi.fn().mockResolvedValue({
501+
content: [{ type: "text", text: output }],
502+
details: { status: "completed", exitCode: 1, aggregated: output },
503+
});
504+
const tool = createWrappedTool("exec", execute);
505+
506+
await withToolLoopEvents(async (emitted) => {
507+
for (let index = 0; index <= GLOBAL_CIRCUIT_BREAKER_THRESHOLD; index += 1) {
508+
const result = await tool.execute(
509+
`exec-semantic-${index}`,
510+
{ command: `python job-${index}.py` },
511+
undefined,
512+
undefined,
513+
);
514+
if (index >= CRITICAL_THRESHOLD) {
515+
expectToolLoopBlockedResult(
516+
result,
517+
index === GLOBAL_CIRCUIT_BREAKER_THRESHOLD
518+
? "global circuit breaker"
519+
: "identical outcomes",
520+
);
521+
}
522+
}
523+
524+
expect(execute).toHaveBeenCalledTimes(CRITICAL_THRESHOLD);
525+
expect(emitted.find((event) => event.detector === "generic_repeat")).toMatchObject({
526+
level: "critical",
527+
action: "block",
528+
count: CRITICAL_THRESHOLD,
529+
toolName: "exec",
530+
});
531+
expect(emitted.at(-1)).toMatchObject({
532+
detector: "global_circuit_breaker",
533+
level: "critical",
534+
action: "block",
535+
count: GLOBAL_CIRCUIT_BREAKER_THRESHOLD,
536+
toolName: "exec",
537+
});
538+
});
539+
});
540+
498541
it("warns on non-strict same-tool argument churn while preserving tool execution", async () => {
499542
const execute = vi.fn().mockImplementation(async (toolCallId: string, _params: unknown) => {
500543
const progressed = toolCallId === "write-churn-progress";

‎src/agents/tool-loop-detection.test.ts‎

Lines changed: 258 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,24 @@ function recordFailedCall(
8080
});
8181
}
8282

83+
function createExecLoopResult(params: {
84+
status: "completed" | "failed";
85+
exitCode: number | null;
86+
output: string;
87+
aggregated?: string;
88+
timedOut?: boolean;
89+
}) {
90+
return {
91+
content: [{ type: "text", text: params.output }],
92+
details: {
93+
status: params.status,
94+
exitCode: params.exitCode,
95+
aggregated: params.aggregated ?? params.output,
96+
...(params.timedOut === undefined ? {} : { timedOut: params.timedOut }),
97+
},
98+
};
99+
}
100+
83101
function recordRepeatedSuccessfulCalls(params: {
84102
state: SessionState;
85103
toolName: string;
@@ -957,6 +975,246 @@ describe("tool-loop-detection", () => {
957975
expect(loopResult.stuck).toBe(false);
958976
});
959977

978+
it.each([
979+
{
980+
label: "completed normal process failures",
981+
status: "completed",
982+
exitCode: 1,
983+
output: "Traceback: missing package\n\n(Command exited with code 1)",
984+
},
985+
{
986+
label: "failed non-executable commands",
987+
status: "failed",
988+
exitCode: 126,
989+
output: "Command not executable (permission denied)",
990+
aggregated: "",
991+
},
992+
{
993+
label: "failed missing commands",
994+
status: "failed",
995+
exitCode: 127,
996+
output: "Command not found",
997+
aggregated: "",
998+
},
999+
] as const)("blocks repeated $label across changing exec arguments", (testCase) => {
1000+
const state = createState();
1001+
const result = createExecLoopResult(testCase);
1002+
1003+
for (let index = 0; index < CRITICAL_THRESHOLD; index += 1) {
1004+
recordSuccessfulCall(state, "exec", { command: `python job-${index}.py` }, result, index);
1005+
}
1006+
1007+
expect(
1008+
state.toolCallHistory?.every((record) => record.outcomeKind === "terminal-exec-failure"),
1009+
).toBe(true);
1010+
expect(
1011+
detectToolCallLoop(
1012+
state,
1013+
"exec",
1014+
{ command: "python next-job.py" },
1015+
enabledLoopDetectionConfig,
1016+
),
1017+
).toMatchObject({
1018+
stuck: true,
1019+
level: "critical",
1020+
detector: "generic_repeat",
1021+
count: CRITICAL_THRESHOLD,
1022+
});
1023+
});
1024+
1025+
it("anchors changing-argument exec vetoes until the global circuit breaker", () => {
1026+
const state = createState();
1027+
const result = createExecLoopResult({
1028+
status: "completed",
1029+
exitCode: 1,
1030+
output: "Traceback: missing package\n\n(Command exited with code 1)",
1031+
});
1032+
1033+
for (let index = 0; index < CRITICAL_THRESHOLD; index += 1) {
1034+
recordSuccessfulCall(state, "exec", { command: `python job-${index}.py` }, result, index);
1035+
}
1036+
for (let index = CRITICAL_THRESHOLD; index < GLOBAL_CIRCUIT_BREAKER_THRESHOLD; index += 1) {
1037+
const params = { command: `python job-${index}.py` };
1038+
expect(detectToolCallLoop(state, "exec", params, enabledLoopDetectionConfig)).toMatchObject(
1039+
{
1040+
stuck: true,
1041+
level: "critical",
1042+
detector: "generic_repeat",
1043+
count: index,
1044+
},
1045+
);
1046+
expect(
1047+
recordToolCallOutcome(state, {
1048+
toolName: "exec",
1049+
toolParams: params,
1050+
toolCallId: `exec-veto-${index}`,
1051+
result: {
1052+
content: [{ type: "text", text: "blocked" }],
1053+
details: { status: "blocked", deniedReason: "tool-loop" },
1054+
},
1055+
config: enabledLoopDetectionConfig,
1056+
}),
1057+
).toMatchObject({ outcomeKind: "tool-loop-veto", resultHash: undefined });
1058+
}
1059+
1060+
expect(
1061+
detectToolCallLoop(
1062+
state,
1063+
"exec",
1064+
{ command: "python final-job.py" },
1065+
enabledLoopDetectionConfig,
1066+
),
1067+
).toMatchObject({
1068+
stuck: true,
1069+
level: "critical",
1070+
detector: "global_circuit_breaker",
1071+
count: GLOBAL_CIRCUIT_BREAKER_THRESHOLD,
1072+
});
1073+
});
1074+
1075+
it.each([
1076+
{
1077+
label: "synthetic exit-code-only output",
1078+
result: createExecLoopResult({
1079+
status: "completed",
1080+
exitCode: 1,
1081+
output: "\n\n(Command exited with code 1)",
1082+
}),
1083+
},
1084+
{
1085+
label: "successful command batches",
1086+
result: createExecLoopResult({ status: "completed", exitCode: 0, output: "done" }),
1087+
},
1088+
{
1089+
label: "timed-out executions",
1090+
result: createExecLoopResult({
1091+
status: "failed",
1092+
exitCode: 1,
1093+
output: "Command timed out",
1094+
timedOut: true,
1095+
}),
1096+
},
1097+
{
1098+
label: "non-finite exit codes",
1099+
result: createExecLoopResult({
1100+
status: "failed",
1101+
exitCode: Number.POSITIVE_INFINITY,
1102+
output: "process failed",
1103+
}),
1104+
},
1105+
{
1106+
label: "failures without an exit code",
1107+
result: createExecLoopResult({
1108+
status: "failed",
1109+
exitCode: null,
1110+
output: "process failed before spawning",
1111+
}),
1112+
},
1113+
])("does not semantically block $label", ({ result }) => {
1114+
const state = createState();
1115+
for (let index = 0; index < GLOBAL_CIRCUIT_BREAKER_THRESHOLD; index += 1) {
1116+
recordSuccessfulCall(state, "exec", { command: `grep target-${index}` }, result, index);
1117+
}
1118+
1119+
expect(state.toolCallHistory?.every((record) => record.outcomeKind === undefined)).toBe(true);
1120+
expect(
1121+
detectToolCallLoop(
1122+
state,
1123+
"exec",
1124+
{ command: "grep next-target" },
1125+
enabledLoopDetectionConfig,
1126+
),
1127+
).toEqual({ stuck: false });
1128+
});
1129+
1130+
it.each([
1131+
{
1132+
label: "a distinct terminal failure",
1133+
toolName: "exec",
1134+
result: createExecLoopResult({
1135+
status: "completed",
1136+
exitCode: 1,
1137+
output: "Traceback: different package\n\n(Command exited with code 1)",
1138+
}),
1139+
},
1140+
{
1141+
label: "a successful execution",
1142+
toolName: "exec",
1143+
result: createExecLoopResult({ status: "completed", exitCode: 0, output: "done" }),
1144+
},
1145+
{
1146+
label: "a timed-out execution",
1147+
toolName: "exec",
1148+
result: createExecLoopResult({
1149+
status: "failed",
1150+
exitCode: 1,
1151+
output: "Command timed out",
1152+
timedOut: true,
1153+
}),
1154+
},
1155+
{
1156+
label: "another tool",
1157+
toolName: "read",
1158+
result: { content: [{ type: "text", text: "read complete" }], details: { ok: true } },
1159+
},
1160+
])("resets the semantic exec failure tail after $label", ({ toolName, result }) => {
1161+
const state = createState();
1162+
const failure = createExecLoopResult({
1163+
status: "completed",
1164+
exitCode: 1,
1165+
output: "Traceback: missing package\n\n(Command exited with code 1)",
1166+
});
1167+
for (let index = 0; index < CRITICAL_THRESHOLD - 1; index += 1) {
1168+
recordSuccessfulCall(state, "exec", { command: `python job-${index}.py` }, failure, index);
1169+
}
1170+
recordSuccessfulCall(state, toolName, { command: "interruption" }, result, 19);
1171+
recordSuccessfulCall(state, "exec", { command: "python latest.py" }, failure, 20);
1172+
1173+
expect(
1174+
detectToolCallLoop(
1175+
state,
1176+
"exec",
1177+
{ command: "python next.py" },
1178+
enabledLoopDetectionConfig,
1179+
),
1180+
).toEqual({ stuck: false });
1181+
});
1182+
1183+
it("does not carry semantic exec failures into another run", () => {
1184+
const state = createState();
1185+
const result = createExecLoopResult({
1186+
status: "completed",
1187+
exitCode: 1,
1188+
output: "Traceback: missing package\n\n(Command exited with code 1)",
1189+
});
1190+
1191+
for (let index = 0; index < CRITICAL_THRESHOLD; index += 1) {
1192+
const params = { command: `python job-${index}.py` };
1193+
const toolCallId = `exec-old-run-${index}`;
1194+
recordToolCall(state, "exec", params, toolCallId, enabledLoopDetectionConfig, {
1195+
runId: "old-run",
1196+
});
1197+
recordToolCallOutcome(state, {
1198+
toolName: "exec",
1199+
toolParams: params,
1200+
toolCallId,
1201+
result,
1202+
config: enabledLoopDetectionConfig,
1203+
runId: "old-run",
1204+
});
1205+
}
1206+
1207+
expect(
1208+
detectToolCallLoop(
1209+
state,
1210+
"exec",
1211+
{ command: "python next.py" },
1212+
enabledLoopDetectionConfig,
1213+
{ runId: "new-run" },
1214+
),
1215+
).toEqual({ stuck: false });
1216+
});
1217+
9601218
it("blocks repeated completed exec calls despite volatile runtime details", () => {
9611219
const state = createState();
9621220
const params = { command: "grafana-api.sh datasources" };

‎src/agents/tool-loop-detection.ts‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -310,7 +310,20 @@ function hashToolOutcome(
310310
if (toolName === "exec") {
311311
const execHash = hashExecToolOutcome(details, text);
312312
if (execHash) {
313-
return { resultHash: execHash };
313+
const exitCode = details.exitCode;
314+
const output = nonEmptyStringField(details.aggregated) ?? text;
315+
// Normal nonzero exits append this footer even when the command emitted nothing.
316+
const terminalFailure =
317+
(details.status === "completed" || details.status === "failed") &&
318+
typeof exitCode === "number" &&
319+
Number.isFinite(exitCode) &&
320+
exitCode !== 0 &&
321+
details.timedOut !== true &&
322+
output !== "" &&
323+
output !== `(Command exited with code ${exitCode})`;
324+
return terminalFailure
325+
? { resultHash: execHash, outcomeKind: "terminal-exec-failure" }
326+
: { resultHash: execHash };
314327
}
315328
}
316329
if (toolName === "write" && isWriteNoProgressOutcome(details)) {
@@ -631,7 +644,7 @@ export function detectToolCallLoop(
631644
level: "critical",
632645
detector: "generic_repeat",
633646
count: noProgressStreak,
634-
message: `CRITICAL: Called ${toolName} with identical arguments and identical outcomes ${noProgressStreak} times. Session execution blocked to prevent runaway loops.`,
647+
message: `CRITICAL: Called ${toolName} with identical outcomes ${noProgressStreak} times. Session execution blocked to prevent runaway loops.`,
635648
warningKey: `generic:${toolName}:${currentHash}:${noProgress.latestResultHash ?? "none"}`,
636649
};
637650
}

0 commit comments

Comments
 (0)