Skip to content

perf(agents): preserve image replay prefixes between cleanup batches - #167613

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-prompt-cache-truncation-pruning-churn-20260919
Oct 9, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-prompt-cache-truncation-pruning-churn-20260919

Conversation

@steipete

@steipete steipete commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

Historical image cleanup changes a previously sent tool result or user message on every completed follow-up turn, breaking reuse of the later prompt prefix.

User Impact

Long image/tool sessions preserve prior request bytes between cleanup batches. The newest three completed turns remain intact; up to ten completed turns are retained between cuts. This trades a bounded increase in retained image context for fewer cache invalidations. Image-heavy sessions can reach compaction pressure sooner. Normal compaction and provider-overflow recovery continue to own the total context limit.

Why This Change Was Made

The existing image-projection owner now derives one cutoff from completed canonical turns: the initial cleanup stays at four completed turns, and subsequent cutoffs advance eight turns at a time. Tool loops never advance it. Restart derives the same bytes without another cache, stored shape, or configuration option. Original transcript images remain untouched. Aggregate tool-result projections and cache-TTL soft/hard pruning already persist their decisions on current main; their owners remain in place and their regression suites were included in this lane.

Production LOC: +18/-28, net -10 (git diff --stat origin/main...HEAD -- ':!*.test.ts' ':!*test-support*' ':!docs/*').

Evidence

Blacksmith Testbox (blacksmith-testbox, profile openclaw-check), lease tbx_01m4fc2h6fp3dqsmm902rvea3z:

  • A synthetic replay through the real Agent loop, image transform, tool-result guard, and final truncation projection captured 57 dispatches across 28 tool/image turns. History rewrites fell from 25 to 4 (84% fewer). Modeled whole-message prefix reuse rose from 81.15% to 93.85%, and modeled lost-prefix tokens fell from 549,929 to 203,943 (62.9% fewer). These are modeled reuse measurements, not provider billing usage.
  • Peak estimated prompt context: 97,988 → 114,527 tokens, both below the 120,000-token prompt budget (128k window minus 8k reserve); zero oversized dispatches. Peak retained images: 4 → 11, including the active turn. All 28 original images remained in canonical history.
  • Tight-budget replay with the existing optional mid-turn precheck enabled intercepted a 19,469-token request against an 18,000-token prompt budget before a second provider call; zero oversized dispatches. This does not claim the diagnostic-only default preflight blocks ordinary overflow.
  • Replay body: 36 → 31 ms; process max RSS: 846,116 → 844,840 KiB. These one-shot timings are secondary to the prefix measurement.
  • New regression failed on the unchanged baseline because cleanup occurred on turns 4,5,…,28; the candidate cleans up only on turns 4,12,20,28. Restart replay, protected recent turns, bounded retained images, source immutability, and existing malformed/orphan/media-ownership cases pass.
  • Focused image, aggregate truncation, and cache-TTL tests: four files pass (node scripts/run-vitest.mjs … --maxWorkers=1, 48.03 seconds across three Vitest shards). Neighboring projection persistence, context guards, preflight, overflow recovery, and Gateway attachment ownership: five files / 64 tests pass, 42.19 seconds.

The changed gate passed its production and all 27 test typecheck graphs, format checks, and structural guards. Its only failure was the dead-export scan. A clean checkout of main 62355575c041dee0491658d4d1bc024d9fb3fc6b reproduced the same four production findings (bindCliQuestionAnswerAuthority, prepareSessionEventTargetForHost, readSessionEntryCreationTransition, and RESTART_CONTINUATION_CONTEXT_PREFIX), with the same latter two full-tree findings. These exports are outside this diff. Candidate gate: 23m13s; clean-main baseline scan workflow: 1m30s. No skip or baseline exception was added.

Full sibling directory: node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run — 206 files / 2621 tests pass, 332.53s wrapper wall time (338.11s remote command). The lease was stopped after proof.

Independent review: scoped-clean at P0–P2. Live provider replay: gpt-5.6-luna, Responses SSE, identical synthetic histories, distinct stable cache series, 1,024-token response budget, 57 requests before + 57 after, zero failures. Provider-reported cache reads 377,664 → 705,747 tokens (1.87×); cache-read share 47.35% → 88.66%; cache writes 419,605 → 90,010 tokens; cache-read drops 25 → 4, summing 368,525 → 58,775 dropped cached tokens. Peak provider-reported prompt size was 27,458 tokens. The initial 32-token-budget probe was discarded after missing usage on an incomplete response; the complete comparison used a fresh cache series. Wall time was 83.2 → 138.3 seconds; the candidate includes one 61.0s request (median request time 1.355 → 1.213s), so this PR claims cache reuse/cost improvement, not lower live latency.

pnpm test src/agents/embedded-agent-runner/run/history-image-prune.behavior.test.ts --maxWorkers=1: 10 tests pass; 7.54s wrapper wall time / 5.97s Vitest wall time; new regression body 11ms. No new test file, worker pin, timer, process fixture, or production export was introduced.

Provider-reported cache reads for every replay request
Request Before cache read After cache read Before prompt tokens After prompt tokens
1 0 0 101 101
2 0 0 1046 1046
3 1043 1043 1070 1070
4 1067 1067 2015 2015
5 2012 2012 2039 2039
6 2036 2036 2984 2984
7 2981 2981 3008 3008
8 3005 3005 3953 3953
9 0 0 3986 3986
10 3983 3983 4931 4931
11 0 4928 4964 4955
12 4961 4952 5909 5900
13 0 5897 5942 5924
14 5939 5921 6887 6869
15 0 6866 6920 6893
16 6917 6890 7865 7838
17 0 7835 7898 7862
18 7895 7859 8843 8807
19 0 8804 8876 8831
20 8873 8828 9821 9776
21 0 9773 9854 9800
22 9851 9797 10799 10745
23 0 10742 10832 10769
24 10829 10766 11777 11714
25 0 0 11810 11810
26 11807 11807 12755 12755
27 0 12752 12788 12779
28 12785 12776 13733 13724
29 0 13721 13766 13748
30 13763 13745 14711 14693
31 0 14690 14744 14717
32 14741 14714 15689 15662
33 0 15659 15722 15686
34 15719 15683 16667 16631
35 0 16628 16700 16655
36 16697 16652 17645 17600
37 0 17597 17678 17624
38 17675 17621 18623 18569
39 0 18566 18656 18593
40 18653 18590 19601 19538
41 0 0 19634 19634
42 19631 19631 20579 20579
43 0 20576 20612 20603
44 20609 20600 21557 21548
45 0 21545 21590 21572
46 21587 21569 22535 22517
47 0 22514 22568 22541
48 22565 22538 23513 23486
49 0 23483 23546 23510
50 23543 23507 24491 24455
51 0 24452 24524 24479
52 24521 24476 25469 25424
53 0 25421 25502 25448
54 25499 25445 26447 26393
55 0 26390 26480 26417
56 26477 26414 27425 27362
57 0 0 27458 27458
Remote proof commands (same Testbox lease)
# Candidate owner/sibling proof: pass, 4 files, 48.03s wrapper wall time.
node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/history-image-prune.behavior.test.ts src/agents/embedded-agent-runner/run/history-image-prune.test.ts src/agents/embedded-agent-runner/tool-result-truncation.test.ts src/agents/embedded-agent-runner/tool-result-truncation.cache-ttl.test.ts --maxWorkers=1

# Neighboring entry points: pass, 5 files / 64 tests, 42.19s.
node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/attempt-context-guards.test.ts src/agents/embedded-agent-runner/run/attempt-prompt-preflight.test.ts src/agents/embedded-agent-runner/run/overflow-context-recovery.test.ts src/agents/embedded-agent-runner/run/attempt-prompt-submit.projections.test.ts src/gateway/server-methods/chat-send-user-turn.test.ts --maxWorkers=1

# Full directory: pass, 206 files / 2,621 tests, 332.53s.
node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run

# Candidate gate: only the inherited dead-export scan fails.
node scripts/check-changed.mjs --staged

# Clean main baseline 62355575c041dee0491658d4d1bc024d9fb3fc6b: same failures.
node --import ./scripts/tsx.mjs scripts/check-deadcode-exports.mts

# Task-only real Agent replay: run once with baseline image cleanup, once with candidate.
LANE687_LABEL=before node --import ./scripts/tsx.mjs .local/lane687/replay.ts
LANE687_LABEL=after node --import ./scripts/tsx.mjs .local/lane687/replay.ts

# Live replay of captured synthetic contexts: 57 requests per series, both pass.
node --import ./scripts/tsx.mjs .local/lane687/live-replay.ts /tmp/lane687-before.json 20261009b all
node --import ./scripts/tsx.mjs .local/lane687/live-replay.ts /tmp/lane687-after.json 20261009b all

Replay fixture: 28 user turns, each invoking one synthetic diagnostic tool with 5,000 characters of text and a tiny PNG, followed by one tool-free turn. The real Agent dispatch uses the production image transform, tool-result context guard, and final truncation projection; per-result cap 8,000 chars, aggregate cap 80,000 chars, context window 128,000 tokens and reserve 8,000 tokens. Original transcript messages are preserved. Cache-TTL restart/soft/hard behavior is covered separately by the existing owner tests.

Advance historical image cleanup eight completed turns at a time after the
initial cut, preserving recent turns and deterministic restart replay.
The live synthetic replay raises cache-read share from 47.35% to 88.66%
and reduces cache-read drops from 25 to 4. Retained image context is bounded
to 3-10 completed turns; compaction and overflow recovery still own capacity.

Regression, 206 sibling files / 2621 tests, and independent review pass.
Changed checks pass except four dead exports reproduced on clean main.
@clawsweeper

clawsweeper Bot commented Oct 9, 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 docs Improvements or additions to documentation agents Agent runtime and tooling size: S labels Oct 9, 2026
@steipete
steipete marked this pull request as ready for review October 9, 2026 04:43
@steipete
steipete enabled auto-merge (squash) October 9, 2026 04:47
@clawsweeper

clawsweeper Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

The branch batches historical image cleanup every eight completed turns after the initial cut, preserving replay prefixes between batches.

Example: The user continues an image conversation through 28 completed turns.

  • Before: Historical image cleanup changes the replay prefix on turns 4, 5, and every subsequent turn through 28.
  • After: Historical image cleanup changes the replay prefix only on turns 4, 12, 20, and 28.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused patch has useful live cache measurements and no actionable finding; confidence is calibrated to harness-based production composition rather than a shipped CLI run.
Proof confidence 🦐 gold shrimp (3/6) Sufficient (live_output): The supplied real Agent replay exercises the changed image projection and surrounding guards, then live Responses replays measure improved provider cache reuse across the captured before/after contexts with zero failures. This is production-path harness and live transport evidence rather than a full CLI session. Canonical transcript writes and stored formats are unchanged.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes
User problem: Long image conversations repeatedly lose reusable cached context as historical images are cleaned up on each follow-up turn.
Reason: Measured provider cache gains justify the focused change. Prior merged history establishes area ownership, and the owner-authored proposal explicitly accepts the bounded increase in retained context.

Merge readiness

✅ Ready for maintainer review

This PR remains useful: current main still advances image cleanup every completed turn, and the proposed batching has measured cache benefits with no concrete blocking defect found.

Priority: P2
Reviewed head: 028f1feac6336a133268d93751f6451ba499f858

Before merge

None.

Findings

None.

Agent review details

How this fits together

The agent prepares a replay view of conversation history before sending it to the model. Image cleanup replaces older image payloads and attachment references in that view while preserving the original transcript.

flowchart TD
  A[Original conversation history] --> B[Count completed turns]
  B --> C[Determine batched cleanup boundary]
  C --> D[Replace older images and references]
  D --> E[Hydrate retained media]
  E --> F[Model request]
  F --> G[Compaction and overflow recovery]
Loading

Technical review

Best possible solution:

Keep deterministic batching in the shared replay owner, preserve canonical transcripts, and leave total context capacity to existing compaction and overflow recovery.

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

Not applicable as a performance proposal; source establishes the existing per-turn cutoff, and supplied before/after provider usage demonstrates its cache impact.

Is this the best way to solve the issue?

Yes. The change adjusts the existing shared owner without adding configuration or persisted state, and the area owner explicitly accepts the measured context-retention tradeoff.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Pinned introduced behavior: The introduced diff changes the existing cutoff calculation to retire one turn initially and then eight turns per batch; rewriting and hydration remain in the same owner. (src/agents/embedded-agent-runner/run/history-image-prune.ts:38, 028f1feac633)
  • Current main still needs this improvement: Current main retains the three-completed-turn sliding cutoff. The production owner and session-pruning documentation are unchanged between the pinned merge base and fetched main. (src/agents/embedded-agent-runner/run/history-image-prune.ts:44, fd2fa6b904a2)
  • Production integration and transcript preservation: Attempt setup installs the shared image transform before model input; the transform projects messages before hydration and again after the existing transform. Replacement messages are cloned rather than written back to canonical history. (src/agents/embedded-agent-runner/run/attempt-setup.ts:339, 028f1feac633)
  • Behavioral regression coverage: The added regression checks prefix changes at turns 4, 12, 20, and 28, deterministic reconstruction from serialized history, preservation of recent messages, and source immutability. The PR reports that this regression fails on the unchanged baseline. (src/agents/embedded-agent-runner/run/history-image-prune.behavior.test.ts:38, 028f1feac633)
  • Real provider cache evidence: The complete supplied PR body, captured as source revision a4f1455e031c93b6ba5c8a71cb69e185bf5b5ae275ef1e29ae08b46d397a9657, reports a real Agent replay followed by 57 live Responses requests per before/after series. Provider-reported cache-read share rises from 47.35% to 88.66%, cache-read drops fall from 25 to 4, and both series have zero failures; the body includes per-request usage values. (028f1feac633)
  • Area-owner capacity tradeoff: The PR explicitly accepts retaining 3–10 completed turns and potentially reaching compaction sooner. Its production replay reports peak estimated context increasing from 97,988 to 114,527 tokens within a 120,000-token budget; it correctly limits the tight-budget precheck claim to the optional enabled mode. Public docs: docs/concepts/session-pruning.md. (docs/concepts/session-pruning.md:108, 028f1feac633)

PR surface

Source -10, Tests +28, Docs 0. Total +18 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 18 28 -10
Tests 1 28 0 +28
Docs 1 2 2 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 48 30 +18

Review metrics

Metric Value Why it matters
Replay retention window 3 completed turns → 3–10 completed turns The explicitly accepted capacity tradeoff buys stable replay prefixes between cleanup batches.

Labels

Label changes:

  • add P2: This is a bounded cache-efficiency improvement for image-heavy conversations without an established urgent runtime regression.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • 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: This is a bounded cache-efficiency improvement for image-heavy conversations without an established urgent runtime regression.
  • 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.
  • 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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

Reviewed October 9, 2026, 12:49 AM ET / 04:49 UTC.

@steipete
steipete merged commit a134038 into main Oct 9, 2026
185 of 186 checks passed
@steipete
steipete deleted the steipete/perf-micro-prompt-cache-truncation-pruning-churn-20260919 branch October 9, 2026 04:52
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 10, 2026
…penclaw#167613)

Advance historical image cleanup eight completed turns at a time after the
initial cut, preserving recent turns and deterministic restart replay.
The live synthetic replay raises cache-read share from 47.35% to 88.66%
and reduces cache-read drops from 25 to 4. Retained image context is bounded
to 3-10 completed turns; compaction and overflow recovery still own capacity.

Regression, 206 sibling files / 2621 tests, and independent review pass.
Changed checks pass except four dead exports reproduced on clean main.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant