Skip to content

fix(agents): avoid synthetic overflow in tool-heavy sessions - #110297

Merged
joshavant merged 8 commits into
mainfrom
fix/provider-authoritative-context-pressure
Jul 20, 2026
Merged

joshavant merged 8 commits into
mainfrom
fix/provider-authoritative-context-pressure

Conversation

@joshavant

Copy link
Copy Markdown
Collaborator

Closes #107655

Related: #107821

What Problem This Solves

Fixes an issue where long-lived, tool-heavy sessions could discard a provider-acceptable projected prompt and trigger whole-session compaction when conservative local character estimates reported pressure.

On current main, a restored session with twelve 50k-character tool results manufactured a local context overflow before provider submission. Recovery compacted and persistently rewrote the session even though the controlled provider accepted the projected prompt.

Why This Change Was Made

Generic aggregate, preflight, and tool-loop character pressure now remains prompt-shaping and diagnostic input rather than proof of context overflow. Explicit opt-in mid-turn recovery remains unchanged. When a provider actually rejects context, the existing recovery path records the final provider request identity and prevents resending a byte-identical rejected payload while allowing materially changed retries.

This addresses the common false-positive authority across all three generic gates. #107821 is a useful narrow mitigation for successful aggregate replacement, but it leaves the normal preflight estimator and always-on tool-loop character guard able to manufacture the same overflow without a provider rejection.

No configuration, protocol, provider identity, public API, or persisted-session format changes.

AI-assisted: yes. I traced the runtime and upstream Codex contracts, reviewed every accepted autoreview finding, and understand the implementation and proof.

User Impact

Tool-heavy sessions can submit their bounded provider prompt without premature compaction or history loss. Genuine provider context rejections still use bounded recovery, and an identical rejected request cannot enter a retry loop.

Evidence

Deterministic Gateway reproduction on the current-main baseline:

  • Accumulated twelve real 50k-character exec results under a 1.05M model window.
  • Restarted the Gateway with the same model set to 272k, then sent a normal follow-up.
  • Baseline made 15 provider calls, triggered synthetic compaction, and retained only 1/12 historical tool results.

Exact final patch on Blacksmith Testbox via Crabbox:

  • The same real Gateway restart scenario passed in 14 provider calls.
  • All 12/12 historical tool results and the newest sentinel reached the follow-up request.
  • The follow-up completed without rerunning tools.
  • Private reproduction harness remained under ignored .artifacts/ and is intentionally not part of this PR.

Regression and repository proof:

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: L maintainer Maintainer-authored PR labels Jul 18, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Jul 18, 2026
@clawsweeper

clawsweeper Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 20, 2026, 12:23 AM ET / 04:23 UTC.

Summary
The branch removes generic synthetic overflow admission in embedded tool-heavy runs, lets actual provider context rejections drive recovery, and prevents retrying an identical rejected provider payload.

PR surface: Source +140, Tests +623. Total +763 across 35 files.

Reproducibility: yes. The PR provides a concrete current-main Gateway restart scenario with twelve large historical tool results, a reduced context budget, and observable provider-call, compaction, and transcript-retention outcomes.

Review metrics: none identified.

Stored data model
Persistent data-model change detected: persistent cache schema: src/agents/embedded-agent-runner/tool-result-char-estimator.ts, serialized state: src/agents/embedded-agent-runner/provider-prompt-state.ts, serialized state: src/agents/sessions/agent-session-base.ts, serialized state: src/agents/sessions/agent-session-loop-correctness.test.ts, serialized state: src/agents/sessions/agent-session-types.ts, serialized state: src/agents/sessions/sdk.ts, and 1 more. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #107655
Summary: This PR is a broader candidate fix for the open canonical premature-compaction bug; the other open PR addresses only one aggregate-pressure gate.

Members:

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

Merge readiness
Overall: 🦞 diamond lobster
Proof: 🦞 diamond lobster
Patch quality: 🦞 diamond lobster
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Risk before merge

  • [P1] Merging deliberately changes compatibility-sensitive recovery policy: existing sessions that previously compacted from local estimates will instead submit the shaped prompt until the provider rejects it, so an agent-runtime owner must accept the provider-authoritative boundary.
  • [P1] The patch touches recovery ownership, retry identity, lifecycle settlement, and both JSONL/SQLite persistence paths; green checks and the supplied proof reduce risk but do not replace the policy decision.

Maintainer options:

  1. Confirm the recovery authority before merge (recommended)
    Have an agent-runtime owner explicitly accept provider rejection as the authority for persistent compaction recovery, then merge with the supplied current-base proof.
  2. Keep a constrained local guard
    If provider-only authority is not acceptable, redesign the remaining local guard with an explicit non-synthetic trigger and regression coverage for projected prompts.

Next step before merge

  • [P2] No mechanical repair remains; an agent-runtime owner must decide whether the compatibility-sensitive provider-authoritative recovery policy is the intended contract before merge.

Maintainer decision needed

  • Question: Should embedded-agent whole-session compaction be authorized only by a provider-classified context rejection when a resolved model budget exists, rather than by generic local character-pressure gates?
  • Rationale: This is a deliberate compatibility-sensitive recovery-policy change across session persistence and retry behavior; tests can establish mechanics but cannot choose the product authority boundary.
  • Likely owner: joshavant — The supplied history identifies this contributor as the only concrete recent owner of the complete recovery-boundary implementation and its validation; an agent-runtime owner should make the final policy call.
  • Options:
    • Adopt provider-authoritative recovery (recommended): Accept the branch's policy: retain local estimates for shaping and diagnostics, and reserve generic whole-session recovery for actual provider rejection.
    • Retain local preflight authority: Keep one or more generic estimate gates as recovery authority, then define and test the exact conditions that avoid synthetic compaction after successful projection.

Security
Cleared: The diff adds no dependency, workflow, credential, permission, artifact-download, or public-payload-retention surface; hashed request identities are process-local and cleared at the run boundary.

Review details

Best possible solution:

Confirm that provider rejection, rather than conservative generic character estimates, is the intended authority for whole-session recovery, then land this tested internal-boundary implementation if that policy is accepted.

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

Yes. The PR provides a concrete current-main Gateway restart scenario with twelve large historical tool results, a reduced context budget, and observable provider-call, compaction, and transcript-retention outcomes.

Is this the best way to solve the issue?

Unclear pending owner approval. The patch is mechanically coherent and avoids exposing a public SDK seam, but only an agent-runtime owner can decide whether provider rejection should replace generic local recovery authority.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against d18a7cff8e54.

Label changes

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P1: Premature compaction can persistently discard usable tool-history context in active long-lived agent sessions.
  • merge-risk: 🚨 compatibility: The branch intentionally changes when existing sessions enter recovery, replacing estimate-triggered compaction with provider-authoritative rejection handling.
  • merge-risk: 🚨 session-state: The changed recovery path controls compaction and persistence of session transcripts across JSONL and SQLite owners.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; 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. Sufficient (live_output): The PR supplies after-fix real Gateway/Testbox evidence for the changed recovery path, including retained tool history, no tool reruns, and a successful follow-up; private values should remain redacted in any future proof updates.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR supplies after-fix real Gateway/Testbox evidence for the changed recovery path, including retained tool history, no tool reruns, and a successful follow-up; private values should remain redacted in any future proof updates.
Evidence reviewed

PR surface:

Source +140, Tests +623. Total +763 across 35 files.

View PR surface stats
Area Files Added Removed Net
Source 22 310 170 +140
Tests 13 706 83 +623
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 35 1016 253 +763

