Skip to content

perf(state): retain reclamation workers across database switches - #155677

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-reclamation-worker-open-all-paths-20260919
Sep 22, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-reclamation-worker-open-all-paths-20260919

Conversation

@steipete

@steipete steipete commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Maintenance that alternates between agent databases repeatedly closes and boots reclamation Workers because the retained Worker slot is global.

Related: #154662.

User Impact

Multi-agent maintenance reuses each database's admitted Worker, reducing repeated startup work. One recently used Worker can remain per database instead of one globally; the existing 30-minute idle expiry, critical-memory retirement, and database-close drainage still apply. No configuration, schema, durability, integrity policy, or update behavior changes.

Why This Change Was Made

Retain Workers by canonical database path while preserving the global archive FIFO and existing file, state-owner, and request-authority checks. Remove a registry entry only after successful retirement and only if it still identifies that Worker; failed cleanup retains custody. Canonical-validation scopes remain separate. Net production change: +28 lines.

The maintenance opens already execute inside withWorkerWriteAdmission, and their nested synchronous opens reuse the admitted connection. Archive read-only opens check schema and ownership without a full integrity scan. The measured defect is cross-database Worker churn, so this change does not add another admission helper.

Evidence

A disposable Testbox probe used two synthetic SQLite databases of 1,077,166,080 bytes each, with current host verification, and alternated maintenance-plan, maintenance-pages, and maintenance-statistics operations.

Measurement Before After
10 alternating operations, total 7,457.5 ms 1,074.9 ms
Workers spawned / 10 alternating operations 10 2
Mean native setup-to-lease report per physical open 24.7 ms 17.8 ms
Full integrity scans / verified operation 0 0
Workers spawned / 10 same-database operations 1 1
Full scans after proof revocation, fresh Worker 1 1
Revoked-proof open / integrity scan 179.7 / 133.1 ms 163.7 / 121.9 ms

Observed alternating-workload time fell 85.6%; timings are samples, not a production latency guarantee. The deterministic improvement is eight fewer Worker starts and physical opens. Warm requests need no physical reopen. The open timer excludes module bootstrap.

The new regression failed on the original implementation with six Workers instead of two, and passes with the fix. It also checks host-proof reuse and retirement of all idle Workers on critical memory pressure. Existing coverage retains revoked-proof checks, current admission, FIFO settlement, idle expiry, and crashed-Worker lease cleanup.

CI also exposed a sibling diagnostic test that still required three Worker IDs for requests spanning two databases. Its assertions now require the two same-database requests to share an ID and the other database to use a different ID. Separately, the embeddings HTTP cleanup fixture had a one-second polling deadline and left its cleanup gate closed on failure, poisoning later tests. Those equivalent cases now use an explicit cleanup-entry signal and settle requests/provider lifetimes in finally; the test file shrinks by 15 lines, with no production embedding changes or timeout increases.

All heavy validation used blacksmith-testbox, profile openclaw-check:

  • Benchmark/regression lease tbx_01m348hrxbqftrnyyggyv778gp: node scripts/run-vitest.mjs src/config/sessions/session-accessor.sqlite-lane105.bench.test.ts src/config/sessions/session-accessor.sqlite-reclamation-reuse.test.ts passed 22 baseline tests. The disposable probe passed again on the candidate with the measurements above. node scripts/run-vitest.mjs src/config/sessions/session-accessor.sqlite-reclamation-reuse.test.ts -t 'retains maintenance Workers' failed on the original implementation as expected (six Workers, expected two).
  • Behavioral validation lease tbx_01m3494a5c7c3fxz0td4bp485m: pnpm test src/config/sessions/session-accessor.sqlite-reclamation-reuse.test.ts --maxWorkers=1 passed all 22 tests, 56.93 s wrapper wall time including cold Worker compilation; the new regression took 1.613 s. node scripts/run-vitest.mjs with the sibling session-accessor.sqlite-reclamation-{worker,admission-race,memory,wal}.test.ts files passed all 16 tests and its required runtime build (75 s). These native Worker tests protect admission, lease settlement, and thread reuse that an in-process mock cannot establish.
  • Static validation lease tbx_01m34a1s575sxq7z036k9tysc3: node scripts/check-changed.mjs --base HEAD -- docs/reference/database-schemas/integrity-and-recovery.md src/config/sessions/session-accessor.sqlite-reclamation-reuse.test.ts src/config/sessions/session-accessor.sqlite-reclamation-worker.ts passed, exit 0. The command completed in 34m21s including remote setup and all 25 core-test typecheck shards; core typechecking, changed-file lint, formatting, dead-export scans, and selected storage/plugin guards passed.
  • CI follow-up lease tbx_01m34cz4rp408azvdnckhhmafz: pnpm test src/config/sessions/session-accessor.sqlite-reclamation.test.ts src/config/sessions/session-accessor.sqlite-reclamation-reuse.test.ts --maxWorkers=1 passed all 56 tests in 123.61 s wrapper wall time. The corrected queued-identity case took 1.669 s. Its test-only changed checks passed. The original 12-file agentic-control-plane-http-models shard was replayed with its recorded two-worker input descriptor through scripts/ci-run-node-test-shard.mts and passed 429 tests in 240.42 s before the embeddings fixture repair; that passing replay is not claimed as proof of a fix.
  • On that same follow-up lease, 20/20 standalone pnpm test src/gateway/embeddings-http.test.ts --maxWorkers=1 runs passed all 43 tests each (137 s cold wrapper wall; 45–92 s subsequent runs). 3/3 original-shard replays passed all 429 tests each (223.68, 187.98, and 188.54 s Vitest wall). These tests exercise real HTTP request selection, local-provider admission, disconnects, and cleanup through a suite-level Gateway. No new Gateway boot per case was added. Final node scripts/check-changed.mjs --base HEAD -- src/config/sessions/session-accessor.sqlite-reclamation.test.ts src/gateway/embeddings-http.test.ts passed both affected typecheck graphs, lint, and selected guards. The combined repetition/check command exited 0 in 36m6s. All four task-owned leases were stopped.

Independent review through P2: scoped-clean for the production change and both CI corrections. Local changed-file formatting and git diff --check passed. No local test, build, or typecheck execution.

CI run 35725516661 passed for 7278894c5d847a605cd7bdbd062631f4b71cac51, including both previously failing jobs. The queued Worker-identity regression took 0.948 s in CI. The four embedding cleanup cases took 0.517–0.644 s each; their original 12-file HTTP group passed 429 tests in 123.49 s. The containing packed jobs took 385 s and 628 s including setup and other groups.

Validation recovery and scope

The first test invocation stopped before tests because remote dependencies were missing; pnpm install --frozen-lockfile succeeded on each isolated lease. The first candidate reuse-suite run was interrupted after the benchmark succeeded because the adapted explicit-retirement fixture called an unwrapped close function while awaiting its wrapper notification. Correcting that fixture produced the clean 22-test result above. The default node scripts/check-changed.mjs run selected unrelated changes from shallow origin/main history, so it was stopped and replaced by the fixed-base, explicit-path invocation. No production change was needed for either validation issue. The disposable large-database probe is not added to per-PR CI.

The first PR CI run, 35718735185, failed the two test assumptions described above; the other selected jobs passed. The follow-up preserves the queued identity check, replaces cleanup-entry polling with an actual callback signal, and settles cleanup even when an assertion fails.

The reported 24-second production scans and eight maintenance-plan rejections were not reproduced. Source inspection identifies stale maintenance input after a foreground write as a possible rejection path, but the supplied log excerpt omits error and errorFrame; no cause is asserted and no authority check or retry policy is weakened. No live Gateway was changed.

Reuse each database worker across alternating maintenance operations while preserving the global archive FIFO, existing admission, idle retirement, and failed-close custody. Keep the worker registry bound to successful lifecycle retirement.
@clawsweeper

clawsweeper Bot commented Sep 22, 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 docs Improvements or additions to documentation size: S maintainer Maintainer-authored PR labels Sep 22, 2026
@clawsweeper clawsweeper Bot added 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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 22, 2026
@clawsweeper

clawsweeper Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 22, 2026, 8:36 AM ET / 12:36 UTC (Revision 3).

ClawSweeper review

What this changes

Retain a database-cleanup worker for each agent database, document retirement behavior, and update worker-reuse and embeddings-cleanup tests.

Merge readiness

✅ Ready for maintainer review

This remains a useful, well-supported optimization: inspected main and the latest release still retain only one reclamation worker globally. No blocking correctness findings remain.

Priority: P2
Reviewed head: 7278894c5d847a605cd7bdbd062631f4b71cac51

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused implementation with convincing real-worker measurements, meaningful lifecycle coverage, and no blocking findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The captured Testbox observations exercise the changed reclamation owner with real workers and two large SQLite databases, showing fewer starts after alternating maintenance while retaining revoked-proof controls. Regression and exact-head CI results supplement that evidence. No stored-data contract changes require migration proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured Testbox observations exercise the changed reclamation owner with real workers and two large SQLite databases, showing fewer starts after alternating maintenance while retaining revoked-proof controls. Regression and exact-head CI results supplement that evidence. No stored-data contract changes require migration proof.
Evidence reviewed 9 items Reviewed introduction: Reviewed the pinned merge-base-to-head changes. Production edits are confined to the reclamation worker owner; the remaining edits concern documentation and tests. Endpoint drift and the stale test merge were not treated as PR-owned changes.
Still necessary on main: Fetched main retains a single global slot and closes its worker when another database's options or identity do not match. Alternating database requests therefore still cause worker churn.
Latest release comparison: The same worker owner in v2026.9.5 also uses a single global slot and closes mismatched workers; the per-database optimization is not present there. GitHub contents inspection supplied the release blob after local historical-blob retrieval failed.
Findings None None.
Security None None.

How this fits together

Session reclamation performs database maintenance and removes obsolete session data in background workers. Requests enter a shared queue, obtain current database authority, and return committed results before their worker becomes idle.

flowchart TD
  A[Session cleanup and maintenance] --> B[Shared request queue]
  B --> C[Worker registry by database]
  C --> D[Current identity and write admission]
  D --> E[SQLite operation and committed result]
  E --> C
  C --> F[Idle expiry or lifecycle retirement]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +28, Tests +22, Docs +5. Total +55 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 1 37 9 +28
Tests 3 119 97 +22
Docs 1 5 0 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 161 106 +55

Review metrics

Metric Value Why it matters
Measured worker reuse 10 → 2 starts across 10 alternating operations The supplied real-worker probe demonstrates avoided startup work without relying solely on timing.
Production versus test growth production +28 net lines; tests +22 net lines Production growth is justified by per-database retention and identity-checked retirement within the existing owner.

Technical review

Best possible solution:

Keep worker reuse within the existing reclamation owner, preserving per-request authority, global ordering, and complete lifecycle retirement.

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

Yes: alternating maintenance between two databases reaches main's single-slot replacement path; the supplied Testbox comparison independently demonstrates the churn. This reviewer did not execute the workload.

Is this the best way to solve the issue?

Yes: extending the existing worker owner's retention registry removes the measured churn while preserving admission, commit, queue, and cleanup contracts.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded database-maintenance performance improvement with measured benefit on alternating-agent workloads.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The captured Testbox observations exercise the changed reclamation owner with real workers and two large SQLite databases, showing fewer starts after alternating maintenance while retaining revoked-proof controls. Regression and exact-head CI results supplement that evidence. No stored-data contract changes require migration proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured Testbox observations exercise the changed reclamation owner with real workers and two large SQLite databases, showing fewer starts after alternating maintenance while retaining revoked-proof controls. Regression and exact-head CI results supplement that evidence. No stored-data contract changes require migration proof.

Evidence

What I checked:

  • Reviewed introduction: Reviewed the pinned merge-base-to-head changes. Production edits are confined to the reclamation worker owner; the remaining edits concern documentation and tests. Endpoint drift and the stale test merge were not treated as PR-owned changes. (src/config/sessions/session-accessor.sqlite-reclamation-worker.ts:103, 7278894c5d84)
  • Still necessary on main: Fetched main retains a single global slot and closes its worker when another database's options or identity do not match. Alternating database requests therefore still cause worker churn. (src/config/sessions/session-accessor.sqlite-reclamation-worker.ts:103, 774687378d80)
  • Latest release comparison: The same worker owner in v2026.9.5 also uses a single global slot and closes mismatched workers; the per-database optimization is not present there. GitHub contents inspection supplied the release blob after local historical-blob retrieval failed. (src/config/sessions/session-accessor.sqlite-reclamation-worker.ts, ec9c1a13db89)
  • Lifecycle and authority preserved: Registry selection remains inside the global FIFO. Reuse checks options, physical identity, state context, and revocation; admission and commit checks remain request-specific. Successful retirement removes only the matching registry entry, while failed cleanup retains custody. No stored format, schema, permission, dependency, or plugin API changes are introduced. (src/config/sessions/session-accessor.sqlite-reclamation-worker.ts:128, 7278894c5d84)
  • Real worker proof and explicit resource tradeoff: The captured PR body reports a disposable Testbox probe using two 1,077,166,080-byte synthetic databases through maintenance-plan, maintenance-pages, and maintenance-statistics. Ten alternating operations spawned 10 workers before and 2 afterward; measured total time fell from 7,457.5 ms to 1,074.9 ms. Same-database and revoked-proof controls were retained. The body explicitly accepts one recently used worker per database with existing idle expiry, memory-pressure retirement, and database-close drainage. These are supplied observations, not reviewer-executed measurements; the unrelated reported 24-second scans remain outside the proven claim. (6504351b3b5d)
  • Regression and fixture coverage: The added regression exercises real worker reuse across alternating databases and retires both idle workers under critical memory pressure. Existing tests cover revoked admission, commit rejection, expiry, crashed-worker cleanup, and failed-close custody. Embeddings changes replace cleanup-entry polling with a callback signal and settle requests before restoring shared fixture state; production embeddings behavior is unchanged. (src/config/sessions/session-accessor.sqlite-reclamation-reuse.test.ts:637, 7278894c5d84)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; 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 (2 earlier review cycles)
  • reviewed 2026-09-22T11:01:24.503Z sha 6504351 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-22T12:17:43.770Z sha 7278894 :: needs maintainer review before merge. :: none

Assert queued reclamations share their database worker and preserve other-store identity. Replace polling in embedding cleanup fixtures with entry signals and settle started requests and provider lifetimes before restoring transport.
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M and removed size: S labels Sep 22, 2026
@steipete
steipete merged commit 9c7324e into main Sep 22, 2026
202 checks passed
@steipete
steipete deleted the steipete/perf-micro-reclamation-worker-open-all-paths-20260919 branch September 22, 2026 12:40
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 23, 2026
…nclaw#155677)

* perf(state): retain reclamation workers across database switches

Reuse each database worker across alternating maintenance operations while preserving the global archive FIFO, existing admission, idle retirement, and failed-close custody. Keep the worker registry bound to successful lifecycle retirement.

* perf(state): finish worker reuse and cleanup regression coverage

Assert queued reclamations share their database worker and preserve other-store identity. Replace polling in embedding cleanup fixtures with entry signals and settle started requests and provider lifetimes before restoring transport.
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 gateway Gateway runtime maintainer Maintainer-authored PR 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. size: M 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