Skip to content

fix(compaction): avoid premature recovery during tool-heavy turns - #168338

Merged
steipete merged 5 commits into
mainfrom
fix/midturn-precheck-provider-anchor
Oct 10, 2026
Merged

steipete merged 5 commits into
mainfrom
fix/midturn-precheck-provider-anchor

Conversation

@steipete

@steipete steipete commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Related: #101929

Main merge refresh

Current head: 6d6d865ab5dbda84aa897ed1a0cdc801fd3b9232. Merged 123d5a1331a8307969767b34e8f8808461ea205b from main without rebasing or force-pushing.

There was one conflict hunk in attempt.spawn-workspace.context-engine.test.ts: main extracted MockCallSource and assertion/context-engine helpers into shared test support, while this PR retired ToolResultGuardInstallParams with 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-gate passed. Its baseline-ratchet job reports the same inherited 456/455 environment-budget mismatch as a warning. ClawSweeper reviewed exact head 6d6d865ab5dbda84aa897ed1a0cdc801fd3b9232 within 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.

File read Main estimate Final estimate Provider prompt tokens, final
1 15,835 11,547 6,384
2 18,282 13,993 8,829
3 20,724 16,436 11,273
4 23,169 18,881 13,718
5 25,615 → recovery 21,327 16,164
6 not comparable after recovery 23,783 18,609

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, then pnpm openclaw --profile precheck-density agent exec --config <isolated-config> --state-dir <isolated-state> --cwd <fixture-workspace> --message-file <task> --json, with isolated OPENCLAW_STATE_DIR/OPENCLAW_CONFIG_PATH and 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 qaRuntime passed 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-gate passed. 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 head 7330da8a9a1f within 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.

Check projected foreground requests against the last matching provider prompt plus appended content. Preserve conservative fallback and existing overflow recovery when request provenance changes.
@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This 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.

  • Before: Main estimates the fifth prompt at 25,615 tokens, triggers recovery, and loses earlier markers despite a tokenizer count of 16,165.
  • After: The candidate reads all six files without recovery and returns all six markers; the final prompt reports 18,609 provider tokens.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong scoped behavior evidence and no actionable findings; overall scope remains partial against the broader linked estimator issue.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Recorded embedded agent exec runs exercise the changed admission owner through a real OpenAI-compatible local-model transport: fitting requests complete without recovery and an oversized control still recovers. Those runs are accurately attributed to the prior head; reviewed admission code is unchanged by the merge, which also has reported focused integration validation.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: Tool-heavy turns can recover unnecessarily and lose useful context even though the next provider prompt fits.
Reason: The targeted repair has concrete user value and maintainer direction; Related remains appropriate because it does not solve every density or next-turn case in the broader report.

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
Reviewed head: 6d6d865ab5dbda84aa897ed1a0cdc801fd3b9232

Before merge

None.

Findings

None.

Agent review details

How this fits together

The 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]
Loading

Technical review

Best 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

  • Mid-turn admission placement changes intended behavior with a stated reason (b85147f: The opt-in guard stopped oversized tool continuations before provider submission and reused existing precheck recovery.)
  • Request-level cache observation keeps the original intent (15e5cf1: Observe canonical foreground inputs before managed cache consumption and pair them with completion usage, excluding compaction requests.)
  • Append-only history fingerprints keeps the original intent (cee0906: Detect undeclared history rewrites while allowing explicitly owned rewrites and retaining bounded diagnostics.)
  • Reserve-adjusted context-engine refill keeps the original intent (3631e7a: Loop assembly must reserve system and compaction space before refilling accepted history.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit cee0906 adds src/agents/embedded-agent-runner/prompt-cache-observability.ts:266 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: cee0906f3877; files: src/agents/embedded-agent-runner/prompt-cache-observability.ts)
  • ruel225: Raw commit 3631e7a adds src/agents/embedded-agent-runner/tool-result-context-guard.ts:362 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 3631e7a45674; files: src/agents/embedded-agent-runner/tool-result-context-guard.ts)

PR surface

Source +75, Tests +327, Docs 0. Total +402 across 31 files. Added test files: 4.

View PR surface stats
Area Files Added Removed Net
Source 10 196 121 +75
Tests 19 897 570 +327
Docs 2 2 2 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 31 1095 693 +402

Review metrics

Metric Value Why it matters
Production versus test growth Production +196/-121; tests and support +897/-570. Production growth carries request provenance and completion accounting after retiring the old guard; test growth includes moved history coverage and composed admission regressions.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #101929
Summary: This PR repairs projected mid-turn admission and repeated accounting within the broader estimator report; next-turn estimation and conservative density remain separate.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Repairs unnecessary recovery in the opt-in mid-turn precheck without changing defaults or introducing configuration.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (7 earlier review cycles)
  • reviewed 2026-10-10T08:23:57.450Z sha a53cff0 :: needs changes before merge. :: [P2] Preserve measured output tokens when reasoning is replayed
  • reviewed 2026-10-10T08:37:23.584Z sha a53cff0 :: needs changes before merge. :: [P2] Preserve measured output tokens when reasoning is replayed
  • reviewed 2026-10-10T09:24:42.500Z sha 3676927 :: needs changes before merge. :: [P2] Preserve measured output tokens when reasoning is replayed
  • reviewed 2026-10-10T09:47:06.453Z sha 3676927 :: needs changes before merge. :: [P2] Preserve measured output tokens when reasoning is replayed
  • reviewed 2026-10-10T10:08:15.280Z sha 88c32f8 :: needs changes before merge. :: [P2] Retain opaque reasoning occupancy when the request anchor is invalidated
  • reviewed 2026-10-10T10:25:09.489Z sha 7330da8 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-10T10:49:24.404Z sha 7330da8 :: needs changes before merge. :: none

Reviewed October 10, 2026, 7:18 AM ET / 11:18 UTC (Revision 8).

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 10, 2026
@steipete
steipete marked this pull request as ready for review October 10, 2026 09:05
@steipete
steipete marked this pull request as draft October 10, 2026 09:15
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Oct 10, 2026
@steipete steipete added the ci:no-fail-fast Keep all selected CI matrix jobs running after failures on the next PR run. label Oct 10, 2026
@clawsweeper clawsweeper Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Oct 10, 2026
@steipete
steipete marked this pull request as ready for review October 10, 2026 10:19
@steipete

Copy link
Copy Markdown
Contributor Author

@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.

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 10, 2026
@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 10, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

@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.

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 10, 2026
@steipete steipete self-assigned this Oct 10, 2026
@steipete
steipete merged commit 45c7bc9 into main Oct 10, 2026
143 checks passed
@steipete
steipete deleted the fix/midturn-precheck-provider-anchor branch October 10, 2026 11:35
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling ci:no-fail-fast Keep all selected CI matrix jobs running after failures on the next PR run. docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant