Repository navigation
perf(agents): preserve prompt prefixes across images and retries - #169237
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review in progressClawSweeper is reviewing this revision. This supersedes any previous blocked status. |
|
Codex review: needs changes before merge. What this changesThis PR preserves historical images, captures unchanged user prompts, and retains failed assistant attempts across retries and replay. Example: A conversation contains an image in turn 1 and reaches turn 5.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Needs changes before merge - 3 items remain Keep open: this PR addresses remaining prompt-prefix rewrites, but removing a released SDK type member still blocks merge. Priority: P2 Before merge
Findings
Provenance
Agent review detailsHow this fits togetherThe agent runner converts persisted conversation history into provider requests and records prompt projections and assistant outcomes for subsequent retries and replay. flowchart LR
A[Admitted user turn] --> B[Transcript owner]
B --> C[Retained conversation history]
C --> D[Media hydration and replay projection]
D --> E[Provider request]
E --> F[Assistant outcome]
F --> B
Technical reviewBest possible solution: Keep the append-only prompt-history implementation and restore the released observation-code literal without reviving image cleanup. Do we have a high-confidence way to reproduce the issue? Current-main cleanup and unchanged-prompt bypass establish the rewrite paths, supported by the supplied before/after provider measurements; no target code was executed during this review. Is this the best way to solve the issue? Fixing the existing history and transcript owners is coherent and reduces competing rewrites, provided the released SDK type remains source-compatible. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against dc1b8e35710b. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource -420, Tests -693, Docs +1, Other -41. Total -1153 across 62 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (2 earlier review cycles)
Reviewed October 11, 2026, 4:21 PM ET / 20:21 UTC (Revision 3). |
7ddb124 to
b43a1dd
Compare
Retain image history until the existing truncation or compaction boundary. Capture native user projections before dispatch and persist failed assistant entries without splitting or replacing their content, so retries and cold replay share the same history.
Preserve the provider-required thinking blocks alongside completed tool calls without mutating failed transcript entries. Cover error and abort replay, keep the retry image fixture typed, and exercise error prefix stability after the declared history truncation boundary.
b43a1dd to
04bbe26
Compare
Hourly 38176740854 jobs 114580699409 and 114580696456 reported empty partial-answer streams and an extra recovered prompt occurrence. 56d5592 (#169237) made failed attempts append-only and captured each user turn's model-prompt projection. The fixtures still counted that metadata as a second turn and expected saved text in the unsaved live tail. Preserve provider request counts, selected history, fallback ordering, and settled-write assertions. Count transcript message content independently of prompt metadata, and prove failed partial answers arrive through a real sessions.messages.subscribe client before their live tail is empty. This follows #167054's saved-message publication contract; production is unchanged. Linux attribution: parent b1cadee passed all 7 tests in 159.16s; child 56d5592 failed the 4 assigned cases in 159.11s. Candidate passed 7/7 in 167.95s. Reverting only these test edits reproduced all 4 failures in 88.67s. Ten repetitions on two CPUs passed 70/70 in 870.00s total. Individual pnpm test <file> --maxWorkers=1 wall times: recovered-output 45.75s, orphaned-recovery 46.36s, xai-fallback 50.50s. These existing real Gateway/HTTP fixtures prove canonical publication and physical request counts; helper-only tests cannot establish that boundary. Full isolated config: 31 files / 176 tests passed across three shards (170.71s, 93.48s, 112.12s). Full Gateway config: 4,950 passed, two pre-existing sibling failures, one existing skip (1,099.53s, 839.15s, 892.61s). The connection-identity failure exactly matches hourly main 0ebcb29; the context-prewarm heartbeat failure reproduces on clean base af93d66 in the same full shard (890.57s; 1,105ms vs 500ms limit). Both pass in the focused baseline probe (24.99s), so retain that distinction. Scoped lint, boundary lint, Gateway test types, formatting, architecture, and diff checks passed. Independent P2 review found no actionable issues. check-changed's only failure is the inherited dead-export scan: the clean base reproduces the same 144 reported entries (49.09s); the lists match exactly. No exports, ignores, or baselines changed. No CI was dispatched.
…nclaw#169237) * perf(agents): keep sent prompt history stable Retain image history until the existing truncation or compaction boundary. Capture native user projections before dispatch and persist failed assistant entries without splitting or replacing their content, so retries and cold replay share the same history. * fix(agents): retain signed thinking with completed failed calls Preserve the provider-required thinking blocks alongside completed tool calls without mutating failed transcript entries. Cover error and abort replay, keep the retry image fixture typed, and exercise error prefix stability after the declared history truncation boundary. * test(agents): verify captured projection on interrupted replay * test(agents): complete prompt history lifecycle cutover * test(agents): reuse owned projection fixtures
Hourly 38176740854 jobs 114580699409 and 114580696456 reported empty partial-answer streams and an extra recovered prompt occurrence. 3e3b261 (openclaw#169237) made failed attempts append-only and captured each user turn's model-prompt projection. The fixtures still counted that metadata as a second turn and expected saved text in the unsaved live tail. Preserve provider request counts, selected history, fallback ordering, and settled-write assertions. Count transcript message content independently of prompt metadata, and prove failed partial answers arrive through a real sessions.messages.subscribe client before their live tail is empty. This follows openclaw#167054's saved-message publication contract; production is unchanged. Linux attribution: parent 4e16a5b passed all 7 tests in 159.16s; child 3e3b261 failed the 4 assigned cases in 159.11s. Candidate passed 7/7 in 167.95s. Reverting only these test edits reproduced all 4 failures in 88.67s. Ten repetitions on two CPUs passed 70/70 in 870.00s total. Individual pnpm test <file> --maxWorkers=1 wall times: recovered-output 45.75s, orphaned-recovery 46.36s, xai-fallback 50.50s. These existing real Gateway/HTTP fixtures prove canonical publication and physical request counts; helper-only tests cannot establish that boundary. Full isolated config: 31 files / 176 tests passed across three shards (170.71s, 93.48s, 112.12s). Full Gateway config: 4,950 passed, two pre-existing sibling failures, one existing skip (1,099.53s, 839.15s, 892.61s). The connection-identity failure exactly matches hourly main 1436673; the context-prewarm heartbeat failure reproduces on clean base f97f05a in the same full shard (890.57s; 1,105ms vs 500ms limit). Both pass in the focused baseline probe (24.99s), so retain that distinction. Scoped lint, boundary lint, Gateway test types, formatting, architecture, and diff checks passed. Independent P2 review found no actionable issues. check-changed's only failure is the inherited dead-export scan: the clean base reproduces the same 144 reported entries (49.09s); the lists match exactly. No exports, ignores, or baselines changed. No CI was dispatched.
|
#169237 makes |
…tored copy Fork-only fix for upstream openclaw#169154 on v2026.10.1. Storage redaction hints some values on its first pass and masks them on a second, so the run's copy of an admitted user turn carrying a bearer token, an env assignment, a URL password or an OAuth code could arrive one pass further than its stored copy and fail every turn with "Transcript idempotency key ... conflicts with the admitted message". Without pending-input custody, a keyed user replay now also matches the stored copy redacted once more. Upstream fixed this in openclaw#169237, which depends on openclaw#167938's prompt projection; drop this commit when the fork carries both.
…re drift Found by typechecking every core test shard on its own (the stock shard runner stopped at upstream's red ui/ partition and hid these): - subagent-run-liveness: keep STALE_UNENDED_SUBAGENT_RUN_MS exported. Gate 2.7 batch 2 (50593f1) un-exported it as upstream has it, but 12 continuation work-dispatch suites age runs past this cutoff by importing it; they ran with NaN timestamps. Visible red: parent-lineage "orphan post-staleness-cutoff -> reap" (green at 4753b39, red at 50593f1 and every later head). Now 15 files / 147 tests green. - agent-request-preflight.test: the reserved continuation run-id cases await the preflight upstream made async in openclaw#169566 (step 66). Green at 2538e5c, 4 failed at 1a6c3a1, 33/33 with the fix. - agent-runner-embedded-candidate.continuation.test: createAssistantError Transcript() takes no argument since upstream openclaw#169237 (step 60); type error only. All 32 core test-shard graphs typecheck at this head. Refs #1475 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ounding, gateway close, cron, ingress, logging - config-reload (openclaw#89526): beta.4 serializes reload passes and dropped the mid-transaction observation re-read, so the fork's accepted-revision carry-over goes. Each transaction still publishes its completed source read in `finally`, only while its revision is current; a write's echo is read and published by its own next pass. Candidate names follow beta.4 (GatewayConfigReloadCandidate, activeConfigCandidate, retryCandidate). config-reload.observation.test.ts pins "no follow-up reload" for two echo cases; those expectations are re-checked when the suite runs. - transcript recent text: the fork's grounded selection (same-turn tool-result media, managed-media grounding, channel replay byte bounds) stays host-side on beta.4's bounded-tail pages; beta.4's transcript-recent-text.ts exports extractRecentConversationText and carries the boundReplayBytes option. - sqlite message append: beta.4's file; the fork's double-redaction replay helper (openclaw#169154) is superseded by openclaw#169237. The fork's redaction-replay conformance test stays as the check. - conformance and server-close tests: beta.4's files (the fork only extracted them for the line cap); the fork's adapter and mocks modules follow beta.4's types and mocks, and server-close.test keeps the fork's restart-trace and shutdown-state resets. - server-close: the fork's shutdown-state module and postShutdownExitCode on beta.4's close. - agent-turn-service: beta.4's file plus the session store path for the fork's answered-turn marker. - cron-job-access: beta.4's visibility read plus the fork's idempotent already-gone remove. - ingress-drain: the fork's dispatch quiescence around beta.4's transferred/pending results. - heartbeat runner: disableMessageTool on beta.4's reply options. - logging: beta.4 removed the redaction pattern guard (openclaw#169063); hasConfiguredRedactPatterns stays for diagnostics-otel. service-traces keeps the stale-span watchdog on beta.4's map.
…st gate (7 files) Bare beta.4 passes every one of these files that it has; each red was the carry's. - cron.validation: the session lookup mock comes from cron-session-reader.test-support.ts directly (a re-export of an import in the shared mocks module was undefined after vitest's mock hoisting). - answered-turn replay rule: the committed-turn entry read is the host's latest-state loadSessionEntryReadOnly again (the worker read did not see another process's write between the stage snapshot and the decision; entry-race test 9/9); a session-actor scope still reads through its memory owner. - non-owner assign test (fork): prepares the runtime config beta.4 reads, as its sibling session-archive test does. - restart-orphaned claim test (fork): runs in the database-worker project like the other claim suites; on a live claim beta.4 refuses one step earlier (ReplyRunAlreadyActiveError at the run's reply admission), so the control accepts either refusal. - cron fallback no-persist test (fork): the fixture's session and run results name the "openclaw" harness, because beta.4 drops context facts on a harness change. - models-cli profile-id test (fork): beta.4's exit spy. - conformance redaction-replay test and its adapters module (fork): deleted. On beta.4 the stored copy keeps the raw bearer token, so the double-redaction case (openclaw#169154) it pinned cannot arise; openclaw#169237 is the upstream fix.
Related: #168848, #169091, #168392.
What Problem This Solves
Conversation prefixes changed between model requests when older images were cleaned up, a captured user turn was replayed, or an assistant failure was split for transcript storage. That discarded reusable prompt-cache prefixes.
User Impact
Previously sent images and captured user content remain stable across subsequent turns and interrupted-turn replay. Failed assistant attempts remain append-only in the transcript, including their completed tool facts, while recovered failures can still be hidden from live display.
Why This Change Was Made
Remove the moving image cleanup policy and its tracking/diagnostic exceptions. Record the existing v1 user projection even when no hook changes the text, then preserve it on retries. This adds one metadata write per ordinary native user turn; retries reuse it without another write. Inter-session turns retain the already-canonical source envelope from the first request, using the fix in #169238. Persist each assistant failure once through the ordinary transcript owner, with the same completed-tool projection for live requests and cold replay. Signed thinking remains attached to completed tool calls. SDK retries continue from the retained failed turn instead of deleting it.
Images remain eligible for removal by ordinary history truncation or compaction. Cold replay of fact-only attachments still requires their source media files; this change does not create a second media store.
Evidence
A synthetic OpenAI Responses session using
gpt-5.6-solexercised two image turns, an injected retryable stream error, its actual retry, and an appended correction. Each before/after session made ten real provider requests over nine turns. Usage below comes from the provider's completed-response events, including the deliberately interrupted response.Aggregate cache reuse rose from 67.3% to 77.4%; uncached input fell from 61,831 to 42,809 tokens (30.8% fewer). The candidate's turn-five miss occurred with an unchanged retained input prefix; provider cache availability remains variable. The baseline rewrote its first image at that turn. Deterministic request-prefix tests separately enforce the invariant.
Observed median provider-request time: 1.86 → 1.52 s. Whole harness wall time: 93.9 → 116.5 s; peak RSS: 2715 → 2543 MiB. Whole-run timings include cold runtime preparation and concurrent-host variation; cache-token and byte-prefix evidence determine the result.
Production diff under the requested exclusions: +94/−542 lines, net -448. (This exclusion pattern also counts the shared lifecycle assertion helper.)
content[1].typeat turn five; old unchanged-user replay fails to make its second request; old error persistence loses original text/error fields. The candidate passes the corresponding owning-boundary checks.node scripts/run-vitest.mjs src/agents/embedded-agent-runner.prompt-cache.test.ts --maxWorkers=1: all four provider routes passed (357.89 s test duration; 506.68 s including worker preparation).node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/attempt-session-replay.test.ts --maxWorkers=1: 60 passed in 204.28 s. The changed replay test also passed the infra TypeScript graph. The 16 prior failures differed only in the intentional first-dispatch projection metadata; expectations now allow that exact addition on the admitted user and still compare every other field.node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/attempt-prompt-submit.projections.test.ts src/agents/embedded-agent-runner/run/attempt.llm-boundary.test.ts src/gateway/gateway.prompt-cache.test.ts --maxWorkers=1: 33 passed across three projects (245.68 s wrapper wall time), including real Gateway completion/restart prefixes.node scripts/check-changed.mjs --stagedpassed static ratchets, core types, and 22 test-type groups before the rig filled its disk while writing the agents/sessions TypeScript cache. All corresponding code, lint, type, and build checks passed in exact-head CI onb43a1dd70af0f560f6c9e4be4e8f65c4a9ee8cc7. No local suites, builds, or typecheck ran.CI exposed stale expectations for the retired image-cleanup exception, preserved error records, and first-dispatch projection metadata. These are corrected without dropping content assertions. The built-CLI lifecycle assertion now allows only the opaque display-generation token to change after the projection write; physical transcript events, message content, and ordering remain exact. A separate rig replay stopped at Doctor's 60-second deadline before reaching that assertion; the built-CLI proof passed in the final hosted CI run.
Validation ran on an isolated Linux rig (Node 26) after the requested Blacksmith Testbox failed sync. Testbox
tbx_01m4npyqrcwtf95tf7entyygq4: initial dependency preflight failed, frozen install passed, then two sync attempts timed out. AWScbx_185b0eeeb3c4: quota fallback supplied only a 2 GiB machine; stopped. Hetznercbx_9a5543211cbd: normal and full-resync stalled; stopped. No production Gateway was accessed.The final CI run has 54 successful jobs and one non-aggregate failure:
checks-ui-e2e (1/2), wherechat-widget-sandbox.e2e.test.tstimed out inelementHandle.hover(39 ms remaining). The UI test, its helpers, and the widget implementation are unchanged between CI's main parent408a1f314ee51d8870c2845d338d3d96a69b42c5and tested merge4dff950e63ac1edf84f598e4347209cfa53f8836. On that exact main parent, the test passed alone; the same 25-file shard passed all 86 tests under Node 26 and CI's Node 24.19.0. The failure has not been reproduced on main; no CI rerun or source change was made to chase it. The aggregate CI gate remains red solely for this UI failure.Rebase and landing follow-through
Rebased the five-commit branch onto
ed684fc775159cb4a3294667789c4e9e86e9293e. The single conflict was inattempt-session-replay.test.ts: main removed redundant table cases, while this branch changed their transcript expectation. The resolution keeps main's reduced table and applies the captured-user-projection assertion. Range-diff confirms no production change in the rebase; the production diff remains +94/−542 lines (net −448).Fresh independent Codex review of rebased head
04bbe26273c87b60f27b9ff3b83e5792ad1d4c02completed with no actionable P0–P2 findings. Current-head remote validation results follow below.Validation on the isolated Linux rig (Node 26, pinned base plus the complete rebased patch; no Team access):
node --import ./scripts/tsx.mjs scripts/check-export-name-collisions.mts: passed.node scripts/check-changed.mjs --stagedpassed formatting, dependency/architecture/closure ratchets, production types, and the completed agent/Gateway/infra test-type groups. Its remaining duplicate static work was superseded by the fully passing exact-head CI, including all type, lint, and build checks; this partial rig run is not claimed as a completed gate.04bbe26273c87b60f27b9ff3b83e5792ad1d4c02, including both UI E2E shards andopenclaw/ci-gate. No CI rerun or admin exception was needed.The separately requested hover investigation identified the old failure precisely:
chat-widget-sandbox.e2e.test.ts/loads protected widgets in chat and preserves isolated interactive frames, inclickBoardWidgetControlwhile hovering the expanded widget'sToggle detailscontrol. It exhausted the helper's 30-second CI deadline. Six full widget replays passed, including original headb43a1dd70awith both Node 26 and Node 24.19.0 and the Playwright-pinned Chromium 153.0.8010.12. Diagnostics observed one stale child-frame size that the existing retry correctly rejected before succeeding. No persistent failure or safe owner fix was established, so no speculative UI change is included or claimed as a repair.