Skip to content

Fix fork PR/MR worktree creation race via durable review-head refs - #10429

Merged
AmethystLiang merged 8 commits into
mainfrom
fix-fork-pr-fetch-head-race
Jul 24, 2026
Merged

AmethystLiang merged 8 commits into
mainfrom
fix-fork-pr-fetch-head-race

Conversation

@AmethystLiang

Copy link
Copy Markdown
Contributor

Summary

Fix a race condition in fork PR/MR worktree creation where concurrent git fetch operations clobber the shared FETCH_HEAD ref, causing the worktree to resolve to the wrong commit (typically the default branch tip instead of the PR/MR head).

The fix replaces reliance on the transient FETCH_HEAD with durable per-review refs (refs/orca/pull/<N> and refs/orca/merge-requests/<N>) that persist between resolve and create operations, preventing concurrent fetches from interfering with each other.

Changes

  • New shared utilities: review-head-tracking-ref.ts for durable ref paths and preferred-git-remote.ts for intelligent remote selection (prefer origin)
  • New narrow fetch RPCs in SSH relay: git.fetchGitHubPullRequestHead and git.fetchGitLabMergeRequestHeadRef (versioned to detect old relays)
  • PR/MR resolution now fetches into dedicated refs and resolves from them instead of FETCH_HEAD
  • Compare-base fetch failures degrade gracefully: base is retained if the local tracking ref already resolves, dropped only on true missing/absent-ref errors
  • SSH provider adds fetchGitHubPullRequestHead() and updates fetchGitLabMergeRequestHead() with old-relay detection and reconnect prompts

Testing

  • New test file pr-start-point-compare-base.test.ts covering fork PR compare-base scenarios under transient fetch failures and missing bases
  • Existing tests updated to verify durable ref usage and rev-parse against new ref paths instead of FETCH_HEAD
  • Tests cover local, SSH, and cross-repository scenarios with old relay compatibility fallback
  • Git binary compatibility test verifies fetch commands work across Git versions

Notes

  • Old SSH relays without new RPC methods will trigger method-not-found errors, prompting users to reconnect and deploy the latest relay
  • Compare-base detection now avoids silent Source Control diffs against the worktree itself by keeping a base whenever the local tracking ref resolves

When creating a fork PR/MR worktree, concurrent `git fetch origin` operations
clobber the shared FETCH_HEAD, causing the wrong commit to be checked out.
Fetch PR/MR heads into dedicated per-review refs (`refs/orca/pull/<N>`,
`refs/orca/merge-requests/<N>`) that persist and isolate each head from other
fetches. Gracefully keep the compare-base when the fetch fails but the local
ref already exists, avoiding silent fallback to the wrong branch on transient
network errors.
@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The change introduces durable local refs for GitHub pull request and GitLab merge request heads. Local repositories fetch review heads through explicit refspecs into refs/orca/pull/<number> and refs/orca/merge-requests/<iid>, while connected SSH repositories delegate to provider RPCs. GitHub and GitLab start-point resolution now reads these dedicated refs and conditionally preserves locally resolvable compare bases when remote fetches fail. Remote selection is centralized through resolveGitHubReviewHeadRemote and pickPreferredGitRemote, with preference for origin. Relay and SSH provider tests cover RPC registration, input validation, timeout enforcement, and compatibility error handling for older relays. Runtime, worktree, and supporting test infrastructure are updated to wire the new fetching and resolution logic end-to-end.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers summary, changes, testing, and notes, but omits required Screenshots, AI Review Report, and Security Audit sections. Add the missing template sections, including screenshots/no visual change, the full testing checklist, AI review details, and a security audit summary.
Docstring Coverage ⚠️ Warning Docstring coverage is 35.29% which is insufficient. The required threshold is 80.00%. 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 summarizes the main change: fixing fork PR/MR worktree creation races with durable review-head refs.
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.

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.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/main/github/pr-start-point.ts (2)

93-127: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Compare-base fallback logic is duplicated in orca-runtime.ts.

compareBaseRefResolvesLocally/fetchCompareBaseRef here mirror the same pair in resolveManagedMrBase (src/main/runtime/orca-runtime.ts) almost line-for-line, including the same warning shape and "keep base only if locally resolvable" trade-off. Since both needed the identical fix in this PR, a shared helper (parameterized by ref/log-field names) would reduce the risk of the two copies drifting apart on the next bugfix.


129-152: 🚀 Performance & Scalability | 🔵 Trivial

Durable per-PR refs are never pruned.

refs/orca/pull/<N> is created but never removed after use, so long-lived repos that resolve/create many PR worktrees over time will accumulate refs under refs/orca/pull/* indefinitely. Worth a lightweight cleanup/gc strategy (e.g., prune on worktree removal or periodic sweep) so this durability guarantee doesn't turn into unbounded ref growth.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 43e74992-8015-41ad-94d1-d00ba99d3c27

📥 Commits

Reviewing files that changed from the base of the PR and between 17959a2 and 38d5693.

📒 Files selected for processing (17)
  • src/main/github/pr-head-tracking-ref.test.ts
  • src/main/github/pr-head-tracking-ref.ts
  • src/main/github/pr-start-point-compare-base.test.ts
  • src/main/github/pr-start-point.test.ts
  • src/main/github/pr-start-point.ts
  • src/main/ipc/worktrees.test.ts
  • src/main/ipc/worktrees.ts
  • src/main/providers/ssh-git-provider.test.ts
  • src/main/providers/ssh-git-provider.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/relay/git-handler.test.ts
  • src/relay/git-handler.ts
  • src/shared/git-binary-compatibility.test.ts
  • src/shared/preferred-git-remote.test.ts
  • src/shared/preferred-git-remote.ts
  • src/shared/review-head-tracking-ref.ts

Comment thread src/main/github/pr-head-tracking-ref.ts Resolved
Comment thread src/relay/git-handler.ts Resolved
Prevent PR/MR creation from hanging when a remote is stalled or
unreachable. Both GitHub and GitLab head fetches now enforce a
60-second timeout, matching the bound used in the create-path
fetch. Durable refs (refs/orca/pull/*, refs/orca/merge-requests/*)
decouple the ref from FETCH_HEAD, preserving legacy client semantics.
PR checks merge into main, which recently changed PowerShell launch args
(cwd restore after profiles) and sparse-checkout detection (require
core.sparseCheckout). Derive PowerShell spawn args from the production
resolver, mock the sparse config flag, reset shared worktree list scan
cache between tests, and stop requiring floating polls to avoid getRepos
hydration.

@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 (1)
src/main/ipc/pty.test.ts (1)

231-245: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Keep the expected PowerShell argv independent of the implementation.

powerShellOsc133ArgsForCwd() derives the expected arguments by calling resolveWindowsShellLaunchArgs from src/main/providers/windows-shell-args.ts. If that resolver regresses, this test’s expected value changes with it and can still pass. Keep an explicit fixture here and test the resolver’s exact output separately.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: da86d828-66dd-41be-85d1-c49a21cfb4cb

📥 Commits

Reviewing files that changed from the base of the PR and between ffe735c and 896ad81.

📒 Files selected for processing (3)
  • src/main/git/remove-worktree.test.ts
  • src/main/ipc/pty.test.ts
  • src/main/runtime/orca-runtime.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/runtime/orca-runtime.test.ts

AmethystLiang and others added 4 commits July 24, 2026 12:08
- Unify PR review-head remote selection: local and SSH GitHub paths share
  resolveGitHubReviewHeadRemote, which prefers the remote mapping to the
  hosting GitHub project (upstream before origin, matching work-item/API
  candidate order) so contributor clones fetch refs/pull from the repo
  that actually hosts the PR.
- Soft-keep durable review heads: when the PR/MR head fetch fails but
  refs/orca/pull/<N> / refs/orca/merge-requests/<iid> still resolves,
  keep the pinned SHA (warn) instead of failing resolve, mirroring the
  compare-base fallback. Extracted shared compare-base soft-keep into
  compare-base-ref-fetch.ts.
- Extract fetchGitLabMergeRequestHeadRef (local + SSH) parallel to the
  GitHub helper; bound its local fetch with the shared 60s timeout.
- Share relay-style fetch validation (positive safe-integer id, remote
  not starting with "-") between relay and local helpers via
  review-head-tracking-ref.ts; move REVIEW_HEAD_FETCH_TIMEOUT_MS there.
- Drop the githubPullRequestHeadLocalRef re-export; resolve head SHAs via
  rev-parse --verify <ref>^{commit}.
- Add GitLab anti-FETCH_HEAD regression test plus durable-head soft-keep
  and remote-selection unit tests.

Co-authored-by: Orca <[email protected]>
Main's headless tab hydrate (#9343) skips worktree keys whose repo is not
in getRepos. Retirement tests that rebuild mobile tabs from a persisted
session now advertise the fixture repo as live so PR Checks merge stays green.
Main's SSH external-image wiring (#10323) pushed RichMarkdownEditor.tsx over
the 400-line tsx budget, failing PR Checks lint on every merge into main.
Move the props type into a sibling module so the component stays under the
limit without disabling max-lines.

@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 (1)
src/main/runtime/orca-runtime-terminal-retirement.test.ts (1)

24-34: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Avoid casting the test store to never.

runtimeStore returns an object but advertises never, so TypeScript cannot validate that this fixture still satisfies the OrcaRuntimeService storage contract. Use the constructor’s store type or a narrow explicit test-double interface, keeping any unavoidable cast at one boundary.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3b387be0-5395-4893-b399-b7960a3548fe

📥 Commits

Reviewing files that changed from the base of the PR and between 6e3ebac and c8bb75c.

📒 Files selected for processing (7)
  • src/main/ipc/worktrees.test.ts
  • src/main/ipc/worktrees.ts
  • src/main/runtime/orca-runtime-terminal-retirement.test.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/renderer/src/components/editor/RichMarkdownEditor.tsx
  • src/renderer/src/components/editor/rich-markdown-editor-props.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/main/runtime/orca-runtime.ts
  • src/main/ipc/worktrees.test.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/ipc/worktrees.ts

Embed remote name + URL hash into refs/orca/pull|merge-requests refs to prevent soft-keep from serving wrong project's PR/MR when FETCH_HEAD is clobbered by concurrent fetch. Fetch functions now return the written ref path (writer-authoritative) so callers rev-parse exactly what was fetched, not re-derive identity. Soft-keep only applies to transient errors (timeout, network); fails hard on missing refs, auth failures, and stale relay. Relay returns localRef so client avoids re-hashing (URL normalization can disagree).
@AmethystLiang
AmethystLiang merged commit 7720815 into main Jul 24, 2026
2 of 3 checks passed
brennanb2025 added a commit that referenced this pull request Jul 24, 2026
…10443)

#9343 broke two contracts at once and #10437 fixed both, but neither is
asserted: #10429 repaired the failing tests by deleting the poll assertion and
by handing the retirement store a live repo, so a revert would land silently.

Restore `expect(getRepos).not.toHaveBeenCalled()` on the floating-tab poll, and
add a hydrate case for a store that cannot report repos. Verified both fail
against the pre-#10437 code: the poll assertion reports getRepos "called 2
times", and the hydrate case returns [] instead of the persisted tab.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tablyai#10429)

* Fix fork PR/MR worktree creation race via durable review-head refs

When creating a fork PR/MR worktree, concurrent `git fetch origin` operations
clobber the shared FETCH_HEAD, causing the wrong commit to be checked out.
Fetch PR/MR heads into dedicated per-review refs (`refs/orca/pull/<N>`,
`refs/orca/merge-requests/<N>`) that persist and isolate each head from other
fetches. Gracefully keep the compare-base when the fetch fails but the local
ref already exists, avoiding silent fallback to the wrong branch on transient
network errors.

* Bound PR/MR head fetches with 60s timeout

Prevent PR/MR creation from hanging when a remote is stalled or
unreachable. Both GitHub and GitLab head fetches now enforce a
60-second timeout, matching the bound used in the create-path
fetch. Durable refs (refs/orca/pull/*, refs/orca/merge-requests/*)
decouple the ref from FETCH_HEAD, preserving legacy client semantics.

* test: align CI expectations with main PowerShell/sparse regressions

PR checks merge into main, which recently changed PowerShell launch args
(cwd restore after profiles) and sparse-checkout detection (require
core.sparseCheckout). Derive PowerShell spawn args from the production
resolver, mock the sparse config flag, reset shared worktree list scan
cache between tests, and stop requiring floating polls to avoid getRepos
hydration.

* Address review follow-ups on durable review-head refs

- Unify PR review-head remote selection: local and SSH GitHub paths share
  resolveGitHubReviewHeadRemote, which prefers the remote mapping to the
  hosting GitHub project (upstream before origin, matching work-item/API
  candidate order) so contributor clones fetch refs/pull from the repo
  that actually hosts the PR.
- Soft-keep durable review heads: when the PR/MR head fetch fails but
  refs/orca/pull/<N> / refs/orca/merge-requests/<iid> still resolves,
  keep the pinned SHA (warn) instead of failing resolve, mirroring the
  compare-base fallback. Extracted shared compare-base soft-keep into
  compare-base-ref-fetch.ts.
- Extract fetchGitLabMergeRequestHeadRef (local + SSH) parallel to the
  GitHub helper; bound its local fetch with the shared 60s timeout.
- Share relay-style fetch validation (positive safe-integer id, remote
  not starting with "-") between relay and local helpers via
  review-head-tracking-ref.ts; move REVIEW_HEAD_FETCH_TIMEOUT_MS there.
- Drop the githubPullRequestHeadLocalRef re-export; resolve head SHAs via
  rev-parse --verify <ref>^{commit}.
- Add GitLab anti-FETCH_HEAD regression test plus durable-head soft-keep
  and remote-selection unit tests.

Co-authored-by: Orca <[email protected]>

* test: supply live getRepos for terminal-retirement hydrates

Main's headless tab hydrate (stablyai#9343) skips worktree keys whose repo is not
in getRepos. Retirement tests that rebuild mobile tabs from a persisted
session now advertise the fixture repo as live so PR Checks merge stays green.

* fix(editor): extract RichMarkdownEditor props to stay under max-lines

Main's SSH external-image wiring (stablyai#10323) pushed RichMarkdownEditor.tsx over
the 400-line tsx budget, failing PR Checks lint on every merge into main.
Move the props type into a sibling module so the component stays under the
limit without disabling max-lines.

* Make durable review-head refs remote-identity scoped

Embed remote name + URL hash into refs/orca/pull|merge-requests refs to prevent soft-keep from serving wrong project's PR/MR when FETCH_HEAD is clobbered by concurrent fetch. Fetch functions now return the written ref path (writer-authoritative) so callers rev-parse exactly what was fetched, not re-derive identity. Soft-keep only applies to transient errors (timeout, network); fails hard on missing refs, auth failures, and stale relay. Relay returns localRef so client avoids re-hashing (URL normalization can disagree).

---------

Co-authored-by: Orca <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tablyai#10443)

stablyai#9343 broke two contracts at once and stablyai#10437 fixed both, but neither is
asserted: stablyai#10429 repaired the failing tests by deleting the poll assertion and
by handing the retirement store a live repo, so a revert would land silently.

Restore `expect(getRepos).not.toHaveBeenCalled()` on the floating-tab poll, and
add a hydrate case for a store that cannot report repos. Verified both fail
against the pre-stablyai#10437 code: the poll assertion reports getRepos "called 2
times", and the hydrate case returns [] instead of the persisted tab.
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