Repository navigation
perf(sessions): parallelize foreground transcript reads - #167029
Conversation
Share the host CPU budget between bounded history and model-context reader pools, with at most eight workers each. Keep SQLite writers and background lanes serial, and retain the existing writer admission and snapshot fences. Settle reader eviction and retirement across the pool before releasing database custody. Track every live worker's native-close capability and preserve failed retirement callbacks in the lifecycle fixtures. Synthetic 20-session mixed-read history p99 improved from 84 ms to 32 ms on a four-CPU Testbox, with about 156 MiB additional RSS. Lazy worker expansion has a first-burst startup cost; no schema, stored-format, or configuration change.
|
🦞👀 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 8, 2026, 4:54 AM ET / 08:54 UTC (Revision 2). ClawSweeper reviewWhat this changesThis PR sizes foreground conversation-history and model-context reader pools from host CPU capacity and makes database cleanup account for every live reader. Review scores
ProductKind: Performance · Worth it: Yes Merge readiness✅ Ready for maintainer review This PR remains useful: current main still serializes foreground reads, and the reviewed patch has no actionable introduced defect. The performance evidence supports the read boundary, with explicitly documented cold-start and memory tradeoffs. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherOpenClaw reads saved conversations from SQLite to display chat history and prepare model context. These worker pools perform those reads off the Gateway thread and return results through the existing snapshot and lifecycle checks. flowchart TD
A[Chat history requests] --> C[Existing read admission]
B[Model context requests] --> C
C --> D[CPU-sized foreground reader pools]
D --> E[Worker-local SQLite snapshots]
E --> F[Validate and return results]
D --> G[Pool-wide database cleanup]
Technical reviewBest possible solution: Keep the existing read and lifecycle owners, with bounded foreground parallelism and the documented warm-latency, cold-start, and memory tradeoffs. Do we have a high-confidence way to reproduce the issue? Not applicable as a correctness bug; source confirms the existing single-reader bottleneck, and the supplied benchmark provides a concrete concurrent-read workload. Is this the best way to solve the issue? Yes: the patch extends the existing pools and cleanup owner while retaining writer admission and result validation, rather than creating a competing read path. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against d94fe35027e7. Provenance checked
TestingProof path: in-process harness. Added test files: 5. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +31, Tests +129, Docs +8, Other +1. Total +169 across 12 files. View PR surface stats
Review metrics
LabelsLabel changes: No label 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 HistoryReview history (1 earlier review cycle)
|
A cold slot can own input before asynchronous preparation creates its worker. Treat active preparations as live work so eviction waits for full retirement before releasing database custody; idle pools retain qualified native close. Cover this boundary and make queued cancellation fixtures fill the configured reader capacity. Preserve all predecessor promises during fixture cleanup and remove the readiness test's wall-clock cancellation race. Validated on AWS Crabbox: failing old-guard control, eight focused and sibling test files, core and session-test typechecks, lint, line-cap, and formatting.
#167029 runs foreground model-context reads on a worker pool, so 128 concurrent openModelContextAsync callers no longer complete in submission order. Keep the bounded-admission, no-early-completion and identical-context checks; assert that every admitted read completes exactly once.
Keep search hits and their connection-local revision check on the existing single-reader projection lane. The parallel history pool introduced by #167029 could validate a token on another connection and report complete results as still indexing. Ordinary foreground history stays parallel. Preserve maintenance readiness, foreign-commit checks, authorization, and database cleanup. The unchanged real-Gateway palette test fails at #167029 and passes at its parent and with this fix; no schema or data migration is required.
) * perf(sessions): parallelize foreground transcript reads Share the host CPU budget between bounded history and model-context reader pools, with at most eight workers each. Keep SQLite writers and background lanes serial, and retain the existing writer admission and snapshot fences. Settle reader eviction and retirement across the pool before releasing database custody. Track every live worker's native-close capability and preserve failed retirement callbacks in the lifecycle fixtures. Synthetic 20-session mixed-read history p99 improved from 84 ms to 32 ms on a four-CPU Testbox, with about 156 MiB additional RSS. Lazy worker expansion has a first-burst startup cost; no schema, stored-format, or configuration change. * fix(sessions): settle admitted readers before eviction cleanup A cold slot can own input before asynchronous preparation creates its worker. Treat active preparations as live work so eviction waits for full retirement before releasing database custody; idle pools retain qualified native close. Cover this boundary and make queued cancellation fixtures fill the configured reader capacity. Preserve all predecessor promises during fixture cleanup and remove the readiness test's wall-clock cancellation race. Validated on AWS Crabbox: failing old-guard control, eight focused and sibling test files, core and session-test typechecks, lint, line-cap, and formatting.
openclaw#167029 runs foreground model-context reads on a worker pool, so 128 concurrent openModelContextAsync callers no longer complete in submission order. Keep the bounded-admission, no-early-completion and identical-context checks; assert that every admitted read completes exactly once.
…law#167174) Keep search hits and their connection-local revision check on the existing single-reader projection lane. The parallel history pool introduced by openclaw#167029 could validate a token on another connection and report complete results as still indexing. Ordinary foreground history stays parallel. Preserve maintenance readiness, foreign-commit checks, authorization, and database cleanup. The unchanged real-Gateway palette test fails at openclaw#167029 and passes at its parent and with this fix; no schema or data migration is required.
What Problem This Solves
Concurrent foreground transcript reads wait behind a single reader even when spare CPUs are available.
User Impact
Chat history and model-context reads can use up to eight workers per foreground pool. Each pool is sized from half the existing host CPU capacity budget (rounded up). Read-only SQLite connections remain worker-local; writer admission, snapshot validation, and the single SQLite writer are unchanged. Maintenance, projection, exports, and usage-cost workers keep their current capacity. No new configuration or migration is required.
Why This Change Was Made
The former single-worker custody accounting could mistake one worker's eviction or exit for proof that every reader was closed. Pool-wide cleanup now owns that decision: an eviction reuses qualified native close or full retirement, every live generation must support native close, and a task's retirement settles the remaining pool before releasing database custody. Cleanup includes admitted reads whose cold workers are still being prepared: active work requires joined retirement, while an idle pool can retain qualified native close. This also bounds retained host registrations after worker replacement. The obsolete latest-generation pointer and its rotation override are removed.
Non-test/doc LOC: +32 (+31 production, +1 wrapper inventory), required by the all-live-generation close policy, the pool-wide eviction handshake, and consolidating the existing pool constructors to stay within the resource owner’s line cap; simply raising the worker count would violate reader cleanup. The change retains one cleanup owner rather than adding a fast path beside the old semantics.
Evidence
Synthetic 20-session workload, one canonical agent database, 100 messages of 1 KiB per session, ten rounds. The benchmark exercises
readChatHistoryPageandSessionManager.openModelContextAsync, verifies returned message IDs/content, and records real worker queue events and native worker heap statistics. This measures the read boundary, not network or complete Gateway RPC latency.The mixed history tail improved about 62%; the <5 ms queue target was missed. Context-only bursts did not improve. Lazy worker creation costs the first concurrent burst: history 65→354 ms and context 79→312 ms. RSS after the workload increased from 1,143 to 1,299 MiB with two additional workers, using 44.7 and 52.1 MiB of heap; each worker retains the existing 512 MiB old-generation limit and bounded SQLite reader cache. No production latency or full-RPC improvement is claimed.
Provider:
blacksmith-testbox, measurement leasetbx_01m4d2e0t2brwjhd8kk73ef2mh(4 available CPUs, Node 24.19.0). The earlier eight-core Linux rig was contended and produced mixed results; those numbers were not used as a clean performance comparison. AWS/Hetzner allocation was unavailable during the initial Testbox sync failure.Validation:
tbx_01m4d40cka5n9em9sq6mprc6bp. The repaired error/lane suites and native lifecycle suite passed 86 tests with--maxWorkers=1; the two import-closure suites passed 20 tests. Export-name collision checks passed.node scripts/check-changed.mjs --staged --base HEADpassed: formatting, all 27 core-test typechecking partitions, production typechecking, dead-export scans, lint, storage guards, and runtime import-cycle checks. The final validation command completed successfully in 30m24s including cold dependency installation.Test cost: the native lifecycle file used 59.1 s wall time including cold worker compilation (about 35 s of native lifecycle tests); the two pure lifecycle/error files together used 10.5 s wall time, with roughly 0.1 s test time. Native tests prove real worker shutdown, SQLite handle release, replacement, and concurrent-reader survival. The later eight-file correction run used 198.3 s across four Vitest shards, including cold worker compilation.
Prepublication proof used
c531ab224174plus this patch. The rebase onto current main preserved the patch ID. The first published-head CI run (37744354958) found three queued-cancellation cases that assumed one reader; these now fill the actual pool capacity, verify queued admission is released on abort, and join all predecessor reads. The readiness fixture no longer uses a wall-clock race.The CI correction and cold-preparation cleanup guard passed a fresh independent review with no actionable P0–P2 findings. Follow-up provider:
aws, leasecbx_03f1f0c165db. The old-guard negative control failed with the expected pending-reader error; the restored candidate passed all 142 tests in eight focused/sibling files:pnpm test src/agents/sessions/session-manager-hydration.test.ts src/agents/sessions/session-manager-hydration-stream.test.ts src/agents/sessions/session-manager-hydration-rejection.test.ts src/config/sessions/session-transcript-reconcile.readiness.test.ts src/config/sessions/session-transcript-worker-lanes.test.ts src/config/sessions/session-history-worker-errors.test.ts src/gateway/session-history-worker-lifecycle.test.ts src/infra/worker-task-pool.preparation.test.ts --maxWorkers=1Core typechecking and the agents/sessions test typechecking partition passed, along with scoped lint, line-cap, and formatting checks. The complete follow-up command took 4m30s (18m03s including source sync and hydration). All leases have been released. Normal-read benchmark inputs are unchanged by this cleanup correction.
Final published-head CI: run 37752194004 passed for
a28954073855f7f537d77123c392efca1f83d455in 11m46s elapsed. All PR checks completed without failures. Squash-merged as6aa926265782b5cf59bf7c1296b877debeb029f9.