Repository navigation
perf(state): switching between agents reopens agent database executors on every request - #165993
Conversation
Keep an owner-local LRU of four idle physical-agent executors with independent idle timers, cleanup custody, and shutdown drainage. Retire affected executors when committed configuration removes or renames their agent ID or changes a storage locator. Keep display-only and unrelated config changes warm. Alternating sessions.create calls previously reopened the executor on every agent switch. The six-create baseline opened six workers with p50 715 ms and p95 854 ms. Deterministic owner tests reproduce six opens on the original code and verify two with retention, alongside eviction, expiry, aliases, config invalidation, shutdown, and failed-close custody. No schema, stored data, public configuration, or update contract changes.
|
🦞👀 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: needs maintainer review before merge. Reviewed October 6, 2026, 9:34 PM ET / October 7, 2026, 01:34 UTC (Revision 6). ClawSweeper reviewWhat this changesRetains up to four idle agent database workers to reduce delays when switching agents, with independent expiry, eviction, configuration cleanup, and supporting tests and documentation. Merge readiness✅ Ready for maintainer review This PR remains useful: current main still retains only one idle executor. The prior wrapper-inventory finding is resolved, and the latest fixture-only repair introduces no blocking finding. The accepted memory tradeoff remains unchanged. Priority: P2 Review scores
Verification
How this fits togetherAgent database workers execute storage operations requested by session creation and other Gateway workflows. The execution owner controls worker reuse, admission, and cleanup before returning results to callers. flowchart TD
A[Session and agent requests] --> B[Database execution owner]
B --> C[Current admission checks]
C --> D[Reuse or open worker]
D --> E[Agent SQLite database]
E --> F[Return operation result]
F --> G[Bounded idle worker pool]
G --> D
H[Expiry configuration changes and shutdown] --> G
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +39, Tests +294, Docs +2, Other +1. Total +336 across 6 files. View PR surface stats
Review metrics
Technical reviewBest possible solution: Keep bounded worker reuse under the existing execution owner, preserving per-operation admission and complete lifecycle cleanup. Do we have a high-confidence way to reproduce the issue? Yes: alternating session creation between agents exercises the single-idle-worker churn shown in current main and the supplied live baseline. This review inspected source and recorded evidence without executing the workload. Is this the best way to solve the issue? Yes: bounded reuse repairs the existing execution owner while preserving admission and cleanup contracts; the latest assertions safely repair fixture typing without weakening coverage. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against c3c55eadb1c8. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (5 earlier review cycles)
|
Merge pinned main d20a281 into the published warm-executor branch without rewriting its history. Retain the current file execution owner, worker admission and validation receipts, creation witness, and creating-borrower accounting. Keep four idle physical-agent executors with independent expiry and lifecycle retirement; evict only idle owners in least-recently-used order. Cover shared creators under eviction pressure and readmission of revoked proof and missing indexes through the same idle native generation. Proof: 203 owner tests passed across 13 files (one Linux-only skip), focused final idle and worker-admission tests passed, core types and scoped lint/format passed, and Madge found no cycles. The main negative control opens six executors for six alternating borrows versus two. Direct sessions.create p50/p95 measured 756/1027 ms on main versus 48/685 ms with retention. Marginal idle RSS measured about 110 MiB per extra executor; maintainer memory sign-off remains pending.
|
@clawsweeper approve |
|
🦞👀 Command router queued. I will update this comment with the next step. |
The extracted PR-tooling wrapper closure requires every runtime source module; add src/state/openclaw-agent-execution-config.ts so wrapper source-closure checks resolve it.
|
@clawsweeper re-review Please review exact head f4493cc. The configuration watcher is now included in scripts/pr-lib/wrapper-components.txt; the focused wrapper source-closure and eager-import-closure tests passed 20/20. The existing maintainer approval for four warm idle executors and its measured memory cost remains in force. |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
…s on every request (openclaw#165993) * fix(state): retain four warm agent database executors Keep an owner-local LRU of four idle physical-agent executors with independent idle timers, cleanup custody, and shutdown drainage. Retire affected executors when committed configuration removes or renames their agent ID or changes a storage locator. Keep display-only and unrelated config changes warm. Alternating sessions.create calls previously reopened the executor on every agent switch. The six-create baseline opened six workers with p50 715 ms and p95 854 ms. Deterministic owner tests reproduce six opens on the original code and verify two with retention, alongside eviction, expiry, aliases, config invalidation, shutdown, and failed-close custody. No schema, stored data, public configuration, or update contract changes. * fix(state): list warm executor config module in the PR wrapper inventory The extracted PR-tooling wrapper closure requires every runtime source module; add src/state/openclaw-agent-execution-config.ts so wrapper source-closure checks resolve it. * test(state): assert warm executor fixture entries exist
Retire warm-cache eligibility when configuration changes, then drain the physical executor after its last borrower settles. Config retirement from #165993 revoked acknowledged work; the fresh-borrower repair in b798788 still fenced captured borrowers through a configuration epoch. Remove that epoch fence while preserving physical identity, explicit revocation, native admission recovery, and exact cleanup ownership. Released references cannot select a current generation for refusal cleanup. Keep new routing in the configuration owner and retain the original store for admitted work. Schemas, stored bytes, and update behavior remain unchanged. Cover last-borrower drainage, released-reference successor safety, and a configuration change after a real native open. Both lifetime regressions fail on current main; the native-open control fails at assertConfigCurrent. Validation: all 544 selected tests pass across 31 files on isolated Linux, including all 23 reported Gateway cases, owner siblings, and the suppression guard. Full changed-file checks pass, including all core/test type graphs, lint, repository guards, and zero runtime value cycles. The loaded macOS parallel run hit readiness/timeouts and fixture cleanup recursion; the same cases pass unchanged on Linux. No timeouts, retries, or suppressions changed.
…se on main (#166529) * test(worker): stop chat.abort cases inheriting a pinned runtime config Each chat.abort case captured the runtime config snapshot only after ComposedGatewayHarness.create had run Gateway session storage work, which pins the ambient test-home config through getRuntimeConfig. The case then "restored" that pinned config, so every later case started with it. Since #165993, agent database executors watch the runtime config's store locator. In case 2+, the Gateway executor for the harness agent database captured the inherited test-home locator, and the case's setRuntimeConfigSnapshot(harness.cfg) retired it. The in-process simulated worker had already replaced process.env.OPENCLAW_STATE_DIR, so the Gateway live-event trajectory recorder reopened that database under the worker's shared-state database and the executor stayed warm. Gateway transcript commits were then refused ("belongs to another shared-state database"), the worker reconnected and retried about a thousand times, and never reached the provider before the cancellation-boundary timeout. Capture the snapshot before the harness exists and restore it after harness.close(), so each case starts from the same state as the first. * test(worker): restore the runtime config even when harness cleanup fails
Retire warm-cache eligibility when configuration changes, then drain the physical executor after its last borrower settles. Config retirement from openclaw#165993 revoked acknowledged work; the fresh-borrower repair in e922159 still fenced captured borrowers through a configuration epoch. Remove that epoch fence while preserving physical identity, explicit revocation, native admission recovery, and exact cleanup ownership. Released references cannot select a current generation for refusal cleanup. Keep new routing in the configuration owner and retain the original store for admitted work. Schemas, stored bytes, and update behavior remain unchanged. Cover last-borrower drainage, released-reference successor safety, and a configuration change after a real native open. Both lifetime regressions fail on current main; the native-open control fails at assertConfigCurrent. Validation: all 544 selected tests pass across 31 files on isolated Linux, including all 23 reported Gateway cases, owner siblings, and the suppression guard. Full changed-file checks pass, including all core/test type graphs, lint, repository guards, and zero runtime value cycles. The loaded macOS parallel run hit readiness/timeouts and fixture cleanup recursion; the same cases pass unchanged on Linux. No timeouts, retries, or suppressions changed.
…se on main (openclaw#166529) * test(worker): stop chat.abort cases inheriting a pinned runtime config Each chat.abort case captured the runtime config snapshot only after ComposedGatewayHarness.create had run Gateway session storage work, which pins the ambient test-home config through getRuntimeConfig. The case then "restored" that pinned config, so every later case started with it. Since openclaw#165993, agent database executors watch the runtime config's store locator. In case 2+, the Gateway executor for the harness agent database captured the inherited test-home locator, and the case's setRuntimeConfigSnapshot(harness.cfg) retired it. The in-process simulated worker had already replaced process.env.OPENCLAW_STATE_DIR, so the Gateway live-event trajectory recorder reopened that database under the worker's shared-state database and the executor stayed warm. Gateway transcript commits were then refused ("belongs to another shared-state database"), the worker reconnected and retried about a thousand times, and never reached the provider before the cancellation-boundary timeout. Capture the snapshot before the harness exists and restore it after harness.close(), so each case starts from the same state as the first. * test(worker): restore the runtime config even when harness cleanup fails
What Problem This Solves
Fixes: creating sessions or running turns for different agents back to back is slow. The agent-database executor kept only one global idle generation, so every switch between agents closed one executor and cold-opened the other, which took about 600-800 ms.
User Impact
User impact: with two or more agents in use,
sessions.createand other agent-database work no longer pay a cold executor open on every agent switch. The cost is memory: each additional warm idle executor holds roughly 100 MiB until its idle timeout or LRU eviction.Why This Change Was Made
The executor owner now retains up to four idle executors, keyed by physical agent, with least-recently-used eviction and an independent idle timer for each. Gateway shutdown closes all of them through the existing custody. A lifecycle watcher retires the affected executor after a committed agent removal, rename, or storage-path change.
Evidence
Live (dev Gateway, two agents on the built-in and Codex runtimes; fresh state, one session per agent first, then 6
sessions.createalternating agents, measured twice):2983dfcfb319Owner probe: 6 alternating creates open 6 executors on main and 2 on this branch (p50 715 to 31 ms). RSS probe: 105-107 MiB per additional warm idle executor, 316-322 MiB more for four than for one. Process RSS stayed elevated after all four stores closed, so prompt memory reclamation is not proven.
Lint, core types, format, docs lint, and the madge cycle check pass. Autoreview was scoped-clean through P2.
After the port onto main (merge commit
66674368539d): 203 tests across 13 files pass (one Linux-only skip). New regressions cover revoked receipts requiring fresh validation and active creators surviving eviction pressure. Owner probe on the port: 6 alternating creates open 6 executors on main and 2 on the branch; p50 756 to 48 ms, p95 1027 to 685 ms; 109.6 MiB per additional warm executor. Autoreview of the merged branch was scoped-clean through P2.Production +109/-70, tests +289/-2, docs +2/-0 (against current main).
Latest conflict repair: merged main
7880834c19616b5efb871e1755cd4b30cf2f2481into this branch ase3bc95ccc2b93ed174417e3f2367c3fda8bf7f18, preserving main's admission-error and execution-scope import split alongside the configuration watcher. No rebase or product-scope change. The PR delta remains five files (+400/-72), including production +109/-70.Validation of the repaired tree:
pnpm test src/state/openclaw-agent-execution*.test.ts src/state/openclaw-agent-db.worker-admission.test.ts --maxWorkers=1passed 315 tests across 21 files, with one platform skip, in 287.95 seconds wall time. This includes idle revoked-receipt readmission, missing-index readmission, active-creator eviction pressure, configuration retirement, restart drain, and shutdown. Formatting andgit diff --checkpassed. Independent Codex autoreview was scoped-clean through P2. Existing live Gateway measurements remain prior-head evidence; the conflict resolution changes imports only.Latest mechanical CI repairs:
f4493cc433e5adds the configuration watcher to the trusted PR wrapper inventory (20/20 source-closure tests pass, 27.80 seconds wall). CI run 37556223388 then found four possibly-undefined fixture accesses inopenclaw-agent-execution.idle.test.ts;7b685c4ffd7aadds runtime presence assertions before those accesses, preserving the expected behavior. The affected state/logging test-type shard passes, all 14 idle-executor tests pass (8.85 seconds wall), and focused lint, formatting, and diff checks pass. Fresh isolated Codex autoreview is scoped-clean through P2 for the full candidate and the subsequent fixture-only repair. Production code is unchanged by both mechanical repairs.