Skip to content

feat: add stuck loop detection and exponential backoff infrastructure for agent polling - #17118

Merged
gumadeiras merged 8 commits into
openclaw:mainfrom
akramcodez:fix/agent-loop-detection-and-backoff
Feb 16, 2026
Merged

gumadeiras merged 8 commits into
openclaw:mainfrom
akramcodez:fix/agent-loop-detection-and-backoff

Conversation

@akramcodez

@akramcodez akramcodez commented Feb 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: Agents getting stuck in infinite polling loops, causing runaway costs ($150 in one incident) and memory crashes (800MB → 3GB)
  • Why it matters: Single stuck session wasted 1,535 API calls over 2 hours with no intervention, representing massive cost and resource waste
  • What changed: Added automatic loop detection (blocks at 20 identical calls) and exponential backoff infrastructure (5s→10s→30s→60s)
  • What did NOT change: No changes to tool execution flow, agent prompts, or existing hooks - purely additive safety features

Change Type (select all)

  • Feature
  • Bug fix
  • Refactor
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

User-visible / Behavior Changes

Visible changes:

  • Agents stuck in loops will now be blocked after 20 identical tool calls with error message
  • Warning logs appear after 10 identical calls (non-blocking)
  • Session terminated with clear error: "CRITICAL: Called [tool] with identical arguments 20 times. Session execution blocked to prevent resource waste."

No config changes required - features are active by default and backward compatible.

Security Impact (required)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No
  • Command/tool execution surface changed? Yes
  • Data access scope changed? No
  • Explanation: Tool execution can now be blocked when repetitive patterns detected. This is a security/safety improvement that prevents resource exhaustion. Mitigation: Only blocks confirmed stuck loops (≥20 identical calls), legitimate workflows unaffected.

Repro + Verification

Environment

  • OS: Linux (tested on Ubuntu)
  • Runtime/container: Node.js with TypeScript
  • Model/provider: N/A (agent-agnostic)
  • Integration/channel: All channels
  • Relevant config: None required

Steps

Before (reproduce stuck loop):

  1. Agent runs long command (e.g., sleep 300)
  2. Agent polls command_status every 4-5 seconds
  3. Continues indefinitely with no intervention
  4. Memory and costs grow unbounded

After (with fix):

  1. Agent runs long command
  2. Polls 1-9: Normal operation
  3. Polls 10-19: Warning logged, execution continues
  4. Poll 20: Execution blocked, session terminated

Expected

  • Loop detection blocks execution at 20th identical call
  • Warning logged at 10th identical call
  • Backoff calculations return correct delays (5s, 10s, 30s, 60s)

Actual

[x] All expected behavior confirmed via 30 unit tests

Evidence

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Test Results:

✓ src/agents/tool-loop-detection.test.ts (16 tests) - All passing
✓ src/agents/command-poll-backoff.test.ts (14 tests) - All passing
✓ src/logging/diagnostic.test.ts (2 tests) - No regressions

TypeScript compilation: No errors
Linter: 0 warnings, 0 errors

Human Verification (required)

Verified scenarios:

  • Loop detection correctly identifies repetitive patterns
  • Warning threshold (10) triggers warnings without blocking
  • Critical threshold (20) blocks execution
  • Different tool/param combinations don't trigger false positives
  • Backoff calculations follow correct schedule (5s→10s→30s→60s)
  • State tracking persists across multiple tool calls
  • Cleanup runs in diagnostic heartbeat without errors

Edge cases checked:

  • Empty history (no false positives)
  • Mixed tool calls (only counts identical patterns)
  • Sliding window behavior (old calls evicted)
  • Type safety with discriminated unions
  • Async import handling in heartbeat

What I did NOT verify:

  • Integration with actual command_status tool (infrastructure ready, integration pending decision on external tool wrapping)
  • Production deployment with real stuck agent scenario
  • Memory impact under high session load

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No
  • Migration needed? No
  • Exact upgrade steps: None - features activate automatically on deployment

Failure Recovery (if this breaks)

How to disable quickly:

  1. Revert commit: git revert 0c28bbd8d
  2. Or comment out loop detection in src/agents/pi-tools.before-tool-call.ts lines 28-57
  3. Redeploy

Files to restore:

  • src/agents/pi-tools.before-tool-call.ts
  • src/logging/diagnostic-session-state.ts
  • src/logging/diagnostic.ts

Known bad symptoms to watch for:

  • Legitimate workflows being blocked (would show "CRITICAL" errors at 20 calls)
  • Performance degradation in high-volume sessions
  • Memory growth from tracking tool call history

Risks and Mitigations

  • Risk: Legitimate workflows with 20+ identical calls could be blocked

    • Mitigation: Threshold (20) is high enough to avoid false positives; real workflows vary params. Monitoring during rollout recommended.
  • Risk: Memory overhead from tracking 30 tool calls per session

    • Mitigation: Sliding window capped at 30 calls; old entries auto-evicted. Cleanup runs every 30s in heartbeat.
  • Risk: Backoff infrastructure unused if integration not completed

    • Mitigation: Code is tested and ready; no runtime cost if unused. Follow-up PR can complete integration.

Greptile Summary

Adds stuck loop detection and exponential backoff infrastructure for agent polling. The loop detection is integrated into runBeforeToolCallHook, tracking tool calls in a sliding window of 30 entries and blocking execution after 20 identical calls. A separate (currently unused) backoff module provides delay calculations for command polling. The heartbeat timer is extended to prune stale poll records.

  • Loop detection integration in pi-tools.before-tool-call.ts correctly gates on sessionKey, detects before recording, and blocks at critical threshold while allowing warnings to pass through
  • hashToolCall has a latent bug: uses JSON.stringify with a top-level-only key array as replacer, which silently drops nested object keys — currently safe because tool schemas are flat, but would produce false positives if nested params are introduced
  • Backoff module (command-poll-backoff.ts) is well-structured infrastructure but entirely unused at runtime — integration is deferred to a follow-up PR
  • Silent error swallowing in the heartbeat's .catch(() => {}) for the dynamic import could hide module loading failures
  • Good test coverage with 30 tests across two test files covering thresholds, sliding window, edge cases, and backoff calculations

Confidence Score: 4/5

  • This PR is safe to merge — the core safety feature works correctly for current tool parameter shapes, and the backoff module is unused infrastructure with no runtime impact.
  • Score of 4 reflects that the active code path (loop detection in before-tool-call hook) works correctly for the current flat tool parameter shapes. The hashToolCall nested-object issue is a latent concern, not an active bug. The backoff module is purely additive and unused. Tests are comprehensive. Deducted 1 point for the hashToolCall replacer bug which could cause false positives if tool schemas evolve to include nested objects.
  • src/agents/tool-loop-detection.ts — the hashToolCall function's use of JSON.stringify replacer array silently drops nested object keys

Last reviewed commit: 0c28bbd

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

7 files reviewed, 3 comments

Edit Code Review Agent Settings | Greptile

Comment thread src/agents/tool-loop-detection.ts Resolved
Comment thread src/agents/pi-tools.before-tool-call.ts Resolved
Comment thread src/logging/diagnostic.ts Resolved
@akramcodez

Copy link
Copy Markdown
Contributor Author

Hi @gumadeiras @cpojer @steipete,

Would appreciate a review when you get a chance. This addresses the review feedback on the agent loop detection PR by fixing nested object hashing in hashToolCall and improving error visibility in diagnostic heartbeat imports.

The changes eliminate potential false positives if tool params become nested and avoid silently swallowing dynamic import failures, without altering the loop detection thresholds or behavior.

Thanks!

@gumadeiras gumadeiras self-assigned this Feb 16, 2026
@gumadeiras
gumadeiras force-pushed the fix/agent-loop-detection-and-backoff branch from 7e57733 to 5c1131e Compare February 16, 2026 19:49
@gumadeiras
gumadeiras force-pushed the fix/agent-loop-detection-and-backoff branch 3 times, most recently from e3fe4e9 to 6ad4706 Compare February 16, 2026 19:59
@gumadeiras
gumadeiras force-pushed the fix/agent-loop-detection-and-backoff branch from 6ad4706 to eebabf6 Compare February 16, 2026 20:16
@gumadeiras
gumadeiras merged commit e5eb5b3 into openclaw:main Feb 16, 2026
9 checks passed
@gumadeiras

Copy link
Copy Markdown
Member

Merged via squash.

Thanks @akramcodez!

lovewanwan pushed a commit to lovewanwan/openclaw that referenced this pull request Apr 28, 2026
… for agent polling (openclaw#17118)

Merged via /review-pr -> /prepare-pr -> /merge-pr.

Prepared head SHA: eebabf6
Co-authored-by: akramcodez <[email protected]>
Co-authored-by: gumadeiras <[email protected]>
Reviewed-by: @gumadeiras
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
… for agent polling (openclaw#17118)

Merged via /review-pr -> /prepare-pr -> /merge-pr.

Prepared head SHA: eebabf6
Co-authored-by: akramcodez <[email protected]>
Co-authored-by: gumadeiras <[email protected]>
Reviewed-by: @gumadeiras
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 9, 2026
… for agent polling (openclaw#17118)

Merged via /review-pr -> /prepare-pr -> /merge-pr.

Prepared head SHA: eebabf6
Co-authored-by: akramcodez <[email protected]>
Co-authored-by: gumadeiras <[email protected]>
Reviewed-by: @gumadeiras
lhfer pushed a commit to lhfer/openclaw that referenced this pull request Oct 11, 2026
… for agent polling (openclaw#17118)

Merged via /review-pr -> /prepare-pr -> /merge-pr.

Prepared head SHA: eebabf6
Co-authored-by: akramcodez <[email protected]>
Co-authored-by: gumadeiras <[email protected]>
Reviewed-by: @gumadeiras
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: Stuck agent / polling loop detection watchdog

2 participants