What I checked:

  • Linked bug remains open: The PR is linked to an open bug report describing premature compaction and persisted loss of historical tool results; no merged replacement is identified in the supplied related-item context.
  • Broader owner-boundary implementation: The patch moves generic aggregate, preflight, and tool-loop estimates to prompt-shaping/diagnostic inputs while preserving reactive recovery after a provider-classified context rejection. (src/agents/embedded-agent-runner/run/attempt-prompt-preflight.ts:147, f6baa97a09a7)
  • Retry-loop guard is run-local: The new provider-prompt state hashes the final provider payload and blocks only an identical retry after a context rejection; cleanup is owned by the embedded run-loop finally path. (src/agents/embedded-agent-runner/provider-prompt-state.ts:1, f6baa97a09a7)
  • Ownership seam stays internal: The patch uses an internal embedded-runner session constructor and removes that constructor from the public sessions barrel, with a regression test asserting it is not exported publicly. (src/agents/sessions/sdk.ts:279, f6baa97a09a7)
  • After-fix behavior proof: The PR body and follow-up report a deterministic real Gateway restart scenario where the patched path retained all 12 historical tool results, avoided tool reruns, and completed the follow-up; the later Testbox run reports 134 focused passing tests on a conflict-free current-main merge. (f6baa97a09a7)
  • Current review status: The supplied GitHub state reports the head as mergeable, all completed non-skipped checks successful or neutral, and a protected maintainer label; current-base validation was refreshed in the PR discussion.

Likely related people:

  • joshavant: Authored the focused overflow-recovery, run-lifecycle, persistence-boundary, and internal-session-seam commits on this branch, and supplied the exact-head Gateway and Testbox evidence. (role: recent area contributor; confidence: medium; commits: 6bbe1785533e, c6fafa18dc50, f6baa97a09a7; files: src/agents/embedded-agent-runner/run/overflow-context-recovery.ts, src/agents/embedded-agent-runner/provider-prompt-state.ts, src/agents/sessions/sdk.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Review history (8 earlier review cycles)
  • reviewed 2026-07-18T01:39:11.731Z sha 3d3df2c :: needs maintainer review before merge. :: none
  • reviewed 2026-07-18T01:55:03.562Z sha 8373f64 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-18T09:24:49.365Z sha 69ddaa9 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-18T10:07:07.868Z sha 69ddaa9 :: found issues before merge. :: [P1] Keep recovery ownership out of the public session SDK
  • reviewed 2026-07-20T01:56:40.609Z sha eb623c0 :: found issues before merge. :: [P1] Keep recovery ownership out of the public session SDK
  • reviewed 2026-07-20T02:39:23.891Z sha eb623c0 :: found issues before merge. :: [P1] Keep recovery ownership out of the public session SDK
  • reviewed 2026-07-20T03:29:53.363Z sha c6fafa1 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-20T03:38:48.256Z sha f6baa97 :: needs maintainer review before merge. :: none

@joshavant

Copy link
Copy Markdown
Collaborator Author

Implemented the remaining root-cause owner-boundary work at 9e1f2eebc3f:

  • The embedded caller owns bounded reactive overflow recovery only when it has a resolved model budget; otherwise the inner session retains recovery. This prevents competing retry loops without dropping budgetless/length recovery.
  • SQLite compaction now stays with the transactional transcript owner; the JSONL append fence remains only on JSONL.
  • Reactive recovery consumes the canonical typed assistant overflow result, including zero-output length stops, before the legacy text heuristic.
  • A successful auxiliary/compaction request no longer clears the rejected primary payload identity. Exact replay stays blocked until the run-finally owner clears it.
  • A new lifecycle start replaces deferred terminal error/metadata from the rejected attempt, so a successful recovery cannot finish as stale aborted.

The persistent-data warning is a false positive: provider-prompt identity is process-local run state cleared in run-loop finally, and this change uses the existing SQLite transcript schema with no schema bump or migration.

Current proof:

  • 184 focused tests across all newly touched owner boundaries passed locally.
  • Fresh full-patch autoreview: clean, 0.90 confidence; the two test-hygiene follow-ups were also clean at 0.98/0.93.
  • Synthetic current-base merge de59fdada1e over ab093bded4f: full check:changed passed (14m54s), including core/core-test typechecks and all lint/guard lanes; packaged build passed (1m31s).
  • Final Gateway proof used a Testbox hydrated at exact base 993c975f573, then tested merge 46feed50ea0: both lanes passed (2/2, 39.13s). The rejection lane executed 12 large tools once, observed exactly one rejected primary payload, one compaction-summary request, and one accepted retry with a different payload hash; the newest tool sentinel survived and no tool reran.
  • No external credentials were used.

This evidence supports the broader provider-authoritative policy as the best fix: local estimates shape and diagnose, while an actual provider rejection is the authority for whole-session recovery. The narrower aggregate-only patch would leave the same false authority in preflight and tool-loop paths.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Jul 18, 2026
@joshavant
joshavant force-pushed the fix/provider-authoritative-context-pressure branch from 69ddaa9 to eb623c0 Compare July 20, 2026 01:30
@joshavant

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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 Jul 20, 2026
@joshavant

Copy link
Copy Markdown
Collaborator Author

ClawSweeper follow-up evidence:

  • Final PR head: f6baa97.
  • Exact-head hosted CI completed with 81 passing checks, 35 expected skips, and no failures.
  • Current-main synthetic merge: 9ace489026bb46ac30a3982a411f8fd4fdf7f1a0, with parents main 990916c and PR head f6baa97. The merge was conflict-free and current main had zero changed-path overlap with the PR.
  • Testbox tbx_01kxysz5t6yqccavycwmym3x5v passed 134/134 focused tests covering overflow-compaction recovery, embedded session ownership, context-engine SQLite behavior, and persistence/retry boundaries: https://github.com/openclaw/openclaw/actions/runs/29715289805
  • The disposable merge worktree and proof artifacts were removed; this proof did not rewrite the PR branch.

This closes the current-main merge-proof rank-up move. Agent-runtime owner confirmation of the provider-authoritative recovery policy remains the final non-mechanical maintainer decision.

@clawsweeper

clawsweeper Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@joshavant

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Jul 20, 2026
@joshavant

Copy link
Copy Markdown
Collaborator Author

Final pre-landing audit follow-up for exact PR head f6baa97a09a70a4c3681fd0fbe8e88b470c882f4:

  • Closed the final two P2 matrix rows without changing the PR.
  • Blacksmith Testbox tbx_01ky0taawkqbc48e5yeq7rjw95, run 29784038094: exact-head packaged build passed; the private audit suite passed 5/5 in 63.63s.
  • Empty, error-only, and legacy role=tool results projected deterministically across fresh runs, retained model-visible content, ignored the large hidden-only detail for pressure, and emitted no mid-turn recovery signal.
  • After repeated provider context rejection exhausted bounded recovery, a real Gateway /new turn rotated the session id, sent a fresh provider request with zero historical function outputs and no rejected-follow-up marker, preserved single execution of all 12 prior tools, and completed with one final answer.
  • No credential was used. The Testbox was stopped, temporary tracked proof paths were removed, the harness remains private under .artifacts/, and the branch worktree is clean.

The private matrix now has 71 passing candidate scenarios, zero planned/blocked/implementation-failing scenarios, and one intentionally retained current-main negative control. This completes the requested user-facing proof audit; ClawSweeper's explicit agent-runtime owner acceptance of provider-authoritative recovery remains the only non-mechanical decision before landing.

@joshavant
joshavant merged commit e07de4c into main Jul 20, 2026
128 of 130 checks passed
@joshavant
joshavant deleted the fix/provider-authoritative-context-pressure branch July 20, 2026 22:49
@joshavant

Copy link
Copy Markdown
Collaborator Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 21, 2026
…w#110297)

* fix(agents): defer context overflow to provider

* fix(agents): align provider pressure tests

* fix(agents): make overflow recovery authoritative

* test(agents): preserve generic compaction lock type

* test(agents): auto-clean SQLite compaction fixture

* test(agents): keep compaction guard private

* fix(agents): keep overflow recovery ownership internal

* fix(agents): preserve session sdk type exports
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. 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.

[Bug]: Aggregate tool-result pressure forces compaction after prompt projection already truncates successfully

2 participants