Skip to content

fix: keep a sub-agent's task when a retry reloads oversized history - #201636

Merged
obviyus merged 2 commits into
mainfrom
fix/keep-subagent-task-on-retry-201605
Nov 19, 2026
Merged

obviyus merged 2 commits into
mainfrom
fix/keep-subagent-task-on-retry-201605

Conversation

@obviyus

@obviyus obviyus commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Root cause: src/config/sessions/session-model-context-window.ts:168 takes a history suffix that starts inside the current turn when that turn's tool results exceed the history byte cap, so a retry that reloads history mid-turn loses the request that opened the turn.

Fixes #201605

What Problem This Solves

A sub-agent working through a long, tool-heavy task (screenshots, large reads) can hit a provider stream error such as degenerate_output. OpenClaw retries on the same model, but the retry's request no longer contains the sub-agent's task. The model only sees the system prompt, a failure note and "continue the current task", so it answers without doing the work and the parent receives a "completed" child that did nothing.

User Impact

User impact: after a transient provider failure, a sub-agent (or any agent turn) whose tool results have grown past the history byte cap retries with its task still in front of the model and continues the work. Turns under the cap, new turns, and retries whose failed stream produced no output are unchanged.

Why This Change Was Made

The first attempt builds its history in memory. A retry reloads the transcript through the bounded history window, which keeps the newest events that fit in eight bytes per context token. Inside one long turn there is no later turn boundary to align to, so the window kept only the newest tool frames and dropped the turn's user request. The internal continuation prompt then became the first user message, which is the historyRewrite(message 0 (user) differs ...) line in the report.

The window now keeps the request that opened the current turn and fills the rest of the cap with the newest frames, the same way it already reserves the latest compaction summary. If that request cannot fit beside any frame, the old suffix is kept. Saved history is not changed.

Evidence

Real Gateway from source with a local OpenAI Responses provider that records every request. The parent calls sessions_spawn with a task; the child reads two screenshot-sized images, then its third stream emits text followed by a runaway tool call that trips degenerate_output.

  • main (67aacbb), twice: the retry request is [system, failed-turn note, "Continue the current task...", runtime context], with no task. The child ends with stopReason=stop 1.3 s later.
  • This branch, twice: the retry request starts with the same task message as the first attempt, and the child continues the task.
  • Controls on both builds: a sub-agent turn that does not fail is identical; an output-free failure and a small-history failure already kept the task.
  • Regression test keeps the current turn's request when its tool frames exceed the byte cap: fails on main (expected [ 3, 4, 5 ] to deeply equal [ +0, 3, 4, 5 ]), passes here.

Observed request lines: #201636 (comment)
Re-run after the review fix (tool ownership kept): #201636 (comment)

Thanks @mike1122real-hub for the detailed report with the four failure timings and the history-rewrite line.

Merge danger

Two-way door: the change only selects which saved events are loaded for one model request and writes nothing, so a revert fully restores the old selection. Blast radius: embedded agent turns whose loaded history exceeds the byte cap in the middle of a turn; they now send the turn's request plus slightly fewer of the oldest tool frames from that turn.

Root cause: src/config/sessions/session-model-context-window.ts:168 slices the bounded history suffix inside the current turn when that turn's tool frames exceed the byte cap, dropping the user request that opened the turn. An in-turn transient retry reloads history through this window, so it answered without its task.

The window now keeps the turn's opening request in front of the newest affordable frames; a request that cannot fit keeps the old suffix.

Fixes #201605
@clawsweeper

clawsweeper Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@obviyus

obviyus commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

Base 67aacbb676 (main) vs candidate 2225b79e02 (this PR head). Gateway proof (source tier, isolated profile, local OpenAI Responses fixture recording each request). Parent calls sessions_spawn with task CHILD-TASK-201605; the child reads two screenshot-sized images, then its third stream emits text and a runaway tool call (degenerate_output).

== base3-img
child:read-image-step-1 sawTask=true input=["system","user:<task>…","user:<runtime-context>…"]
child:read-image-step-2 sawTask=true input=["system","user:<task>…","user:<runtime-context>…","function_call","function_call_output"]
child:degenerate-stream sawTask=true input=["system","user:<task>…","user:<runtime-context>…","function_call","function_call_output","function_call","function_call_output"]
child:final-WITHOUT-task sawTask=false input=["system","assistant:[This turn failed before it completed. D…","user:Continue the current task from the exi…","user:<runtime-context>…"]
2026-11-19T10:31:02.536+05:30 [provider-error] Model request failed sessionKey=<child>  requestNumber=3 provider=mock-openai model=child name=DegenerateToolCallArgumentsError abortReason=degenerate_output code=degenerate_output 
2026-11-19T10:31:03.876+05:30 [agents/agent-command] [agent] run <child> ended with stopReason=stop
== base5-img-repeat
child:read-image-step-1 sawTask=true input=["system","user:<task>…","user:<runtime-context>…"]
child:read-image-step-2 sawTask=true input=["system","user:<task>…","user:<runtime-context>…","function_call","function_call_output"]
child:degenerate-stream sawTask=true input=["system","user:<task>…","user:<runtime-context>…","function_call","function_call_output","function_call","function_call_output"]
child:final-WITHOUT-task sawTask=false input=["system","assistant:[This turn failed before it completed. D…","user:Continue the current task from the exi…","user:<runtime-context>…"]
2026-11-19T10:38:59.063+05:30 [provider-error] Model request failed sessionKey=<child>  requestNumber=3 provider=mock-openai model=child name=DegenerateToolCallArgumentsError abortReason=degenerate_output code=degenerate_output 
2026-11-19T10:39:00.277+05:30 [agents/agent-command] [agent] run <child> ended with stopReason=stop
== cand1-img
child:read-image-step-1 sawTask=true input=["system","user:<task>…","user:<runtime-context>…"]
child:read-image-step-2 sawTask=true input=["system","user:<task>…","user:<runtime-context>…","function_call","function_call_output"]
child:degenerate-stream sawTask=true input=["system","user:<task>…","user:<runtime-context>…","function_call","function_call_output","function_call","function_call_output"]
child:read-image-step-1 sawTask=true input=["system","user:<task>…","assistant:[This turn failed before it completed. D…","user:Continue the current task from the exi…","user:<runtime-context>…"]
child:read-image-step-2 sawTask=true input=["system","user:<task>…","assistant:[This turn failed before it completed. D…","user:Continue the current task from the exi…","user:<runtime-context>…","function_call","function_call_output"]
child:final-with-task sawTask=true input=["system","user:<task>…","assistant:[This turn failed before it completed. D…","user:Continue the current task from the exi…","user:<runtime-context>…","function_call","function_call_output","function_call","function_call_output"]
2026-11-19T10:35:24.138+05:30 [provider-error] Model request failed sessionKey=<child>  requestNumber=3 provider=mock-openai model=child name=DegenerateToolCallArgumentsError abortReason=degenerate_output code=degenerate_output 
2026-11-19T10:35:26.202+05:30 [agents/agent-command] [agent] run <child> ended with stopReason=stop
== cand3-img-repeat
child:read-image-step-1 sawTask=true input=["system","user:<task>…","user:<runtime-context>…"]
child:read-image-step-2 sawTask=true input=["system","user:<task>…","user:<runtime-context>…","function_call","function_call_output"]
child:degenerate-stream sawTask=true input=["system","user:<task>…","user:<runtime-context>…","function_call","function_call_output","function_call","function_call_output"]
child:read-image-step-1 sawTask=true input=["system","user:<task>…","assistant:[This turn failed before it completed. D…","user:Continue the current task from the exi…","user:<runtime-context>…"]
child:read-image-step-2 sawTask=true input=["system","user:<task>…","assistant:[This turn failed before it completed. D…","user:Continue the current task from the exi…","user:<runtime-context>…","function_call","function_call_output"]
child:final-with-task sawTask=true input=["system","user:<task>…","assistant:[This turn failed before it completed. D…","user:Continue the current task from the exi…","user:<runtime-context>…","function_call","function_call_output","function_call","function_call_output"]
2026-11-19T10:39:54.682+05:30 [provider-error] Model request failed sessionKey=<child>  requestNumber=3 provider=mock-openai model=child name=DegenerateToolCallArgumentsError abortReason=degenerate_output code=degenerate_output 
2026-11-19T10:39:56.932+05:30 [agents/agent-command] [agent] run <child> ended with stopReason=stop
== base-control
child:read-image-step-1 sawTask=true input=["system","user:<task>…","user:<runtime-context>…"]
child:read-image-step-2 sawTask=true input=["system","user:<task>…","user:<runtime-context>…","function_call","function_call_output"]
child:final-with-task sawTask=true input=["system","user:<task>…","user:<runtime-context>…","function_call","function_call_output","function_call","function_call_output"]
2026-11-19T10:38:24.167+05:30 [agents/agent-command] [agent] run <child> ended with stopReason=stop
== cand-control
child:read-image-step-1 sawTask=true input=["system","user:<task>…","user:<runtime-context>…"]
child:read-image-step-2 sawTask=true input=["system","user:<task>…","user:<runtime-context>…","function_call","function_call_output"]
child:final-with-task sawTask=true input=["system","user:<task>…","user:<runtime-context>…","function_call","function_call_output","function_call","function_call_output"]
2026-11-19T10:36:49.984+05:30 [agents/agent-command] [agent] run <child> ended with stopReason=stop

@obviyus
obviyus marked this pull request as ready for review November 19, 2026 05:39
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: S labels Nov 19, 2026
@obviyus

obviyus commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. 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 19, 2026
@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Preserve the current turn’s opening request when a retry reloads oversized history, while retaining byte limits and canonical tool-result ownership.

Example: A child running CHILD-TASK-201605 reads two large images and encounters degenerate_output.

  • Before: The retry loses the task and completes without doing the remaining work.
  • After: The retry retains the task and continues working.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, useful repair with production-entry-point evidence and the prior correctness finding resolved; broad exact-head validation remains in progress.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): Isolated source-built Gateway runs exercise sessions_spawn, real request assembly and transport to a recording local Responses provider, large image reads, and injected degenerate output; the exact-head rerun retains the task through recovery, with an unchanged successful-run control.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A transient provider failure can make a tool-heavy sub-agent forget its task and report completion without doing the remaining work.
Reason: The collaborator-authored direction addresses demonstrated loss of active work without new settings, public APIs, or persistence changes.

Merge readiness

✅ Ready for maintainer review

This PR fixes demonstrated task loss during oversized-history retries, and the earlier tool-ownership finding is resolved; no actionable defects remain, with exact-head CI still pending.

Priority: P1
Reviewed head: 4da45c441b5ba32f3b542997b6b7033d2638f885

Before merge

None.

Findings

None.

Agent review details

How this fits together

The session model-context selector converts canonical transcript requests and resource limits into bounded history loaded by agent attempts and retries.

flowchart LR
  A[Canonical transcript] --> B[Context projection]
  B --> C[Bounded history selector]
  C --> D[Task and owned recent frames]
  D --> E[Agent retry]
  E --> F[Provider request]
Loading

Technical review

Best possible solution:

Retain the affordable opening task in the existing bounded selector while preserving required summaries, hard limits, and canonical tool-result ownership.

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

Supplied Gateway captures reproduce task loss twice on the pinned base after large image results and degenerate output; source inspection confirms the responsible suffix selection, and no target code was executed during this review.

Is this the best way to solve the issue?

The change repairs the existing selection owner directly, reuses its bounded-tail logic, and now preserves the canonical pairing facts that the earlier implementation lost.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Stepped bounded-history selection changes intended behavior with a stated reason (c16bff1: Prefer stable quarter-cap history windows and complete turns to improve prompt-cache reuse without exceeding resource limits.)
  • Canonical tool-result ownership keeps the original intent (afbd484: Share pairing facts while preventing truncation from assigning a result to a different occurrence of a repeated call ID.)
  • Tool-result omission and restoration keeps the original intent (d5e82b9: Prefer retaining requests over large result bodies in the existing omit mode while leaving saved transcripts intact.)
  • Oversized previous-turn fallback keeps the original intent (5958c81: Avoid loading only a trailing prompt that the runner removes before inference.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit c16bff1 adds src/config/sessions/session-model-context-window.ts:99 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: c16bff1978ba; files: src/config/sessions/session-model-context-window.ts)
  • Yun.: Raw commit 5958c81 adds src/config/sessions/session-model-context-window.ts:164 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 5958c8191e0a; files: src/config/sessions/session-model-context-window.ts)
  • Yuriy: Raw commit d5e82b9 adds src/config/sessions/session-model-context-window.ts:141 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: d5e82b993600; files: src/config/sessions/session-model-context-window.ts)

PR surface

Source +30, Tests +41, Docs +3. Total +74 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 39 9 +30
Tests 1 41 0 +41
Docs 1 3 0 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 83 9 +74

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 rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: Reported and captured retries silently lose delegated tasks and return apparently completed children without completing the work.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • 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 execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-11-19T05:44:29.147Z sha 2225b79 :: needs changes before merge. :: [P2] Preserve canonical tool ownership when selecting the reserved tail

Reviewed November 19, 2026, 1:27 AM ET / 06:27 UTC (Revision 2).

The pinned tail is selected without the calls before the request, so validate it against the canonical tool-result owners and keep the plain suffix when a result would lose its call.
@obviyus

obviyus commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

Re-run on 4da45c441b (review fix: the pinned tail keeps canonical tool ownership). Same harness as the first proof comment; base 67aacbb676 lines are there.

