Repository navigation
perf(sessions): reuse bounded worker history projections - #174275
Conversation
Retain worker-owned marker positions across ordinary appends, use indexed marker lookups, and seek cache-TTL controls without scanning message history. Preserve canonical cold, branch, reset, and deprecated synchronous SDK paths.
…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: 0607f14438
ℹ️ 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".
| return buildVisibleHistoryProjection(projection); | ||
| } | ||
| const sessions = historyProjections(projection.database.db); | ||
| const key = projection.resolved.sessionId; |
There was a problem hiding this comment.
Include the logical agent in the projection-cache key
When one retained history-worker connection serves a shared physical store for multiple logical agents, this session-ID-only key can return a projection built for another resolved.agentId. The projection retains displaySource, whose identity explicitly includes the logical agent, and the adjacent recent-page cache already keys by agent ID; reusing it across agents therefore returns the wrong display/read-window source and can make cursors collide across logical owners. Include projection.resolved.agentId in this cache key.
AGENTS.md reference: src/gateway/AGENTS.md:L60-L60
Useful? React with 👍 / 👎.
|
The PR-caused Madge failure is fixed by moving the history projection types into a dependency-free leaf. The four changed modules emit identical executable JavaScript after type stripping. Follow-up: qualify the per-connection history cache key with the logical agent ID, matching the recent-page cache. Logical agents sharing a physical session can currently reuse the first agent's display-source/cursor identity. This is a valid P2 cursor-consistency finding; it is deferred under the requested two-review-round cap. No disclosure or data-loss effect was demonstrated. |
Supply the required validateTurn flag and retain the literal message event type. Production behavior and regression assertions are unchanged.
|
Codex review: needs changes before merge. What this changesThis PR reuses worker-local history marker projections across reads and ordinary appends and makes cache-TTL control queries selective. Example: Read a three-event history page after appending one message to a session containing 4,001 visible events.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Needs changes before merge - 1 item remains Keep open: this maintainer-directed optimization is useful, but a verified shared-store cursor-identity defect remains. Priority: P2 Before merge
Findings
Tests
Agent review detailsHow this fits togetherGateway history and preview requests enter read-only transcript workers, which combine SQLite projection metadata with bounded payload reads and return positioned events and cursor identities. flowchart LR
A[Gateway history or preview request] --> B[Read-only worker]
B --> C[Current transcript snapshot]
C --> D[Retained marker projection]
D --> E[Bounded SQLite payload read]
E --> F[Positioned events and cursors]
Technical reviewBest possible solution: Qualify worker projection reuse by logical agent and session while preserving incremental appends, canonical fallback, and payload limits. Do we have a high-confidence way to reproduce the issue? Source establishes the failing case: two logical agents read the same session through one retained physical connection, and the second receives the first agent's cached display source; no target code was executed. Is this the best way to solve the issue? Incremental reuse fits the existing worker owner, but its key must include every logical identity component retained in the projection. Full review comments:
Overall correctness: patch is incorrect 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. EvidenceAcceptance criteria:
What I checked:
Likely related people:
PR surfaceSource +218, Tests +239, Docs +6. Total +463 across 12 files. Added test files: 1. 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:47 AM ET / 14:47 UTC. |
Integrate the landed accounting change and preserve the existing lazy history resolver type. Supply currentOnly for the byte-capped by-ID fixture and the database storePath for the prepared history target. Production behavior and assertions are unchanged.
…4275) Reuse and incrementally extend visible history marker projections in the history worker. Use indexed marker lookup and portable control-event selection for cache-TTL prefixes while preserving bounded payload projections and canonical cold readers. Focused history and query-plan tests, two Codex review rounds, and CI/static proof cover the change. The known logical-agent cursor-source consistency case remains a P2 follow-up. Full large-session measurements follow separately; no latency saving is claimed. Release notes: repeated history pages and ordinary append refreshes reuse worker-owned projection facts instead of rebuilding retained marker history.
What Problem This Solves
History pages repeatedly rebuild visible marker positions and linearly search them. Cache-TTL prefix selection can scan message rows to locate a small number of control markers. Those costs grow with retained session history.
User Impact
The history worker retains marker positions for recently read sessions and extends them from newly appended navigation. Indexed maps replace linear marker lookup, and the TTL query starts with indexed control-event candidates. Page limits and SQL-side payload-size projections stay intact. Same-generation payload rewrites invalidate the recent payload cache through its existing update timestamp.
Cold/evicted projections and branch/reset/rewritten-marker changes retain the canonical builder. Accepted edge: cold or evicted marker projections still pay a rebuild; repeated pages and ordinary append refreshes reuse or extend them. The deprecated synchronous SDK title reader retains its canonical uncached path through the documented compatibility window. The new incremental SQL query lives only in the history worker.
This is the second scoped change in the large-session turn campaign. It does not change model prompt selection, stored transcript bytes, schemas, or the public SDK.
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: 12 files, +512/−48 lines relative to main after accounting; production +266/−48, tests +240, docs +6.