Skip to content

refactor(sessions): move cold maintenance selection into workers - #163200

Merged
steipete merged 3 commits into
mainfrom
dbasync/s21
Oct 2, 2026
Merged

steipete merged 3 commits into
mainfrom
dbasync/s21

Conversation

@steipete

@steipete steipete commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Enabled cold-storage maintenance runs every 60 seconds and through sessions.storage.run. Candidate selection, protection scans, target discovery, and cold mutation opening could execute SQLite on the Gateway thread.

Related: #163041.

Why This Change Was Made

Extend the existing cold-prepare archive-worker operation to select candidates from captured admission identities and cooldowns. The host keeps live admissions and single-flight scheduling; the worker owns stored references and deletion snapshots. Mutation rechecks both stored ownership and the host's current authority before committing.

Prepare configured targets through the existing inventory/registry readers. Preserve logical admission scopes and lexical SQLite locators for archive files and restore cooldowns. Ordinary maintenance opens its database through the existing agent execution owner. Registry snapshots guard discovery; physical source and execution claims guard writes, including integrity-triggered re-registration.

User Impact

Cold-storage maintenance moves SQLite selection off the Gateway thread while retaining existing archive ordering, budgets, and admission protections.

  • Cold-storage owner T1 sites: 6 → 1. Including the unchanged shared deletion-snapshot and eviction-candidate kernels: 13 → 8.
  • The real maintenance boundary's baseline control executed 64 parent-thread SQLite operations; the new boundary tests require zero across all eight observed primitives.
  • Production delta: +393 / -192 / net +201 LOC. The remaining direct native metadata read is unchanged incognito restoration; existing restore/native-maintenance ownership stays outside this timer-selection cutover.
  • Candidate ordering, the 128-transcript/64-MiB budgets, round-robin loop, restore/oversize cooldowns, and timer single-flight ownership are retained. No broker core changes or new worker dispatch mechanism.

Evidence

Coordinator-reviewed head: 19c648991c6e0e54d3f88fff51815cf42667504d, after merging d4b98b3a5101349febc02ae14b828f689f7b8538 from main without conflicts.

All 72 focused tests passed on that head. Serial local invocations used OPENCLAW_VITEST_NO_OUTPUT_TIMEOUT_MS=1800000 and /usr/bin/time -p; wall times include the pnpm wrapper and compiled-worker preparation:

Command Result Wall time
pnpm test src/config/sessions/session-cold-storage.test.ts --maxWorkers=1 23 passed 199.19 s
pnpm test src/config/sessions/session-cold-storage.selection.test.ts --maxWorkers=1 5 passed 54.15 s
pnpm test src/config/sessions/session-cold-storage.admission.test.ts src/config/sessions/session-cold-storage-eligibility.test.ts src/config/sessions/session-cold-storage.preflight.test.ts src/config/sessions/session-cold-storage.publication.test.ts src/gateway/session-cold-storage-maintenance.test.ts --maxWorkers=1 44 passed (including 7 timer tests) 50.61 s

The selection tests exercise real worker boundaries and use deferred gates for ordering; no sleeps or timer polling were added. The original tests exposed the defects described below and were repaired before this final run.

Testbox did not execute the test commands: its assigned job was canceled before any steps while the provider kept reporting the lease as queued. The lease is confirmed completed; the final proof above comes from the supported local fallback.

  • node scripts/worktree-setup.mjs gateway: passed on the merged head (build 8m28.9s; dependency setup 23.7s).
  • node scripts/check-changed.mjs -- scripts/database-worker-inventory.mjs src/config/sessions/session-cold-storage.ts src/config/sessions/session-cold-storage-worker.ts src/config/sessions/session-cold-storage-selection.ts src/config/sessions/session-cold-storage.selection.test.ts src/config/sessions/session-cold-storage.test.ts: passed, exit 0. This includes core and all core-test type-check shards, touched-file lint/formatting, dead-export scans, runtime cycle checks, and selected repository guards.
  • pnpm check:database-worker-ratchet --base 786a6b56e8c8b7f2b9b0bf154db179c3e833efd2: passed.
  • pnpm check:madge-import-cycles: passed, zero cycles.
  • node scripts/database-worker-inventory.mjs --json: measured the original base and candidate; owner T1 6→1. The new selection kernel contributes 3 worker-tier calls; cold worker calls 18→19.
  • Codex autoreview, branch mode against the final merge base, high reasoning, P0–P2: scoped-clean, no accepted/actionable findings. The original pinned-base review also passed before merging main.

PR CI on 19c648991c6e0e54d3f88fff51815cf42667504d ran and passed the cold-storage suites: core 23 tests (48.65 s), selection 5 (8.11 s), admission 1 (5.26 s), eligibility 16 (0.73 s), preflight 13 (2.51 s), publication 7 (2.69 s), lifecycle 18 (14.36 s), and backup 6 (18.10 s). See CI run 36958544766.

Landing correction 37738d8e09fee92acc612e13eb272d04ed7cd2eb moves the existing raw-SQLite allowance comment directly above its freelist PRAGMA call. The extraction had separated them, causing lint:kysely to fail; executable code is unchanged. The failure reproduced locally, and the corrected Kysely guard passed. The five selection tests passed again (99.48 s wall, including worker preparation); independent Codex review of the correction found no actionable P0–P2 issues. Exact-head CI run 36959614441 passed, including the previously failing architecture guard. Its logs confirm all 65 focused cold-storage tests: core 23 (50.34 s), selection 5 (9.16 s), admission 1 (4.81 s), eligibility 16 (0.658 s), preflight 13 (2.60 s), and publication 7 (2.52 s). Additional lifecycle, inventory, read, synchronous-write, transcript-turn, and backup suites also passed. The unchanged seven Gateway timer tests retain the prior local proof; this CI run did not select that file. The initial PR context check also rejected the problem heading; the body now uses the required template headings.

The baseline control ran the new logical-admission boundary test with the two original cold-storage implementation files from 786a6b56e8c8b7f2b9b0bf154db179c3e833efd2; it failed only the zero-SQLite assertion (29 prepares, 20 gets, 7 iterates, 4 alls, 2 opens, 1 exec, 1 close). The final tests additionally cover delayed admissions, unrelated work, configuration revocation, worker rejection, lexical file aliases, and embedded-archive ownership changes.

The broader local run exposed a real discovery/writer lifetime error during forced integrity verification: re-registration invalidated the discovery memo. The fix limits that witness to discovery and retains live source/execution guards for writes. Tests still prove rollback and exact archive-worker exit, while permitting the separately owned shared actor to remain idle.

Worker classification trace: session-accessor.sqlite-archive.worker.ts dispatches cold-prepare to prepareSessionColdBatchInWorker, which calls the new selection kernel and admission-key reader. cold-mutate reaches mutateSessionColdTranscriptInWorker through the existing mutation-worker port and calls the same admission-key reader inside its transaction. These are the only production callers of the new module's SQL functions; no existing mixed kernel was reclassified.

Compatibility retained

No public SDK contract changed. The private SessionColdBatchInput type moved from the archive-worker module to the selection kernel; no runtime function export was deleted. The synchronous host selection, existence probe, and protection closures were removed. The shared snapshot/reference kernels still serve their other callers. Existing incognito, restore, and explicit Doctor/maintenance native ownership is retained.

Update behavior

No schema, stored-byte format, retention, durability, configuration, or permission changes. Existing installations and updater/Doctor behavior are unchanged.

Overlapping open PRs

#157922 replaces the archive-size constant in prepareSessionColdBatchInWorker and decodeSessionColdRecords for usage date filtering. Its goal is independent; this change leaves those constants intact.

Keep live work admissions and cooldowns on the host while selecting and rechecking stored protection in the archive worker. Retain logical admission scopes and lexical artifact paths, and use the existing execution owner for ordinary cold maintenance opening. No schema, retention, configuration, or update behavior changes.
@clawsweeper

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

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: L labels Oct 2, 2026
@steipete

steipete commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 1, 2026, 11:34 PM ET / October 2, 2026, 03:34 UTC (Revision 4).

ClawSweeper review

What this changes

The branch moves cold-transcript discovery, candidate selection, and protection reads into existing database workers while retaining host scheduling and live commit checks.

Merge readiness

✅ Ready for maintainer review

This remains a useful landing candidate: current main still performs cold-maintenance selection on the Gateway thread. No introduced correctness or security defect was found, and the production-boundary evidence covers selection, revocation, rollback, and archive preservation.

Priority: P2
Reviewed head: 37738d8e09fee92acc612e13eb272d04ed7cd2eb

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused worker cutover with meaningful boundary and rollback evidence and no actionable introduced findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): Reported production-boundary runs invoke cold maintenance against real SQLite files and actual archive-worker messaging, showing zero parent-thread SQL, successful archival, and persisted rollback after authority retirement or ownership reassignment. The inspected harness delegates transport to production code rather than mocking it. Stored formats remain unchanged, with existing archive/reopen coverage retained.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): Reported production-boundary runs invoke cold maintenance against real SQLite files and actual archive-worker messaging, showing zero parent-thread SQL, successful archival, and persisted rollback after authority retirement or ownership reassignment. The inspected harness delegates transport to production code rather than mocking it. Stored formats remain unchanged, with existing archive/reopen coverage retained.
Evidence reviewed 8 items Introduced scope: Reviewed the pinned merge-base-to-head change, rather than endpoint drift. The introduced work concerns cold maintenance and its worker classification; unrelated base-branch changes were excluded.
Still necessary on current main: Fetched main retains host-side candidate queries, protection scans, and native mutation opening. The merged inventory/restore work did not move timer selection, so it does not supersede this change.
Worker-only selection boundary: The selection kernel retains candidate ordering, admission exclusions, cooldowns, and deletion snapshots. Reference tracing found its SQL functions called only by the existing cold preparation and mutation worker owner; the inventory classification matches that boundary.
Findings None None.
Security None None.

How this fits together

Cold storage moves inactive session transcripts from SQLite into compressed archives. Gateway timers and storage requests initiate maintenance; database workers prepare archives and commit changes while the host checks current admissions and configuration.

flowchart TD
  A[Timer or storage request] --> B[Host maintenance scheduler]
  B --> C[Worker store discovery]
  C --> D[Worker candidate selection]
  D --> E[Archive preparation]
  E --> F[Stored ownership and live authority checks]
  F --> G[Commit archive or retain transcript]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +201, Tests +261, Other +1. Total +463 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 3 393 192 +201
Tests 2 274 13 +261
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 6 668 205 +463

Review metrics

Metric Value Why it matters
Production versus test growth production net +201 LOC; tests net +261 LOC; tooling +1 LOC Production growth is justified by worker discovery and retained authority checks replacing synchronous host selection.
Parent-thread SQLite reported baseline 64 operations; after-fix 0 across 8 primitives The boundary harness measures the operational problem this cutover addresses.

Technical review

Best possible solution:

Keep cold-maintenance SQL behind the existing worker owners while preserving host admissions, archive compatibility, and transaction-time protection.

Do we have a high-confidence way to reproduce the issue?

Yes, source establishes the current-main host-side SQLite path, and the supplied baseline control exercises the real maintenance boundary; this reviewer did not execute it.

Is this the best way to solve the issue?

Yes, extending the existing archive and discovery workers removes the synchronous work without adding a competing scheduler, storage format, or public API.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. Reported production-boundary runs invoke cold maintenance against real SQLite files and actual archive-worker messaging, showing zero parent-thread SQL, successful archival, and persisted rollback after authority retirement or ownership reassignment. The inspected harness delegates transport to production code rather than mocking it. Stored formats remain unchanged, with existing archive/reopen coverage retained.

Label justifications:

  • P2: This is a bounded runtime responsiveness improvement to opt-in cold-storage maintenance.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): Reported production-boundary runs invoke cold maintenance against real SQLite files and actual archive-worker messaging, showing zero parent-thread SQL, successful archival, and persisted rollback after authority retirement or ownership reassignment. The inspected harness delegates transport to production code rather than mocking it. Stored formats remain unchanged, with existing archive/reopen coverage retained.
  • proof: sufficient: Contributor real behavior proof is sufficient. Reported production-boundary runs invoke cold maintenance against real SQLite files and actual archive-worker messaging, showing zero parent-thread SQL, successful archival, and persisted rollback after authority retirement or ownership reassignment. The inspected harness delegates transport to production code rather than mocking it. Stored formats remain unchanged, with existing archive/reopen coverage retained.

Evidence

What I checked:

  • Introduced scope: Reviewed the pinned merge-base-to-head change, rather than endpoint drift. The introduced work concerns cold maintenance and its worker classification; unrelated base-branch changes were excluded. (src/config/sessions/session-cold-storage.ts:95, 37738d8e09fe)
  • Still necessary on current main: Fetched main retains host-side candidate queries, protection scans, and native mutation opening. The merged inventory/restore work did not move timer selection, so it does not supersede this change. (src/config/sessions/session-cold-storage.ts:208, f2b72224a65f)
  • Worker-only selection boundary: The selection kernel retains candidate ordering, admission exclusions, cooldowns, and deletion snapshots. Reference tracing found its SQL functions called only by the existing cold preparation and mutation worker owner; the inventory classification matches that boundary. (src/config/sessions/session-cold-storage-selection.ts:30, 37738d8e09fe)
  • Final commit authority: The host retains an execution-generation claim and checks it alongside request authority and live admissions. The mutation transaction rejects newly introduced protection keys, rechecks snapshots, and waits for the existing host commit grant before committing. (src/config/sessions/session-cold-storage-worker.ts:494, 37738d8e09fe)
  • Production-boundary fault evidence: Inspected the real maintenance entrypoint harness: spies delegate to actual archive workers and native SQLite. Cases cover allowed unrelated admissions, blocked newly active logical owners, configuration revocation, worker rejection, and reassigned embedded-archive ownership. Commit-time authority/database retirement cases assert unchanged persisted snapshots, no archive rows, and exact archive-worker exit. The captured body reports passing runs and a baseline control with 64 parent-thread SQLite operations versus zero after the change. (src/config/sessions/session-cold-storage.selection.test.ts:89, 37738d8e09fe)
  • Compatibility retained: The diff changes execution ownership without changing schema, archive encoding, retention settings, or public SDK contracts. Existing-state coverage exercises embedded archives, exact restoration after reopening, cooldowns, aggregate budgets, and integrity-triggered reopening. (src/config/sessions/session-cold-storage.test.ts:296, 37738d8e09fe)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (3 earlier review cycles)
  • reviewed 2026-10-02T03:08:49.089Z sha 19c6489 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-02T03:16:20.094Z sha 19c6489 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-02T03:23:39.878Z sha 37738d8 :: needs maintainer review before merge. :: none

@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 2, 2026
@steipete

steipete commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete
steipete merged commit 418ec9b into main Oct 2, 2026
134 of 136 checks passed
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Oct 2, 2026
@steipete
steipete deleted the dbasync/s21 branch October 2, 2026 03:35
@steipete

steipete commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
…nclaw#163200)

* refactor(sessions): move cold selection and protection to workers

Keep live work admissions and cooldowns on the host while selecting and rechecking stored protection in the archive worker. Retain logical admission scopes and lexical artifact paths, and use the existing execution owner for ordinary cold maintenance opening. No schema, retention, configuration, or update behavior changes.

* fix(sessions): retain freelist pragma guard annotation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant