Skip to content

perf(sessions): reduce new worktree creation latency - #184253

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-sessions-create-latency-20260919
Oct 26, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-sessions-create-latency-20260919

Conversation

@steipete

@steipete steipete commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fresh managed-worktree session creation discovers the same Git checkout twice, adding three serial subprocesses before the session is ready.

User Impact

Creating a new session with worktree: true avoids that duplicate discovery. Created session/worktree state, nested working directories, replay checks, early prompts, and source/commit authority remain unchanged. This is a small creation-path improvement, not a claim to fix all session-create tail latency.

Why This Change Was Made

The managed-worktree creation owner already resolves the checkout source root. Return that fact to session preparation, which consumes it for nested cwd mapping. Retain the earlier discovery where an existing binding or early prompt requires it. No cache, new configuration, schema, or provider behavior changes.

Runtime production changes total +6 lines across three files: the existing source-root fact crosses the owner boundary to preserve nested cwd. The redundant service forwarding method is removed, and the identical nested-cwd mapping now lives with worktree bindings. Both previously oversized files shrink. The non-test diff totals +653/−34 (+619): runtime +6 and reproducible measurement scripts +613. The scripts provide the requested built-Gateway phase/state proof and separate CPU/allocation workload using existing fixture, transport, and profiling helpers. Usage lives in their header comments; the shared perf README is unchanged.

Evidence

The real nested-workspace regression fails on the baseline with two discoveries and passes with one, while checking cwd and registry state. Final extraction validation passed 70 tests: 23 project/spawn cases, 4 worktree-preparation cases, 21 canonical service cases, and 22 source-closure cases. The earlier unchanged selection and incognito checks passed 9 additional tests, for 79 distinct passing tests across seven focused files. Baseline and candidate runtime builds completed successfully.

Five alternating-order owner pairs, 100 operations per arm per pair, use real Git and assert identical resolved roots. A separate sampled-allocation pass uses the same workload (2,000 logical operations across both passes):

Discovery slice, per operation Before After Change
Node-process CPU, excluding Git children 17.98 ms 10.24 ms −43.0%
Sampled allocation 2.42 MB 1.39 MB −42.7%
Wall time 118.11 ms 66.13 ms −44.0%

These numbers measure the duplicate-plus-required repository discovery composition, not full session creation. Every pair favored the candidate for CPU and allocation. Shared-host wall time is context.

The isolated built Gateway workload uses 10,800 synthetic sessions, 40 enabled plugins, and 25 warmed creates each for plain sessions, worktree sessions, and initial mock-provider turns with a 150 ms response delay. Repository-discovery Git launches fell 7→4 in every measured worktree create; total observed Git launches fell 36→33. Matched adapter overhead p50/p95 was 224/475→5/16 ms. All 25 normalized durable worktree states matched, and both arms passed session identity, registry/checkout, and completed mock-response verification. Whole-create timing is confounded by host load, so the much larger overall latency reduction is not attributed to this patch.

The focused fast-path scope does not run a multi-pair ten-minute whole-Gateway stress campaign: it removes duplicate subprocess discovery on new worktree creation and does not change a frequent Gateway loop. The 25-sample p95 values below are context, not tail gates; no adverse conclusion is drawn from uncontrolled host timing.

Independent subagent review (autoreview route unavailable) found one obsolete test pause at the removed caller discovery. The pause now targets the creation owner's real discovery, retaining all lifecycle/intent invalidation assertions. Follow-up review found no remaining P0–P2 findings.

Formatting and the export-name collision guard pass. Changed-file core lint reports only the inherited file-size limit: the same rule counts baseline 724 and final 723 nonblank/noncomment lines against a 700-line budget. The final change shrinks both capped files, and the tracked no-growth ratchet passes. No lint rule, baseline, or suppression changed. Scripts and repaired authority-test lint pass. PR CI supplies the broad checks on the final head.

Measurements used baseline 29397d2a185c29d4b4d79d2ad41af0f7cf1f6a9b and the same built source plus this change. The first prepublication rebase left all eleven reviewed files byte-identical. After measurement, the commit hook required the two oversized files to stop growing: the redundant forwarding method was removed and identical nested-cwd mapping moved to the existing binding module. Independent review confirmed unchanged discovery work and cwd/authority behavior; affected final tests cover that extraction. Timing results remain evidence for the earlier measured build, not a new timing claim for the extraction or subsequent main integration. No live Team load or production-state copy was used.

Initial PR CI identified two defects: the measurement script's result array needed an explicit inferred-return type, and the merged test run included a new exact-outcome assertion from #184138 that needed the returned sourceRoot. The branch integrates that main change and fixes both, preserving its workspace acquisition behavior. These were repaired rather than rerun unchanged. All 17 pending-slot tests, the targeted scripts typecheck, changed-file lint, and formatting pass; a fresh independent review found no actionable findings.

Full Gateway phase and resource measurements, state proof, and limitations

Each cell is base → candidate. 25 measured creates per kind/arm after 3 warmups; every RPC/phase p95 has fewer than 200 samples and is context. CPU covers create/readback cycles; initial also waits for the completed turn.

Latency: p50 / p95 ms.

Metric Plain Worktree Initial message
RPC wall 95.95 / 258.74 → 71.10 / 180.08 4978.77 / 8005.46 → 2805.80 / 4119.90 640.76 / 2342.90 → 132.82 / 297.91
Server handler 94.00 / 256.00 → 66.00 / 178.00 4978.00 / 8005.00 → 2804.00 / 4119.00 638.00 / 2343.00 → 114.00 / 297.00
preflight 8 / 42 → 9 / 74 167 / 351 → 105 / 154 8 / 36 → 6 / 24
admission 1 / 2 → 0 / 2 0 / 2 → 0 / 6 0 / 2 → 0 / 1
lifecycleAdmission 0 / 1 → 0 / 0 0 / 1 → 0 / 0 0 / 0 → 0 / 0
targetPreparation 5 / 31 → 3 / 47 9 / 30 → 3 / 6 2 / 16 → 4 / 20
entry 1 / 3 → 1 / 8 1 / 2 → 0 / 1 0 / 2 → 0 / 6
worktree 0 / 0 → 0 / 0 4450 / 5552 → 2501 / 2858 0 / 0 → 0 / 0
snapshot 3 / 17 → 3 / 14 5 / 30 → 3 / 11 5 / 55 → 2 / 13
writerAdmission 1 / 89 → 0 / 23 1 / 2772 → 0 / 220 2 / 1241 → 0 / 18
commit 28 / 214 → 29 / 95 50 / 225 → 28 / 201 205 / 429 → 13 / 44
publication 1 / 19 → 1 / 15 1 / 7 → 1 / 2 2 / 16 → 1 / 4
effects 0 / 0 → 0 / 0 1 / 3 → 1 / 2 0 / 1 → 0 / 0
initialTurn 0 / 1 → 0 / 0 0 / 1 → 0 / 1 274 / 1162 → 61 / 220
response 0 / 0 → 0 / 3 0 / 1 → 0 / 1 0 / 1 → 0 / 0
handlerExit 0 / 3 → 0 / 0 0 / 0 → 0 / 0 1 / 4 → 0 / 1

Resource context.

Metric Plain Worktree Initial message
Main-thread CPU ms/create 29.26 → 30.63 295.25 → 238.11 371.55 → 294.19
Main-thread CPU % of one core 18.54 → 21.73 6.02 → 8.90 8.82 → 22.04
Process CPU ms/create 150.85 → 88.70 1059.23 → 804.63 1402.30 → 942.96
GC total ms/create 1.50 → 6.47 24.56 → 18.15 20.02 → 37.22
GC s/min 0.572 → 2.755 0.300 → 0.407 0.285 → 1.673
All GC count / total ms / max ms 5 / 37.60 / 19.40 → 8 / 161.67 / 102.23 78 / 613.97 / 148.43 → 39 / 453.74 / 188.01 70 / 500.62 / 83.08 → 78 / 930.49 / 104.64
Minor GC count / total ms / max ms 5 / 37.60 / 19.40 → 6 / 58.13 / 46.13 72 / 296.28 / 38.42 → 35 / 175.87 / 53.18 62 / 403.44 / 83.08 → 76 / 808.29 / 104.64
Major GC count / total ms / max ms 0 / 0.00 / 0.00 → 1 / 102.23 / 102.23 3 / 308.35 / 148.43 → 2 / 273.38 / 188.01 4 / 90.01 / 34.53 → 1 / 100.68 / 100.68
Incremental GC count / total ms / max ms 0 / 0.00 / 0.00 → 1 / 1.30 / 1.30 3 / 9.33 / 4.77 → 2 / 4.49 / 3.13 4 / 7.17 / 3.64 → 1 / 21.52 / 21.52
Loop p99 ms (sample count) 134.87 (119) → 108.13 (88) 91.03 (4781) → 52.69 (2964) 58.82 (4707) → 105.84 (1164)
RSS MiB start/end 2211.58 / 2165.17 → 2160.10 / 2185.04 2362.92 / 1777.64 → 2254.51 / 1869.30 2291.37 / 2197.89 → 2650.88 / 2711.55
Heap used MiB start/end 582.30 / 600.97 → 594.14 / 587.33 603.92 / 575.35 → 607.28 / 575.20 623.77 / 649.13 → 749.69 / 950.41
Host 1-min load start/end 92.07 / 92.87 → 69.24 / 69.24 92.17 / 138.30 → 70.18 / 75.08 114.67 / 71.30 → 71.56 / 70.72

Managed-worktree phases are inclusive/nested and cannot be summed. All 25 measured logs were captured per arm.

Worktree subphase Base p50/p95 ms Candidate p50/p95 ms
allocate 57 / 129 24 / 46
allocationWait 49 / 106 17 / 53
base 242 / 436 189 / 241
baseHydration 92 / 146 71 / 111
baseRefresh 154 / 271 113 / 160
baseWait 242 / 436 189 / 241
checkout 2808 / 4045 1866 / 2350
diskAdmission 119 / 301 55 / 96
indexRefresh 46 / 146 26 / 37
leaseRelease 183 / 361 74 / 120
mutationWait 115 / 261 43 / 70
provision 14 / 57 9 / 21
publication 38 / 117 22 / 40
registration 235 / 368 134 / 273
repository 243 / 347 141 / 262
reservation 64 / 187 31 / 96
sourceRelease 0 / 0 0 / 0
sources 43 / 168 23 / 52
templateApply 920 / 1599 487 / 723
templatePrepare 529 / 1098 281 / 413
Adapter outside managed interval 224 / 475 5 / 16

The repository subphase begins inside createWithOutcome and measures retained owner discovery. Adapter overhead subtracts the matched managed duration from the aggregate worktree stage: discovery/binding/accept overhead, not pure discovery. Its mean fell 249.52→6.28 ms. Repository identity Git launches were 7→4 in every measured worktree sample; total Git launches 36→33, other operation buckets unchanged. Interval counters can include background launches; the owner regression establishes the duplicate-call deletion.

The candidate ran under substantially lighter host load. The unchanged initial-message flow improved greatly too, so whole-run latency, CPU and memory deltas are contextual, not causal estimates. Worktree GC per create fell 24.56→18.15 ms while throughput increased, making GC per time rise 0.300→0.407 s/min; this is not an adverse verdict. Major GC counts are below 50 per arm. No A/A or 10-minute stress campaign ran under the requested fast-path protocol. Allocation comes from the separate owner microbenchmark only; no whole-Gateway allocation claim. sessions.list was startup inventory only, without a latency distribution.

Both arms used 10,800 synthetic fixture sessions, 40 enabled plugins, seed 1826, 128 MiB transcripts and the same older fixture anchor 1791892800000 (2026-10-13), with maintenance unchanged. Actual startup retained count was 10,804 base (after 4 setup smoke creates) and 10,800 candidate. Each arm completed 75 measured creates; 56 mock requests including warmups consumed the 150 ms provider delay. All 25 initial sessions retained the expected assistant response. All 25 worktree bindings matched durable session rows and live registry entries, with exact source README and managed Git registration; 25 normalized stable states matched across arms, retaining UUID slug truncation/collision shape. Nested source is covered by focused tests, not this Gateway fixture. Placement is local only. Both owned Gateways stopped; candidate logged clean shutdown.

@clawsweeper

clawsweeper Bot commented Oct 26, 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 gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: L labels Oct 26, 2026
@steipete
steipete marked this pull request as ready for review October 26, 2026 05:36
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 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-26T06:09:04.382601Z a8c74fa 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.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 26, 2026
@clawsweeper

clawsweeper Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR avoids duplicate Git discovery during fresh worktree session creation by returning the source root from the existing creation owner.

Example: Create a worktree session from /repo/..notes/app with worktree: true.

  • Before: Session preparation and worktree creation both discover the source checkout.
  • After: Creation discovers it once, and the session still starts in the new checkout’s ..notes/app directory.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, useful optimization with production-path evidence and no remaining finding; host-load differences limit broader latency conclusions.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied built-Gateway WebSocket workload exercises fresh worktree creation with real Git and records reduced discovery launches plus matching durable state; focused final-source tests cover the subsequent cwd extraction and replay repair.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Fresh worktree sessions wait for an unnecessary second discovery of the same Git checkout.
Reason: The maintainer-authored direction removes measurable subprocess work while preserving existing bindings, nested working directories, early prompts, and lifecycle checks.

Merge readiness

✅ Ready for maintainer review

This PR provides a focused performance improvement, and the previous replay-assertion finding is fixed; no new actionable defect was found.

Priority: P2
Reviewed head: a8c74fa54ecc2310101ed57eaa0a90d827902e8f

Before merge

None.

Findings

None.

Agent review details

How this fits together

The Gateway turns session workspace selections into managed Git checkouts, then binds the resulting worktree and working directory to the session.

flowchart TD
A[Session create RPC] --> B[Session worktree preparation]
B --> C[Managed worktree creation]
C --> D[Git checkout discovery]
D --> C
C --> E[Worktree record and source root]
E --> B
B --> F[Bound session and nested cwd]
Loading

Technical review

Best possible solution:

Reuse the creation owner’s resolved source root while retaining discovery for existing bindings and early prompts.

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

Current-main source shows both discovery calls, and the supplied real-Git regression reports baseline failure and candidate success; no target code was executed during this review.

Is this the best way to solve the issue?

The patch follows the smallest complete approach: carry an existing owner’s fact to its consumer, preserve required preflights, and remove the redundant wrapper.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Paths-only repository discovery keeps the original intent (ed535c5: Separate cheap path discovery from full repository identity validation without weakening publication checks.)
  • Nested working-directory mapping keeps the original intent (23fb1c0: Preserve creation and cleanup ownership, including nested working directories such as ..notes.)
  • Early prompt preparation keeps the original intent (325c56d: Allow inference during checkout while retaining complete preparation for unsupported or workspace-dependent cases.)
  • Registered-source contention and replay keeps the original intent (95a3ccd: Let unrelated repositories proceed while a registered source waits, retaining ordinary reservation and replay behavior.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit e1dbb59 adds src/agents/worktrees/service.ts:205 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: e1dbb59b46bd; files: src/agents/worktrees/service.ts)
  • Shakker: Raw commit 95a3ccd adds src/agents/worktrees/service.pending-slots.test.ts:310 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 95a3ccde1410; files: src/agents/worktrees/service.pending-slots.test.ts)

PR surface

Source +6, Tests +53, Other +613. Total +672 across 12 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 40 34 +6
Tests 6 83 30 +53
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 3 613 0 +613
Total 12 736 64 +672

Review metrics

Metric Value Why it matters
Repository discovery work 7 → 4 Git launches per fresh worktree create Reported consistently across 25 Gateway worktree samples and supported by the focused real-Git work-count regression.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This removes bounded, unnecessary work from session creation without changing user settings or workspace behavior.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-26T05:53:26.179Z sha f60140014d9527f0551c52cc069615f81a86b9e4 :: needs changes before merge. :: [P2] Update the pending-slot replay assertion for the enriched outcome

Reviewed October 26, 2026, 2:16 AM ET / 06:16 UTC (Revision 2).

Reuse the source checkout root resolved by the managed-worktree creation
owner instead of discovering it again during fresh session preparation.
Preserve nested cwd mapping, existing-binding and early-prompt preflights,
and source/commit authority checks.

This removes three serial Git subprocesses from sessions.create with a
new worktree. Add a real work-count regression and reproducible owner/RPC
measurements; retain the existing incognito invalidation assertions at
the actual creation discovery boundary.
@steipete
steipete force-pushed the steipete/perf-micro-sessions-create-latency-20260919 branch from f601400 to a8c74fa Compare October 26, 2026 06:06
@steipete

Copy link
Copy Markdown
Contributor Author

Fixed on a8c74fa: the pending-slot reuse assertion now includes the resolved sourceRoot while retaining the exact record/materialized checks. All 17 tests in service.pending-slots.test.ts pass. The separate script type failure was an implicit-any result array; it now uses the inferred run return type, and pnpm tsgo:scripts passes. Changed-file lint and independent review are clean. The PR body contains both repairs and the current proof; fresh exact-head CI is running.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 26, 2026
@steipete
steipete merged commit b70762f into main Oct 26, 2026
144 of 146 checks passed
@steipete
steipete deleted the steipete/perf-micro-sessions-create-latency-20260919 branch October 26, 2026 06:32
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 27, 2026
* perf(sessions): avoid duplicate worktree repository discovery

Reuse the source checkout root resolved by the managed-worktree creation
owner instead of discovering it again during fresh session preparation.
Preserve nested cwd mapping, existing-binding and early-prompt preflights,
and source/commit authority checks.

This removes three serial Git subprocesses from sessions.create with a
new worktree. Add a real work-count regression and reproducible owner/RPC
measurements; retain the existing incognito invalidation assertions at
the actual creation discovery boundary.

* fix(sessions): repair create measurement and outcome checks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime 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. scripts Repository scripts size: L 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