Skip to content

fix(agents): never fail a turn on the soft compaction threshold - #200483

Closed
fuller-stack-dev wants to merge 4 commits into
mainfrom
openclaw/soft-threshold-no-fail
Closed

fuller-stack-dev wants to merge 4 commits into
mainfrom
openclaw/soft-threshold-no-fail

Conversation

@fuller-stack-dev

Copy link
Copy Markdown
Member

Problem

Between tool rounds, the embedded runner stops the attempt (MidTurnPrecheckSignal) when projected occupancy crosses the client maintenance threshold (for example 204,000 of a 272,000-token window). Recovery then decides whether it can compact and continue the transcript. When it cannot (replay_unsafe), the user sees "Context overflow: prompt too large for the model" for a request that would have fit the real window, and has to press Continue.

Production evidence (one Odin gateway, two days): 73 mid-turn precheck aborts with median estimate 207k and p90 215k against a 272k window, none near the window, and no provider-side overflow rejections. One user-visible failure: estimate 206,084 vs threshold 204,000, last batch a Code Mode wait returning status: "waiting". Recovery rejected it because only Code Mode exec was recorded as parking a run, so parkedCodeModeRun was false. The next run compacted 206,029 → 14,530 without trouble.

Fix

  1. Threshold pressure no longer fails a turn. checkMidTurnPrecheck asks recovery's own question (canCompactAndContinueMidTurn, now shared by the boundary and attempt-recovery) before stopping for reserve-based pressure. It uses live subscription evidence for the current batch. If compaction could not continue the batch and the request fits the hard window (the same nominal full-window check as today's hard admission), the request is sent and compaction waits for a later boundary or the end of the turn. The run still stops for a request over the window, with the existing overflow copy.
  2. A Code Mode wait that parks its run counts as parked. codeModeExecToolNames becomes codeModeControlToolNames and includes the marked exec and wait controls (isCodeModeControlTool). Plain tools named exec or wait are excluded. This feeds the completion handler (codeModeSuspended), the conditional sessions_yield check in attempt.ts and the worker runtime.
  3. These protections are unchanged: the hard window, the asynchronous-tool rejection, and the rule that compaction may not rotate the session while Code Mode work is parked.

The boundary predicate trusts subscription evidence only after every call in the current batch has a terminal record. Subscription events trail the agent loop in order, so incomplete evidence makes it defer compaction rather than stop the turn.

Consistent with #189810, #189891 and #190017: hard admission and the soft maintenance threshold remain. This PR only stops the soft threshold from failing a turn that compaction cannot safely continue.

Tests

  • attempt-context-guards.test.ts: proactive (measured occupancy) pressure that fits the window is sent when the batch cannot continue after compaction, and still signals when it can. Red on base.
  • attempt-midturn-precheck.test.ts (real session/request flow): deferred pressure sends the second request; a deferred request over the window still stops. Red on base for the deferral row.
  • attempt-client-tools.test.ts: the marked Code Mode controls yield {exec, wait}; plain exec/wait yield none. Red on base.
  • embedded-agent-subscribe.handlers.tools.test.ts: a marked exec or wait returning waiting parks; unmarked ones do not.
  • run.midturn-precheck-retry.test-support.ts: exec waiting → wait waiting compacts and continues with no error; a replay-unsafe stop shows overflow copy (it is now reached only for a real over-window request).

Evidence

  • Targeted suites pass: context guards, mid-turn precheck, client tools, handlers.tools, shared run integration (including the mid-turn retry file), attempt recovery, execution phase, code-mode bridge lifecycle, tool usage, cron session lifecycle, Talk client-native control, Code Mode continuation.
  • attempt-stream-custody.test.ts and attempt.sessions-yield.test.ts have the same 13 local failures on the unmodified base. They are environmental and were left for CI.
  • Type check (tsrs) of core plus the agents/cron/gateway test projects shows no errors in touched files. Oxfmt and oxlint pass on touched files, except a max-lines count on attempt-stream-prepare.ts that this one-line rename does not change.

Known gaps

  • No isolated-Gateway end-to-end run against a real 200k-token conversation. Proof is at the owning boundaries plus the outer run loop.
  • If threshold-triggered compaction is attempted and fails, or exhausts its attempts, the turn still surfaces compaction guidance. Handling that would need a carried deferral flag across attempts. Left as follow-up.
  • The native ChatGPT V2 boundary fallback (chatgpt-v2-compaction.ts) still signals at its soft trigger. That path is not involved in this incident.

Mid-turn maintenance pressure stopped the attempt before checking whether
compaction could continue the tool batch. When recovery then refused the
batch (for example, a Code Mode wait that parked its run), the user saw a
context-overflow error for a request that fit the model window.

The provider-request precheck now asks recovery's own question with live
evidence before stopping. A request that fits the window is sent and
compaction waits for a boundary that can continue or for the turn end.
A Code Mode wait that returns status waiting now parks its run like exec,
including for the conditional sessions_yield check.
OpenClaw-Publication: 35abb358-ecb3-4815-89db-3befe4f1eb2c
@clawsweeper

clawsweeper Bot commented Nov 17, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: M labels Nov 17, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 17, 2026
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Nov 17, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 17, 2026
@clawsweeper

clawsweeper Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

The PR defers soft-threshold compaction when continuation is unsafe and recognizes marked Code Mode wait results as parked runs.

Example: A Code Mode wait returns waiting at an estimated 206,084 tokens in a 272,000-token window with a 204,000-token maintenance threshold.

  • Before: Recovery can reject continuation and display a context-overflow error despite the request fitting the window.
  • After: The marked wait supplies parked-run evidence so recovery can compact and continue; fitting requests with non-continuable batches defer maintenance.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The focused implementation and regression coverage support correctness, but required proof of the changed behavior through the shipped entry point is absent.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A long tool turn reports context overflow and requires Continue even though its next request fits the model window.
Reason: The reported failure has a concrete source path and useful bounded repair; maintainer authorship establishes direction, while failed-compaction handling remains an explicitly disclosed follow-up.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR addresses a source-confirmed false-overflow failure still present on main. No introduced runtime or security defect was found; the documentation overstates the guarantee.

Priority: P2
Reviewed head: 84ed0d3acbdadd66d41a4f791a74473d739d4b6e

Before merge

None.

Findings

  • [P3] Qualify the documentation's unconditional threshold guarantee — docs/reference/session-management-compaction/compaction.md:82-83

Tests

  • Missing end-to-end proof: Provide redacted terminal output or logs from an isolated Gateway with a real agent and model showing parked-wait recovery and fitting unsafe-batch deferral through the changed production path.
Agent review details

How this fits together

The embedded runner combines projected provider-request pressure with subscription completion evidence to choose between sending the request and entering transcript compaction recovery.

flowchart TD
  A[Tool batch results] --> B[Subscription evidence]
  A --> C[Provider request projection]
  B --> D[Shared continuation predicate]
  C --> E[Context pressure guard]
  D --> E
  E --> F[Send fitting request]
  E --> G[Compaction recovery]
  D --> G
Loading

Technical review

Best possible solution:

Retain the shared continuation predicate and marked-control identity, and describe the guarantee specifically as deferring maintenance for non-continuable batches.

Do we have a high-confidence way to reproduce the issue?

Main can stop a below-window request on maintenance pressure and then reject continuation because a parked wait lacks the exec-only suspension marker; the PR supplies concrete production values, but this review executed no target code.

Is this the best way to solve the issue?

The implementation uses the existing pressure and settlement owners, shares the continuation decision, preserves asynchronous-work rejection and session-binding checks, and updates the renamed metadata consumers without adding persistent state.

Full review comments:

  • [P3] Qualify the documentation's unconditional threshold guarantee — docs/reference/session-management-compaction/compaction.md:82-83
    A fitting request whose batch can continue still enters compaction recovery; if that compaction fails or exhausts recovery attempts, the run still stops with compaction guidance. The PR explicitly acknowledges this case, so saying only an over-window request stops the run overstates the implementation. Qualify this sentence and the matching guarantee in docs/concepts/compaction.md to describe unsafe-batch deferral.
    Confidence: 0.99

Overall correctness: patch is correct
Overall confidence: 0.87

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 96763b979fed.

Provenance checked

  • Measured maintenance pressure and hard request admission keeps the original intent (e0ed68c: Compact long tool turns before exhausting the window while checking every prepared request against nominal hard occupancy.)
  • Marked Code Mode suspension evidence keeps the original intent (7245092: Continue recorded parked Code Mode work without replaying tools, while excluding ordinary tools with matching names and preserving session binding.)
  • Settled-transcript continuation keeps the original intent (12e52a1: Separate permission to replay an attempt from permission to compact and continue its settled transcript.)
  • Steered messages within the current tool turn keeps the original intent (43d750a: Keep settled-batch evidence when a steered user message belongs to the same active run.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit e0ed68c adds src/agents/embedded-agent-runner/run/attempt-setup.ts:452 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: e0ed68c7b845; files: src/agents/embedded-agent-runner/run/attempt-setup.ts)
  • Vito Cappello: Raw commit 7245092 adds src/agents/embedded-agent-runner/run/incomplete-turn-recovery.ts:252 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 72450920f39d; files: src/agents/embedded-agent-runner/run/incomplete-turn-recovery.ts)
  • Ayaan Zaidi: Raw commit 20992c9 adds src/agents/embedded-agent-runner/run/attempt-recovery.ts:572 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 20992c9476de; files: src/agents/embedded-agent-runner/run/attempt-recovery.ts)

PR surface

Source +87, Tests +81, Docs +9, Other +2. Total +179 across 29 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 12 119 32 +87
Tests 12 131 50 +81
Docs 2 11 2 +9
Config 0 0 0 0
Generated 0 0 0 0
Other 3 3 1 +2
Total 29 264 85 +179

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add P2: Fixes a recoverable but disruptive false-overflow failure during long embedded-agent tool turns.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Fixes a recoverable but disruptive false-overflow failure during long embedded-agent tool turns.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

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 execution lanes are retired.

Reviewed November 17, 2026, 3:11 AM ET / 08:11 UTC.

@obviyus

obviyus commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

Thanks for finding this. Your PR showed the soft threshold failing turns at the mid-turn check, and the same mistake turned out to exist in four more places: preflight, the ChatGPT V2 fallback, reply pre-turn compaction and CLI post-turn compaction. #200714 moves all five behind one owner: only a request that cannot fit the window may fail a turn. It credits you as co-author. Once it lands I'll close this one as superseded.

obviyus added a commit that referenced this pull request Nov 17, 2026
Context pressure had several independent deciders that stopped or failed a turn on a reserve-based soft threshold even when the request fit the model window: the mid-turn check, prompt preflight, the ChatGPT V2 fallback, reply pre-turn compaction and CLI post-turn compaction.

src/agents/context-pressure.ts is now the single owner. Only a request larger than the window may fail a turn. Soft pressure compacts only at a settled tool boundary (no pending, active, background or parked Code Mode work) and always continues the turn; maintenance that cannot reduce context is declined for the rest of the run.

Real-model E2E on gpt-6.1-sol (272k window, 204k threshold): base failed the turn with "Auto-compaction failed"; head completed with the correct answer in both journeys. Replay of 79 production stops: 44 soft-threshold stops now continue.

Supersedes #200483. Thanks @fuller-stack-dev.

Co-authored-by: Jason (Json) <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
@obviyus

obviyus commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

Superseded by #200714 (landed as fb9337a), which credits you as co-author. Thanks again.

@obviyus obviyus closed this Nov 17, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
…#200714)

Context pressure had several independent deciders that stopped or failed a turn on a reserve-based soft threshold even when the request fit the model window: the mid-turn check, prompt preflight, the ChatGPT V2 fallback, reply pre-turn compaction and CLI post-turn compaction.

src/agents/context-pressure.ts is now the single owner. Only a request larger than the window may fail a turn. Soft pressure compacts only at a settled tool boundary (no pending, active, background or parked Code Mode work) and always continues the turn; maintenance that cannot reduce context is declined for the rest of the run.

Real-model E2E on gpt-6.1-sol (272k window, 204k threshold): base failed the turn with "Auto-compaction failed"; head completed with the correct answer in both journeys. Replay of 79 production stops: 44 soft-threshold stops now continue.

Supersedes openclaw#200483. Thanks @fuller-stack-dev.

Co-authored-by: Jason (Json) <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to clawhaven/openclaw that referenced this pull request Nov 23, 2026
…#200714)

Context pressure had several independent deciders that stopped or failed a turn on a reserve-based soft threshold even when the request fit the model window: the mid-turn check, prompt preflight, the ChatGPT V2 fallback, reply pre-turn compaction and CLI post-turn compaction.

src/agents/context-pressure.ts is now the single owner. Only a request larger than the window may fail a turn. Soft pressure compacts only at a settled tool boundary (no pending, active, background or parked Code Mode work) and always continues the turn; maintenance that cannot reduce context is declined for the rest of the run.

Real-model E2E on gpt-6.1-sol (272k window, 204k threshold): base failed the turn with "Auto-compaction failed"; head completed with the correct answer in both journeys. Replay of 79 production stops: 44 soft-threshold stops now continue.

Supersedes openclaw#200483. Thanks @fuller-stack-dev.

Co-authored-by: Jason (Json) <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>

Release adaptation: Reviewed soft pressure safe-boundary maintenance and preserved overflow protections. Includes final unchanged memory/gateway helper extractions needed by cap.

(cherry picked from commit fb9337a)

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 23, 2026
Context pressure had several independent deciders that stopped or failed a turn on a reserve-based soft threshold even when the request fit the model window: the mid-turn check, prompt preflight, the ChatGPT V2 fallback, reply pre-turn compaction and CLI post-turn compaction.

src/agents/context-pressure.ts is now the single owner. Only a request larger than the window may fail a turn. Soft pressure compacts only at a settled tool boundary (no pending, active, background or parked Code Mode work) and always continues the turn; maintenance that cannot reduce context is declined for the rest of the run.

Real-model E2E on gpt-6.1-sol (272k window, 204k threshold): base failed the turn with "Auto-compaction failed"; head completed with the correct answer in both journeys. Replay of 79 production stops: 44 soft-threshold stops now continue.

Supersedes #200483. Thanks @fuller-stack-dev.

Co-authored-by: Jason (Json) <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit fb9337a)
Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 28703d8fbcd79dd6cfb5a82aea5ca3b370862590)
(cherry picked from commit 5050a8b2af18d68a2e2c509819387206ca1a002a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts size: M 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.

2 participants