Skip to content

perf(sessions): narrow retention reads and batch automatic capacity cleanup - #172985

Merged
steipete merged 3 commits into
mainfrom
dbasync/maintscale
Oct 15, 2026
Merged

steipete merged 3 commits into
mainfrom
dbasync/maintscale

Conversation

@steipete

@steipete steipete commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • Unconditional protection inventory: active roots traverse only their ancestry; deeper trees may need several indexed queries. Admitted work/lifecycle identities retain the inventory path.
  • Premature dashboard/model-run candidate reads: rows outside every enabled deadline wait for their applicable age or capacity phase.
  • Duplicate age-probe currency assertions immediately after the same owner check: the existing dispatch/effect guard still rejects retired ownership.
  • One redundant preservation disposal in the error path: the existing finally remains the sole cleanup owner.
  • One uninterrupted capacity operation: an error or stale rejection after a committed batch can defer the remaining below-high-water cleanup until a later trigger. Earlier committed batches remain published.

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 99c22c38fe38f936a4b352c3ee5e553d4b2cf638 and candidate ce5ad566249c74c90dbdfc2d96d50e3ae3a3068c into 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 commit 2ff5d6fbb21d681922c17d292094baa4f21d934b.

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_stat1 rows; 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

Measurement Base Candidate
All-thread SQL statements 22,116 23,051
Worker requests 54 201
MAIN statements 0 0
Returned rows 310,497 302,605
Direct changed rows 4,714 4,714
Capacity metadata transactions 1 50
Maximum metadata upserts per transaction 3,182 64
Transcript-delete transactions 6 6
ANALYZE transactions 1 1
Observed elapsed time 760.146 s 516.629 s
Largest writer interval, upper bound 13.351 s 6.929 s
Largest capacity metadata writer interval, upper bound 13.351 s 1.134 s
Largest transcript-delete writer interval, upper bound 3.849 s 2.855 s
ANALYZE interval, upper bound 0.085 s 6.929 s

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.

Substep Base SQL Candidate SQL Base returned rows Candidate returned rows
Entry count 3 101 3 101
Age candidate selection 1 50 640 482
Protection key capture 1 50 8,564 50
Capacity candidate selection 1 50 3,185 3,332
Age deadlines 3 150 257 690
Ancestor protection capture 2 100 2 100
Transcript-reference protection 7 7 58,224 58,224
Metadata archive 6,364 6,364 3,182 3,182
Metadata archive publication 1 50 3,182 3,182
Transcript archive/delete/protection 6,909 6,958 218,965 218,965
Shared planning/publication 767 914 7,128 7,128
Shared metadata/deletion planning 7,128 7,128 7,128 7,128
Transactions/admission/housekeeping 925 1,125 36 40
Planner statistics 4 4 1 1

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

Maintenance case Base SQL / requests / MAIN / returned rows Candidate SQL / requests / MAIN / returned rows
Cold no-op 51 / 5 / 0 / 9,089 50 / 5 / 0 / 269
Warm no-op 5 / 3 / 0 / 1 5 / 3 / 0 / 1

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.

Measurement Base Candidate
Causal warm statements / turn 84.4 [83.9–84.4] 83.9 [83.9–83.9]
Causal warm requests / turn 27.3 [27.2–27.3] 27.2 [27.2–27.2]
Raw warm-window statements / turn 86.1 [85.8–86.7] 85.2 [84.3–86.8]
Raw warm-window requests / turn 27.7 [27.5–28.1] 27.5 [27.3–27.9]
Warm MAIN statements / turn, causal and raw 0 [0–0] 0 [0–0]
30-second post-workload idle statements 107 [46–224] 105 [98–108]
30-second post-workload idle requests 41 [24–73] 35 [35–41]
Idle MAIN statements 0 [0–0] 0 [0–0]
First-turn causal statements 259 [256–263] 257 [256–257]
First-turn causal requests 68 [67–70] 69 [68–69]
First-turn raw statements 443 [315–450] 378 [377–385]
First-turn raw requests 105 [86–111] 95 [94–97]
Attempted whole-workload statements 3719 [3680–3751] 3684 [3679–3692]
Attempted whole-workload requests 771 [763–781] 768 [768–769]
Whole-workload MAIN statements 467 [467–467] 467 [467–467]

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):

Observed read family Base Candidate
Exact-entry facts 0 / 0 0 / 0
Actor hydration 0 / 0 0 / 0
Entry-cache snapshot loads 0 / 0 0 / 0
Row facts 0 / 0 0 / 0
Watermark-read helper 0 / 0 0 / 0
Selected-entry rows 2.2 / 2.1 2.0 / 2.0
Context-state reads 1 / 1 1 / 1
SELECTs referencing transcript watermarks 1 / 1 1 / 1

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 execute or task are 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 readExactEntries path through session-entry-read-ordered (1/1/1 → 2/2/2 requests) and session-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:

Run Compaction → shutdown SQL: base / candidate Requests: base / candidate
1 192 / 211 67 / 73
2 172 / 204 63 / 71
3 298 / 230 98 / 76

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):

Operation Tail base Tail candidate Whole base Whole candidate
Memory publication commit/schema observations [6, 2, 2] [6, 6, 6] [15, 17, 17] [15, 15, 15]
Subagent registry upserts [0, 0, 7] [4, 0, 5] [8, 8, 8] [8, 8, 8]
Turn-rooted state transaction boundaries [0, 0, 16] [8, 0, 10] [24, 24, 24] [24, 24, 24]

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.maintenance and post-ready.startup-maintenance spans 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, and openclaw/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, assertRecord in the Google provider test helper, createAgentFixture in snapshot test support, renderMessageGroupContent in chat-message test support, QuestionPanelQuestion, and recommendedIconUrl in 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.

@clawsweeper

clawsweeper Bot commented Oct 15, 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-15T10:58:39.110536Z ce5ad56 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: S labels Oct 15, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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. labels Oct 15, 2026
@clawsweeper

clawsweeper Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This 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.

  • Before: Maintenance reads every unarchived session key to resolve protection.
  • After: The intended result is zero protection inventory rows, but the current patch still reads them because an empty placeholder makes the condition true.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The direction is useful and focused, but a central optimization is unreachable and its new regression fails on the exact head.
Proof confidence 🦪 silver shellfish (2/6) This maintainer-authored internal query optimization is outside the ordinary contributor proof gate; its proposed scale measurements remain pending and are not treated as demonstrated results.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Large session stores perform unnecessary inventory reads and decode retention candidates before the applicable phase is due.
Reason: The existing feature owner proposes a focused reduction in database work without adding settings or changing retention policy.

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
Reviewed head: 51c1cb2e49eb0c9541219e9b5bbf6073476c41c2

Before merge

  • Drop empty active keys before selecting the protection projection (P2) - When activeSessionKey is omitted, the array constructed above still contains "" because uniqueStrings deduplicates without removing empty values. Consequently activeSessionKeys.length is always positive, so the new conditional always reads the full protection inventory, including the provider-only scenario this PR intends to optimize. The added regression confirms this on the reviewed head: CI reports five projected rows instead of zero at line 241. Filter empty normalized keys before this check so the no-identity branch is reachable.

Findings

  • [P2] Drop empty active keys before selecting the protection projection — src/config/sessions/session-accessor.sqlite-maintenance-store.ts:174

Tests

  • Missing end-to-end proof: No shipped Gateway or CLI performance run is supplied, and the new regressions do not yet have a demonstrated base-fails/head-passes result.
Agent review details

How this fits together

The 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]
Loading

Technical review

Best 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:

  • [P2] Drop empty active keys before selecting the protection projection — src/config/sessions/session-accessor.sqlite-maintenance-store.ts:174
    When activeSessionKey is omitted, the array constructed above still contains "" because uniqueStrings deduplicates without removing empty values. Consequently activeSessionKeys.length is always positive, so the new conditional always reads the full protection inventory, including the provider-only scenario this PR intends to optimize. The added regression confirms this on the reviewed head: CI reports five projected rows instead of zero at line 241. Filter empty normalized keys before this check so the no-identity branch is reachable.
    Confidence: 1

Overall correctness: patch is incorrect
Overall confidence: 0.99

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 8da316f85d87.

Provenance checked

  • Indexed maintenance candidate selection and protection projection keeps the original intent (645c0ac: Separate maintenance from foreground entry writes and load full payloads only for selected rows.)
  • Bounded metadata planning keeps the original intent (096f048: Avoid decoding unrelated payloads and prepare maintenance outside foreground write admission while preserving protection and retention.)
  • Shared retention phase sequencing keeps the original intent (d3e41c0: Keep phase ordering and pressure decisions in one storage-neutral planner shared by cleanup and storage callers.)
  • Worker placement and live commit validation keeps the original intent (c958468: Move automatic maintenance database work off the Gateway thread while preserving lifecycle custody and protection checks.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/config/sessions/session-accessor.sqlite-maintenance-writer.test.ts src/config/sessions/session-accessor.sqlite-maintenance-cadence.test.ts --maxWorkers=1
  • pnpm check:changed --base 9b2bc0e

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit c958468 adds src/config/sessions/session-accessor.sqlite-maintenance-store.ts:115 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: c9584688c461; files: src/config/sessions/session-accessor.sqlite-maintenance-store.ts)
  • Ayaan Zaidi: Raw commit 645c0ac adds src/config/sessions/session-accessor.sqlite-maintenance-candidates.ts:19 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 645c0ac609ab; files: src/config/sessions/session-accessor.sqlite-maintenance-candidates.ts)

PR surface

Source +26, Tests +124, Docs +2. Total +152 across 5 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 34 8 +26
Tests 1 124 0 +124
Docs 1 3 1 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 161 9 +152

Labels

Label changes:

  • add P2: This is a bounded maintenance performance improvement with a deterministic implementation defect and matching CI failure.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: This is a bounded maintenance performance improvement with a deterministic implementation defect and matching CI failure.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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 execution lanes are retired.

Reviewed October 15, 2026, 5:31 AM ET / 09:31 UTC.

@steipete steipete changed the title improve(sessions): avoid unnecessary retention candidate reads perf(sessions): narrow retention reads and batch automatic capacity cleanup Oct 15, 2026
@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: L and removed size: S labels Oct 15, 2026
@steipete
steipete merged commit 2ff5d6f into main Oct 15, 2026
161 checks passed
@steipete
steipete deleted the dbasync/maintscale branch October 15, 2026 12:10
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant