Skip to content

perf(sessions): reduce cold input reads and warm worktree lease contention - #170903

Merged
steipete merged 4 commits into
mainfrom
steipete/perf-micro-create-persist-and-worktree-leases-20260919
Oct 13, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/perf-micro-create-persist-and-worktree-leases-20260919

Conversation

@steipete

@steipete steipete commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Twenty simultaneous session starts put eager actor reads and warm worktree template lease admissions ahead of useful work.

User Impact

Cold input commits avoid eager whole-actor reads, and consumers of an actively retained warm template can clone concurrently. Initial transcript custody and restart recovery still commit atomically. No schema, durability, configuration, or update migration changes.

Why This Change Was Made

Use an already available actor replica for preparation; otherwise use the existing narrow turn planner. The disk, memory, and replica planners carry the recovery expectation from their already-read preimage; prepared, explicit, and warm expectations remain fixed through hooks and retries. Missing entries use an empty preimage expectation even when the initial postimage supplies lifecycle fields. Source authority, FIFO admission, final COMMIT authorization, receipt settlement, and publication retain their existing owners. Capture the native preimage for creation/identity publication instead of needing an eager read solely for that bookkeeping.

The existing template registry transaction now selects and retains a matching ready generation with current readers. That makes the template mutation lease unnecessary for those consumers. Reader admission and unpublication share the same transaction, so retirement cannot delete an admitted generation. Idle validation, cold construction, capacity/count/disk decisions, and Git registration retain their existing owners. Materialization already runs outside global capacity custody.

Production LOC delta: +100 across seven production files (+38 session input, +62 worktree custody). The added code preserves two existing contracts while deleting eager input reads and the active-template lease admission: explicit recovery expectations must remain fixed through rebases, and idle templates must be validated before use while retained readers exclude retirement. Prepared lifecycle facts and atomic reader-versus-unpublish selection encode those contracts. No new cache, lease, command variant, database table, worker operation, configuration option, or public API.

Evidence

Measurements used isolated synthetic Team sandboxes, constrained to CPUs 64–127 and 64 GiB with low CPU/I/O priority. Own state, HOME, OPENCLAW_HOME, TMPDIR, and loopback ports; production Gateway/config/databases were untouched. No validation leases were allocated. Source pins: final session comparison 7a5529f4c964 → 597b5fb126b1; unchanged warm-worktree comparison 96c88920ee0b → fa2938845c74. Exact-head CI covers the final merged context.

Public session creation boundary

Installed runtime Gateway, mock provider with a real exec tool turn, 20 concurrent sessions.create calls with initial messages, one excluded warmup, 20 seeded sessions with 20 historical messages each. The final corrected source was compared sequentially A–B–B–A against its base. All 80 runs completed successfully; a hash of all six changed disk/worktree production files matched the committed candidate; the later memory adapter completion leaves this disk benchmark path unchanged. Entries below are medians of the two per-run p50/max values, in milliseconds:

Measurement Before After
Create p50 / batch max 632 / 777 567 / 725
Persist p50 / batch max 269 / 382 266 / 388
First tool event p50 / batch max 4,534 / 4,830 4,852 / 5,119

The final result is neutral within observed run variation, not a demonstrated fix for the reported 1.5 s persistence stall. This synthetic database is much smaller than the incident database. Individual create p50/max runs were before 779/950 and 486/604; after 476/616 and 658/835. Individual first-tool p50/max runs were before 4,851/5,207 and 4,217/4,453; after 4,278/4,493 and 5,426/5,744. The broad overlapping ranges do not establish a causal first-tool regression or improvement. Earlier interim-candidate and overlapping exploratory comparisons are excluded from the final-source result.

A separate diagnostic-only run lowered the transaction logging threshold in sandbox bundles and restored it afterward; it is excluded from performance comparisons. The 20 session.actor.acceptInput transactions held SQLite for p50/max 3/8 ms: SQL 30 ms total, authority waits within holds 36 ms, COMMIT 3 ms. A second diagnostic-only run had input transaction hold p50/max 6/36 ms (SQL 31 ms total, authority waits within holds 113 ms, COMMIT 4 ms), and also lowered reservation logging thresholds: during its burst persistence window, 103 physical agent-database reservations (including creation/preparation reads and sibling writes) had FIFO wait p50/max 76/348 ms, versus reservation execution 1/62 ms; summed wait/execution was 9,948/503 ms. This attributes the synthetic burst primarily to FIFO scheduling rather than large SQL holds; it does not reproduce or precisely apportion the incident's 1.5 s. The normal atomic input ensures the transcript header and writes the message and its identity/index/watermark state, then the final session/recovery entry. No duplicate normal-path entry rewrite was found. Authority transfer remains owned by the existing writer-admission program in docs/architecture/writer-admission-authority.md.

Warm worktree allocation boundary

Real Btrfs snapshots, Git registration/index work, 10,001 synthetic files, 20 concurrent allocations and first workspace reads. An actually validated reader remains retained for the burst. The existing restoration-mode deferGitCheckout option keeps the benchmark on Btrfs instead of the adaptive owner's Git sample; filesystem operations were not mocked. Three rounds:

Round Before first-read p50 / max (ms) After first-read p50 / max (ms)
1 7,028 / 12,431 3,151 / 3,305
2 6,601 / 11,847 2,101 / 2,295
3 6,864 / 12,232 1,881 / 2,134

Median p50 6,864 → 2,101 ms (3.27×); median batch max 12,232 → 2,295 ms (5.33×). This is allocation-to-first-workspace-read evidence, not Gateway create-to-first-tool evidence with managed worktrees enabled. Count/disk/provisioning are outside this owner benchmark. The lease-held regression rejects the original code in 5 ms and succeeds with the patch in 4 ms, using zero contention budget.

The full default ManagedWorktreeService comparison includes real capacity admission, provisioning and publication, with no retained-reader or adaptive overrides. Sequential before/after/after/before create p50/max: 3,932/5,857; 3,183/4,715; 3,330/4,970; 3,291/4,693 ms. Median per-run p50/max 3,612/5,275 → 3,257/4,843 ms: no observed default-flow regression; the overlapping ranges do not establish an isolated macro gain. Each run selected three warm clones and 17 Git fallbacks. Capacity wait remains dominant (p50 about 1.7–2.1 s), reservation 49–82 ms, Git registration 14–18 ms. Authoritative capacity reservation remains serialized; this change removes the unnecessary active-template lease, not the count owner.

An initially idle-template owner comparison was neutral/noisy: median p50/max 9,214/17,400 → 9,641/16,841 ms. Idle revalidation remains exclusive. Earlier unpaired full-service trials were inconclusive under concurrent activity; a larger fixture selected Git and cannot substantiate a warm-template gain.

A pending-slot recovery preflight was explored and excluded: it removed 20 no-op transactions and halved the inner recovery call (median 0.957 → 0.471 ms), but the final full-service median create p50/max rose 3,035/4,624 → 4,443/6,653 ms. One candidate run contained multi-second filesystem stalls, so causality was not isolated; the experiment failed to establish no regression and did not justify its additional code. Capacity recovery/admission remains unchanged in this PR.

Validation and review

  • Changed-file oxfmt --check, repo lint scoped to changed TypeScript files, and git diff --check: passed.
  • pnpm test src/config/sessions/session-actor-worker.test.ts src/config/sessions/session-input-concurrency.test.ts src/agents/worktrees/template-cache.test.ts src/agents/worktrees/template-registry.test.ts --maxWorkers=1: 43 assertions passed on the first candidate, 188.90 s total wrapper wall time (worktree shard 33.43 s, session shard 73.16 s). Together with the final session proof below, coverage includes exact atomic transcript/recovery commits, cold hydration, authority changes during rebases, concurrent input idempotency, warm reader admission while the mutation lease is held, and retirement excluding active readers.
  • An earlier invocation passed its assertions but its worker wrapper rejected a mid-run source change; the final frozen-source invocation passed. Initial worktree cancellation/expectation failures were fixed before the final run.
  • independent subagent review (autoreview route unavailable): no remaining actionable findings; final test compaction and planner correction reviewed. Autoreview refused the provider/operator configuration mismatch; no configuration was changed.
  • Full typecheck, suites, changed lanes, and E2E are delegated to PR CI per the validation rule. The first ready-head run caught a widened command literal and two cold-recorder lifecycle-fence failures. The corrected producer carries the narrow planner’s existing preimage expectation into the existing command API; the extra cold command variant was removed entirely. Independent review identified and resolved missing-entry versus initial-postimage expectations. Changed-file format/lint and focused session custody proof passed again; The final source-custody file passed all 11 assertions in 84.11 s, including cold and warm initialization; the three focused session files passed 38 assertions in 185.16 s before the narrow missing-preimage correction. The unchanged worktree proof is reused. An initial regression assertion incorrectly inspected raw rows as parsed events; its corrected frozen-source invocation passed. A second CI run identified the memory planner’s missing field and a Gateway test that required a private stale-version reply. The memory adapter now implements the same preimage contract; five memory-turn assertions passed in 48.76 s. The Gateway test retains public exactly-once persistence/dispatch and concurrent participant writes, while removing the retired internal reply requirement; its focused run passed all 15 assertions in 124.97 s. Both corrections received independent review. The third CI run passed production types, builds, and runtime shards, and caught an unsupported status literal in the new regression fixture. The fixture now uses the supported done status, retains its original preimage contract, and passed all 11 assertions again; the two-line correction received independent review. Final exact-head CI run 38383581287 passed on 1dfa1fa6c46b208174ffb3cd07594741b4ff23d1: 10 min 34 s wall time, 9,604 summed job-seconds (parallel jobs). Builds, production/test types, changed runtime lanes, UI E2E, lint/format, and security checks passed. No reruns or inherited-failure exception were used.

…ntion

Keep first-input transcript and restart recovery in one native actor transaction while selecting uncaptured recovery expectations from its authoritative preimage. Preserve explicit expectations through rebases and avoid eager whole-actor reads.

Retain an already validated warm template generation atomically with reader custody instead of taking its mutation lease for every clone. Retirement shares the same admission boundary; idle validation and Git registration retain their existing owners.

Release-note context: concurrent session startup can consume retained warm worktree templates concurrently, without schema or durability changes.
@clawsweeper

clawsweeper Bot commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@steipete
steipete marked this pull request as ready for review October 13, 2026 09:31
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-13T10:12:21.406614Z 8a4c192 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: M labels Oct 13, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 597b5fb126

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/config/sessions/session-turn.ts Resolved
@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Oct 13, 2026
@steipete
steipete merged commit 3cc16ae into main Oct 13, 2026
130 checks passed
@steipete
steipete deleted the steipete/perf-micro-create-persist-and-worktree-leases-20260919 branch October 13, 2026 10:41
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 14, 2026
…ntion (openclaw#170903)

* perf(sessions): reduce cold input reads and warm worktree lease contention

Keep first-input transcript and restart recovery in one native actor transaction while selecting uncaptured recovery expectations from its authoritative preimage. Preserve explicit expectations through rebases and avoid eager whole-actor reads.

Retain an already validated warm template generation atomically with reader custody instead of taking its mutation lease for every clone. Retirement shares the same admission boundary; idle validation and Git registration retain their existing owners.

Release-note context: concurrent session startup can consume retained warm worktree templates concurrently, without schema or durability changes.

* fix(sessions): retain planned lifecycle expectations for cold input

* fix(sessions): complete prepared input lifecycle contract

* test(sessions): use supported initial lifecycle status
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 size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant