Skip to content

feat: auto-compact and retry on context window errors#2808

Open
TheArchitectit wants to merge 10 commits into
ultraworkers:mainfrom
TheArchitectit:feat/auto-compact-upstream
Open

feat: auto-compact and retry on context window errors#2808
TheArchitectit wants to merge 10 commits into
ultraworkers:mainfrom
TheArchitectit:feat/auto-compact-upstream

Conversation

@TheArchitectit
Copy link
Copy Markdown

@TheArchitectit TheArchitectit commented Apr 26, 2026

Summary

Automatically compact the session and retry when the model API returns a context window error. Users no longer need to manually run /compact when hitting context limits — recovery happens transparently with progressive compaction.

Problem this solves

Context window errors with no recovery path

Before: when a conversation grew too large for the model's context window, the API would return an error (e.g. context_window_blocked) and the turn would fail. The user had to manually run /compact and retry — if the session was still too large after one compaction, they were stuck. There was no automatic recovery and no gradual escalation.

Fix: The progressive auto-compact retry loop automatically detects context window errors and compacts the session in up to 4 rounds with decreasing preserve_recent_messages (4→2→1→0), trading conversation continuity for a smaller payload until the request fits. Each round:

  1. Compacts the session via the Trident pipeline + summary compaction
  2. Saves the compacted session back to self.runtime (critical — without this, prepare_turn_runtime would rebuild from the original un-compacted session)
  3. Retries the request
  4. If it still fails with a context window error, loops to the next round with more aggressive compaction

Compacted session never actually used (Bug fix)

Before: the original auto-compact code called prepare_turn_runtime(true) after compaction, but prepare_turn_runtime reads from self.runtime.session() — the original un-compacted session. The compacted result was computed and discarded, so every retry sent the same bloated request. Compaction was completely wasted.

Fix: *self.runtime.session_mut() = result.compacted_session.clone() is called before rebuilding the runtime, so the retry uses the actually-compacted session.

Panic when preserve_recent_messages=0 (Bug fix)

Before: calling compact_session with preserve_recent_messages=0 caused saturating_sub(0) = messages.len(), which produced keep_from = messages.len() — an out-of-bounds index when the code later accessed session.messages[k].

Fix: explicit guard returns messages.len() for preserve_recent_messages == 0, which tells compaction "remove everything" without hitting the out-of-bounds path.

Context overflow disguised as 400

Before: some OpenAI-compat backends return 400 "no parseable body" when the request is too large to parse, instead of a proper context_length_exceeded error. The retry loop only checked for "context_window" in the error message, so these disguised context overflows were never caught.

Fix: the error detection now also matches "no parseable body", so the progressive compact-retry loop triggers correctly for these cases too.

How it works

Trident 3-stage compaction pipeline (new)

Before compaction was a single summary-based pass. Trident adds three structural reduction stages before summary compaction, making compaction much more aggressive:

Stage Name What it does Why
1 Supersede Removes obsolete file operations (old reads/edits superseded by later ones on the same file) Reading a file 5 times and editing it 3 times leaves 8 messages; only the latest read and edit matter
2 Collapse Merges consecutive chatty exchanges (back-and-forth tool calls) into single summary messages A 10-message debugging cycle (read→edit→read→edit…) becomes 1–2 messages
3 Cluster Groups semantically similar messages using Jaccard fingerprinting Multiple "fix lint errors" turns get merged into one summary

After Trident runs, the existing summary-based compaction runs on the already-reduced session for maximum context reduction.

Progressive auto-compact retry (new)

When a context window error is detected:

Round 1: preserve 4 recent messages → compact → retry
  ├─ Success → done
  └─ Still too large →
Round 2: preserve 2 recent messages → compact → retry
  ├─ Success → done
  └─ Still too large →
Round 3: preserve 1 recent message → compact → retry
  ├─ Success → done
  └─ Still too large →
Round 4: preserve 0 recent messages (maximum compaction) → compact → retry
  ├─ Success → done
  └─ Still too large → surface error to user

Files changed

File What changed
runtime/src/trident.rs New file (~791 lines). 3-stage Trident pipeline (supersede/collapse/cluster), config, stats, 6 tests
runtime/src/compact.rs Fix panic when preserve_recent_messages=0 — guard against out-of-bounds index
runtime/src/lib.rs Export trident module
rusty-claude-cli/src/main.rs Progressive auto-compact retry loop with session_mut fix, /compact updated to use Trident, "no parseable body" detection

Test plan

  • cargo test --workspace — all tests pass
  • cargo clippy --workspace --all-targets -- -D warnings — clean
  • 6 Trident unit tests pass (supersede, collapse, cluster, full pipeline, stats)
  • Tested end-to-end with bloated session against OpenAI-compat provider — progressive auto-compact retry triggered and completed successfully
  • Run a session that exceeds the model's context window — automatic compaction + retry occurs
  • Non-context-window errors still propagate without triggering auto-compact
  • Session is persisted to disk after successful auto-compact retry

💘 Generated with Crush

@TheArchitectit TheArchitectit marked this pull request as draft April 26, 2026 21:24
@TheArchitectit TheArchitectit marked this pull request as ready for review April 26, 2026 22:38
@Pilser
Copy link
Copy Markdown

Pilser commented Apr 27, 2026

Yeah we need this , and if possible some one to add fff search ([dependencies]
fff-search = "0.6")
, the Issue page is to messy to propose feature request

@TheArchitectit TheArchitectit force-pushed the feat/auto-compact-upstream branch from ad7887b to 390c1fe Compare April 27, 2026 20:09
@TheArchitectit
Copy link
Copy Markdown
Author

This fixes the 400 error if you run out of compact space.

TheArchitectit and others added 10 commits May 10, 2026 21:21
When the model API returns a context_window_blocked error (because the request
exceeds the model's context window), the CLI now automatically:

1. Compact the session (remove old messages to free up space)
2. Retry the original request with the compacted session
3. Report results to the user

This eliminates the need for users to manually run /compact when they
hit context limits - the recovery happens automatically.

## Technical Details

- Detection: Looks for 'context_window' or 'Context window' in error message
- Uses runtime::compact_session() to aggressively compact (max_estimated_tokens=0)
- Creates new runtime with compacted session and retries the turn
- Reports compaction results and final status to user

## Testing

Tested successfully with a request that exceeded model's context:
- Auto-compact triggered: 'Messages removed 19, Messages kept 5'
- Successfully retried and completed after compaction
Add the 3-stage Trident compaction strategy from R.A.D.1.C.A.L,
adapted for the Rust CLI session model:

Stage 1 - SUPERSEDE: Zero-cost factual pruning. If a file was read
and then later written/edited, the earlier read is obsolete and
removed. Earlier writes superseded by later writes are also dropped.

Stage 2 - COLLAPSE: Buffer short chatty exchanges (under 200 chars,
no tool calls) and collapse them into dense summary blocks when the
threshold is exceeded.

Stage 3 - CLUSTER: Group semantically similar messages (same tool
names, same file paths, similar lengths) using Jaccard-based
fingerprinting and collapse clusters into summary blocks.

All three stages run before the existing summary-based compaction,
so less data needs to be summarized. Wired into both /compact and
the auto-compact retry on context window errors.
… when preserve_recent_messages=0

Two bugs fixed:
1. compact_session() panicked when preserve_recent_messages=0 because
   raw_keep_from = messages.len() causing index-out-of-bounds. Now
   explicitly returns messages.len() when preserve is 0 (compact all).
2. Progressive auto-compact retry loop compacted the session but never
   saved it back to self.runtime, so each retry round rebuilt from the
   original un-compacted session. Now calls
   *self.runtime.session_mut() = result.compacted_session.clone()
   before prepare_turn_runtime().

Also upgrades single-round retry to progressive 4-round loop with
decreasing preserve schedule [4,2,1,0] and "no parseable body" context
window detection.

💘 Generated with Crush

Assisted-by: GLM 5.1 FP8 via Crush <crush@charm.land>
Some OpenAI-compatible providers (e.g., GLM-5) omit the `id` field in
streaming and non-streaming responses. Adding #[serde(default)] allows
the parser to accept these responses instead of failing with
"missing field `id`".

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Adds scripts/install.sh that builds the release binary and links it
to ~/.local/bin/claw. Run after code changes to update the CLI.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
When a provider returns HTML (e.g., error page, wrong endpoint) instead
of JSON in an SSE stream, provide a clear error message instead of
hanging or failing with a cryptic parse error.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
When a provider returns a JSON error (e.g., {"error":{"message":"..."}})
without SSE framing (no "data:" prefix), the SSE parser was silently
ignoring it and hanging. Now detects and surfaces these errors.

Also handles HTML responses that lack SSE framing.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Some providers (GLM, DeepSeek) emit reasoning tokens in `reasoning_content`
or nested `thinking.content` fields instead of `content`. Added support
for these fields so reasoning models work correctly.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
The final streaming chunk from some providers contains only finish_reason
and usage, with no delta field. Made it optional to prevent parse errors.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
When preserve_recent_messages == 0, raw_keep_from equals messages.len(),
causing index out of bounds when accessing session.messages[k].

Added k >= session.messages.len() check to prevent panic.

Reason: Compaction with preserve_recent_messages=0 triggered OOB access
when checking for tool-use/tool-result pair preservation at boundary.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
@TheArchitectit TheArchitectit force-pushed the feat/auto-compact-upstream branch from 02dfe66 to b57e0df Compare May 10, 2026 21:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants