Skip to content

perf(worktree): overlap base refresh with prepared checkout - #18998

Merged
nwparker merged 7 commits into
mainfrom
nwparker/overlap-create-fetch-and-checkout
Sep 6, 2026
Merged

nwparker merged 7 commits into
mainfrom
nwparker/overlap-create-fetch-and-checkout

Conversation

@nwparker

@nwparker nwparker commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​198 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​197
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​44 $\color{#cf222e}{\Huge{\mathbf{−}}}$​17 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​27

Worktree preparation currently waits for the remote base refresh before materializing files, even when that base already exists locally. Start the existing checkout alongside the refresh, so a Create click can reuse more of that work. Create still awaits refresh and finalization revalidates the target commit.

Both desktop IPC and runtime RPC use the same preparation callback. Each warm-up starts at most one checkout, settles it even on refresh failure, and isolates preparation failure from refresh success. Missing refs remain fetch-first. SSH and folder repositories do not enter local preparation; WSL routing is preserved. No UI, draft composer, hook/profile/agent startup, pool limit, Git-worker preference, wire, or persistence change.

Stacked on #18967 (which follows #18951), independent of parked draft-composer PR #18876. No merge authorized.

Validation:

  • 20 focused prefetch/runtime/OID tests passed; 44 pool and real-Git tests passed; 49 local/WSL/SSH routing and updated prefetch tests passed. These groups overlap.
  • Held-refresh regression fails on the old implementation and passes here, for native and WSL options.
  • Real Git tests move the remote ref before and after reset; finalized HEAD/content match the refreshed commit and the tree is clean.
  • Node typecheck, formatting, lint, and diff checks passed. Independent review and elegance pass found no required correction.
  • A 23,608-file real-Git scheduling probe with an injected two-second fetch delay measured serial 7.73–8.17 s versus overlap 4.47–4.89 s. Local fetch source and potentially warm filesystem caches; this is not packaged app timing or a universal speedup claim. Every probe checkout was clean and removed.

Full CI passed at 64248b4893c, including all eight test shards, native/WSL routing tests, Git compatibility, typecheck, static analysis, and Linux/Windows packaging.

The composer-free combined trial at 6d989819c5e integrates these backend PRs onto main 681119dc05b. Full typecheck, 60 focused tests, and background Electron existing Create-flow validation passed; screenshot inspected. Packaged macOS verification passed; see the current trial below.

Assessed merge risk: low-to-moderate. Packaged macOS verification passed. No proven correctness issue. Live Windows/WSL concurrent fetch/checkout remains unverified.

User-facing negative trade-offs:

  • Fetch and checkout can compete for disk I/O while running together.
  • A large upstream update can require substantial additional checkout work.
  • An early preparation failure falls back to normal Create; no retry is added within that warm-up.

Current composer-free trial: v1.4.198-adhoc.20260906024508, source 6d989819c5ef5d85b8253d763450de9df4c88d57, includes current main 681119dc05b (including A), cancellation #18951, background stale cleanup #18967, and fetch/checkout overlap #18998. Parked draft composer #18876 is excluded.

Combined full typecheck, 60 focused tests, and background Electron existing Create flow passed. Downloaded ARM64 DMG passed SHA512/size, extraction identity, exact source/version, code signature and notarization. The actual background packaged app passed immediate Create, prepared Create, cancellation without additional workspaces/terminals, and real shell input/output. No draft editor appeared. Owned workspaces were clean and removed, terminal inventory returned to zero, the owned app stopped, and its remaining owned detached preparation was removed.

On the 23,608-file fixture: immediate Create took 7.317 s to observed selection; a second Create after nine seconds of composer dwell took 683 ms. Backend spans were 6.644 s and 515 ms. These are individual potentially warm-cache samples, with a blank terminal and no setup hook. They demonstrate the prepared path, not a universal cold speedup or agent readiness. Screenshots inspected. Windows release packaging is still running; no live Windows/WSL UI validation.


Post-review measurement (readiness review, 2026-09-05) — supersedes the injected-delay numbers above

The 7.7–8.2 s → 4.5–4.9 s (~41%) figure quoted above is an artifact of the injected two-second fetch delay and should not be read as the real-world win. Re-measured against a real GitHub fetch and against the degenerate cases, using a private hardlinked clone of the 23,608-file fixture (macOS, warm cache). Totals are fetch‖checkout wall time; the finalize reset is reported separately.

Case Serial — median (min–max) Overlap — median (min–max)
Real GitHub fetch (5 runs, ref moves 138 commits) 4.88 s (4.48–12.43) 4.34 s (3.25–6.85)
Instant / already up to date (10 runs) 3.78 s (3.27–4.56) 3.16 s (3.04–4.33)
Fetch fails, nonexistent remote (5 runs) 4.01 s (3.18–4.86) 3.40 s (3.00–6.23)

A real single-ref fetch is only 0.5–1.3 s, so the saving is ≈0.5 s, not 3.3 s. The win scales with fetch latency; on a fast link it is small. The instant-fetch control shows no regression. The failure case exits 128 every run with no hang, and the resulting tree was correct and clean every run. One 12.4 s serial outlier (11.1 s checkout) reflects OS cache eviction noise.

Known trade-off: stale-ref start shifts reset work onto the Create path

The checkout now starts at the stale refs/remotes/origin/<base> (src/main/worktree-create-base-prefetch.ts:91-94). When the fetch actually moves the ref, finalizePreparedWorktree (src/main/git/worktree-create-preparation.ts:237-242) runs a second reset --hard at Create time — measured 0.48–0.84 s for a 138-commit / 1032-file drift. The previous code prepared after the fetch, keeping that reset off the critical path.

Net effect: faster when the user clicks Create before warm-up finishes; roughly parity end-to-end (4.96 s vs 4.88 s) when they click after warm-up and the ref moved. A follow-up could re-reset the pooled entry once the refresh resolves, but that touches pool/claim lifecycle and was left out of this PR.

Overlap correctness: proven, not assumed

  • A half-updated ref is impossible. Git ref writes are lock+rename atomic. Hammered empirically: 4 concurrent readers running rev-parse against 954 update-ref writes with periodic pack-refs (forcing loose↔packed transitions) produced 0 torn or empty reads across 4,271 reads.
  • The worktree is always at the intended commit. Both consumers await the shared refresh promise before claiming a preparation (src/main/ipc/worktree-remote.ts:2660, src/main/runtime/runtime-local-git-worktree-create.ts:91), and finalizePreparedWorktree re-resolves the base and resets on mismatch. All 40 probe runs ended with finalHeadMatchesTarget && clean && treeReadable, including 5 where the ref genuinely moved mid-overlap.
  • Fetch failure returns {ok:false} and never rejects; create proceeds on the existing local ref exactly as pre-PR, gated by hadLocalBaseRef. The prepared checkout sits at that same ref, matching cold-create output.
  • No unhandled rejection: .catch(() => {}) wraps Promise.resolve().then(...) so sync throws are caught too, and finally { await preparation } settles it before any refresh error propagates.
  • No lock contention: fetch touches refs/remotes/*.lock / packed-refs.lock / objects; worktree add + reset --hard touch .git/worktrees/<id>/{HEAD,index.lock,locked}. The GIT_FETCH_SKIP_AUTO_MAINTENANCE_CONFIG_ARGS -c prefix is untouched, and checkout runs under withRepoRefMaintenancePaused.
  • Git 2.25 baseline: this PR introduces no new Git subcommands or flags, so no GitCapabilityCache entry is needed.
  • SSH / folder / WSL: SSH repos exit via prefetchRemoteWorktreeCreateBase before a preparation exists; folder repos return early. Both covered by new tests; WSL options threaded unchanged.

Residual risk

  • Windows/WSL concurrent fetch + reset --hard on the same repo is unverified live.
  • Disk I/O contention on slow disks or a cold cache could erode the overlap gain; not measured cold.

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

✅ No new issues found.

Reviewed changes

  • Overlap base refresh with prepared checkout — prefetchWorktreeCreateBase gains a prepareCheckout callback; when the remote-tracking ref already exists locally, prefetchLocalWorktreeCreateBase starts the checkout before awaiting getOrStartRemoteTrackingBaseRefresh instead of after, so Create can reuse more warm-up work.
  • Shared prepare wrapper — dedups to one checkout per warm-up, swallows checkout failures with .catch(() => {}), and is awaited in a finally so speculative work settles even when refresh fails.
  • Caller simplification — both the desktop IPC handler and the runtime RPC host now pass prepareCheckout: (base) => prepareWorktreeCreateForRepo(store, repo, base) rather than awaiting it after the prefetch returns, preserving the prior error-swallowing semantics.
  • Test coverage — overlap/held-refresh unit tests, a real-Git finalize-revalidation test that moves the ref before and after reset, and routing tests confirming SSH and folder repos skip local preparation.

The correctness hinge is finalizePreparedWorktree, which re-resolves the requested base and reset --hards the prepared checkout onto the refreshed commit, so a checkout keyed on the pre-refresh (stale) base is retargeted or rejected (cold create) at claim time. The real-Git test pins this behavior for both "base moved before reset" and "base moved after reset".

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker changed the base branch from nwparker/unblock-create-from-stale-reclamation to main September 6, 2026 05:30
Resolve squash-rewrite conflicts from #18951/#18967: keep main's
cancellation test split and fs.watch null-filename fix, plus this
branch's fetch/checkout overlap real-git tests.
@coderabbitai

coderabbitai Bot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 120ac30b-8f15-4746-977b-46dcbb56522b

📥 Commits

Reviewing files that changed from the base of the PR and between a63a457 and a9e5ab6.

📒 Files selected for processing (6)
  • src/main/git/worktree-create-preparation-real-git.test.ts
  • src/main/ipc/worktrees/create/register-worktree-prefetch-handler.ts
  • src/main/runtime/orca-runtime-create-base-prefetch.test.ts
  • src/main/runtime/orca-runtime-get-worktree-terminal-provisioning-host.ts
  • src/main/worktree-create-base-prefetch.test.ts
  • src/main/worktree-create-base-prefetch.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

Worktree base prefetch now accepts a checkout-preparation callback. It starts preparation at the correct point, runs it once, suppresses preparation errors, and waits for completion around remote-tracking refreshes. IPC and runtime callers now provide this callback. Tests cover local, WSL, SSH, folder, refresh-failure, and refreshed-base finalization scenarios.

Merge Risk: ⚪ Minimal · up to a9e5a

Worktree checkout preparation now overlaps eligible local base refreshes while preserving finalization against the refreshed commit. The supplied coverage indicates preparation failures and refresh failures are handled as intended, with no current merge-blocking risk identified.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides detailed scope, rationale, testing, measurements, risks, and validation, but it does not follow the required template structure. It lacks an explicit linked issue, Visual Proo… Reformat the description using all template headings. Add an explicit linked issue in the required format, state N/A with a reason or attach visual proof, complete the Agent skill upstream boundary and checklist items, and include any appli…
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 3 functions across 6 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary change: overlapping base refresh with prepared checkout.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description provides detailed scope, rationale, testing, measurements, risks, and validation, but it does not follow the required template structure. It lacks an explicit linked issue, Visual Proof section with N/A or attachments, Agent skill upstream boundary confirmation, and completed checklist items.

Resolution

Reformat the description using all template headings. Add an explicit linked issue in the required format, state N/A with a reason or attach visual proof, complete the Agent skill upstream boundary and checklist items, and include any applicable AI Disclosure and Review content.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@nwparker
nwparker merged commit 15dabf8 into main Sep 6, 2026
27 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…#18998)

* Stop obsolete worktree preparations when evicted or expired

* Let worktree preparation proceed during stale reclamation

* Verify creation during stalled stale worktree reclamation

* Preserve preparation ownership until Git removal starts

* test: keep artifact share fixtures unexpired across calendar dates (stablyai#18955)

* perf(worktree): overlap base refresh with prepared checkout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant