Skip to content

fix(agents): keep the replayed user turn in history after compaction - #204313

Merged
obviyus merged 2 commits into
mainfrom
fix/replay-keyed-turn-on-retry
Nov 24, 2026
Merged

obviyus merged 2 commits into
mainfrom
fix/replay-keyed-turn-on-retry

Conversation

@obviyus

@obviyus obviyus commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

After mid-turn compaction, the retry that crosses the compaction boundary continued through a hidden user turn ("Continue the current task from the existing transcript…") plus a runtime carrier. That prompt was persisted. Every such retry added another hidden user turn, and the user's own question was gone from history: compaction had summarized it as part of the split turn.

User Impact

  • The question the user asked stays in the conversation history after compaction. The next turn sees it verbatim, instead of a hidden "continue" instruction.
  • No hidden continuation turn is added after compaction when the user's turn can be replayed.
  • The next turn's request extends the retry request byte for byte, so the provider prompt cache keeps working across the turn.

Why This Change Was Made

  • One owner decides the retry mode. continueFromCurrentTranscript (session-prompt-state.ts) now replays a persisted keyed user turn in place unless the attempt left an unsettled tail (partial output, or an operator abort mid-flight; callers pass unsettledTail). The caller-chosen replayCurrentUserTurn option is removed. The hidden prompt stays only for non-replayable turns.
  • The replayed turn is written where the model sees it. persistCompactedCurrentUserTurnReplay (pre-persisted-user-turn.ts), called from the replay branch of prepareEmbeddedAttemptSessionBoundary, appends the turn after the kept tail when a compaction summarized it. The original row keeps the turn key, because the transcript identity index is unique per session. The copy uses a key derived from the turn key and the compaction entry id, so repeated retries after the same compaction write it once, and a second compaction writes one new copy. It is display: false, so the chat still shows the question once.
  • Submission replays that row in place. resolveCurrentUserTurnContextKey returns the key under which the current turn sits in live context (its own row or its replay copy). Prompt submission and the compaction budget use it, so a later retry (for example after a rate limit) reuses the copy and its carrier instead of appending the question again.
  • Accepted edge, no code: if the process crashes between the compaction commit and the copy's write, the restart writes no copy for that run. The question stays in the original row and in the summary.

Evidence

Real-API replay (gpt-4.1-mini, captured wire pair: the retry after compaction, then the first request of the next turn; fresh seed and cache key per trial). The metric that does not depend on request length is whether the next turn reuses the whole cacheable retry prefix.

Arm, trial Retry input Next-turn input Next-turn cached Next-turn uncached New tokens in next turn Retry prefix fully cached Question in next-turn history
main, 1 9,071 9,153 8,960 193 82 yes no (hidden prompt instead)
main, 2 9,073 9,155 8,960 195 82 yes no
this PR, 1 8,995 9,077 8,832 245 82 yes yes
this PR, 2 8,998 9,080 8,832 248 82 yes yes
this PR, 3 8,999 9,081 8,960 121 82 yes yes
this PR, 4 8,993 9,075 8,832 243 82 yes yes
replay without persistence (rejected design) 9,007 9,059 7,936 1,123 52 no (breaks at the user turn) no
  • The provider caches in 128-token blocks. Next-turn uncached = the 82 new tokens (the same in both arms) + the retry's tail inside its last partial block. That tail depends only on where the retry length falls, not on changed bytes.
  • "Fully cached" means the next turn caches as much as resending the identical retry request. The control resend caches 8,832 for this PR's retry (8,996 tokens) and 8,960 for main's (9,072 tokens, 76 tokens longer because of the hidden prompt). The next request's input starts with the retry's full input byte for byte.

Tests:

  • agent-runner-compaction-fallback.test.ts (mid-turn case) checks:
    • the warm summary request equals the previous request plus one instruction;
    • a rate-limited first retry and the second retry after the same compaction send the identical request, with the keyed turn once and no hidden prompt;
    • the next turn's input starts with the retry's input and holds the question once.
      It is red on main (hidden prompt) and on the previous head of this PR (the rate-limited retry), and green here.
  • The fixture's stale largestPrompt < 800_000 check moves to the end of the test, unchanged, so the new assertions run first. It fails on main too (851,263 at the 85% trigger) and has its own owner.
  • embedded-agent-runner.prompt-cache.test.ts: the fixture window is raised so its journey stays below the compaction trigger. This test covers prefix stability; the compaction-fallback test owns the warm summary shape.