== cand4-img-r2
child:read-image-step-1 sawTask=true input=["system","user:<task>…","user:<runtime-context>…"]
child:read-image-step-2 sawTask=true input=["system","user:<task>…","user:<runtime-context>…","function_call","function_call_output"]
child:degenerate-stream sawTask=true input=["system","user:<task>…","user:<runtime-context>…","function_call","function_call_output","function_call","function_call_output"]
child:read-image-step-1 sawTask=true input=["system","user:<task>…","assistant:[This turn failed before it completed. D…","user:Continue the current task from the exi…","user:<runtime-context>…"]
child:read-image-step-2 sawTask=true input=["system","user:<task>…","assistant:[This turn failed before it completed. D…","user:Continue the current task from the exi…","user:<runtime-context>…","function_call","function_call_output"]
child:final-with-task sawTask=true input=["system","user:<task>…","assistant:[This turn failed before it completed. D…","user:Continue the current task from the exi…","user:<runtime-context>…","function_call","function_call_output","function_call","function_call_output"]
2026-11-19T11:45:07.345+05:30 [provider-error] Model request failed sessionKey=<child>  requestNumber=3 provider=mock-openai model=child name=DegenerateToolCallArgumentsError abortReason=degenerate_output code=degenerate_output 
== cand-control-r2
child:read-image-step-1 sawTask=true input=["system","user:<task>…","user:<runtime-context>…"]
child:read-image-step-2 sawTask=true input=["system","user:<task>…","user:<runtime-context>…","function_call","function_call_output"]
child:final-with-task sawTask=true input=["system","user:<task>…","user:<runtime-context>…","function_call","function_call_output","function_call","function_call_output"]

ocx test session-model-context-window + pairing: 19 passed on 4da45c441b; the displaced-result case fails on 2225b79e02 (expected [ 2, 3, 4 ] to deeply equal [ 4 ]).

@obviyus

obviyus commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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 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 Nov 19, 2026
@obviyus

obviyus commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override: checks-ui-e2e (1/2) on 4da45c4 failed during runner setup, before any test ran, for a reason this diff cannot reach.

  • Job: https://github.com/openclaw/openclaw/actions/runs/44471725333/job/135383350097
  • Failing step 8, "Install selected Control UI E2E WebKit", 06:26:04 to 06:33:04 (7 min): ##[error]WebKit system packages did not download from the fallback archive mirrors (exit 124). The log ends in apt fetches from azure.archive.ubuntu.com / mirrors.edge.kernel.org. Steps 9 ("Prepare selected Control UI E2E Gateway runtime") and 10 ("Test Control UI end-to-end") were skipped, so no Control UI test ran.
  • The PR changes only src/config/sessions/session-model-context-window.ts (bounded history selection for model replay), its unit test, and docs/concepts/compaction.md. It touches no Control UI, Playwright, WebKit, or CI setup.
  • On the previous head 2225b79 the same CI workflow passed (run 44466662974, openclaw/ci-gate pass). Between the two heads only the selector's tool-ownership check and its unit test changed.
  • All other jobs in run 44471725333 passed. Cancelled: 0.

@obviyus
obviyus merged commit adda3db into main Nov 19, 2026
126 of 129 checks passed
@obviyus
obviyus deleted the fix/keep-subagent-task-on-retry-201605 branch November 19, 2026 06:45
@obviyus

obviyus commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks @mike1122real-hub for the detailed report. This is merged in adda3db: when a sub-agent's turn fails mid-stream and is retried, the retry now keeps the message that started the turn (the sub-agent's task) even when large tool results such as screenshots fill the retry's history window, so the sub-agent continues its task instead of answering without it. The history byte cap is unchanged, and a tool result is never kept without its call.

RomneyDa added a commit that referenced this pull request Nov 19, 2026
…201636)

Root cause: src/config/sessions/session-model-context-window.ts:168 takes a history suffix that starts inside the current turn when that turn's tool results exceed the history byte cap, so a retry that reloads history mid-turn loses the request that opened the turn.

Fixes #201605

## What Problem This Solves

A sub-agent working through a long, tool-heavy task (screenshots, large reads) can hit a provider stream error such as `degenerate_output`. OpenClaw retries on the same model, but the retry's request no longer contains the sub-agent's task. The model only sees the system prompt, a failure note and "continue the current task", so it answers without doing the work and the parent receives a "completed" child that did nothing.

## User Impact

User impact: after a transient provider failure, a sub-agent (or any agent turn) whose tool results have grown past the history byte cap retries with its task still in front of the model and continues the work. Turns under the cap, new turns, and retries whose failed stream produced no output are unchanged.

## Why This Change Was Made

The first attempt builds its history in memory. A retry reloads the transcript through the bounded history window, which keeps the newest events that fit in eight bytes per context token. Inside one long turn there is no later turn boundary to align to, so the window kept only the newest tool frames and dropped the turn's user request. The internal continuation prompt then became the first user message, which is the `historyRewrite(message 0 (user) differs ...)` line in the report.

The window now keeps the request that opened the current turn and fills the rest of the cap with the newest frames, the same way it already reserves the latest compaction summary. If that request cannot fit beside any frame, the old suffix is kept. Saved history is not changed.

## Evidence

Real Gateway from source with a local OpenAI Responses provider that records every request. The parent calls `sessions_spawn` with a task; the child reads two screenshot-sized images, then its third stream emits text followed by a runaway tool call that trips `degenerate_output`.

- `main` (67aacbb), twice: the retry request is `[system, failed-turn note, "Continue the current task...", runtime context]`, with no task. The child ends with `stopReason=stop` 1.3 s later.
- This branch, twice: the retry request starts with the same task message as the first attempt, and the child continues the task.
- Controls on both builds: a sub-agent turn that does not fail is identical; an output-free failure and a small-history failure already kept the task.
- Regression test `keeps the current turn's request when its tool frames exceed the byte cap`: fails on `main` (`expected [ 3, 4, 5 ] to deeply equal [ +0, 3, 4, 5 ]`), passes here.

Observed request lines: #201636 (comment)
Re-run after the review fix (tool ownership kept): #201636 (comment)

Thanks @mike1122real-hub for the detailed report with the four failure timings and the history-rewrite line.

## Merge danger

Two-way door: the change only selects which saved events are loaded for one model request and writes nothing, so a revert fully restores the old selection. Blast radius: embedded agent turns whose loaded history exceeds the byte cap in the middle of a turn; they now send the turn's request plus slightly fewer of the oldest tool frames from that turn.

Co-authored-by: Ayaan Zaidi <[email protected]>

(cherry picked from commit adda3db)

Co-authored-by: RomneyDa <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 20, 2026
…penclaw#201636)

Root cause: src/config/sessions/session-model-context-window.ts:168 takes a history suffix that starts inside the current turn when that turn's tool results exceed the history byte cap, so a retry that reloads history mid-turn loses the request that opened the turn.

Fixes openclaw#201605

## What Problem This Solves

A sub-agent working through a long, tool-heavy task (screenshots, large reads) can hit a provider stream error such as `degenerate_output`. OpenClaw retries on the same model, but the retry's request no longer contains the sub-agent's task. The model only sees the system prompt, a failure note and "continue the current task", so it answers without doing the work and the parent receives a "completed" child that did nothing.

## User Impact

User impact: after a transient provider failure, a sub-agent (or any agent turn) whose tool results have grown past the history byte cap retries with its task still in front of the model and continues the work. Turns under the cap, new turns, and retries whose failed stream produced no output are unchanged.

## Why This Change Was Made

The first attempt builds its history in memory. A retry reloads the transcript through the bounded history window, which keeps the newest events that fit in eight bytes per context token. Inside one long turn there is no later turn boundary to align to, so the window kept only the newest tool frames and dropped the turn's user request. The internal continuation prompt then became the first user message, which is the `historyRewrite(message 0 (user) differs ...)` line in the report.

The window now keeps the request that opened the current turn and fills the rest of the cap with the newest frames, the same way it already reserves the latest compaction summary. If that request cannot fit beside any frame, the old suffix is kept. Saved history is not changed.

## Evidence

Real Gateway from source with a local OpenAI Responses provider that records every request. The parent calls `sessions_spawn` with a task; the child reads two screenshot-sized images, then its third stream emits text followed by a runaway tool call that trips `degenerate_output`.

- `main` (78f5d6e), twice: the retry request is `[system, failed-turn note, "Continue the current task...", runtime context]`, with no task. The child ends with `stopReason=stop` 1.3 s later.
- This branch, twice: the retry request starts with the same task message as the first attempt, and the child continues the task.
- Controls on both builds: a sub-agent turn that does not fail is identical; an output-free failure and a small-history failure already kept the task.
- Regression test `keeps the current turn's request when its tool frames exceed the byte cap`: fails on `main` (`expected [ 3, 4, 5 ] to deeply equal [ +0, 3, 4, 5 ]`), passes here.

Observed request lines: openclaw#201636 (comment)
Re-run after the review fix (tool ownership kept): openclaw#201636 (comment)

Thanks @mike1122real-hub for the detailed report with the four failure timings and the history-rewrite line.

## Merge danger

Two-way door: the change only selects which saved events are loaded for one model request and writes nothing, so a revert fully restores the old selection. Blast radius: embedded agent turns whose loaded history exceeds the byte cap in the middle of a turn; they now send the turn's request plus slightly fewer of the oldest tool frames from that turn.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 22, 2026
…#203536)

