Repository navigation
perf(sessions): narrow retention reads and batch automatic capacity cleanup - #172985
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 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. |
|
Codex review: needs changes before merge. What this changesThis PR narrows session retention candidate reads and skips protection inventory reads when no session identities need resolving. Example: A store has expired sessions protected only by a provider, with no active-session, work, or lifecycle identities.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Needs changes before merge - 1 item remains Keep this useful performance PR open, but repair the always-true projection condition before merging. Priority: P2 Before merge
Findings
Tests
Agent review detailsHow this fits togetherThe SQLite maintenance planner receives retention policy and live protection snapshots, selects eligible session rows, and passes archive or removal plans to the existing transaction and finalization owners. flowchart TD
A[Background maintenance] --> B[Shared retention planner]
B --> C[SQLite candidate queries]
D[Live protection snapshot] --> B
C --> E[Selected session rows]
E --> F[Commit checks]
F --> G[Archive and removal owners]
Technical reviewBest possible solution: Drop empty active keys before deciding whether to load the protection projection, retaining the phase-specific cutoffs and existing commit checks. Do we have a high-confidence way to reproduce the issue? Current-main source establishes the unnecessary inventory read; source inspection and the exact-head CI assertion establish that the new skip condition cannot take effect. Is this the best way to solve the issue? Filtering candidates at their existing query owner and reusing the shared planner's pressure decision is appropriate, with a small correction needed to recognize an empty active-key set. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 8da316f85d87. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceAcceptance criteria:
What I checked:
Likely related people:
PR surfaceSource +26, Tests +124, Docs +2. Total +152 across 5 files. Added test files: 0. View PR surface stats
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 15, 2026, 5:31 AM ET / 09:31 UTC. |
…leanup (openclaw#172985) * perf(sessions): narrow retention candidate reads * perf(sessions): narrow protection reads and yield capacity cleanup * chore: merge main to pick up CI capacity assertion repair
What Problem This Solves
Session retention planning loads every active session key even when protection needs only a few ancestors. It also decodes dashboard and model-run candidates before their enabled retention phase is due. Automatic capacity cleanup can archive thousands of entries while retaining the writer for one operation.
User Impact
Large session stores read less unrelated maintenance metadata. Automatic capacity cleanup yields the writer between batches of up to 64 entries, allowing foreground writes to run between them. Explicit cleanup remains exhaustive. Existing age, capacity, live-protection, and transcript archive rules remain in force, with no configuration, schema, migration, or SDK change.
Why This Change Was Made
The existing maintenance owner now loads active ancestry through indexed key lookups, one query per frontier. It keeps the full session-key projection only when admitted work or lifecycle identities require identity resolution. Provider-only protection uses the published provider keys directly. The indexed age query applies each enabled retention phase's cutoff before projecting entry metadata; the SQL-side projection still bounds large payloads.
Automatic cap work uses successive fully settled operations, refreshing protection between batches and continuing below the high-water trigger until the configured cap is reached or no eligible progress remains. Count/age receipts and deadline scheduling stay with their existing owner. Age-driven metadata archival is not newly bounded by this change.
Removed work and accepted edge cases:
finallyremains the sole cleanup owner.Selected-row and transcript-version checks, live protection at destructive commit, and lease-loss abort remain because they protect user data. No schema/index proposal is required for these code-only changes.
Evidence
Gateway main-thread database inventory in the changed owner: T1 0 → 0. No new synchronous fallback or dialect-specific SQL.
The scale comparison substitutes the six maintenance-owner source files from baseline
99c22c38fe38f936a4b352c3ee5e553d4b2cf638and candidatece5ad566249c74c90dbdfc2d96d50e3ae3a3068cinto the same candidate common tree. These are controlled owner comparisons, not two complete historical checkout builds. The candidate owner files are byte-identical to merged commit2ff5d6fbb21d681922c17d292094baa4f21d934b.The synthetic database has 8,564 sessions and 4,760,000 transcript events, compact payloads, and a size of approximately 983 MB. It imports 84 matching aggregate
sqlite_stat1rows; 18 unmatched rows are skipped. The source statistics came from a newer snapshot with 9,381 sessions and 5,485,951 events, so their cardinalities and the synthetic distribution do not exactly match. No private rows, transcripts, or database files were copied.Matched full automatic maintenance pass
This is a deliberate writer-fairness tradeoff: +935 statements (+4.23%) and +147 requests for the complete pressure pass, with 7,892 fewer returned rows. The extra requests are exactly 49 additional batch rounds × three execute requests. Each batch settles and releases the writer before the next operation, so foreground work can run and new protection is captured. The largest candidate interval is the existing ANALYZE transaction. These times were observed on a busy shared host, include scheduling, lock-acquisition wait, and observation overhead, and do not establish a latency improvement or regression.
Both variants reach 5,000 active sessions, archive 3,182 metadata entries, and publish all 382 transcript archives. Both provider-protected expired sessions survive. Each publishes 3,564 unique receipt keys and 382 unique removed keys, closes its owners, and returns automatic scheduling to the next deadline. The fixture is restored between runs, including canonical metadata and transcript generations.
The SQL ledger below accounts for the whole matched pass. Requests are instrumented at the automatic-driver boundary (open/execute/task), so per-substep request counts cannot be separated; the overall request counts are 2/39/13 for base and 2/186/13 for candidate. Short-lived transcript workers remain; this change does not claim to retain every worker.
Full-pass physical rows scanned are unavailable: Node SQLite does not expose scanstatus in this harness. Returned rows above are not scan totals. Separate CLI SELECT replays succeeded for 30 baseline and 15 candidate samples, including baseline-only diagnostics. For the matched automatic pass, the protection-key query changes from an active-index scan visiting 8,564 session rows to an indexed lookup visiting one session row for the captured root. Both age queries visit 640 indexed candidates, but metadata projection falls from 640 to 384 rows. The first deadline sample still visits 8,436 rows in both variants; transcript-reference protection still scans the session set. Entry-count queries rise from three to 101 calls and ordinary deadline reads from one to 50 calls, so this is not evidence of an overall physical-scan reduction. Reusing count/deadline facts across batches is a follow-up opportunity. Capacity-query replay fully consumes a query that runtime iteration may stop early. These are first-sample observations, never multiplied by batch count or presented as full-pass scans.
No-op maintenance and conversation non-regression
Three alternating pairs (
M,C,M,C,M,C), ten warmed turns per run. Values are medians [minimum–maximum] of the three run means for warmed metrics, and of the three run totals for other windows. The controlled source comparison is described above. Both variants were built once and their build snapshots reused; the shared harness was not edited.Maintenance contributes 0 statements / 0 requests to every causal first-turn, warmed, idle, and compaction-through-shutdown window. Across the whole workload, its observed contribution is exactly 9 statements / 3 linked wire requests in every run (planning accounts for 7 statements / 1 request). Finalization, age refresh, and planner statistics contribute zero in this small fixture. These small foreground differences are not claimed as savings from this PR. Whole-workload MAIN counts are identical in every run: 445 during boot, 13 during connect, and 9 during shutdown; none belongs to the changed maintenance owner.
Shared-read attribution, causal warmed medians (SQL statements / linked wire requests per turn):
Families are classified by observed owner stacks and may overlap; they must not be summed. Zero means no matching observed SQL, not no in-memory calls. Generic wire labels such as
executeortaskare not treated as semantic owner operations.First-turn causal requests rise by one at the median, despite lower first-turn SQL. The added request origins include the unchanged
readExactEntriespath throughsession-entry-read-ordered(1/1/1 → 2/2/2 requests) andsession-entry-read-runtime(0/0/0 → 1/1/0), offset by different counts in other unchanged read/admission paths. The first-turn selected-entry family remains 8 statements / 6 linked requests in every run. Raw first-turn and whole-workload statements and requests fall; no new maintenance operation appears.Adjacent tail windows show deferred-work redistribution and are not presented as a separate improvement:
The tail median rises from 192 to 211 statements and 67 to 73 requests. Observed memory-publication and deferred failed-spawn/subagent-registry work moves between windows; maintenance contributes zero here. Startup-through-first medians fall from 2,039 statements / 253 requests to 1,991 / 246, and whole-workload medians fall from 3,719 / 771 to 3,684 / 768. Per-family medians are not additive.
Observed SQL groups, per-run counts (first execution frame plus recorded cause; state boundaries are not claimed to belong exclusively to subagent writes):
All six runs independently pass 13/13 ordinary turns (including 10/10 warmed turns), successful compaction, and clean shutdown. Their recorded source hashes match the baseline/candidate Git blobs. Cron remains unmeasured because the fixture lacks a stored inference account; spawn lacks a successful receipt. Those two assertions make the workload wrapper return nonzero, so totals describe the attempted workload, not successful cron/spawn proof. The idle window is post-workload connected idle, including deferred work, not a quiescent idle benchmark.
An initial candidate attempt failed before turns because deferred schema startup had not settled; both preliminary attempts are excluded. All six counted runs use the same task-local trace-based prerequisite: wait for completed
post-ready.maintenanceandpost-ready.startup-maintenancespans and reject logged failures. This is fixture settling, not a public readiness guarantee; its SQL and requests remain in connect totals. No production startup guard was changed.The host was heavily loaded (observed load averages roughly 71–118). Candidate/base median duration ratios are 0.708 for warm windows, 0.865 for first turns, and 1.000 for idle; none exceeds the comparison-skew limit. These are comparability checks only, not latency claims.
The historical 41.4-second startup session-maintenance timing belongs to transcript-index reconciliation, a separate owner; this retention change does not claim to fix it. Age-driven metadata archival remains unbounded, and the existing deadline and transcript-reference scans remain follow-up opportunities. No schema or index migration is included.
Focused regressions cover provider protection after an in-process backdate, enabled age cutoffs, recent dashboard activity, active ancestry including missing parents and cycles, 64+16 automatic cap continuation below high-water, exhaustive inline cleanup, foreground writes and new protection between batches, protected-only termination, and retirement after the first receipt.
Two Codex autoreview rounds completed with no actionable P0–P2 findings. Formatting, type-aware core/script lint, and diff checks pass. Exact-head CI is green on
ce5ad566249c74c90dbdfc2d96d50e3ae3a3068c, including all Node tests, types, lint, source contracts, architecture/Madge, database ratchets, security, andopenclaw/ci-gate. The previous head hit an incidental CI shard-count assertion; integrating main picked up its existing capacity-contract repair without changing the six reviewed production files.Knip is resolved with inherited findings: production has three unused exports and full-tree has seven (eight distinct findings); both sets reproduce exactly with the baseline owner code. The script scan passes. The initial full-tree scan timed out at 600 seconds under shared-host load; the isolated candidate scan completed in 261 seconds and its matching baseline scan in 311 seconds. No finding is in the changed owner. Inherited exports:
FollowupQueueDisposition,DoctorLintCliOptionsSchema,authorizeSessionSharingTarget,assertRecordin the Google provider test helper,createAgentFixturein snapshot test support,renderMessageGroupContentin chat-message test support,QuestionPanelQuestion, andrecommendedIconUrlin model-setup test support.Scale and all three warm/idle pairs completed through the campaign CPU semaphore. Measurements finished after merge under the campaign's land-on-green rule. The published-driver update cell does not apply.
Diff size: production +239 / −164 lines; tests +388; CI test inventory +1; docs +5 / −1.