[BUG] Autocompacting Loop Causing Massive Token Usage Spikes OCT 15 2025
Preflight Checklist
- [x] I have searched existing issues and this hasn't been reported yet
- [x] This is a single bug report (please file separate reports for different bugs)
- [x] I am using the latest version of Claude Code
What's Wrong?
Status: ๐ด CRITICAL
Priority: High
Severity: Production Impact
Labels: bug, critical, performance, cost-optimization
---
๐ Issue Summary
Problem: Autocompacting mechanism is stuck in a loop, repeatedly reading the same file and causing exponential token usage spikes.
Impact Period: October 11-14, 2025
Peak Impact: 108.8M tokens ($64+) on Oct 14, 107.4M tokens ($78+) on Oct 12
Total Additional Cost: ~$235+ during spike period
---
๐จ Critical Impact Analysis
Cost Escalation (Oct 11-14)
- Oct 14: 108.8M tokens, $64+ - Extreme mixed combat
- Oct 12: 107.4M tokens, $78+ - Heavy artillery deployment
- Oct 11: 96.4M tokens, $77+ - Multi-front warfare
- Oct 13: 33.1M tokens, $26+ - Sustained operations
Monthly Context
- Total Period Usage: 1,247,031,522 tokens (1.25 billion)
- Total Cost: $1,027.16 (CRITICAL LEVEL)
- Spike Contribution: ~23% of monthly tokens in 4 days
---
๐ Root Cause Analysis
Primary Issue: Autocompacting process is repeatedly reading the same file without making progress, creating an infinite processing loop.
Symptoms Identified:
- Repeated API calls to same file/content
- Exponential token consumption without proportional output
- Sustained high usage across multiple days
Evidence from Data:
- Consistent high token consumption (96-108M tokens/day) during spike
- No corresponding output/completion indicators
---
๐ Technical Details
Affected Components
- Autocompacting service/file processor
- File reading/caching mechanism
- Token consumption monitoring
Error Pattern
[Autocompact] โ Read File โ Process โ [Repeat Same File] โ Exponential Tokens
Performance Metrics During Incident
- Average Daily Tokens: 41.57M (normal) vs 96.4M (spike) - 232% increase
- Cost Efficiency: Worst during spike period ($78 for 107.4M tokens)
- API Call Volume: 12,986 entries total, concentrated during spike
---
๐ ๏ธ Suggested Fixes
Immediate Hotfix (Priority 1)
# Add loop detection to autocompacting
MAX_FILE_READ_ATTEMPTS = 3
file_read_count = {}
def safe_autocompact(file_path):
if file_path not in file_read_count:
file_read_count[file_path] = 0
file_read_count[file_path] += 1
if file_read_count[file_path] > MAX_FILE_READ_ATTEMPTS:
logger.error(f"Autocompact loop detected for {file_path}")
return False # Break the loop
Medium-term Solutions
- Add progress tracking for file processing
- Implement circuit breaker pattern for autocompacting
- Add token budget alerts for abnormal consumption patterns
- File fingerprinting to detect duplicate processing
Long-term Architecture
- Idempotent processing guarantees
- State management for compaction progress
- Cost-aware processing with automatic throttling
- Comprehensive monitoring with auto-remediation
---
๐ Impact Assessment
Financial Impact
- Direct Cost: $235+ unnecessary spending during spike
- Monthly Overspend: Pushed total to CRITICAL $1,027.16
- Future Risk: Potential recurrence could cost $250+/week
System Impact
- Performance: Reduced system availability during spikes
- Reliability: Processing failures due to resource exhaustion
- Monitoring: Alert fatigue from false positives
---
๐ Workaround
Immediate Action Required:
# Temporarily disable autocompacting
systemctl stop autocompact-service
# Or implement manual throttling
echo "MAX_CONCURRENT_COMPACT=1" >> /etc/autocompact/config
Manual Processing:
- Process files individually with monitoring
- Set explicit token limits per operation
- Use cache-heavy operations (like Sept 24 pattern)
---
๐ Additional Context
Related Issues
- Similar pattern observed on Sept 24 (514.6M tokens) but with cache efficiency
- Weekly cost limits approaching/exceeded ($1,026+ consumed)
- Daily reset patterns not preventing accumulation
Monitoring Data
- Current Session: 50.2% cost usage, 12.1% token usage
- Burn Rate: 80.4 tokens/min during normal operation
- Time to Reset: 2h 20m (6:00 PM ET daily)
---
๐ Reference: Historical Usage Data (Sept 15 - Oct 15, 2025)
Executive Summary
- Total Period: 30 days of operations
- Total Tokens Consumed: 1,247,031,522 tokens (1.25 BILLION!)
- Total Cost: $1,027.16 (CRITICAL LEVEL!)
- Total API Calls: 12,986 entries
- Average Daily Tokens: ~41.57 million tokens/day
- Average Daily Cost: ~$34.24/day
Daily Token Breakdown
Week 1: Oct 9-15, 2025 (Spike Period)
| Date | Total Tokens | Cost | Token Type Breakdown | Battle Intensity |
|------|-------------|------|---------------------|------------------|
| Oct 15 | 25,890,000+ | $15.xx | Sonnet 4 heavy usage | ๐ฅ Major |
| Oct 14 | 108,800,000+ | $64.xx | Mixed Sonnet/Opus combat | ๐ฅ๐ฅ Extreme |
| Oct 13 | 33,080,000+ | $26.xx | Sonnet 4 primary | ๐ฅ Major |
| Oct 12 | 107,400,000+ | $78.xx | Heavy Opus artillery | ๐ฅ๐ฅ๐ฅ Maximum |
| Oct 11 | 96,410,000+ | $77.xx | Multi-model warfare | ๐ฅ๐ฅ๐ฅ Maximum |
| Oct 10 | 23,930,000+ | $20.xx | Mixed operations | ๐ฅ Major |
| Oct 9 | 21,910,000+ | $15.xx | Standard battles | ๐ฅ Major |
---
๐ฏ Bug vs Normal Limits
Conclusion: This is NOT Normal Limit Behavior
Based on my 30-day usage history, the evidence strongly indicates this is an autocompacting loop bug rather than legitimate workload hitting limits:
---
๐ Key Evidence Points
1. Pattern Analysis: Erratic vs Predictable
- Normal Limits: Gradual, consistent daily usage patterns
- Your Data: Sudden 3-5x spikes (20M โ 108M tokens) with immediate returns to baseline
2. Duration & Consistency
- Normal Workloads: Sustained high usage across multiple days
- Your Pattern: Isolated 4-day extreme spike (Oct 11-14) surrounded by normal operation
3. Efficiency Anomalies
- Sept 24: 514.6M tokens for $2.15 (optimal cache usage)
- Oct 12: 107.4M tokens for $78 (extremely inefficient)
- Same system shouldn't have 36x cost efficiency variance with legitimate work
4. Comparative Baseline
- Pre-Spike Normal: 20-55M tokens/day, $13-47 cost
- Spike Period: 96-108M tokens/day, $64-78 cost
- Post-Spike: Immediate return to 25M tokens, $15 cost due to forced stop.
---
๐ Supporting Data Patterns
| Metric | Normal Behavior | Your Observed Pattern | Conclusion |
|------------|-------------------|-------------------------|---------------|
| Daily Consistency | Predictable patterns | Erratic spikes | Bug |
| Cost Efficiency | Relatively stable | 36x variance | Bug |
| Recovery Pattern | Gradual decline | Immediate return to baseline | Manual intervention (Bug) |
| Workload Correlation | Matches project phases | No clear project correlation | Bug |
---
๐ฏ Final Determination
The data patterns match exactly what we'd expect from:
- Process getting stuck in infinite file reading
- Manual intervention stopping the loop (explaining sudden returns to normal)
- Inefficient processing causing high cost per token
Not consistent with: Legitimate workload increases, normal limit hitting, or planned intensive work periods.
This conclusion is based on comprehensive analysis of 30 days of usage data and known system behavior patterns.
๐ฏ Root Cause Analysis: Autocompacting Loop Bug Confirmed
Definitive Evidence This is a Software Bug
1. The Limit Consequence Pattern
- Oct 11-14: Extreme token consumption (96-108M tokens/day)
- Oct 15: Forced Stop usage due to limit exhaustion
- Critical Insight: The limit hit is the effect, not the cause
- Normal Work: Never consumes 3x daily budget for 4 consecutive days
2. Inefficiency Anomaly Proves Waste
Sept 24: 514.6M tokens for $2.15 (Optimal - cache working)
Oct 12: 107.4M tokens for $78 (Extreme waste - 36x less efficient)
- Same system cannot have 36x efficiency variance with legitimate work
- Indicates: Tokens being burned on repeated, unproductive operations
3. Erratic Usage Pattern
- Normal Work: Gradual, predictable daily patterns
- Your Data: Sudden 5x spikes โ Immediate crash โ Limit forced shutdown
- Classic Bug Signature: Runaway process triggering system safeguards
4. Timeline Tells the Story
Oct 1-10: Normal operations (12-68M tokens/day)
Oct 11-14: RUNAWAY SPIKE (96-108M tokens/day) โ BUG ACTIVATED
Oct 15: LIMIT HIT - Forced shutdown โ CONSEQUENCE OF BUG
5. Comparative Analysis
| Metric | Normal Work Pattern | Your Oct 11-14 Pattern |
|------------|------------------------|---------------------------|
| Daily Consistency | Predictable fluctuations | Extreme, sustained spikes |
| Cost Efficiency | Relatively stable | 36x variance (proves waste) |
| Limit Impact | Gradual approach | Sudden exhaustion |
| Recovery | Natural workflow resumption | Forced by system limits |
Conclusion: This is NOT Normal Usage
The evidence overwhelmingly confirms an autocompacting loop bug:
- The pattern matches runaway process behavior
- The limit hit is a consequence, not a cause
- The efficiency anomalies prove token waste
- The timing correlates with known compaction issues
Without this bug, my normal 20-55M token daily usage would have sustained comfortably within limits. The Oct 15th shutdown is direct proof of the bug's financial impact.
This analysis is based on 30 days of usage data and matches known software failure patterns.
---
๐ Related Issues & Broader Impact
This autocompacting loop issue is not isolated. Recent GitHub issues indicate a pattern of similar compaction failures among other users, suggesting a potential systemic problem or regression, particularly around October 2025.
- #6461 and #8838 directly report compaction loops and the system losing track of commands, which aligns with the "infinite loop" behavior observed in our incident.
- #9029 is a notable regression reported around October 5, 2025, where auto-compaction stopped working entirely, forcing manual intervention that also fails. This timeline closely precedes our massive usage spike.
- #9493 further confirms issues with the compaction command itself failing due to conversation length.
The consistency of these reports reinforces the criticality of this bug and its impact on user workflow and API costs.
---
๐ท๏ธ Metadata
- Reported By: Panda
- Report Date: October 15, 2025
- Environment: Production
- Affected Version: Current autocompacting service
- Fix Deadline: ASAP (cost escalation ongoing)
---
๐ฅ Assignments
- Engineering Lead: Investigate root cause and implement hotfix
- DevOps: Monitor token usage and implement throttling
- QA: Test loop detection and circuit breakers
- Product: Communicate impact and timeline
---
Status: ๐ด ACTIVE INCIDENT - Cost escalation ongoing
What Should Happen?
๐ฏ What Should Happen? (Expected Behavior)
Normal Autocompacting Operation
Expected Workflow:
File โ Read Once โ Process โ Compact โ Complete
What Should Happen:
- Each file processes once then completes
- Predictable token usage (20-55M tokens/day)
- Consistent cost efficiency (~$0.82 per million tokens)
- Clear completion status - no infinite loops
- Monthly limits last entire billing cycle
Normal Daily Pattern:
- Regular development: 20-35M tokens
- Intensive work: 40-55M tokens
- Light days: 5-15M tokens
- No sudden 5x spikes
The system should process files efficiently and stop when done - not enter infinite loops that burn through monthly budgets in 4 days.
Error Messages/Logs
Steps to Reproduce
๐ฏ Observed Behavior & Symptoms
We cannot reliably reproduce the exact trigger, but the autocompacting loop exhibits these consistent patterns when it occurs:
Symptom Timeline:
- Normal Operation: Autocompacting works as expected (0-45M tokens/day)
- Trigger Event: Unknown condition causes loop initiation
- Loop Phase: System repeatedly processes same file (96-108M tokens/day)
- Manual Intervention Required: Process must be stopped
Observed Loop Characteristics:
- File Repetition: Same file appears in processing logs multiple times
- Token Consumption: Exponential increase without corresponding output
- Model Usage: Mixed Sonnet/Opus usage as system attempts different approaches
Environmental Context:
- Timing: Often occurs during sustained development sessions
- System State: No consistent memory/CPU patterns identified
- Recent Changes: Potential regression around early October 2025
Detection Methods:
# Indicators of potential autocompacting loop
1. Token consumption > 70M/day without major feature work
2. Sustained high usage across multiple daily resets
Current Investigation Status:
- ๐ Root Cause: Unknown trigger condition
- ๐ Pattern Analysis: Correlating with file sizes/types
- โ ๏ธ Workaround: Manual monitoring and process termination
- ๐ฏ Focus: Identifying common preconditions across incidents
Note: The exact reproduction steps remain elusive, but the symptom pattern is consistent and severe when it occurs.
Claude Model
Not sure / Multiple models
Is this a regression?
Yes, this worked in a previous version
Last Working Version
_No response_
Claude Code Version
Claude Code v1.0.108
Platform
Anthropic API
Operating System
Windows
Terminal/Shell
PowerShell
14 Comments
Found 3 possible duplicate issues:
This issue will be automatically closed as a duplicate in 3 days.
๐ค Generated with Claude Code
has happened to me twice now. its stuck on it right now.
Yeah i didn't even notice at first! but it got stuck on this huge test output file for me a couple of times! ran my usage right through the roof!
Now I try to use custom subagents as often as possible, which work with a clean context window every time... Well, so that they have time to finish their work before the context overflows, and return the results.
yeah ive been looking at setting up some myself now, just got to look at the work flow a bit better tbh
@jimbob60 Based on my experience, I decided to first create roadmap documentation with small stages, and create special subagents that are assigned a small portion of the work, broken down into stages. The user subagents then do the work itself in their own separate context, and then return reports to the main agent. This significantly saves on the context window; often, the subagents don't even fill their context window until their stage of work is completed.
<img width="404" height="333" alt="Image" src="https://github.com/user-attachments/assets/bc9ebf97-beac-4de1-866e-a59ede2c66a5" />
<img width="497" height="700" alt="Image" src="https://github.com/user-attachments/assets/28358cbb-70d4-4512-95d7-ccc0186a0f1f" />
<img width="521" height="464" alt="Image" src="https://github.com/user-attachments/assets/7c916e75-878d-47c2-9d5c-472150d131b9" />
My understanding has been Growing after today to be honest! im redesigning my entire work flow might be incorporating a local backup coding ai as well for emergencies ;), either way ill be using subagents and custom commands thoroughly, to do so. Thanks for the information!
I'd be very happy if this helps at all. Please let other users know if this approach works for more than just me. I'm currently on the MAX 20x plan, and it's finally almost enough for me... But it's true that I do most of my work developing open source projects, and that's also unfair. Anthropic could create a special plan for those working on open source projects.
my 6 cc are stuck in compacting conversation all day long
i cancelled my cursor sub yesterday :( (down from spending $3k/m on cursor)
Yes, honestly, Anthropic's vibe coding was getting on my nerves, and I was afraid to update the app... I had to sit down and write my own agent ecosystem in Go. They already support many LLMs out of the box.
What's also annoying is that the Anthropic team doesn't communicate with users at all and doesn't address problems. It seems like there are simply no real engineers and QA there, only managers and company owners. ((
I've developed a methodology around iterative AI workflows based on my recent research that creates systematic improvement
through multiple cycles: Analyze โ Build โ Analyze โ Build โ Validate โ Analyze โ [continues]. Each cycle generates a
comprehensive roadmap that gets split into manageable sessions, preventing context overflow while maintaining continuity. The
approach treats AI interactions as part of a learning system rather than isolated requests, with each phase building upon
documented findings from previous phases. This methodology intentionally slows down the AI and forces it to focus on specific
phases rather than trying to tackle everything at once, which leads to more thorough and effective improvements.
Core implementation: I use specialized subagents (analysis agents for reconnaissance, master builder agents for
implementation, validation agents for verification) that must read universal principles and previous reports before starting
work. Each subagent generates structured reports containing their findings, recommendations, and implementation details. This
creates intelligent handoffs where subsequent subagents build upon documented knowledge rather than starting fresh. The
learning database captures workflow patterns, subagent performance metrics, and optimization opportunities across all
projects. By forcing each subagent to focus on one specific role, the AI produces deeper analysis and more targeted solutions
instead of surface-level fixes.
Process flow detail: Start with analysis subagents to identify issues and opportunities, then deploy master builder subagents
to implement systematic improvements. Re-analyze with fresh subagents to discover new optimization opportunities that
weren't visible before the improvements. Implement again through additional builder cycles, then validate with specialized
agents that verify changes and hunt for any new issues introduced. The cycle continues with another analysis phase to
identify the next level of improvements. Each iteration compounds the enhancements and reveals deeper optimization
possibilities. The deliberate pacing prevents the AI from rushing through complex problems and ensures each phase gets proper
attention.
Practical benefits: This methodology transforms one-shot AI fixes into systematic improvement campaigns that produce better
long-term results. The roadmap approach lets you break large refactoring efforts into session-sized chunks that fit within
context limits, while the iterative cycles ensure compound improvements rather than isolated changes. By slowing down the
process and focusing on longer roadmaps, the AI develops more sophisticated solutions and catches issues that would be missed
in rushed implementations. The learning database gets smarter over time, suggesting optimal subagent sequences for different
scenarios. Final verification always happens through personal testing outside of AI to validate that the improvements work
effectively in real-world usage. @kolkov - your staged subagent approach aligns perfectly with this framework, just adding
the iterative learning layer for continuous improvement. I'm still testing this system and plan to make a dedicated GitHub
post about the methodology once I've refined it further.
Fix landed, and is going out tomorrow morning. Thanks for the report!
@jimbob60 I havent been able to use agent/subagent effectively or in a way that beats my current workflow which is more akin to layering on complexity than specializing and handing off. to me the fact that i cant see what the agent is doing (i can if i click individually but then thats poor ux) in code just makes it unusable. for me it actually adds context complexity because now the primary agent will have some context missing and i have to keep track. i tried a workflow where all the agents update the same doc which becomes the single point of reference or central context repository for a particular session but once again distorts context. for me, what works best is layering. create a plan, execute the plan, then add more complexity to a second iteration. get to the end, then remove the fluff or overengineered bits. hook up to observability, test, repeat. on the agent workflow, i think the best possible solution would be if there was a way to invoke an agent which then splits off into a new terminal window with the conversation forked. git trees in realtime with one agent per fork. when im multiclauding this is pretty much what im doing. grows new brain cells :P
This issue has been automatically locked since it was closed and has not had any activity for 7 days. If you're experiencing a similar issue, please file a new issue and reference this one if it's relevant.