Repository navigation
fix(sessions): preserve local prompt caches when history hits its byte cap - #168157
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis 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.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Partial 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 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe 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]
Technical reviewBest 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
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +41, Tests +183, Docs +24, Other +1. Total +249 across 7 files. Added test files: 2. View PR surface stats
LabelsLabel changes: No label 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 (3 earlier review cycles)
Reviewed October 10, 2026, 1:25 AM ET / 05:25 UTC (Revision 4). |
|
Merged via squash.
|
…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
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: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 reportedshouldCompact: false. Cached-token counts come from Ollama's actualprompt_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 reportedshouldCompact: falseandroute: fits.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.mjsgate 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 bydfdda05fe3c5(#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 combinedopenclaw/ci-gatestatus 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
3fe5d19d3fd8215b74936a7ecef34d3d081b9ac5is scoped-clean through P2; both accepted initial findings were fixed and covered.pnpm build qaRuntimepassed (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 replacingpackages/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.