A retry after mid-turn compaction continued through a persisted hidden
"continue the current task" turn, and the user's question was gone from
history because compaction summarized it with the split turn.

- continueFromCurrentTranscript decides the mode: a persisted keyed turn is
  replayed in place unless the attempt left an unsettled tail.
- After a compaction, the replay writes a copy of the turn after the kept
  tail (derived per-compaction key, display: false), so the next turn's
  history holds the question and extends the retry request byte for byte.
- A replayed turn keeps its persisted timestamp.

Co-authored-by: obviyus <[email protected]>
@clawsweeper

clawsweeper Bot commented Nov 24, 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: M labels Nov 24, 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 24, 2026

@THE-NAVVV THE-NAVVV left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

​

A retry after the same compaction found the replay copy under its derived
key while submission looked up the original turn key, so it appended the
question again. Resolve the key under which the current turn sits in live
context in one place and use it for submission and the compaction budget.
The copy now stays in live history and is replayed in place, which also
keeps its persisted timestamp.

Co-authored-by: obviyus <[email protected]>
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. 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 24, 2026
@clawsweeper

clawsweeper Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR persists compacted user-turn replays and reuses their keys during later retries and prompt budgeting.

Example: “First question after the long history.” crosses a mid-turn compaction and a rate-limit retry.

  • Before: The next turn sees a hidden continuation instruction instead of the original question.
  • After: The question remains in model history, and the rate-limit retry reuses its persisted replay copy.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The repair is useful and focused, but retained replay detection has a concrete defect and complete product-flow proof is not established.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: After compaction, the next model turn can lose the user's verbatim question and inherit hidden continuation text instead.
Reason: Preserving accepted input and stable retry history has clear value, and collaborator authorship supplies direction approval.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep open: this maintainer-authored PR addresses a concrete history defect, but a second compaction can cause it to persist another copy of an already-retained question.

Priority: P2
Reviewed head: 36a2a52a41490d9ad9c29a1e17a2ee181e73e79f

Before merge

  • Recognize replay copies retained by a later compaction (P2) - After compaction C1 persists turn-1:user:replay:C1, a later compaction C2 can retain that user row in its kept tail. The compaction budget now resolves that copy's key, and the existing compactor explicitly preserves admitted pending users. Here neither turn-1:user nor turn-1:user:replay:C2 is present, so the guard falls through and appends a second copy despite C1's copy still being live. Both questions then remain in durable model history. Resolve the existing current-turn context key before deciding to append, and cover a second compaction that retains the first replay.

Findings

  • [P2] Recognize replay copies retained by a later compaction — src/agents/embedded-agent-runner/run/pre-persisted-user-turn.ts:583-585

Tests

  • Missing end-to-end proof: Supply a redacted shipped Gateway or CLI trace covering compaction, retry, and the next turn; the API replay table does not establish that complete runtime path.
Agent review details

How this fits together

The embedded runner restores persisted session history, chooses replay or continuation, and submits the resulting messages through the provider transport.

flowchart TD
  A[Accepted user turn] --> B[Session transcript]
  B --> C[Compaction]
  C --> D[Replay preparation]
  D --> B
  D --> E[Prompt submission]
  E --> F[Provider transport]
  B --> G[Next turn history]
Loading

Technical review

Best possible solution:

Reuse the existing context-key resolver before appending so any retained replay satisfies the current turn, while a summarized-away replay still receives one replacement.

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

Source establishes the hidden-continuation path on main and the repeated-compaction duplication in the patch; this read-only review executed no reproduction.

Is this the best way to solve the issue?

Persisting the model-visible replay through the existing transcript owner is appropriate, but replay detection must recognize copies retained across compaction boundaries.

Full review comments:

  • [P2] Recognize replay copies retained by a later compaction — src/agents/embedded-agent-runner/run/pre-persisted-user-turn.ts:583-585
    After compaction C1 persists turn-1:user:replay:C1, a later compaction C2 can retain that user row in its kept tail. The compaction budget now resolves that copy's key, and the existing compactor explicitly preserves admitted pending users. Here neither turn-1:user nor turn-1:user:replay:C2 is present, so the guard falls through and appends a second copy despite C1's copy still being live. Both questions then remain in durable model history. Resolve the existing current-turn context key before deciding to append, and cover a second compaction that retains the first replay.
    Confidence: 0.94
    Late finding: first raised on code an earlier review cycle already covered.

Overall correctness: patch is incorrect
Overall confidence: 0.91

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/auto-reply/reply/agent-runner-compaction-fallback.test.ts --maxWorkers=1
  • pnpm test src/agents/embedded-agent-runner/run/attempt-session-replay.test.ts src/agents/embedded-agent-runner/run.session-prompt-state.test.ts --maxWorkers=1
  • pnpm test src/agents/agent-tools.prefix-stability.test.ts --maxWorkers=1
  • pnpm check:changed

What I checked:

Likely related people:

  • Josh Lehman: Raw commit 8d5a138 adds src/agents/embedded-agent-runner/run/session-prompt-state.ts:194 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 8d5a13806699; files: src/agents/embedded-agent-runner/run/session-prompt-state.ts)
  • Peter Steinberger: Raw commit ca9bbf6 adds src/agents/embedded-agent-runner/run/session-prompt-state.ts:109 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ca9bbf6ee006; files: src/agents/embedded-agent-runner/run/session-prompt-state.ts)

PR surface

Source +91, Tests +112. Total +203 across 14 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 8 111 20 +91
Tests 6 119 7 +112
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 230 27 +203

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: The PR repairs compacted conversation history, with a remaining duplication defect limited to repeated compaction.
  • add merge-risk: 🚨 session-state: A retained replay can be duplicated in durable model history after another compaction.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: The PR repairs compacted conversation history, with a remaining duplication defect limited to repeated compaction.
  • merge-risk: 🚨 session-state: A retained replay can be duplicated in durable model history after another compaction.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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 23, 2026, 9:19 PM ET / November 24, 2026, 02:19 UTC.

@obviyus

obviyus commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override: all 30 red test files on head 36a2a52 (PR CI run 45309489715, both attempts) also fail on the merge base. Each file is named below with its base evidence. None is caused by this PR.

Merge base: main 7cbf1585ed73 (main at 02:01Z, the parent of the CI merge commit). Base runs are local ocx test --no-memo on a clean detached checkout of 7cbf158 with continue-on-failure, unless a scheduled-main job is cited. Scheduled run 45312791464 ran on 7cbf158 itself.

# File (failing case) Head evidence Merge-base evidence Class
1 src/agents/bash-tools.exec-gateway-approval.e2e.test.ts (withholds the active hook token source…) job 138200179709, line 524 main red per the #204335 override table MAIN-ALSO
2 src/agents/subagents/registry/subagent-registry.requester-wake.e2e.test.ts (settles requester receipts ×6) job 138200179709, 120 s timeouts at requester-wake-receipts.test-support.ts:250 same 6 cases time out on 7cbf158 (local) MAIN-ALSO
3 src/auto-reply/reply/agent-runner-compaction-fallback.test.ts (tool rounds: true) expected 851220 to be less than 800000 scheduled 45312791464 job 138173038133 (also 45319833099 job 138196196066) MAIN-ALSO
4 src/auto-reply/reply/agent-runner-required-maintenance.pending-input.test.ts (two archives) line 335 expected +0 to be 1 scheduled 45312791464 job 138173031811 (also 45319833099 job 138196191763) MAIN-ALSO
5-12 src/config/state-startup-corpus.test.ts and .part-2…part-8.test.ts listed red for this head; no FAIL line found in either attempt's job logs on 7cbf158: state-startup-corpus.test.ts (generic-github-token.json) and part-8 (peanutto.json) time out at 120 s; the rest pass MAIN-ALSO
13 src/cron/session-context-accounting.gateway.integration.test.ts line 280 expected 853358 to be less than 800000 scheduled 45312791464 job 138173031998 (also 45319833099 job 138196191867) MAIN-ALSO
14 src/cron/session-run.session-model-strictness.integration.test.ts (preflight compaction watchdog) line 663 expected +0 to be 1 scheduled 45312791464 job 138173031998 (also 45319833099 job 138196191867) MAIN-ALSO
15 src/gateway/cron-forced-after-turn.e2e.test.ts 120 s timeout same timeout on 7cbf158 (local; #204331) MAIN-ALSO
16 src/gateway/gateway-skill-authoring-plugin.e2e.test.ts line 217 expected [] to have a length of 1 same on 7cbf158 (local) MAIN-ALSO
17 src/gateway/server-templates-add-authority.e2e.test.ts (fences … publication ×3) line 777 deep-equal mismatch same 3 cases on 7cbf158 (local) MAIN-ALSO
18 src/gateway/server.chat-membership-authority.product.test.ts line 177 expected status 'ok' same on 7cbf158 (local); also red on scheduled main 45305041178 MAIN-ALSO
19 src/gateway/worker-environments/destination-authority.e2e.test.ts (×3) No model is configured… same 3 cases on 7cbf158 (local) MAIN-ALSO
20 test/e2e/qa-lab/runtime/channel-progress-presentation.e2e.test.ts (suppressed Slack; ambiguous Discord) expected 'delivered' to be 'failed'; settlement timeout same 2 cases on 7cbf158 (local) MAIN-ALSO
21 test/e2e/qa-lab/runtime/cron-one-shot-run.e2e.test.ts (spawned child's result) line 50 expected undefined to be defined same on 7cbf158 (local; #204331) MAIN-ALSO
22 test/e2e/qa-lab/runtime/gateway-plugin-turn-handover.e2e.test.ts (plugin reload ×4) JSON parse errors at lines 222/251 same 4 cases on 7cbf158 (local) MAIN-ALSO
23 test/e2e/qa-lab/runtime/gateway-provider-review-product-proof.e2e.test.ts line 572 expected status 'error' (mid-run device removal; #204249 removed that re-check) same on 7cbf158 (local) MAIN-ALSO
24 test/e2e/qa-lab/runtime/managed-worktrees-session-lifecycle-product-proof.e2e.test.ts line 217 git -C … Command failed same on 7cbf158 (local) MAIN-ALSO
25 test/e2e/qa-lab/runtime/managed-worktrees-workboard-lifecycle-product-proof.e2e.test.ts line 371 match-object mismatch same on 7cbf158 (local) MAIN-ALSO
26 test/gateway-cold-agent-abort.e2e.test.ts expected {…5} to deeply equal {…4} same on 7cbf158 (local) MAIN-ALSO
27 test/gateway-restart-resume.e2e.test.ts (graceful shutdown, blocked store: false) line 1339 expected true to be false same on 7cbf158 (local; #204331) MAIN-ALSO
28 test/gateway-subagent-completion-restart.e2e.test.ts attempt 1: (announcing) expected {…} to match object { delivery }; attempt 2: line 617 same (announcing) assertion on 7cbf158 in a dedicated base run, plus service-child cleanup deadlines MAIN-ALSO
29 test/gateway-yield-restart.e2e.test.ts line 731 missing REQUESTER_RECEIVED_CHILD_COMPLETION same (policy-unavailable) on 7cbf158 (local) MAIN-ALSO
30 test/prompt-cache-prefix-stability.google.e2e.test.ts (append-only until compaction) job 138200179709: breaks at requests 12/23/28, expected 2 to be 1 same breaks at 12/23/28 and same assertion on 7cbf158 (local) MAIN-ALSO

server-cron-notifications.repair.test.ts failed once with a vitest EnvironmentTeardownError (no assertion failed) and passed on the rerun of the failed jobs; it is not part of this override.

@obviyus
obviyus merged commit 39bdddd into main Nov 24, 2026
418 of 456 checks passed
@obviyus
obviyus deleted the fix/replay-keyed-turn-on-retry branch November 24, 2026 05:13
@obviyus

obviyus commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

Landed. After mid-turn compaction, the retry now replays the user's keyed question in place, and the question stays in history for the next turn, instead of continuing through a persisted hidden prompt. The next turn caches the whole cacheable retry prefix (table in the description). Every red check is named in the override comment above with merge-base evidence.

tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
…204313)

## What Problem This Solves

After mid-turn compaction, the retry that crosses the compaction boundary continued through a hidden user turn ("Continue the current task from the existing transcript…") plus a runtime carrier. That prompt was persisted. Every such retry added another hidden user turn, and the user's own question was gone from history: compaction had summarized it as part of the split turn.

## User Impact

- The question the user asked stays in the conversation history after compaction. The next turn sees it verbatim, instead of a hidden "continue" instruction.
- No hidden continuation turn is added after compaction when the user's turn can be replayed.
- The next turn's request extends the retry request byte for byte, so the provider prompt cache keeps working across the turn.

## Why This Change Was Made

- **One owner decides the retry mode.** `continueFromCurrentTranscript` (`session-prompt-state.ts`) now replays a persisted keyed user turn in place unless the attempt left an unsettled tail (partial output, or an operator abort mid-flight; callers pass `unsettledTail`). The caller-chosen `replayCurrentUserTurn` option is removed. The hidden prompt stays only for non-replayable turns.
- **The replayed turn is written where the model sees it.** `persistCompactedCurrentUserTurnReplay` (`pre-persisted-user-turn.ts`), called from the replay branch of `prepareEmbeddedAttemptSessionBoundary`, appends the turn after the kept tail when a compaction summarized it. The original row keeps the turn key, because the transcript identity index is unique per session. The copy uses a key derived from the turn key and the compaction entry id, so repeated retries after the same compaction write it once, and a second compaction writes one new copy. It is `display: false`, so the chat still shows the question once.
- **Submission replays that row in place.** `resolveCurrentUserTurnContextKey` returns the key under which the current turn sits in live context (its own row or its replay copy). Prompt submission and the compaction budget use it, so a later retry (for example after a rate limit) reuses the copy and its carrier instead of appending the question again.
- Accepted edge, no code: if the process crashes between the compaction commit and the copy's write, the restart writes no copy for that run. The question stays in the original row and in the summary.

## Evidence

Real-API replay (gpt-4.1-mini, captured wire pair: the retry after compaction, then the first request of the next turn; fresh seed and cache key per trial). The metric that does not depend on request length is whether the next turn reuses the whole cacheable retry prefix.

| Arm, trial | Retry input | Next-turn input | Next-turn cached | Next-turn uncached | New tokens in next turn | Retry prefix fully cached | Question in next-turn history |
|---|---|---|---|---|---|---|---|
| main, 1 | 9,071 | 9,153 | 8,960 | 193 | 82 | yes | no (hidden prompt instead) |
| main, 2 | 9,073 | 9,155 | 8,960 | 195 | 82 | yes | no |
| this PR, 1 | 8,995 | 9,077 | 8,832 | 245 | 82 | yes | yes |
| this PR, 2 | 8,998 | 9,080 | 8,832 | 248 | 82 | yes | yes |
| this PR, 3 | 8,999 | 9,081 | 8,960 | 121 | 82 | yes | yes |
| this PR, 4 | 8,993 | 9,075 | 8,832 | 243 | 82 | yes | yes |
| replay without persistence (rejected design) | 9,007 | 9,059 | 7,936 | 1,123 | 52 | no (breaks at the user turn) | no |

- The provider caches in 128-token blocks. Next-turn uncached = the 82 new tokens (the same in both arms) + the retry's tail inside its last partial block. That tail depends only on where the retry length falls, not on changed bytes.
- "Fully cached" means the next turn caches as much as resending the identical retry request. The control resend caches 8,832 for this PR's retry (8,996 tokens) and 8,960 for main's (9,072 tokens, 76 tokens longer because of the hidden prompt). The next request's input starts with the retry's full input byte for byte.

Tests:

- `agent-runner-compaction-fallback.test.ts` (mid-turn case) checks:
  - the warm summary request equals the previous request plus one instruction;
  - a rate-limited first retry and the second retry after the same compaction send the identical request, with the keyed turn once and no hidden prompt;
  - the next turn's input starts with the retry's input and holds the question once.
  It is red on `main` (hidden prompt) and on the previous head of this PR (the rate-limited retry), and green here.
- The fixture's stale `largestPrompt < 800_000` check moves to the end of the test, unchanged, so the new assertions run first. It fails on `main` too (851,263 at the 85% trigger) and has its own owner.
- `embedded-agent-runner.prompt-cache.test.ts`: the fixture window is raised so its journey stays below the compaction trigger. This test covers prefix stability; the compaction-fallback test owns the warm summary shape.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 39bdddd)
Co-authored-by: RomneyDa <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 25, 2026
…penclaw#204313)

## What Problem This Solves

After mid-turn compaction, the retry that crosses the compaction boundary continued through a hidden user turn ("Continue the current task from the existing transcript…") plus a runtime carrier. That prompt was persisted. Every such retry added another hidden user turn, and the user's own question was gone from history: compaction had summarized it as part of the split turn.

## User Impact

- The question the user asked stays in the conversation history after compaction. The next turn sees it verbatim, instead of a hidden "continue" instruction.
- No hidden continuation turn is added after compaction when the user's turn can be replayed.
- The next turn's request extends the retry request byte for byte, so the provider prompt cache keeps working across the turn.

## Why This Change Was Made

- **One owner decides the retry mode.** `continueFromCurrentTranscript` (`session-prompt-state.ts`) now replays a persisted keyed user turn in place unless the attempt left an unsettled tail (partial output, or an operator abort mid-flight; callers pass `unsettledTail`). The caller-chosen `replayCurrentUserTurn` option is removed. The hidden prompt stays only for non-replayable turns.
- **The replayed turn is written where the model sees it.** `persistCompactedCurrentUserTurnReplay` (`pre-persisted-user-turn.ts`), called from the replay branch of `prepareEmbeddedAttemptSessionBoundary`, appends the turn after the kept tail when a compaction summarized it. The original row keeps the turn key, because the transcript identity index is unique per session. The copy uses a key derived from the turn key and the compaction entry id, so repeated retries after the same compaction write it once, and a second compaction writes one new copy. It is `display: false`, so the chat still shows the question once.
- **Submission replays that row in place.** `resolveCurrentUserTurnContextKey` returns the key under which the current turn sits in live context (its own row or its replay copy). Prompt submission and the compaction budget use it, so a later retry (for example after a rate limit) reuses the copy and its carrier instead of appending the question again.
- Accepted edge, no code: if the process crashes between the compaction commit and the copy's write, the restart writes no copy for that run. The question stays in the original row and in the summary.

## Evidence

Real-API replay (gpt-4.1-mini, captured wire pair: the retry after compaction, then the first request of the next turn; fresh seed and cache key per trial). The metric that does not depend on request length is whether the next turn reuses the whole cacheable retry prefix.

| Arm, trial | Retry input | Next-turn input | Next-turn cached | Next-turn uncached | New tokens in next turn | Retry prefix fully cached | Question in next-turn history |
|---|---|---|---|---|---|---|---|
| main, 1 | 9,071 | 9,153 | 8,960 | 193 | 82 | yes | no (hidden prompt instead) |
| main, 2 | 9,073 | 9,155 | 8,960 | 195 | 82 | yes | no |
| this PR, 1 | 8,995 | 9,077 | 8,832 | 245 | 82 | yes | yes |
| this PR, 2 | 8,998 | 9,080 | 8,832 | 248 | 82 | yes | yes |
| this PR, 3 | 8,999 | 9,081 | 8,960 | 121 | 82 | yes | yes |
| this PR, 4 | 8,993 | 9,075 | 8,832 | 243 | 82 | yes | yes |
| replay without persistence (rejected design) | 9,007 | 9,059 | 7,936 | 1,123 | 52 | no (breaks at the user turn) | no |

- The provider caches in 128-token blocks. Next-turn uncached = the 82 new tokens (the same in both arms) + the retry's tail inside its last partial block. That tail depends only on where the retry length falls, not on changed bytes.
- "Fully cached" means the next turn caches as much as resending the identical retry request. The control resend caches 8,832 for this PR's retry (8,996 tokens) and 8,960 for main's (9,072 tokens, 76 tokens longer because of the hidden prompt). The next request's input starts with the retry's full input byte for byte.

Tests:

- `agent-runner-compaction-fallback.test.ts` (mid-turn case) checks:
  - the warm summary request equals the previous request plus one instruction;
  - a rate-limited first retry and the second retry after the same compaction send the identical request, with the keyed turn once and no hidden prompt;
  - the next turn's input starts with the retry's input and holds the question once.
  It is red on `main` (hidden prompt) and on the previous head of this PR (the rate-limited retry), and green here.
- The fixture's stale `largestPrompt < 800_000` check moves to the end of the test, unchanged, so the new assertions run first. It fails on `main` too (851,263 at the 85% trigger) and has its own owner.
- `embedded-agent-runner.prompt-cache.test.ts`: the fixture window is raised so its journey stays below the compaction trigger. This test covers prefix stability; the compaction-fallback test owns the warm summary shape.

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
…204313)

After mid-turn compaction, the retry that crosses the compaction boundary continued through a hidden user turn ("Continue the current task from the existing transcript…") plus a runtime carrier. That prompt was persisted. Every such retry added another hidden user turn, and the user's own question was gone from history: compaction had summarized it as part of the split turn.

- The question the user asked stays in the conversation history after compaction. The next turn sees it verbatim, instead of a hidden "continue" instruction.
- No hidden continuation turn is added after compaction when the user's turn can be replayed.
- The next turn's request extends the retry request byte for byte, so the provider prompt cache keeps working across the turn.

- **One owner decides the retry mode.** `continueFromCurrentTranscript` (`session-prompt-state.ts`) now replays a persisted keyed user turn in place unless the attempt left an unsettled tail (partial output, or an operator abort mid-flight; callers pass `unsettledTail`). The caller-chosen `replayCurrentUserTurn` option is removed. The hidden prompt stays only for non-replayable turns.
- **The replayed turn is written where the model sees it.** `persistCompactedCurrentUserTurnReplay` (`pre-persisted-user-turn.ts`), called from the replay branch of `prepareEmbeddedAttemptSessionBoundary`, appends the turn after the kept tail when a compaction summarized it. The original row keeps the turn key, because the transcript identity index is unique per session. The copy uses a key derived from the turn key and the compaction entry id, so repeated retries after the same compaction write it once, and a second compaction writes one new copy. It is `display: false`, so the chat still shows the question once.
- **Submission replays that row in place.** `resolveCurrentUserTurnContextKey` returns the key under which the current turn sits in live context (its own row or its replay copy). Prompt submission and the compaction budget use it, so a later retry (for example after a rate limit) reuses the copy and its carrier instead of appending the question again.
- Accepted edge, no code: if the process crashes between the compaction commit and the copy's write, the restart writes no copy for that run. The question stays in the original row and in the summary.

Real-API replay (gpt-4.1-mini, captured wire pair: the retry after compaction, then the first request of the next turn; fresh seed and cache key per trial). The metric that does not depend on request length is whether the next turn reuses the whole cacheable retry prefix.

| Arm, trial | Retry input | Next-turn input | Next-turn cached | Next-turn uncached | New tokens in next turn | Retry prefix fully cached | Question in next-turn history |
|---|---|---|---|---|---|---|---|
| main, 1 | 9,071 | 9,153 | 8,960 | 193 | 82 | yes | no (hidden prompt instead) |
| main, 2 | 9,073 | 9,155 | 8,960 | 195 | 82 | yes | no |
| this PR, 1 | 8,995 | 9,077 | 8,832 | 245 | 82 | yes | yes |
| this PR, 2 | 8,998 | 9,080 | 8,832 | 248 | 82 | yes | yes |
| this PR, 3 | 8,999 | 9,081 | 8,960 | 121 | 82 | yes | yes |
| this PR, 4 | 8,993 | 9,075 | 8,832 | 243 | 82 | yes | yes |
| replay without persistence (rejected design) | 9,007 | 9,059 | 7,936 | 1,123 | 52 | no (breaks at the user turn) | no |

- The provider caches in 128-token blocks. Next-turn uncached = the 82 new tokens (the same in both arms) + the retry's tail inside its last partial block. That tail depends only on where the retry length falls, not on changed bytes.
- "Fully cached" means the next turn caches as much as resending the identical retry request. The control resend caches 8,832 for this PR's retry (8,996 tokens) and 8,960 for main's (9,072 tokens, 76 tokens longer because of the hidden prompt). The next request's input starts with the retry's full input byte for byte.

Tests:

- `agent-runner-compaction-fallback.test.ts` (mid-turn case) checks:
  - the warm summary request equals the previous request plus one instruction;
  - a rate-limited first retry and the second retry after the same compaction send the identical request, with the keyed turn once and no hidden prompt;
  - the next turn's input starts with the retry's input and holds the question once.
  It is red on `main` (hidden prompt) and on the previous head of this PR (the rate-limited retry), and green here.
- The fixture's stale `largestPrompt < 800_000` check moves to the end of the test, unchanged, so the new assertions run first. It fails on `main` too (851,263 at the 85% trigger) and has its own owner.
- `embedded-agent-runner.prompt-cache.test.ts`: the fixture window is raised so its journey stays below the compaction trigger. This test covers prefix stability; the compaction-fallback test owns the warm summary shape.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 39bdddd)

Release adaptation: Preserve the stable ChatGPT V2 compaction boundary and test the cold-summary retry, without importing the warm-summary feature or its unrelated assertion.

Companion audit: #204443 changes only fixture sizing; stable test retains its pre-existing budget assertion. #207519 consolidates separate output-limit tests; #208522 is separately ordered in this lane; #204111 warm summaries are not needed for the stable cold path.

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

agents Agent runtime and tooling merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: M status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants