Skip to content

fix(agents): rate-limit retries add hidden continuation turns that break prompt caching - #183206

Closed
jalehman wants to merge 1 commit into
mainfrom
openclaw-36c/zero-output-retry-keyed-replay
Closed

jalehman wants to merge 1 commit into
mainfrom
openclaw-36c/zero-output-retry-keyed-replay

Conversation

@jalehman

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: each rate-limit retry adds a hidden "Continue the current task…" user message, even when the provider rejected the request before producing any output.

User Impact

User impact: when a provider returns a rate limit (or another transient error) without streaming anything, the agent resends the same request instead of starting a new hidden turn. On OpenAI Responses routes this keeps the prompt cache intact across retries. Before, every retry re-sent a prompt that missed the cache from the rewritten message onward; a live session re-sent ~100k uncached input tokens per retry. Transcripts also stop accumulating empty-error + hidden "Continue…" pairs, five of which appeared in one live session in two minutes.

Why This Change Was Made

Transient-failure recovery (#139397) always resumes through the hidden continuation prompt, because replaying the original request after tools ran could repeat their work. That prompt is still right when output was partly produced or a tool's outcome is uncertain. A rejection with no output, after every tool has settled, leaves the transcript exactly as it was before the request. In that case the persisted user turn (matched by its idempotency key) is replayed in place. AgentSession.prompt() already supports this without appending a message, and the LLM boundary drops the empty error turn.

The hidden prompt remains for: partial output, unsettled or async tools, thrown prompt failures, native harness threads (pluginHarnessOwnsTransport), active internal prompts, and user turns without a persisted idempotency key.

Evidence

  • Live symptom (openclaw-fsn1 Gateway logs): cache read dropped 141511 -> 32925 … runtimeContextCarrier(runtimeContextCarrier changed provider history), historyRewrite(message 276 (user) differs from the previous request …) followed each rate_limit_exceeded type=tokens retry. The transcript shows assistant(error, content: []) + hidden user "Continue the current task…" per retry.
  • attempt-session-replay.test.ts (real session boundary + persisted transcript): after completed tools, a rate-limited request with no output is retried across a rebuilt session. The resent request equals the rejected one. Only the regenerated tail runtime context differs on the non-append-only route. Exactly one user row remains.
  • attempt-recovery.test.ts: eligibility matrix (no output after settled tools / before work → replay; partial reasoning, native harness, active lifecycle item, thrown prompt failure → continuation). The two replay cases fail on the previous attempt-recovery.ts.
  • run.session-prompt-state.test.ts: replay only for a persisted keyed operator turn; unkeyed, unpersisted, and internal prompts keep the continuation.
  • pnpm test <file> --maxWorkers=1: attempt-recovery.test.ts 134 passed; run.session-prompt-state.test.ts 20 passed; attempt-session-replay.test.ts 52 passed (171s wall for the file; the two new boundary cases take ~2.9s each because they open the real agent database, the only layer that proves the request bytes across a rebuilt attempt).
  • pnpm check:changed: format, lint, core and test typecheck pass. The dead-export scan fails only on untouched scripts/ exports that are already present on main.

…on turn

A transient provider rejection that streamed no output after settled tools left the transcript unchanged, but recovery still activated the hidden continuation prompt. That appended an internal user turn per retry, shifted the runtime-context boundary, and invalidated the prompt-cache prefix on non-append-only routes. Replay the persisted keyed user turn in place for that case; keep the continuation prompt for partial output, uncertain tools, native harness threads, thrown prompt failures, internal prompts, and unkeyed turns.
@clawsweeper

clawsweeper Bot commented Oct 25, 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 agents Agent runtime and tooling size: S labels Oct 25, 2026
@jalehman jalehman self-assigned this Oct 25, 2026
@jalehman
jalehman marked this pull request as ready for review October 25, 2026 03:33
@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. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed 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 Oct 25, 2026
@clawsweeper

clawsweeper Bot commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR replays persisted keyed user turns after transient provider failures with no output instead of adding a hidden continuation turn.

Example: An embedded OpenAI Responses request receives HTTP 429 after completed tool work without producing output.

  • Before: Recovery adds a hidden continuation user message, shifting subsequent prompt history.
  • After: Recovery reuses the existing keyed user turn and recorded tool results without adding that message.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A useful, focused patch with no actionable defect found; evidence supports its component contracts but does not demonstrate the complete changed recovery flow.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; supplied evidence covers mocked recovery decisions and real session persistence with a mocked provider stream, while the inspected older screenshots exercise native continuation rather than this replay branch.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Rate-limited requests can create hidden extra turns and lose prompt-prefix reuse, increasing input cost.
Reason: Stable prompt history is an existing contract, and the supplied maintainer-authored direction authorizes this focused repair without introducing an option or changing the retry budget.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR addresses a remaining current-main prompt-history problem with a focused change; no concrete correctness or security defect was found, and the reviewed head has green CI.

Priority: P2
Reviewed head: f8148cdd1d6d64858407abd1a4300b367fd559fb

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The added session tests submit twice directly rather than exercising the complete recovery loop, and do not establish a post-fix provider-wire or live cache-token result.
Agent review details

How this fits together

The embedded runner classifies failed attempts, selects recovery, and prepares the next session request from the durable transcript before provider dispatch.

flowchart LR
 A[User turn] --> B[Embedded runner]
 B --> C[Provider request]
 C --> D[Attempt recovery]
 D --> E[Session prompt state]
 E --> F[Keyed transcript replay]
 F --> C
Loading

Technical review

Best possible solution:

Use the existing keyed replay owner for proven zero-output rejections while retaining continuation for partial output, uncertain tools, internal prompts, and native harnesses.

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

Current-main source unconditionally activates continuation after accepted transient retries, and the supplied production log excerpt reports matching history rewrites; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The patch removes unnecessary turn creation through existing recovery and replay owners, with narrow eligibility checks and no new configuration or persistence format.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Transient recovery continuation selection changes intended behavior with a stated reason (a9e9dec: Continue from completed work and uncertain effects instead of restarting the original task after temporary provider failures.)
  • Continuation snapshots and native harness behavior keeps the original intent (be4c0b1: Carry the current request and settled snapshots when native harness admission excludes the active turn from history.)
  • Settled failed-tool recovery keeps the original intent (7d8080c: Resume recorded failed-tool batches without executing completed tools again.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Vito Cappello: Raw commit fc19759 adds src/agents/embedded-agent-runner/run/attempt-recovery.ts:121 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: fc1975991f22; files: src/agents/embedded-agent-runner/run/attempt-recovery.ts)

PR surface

Source +31, Tests +109. Total +140 across 5 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 31 0 +31
Tests 3 109 0 +109
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 140 0 +140

Labels

Label changes:

  • add P2: Transient failures can add unnecessary prompt history and increase uncached input cost, while ordinary conversation recovery remains available.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp 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: Transient failures can add unnecessary prompt history and increase uncached input cost, while ordinary conversation recovery remains available.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Exercise a keyed turn through the full runner with a zero-output HTTP 429 and compare serialized provider requests before and after recovery.

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 October 24, 2026, 11:51 PM ET / October 25, 2026, 03:51 UTC.

salad-maker pushed a commit to salad-maker/openclaw that referenced this pull request Oct 25, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 25, 2026
@jalehman

Copy link
Copy Markdown
Contributor Author

Landed on main as 8d5a138. That commit has the same patch as this PR's head f8148cdd1d6 (git patch-id --stable matches), but GitHub never recorded the merge on this PR. The later conflict comes from #183196 moving an import in session-prompt-state.ts after the landing; the fix is unchanged on current main. Closing as landed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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.

1 participant