Result: between two compactions, the history the model sees now only grows. It no longer slides on each new attempt, so the provider prompt cache and the OpenAI Responses continuation keep matching. Token-based compaction is the only step that shortens it.

## What Problem This Solves

Each attempt (a new turn, a subagent settle, `sessions_send`, a retry) loads history through `selectBoundedModelRequests` with a byte cap of `contextTokenBudget × 8`. The attempt then grows that history in memory with no cap. The next attempt reloads it and cuts the oldest turns again. Message 0/1 moves, the Responses continuation becomes `history_changed`/`history_shorter`, and the full replay hits only instructions and tools.

The cap counts serialized bytes. Encrypted reasoning, thinking signatures, images and event envelopes use 8-30 bytes per token, so the cut fires far below the token budget (1-2 MB for 70-170k tokens of a 272k budget). The cut also hides the dropped history from the compaction estimate, so the session slides on every quarter-cap of growth and never compacts.

On a busy production host this is the largest remaining cache loss: 186 head cuts in 24 h, 14.64M uncached input tokens (1.84% of input). All are `request=1`, the first request of an attempt.

## Why This Change Was Made

Repo rule (AGENTS.md, stable conversation context): "Preserve transcript bytes; only compaction rewrites history." The hydration cut rewrote history outside compaction.

- `resolveEmbeddedSessionContextLimits` returns a fixed 16 MiB / 10,000-event guard. It no longer depends on the token budget. 16 MiB stays below the smallest provider request-body limit (Gemini inline data, 20 MB). Images count only about 2,000 tokens each in the compaction estimate, so a larger guard could let a request pass a body limit before compaction fires.
- Token compaction (preflight, mid-turn precheck, overflow recovery) already owns model-context size. It now sees the whole history since the boundary, so a long session compacts once, as a recorded and declared rebuild, instead of sliding on every attempt.
- The `contextTokenBudget` plumbing that existed only for this cap is removed (`prepareRecoverySession`, `readCompactionTranscriptBytes`, `readPreflightTranscriptContextMessages`).
- Unchanged: `selectBoundedModelRequests` and its fallbacks (quarter-cap steps, #191146 trailing prompt, #201636 in-turn request reservation). They now run only past the 16 MiB guard. The settled-tool finalizer keeps `toolResultOverflow: "omit"` (#184704). With the larger guard, it keeps every result body in every case that fit before.
- Rejected: a sticky recorded cut (it still moves once per growth step, and it needs a new boundary writer outside compaction) and byte counting that excludes opaque fields (that needs per-provider payload parsing).

Accepted edge cases, without code:
- A session that passes 16 MiB before it compacts (a long run of screenshots) still slides in 4 MiB steps, not 512 KB steps.
- On deploy, a session that already slid loads its history again once (one uncached replay). Then it can compact.
- Plugin harnesses that use `resolveAgentHarnessHistoryLimits` (Plugin SDK) keep their own budget-based bound. That is a public SDK export with different seeding semantics, so it gets its own follow-up.

## Evidence

**Regression step on every transport.** The step is in the prefix-stability journey (`test/prompt-cache-prefix-stability.test-support.ts`). A chat on the 64k-window model views four incompressible screenshots: more than 512 KB, the old cut, and far below compaction. Two plain turns follow. Each turn is a new attempt, and every request must extend the previous one.
- Base `8d1e59c2fddc`: red on all 5 transports (anthropic, bedrock, google, openai-completions, openai-responses), with two `message 0` breaks each.
- This head: green on all 5.
- Mutation: the head with the old `budget × 8` cap restored is red again.

**Scratch Gateway E2E.** Native `https://api.openai.com/v1`, `openai/gpt-6.2-astra`, Code Mode, 64k context window. Six turns: four view screenshots, two are plain. Request bodies and `response.completed` usage were captured.

| req | base status | base input / cached | head status | head input / cached |
|---|---|---|---|---|
| 1-6 | first, then `continued` | 17096/0 … 18214/18099 | same | same |
| 7 (turn 3, request=1) | `history_shorter`, msg 1 moved, 10 items sent in full | 17959 / **16430** | `continued`, 2 items sent | 18853 / 18211 |
| 8-10 | `continued` | … 18853/18738 | `continued` | … 19747/19632 |
| 11 (turn 5, request=1) | `history_shorter`, msg 1 moved, 13 items sent in full | 18598 / **16430** | `continued`, 2 items sent | 20386 / 19744 |
| 12 | `continued` | 19237/18030 | `continued` | 21025/19818 |

16430 is the instructions+tools prefix alone. Base logged `historyRewrite(message 0 (user) differs ...)` twice, and head logged it zero times.

Tests: the touched test files and every test file that imports a changed source (31 files), `pnpm check:changed`, oxfmt and oxlint.

## What Changes for Users

Long sessions with reasoning, screenshots or many tool calls keep their prompt cache across turns, subagent settles and retries. The model also sees its full history until compaction, where before old turns were dropped silently.

## Merge danger

Two-way door. No schema, config or stored-row change. A revert restores the budget-based cut. Blast radius: embedded attempts whose history since the last compaction is larger than 8 bytes per budget token. These now send more history, and token compaction trims it.

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

Result: between two compactions, the history the model sees now only grows. It no longer slides on each new attempt, so the provider prompt cache and the OpenAI Responses continuation keep matching. Token-based compaction is the only step that shortens it.

## What Problem This Solves

Each attempt (a new turn, a subagent settle, `sessions_send`, a retry) loads history through `selectBoundedModelRequests` with a byte cap of `contextTokenBudget × 8`. The attempt then grows that history in memory with no cap. The next attempt reloads it and cuts the oldest turns again. Message 0/1 moves, the Responses continuation becomes `history_changed`/`history_shorter`, and the full replay hits only instructions and tools.

The cap counts serialized bytes. Encrypted reasoning, thinking signatures, images and event envelopes use 8-30 bytes per token, so the cut fires far below the token budget (1-2 MB for 70-170k tokens of a 272k budget). The cut also hides the dropped history from the compaction estimate, so the session slides on every quarter-cap of growth and never compacts.

On a busy production host this is the largest remaining cache loss: 186 head cuts in 24 h, 14.64M uncached input tokens (1.84% of input). All are `request=1`, the first request of an attempt.

## Why This Change Was Made

Repo rule (AGENTS.md, stable conversation context): "Preserve transcript bytes; only compaction rewrites history." The hydration cut rewrote history outside compaction.

- `resolveEmbeddedSessionContextLimits` returns a fixed 16 MiB / 10,000-event guard. It no longer depends on the token budget. 16 MiB stays below the smallest provider request-body limit (Gemini inline data, 20 MB). Images count only about 2,000 tokens each in the compaction estimate, so a larger guard could let a request pass a body limit before compaction fires.
- Token compaction (preflight, mid-turn precheck, overflow recovery) already owns model-context size. It now sees the whole history since the boundary, so a long session compacts once, as a recorded and declared rebuild, instead of sliding on every attempt.
- The `contextTokenBudget` plumbing that existed only for this cap is removed (`prepareRecoverySession`, `readCompactionTranscriptBytes`, `readPreflightTranscriptContextMessages`).
- Unchanged: `selectBoundedModelRequests` and its fallbacks (quarter-cap steps, openclaw#191146 trailing prompt, openclaw#201636 in-turn request reservation). They now run only past the 16 MiB guard. The settled-tool finalizer keeps `toolResultOverflow: "omit"` (openclaw#184704). With the larger guard, it keeps every result body in every case that fit before.
- Rejected: a sticky recorded cut (it still moves once per growth step, and it needs a new boundary writer outside compaction) and byte counting that excludes opaque fields (that needs per-provider payload parsing).

Accepted edge cases, without code:
- A session that passes 16 MiB before it compacts (a long run of screenshots) still slides in 4 MiB steps, not 512 KB steps.
- On deploy, a session that already slid loads its history again once (one uncached replay). Then it can compact.
- Plugin harnesses that use `resolveAgentHarnessHistoryLimits` (Plugin SDK) keep their own budget-based bound. That is a public SDK export with different seeding semantics, so it gets its own follow-up.

## Evidence

**Regression step on every transport.** The step is in the prefix-stability journey (`test/prompt-cache-prefix-stability.test-support.ts`). A chat on the 64k-window model views four incompressible screenshots: more than 512 KB, the old cut, and far below compaction. Two plain turns follow. Each turn is a new attempt, and every request must extend the previous one.
- Base `735a7475c1fb`: red on all 5 transports (anthropic, bedrock, google, openai-completions, openai-responses), with two `message 0` breaks each.
- This head: green on all 5.
- Mutation: the head with the old `budget × 8` cap restored is red again.

**Scratch Gateway E2E.** Native `https://api.openai.com/v1`, `openai/gpt-6.2-astra`, Code Mode, 64k context window. Six turns: four view screenshots, two are plain. Request bodies and `response.completed` usage were captured.

| req | base status | base input / cached | head status | head input / cached |
|---|---|---|---|---|
| 1-6 | first, then `continued` | 17096/0 … 18214/18099 | same | same |
| 7 (turn 3, request=1) | `history_shorter`, msg 1 moved, 10 items sent in full | 17959 / **16430** | `continued`, 2 items sent | 18853 / 18211 |
| 8-10 | `continued` | … 18853/18738 | `continued` | … 19747/19632 |
| 11 (turn 5, request=1) | `history_shorter`, msg 1 moved, 13 items sent in full | 18598 / **16430** | `continued`, 2 items sent | 20386 / 19744 |
| 12 | `continued` | 19237/18030 | `continued` | 21025/19818 |

16430 is the instructions+tools prefix alone. Base logged `historyRewrite(message 0 (user) differs ...)` twice, and head logged it zero times.

Tests: the touched test files and every test file that imports a changed source (31 files), `pnpm check:changed`, oxfmt and oxlint.

## What Changes for Users

Long sessions with reasoning, screenshots or many tool calls keep their prompt cache across turns, subagent settles and retries. The model also sees its full history until compaction, where before old turns were dropped silently.

## Merge danger

Two-way door. No schema, config or stored-row change. A revert restores the budget-based cut. Blast radius: embedded attempts whose history since the last compaction is larger than 8 bytes per budget token. These now send more history, and token compaction trims it.

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

Root cause: src/config/sessions/session-model-context-window.ts:168 takes a history suffix that starts inside the current turn when that turn's tool results exceed the history byte cap, so a retry that reloads history mid-turn loses the request that opened the turn.

Fixes openclaw#201605

## What Problem This Solves

A sub-agent working through a long, tool-heavy task (screenshots, large reads) can hit a provider stream error such as `degenerate_output`. OpenClaw retries on the same model, but the retry's request no longer contains the sub-agent's task. The model only sees the system prompt, a failure note and "continue the current task", so it answers without doing the work and the parent receives a "completed" child that did nothing.

## User Impact

User impact: after a transient provider failure, a sub-agent (or any agent turn) whose tool results have grown past the history byte cap retries with its task still in front of the model and continues the work. Turns under the cap, new turns, and retries whose failed stream produced no output are unchanged.

## Why This Change Was Made

The first attempt builds its history in memory. A retry reloads the transcript through the bounded history window, which keeps the newest events that fit in eight bytes per context token. Inside one long turn there is no later turn boundary to align to, so the window kept only the newest tool frames and dropped the turn's user request. The internal continuation prompt then became the first user message, which is the `historyRewrite(message 0 (user) differs ...)` line in the report.

The window now keeps the request that opened the current turn and fills the rest of the cap with the newest frames, the same way it already reserves the latest compaction summary. If that request cannot fit beside any frame, the old suffix is kept. Saved history is not changed.

## Evidence

Real Gateway from source with a local OpenAI Responses provider that records every request. The parent calls `sessions_spawn` with a task; the child reads two screenshot-sized images, then its third stream emits text followed by a runaway tool call that trips `degenerate_output`.

- `main` (67aacbb), twice: the retry request is `[system, failed-turn note, "Continue the current task...", runtime context]`, with no task. The child ends with `stopReason=stop` 1.3 s later.
- This branch, twice: the retry request starts with the same task message as the first attempt, and the child continues the task.
- Controls on both builds: a sub-agent turn that does not fail is identical; an output-free failure and a small-history failure already kept the task.
- Regression test `keeps the current turn's request when its tool frames exceed the byte cap`: fails on `main` (`expected [ 3, 4, 5 ] to deeply equal [ +0, 3, 4, 5 ]`), passes here.

Observed request lines: openclaw#201636 (comment)
Re-run after the review fix (tool ownership kept): openclaw#201636 (comment)

Thanks @mike1122real-hub for the detailed report with the four failure timings and the history-rewrite line.

## Merge danger

Two-way door: the change only selects which saved events are loaded for one model request and writes nothing, so a revert fully restores the old selection. Blast radius: embedded agent turns whose loaded history exceeds the byte cap in the middle of a turn; they now send the turn's request plus slightly fewer of the oldest tool frames from that turn.

Co-authored-by: Ayaan Zaidi <[email protected]>

(cherry picked from commit adda3db)

Release adaptation: Source selector and regression unchanged; retained compaction note; exact 41-line regression allocation. Red on pinned production, 7 tests green after fix (2.22s).

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
…201636)

Baseline adaptation: Reserve the current request only under byte pressure, using baseline event/sizing rules and occurrence-aware tool ownership. No storage or config schema change.

(cherry picked from commit adda3db)

Co-authored-by: RomneyDa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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]: sub-agent transient same-model retry after degenerate_output restarts with rewritten message 0, run loses its task and ends

1 participant