Polycracker Guides · Agent Stability

Stop AI Agent Thrashing

Thrashing is what happens when an agent retries the same failed plan, re-fetches the same files, and balloons chat history until a simple fix costs more tokens than a production incident. This guide defines thrash signatures, quantifies their cost, and shows how Polycracker ECU, The Tuning House, and Polydyno circuit-breakers keep autonomous loops from melting your monthly budget.

What thrashing looks like in telemetry

Thrashing is not one bug—it is a family of failure modes where each turn makes the next turn harder. Classic signs: monotonically increasing prompt_tokens across turns with flat or declining useful progress; repeated tool calls with identical arguments; oscillation between two opposing edits (add import, remove import); and error messages copied in full into every subsequent user message. If you only glance at completion length, thrash hides in plain sight—the model looks “busy” while input snowballs.

Measure thrash with two ratios: context growth rate (input tokens turn n divided by turn n−1) and yield (useful artifact produced per thousand input tokens). Healthy agents hold growth below 1.15× after the first turn and maintain yield. Thrashing agents blow past 1.4× and approach zero yield long before the task completes.

Worked example: thrash spiral on a flaky test

An agent attempts to fix a flaky integration test. Each failure pastes the entire stderr log and re-attaches the whole test suite. Below is a simplified eight-turn capture before ECU guardrails.

Turn Input tokens Growth vs prior Output tokens Tool calls
1 3,800 — 320 2
2 5,600 1.47× 280 4
3 8,900 1.59× 410 6
4 13,200 1.48× 390 5
5 19,400 1.47× 520 8
6 27,100 1.40× 480 9

Six turns consumed 78,000 input tokens and still no green CI. Output was only 2,400 tokens. The session failed not because the model could not write code, but because the harness kept feeding it an ever-larger replay of its own mistakes. That is thrash.

{
  "thrash_alert": true,
  "reason": "duplicate_tool_call",
  "tool": "read_file",
  "args_hash": "a91f3c…",
  "repeats_last_3_turns": 5,
  "recommended_action": "circuit_break"
}

Root causes teams overlook

Unbounded history. Frameworks append full assistant and tool messages forever. Over-eager retrieval. RAG returns whole documents when a paragraph would suffice. Verbose tool payloads. MCP servers return megabytes of JSON the model cannot act on in one turn—see fixing input/output bloat. Missing stop conditions. Agents lack max-turn budgets and identical-call detection. Aggressive AST maps. Over-pruned context causes failed edits, which triggers retries—tune maps in The Tuning House must be staged, not slammed to seventy percent on day one.

Circuit breakers that actually work

Polycracker ECU implements knock-style guardrails analogous to engine detonation sensors. When input growth exceeds your signed threshold—or duplicate tool hashes fire—the ECU can limp the session: drop redundant history, dedupe tool results, or hard-stop with a human-readable reason instead of burning another forty thousand tokens.

Configure breakers in The Tuning House alongside AST tables: max turns per task, max identical tool invocations, max prompt tokens per session, and cooldown before retry. Maps ship as tune.jwt so every seat enforces the same policy.

Before and after: same task with ECU limp mode

Metric Thrash (stock) ECU guarded
Turns to completion 12 (aborted) 5
Total input tokens 142,000 24,800
Duplicate tool calls 23 0
Wall time 18 min 4 min
Est. API cost (input-only) $0.355 $0.062

The guarded run finished because history compression reset after turn three and ECU refused a fourth identical grep across the monorepo. Quality did not drop: Polydyno invariants still passed.

Detection checklist for platform owners

  1. Log turn index with prompt and completion tokens on every call (measurement guide).
  2. Alert when three consecutive turns exceed 1.35× input growth.
  3. Hash tool name + canonicalized args; flag repeats within a sliding window.
  4. Track sessions that end without a mergeable artifact after N turns.
  5. Compare thrash rate before and after map rollouts; publish weekly.

Export those metrics into Polydyno adversarial profiles so regressions fail CI before finance notices the spike.

Organizational habits that reduce thrash

Give agents a clear definition of done (“single PR, one test file changed”) instead of open-ended “fix the build.” Cap pasted logs—store artifacts in object storage and pass links. Split monolithic MCP servers into task-scoped toolsets. Teach engineers to reset threads when context growth exceeds five thousand tokens rather than “pushing through.” Pair these habits with structural shred from decreasing token usage fifty to seventy percent so remaining turns stay cheap.

When to escalate to human review

Circuit breakers should not infinite-loop either. After a limp stop, surface a compact trace: last error, files touched, tool calls suppressed. Human takeover at that point costs less than another autonomous spiral. Enterprise teams route those events through the same intake as production incidents—optionally via ECU sales / support for signed SLA maps.

Framework patterns that invite thrash

ReAct-style loops without memory compression amplify errors: the model narrates a failed plan, then reads its own narration back on the next turn as sacred context. Auto-continue commands that fire whenever the assistant stops mid-sentence encourage rambling outputs that become input bloat on the following hop. Tool routers that let the model pick among thirty similar MCP endpoints statistically increase duplicate calls—collapse them into one well-designed tool with a mode parameter. Eval harnesses that score verbosity unknowingly train teams to tolerate long outputs that later get replayed into prompts.

Fix these at the orchestration layer, not with bigger context windows. A wider window only delays thrash; it rarely prevents it. Prefer explicit state machines with checkpoints: after each successful tool mutation, snapshot a concise state blob instead of forwarding entire transcripts.

Building a thrash budget per workflow

Assign each workflow a monthly token budget and a maximum tolerated thrash rate (failed or aborted sessions divided by attempts). Platform teams importing metrics from ECU can chart budget burn on the same dashboard as CI reliability. When thrash rate crosses five percent for a workflow, freeze new tool mounts until schemas are audited—often the culprit is a freshly added internal MCP integration returning unbounded JSON.

Workflow Monthly token budget Thrash rate (4 wk) Action
Unit test repair 12M input 2.1% On track
Migration scripts 28M input 8.4% Tighten history cap
Incident triage 45M input 11.2% Audit log MCP tool

Load testing thrash in Polydyno

Adversarial Polydyno profiles deliberately feed contradictory linter output and flaky test logs to agents under test. Measure how many turns occur before guardrails trip. Compare stock vs ECU maps: a healthy map should reduce median turns to completion without increasing invariant failures. Publish those curves beside latency percentiles so leadership sees thrash as measurable quality, not a vague complaint about “the AI being flaky.”

Developer education that sticks

Short internal docs beat hour-long trainings: when to reset a thread, how to recognize duplicate tool calls in the trace pane, and why pasting fifty-kilobyte logs hurts everyone’s budget. Pair the doc with a chat command that prints current session input totals pulled from ECU’s local metrics endpoint. Engineers self-correct quickly when they see a number climb past ten thousand tokens mid-task.