Skip to content

perf(worktrees): avoid auto-maintenance in create fetches - #8039

Merged
nwparker merged 4 commits into
mainfrom
nwparker/faster-create
Jul 10, 2026
Merged

nwparker merged 4 commits into
mainfrom
nwparker/faster-create

Conversation

@nwparker

@nwparker nwparker commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • keep exact-base worktree refreshes from waiting on unrelated opportunistic Git maintenance
  • preserve the existing exact refspec, 30-second freshness window, timeout, failure fallback, and normal full-fetch maintenance behavior
  • carry the latency-sensitive hint through the SSH provider/relay as an optional, validated field so old/new relay pairings remain compatible

The intermittent delay was not the network transfer: a traced real fetch negotiated and refreshed the requested ref in about 0.37s, then remained blocked in git maintenance run --auto / reflog expire --all. The same exact fetch with per-command maintenance disabled completed in 0.42s instead of 26.65s, with the remote-tracking SHA unchanged.

ELI5

Before Orca creates a worktree from a base such as origin/main, it asks Git to update Orca's local pointer to that remote branch. This required step makes sure the new worktree starts from the current remote commit.

Sometimes that one git fetch command did two separate jobs:

  1. Required: contact the remote and update the exact base-branch pointer.
  2. Optional: if Git decided the repository had crossed a housekeeping threshold, clean up old Git logs and repository metadata.

Orca must wait for the whole command to exit, so the UI continued to say “Fetching base branch…” during the optional cleanup—even though the base branch itself was already updated. That explains why the delay was intermittent: Git only starts automatic housekeeping when its thresholds are reached. In the traced slow case, the required remote work finished in about 0.37s and the later housekeeping caused nearly all of the remaining 26.65s.

This PR tells Git, for this one latency-sensitive create-time fetch: update the exact branch pointer, but do not start optional automatic housekeeping inside this command. It does not skip the required fetch, accept a stale branch, change which branch is fetched, or change what happens when the fetch fails. Normal fetch/pull operations and explicit or scheduled Git maintenance can still perform housekeeping.

Git version and platform compatibility

Orca's worktree feature requires Git 2.5 or newer. The final command covers every worktree-capable Git generation:

  • Git 2.5–2.28: -c and gc.auto=0 are supported. These versions safely ignore the newer, syntactically valid maintenance keys.
  • Git 2.29.x: this transitional release starts git maintenance run --auto before maintenance.auto=false became a top-level gate. gc.auto=0 disables its GC task and maintenance.commit-graph.auto=0 disables its only other automatic task. Git still starts one fast no-op maintenance process, but performs no housekeeping task.
  • Git 2.30 and newer: maintenance.auto=false prevents the automatic maintenance process from starting. The other two keys remain valid and harmless.

This was verified with locally built official Git 2.5.0 and Git 2.29.3 sources, Homebrew Git 2.44, and Apple Git 2.50.1. On Git 2.5.0, the three-key command fetched the exact remote SHA and successfully created a linked worktree from it. On Git 2.29.3, a trace first reproduced the commit-graph task with the two-key command, then showed the final three-key command running no maintenance task.

The arguments are passed as an argv array, not shell text, so no platform-specific quoting was added. Relay bundles build for Linux, macOS, Windows, and WSL on the supported x64/arm64 targets. Local, WSL, SSH, and mixed old/new relay behavior is covered by tests and static routing review.

Trade-offs

There is no known end-user correctness or freshness trade-off. There are deliberate scheduling and compatibility details:

  • Maintenance is deferred, not eliminated. A later normal fetch/pull, explicit maintenance command, or scheduled Git maintenance may perform the same cleanup. This moves optional work out of the interactive worktree-create path; it does not guarantee that the repository will never pay that maintenance cost elsewhere.
  • Cleanup can happen later than it otherwise would. If a repository only ever receives these exact create-time fetches and never runs another maintenance-eligible Git operation, old reflog/metadata cleanup may be postponed and the repository metadata may remain larger for longer. Orca's ordinary fetches still allow automatic maintenance, and this PR does not disable explicit or scheduled maintenance.
  • The speedup only applies when auto-maintenance was the delay. If Git was not going to run housekeeping, this change has little or no effect. The 26.65s → 0.42s measurement is a reproduced slow case, not a guarantee that every create will take 0.42s.
  • Git 2.29 keeps one fast no-op process. Its version-specific behavior cannot avoid starting git maintenance, but the final command prevents both available tasks from running.
  • An old SSH relay preserves correctness but not the speedup. Older relays ignore the optional new field and perform the original fetch behavior until the relay is upgraded. An old client talking to a new relay also keeps the original behavior.
  • Explicit user fetch configuration remains honored. For example, fetch.writeCommitGraph=true is an explicit request inside fetch itself, not opportunistic auto-maintenance. Overriding it would create a user-configuration trade-off, so this PR intentionally does not.

What is specifically not traded away: the exact remote ref update, the existing 30-second freshness rule, network/authentication behavior, configured SSH/WSL routing, timeouts, failure handling, or the commit SHA used to create the worktree.

Screenshots

No visual change.

Testing

  • pnpm lint — branch checks pass; a latest-main local rebase separately exposed an unrelated Japanese localization mismatch in files untouched by this PR
  • pnpm typecheck
  • pnpm test — the full required GitHub verify check passed on the final PR head
  • pnpm build — pnpm build:relay passed for linux-x64, linux-arm64, darwin-x64, darwin-arm64, win32-x64, win32-arm64, and WSL
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

Focused final regression suite (952 passed):

pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/fetch-remote-cache.test.ts src/main/runtime/orca-runtime.test.ts src/main/ipc/worktrees.test.ts src/main/providers/ssh-git-provider.test.ts src/relay/git-handler.test.ts

Windows/WSL Git runner suite: 26 passed.

Performance/correctness trace:

  • before: git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main — 26.65s total; remote negotiation/ref consumption finished in about 0.37s and the remainder was auto-maintenance
  • after: git -c maintenance.auto=false -c maintenance.commit-graph.auto=0 -c gc.auto=0 fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main — 0.42s in the reproduced slow repository
  • refs/remotes/origin/main resolved to the same SHA before and after the optimized command
  • none of the maintenance settings were persisted in repository config
  • isolated Electron validation visibly created and opened the exact-base worktree in 277ms; Git Trace2 recorded the final argv, no modern maintenance child, and matching remote/tracking/worktree SHAs

AI Review Report

Two adversarial review/fix rounds covered the create hot path, fetch cache, WSL routing, SSH provider/relay protocol, Git version boundaries, and relevant tests. The review checked:

  • exact remote-base freshness is still required before git worktree add; there is no stale-ref shortcut or longer cache window
  • ordinary full remote fetches retain automatic maintenance, with a dedicated regression assertion
  • no polling, additional application subprocess, fanout, unbounded cache, listener, or lifecycle work was added
  • macOS/Linux/Windows use fixed argv rather than shell syntax; WSL keeps the existing distro and configured-SSH routing
  • SSH's new field is optional for old/new relay compatibility and only a boolean is accepted by the relay

The first implementation used --no-auto-gc, which is unavailable on older Git versions Orca tolerates. It was replaced with invocation-scoped config. A later adversarial pass then reproduced Git 2.29's transitional behavior and added maintenance.commit-graph.auto=0. Fresh Claude and Codex reviewers both returned no issues on the final three-key implementation.

Security Audit

  • the new Git config argv is a fixed constant; no user-controlled value reaches -c and no shell is involved
  • existing remote, branch, ref, credential, timeout, and SSH-command validation remains unchanged
  • the relay validates the optional maintenance hint as a boolean and retains exact remote/ref matching checks
  • no paths, auth data, secrets, dependencies, permissions, or persistent Git config were added or changed

Notes

  • Root cause: Git's threshold-triggered repository housekeeping occasionally ran after the exact base ref was already current, explaining why the delay appeared only sometimes.
  • Automatic maintenance is suppressed only for latency-sensitive create-base refreshes. Normal fetch/pull paths and explicit/scheduled Git maintenance remain unchanged.
  • A live throwaway Linux SSH smoke could not run because Docker Desktop's backend is non-responsive; it was not force-restarted to avoid disrupting user containers. Real relay Git integration tests, provider serialization tests, SSH create tests, and all relay target builds pass.
  • No live Windows run was available. Cross-platform argv, old-Git compatibility, WSL option propagation, Windows/WSL runner tests, and win32 relay builds were verified.

Git's opportunistic maintenance can keep an already-complete exact-base fetch open for seconds. Disable it per command for create-base refreshes only, leaving ordinary fetch maintenance and exact-ref freshness unchanged.
@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Added optional auto-maintenance suppression to remote-tracking fetches. SSH provider calls now forward the option through the relay, which validates it and prepends Git configuration flags when enabled. Worktree base refreshes pass the option, runtime fetch construction uses shared arguments, and related tests were updated to recognize and assert the new command shape.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Title check ✅ Passed The title clearly and concisely summarizes the main change: skipping auto-maintenance during worktree create fetches.
Description check ✅ Passed The description follows the required template and includes summary, screenshots, testing, AI review, security audit, and notes.
✨ Finishing Touches
📝 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.

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

🧹 Nitpick comments (2)
src/main/ipc/worktree-remote.ts (1)

480-484: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a "Why" comment for the maintenance-skip flag.

The behavior is non-obvious (opportunistic git maintenance/gc disabled only for this fetch). As per coding guidelines, "When writing or modifying code driven by a design doc or another non-obvious constraint, add a brief comment explaining why the code behaves that way."

📝 Proposed comment addition
-    () =>
-      provider.fetchRemoteTrackingRef(repo.path, base.remote, base.branch, base.ref, {
-        skipAutoMaintenance: true
-      })
+    () =>
+      // Why: this exact-base refresh sits on the create hot path; skip
+      // opportunistic maintenance/gc for this fetch only instead of mutating
+      // repo config (see git-fetch-auto-maintenance.ts).
+      provider.fetchRemoteTrackingRef(repo.path, base.remote, base.branch, base.ref, {
+        skipAutoMaintenance: true
+      })

Source: Coding guidelines

src/main/runtime/orca-runtime.ts (1)

14624-14631: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a "Why" comment for the unconditional maintenance-skip here.

This spot always disables maintenance.auto/gc.auto for the exact-base refresh, unlike the SSH path which gates it behind an opt-in flag. A brief comment would clarify that this function is scoped to the create-path base-ref resolution only, per coding guidelines' requirement to explain non-obvious, design-driven behavior.

📝 Proposed comment addition
       return gitExecFileAsync(
-        [
+        // Why: this refresh backs worktree-create base-ref resolution only;
+        // skip opportunistic maintenance/gc for this fetch to keep create fast.
+        [
           ...GIT_FETCH_SKIP_AUTO_MAINTENANCE_CONFIG_ARGS,
           'fetch',
           '--no-tags',
           base.remote,
           `+refs/heads/${base.branch}:${base.ref}`
         ],

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 8899a7c8-6885-434f-aceb-961cad348f7f

📥 Commits

Reviewing files that changed from the base of the PR and between 830024d and 7a1afb5.

📒 Files selected for processing (9)
  • src/main/ipc/worktree-remote.ts
  • src/main/ipc/worktrees.test.ts
  • src/main/providers/ssh-git-provider.test.ts
  • src/main/providers/ssh-git-provider.ts
  • src/main/runtime/fetch-remote-cache.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/relay/git-handler.test.ts
  • src/relay/git-handler.ts
  • src/shared/git-fetch-auto-maintenance.ts

@nwparker

Copy link
Copy Markdown
Contributor Author

Compatibility audit complete.

  • Fixed the Git 2.29 transitional maintenance gap with maintenance.commit-graph.auto=0.
  • Exercised the final command on official Git 2.5.0 and 2.29.3 builds, plus Git 2.44 and Apple Git 2.50.1.
  • Verified exact SHA preservation, non-persistent config, local/WSL/SSH and mixed-relay behavior, 952 affected tests, 26 Windows/WSL runner tests, all relay OS/architecture builds, and an isolated Electron create flow.
  • Fresh Claude and Codex review passes are clean; final CodeRabbit and required verify checks pass.

Remaining manual gaps are a live Windows run and Docker SSH smoke; fixed argv routing, Windows/WSL tests, SSH integration tests, and win32/Linux relay builds cover those paths proportionally. Merging with squash.

@nwparker
nwparker merged commit 2622419 into main Jul 10, 2026
2 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
)

* perf(worktrees): avoid auto-maintenance in create fetches

Git's opportunistic maintenance can keep an already-complete exact-base fetch open for seconds. Disable it per command for create-base refreshes only, leaving ordinary fetch maintenance and exact-ref freshness unchanged.

* docs(worktrees): explain create fetch maintenance scope

* test(worktrees): account for fetch config prefixes

* fix(worktrees): cover Git 2.29 auto maintenance
brennanb2025 added a commit that referenced this pull request Oct 21, 2026
…ontroller (#30654)

* fix(github): PR conflict previews fetch the base branch through the fetch controller

The conflict summary on a PR card spawned its own `git fetch origin <base>`,
outside RuntimeRemoteFetchController: it refetched a base a worktree create
had just refreshed (and vice versa), ran git's auto-maintenance in the
background, and never armed the idle loose-ref sweep.

It now asks the runtime's controller for the exact-base refresh creates
already use (same argv, per-remote queue, dedupe and freshness), waiting at
most the old 10 s before falling back to the local ref. The runtime registers
its controller at construction, since the IPC and poller paths have no
runtime handle.

Also corrects the controller comment that claimed every fetch skips
auto-maintenance: full fetches keep it on purpose (#8039).

* test(github): read the mocked fetch's WSL option without a type assertion

* test(github): give the conflicting fallback-lookup test a git mock for its conflict summary

* test(github): check WSL routing without duplicating fetch policy

* fix(git): bound preview fetch ownership without cancelling create

* Preserve repository identity after preview cancellation
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