Repository navigation
fix(compaction): avoid premature recovery during tool-heavy turns - #168338
Conversation
Check projected foreground requests against the last matching provider prompt plus appended content. Preserve conservative fallback and existing overflow recovery when request provenance changes.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis PR checks prepared provider requests using matching measured usage and conservative estimates for newly appended content. Example: An agent reads six synthetic files with a 24,576-token usable prompt budget.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Partial Merge readiness✅ Ready for maintainer review This PR provides a useful, scoped repair for premature mid-turn recovery. The previous conflict is resolved, earlier reasoning-accounting findings remain fixed, and no new actionable defect was found; current-head CI remains pending. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe embedded agent runner prepares conversation history, system instructions, and tools for provider dispatch; its admission check either permits the request or signals the existing truncation and compaction recovery owner. flowchart TD
A[Agent tool loop] --> B[Prepared prompt projection]
B --> C[Request observer]
D[Terminal provider usage] --> C
C --> E[Mid-turn admission]
E --> F[Provider dispatch]
E --> G[Existing recovery owner]
Technical reviewBest possible solution: Land this focused mid-turn repair after required checks pass, retaining the broader issue for remaining estimator cases. Do we have a high-confidence way to reproduce the issue? Current-main source exposes the premature admission path, and supplied real CLI traces demonstrate a fitting prompt being routed to recovery; no target code was executed during this review. Is this the best way to solve the issue? Checking the prepared request and binding measured usage to an unchanged adjacent prefix fixes the admission owner while retaining conservative fallback and existing recovery. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 8420f82cbbf8. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +75, Tests +327, Docs 0. Total +402 across 31 files. Added test files: 4. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (7 earlier review cycles)
Reviewed October 10, 2026, 7:18 AM ET / 11:18 UTC (Revision 8). |
|
@clawsweeper re-review Both opaque-reasoning paths are now covered: measured completion occupancy in the matching anchor, and conservative retained completion occupancy after a context change invalidates that anchor. Failing-before regressions and final-head real local-model fit/overflow evidence are in the PR body. |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review Merged current main without rebasing. The single test-type conflict preserves main’s shared helpers and temporal-context assertions while keeping the retired guard-callback type/test removed. Admission and opaque-reasoning production code is unchanged. All 90 selected tests passed, and scoped autoreview is clean; the PR body records the inherited environment-variable budget failure and refreshed validation. |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
…enclaw#168338) * fix(compaction): avoid premature mid-turn recovery Check projected foreground requests against the last matching provider prompt plus appended content. Preserve conservative fallback and existing overflow recovery when request provenance changes. * test(compaction): split provider admission coverage * fix(agents): retain measured completion context in mid-turn checks * fix(agents): preserve completion usage in precheck fallback
Related: #101929
Main merge refresh
Current head:
6d6d865ab5dbda84aa897ed1a0cdc801fd3b9232. Merged123d5a1331a8307969767b34e8f8808461ea205bfrom main without rebasing or force-pushing.There was one conflict hunk in
attempt.spawn-workspace.context-engine.test.ts: main extractedMockCallSourceand assertion/context-engine helpers into shared test support, while this PR retiredToolResultGuardInstallParamswith the obsolete guard-callback test. The resolution uses main's shared imports, removes both superseded local types, preserves main's temporal-context assertions, and keeps the obsolete guard test removed. Anchored admission and opaque-reasoning production files are byte-identical to the prior validated head.Post-resolution validation: 90 tests passed in 415.62s across the admission, context-engine, orphan, prompt-context, and system-prompt suites. Scoped lint/format, core and relevant test typechecks, line-cap, assertion-safety, timeout-race, mock-export, config-doc and plugin-inventory checks passed. Fresh scoped autoreview of the committed merge is clean through P2.
Known inherited local guard failure: the max-lines check's environment-variable subcheck reports 456 names against a budget of 455. The guard's own inventory functions report identical sets and budget on fetched main and the merge head, with zero names added or removed by this PR. The max-lines suppression check itself passes. The budget is unchanged. An earlier provisional ratchet invocation, before committing the merge, used the old merge-base and reported incoming-main size growth; the committed-merge line-cap check passes.
Refreshed-head CI run 38047625624 and
openclaw/ci-gatepassed. Its baseline-ratchet job reports the same inherited 456/455 environment-budget mismatch as a warning. ClawSweeper reviewed exact head6d6d865ab5dbda84aa897ed1a0cdc801fd3b9232within the 15-minute window: no findings, no Before merge items, ready for maintainer review. No proof-only override was needed.What Problem This Solves
Tool-heavy turns can compact prematurely even when the next provider prompt fits comfortably: mid-turn admission adds the unchanged system prompt to already measured usage and checks before the final tool-result projection.
User Impact
With
compaction.midTurnPrecheck.enabled, successive tool calls retain more usable context without unnecessary recovery. Missing usage, changed request context, and genuinely oversized prompts retain conservative protection. No new configuration or token-density setting is introduced.Why This Change Was Made
Admission now checks the prepared provider request before marking it sent. The existing foreground request observer binds measured context usage to the adjacent completed request and its unchanged prefix, system prompt, tools, and model. Matching assistant fragments count once using the runtime/provider response identities; new tool results and unrelated appended content are estimated. Projecting new tail content retains the anchor only when the historical prefix is unchanged. Next-turn system-prompt protection and existing recovery routing remain intact.
Measured completion occupancy includes opaque reasoning that Responses may replay. When context changes invalidate the anchor, the full projected-text fallback also retains the remaining assistants' measured completion occupancy. This deliberately favors conservative accounting on fallback, without borrowing an invalidated prompt total.
The conservative new-content estimate still exceeds exact tokenizer counts. This removes repeated accounting of covered context without lowering fallback density; it does not claim tokenizer parity or every shape in the original report.
Evidence
Prior live-proof head:
7330da8a9a1f37887f30b51b4b27301270af62a6. The live runs below were completed before the main merge; they are not relabeled as live runs of the refreshed head.Real OpenClaw embedded
agent exec→ OpenAI-compatible transport → Homebrew llama-server 0.6.0/b11429 (d81235049), Qwen3 8B Q4_K_M, reasoning off. Isolated state, 32,768-token model context, 24,576-token usable prompt budget. Gateway transport was not exercised.Six ~12.5 KB synthetic files revealed the next filename one at a time. Main (
e7eece5bae3d) compacted after the fifth read and lost earlier markers. The final candidate read all six files, returned all six markers, and performed no recovery.The server's own chat-template/tokenizer counted main's blocked fifth prompt at 16,165, below 24,576. It exactly reproduced provider usage for the preceding request. Small differences between runs reflect request text.
The final token-dense four-file control remained protected: 29,427 estimated, 28,188 server-tokenized next-prompt tokens, against the 24,576 usable budget. The server tokenizer exactly reproduced the preceding 22,124-token request. One compaction succeeded and the agent completed. This tests reserved-budget overflow, not hard rejection by the 32,768-token server.
Commands:
pnpm build qaRuntime, thenpnpm openclaw --profile precheck-density agent exec --config <isolated-config> --state-dir <isolated-state> --cwd <fixture-workspace> --message-file <task> --json, with isolatedOPENCLAW_STATE_DIR/OPENCLAW_CONFIG_PATHand a recording loopback proxy. Main/final fitting/final oversized wall times: 222.43s / 95.10s / 116.14s; startup is included and these are not latency benchmarks.The fitting measured-prefix and no-usage projection regressions fail against original production files; three oversized controls pass on that baseline (462.49s wall). The opaque-reasoning regression fails on the prior prompt-only implementation (61.14s). The small-system-change plus opaque-reasoning regression fails on the subsequent implementation (95.17s). Both review findings are fixed.
Final
node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/attempt-midturn-precheck.test.ts --maxWorkers=1: 11 passed, 101.56s wall, including worker preparation (81.85s Vitest duration; about 3% reported case time). These session-level cases exercise terminal usage, async fragments, final projection, dispatch and recovery signaling together. The earlier three-shard replay passed 49 tests in 430.05s, including model-state and execution-phase coverage; the pre-follow-up six-file replay passed 118 tests in 719.28s, including retained persistence tests. Existing persistence cases account for about 100s of test time and were retained unchanged. Final CI node-test job wall times were 70–405 seconds (whole jobs, not individual test timings).Core and affected test typechecks, scoped lint, formatting, line/max-lines, assertion-safety, test-timeout-race, test-mock-exports, config docs and plugin inventory checks passed. The size/assertion ratchets were repeated after the final fallback edit. One verified stale max-lines baseline entry was removed. Final
pnpm build qaRuntimepassed in 336.50s. A prior full build was interrupted during declaration generation after 2,142.90s and is not claimed as passing. One earlier test replay was discarded because concurrent build output changed its compilation inputs; subsequent tests/builds were serialized.Isolated Codex autoreview before the main merge: scoped-clean through P2, with no accepted/actionable findings. Prior-head CI run 38044486051 succeeded, and
openclaw/ci-gatepassed. Prior-head Canvas dashboard and Kysely failures did not recur on final CI. A stale PR-check listing briefly showed dependency-review failure; the exact commit status and successful security-review run confirm no dependency changes require review. Before the merge, ClawSweeper reviewed head7330da8a9a1fwithin the 15-minute loop: no findings, no Before merge items, proof sufficient, ready for maintainer review. That prior-head gate passed; refreshed-head CI and review are recorded above.Production: +196/−121 (net +75). Request provenance and completion-identity/fallback protection require growth after removing the old guard; no formatting compression or compatibility path was added to meet a LOC target. Tests/support: +897/−570, including mechanical extraction without dropping coverage. Docs: +2/−2. One stale baseline line removed. No model-facing text changed.