Repository navigation
perf(sessions): keep context accounting bounded on large sessions - #174274
Conversation
…ions Keep exact context accounting in the session actor across ordinary appends and metadata rewrites. Bound resident completion history and preserve durable retry lookup. Remove duplicate completion and transcript reads during input staging.
|
🦞👀 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 SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Carry the complete actor projection into cold accounting without another snapshot read. Correct the regression fixtures to exercise the existing worker message path.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 880889261d
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (input.kind === "stage") { | ||
| const snapshot = readPendingInputStage(current, input, row); | ||
| if (!isDeepStrictEqual(snapshot, input.expected)) { | ||
| if (row?.input_id !== input.expected.existing?.input_id) { |
There was a problem hiding this comment.
Recheck terminal completion before restaging
When a tracked retry reads its snapshot just before the original run records a terminal completion and removes the pending row, both row?.input_id and input.expected.existing?.input_id are undefined, so this check passes and the transaction inserts the pending input again without noticing the newly committed completion. The retry then receives custody and can execute the same user input twice; recheck the completion/committed-input state at the staging effect rather than comparing only the pending-row identity.
AGENTS.md reference: AGENTS.md:L71-L71
Useful? React with 👍 / 👎.
|
Review disposition: the absent → staged → terminal → absent retry case is an accepted internal-bookkeeping interleaving under this change's design scope. Staging keeps the input-ID comparison, session authority, and live input-owner check; it does not recapture the full completion/transcript snapshot after preparation. The accepted edge is now explicit in the PR body. No reproduced data-loss, disclosure, or money-risk case was provided. |
Supply the required validateTurn flag and retain the literal message event type. Production behavior and regression assertions are unchanged.
|
Codex review: needs maintainer review before merge. What this changesThis PR maintains incremental context totals, bounds resident completion records, and removes duplicate bookkeeping reads during input staging. Example: Append a message to a session containing 600 retained events.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this maintainer-authored PR addresses remaining history-dependent work on main, and source review found no actionable introduced defect. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherThe session writer receives transcript and pending-input operations, commits SQLite changes, and publishes actor receipts that context-accounting readers consume. flowchart TD
A[Session operations] --> B[Session actor writer]
B --> C[SQLite transcript and completions]
B --> D[Committed actor receipt]
D --> E[Context accounting reader]
E --> F[Context size and event totals]
C --> E
Technical reviewBest possible solution: Land the existing actor-owned accounting and bounded completion changes once the exact-head CI gate completes successfully. Do we have a high-confidence way to reproduce the issue? Current-main source shows unbounded completion hydration and aggregate accounting outside complete actor windows; no target code was executed during this read-only review. Is this the best way to solve the issue? The change appropriately extends the existing actor and receipt owners, preserves canonical fallback readers, and makes the accepted staging-bookkeeping tradeoff explicit. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 33f497e178d7. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +201, Tests +145, Docs +8. Total +354 across 25 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 Reviewed October 16, 2026, 10:46 AM ET / 14:46 UTC. |
…enclaw#174274) Keep exact context event/byte totals in the session actor across ordinary appends and metadata rewrites, with receipt publication and rollback. Bound resident completion history to 512 entries and retain indexed lookup for older retries. Remove duplicate staging snapshot reads while preserving input identity and live authority. Focused owner tests, two Codex review rounds, and static proof cover the change. Full large-session measurements follow separately; no latency saving is claimed. Release notes: large-session context accounting and completion hydration no longer reread all retained history during ordinary warmed operations.
…turn (#1475 D1) Carry openclaw#169843 (ca0a172, "fix: chat turns fail when session receipts exceed transport limits") onto the composite's actor shape, plus the transfer collector it depends on from openclaw#169744 (31a4b92, sqlite-worker-transfer.ts only). When the committed outcome serializes past SQLITE_WORKER_MAX_MESSAGE_BYTES, the worker frames it through live transaction admissions and commits only a small transfer witness. The host accepts the frames, and certifies the outcome only when the witness names the completed transfer. The receipt cap is unchanged. Adaptation to 855242b: admissions carry the full projected hot snapshot (this base has no projectSessionActorAuthority), and the commit admission has no inner kernel publication, so authorities receive undefined there as before. Accepted cost: on oversized sessions every frame repeats the hot snapshot; upstream later bounded the hot state itself (openclaw#172702, openclaw#174274), which stays a separate carry. Refs #1475 Co-Authored-By: Claude Opus 5.5 <[email protected]> (cherry picked from commit 454e86e)
What Problem This Solves
Large sessions repeatedly scan retained events to compute context totals, and session actors hydrate every historical input-completion receipt. Both costs grow with retained history even when the next model prompt uses a bounded window.
User Impact
The session actor now retains exact event and byte totals independently of its bounded transcript window. Appends and metadata-only rewrites update those totals in the existing writer transaction and publish them with the receipt. Boundaries and uncovered historical rewrites use the canonical reader; rollback preserves the previous totals. Completion residency is limited to 512 records, with indexed durable lookup preserving older retry outcomes.
Input staging consumes prepared completion/transcript facts instead of reading them again. It retains the accepted input-ID comparison, session authority, and live input-owner check. Accepted edge: completion/transcript bookkeeping may advance after preparation; a still-authorized run consumes its prepared facts. In particular, a retry prepared before an input is staged can observe an absent row again after that input finishes; staging does not add a second completion-snapshot check for that theoretical interleaving. A different accepted input still refuses staging.
Prompt/context selection, stored transcript bytes, durability, schemas, and retention are unchanged. This is the accounting half of the two merged large-session changes.
Validation and scope
The corrected focused owner batch passed 57 tests across eight files, including accounting rollback/rewrites, completion eviction and old retries, pending-input custody, history readers, query plans before and after ANALYZE, and live session previews. Formatting, type-aware lint, source-contract/export checks, types, Madge, PostgreSQL conformance, selected changed tests, and T1/dialect ratchets passed on the final PR heads. Accounting CI: 38916493040; history CI: 38919216838. Both required CI gates passed; no CI/admin exception was used.
Knip's lane-caused obsolete export was removed. Two remaining unused exports,
redactSensitiveTextinpackages/ai/src/transports/transport-utils.tsandI18nControllerinui/src/i18n/lib/lit-controller.ts, reproduced under the same rules/files on maincf7522093c8832429689ac32d5e79d2eafdb3f3aand were routed for repair. Knip is not described as wholly green. Two Codex review rounds completed; the remaining P2 history-cache finding is recorded below.T1 inventory: touched shared modules 28 → 28, broader session/history scope 164 → 164, global 222 → 222, global compatibility tier 12 → 12. Retained synchronous SDK/opaque-callback roots require a public-contract/owner cutover; not every shared primitive has independently proven SDK reachability. No worker-only relabel hides that debt. Dialect ratchet: mechanical 2 → 2, design 12 → 9, engine-maintenance 0 → 0. No public SDK surface, schema, update, Doctor, plugin-loading, or service-lifecycle change; the update cell is not applicable.
Combined measurement
These measurements cover both the accounting and history changes together. The 25 owned production files at the final history merge are byte-identical to measured candidate
027ba984fb63a06d323303ef5caa728406df7484; CI fixture/type-only integration fixes do not change that implementation. This does not establish session-size-independent end-to-end turns.withTranscriptContextSnapshotstill reads the entire navigation projection before bounding context, and older model-size batches grow with history. Cold accounting, cache eviction, marker-dense TTL work, and the legacy unindexed-prefix join also remain.Base
95a27d0779d1c8e0c44b35e6cab9d7662e3bb6e7; candidate027ba984fb63a06d323303ef5caa728406df7484. Three alternating pairs. Counts are median [min–max]. Ordinary warm rows have n=9 per available side; supplemental profiles have n=1. No quiet-host latency claim. Sizes are initial synthetic transcript-event counts; ordinary turns append normally. Full active history is retained with the supported 20-message channel history limit, disabled transport and memory search, and synthetic completion rows.Ordinary warm turns
Causal SQL / requests / MAIN follow turn ownership, including work outside the observed window.
Raw SQL / requests / MAIN include all work observed in the named phase.
Baseline 30k/60k paired warm samples are unavailable after product worker timeouts. An earlier excluded 30k diagnostic succeeded; the 30k failure is not universal. Later baseline arms were restricted to 1k/10k; no further large-session timeout probes were run.
Cost diagnostics
Logical returned MB follow causal turn ownership, including work outside the observed window; they are decoded values, not disk I/O. MAIN CPU is thread CPU measured within the tighter operation snapshots. These loaded-host instrumented CPU values do not support latency or speedup claims. Snapshot bytes, service and elapsed observations remain in the local measurement artifact. No quiet Testbox was immediately available; the queued lease was cancelled.
Remaining model-context growth
SQL families use full observed phases; request families use causal ownership. Full-phase SQL-family bytes need not reconcile with the causal bytes above. The zero at 1k means this named model-context worker request was not used; it does not mean there was no context assembly.
At the matched 1k/10k sizes, median causal SQL falls by four and total causal request counts are unchanged. Four measured native read classes shrink: active COUNT/SUM, latest active boundary, exact-entry snapshots and participant projection. Individual turn deltas vary, and observed phases can straddle operation boundaries. Other shared entry/row/watermark reads remain. The generic accounting-associated request lacks a retained domain caller at 10k, so its request-level attribution is positional and is not included as a machine-classified family. Actor operations are mixed reads/writes, not an actor-rehydration-only total. Candidate 30k/60k first warm turns can still include a boundary lookup; no universal zero-boundary claim is made.
Shared native-read families (statements per warm phase, median [min–max]; n=9 per cell):
Actor hydration and entry-cache loads are not separately isolated in retained request origins. Snapshot-bearing SELECTs above are directly measurable native reads, not independent cache-load requests. Mixed actor command counts are retained separately in JSON and must not be relabeled as hydration. No zero-hydration or flat-rehydration claim is made.
History and session list
Ordinary chat.history first page, observed SQL / requests / MAIN and snapshot logical returned MB (n=3 per available side). UI bytes use the tighter operation snapshots, not the full observed phase:
The marker/reply-heavy supplemental profile shows the following after-append refresh (n=1); raw counts use the full observed phase, while bytes use the operation snapshots:
At 60k the metadata projection changes from 41 calls/2,596,325 logical bytes to 1 call/235 bytes. The extra candidate observed request is a nested readonly-worker request with no retained domain caller; do not label it confidently unrelated background. Its associated SQL finishes outside the named phase. sessions.list at 60k has 0 observed SQL/requests on both sides. Initial 1k UI observations include initialization/background work.
Unchanged shared harness
Warm rows pool 30 turns per side; whole rows have 3 runs per side. Observed warm MAIN outliers are background lease-expiry reads (
openclaw-state-lease-store.ts:131), not causal turn SQL.Prompt and evidence limits
Across 26 matched prompts, all 63 differing fields are observed wall-clock prefixes after fixture-root normalization. Exact bytes differ; source comparison retains every difference. 30k/60k prompts are unpaired. Provider input items and bytes are retained in the measurement artifact; exact selected source-event counts are not fully retained.
The source inventory is distinct from measured MAIN statements: changed shared files retain 28 T1 sites; the measured ordinary scale path is 0 MAIN.
Remaining review follow-up
P2: the per-connection history cache key contains session ID, while display-source identity also includes logical agent. Two logical agents reading the same physical session may reuse the first agent's cursor source. No data-loss or disclosure effect was demonstrated. This cursor-consistency case is deferred under the requested two-round review cap; it is not claimed fixed.
Change size: 25 files, +442/−88 lines; production +257/−56, tests +173/−31, test support +4/−1, docs +8.