Skip to content

fix(sessions): preserve local prompt caches when history hits its byte cap - #168157

Merged
steipete merged 3 commits into
mainfrom
fix/history-hydration-stepped-window
Oct 10, 2026
Merged

steipete merged 3 commits into
mainfrom
fix/history-hydration-stepped-window

Conversation

@steipete

@steipete steipete commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Related: #159799

What Problem This Solves

Fixes repeated local-model prompt-cache misses when session history exceeds the model replay byte cap: selecting the newest events that fit moves the history start on every turn, even while the model has token capacity left.

User Impact

Byte-limited history now advances in quarter-cap chunks, preferring complete turns and preserving tool-call/result ownership. The selected prefix can grow unchanged between steps, including across fresh workers and processes. The hard byte bound, required compaction summaries, existing event-count limit, and compaction triggers stay intact; no configuration or schema change is needed.

This deliberately leaves headroom after a step. It does not summarize omitted context or recover the byte/token mismatch: serialized model-context events can still hit the resource limit below the token budget. Saved history remains intact. The docs now distinguish this limit from semantic compaction and the opt-in active-transcript byte guard.

Why This Change Was Made

This implements the maintainer-selected chunked-window policy. The current model replay hydration owner rereads canonical projected history independently of the raw resident SessionManager window. The fix stays in that existing selector, extracted into a focused module; no additional trimming layer is introduced. It rounds the absolute omitted-byte position into stable buckets after reserving the required boundary. Existing occurrence-aware tool pairing closes the cut, and a newest atomic turn that fits the hard cap can consume the headroom.

Production: +188/-147 lines (net +41). Tests: +182 lines, plus one test-routing line. Docs: +24 lines. Tooling inventory: +1 line. The added policy arithmetic and boundary handling account for the production growth; the existing selector was moved intact rather than duplicating it or deleting unrelated safeguards to meet a line target.

Evidence

The new persistent-history regression failed on unchanged production: the longest unchanged prefix run was one turn instead of at least three. Two focused policy regressions also failed against the initial candidate and pass after reserving the boundary's event slot and preserving a large tool turn through its final reply.

Native Ollama 0.40.2, qwen3:8b, 32,768-token context, 262,144-byte replay cap. A synthetic archive contains 409,600 bytes of text (mostly interior whitespace); native calibration measured 5,005 prompt tokens. All measured turns use the actual built embedded CLI:

OPENCLAW_STATE_DIR=<isolated-state> OPENCLAW_CONFIG_PATH=<isolated-config> \
  pnpm openclaw --profile prefix-history agent --local --agent main \
  --session-key agent:main:prefix-history-live --message-file <synthetic-prompt> \
  --thinking off --timeout 300 --json

Before: four replies returned OK, each loaded 59 messages, and all three transitions changed the first history fingerprint. Prompt tokens were 5,877/5,876/5,875/5,874; native cached tokens were 0/2,258/2,257/2,258. Every turn reported shouldCompact: false. Cached-token counts come from Ollama's actual prompt_eval_cached_count, not latency or total prompt size. The shared server can experience cache-slot interference.

Final candidate focused validation passed: 26 tests across three files with node scripts/run-vitest.mjs <files> --maxWorkers=1 (396.75 s wall, including 149.653 s native-worker preparation). The new persistent-prefix regression took 24.229 s of test time; the existing 23-test model-context-limit suite took 95.907 s; the two new policy tests took 2 ms. The database regression uses one isolated store to exercise actual serialized sizing, repeated appends, compaction/reset, and a large atomic tool turn; a helper-only test would not establish that storage contract. Its baseline run failed as intended (458.28 s wall /12.080 s test time).

The focused policy file also passed standalone (9.24 s wall /3 ms test time), and both cases failed against the first candidate (8.66 s wall). After: ten real replies returned OK; loaded-message counts were 54/56/44/46/48/50/52/54/56/58. There was one chunk advance, then eight consecutive turns with an identical existing history prefix. All ten still reported shouldCompact: false and route: fits.

Measurement Before After
Full previous history prefix preserved 0/3 transitions 8/9 transitions
Longest unchanged prefix run 1 turn 8 consecutive turns
Cached tokens on ordinary continuation 2,257–2,258 4,986–5,700
Uncached tokens on a preserving turn No preserving turn 132

After native cache counts: 0/5,588/2,266 (the chunk step)/4,986/5,105/5,224/5,343/5,462/5,581/5,700. The first two after-arm turns preserve a shorter prefix before the next step; each subsequent continuation reuses the full selected prefix. This exercises the real embedded CLI and native Ollama transport, not a mock or a Gateway run.

All pre-push ratchets affected by the runtime change passed (max-lines, line-cap, assertion-safety, database-worker, timeout-race, mock exports); config docs, plugin inventory, and focused core typechecking passed. The complete node scripts/check-changed.mjs gate passed all 35 stages (2,853.52 s wall), including all 27 test-type graphs, core typechecking, ratchets, formatting, API-usage checks, unused-export scans, and normal core/script lint. The first CI run found a missing PR-wrapper inventory entry, now fixed, and an inherited Active Memory status expectation, already fixed on main by dfdda05fe3c5 (#168182). The wrapper suite now passes 17/17 tests (416.22 s wall). Final-head CI passed with 94 successful jobs and zero failures (858 s run wall time); both the CI job and combined openclaw/ci-gate status are successful. A redundant focused-lint invocation using the broad core tsconfig timed out in its extra SDK declaration prerequisite; the normal core lint shard passed and is the accepted lint evidence.

Codex autoreview on final head 3fe5d19d3fd8215b74936a7ecef34d3d081b9ac5 is scoped-clean through P2; both accepted initial findings were fixed and covered. pnpm build qaRuntime passed (462.69 s wall including an artifact-lock wait; 298.1 s build phases). The full declaration build was stopped during package compilation; the supported runtime profile is the same profile used by Gateway worktree setup. A premature parallel test compile encountered the build replacing packages/ai/dist; final test proof runs after the build. No model-facing prompt or tool text changed.

ClawSweeper reviewed final head 3fe5d19d3fd8215b74936a7ecef34d3d081b9ac5: no findings or Before merge items, native proof sufficient, ready for maintainer review. The wrapper-inventory finding is resolved. The broader linked issue remains open for its documented context-retention concern.

Validation reuse: the final commit adds only the selector path to the PR-wrapper inventory. Runtime, test, and docs bytes match 9b9d37a6bf5f45d693086e5282ca29a59ad61f8e, where the live proof and complete changed-files gate ran. The targeted wrapper tests cover the additional inventory change; a fresh full-branch autoreview passed.

@clawsweeper

clawsweeper Bot commented Oct 10, 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: L labels Oct 10, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. labels Oct 10, 2026
@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR advances byte-limited replay history in stable chunks while preserving required summaries and tool-call/result ownership.

Example: An Ollama qwen3:8b session exceeds its 262,144-byte replay cap while remaining below its token budget.

  • Before: All three measured continuation transitions changed the history prefix.
  • After: Eight of nine measured transitions preserved the previous history prefix.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong shipped-entry-point evidence supports a focused correct repair; the overall tier reflects partial coverage of the broader linked issue.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied native Ollama results exercise the built embedded CLI through byte-limited replay selection with existing oversized history, showing successful replies, stable prefixes, and improved native cached-token reuse; the final commit only updates the wrapper inventory.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: Long local-model sessions repeatedly lose reusable prompt prefixes because byte-limited replay history advances on every turn.
Reason: The selected policy demonstrates useful cache reuse with a documented headroom tradeoff while correctly leaving the broader linked report open.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR provides a useful cache-stability repair absent from current main, and the previous wrapper-inventory finding is resolved; no actionable defects remain.

Priority: P2
Reviewed head: 3fe5d19d3fd8215b74936a7ecef34d3d081b9ac5

Before merge

None.

Findings

None.

Agent review details

How this fits together

The SQLite model-context reader selects projected transcript events before hydrating payloads, then supplies the bounded history to model replay.

flowchart TD
  A[Stored transcript] --> B[Canonical context selection]
  B --> C[Projected byte sizing]
  C --> D[Chunked suffix selection]
  D --> E[Tool ownership validation]
  E --> F[Bounded payload hydration]
  F --> G[Model replay]
Loading

Technical review

Best possible solution:

Land the focused chunked-window repair through normal gates while retaining the broader context-retention issue.

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

Current-main newest-fit selection explains the prefix churn, and the supplied native CLI comparison demonstrates it; this read-only review ran no target code.

Is this the best way to solve the issue?

Absolute byte buckets address cache churn in the existing hydration owner without adding competing state or relaxing the resource bound.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Bounded model-history selection changes intended behavior with a stated reason (83f9484: Bound model-context hydration to reduce memory use while retaining required summaries and complete tool frames.)
  • Oversized tool-frame recovery keeps the original intent (85ae291: Recover oversized result bodies only in opted-in temporary model views without changing canonical transcript bytes or tool ownership.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source +41, Tests +183, Docs +24, Other +1. Total +249 across 7 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 2 188 147 +41
Tests 3 183 0 +183
Docs 1 24 0 +24
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 7 396 147 +249

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This improves continuation performance for byte-limited histories without changing durable transcript data or introducing configuration.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • 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.

History

Review history (3 earlier review cycles)
  • reviewed 2026-10-10T03:40:58.042Z sha 9b9d37a :: needs maintainer review before merge. :: none
  • reviewed 2026-10-10T04:11:43.196Z sha 9b9d37a :: needs changes before merge. :: [P1] Add the extracted selector to the PR-wrapper inventory
  • reviewed 2026-10-10T04:56:12.582Z sha 3fe5d19 :: needs maintainer review before merge. :: none

Reviewed October 10, 2026, 1:25 AM ET / 05:25 UTC (Revision 4).

@steipete
steipete marked this pull request as ready for review October 10, 2026 04:00
@clawsweeper clawsweeper Bot added merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. 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 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. labels Oct 10, 2026
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Oct 10, 2026
@clawsweeper clawsweeper Bot added 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 rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 10, 2026
@steipete steipete self-assigned this Oct 10, 2026
@steipete
steipete merged commit c16bff1 into main Oct 10, 2026
202 checks passed
@steipete
steipete deleted the fix/history-hydration-stepped-window branch October 10, 2026 05:51
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
…e cap (openclaw#168157)

* fix(sessions): keep byte-capped history stable across turns

* fix(sessions): preserve complete turns at stepped window edges

* fix(tooling): include history window selector in PR wrapper
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 P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: L 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