feat: auto-compact and retry on context window errors#2808
Open
TheArchitectit wants to merge 10 commits into
Open
feat: auto-compact and retry on context window errors#2808TheArchitectit wants to merge 10 commits into
TheArchitectit wants to merge 10 commits into
Conversation
|
Yeah we need this , and if possible some one to add fff search ([dependencies] |
ad7887b to
390c1fe
Compare
Author
|
This fixes the 400 error if you run out of compact space. |
7 tasks
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>
02dfe66 to
b57e0df
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Automatically compact the session and retry when the model API returns a context window error. Users no longer need to manually run
/compactwhen 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/compactand 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:self.runtime(critical — without this,prepare_turn_runtimewould rebuild from the original un-compacted session)Compacted session never actually used (Bug fix)
Before: the original auto-compact code called
prepare_turn_runtime(true)after compaction, butprepare_turn_runtimereads fromself.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_sessionwithpreserve_recent_messages=0causedsaturating_sub(0) = messages.len(), which producedkeep_from = messages.len()— an out-of-bounds index when the code later accessedsession.messages[k].Fix: explicit guard returns
messages.len()forpreserve_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 propercontext_length_exceedederror. 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:
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:
Files changed
runtime/src/trident.rsruntime/src/compact.rspreserve_recent_messages=0— guard against out-of-bounds indexruntime/src/lib.rstridentmodulerusty-claude-cli/src/main.rssession_mutfix,/compactupdated to use Trident,"no parseable body"detectionTest plan
cargo test --workspace— all tests passcargo clippy --workspace --all-targets -- -D warnings— clean💘 Generated with Crush