Skip to content

perf(sessions): parallelize foreground transcript reads - #167029

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-transcript-read-pool-parallel-20260919
Oct 8, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-transcript-read-pool-parallel-20260919

Conversation

@steipete

@steipete steipete commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

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 readChatHistoryPage and SessionManager.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.

p99 metric One reader per pool CPU-derived pools (2 each on this runner)
Mixed workload: history 84.4 ms 32.3 ms
Mixed workload: model context 141.7 ms 102.0 ms
Mixed workload: transcript queue 74.0 ms 49.6 ms
History-only bursts 105.0 ms 67.8 ms
Context-only bursts 67.3 ms 74.7 ms

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 lease tbx_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:

  • Three cleanup regressions failed on the unchanged base for the intended reasons: sibling eviction cleanup, mixed-generation close qualification, and premature custody release after an individual worker retired.
  • 16 focused/sibling test files covered history, context, ordered reads, anchors, events, cancellation, replacement, and usage-cost behavior. The full run exposed a mock that discarded failed native-retirement callbacks; the fixture now preserves them for retry, matching the real pool.
  • Full changed-gate validation lease: 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.
  • Independent review of production behavior and the repaired fixtures passed with no actionable P0–P2 findings. node scripts/check-changed.mjs --staged --base HEAD passed: 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 c531ab224174 plus 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, lease cbx_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=1

Core 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 a28954073855f7f537d77123c392efca1f83d455 in 11m46s elapsed. All PR checks completed without failures. Squash-merged as 6aa926265782b5cf59bf7c1296b877debeb029f9.

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.
@clawsweeper

clawsweeper Bot commented Oct 8, 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 gateway Gateway runtime scripts Repository scripts size: M labels Oct 8, 2026
@steipete
steipete marked this pull request as ready for review October 8, 2026 07:35
@steipete
steipete enabled auto-merge (squash) October 8, 2026 07:35
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 8, 2026
@clawsweeper

clawsweeper Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 8, 2026, 4:54 AM ET / 08:54 UTC (Revision 2).

ClawSweeper review

What this changes

This 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

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is focused and source-clean, with meaningful real-worker boundary evidence but no complete shipped-entry-point performance proof.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: Repository State identifies this as maintainer-authored, outside the ordinary contributor proof gate. The supplied Testbox evidence exercises both changed foreground pools through real read APIs and native workers, checks returned content, and reports scoped gains and adverse results; follow-up cleanup tests are supplemental. Source verifies that no stored-data migration is needed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes
User problem: Concurrent requests for conversation history and model context wait behind one reader despite spare CPU capacity.
Reason: The existing area contributor proposes a bounded optimization with measured warm-history gains and explicitly accepts its cold-start and memory costs.

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
Reviewed head: a28954073855f7f537d77123c392efca1f83d455

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied benchmark exercises production read APIs and real workers with synthetic sessions; it does not run the complete shipped Gateway RPC or CLI flow. This read-only review did not rerun the reported base/head controls.
Agent review details

How this fits together

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

Technical review

Best 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

Testing

Proof path: in-process harness. Added test files: 5.

Security

None.

Evidence

What I checked:

  • Introduced production changes: The pinned merge-base-to-head diff expands only foreground reader capacity, extracts the pool constructors, and changes history cleanup from individual-worker receipts to pool-wide settlement. (src/config/sessions/session-transcript-read-pools.ts:18, a28954073855)
  • Still necessary on current main: Fetched main retains maxWorkers: 1 for model-context reads. Comparing all 12 touched paths against the merge base found no intervening main changes; the related merged PRs establish earlier worker and lifecycle improvements, not this parallelization. (src/config/sessions/session-transcript-read-worker-runtime.ts:33, d94fe35027e7)
  • Cold preparation and cleanup: Eviction checks active tasks, including cold preparations, before choosing qualified native close. Otherwise it joins pool rotation; native-close qualification requires every retained generation to support it. (src/config/sessions/session-transcript-worker-resources.ts:310, a28954073855)
  • Existing publication fence: The model-context consumer still validates transcript version, admission, anchors, cancellation, and source identity before publishing the selected context; the patch does not modify that owner. (src/config/sessions/session-transcript-context-read.ts:49, a28954073855)
  • Reported boundary measurements and accepted tradeoffs: The complete supplied PR body, captured as sourceRevision 1fefc4f278b4aca4195902cebdc30496c11825cd7dde6e95a16159f35e978ef9, reports a real-worker Testbox benchmark through readChatHistoryPage and SessionManager.openModelContextAsync with content checks. Mixed history p99 was 84.4→32.3 ms, RSS increased 156 MiB, and cold history increased 65→354 ms. The established area contributor explicitly presents these tradeoffs and makes no full-Gateway latency claim. (fe4d19166ae1)
  • Follow-up validation and review continuity: The body reports an old-guard negative control failing with the intended pending-reader error and the restored candidate passing 142 tests across eight focused/sibling files on AWS. The prior review had no findings or published rank-up moves; the new commit repairs cold-preparation cleanup and capacity-dependent cancellation fixtures. These are contributor-reported executions, not reviewer-run tests. (src/config/sessions/session-transcript-worker-lanes.test.ts:394, a28954073855)

Likely related people:

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

PR surface

Source +31, Tests +129, Docs +8, Other +1. Total +169 across 12 files.

View PR surface stats
Area Files Added Removed Net
Source 4 126 95 +31
Tests 6 188 59 +129
Docs 1 9 1 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 12 324 155 +169

Review metrics

Metric Value Why it matters
Measured resource tradeoff RSS +156 MiB with two readers per foreground pool The reported memory cost gives concrete context for the measured warm-history improvement.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded conversation-read performance improvement without evidence of an urgent user-facing outage.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-08T07:42:08.363Z sha fe4d191 :: needs maintainer review before merge. :: none

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-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Oct 8, 2026
@steipete
steipete merged commit 6aa9262 into main Oct 8, 2026
132 checks passed
@steipete
steipete deleted the steipete/perf-micro-transcript-read-pool-parallel-20260919 branch October 8, 2026 09:00
steipete added a commit that referenced this pull request Oct 8, 2026
#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.
steipete added a commit that referenced this pull request Oct 8, 2026
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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 9, 2026
)

* 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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 9, 2026
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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 9, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts 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