diff --git a/packages/host-service/src/runtime/pull-requests/pull-requests.test.ts b/packages/host-service/src/runtime/pull-requests/pull-requests.test.ts index 55551c65075..6b154295b60 100644 --- a/packages/host-service/src/runtime/pull-requests/pull-requests.test.ts +++ b/packages/host-service/src/runtime/pull-requests/pull-requests.test.ts @@ -217,16 +217,22 @@ function makePrNode(pr: { // tsc (no private dot-access) and biome (no bracket-access) both satisfied. function openPullRequestsSweeper(manager: PullRequestRuntimeManager) { const accessible = manager as unknown as { - getCachedOpenPullRequests(repo: { - provider: "github"; - owner: string; - name: string; - url: string; - remoteName: string; - defaultBranch: string | null; - }): Promise; + getCachedOpenPullRequests( + repo: { + provider: "github"; + owner: string; + name: string; + url: string; + remoteName: string; + defaultBranch: string | null; + }, + options?: { bypassCache?: boolean }, + ): { promise: Promise }; }; - return accessible.getCachedOpenPullRequests.bind(accessible); + return ( + repo: Parameters[0], + options?: { bypassCache?: boolean }, + ) => accessible.getCachedOpenPullRequests(repo, options).promise; } // Silences the expected warnings the manager logs on handled failures. @@ -342,6 +348,360 @@ describe("PullRequestRuntimeManager direct checkout PR linking", () => { }); }); +describe("PullRequestRuntimeManager synthetic PR refs", () => { + function setup() { + const db = createRealDb(); + seedProject(db); + seedWorkspace(db, { + id: "ws", + branch: "deleted-feature", + headSha: "abc123", + upstreamOwner: REPO.owner, + upstreamRepo: REPO.name, + upstreamBranch: "refs/pull/42/head", + }); + const paths: string[] = []; + const network = { + offline: false, + headSha: "abc123", + beforeLookup: undefined as (() => Promise) | undefined, + beforeChecks: undefined as (() => Promise) | undefined, + beforeRefs: undefined as (() => Promise) | undefined, + overrideBranch: null as string | null, + branchHeadSha: null as string | null, + }; + const manager = createManager(db, { + readWorkspaceRefs: async (worktreePath) => { + const workspace = getWorkspace( + db, + worktreePath.split("/").at(-1) ?? "", + ); + await network.beforeRefs?.(); + return { + branch: network.overrideBranch ?? workspace?.branch ?? null, + headSha: workspace?.headSha ?? null, + upstream: { + owner: workspace?.upstreamOwner ?? REPO.owner, + name: workspace?.upstreamRepo ?? REPO.name, + branch: + workspace?.upstreamBranch ?? + workspace?.branch ?? + "refs/pull/42/head", + }, + }; + }, + execGh: async (args) => { + if (network.offline) { + throw Object.assign(new Error("Command failed: gh api"), { + stderr: "error connecting to api.github.com", + }); + } + const path = args.find((arg) => arg.startsWith("repos/")) ?? ""; + paths.push(path); + if (path === `repos/${REPO.owner}/${REPO.name}/pulls/42`) { + await network.beforeLookup?.(); + return makePrNode({ + number: 42, + headRef: "deleted-feature", + headSha: network.headSha, + state: "closed", + mergedAt: "2026-05-01T10:00:00Z", + }); + } + if ( + path === `repos/${REPO.owner}/${REPO.name}/pulls` && + network.branchHeadSha + ) { + return [ + makePrNode({ + number: 42, + headRef: "deleted-feature", + headSha: network.branchHeadSha, + }), + ]; + } + if (path?.endsWith("/check-runs")) { + await network.beforeChecks?.(); + return { check_runs: [] }; + } + return []; + }, + }); + return { db, manager, paths, network }; + } + + test("discovers a merged PR by its synthetic ref without an existing link", async () => { + const { db, manager, paths } = setup(); + + await manager.refreshPullRequestsByWorkspaces(["ws"]); + + const [snapshot] = await manager.getPullRequestsByWorkspaces(["ws"]); + expect(snapshot?.pullRequest?.number).toBe(42); + expect(snapshot?.pullRequest?.state).toBe("merged"); + expect(getWorkspace(db, "ws")?.upstreamBranch).toBe("refs/pull/42/head"); + const [history] = await manager.getPullRequestHistoryByWorkspaces(["ws"]); + expect(history?.pullRequests.map((pr) => pr.number)).toEqual([42]); + expect(paths).toContain(`repos/${REPO.owner}/${REPO.name}/pulls/42`); + expect(paths).not.toContain(`repos/${REPO.owner}/${REPO.name}/pulls`); + }); + + test("clears the current checkout link when HEAD changes, keeping its history", async () => { + const { db, manager } = setup(); + await manager.refreshPullRequestsByWorkspaces(["ws"]); + expect(getWorkspace(db, "ws")?.pullRequestId).toBeTruthy(); + + db.update(workspaces) + .set({ headSha: "def456" }) + .where(eq(workspaces.id, "ws")) + .run(); + await manager.refreshPullRequestsByWorkspaces(["ws"]); + + expect(getWorkspace(db, "ws")?.pullRequestId).toBeNull(); + const [history] = await manager.getPullRequestHistoryByWorkspaces(["ws"]); + expect(history?.pullRequests.map((pr) => pr.number)).toEqual([42]); + }); + + test("does not restore an explicitly unlinked synthetic-ref PR", async () => { + const { db, manager } = setup(); + await manager.refreshPullRequestsByWorkspaces(["ws"]); + const prId = getWorkspace(db, "ws")?.pullRequestId; + expect(prId).toBeTruthy(); + + manager.unlinkWorkspacePullRequest("ws"); + await manager.refreshPullRequestsByWorkspaces(["ws"]); + + expect(getWorkspace(db, "ws")?.pullRequestId).toBeNull(); + expect(getWorkspace(db, "ws")?.suppressedPullRequestId).toBe(prId); + }); + + test.each([ + { name: "changed HEAD", headSha: "def456", keepsLink: false }, + { name: "matching HEAD", headSha: "abc123", keepsLink: true }, + { name: "unknown HEAD", headSha: null, keepsLink: true }, + ])("offline refresh with $name", async ({ headSha, keepsLink }) => { + const { db, manager, network } = setup(); + await manager.refreshPullRequestsByWorkspaces(["ws"]); + const prId = getWorkspace(db, "ws")?.pullRequestId; + expect(prId).toBeTruthy(); + + db.update(workspaces).set({ headSha }).where(eq(workspaces.id, "ws")).run(); + network.offline = true; + await withSilencedWarnings(() => + manager.refreshPullRequestsByWorkspaces(["ws"]), + ); + + expect(getWorkspace(db, "ws")?.pullRequestId).toBe(keepsLink ? prId : null); + const [history] = await manager.getPullRequestHistoryByWorkspaces(["ws"]); + expect(history?.pullRequests.map((pr) => pr.number)).toEqual([42]); + }); + + test("does not resolve a different repository's synthetic ref in the base repo", async () => { + const { db, manager, paths } = setup(); + db.update(workspaces) + .set({ upstreamOwner: "fork-owner" }) + .where(eq(workspaces.id, "ws")) + .run(); + + await manager.refreshPullRequestsByWorkspaces(["ws"]); + + expect(getWorkspace(db, "ws")?.pullRequestId).toBeNull(); + expect(paths).not.toContain(`repos/${REPO.owner}/${REPO.name}/pulls/42`); + }); + + test("a failed old project lookup preserves the newer scoped refresh's matching PR link", async () => { + const { db, manager, network } = setup(); + seedPullRequest(db, { + id: "pr-existing", + prNumber: 42, + headBranch: "deleted-feature", + headSha: "abc123", + }); + db.update(workspaces) + .set({ pullRequestId: "pr-existing" }) + .where(eq(workspaces.id, "ws")) + .run(); + const entered = Promise.withResolvers(); + const pending = Promise.withResolvers(); + network.beforeLookup = () => { + entered.resolve(); + return pending.promise; + }; + await withSilencedWarnings(async () => { + const fullRefresh = projectRefresher(manager)(PROJECT_ID); + await entered.promise; + network.beforeLookup = undefined; + network.headSha = "def456"; + db.update(workspaces) + .set({ headSha: "def456" }) + .where(eq(workspaces.id, "ws")) + .run(); + await manager.refreshPullRequestsByWorkspaces(["ws"]); + expect(getPrById(db, "pr-existing")?.headSha).toBe("def456"); + pending.reject(new Error("old lookup failed")); + await fullRefresh; + }); + expect(getWorkspace(db, "ws")?.headSha).toBe("def456"); + expect(getWorkspace(db, "ws")?.pullRequestId).toBe("pr-existing"); + }); + + test("a successful old project lookup does not link a checkout that moved to a different HEAD", async () => { + const { db, manager, network } = setup(); + const entered = Promise.withResolvers(); + const pending = Promise.withResolvers(); + network.beforeLookup = () => { + entered.resolve(); + return pending.promise; + }; + const fullRefresh = projectRefresher(manager)(PROJECT_ID); + try { + await entered.promise; + network.beforeLookup = undefined; + db.update(workspaces) + .set({ headSha: "def456" }) + .where(eq(workspaces.id, "ws")) + .run(); + await manager.refreshPullRequestsByWorkspaces(["ws"]); + expect(getWorkspace(db, "ws")?.pullRequestId).toBeNull(); + } finally { + pending.resolve(); + await fullRefresh; + } + expect(getWorkspace(db, "ws")?.pullRequestId).toBeNull(); + const [history] = await manager.getPullRequestHistoryByWorkspaces(["ws"]); + expect(history?.pullRequests).toEqual([]); + }); + + test("keeps a verified link if a sweep sees a cached PR but cannot read HEAD", async () => { + const { db, manager, network, paths } = setup(); + await manager.refreshPullRequestsByWorkspaces(["ws"]); + const prId = getWorkspace(db, "ws")?.pullRequestId; + expect(prId).toBeTruthy(); + seedWorkspace(db, { + id: "other", + branch: "other", + upstreamOwner: REPO.owner, + upstreamRepo: REPO.name, + }); + network.offline = true; + db.update(workspaces) + .set({ headSha: null }) + .where(eq(workspaces.id, "ws")) + .run(); + await withSilencedWarnings(async () => { + await manager.refreshPullRequestsByWorkspaces(["other"]); + await projectRefresher(manager)(PROJECT_ID); + }); + expect(paths.filter((p) => p.endsWith("/pulls/42"))).toHaveLength(1); + expect(getWorkspace(db, "ws")?.pullRequestId).toBe(prId); + }); + + test("uses the newer numbered result when another ref has the old PR head cached", async () => { + const { db, manager, network } = setup(); + seedWorkspace(db, { + id: "branch", + branch: "deleted-feature", + upstreamOwner: REPO.owner, + upstreamRepo: REPO.name, + }); + seedWorkspace(db, { + id: "matching", + branch: "matching", + headSha: "def456", + upstreamOwner: REPO.owner, + upstreamRepo: REPO.name, + upstreamBranch: "refs/pull/42/head", + }); + network.branchHeadSha = "abc123"; + await manager.refreshPullRequestsByWorkspaces(["branch"]); + network.headSha = "def456"; + await manager.refreshPullRequestsByWorkspaces(["matching"]); + const prId = getWorkspace(db, "matching")?.pullRequestId; + expect(prId).toBeTruthy(); + await projectRefresher(manager)(PROJECT_ID); + expect(getPrById(db, prId as string)?.headSha).toBe("def456"); + expect(getWorkspace(db, "matching")?.pullRequestId).toBe(prId); + expect(getWorkspace(db, "ws")?.pullRequestId).toBeNull(); + }); + + test("does not replace a newer PR head when older checks finish later", async () => { + const { db, manager, network } = setup(); + const entered = Promise.withResolvers(); + const pending = Promise.withResolvers(); + network.beforeChecks = () => { + entered.resolve(); + return pending.promise; + }; + const fullRefresh = projectRefresher(manager)(PROJECT_ID); + try { + await entered.promise; + network.beforeChecks = undefined; + network.headSha = "def456"; + db.update(workspaces) + .set({ headSha: "def456" }) + .where(eq(workspaces.id, "ws")) + .run(); + await manager.refreshPullRequestsByWorkspaces(["ws"]); + } finally { + pending.resolve(); + await fullRefresh; + } + const prId = getWorkspace(db, "ws")?.pullRequestId; + expect(prId).toBeTruthy(); + expect(getPrById(db, prId as string)?.headSha).toBe("def456"); + network.offline = true; + await withSilencedWarnings(() => + manager.refreshPullRequestsByWorkspaces(["ws"]), + ); + expect(getWorkspace(db, "ws")?.pullRequestId).toBe(prId); + }); + + test("clears a stale synthetic link when another ref already refreshed its PR head", async () => { + const { db, manager, network } = setup(); + await manager.refreshPullRequestsByWorkspaces(["ws"]); + expect(getWorkspace(db, "ws")?.pullRequestId).toBeTruthy(); + seedWorkspace(db, { + id: "branch", + branch: "deleted-feature", + upstreamOwner: REPO.owner, + upstreamRepo: REPO.name, + }); + network.branchHeadSha = "def456"; + await manager.refreshPullRequestsByWorkspaces(["branch"]); + await projectRefresher(manager)(PROJECT_ID); + expect(getWorkspace(db, "ws")?.pullRequestId).toBeNull(); + const [history] = await manager.getPullRequestHistoryByWorkspaces(["ws"]); + expect(history?.pullRequests.map((pr) => pr.number)).toEqual([42]); + }); + + test("a delayed Git ref read does not restore a link removed during the read", async () => { + const { db, manager, network } = setup(); + await manager.refreshPullRequestsByWorkspaces(["ws"]); + const prId = getWorkspace(db, "ws")?.pullRequestId; + expect(prId).toBeTruthy(); + const entered = Promise.withResolvers(); + const pending = Promise.withResolvers(); + network.beforeRefs = () => { + entered.resolve(); + return pending.promise; + }; + network.overrideBranch = "renamed"; + network.offline = true; + await withSilencedWarnings(async () => { + const refresh = manager.refreshPullRequestsByWorkspaces(["ws"]); + try { + await entered.promise; + manager.unlinkWorkspacePullRequest("ws"); + } finally { + pending.resolve(); + await refresh; + } + }); + expect(getWorkspace(db, "ws")?.branch).toBe("renamed"); + expect(getWorkspace(db, "ws")?.suppressedPullRequestId).toBe(prId); + expect(getWorkspace(db, "ws")?.pullRequestId).toBeNull(); + }); +}); + describe("PullRequestRuntimeManager mergedAt attribution", () => { const MERGED_AT_ISO = "2026-05-01T10:00:00Z"; const MERGED_AT = Date.parse(MERGED_AT_ISO); @@ -1042,22 +1402,15 @@ describe("PullRequestRuntimeManager refresh", () => { remoteName: "origin", defaultBranch: "main", }); - const accessible = manager as unknown as { - getCachedOpenPullRequests( - repo: ReturnType, - options?: { bypassCache?: boolean }, - ): Promise; - }; + const sweep = openPullRequestsSweeper(manager); await withSilencedWarnings(async () => { - await accessible.getCachedOpenPullRequests(repoOf("a")).catch(() => {}); + await sweep(repoOf("a")).catch(() => {}); expect(ghAttempts).toBe(1); // Polling is held. - await accessible.getCachedOpenPullRequests(repoOf("b")).catch(() => {}); + await sweep(repoOf("b")).catch(() => {}); expect(ghAttempts).toBe(1); // A user-driven refresh is not: it is the probe that can reopen the gate. - await accessible - .getCachedOpenPullRequests(repoOf("c"), { bypassCache: true }) - .catch(() => {}); + await sweep(repoOf("c"), { bypassCache: true }).catch(() => {}); expect(ghAttempts).toBe(2); }); }); @@ -1085,26 +1438,17 @@ describe("PullRequestRuntimeManager refresh", () => { remoteName: "origin", defaultBranch: "main", }); - const accessible = manager as unknown as { - getCachedOpenPullRequests( - repo: ReturnType, - options?: { bypassCache?: boolean }, - ): Promise; - }; + const sweep = openPullRequestsSweeper(manager); await withSilencedWarnings(async () => { - await accessible.getCachedOpenPullRequests(repoOf("a")).catch(() => {}); + await sweep(repoOf("a")).catch(() => {}); expect(ghAttempts).toBe(1); // Polling is held. - await accessible.getCachedOpenPullRequests(repoOf("b")).catch(() => {}); + await sweep(repoOf("b")).catch(() => {}); expect(ghAttempts).toBe(1); online = true; - await accessible - .getCachedOpenPullRequests(repoOf("c"), { bypassCache: true }) - .catch(() => {}); + await sweep(repoOf("c"), { bypassCache: true }).catch(() => {}); expect(ghAttempts).toBe(2); - await expect( - accessible.getCachedOpenPullRequests(repoOf("b")), - ).resolves.toEqual([]); + await expect(sweep(repoOf("b"))).resolves.toEqual([]); expect(ghAttempts).toBe(3); }); }); diff --git a/packages/host-service/src/runtime/pull-requests/pull-requests.ts b/packages/host-service/src/runtime/pull-requests/pull-requests.ts index c5949e9fd01..4dedc089605 100644 --- a/packages/host-service/src/runtime/pull-requests/pull-requests.ts +++ b/packages/host-service/src/runtime/pull-requests/pull-requests.ts @@ -3,7 +3,7 @@ import { existsSync } from "node:fs"; import type { Octokit } from "@octokit/rest"; import { parseGitHubRemote } from "@superset/shared/github-remote"; import { computeChecksStatus } from "@superset/shared/pull-request-checks"; -import { and, eq, inArray, isNull, notInArray } from "drizzle-orm"; +import { and, eq, inArray, isNull, notInArray, sql } from "drizzle-orm"; import type { HostDb } from "../../db"; import { projects, @@ -58,6 +58,9 @@ import { type ReviewDecision, } from "./utils/pull-request-mappers"; import { + decodeHeadBranch, + encodeHeadBranch, + pullRequestRefNumber, readWorkspaceRefs, type WorkspaceRefsSnapshot, } from "./utils/workspace-refs"; @@ -97,6 +100,19 @@ function upstreamKey( return `${owner.toLowerCase()}/${repo.toLowerCase()}#${branch}`; } +function syntheticPullRequestNumber( + head: GitHubPullRequestHeadRef, + repo: { owner: string; name: string }, +): number | null { + if ( + head.owner.toLowerCase() !== repo.owner.toLowerCase() || + head.repo.toLowerCase() !== repo.name.toLowerCase() + ) { + return null; + } + return pullRequestRefNumber(head.branch); +} + type RepoProvider = "github"; export interface PullRequestStateSnapshot { @@ -170,6 +186,21 @@ interface NormalizedRepoIdentity { type PullRequestRow = typeof pullRequests.$inferSelect; +interface CachedGitHubRequest { + promise: Promise; + fetchedAt: number; + consecutiveFailures: number; + fingerprint?: string; + sequence: number; +} + +interface PullRequestMatch { + id: string; + isOpen: boolean; + headSha: string; + sequence: number; +} + export interface CheckoutPullRequestMetadata { number: number; url: string; @@ -200,13 +231,17 @@ function deriveCheckoutPullRequestUpstream( pr: CheckoutPullRequestMetadata, ): { owner: string; name: string; branch: string } | null { if (!pr.isCrossRepository) { - return { owner: repo.owner, name: repo.name, branch: pr.headRefName }; + return { + owner: repo.owner, + name: repo.name, + branch: encodeHeadBranch(pr.headRefName), + }; } const owner = pr.headRepositoryOwner?.trim(); const name = pr.headRepositoryName?.trim(); if (!owner || !name) return null; - return { owner, name, branch: pr.headRefName }; + return { owner, name, branch: encodeHeadBranch(pr.headRefName) }; } interface ProjectRefreshOptions { @@ -247,11 +282,7 @@ export class PullRequestRuntimeManager { >(); private readonly pullRequestHeadCache = new Map< string, - { - promise: Promise; - fetchedAt: number; - consecutiveFailures: number; - } + CachedGitHubRequest >(); // Review decision, checks, and merge-queue state per PR head. These were // the bulk of the runtime's GitHub traffic: four uncached calls per linked @@ -259,29 +290,18 @@ export class PullRequestRuntimeManager { // spends the user's hourly quota by itself (SUPER-2107). private pullRequestDetailsCache = new Map< string, - { - promise: Promise; - fetchedAt: number; - consecutiveFailures: number; - fingerprint?: string; - } + CachedGitHubRequest >(); private readonly openPullRequestsCache = new Map< string, - { - promise: Promise; - fetchedAt: number; - consecutiveFailures: number; - } + CachedGitHubRequest >(); private readonly pullRequestNumberCache = new Map< string, - { - promise: Promise; - fetchedAt: number; - consecutiveFailures: number; - } + CachedGitHubRequest >(); + private requestSequence = 0; + private readonly appliedPullRequestSequence = new Map(); private readonly readWorkspaceRefs: ( worktreePath: string, ) => Promise; @@ -644,6 +664,7 @@ export class PullRequestRuntimeManager { error: null, now, }); + this.appliedPullRequestSequence.set(rowId, ++this.requestSequence); const upstream = deriveCheckoutPullRequestUpstream(repo, pullRequest); this.db @@ -874,11 +895,10 @@ export class PullRequestRuntimeManager { const upstreamOwner = upstream?.owner ?? null; const upstreamRepo = upstream?.name ?? null; const upstreamBranch = upstream?.branch ?? null; - const pullRequestId = - upstream || - this.pullRequestHeadMatches(workspace.pullRequestId, headSha) - ? workspace.pullRequestId - : null; + const shouldClearLink = + workspace.pullRequestId !== null && + !upstream && + !this.pullRequestHeadMatches(workspace.pullRequestId, headSha); if ( branch === workspace.branch && @@ -886,7 +906,7 @@ export class PullRequestRuntimeManager { upstreamOwner === workspace.upstreamOwner && upstreamRepo === workspace.upstreamRepo && upstreamBranch === workspace.upstreamBranch && - pullRequestId === workspace.pullRequestId + !shouldClearLink ) { return null; } @@ -899,7 +919,11 @@ export class PullRequestRuntimeManager { upstreamOwner, upstreamRepo, upstreamBranch, - pullRequestId, + ...(shouldClearLink + ? { + pullRequestId: sql`CASE WHEN ${workspaces.pullRequestId} = ${workspace.pullRequestId} THEN NULL ELSE ${workspaces.pullRequestId} END`, + } + : {}), ...(branch !== workspace.branch ? { updatedAt: Date.now() } : {}), }) // Guard: the workspace can archive during the awaited ref read; @@ -1049,8 +1073,11 @@ export class PullRequestRuntimeManager { } } - const { failedKeys, matched: keyToPullRequest } = - await this.fetchRepoPullRequests(projectId, repo, wantedRefs, options); + const { + failedKeys, + supersededKeys, + matched: keyToPullRequest, + } = await this.fetchRepoPullRequests(projectId, repo, wantedRefs, options); await this.refreshPastPullRequests( projectId, repo, @@ -1087,7 +1114,60 @@ export class PullRequestRuntimeManager { } continue; } - const rawMatch = keyToPullRequest.get(key); + const fetchedMatch = keyToPullRequest.get(key); + const head = wantedRefs.get(key); + const isSyntheticCheckout = + head !== undefined && syntheticPullRequestNumber(head, repo) !== null; + const lookupSuperseded = + supersededKeys.has(key) || + Boolean( + isSyntheticCheckout && + fetchedMatch && + (this.appliedPullRequestSequence.get(fetchedMatch.id) ?? 0) > + fetchedMatch.sequence && + !this.pullRequestHeadMatches(fetchedMatch.id, fetchedMatch.headSha), + ); + if (lookupSuperseded && !isSyntheticCheckout) continue; + const rawMatch = lookupSuperseded ? undefined : fetchedMatch; + const useStoredHead = failedKeys.has(key) || lookupSuperseded; + let headSha = workspace.headSha; + let linkCondition = and( + eq(workspaces.id, workspace.id), + isNull(workspaces.archivedAt), + ); + if (isSyntheticCheckout) { + const sameCheckout = and( + linkCondition, + eq(workspaces.projectId, projectId), + eq(workspaces.branch, workspace.branch), + sql`${workspaces.upstreamOwner} IS ${workspace.upstreamOwner}`, + sql`${workspaces.upstreamRepo} IS ${workspace.upstreamRepo}`, + sql`${workspaces.upstreamBranch} IS ${workspace.upstreamBranch}`, + sql`${workspaces.pullRequestId} IS ${workspace.pullRequestId}`, + sql`${workspaces.suppressedPullRequestId} IS ${workspace.suppressedPullRequestId}`, + ); + const current = this.db + .select({ headSha: workspaces.headSha }) + .from(workspaces) + .where(sameCheckout) + .get(); + if ( + !current || + (!useStoredHead && current.headSha !== workspace.headSha) + ) { + continue; + } + headSha = current.headSha; + if (!headSha) continue; + linkCondition = and( + sameCheckout, + sql`${workspaces.headSha} IS ${headSha}`, + ); + } + const checkoutHeadChanged = + !!rawMatch && + isSyntheticCheckout && + rawMatch.headSha.toLowerCase() !== headSha?.trim().toLowerCase(); // A head= PR that is merged or closed is a past promotion // (e.g. main -> staging), never the default-branch workspace's work. const isPastPromotion = @@ -1099,32 +1179,47 @@ export class PullRequestRuntimeManager { } // A PR the user unlinked stays unlinked; a different PR still links. const match = - rawMatch?.id === workspace.suppressedPullRequestId || isPastPromotion + rawMatch?.id === workspace.suppressedPullRequestId || + isPastPromotion || + checkoutHeadChanged ? undefined : rawMatch; if (match) { - this.db + const { changes } = this.db .update(workspaces) .set({ pullRequestId: match.id }) - .where( - and(eq(workspaces.id, workspace.id), isNull(workspaces.archivedAt)), - ) + .where(linkCondition) .run(); // The sweep re-asserts the link every pass, so this also heals // history rows for links that predate the table. - this.recordWorkspacePullRequestLink(workspace.id, match.id, Date.now()); + if (changes > 0) { + this.recordWorkspacePullRequestLink( + workspace.id, + match.id, + Date.now(), + ); + } continue; } - if (failedKeys.has(key)) continue; + if (useStoredHead) { + if (!isSyntheticCheckout || !workspace.pullRequestId || !headSha) { + continue; + } + const linkedPr = this.findPullRequestRowById(workspace.pullRequestId); + if ( + !linkedPr?.headSha || + linkedPr.headSha.toLowerCase() === headSha.trim().toLowerCase() + ) { + continue; + } + } if (workspace.pullRequestId) { this.db .update(workspaces) .set({ pullRequestId: null }) - .where( - and(eq(workspaces.id, workspace.id), isNull(workspaces.archivedAt)), - ) + .where(linkCondition) .run(); } } @@ -1420,20 +1515,12 @@ export class PullRequestRuntimeManager { // retried, hit the same 403, and re-evicted. Network blips heal at the // next TTL boundary instead. Gate-held calls are the exception: they never // reached GitHub, and must retry as soon as another lookup restores access. - private cachedGitHubFetch( - cache: Map< - string, - { - promise: Promise; - fetchedAt: number; - consecutiveFailures: number; - fingerprint?: string; - } - >, + private cachedGitHubRequest( + cache: Map>, cacheKey: string, options: { bypassCache?: boolean; fingerprint?: string }, fetcher: () => Promise, - ): Promise { + ): CachedGitHubRequest { const existing = cache.get(cacheKey); // A fingerprint names the version of the thing cached (a PR's head // SHA): a different one is a miss and a fresh failure streak, while @@ -1448,13 +1535,14 @@ export class PullRequestRuntimeManager { REPO_PULL_REQUEST_CACHE_MAX_TTL_MS, ); if (Date.now() - cached.fetchedAt < ttl) { - return cached.promise; + return cached; } } // Carry the failure streak forward so an in-flight retry keeps the // backed-off TTL until it actually resolves. const entry = { + sequence: ++this.requestSequence, promise: fetcher(), fetchedAt: Date.now(), consecutiveFailures: cached?.consecutiveFailures ?? 0, @@ -1481,14 +1569,18 @@ export class PullRequestRuntimeManager { }, ); cache.set(cacheKey, entry); - return entry.promise; + return entry; } - private async getCachedPullRequestByHead( + private getCachedPullRequestForRef( repo: NormalizedRepoIdentity, head: GitHubPullRequestHeadRef, options: { bypassCache?: boolean } = {}, - ): Promise { + ): CachedGitHubRequest { + const prNumber = syntheticPullRequestNumber(head, repo); + if (prNumber !== null) + return this.getCachedPullRequestByNumber(repo, prNumber, options); + const branchHead = { ...head, branch: decodeHeadBranch(head.branch) }; // Branch stays case-sensitive so two case-variant branches can't share // a cache entry and return each other's PR. const cacheKey = [ @@ -1498,7 +1590,7 @@ export class PullRequestRuntimeManager { head.repo.toLowerCase(), head.branch, ].join("/"); - return this.cachedGitHubFetch( + return this.cachedGitHubRequest( this.pullRequestHeadCache, cacheKey, options, @@ -1506,18 +1598,30 @@ export class PullRequestRuntimeManager { this.fetchFromGitHub( "PR head lookup", { owner: repo.owner, name: repo.name, head }, - () => - fetchPullRequestByHeadFromGh( - this.execGh, - { owner: repo.owner, name: repo.name }, - head, - ), + () => fetchPullRequestByHeadFromGh(this.execGh, repo, branchHead), async () => - fetchPullRequestByHead( - await this.github(), - { owner: repo.owner, name: repo.name }, - head, - ), + fetchPullRequestByHead(await this.github(), repo, branchHead), + { probe: options.bypassCache === true }, + ), + ); + } + + private getCachedPullRequestByNumber( + repo: NormalizedRepoIdentity, + prNumber: number, + options: { bypassCache?: boolean }, + ): CachedGitHubRequest { + return this.cachedGitHubRequest( + this.pullRequestNumberCache, + `${repo.owner.toLowerCase()}/${repo.name.toLowerCase()}#${prNumber}`, + options, + () => + this.fetchFromGitHub( + "PR number lookup", + { owner: repo.owner, name: repo.name, prNumber }, + () => fetchPullRequestByNumberFromGh(this.execGh, repo, prNumber), + async () => + fetchPullRequestByNumber(await this.github(), repo, prNumber), { probe: options.bypassCache === true }, ), ); @@ -1537,7 +1641,7 @@ export class PullRequestRuntimeManager { name: repo.name, prNumber: node.number, }; - return this.cachedGitHubFetch( + return this.cachedGitHubRequest( this.pullRequestDetailsCache, cacheKey, { ...options, fingerprint: node.headRefOid }, @@ -1602,18 +1706,18 @@ export class PullRequestRuntimeManager { } return { reviewDecision, checks, isInMergeQueue }; }, - ); + ).promise; } // Deliberately narrow: repo-wide listing was removed in #4268/#4291 (the // GraphQL sweep 504'd on large repos). This is a shallow `pulls?state=open` // page, no checks, once per repo per TTL, only when a per-head lookup missed. - private async getCachedOpenPullRequests( + private getCachedOpenPullRequests( repo: NormalizedRepoIdentity, options: { bypassCache?: boolean } = {}, - ): Promise { + ): CachedGitHubRequest { const cacheKey = `${repo.owner.toLowerCase()}/${repo.name.toLowerCase()}`; - return this.cachedGitHubFetch( + return this.cachedGitHubRequest( this.openPullRequestsCache, cacheKey, options, @@ -1698,20 +1802,12 @@ export class PullRequestRuntimeManager { }; const startedAt = Date.now(); try { - const node = await this.cachedGitHubFetch( - this.pullRequestNumberCache, - `${repo.owner.toLowerCase()}/${repo.name.toLowerCase()}#${prNumber}`, + const request = this.getCachedPullRequestByNumber( + repo, + prNumber, options, - () => - this.fetchFromGitHub( - "PR number lookup", - context, - () => fetchPullRequestByNumberFromGh(this.execGh, repo, prNumber), - async () => - fetchPullRequestByNumber(await this.github(), repo, prNumber), - { probe: options.bypassCache === true }, - ), ); + const node = await request.promise; if (!node || node.number !== prNumber) return; // A lookup that started earlier can resolve later; never let it // overwrite what a newer one already stored. @@ -1719,6 +1815,7 @@ export class PullRequestRuntimeManager { if ( !latest || !PAST_PULL_REQUEST_REFRESH_STATES.includes(latest.state) || + (this.appliedPullRequestSequence.get(rowId) ?? 0) > request.sequence || (latest.lastFetchedAt ?? 0) > startedAt ) { return; @@ -1746,6 +1843,7 @@ export class PullRequestRuntimeManager { error: null, now, }); + this.appliedPullRequestSequence.set(rowId, request.sequence); } catch (error) { console.warn( "[host-service:pull-request-runtime] Failed to fetch past PR by number", @@ -1760,30 +1858,37 @@ export class PullRequestRuntimeManager { wantedRefs: Map, options: { bypassCache?: boolean } = {}, ): Promise<{ - matched: Map; + matched: Map; failedKeys: Set; + supersededKeys: Set; }> { - const matched = new Map(); + const matched = new Map(); const failedKeys = new Set(); - if (wantedRefs.size === 0) return { matched, failedKeys }; + const supersededKeys = new Set(); + if (wantedRefs.size === 0) return { matched, failedKeys, supersededKeys }; - const latestByKey = new Map(); + const latestByKey = new Map< + string, + { node: GitHubPullRequestNode; sequence: number } + >(); await Promise.all( Array.from(wantedRefs.entries()).map(async ([key, head]) => { try { - const node = await this.getCachedPullRequestByHead( - repo, - head, - options, - ); + const request = this.getCachedPullRequestForRef(repo, head, options); + const node = await request.promise; if (!node) return; const nodeKey = upstreamKey( node.headRepositoryOwner?.login ?? null, node.headRepository?.name ?? null, - node.headRefName, + encodeHeadBranch(node.headRefName), ); - if (nodeKey === key) latestByKey.set(key, node); + if ( + nodeKey === key || + node.number === syntheticPullRequestNumber(head, repo) + ) { + latestByKey.set(key, { node, sequence: request.sequence }); + } } catch (error) { failedKeys.add(key); console.warn( @@ -1804,12 +1909,18 @@ export class PullRequestRuntimeManager { // a workspace whose local branch casing drifted from the PR's // headRefName gets nothing from the per-head lookups above. Sweep the // repo's open PRs once and fill the gaps case-insensitively. - const unmatchedKeys = Array.from(wantedRefs.keys()).filter( - (key) => !latestByKey.has(key) && !failedKeys.has(key), - ); + const unmatchedKeys = Array.from(wantedRefs.entries()) + .filter( + ([key, head]) => + !latestByKey.has(key) && + !failedKeys.has(key) && + syntheticPullRequestNumber(head, repo) === null, + ) + .map(([key]) => key); if (unmatchedKeys.length > 0) { try { - const openNodes = await this.getCachedOpenPullRequests(repo, options); + const request = this.getCachedOpenPullRequests(repo, options); + const openNodes = await request.promise; // The one place drift is tolerated: index open PRs by a lowercased // key. latestByKey stays keyed by the exact workspace key, so link // assignment downstream is unchanged. @@ -1818,7 +1929,7 @@ export class PullRequestRuntimeManager { const nodeKey = upstreamKey( node.headRepositoryOwner?.login ?? null, node.headRepository?.name ?? null, - node.headRefName, + encodeHeadBranch(node.headRefName), ); if (!nodeKey) continue; const lower = nodeKey.toLowerCase(); @@ -1827,7 +1938,7 @@ export class PullRequestRuntimeManager { } for (const key of unmatchedKeys) { const node = openByLowerKey.get(key.toLowerCase()); - if (node) latestByKey.set(key, node); + if (node) latestByKey.set(key, { node, sequence: request.sequence }); } } catch (error) { // Treat the whole sweep as failed lookups so existing links are @@ -1841,10 +1952,20 @@ export class PullRequestRuntimeManager { } const now = Date.now(); + // Different refs can identify the same PR. A cached branch response can + // outlive a newer numbered lookup, even within a single refresh. + const observations = [...latestByKey].sort( + (a, b) => b[1].sequence - a[1].sequence, + ); + const latestByNumber = new Map(); + for (const [, { node }] of observations) { + if (!latestByNumber.has(node.number)) + latestByNumber.set(node.number, node); + } const detailsByNumber = new Map(); await Promise.all( - Array.from(latestByKey.values()).map(async (node) => { + Array.from(latestByNumber.values()).map(async (node) => { try { detailsByNumber.set( node.number, @@ -1865,8 +1986,30 @@ export class PullRequestRuntimeManager { }), ); - for (const [key, node] of latestByKey) { + for (const [key, { node, sequence }] of observations) { const existing = this.findPullRequestRow(repo, node.number); + if ( + existing && + (this.appliedPullRequestSequence.get(existing.id) ?? 0) > sequence + ) { + if ( + existing.headSha === node.headRefOid && + existing.headBranch === node.headRefName + ) { + matched.set(key, { + id: existing.id, + headSha: node.headRefOid, + sequence, + isOpen: + existing.state === "open" || + existing.state === "draft" || + existing.state === "queued", + }); + } else { + supersededKeys.add(key); + } + continue; + } // A failed fetch keeps the last-known state rather than blanking it. const details = detailsByNumber.get(node.number); const checks = details @@ -1898,9 +2041,15 @@ export class PullRequestRuntimeManager { now, }); - matched.set(key, { id: rowId, isOpen: node.state === "OPEN" }); + this.appliedPullRequestSequence.set(rowId, sequence); + matched.set(key, { + id: rowId, + isOpen: node.state === "OPEN", + headSha: node.headRefOid, + sequence, + }); } - return { matched, failedKeys }; + return { matched, failedKeys, supersededKeys }; } } diff --git a/packages/host-service/src/runtime/pull-requests/utils/github-query/github-query.test.ts b/packages/host-service/src/runtime/pull-requests/utils/github-query/github-query.test.ts index a6cc3e7f400..3c79ca3a8ea 100644 --- a/packages/host-service/src/runtime/pull-requests/utils/github-query/github-query.test.ts +++ b/packages/host-service/src/runtime/pull-requests/utils/github-query/github-query.test.ts @@ -1,7 +1,10 @@ import { describe, expect, test } from "bun:test"; +import type { Octokit } from "@octokit/rest"; import { fetchOpenPullRequestsFromGh, fetchPullRequestByHeadFromGh, + fetchPullRequestByNumber, + fetchPullRequestByNumberFromGh, fetchPullRequestChecksFromGh, fetchPullRequestMergeQueueStateFromGh, fetchPullRequestReviewDecisionFromGh, @@ -25,6 +28,55 @@ function createExecGh(responses: unknown[]) { } describe("GitHub pull request REST queries", () => { + test("normalizes a numbered merged PR lookup through gh and Octokit", async () => { + const raw = { + number: 42, + title: "Deleted branch", + html_url: "https://github.com/owner/repo/pull/42", + state: "closed", + merged_at: "2026-05-01T10:00:00Z", + head: { + ref: "deleted-feature", + sha: "abc123", + repo: { name: "repo", owner: { login: "owner" } }, + }, + }; + const repo = { owner: "owner", name: "repo" }; + const { execGh, calls } = createExecGh([raw]); + const fromGh = await fetchPullRequestByNumberFromGh(execGh, repo, 42); + const octokit = { + rest: { + pulls: { + get: async (params: unknown) => { + expect(params).toEqual({ + owner: "owner", + repo: "repo", + pull_number: 42, + }); + return { data: raw }; + }, + }, + }, + } as unknown as Octokit; + + const fromOctokit = await fetchPullRequestByNumber(octokit, repo, 42); + + expect(fromGh).toMatchObject({ + number: 42, + state: "MERGED", + headRefName: "deleted-feature", + headRefOid: "abc123", + mergedAt: Date.parse(raw.merged_at), + }); + expect(fromOctokit).toEqual(fromGh); + expect(calls[0]?.args).toEqual([ + "api", + "--method", + "GET", + "repos/owner/repo/pulls/42", + ]); + }); + test("fetches only the PR matching the requested upstream head", async () => { const { calls, execGh } = createExecGh([ [ diff --git a/packages/host-service/src/runtime/pull-requests/utils/workspace-refs.test.ts b/packages/host-service/src/runtime/pull-requests/utils/workspace-refs.test.ts new file mode 100644 index 00000000000..4793fc10cff --- /dev/null +++ b/packages/host-service/src/runtime/pull-requests/utils/workspace-refs.test.ts @@ -0,0 +1,50 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { simpleGit } from "simple-git"; +import { readWorkspaceRefs } from "./workspace-refs"; + +test("pull refs keep their tracking remote and ordinary branches keep their namespace", async () => { + const path = mkdtempSync(join(tmpdir(), "paradev-pull-ref-")); + try { + const git = simpleGit(path); + await git.raw(["init", "--initial-branch=fixture"]); + await git.raw([ + "-c", + "user.name=Fixture", + "-c", + "user.email=fixture@example.invalid", + "-c", + "commit.gpgsign=false", + "commit", + "--allow-empty", + "-m", + "initial", + ]); + await git.addRemote("origin", "https://github.com/base/project.git"); + await git.addRemote("fork", "https://github.com/fork/project.git"); + await git.raw(["config", "remote.pushDefault", "fork"]); + await git.raw(["config", "branch.fixture.remote", "origin"]); + await git.raw(["config", "branch.fixture.merge", "refs/pull/42/head"]); + expect((await readWorkspaceRefs(git)).upstream).toEqual({ + owner: "base", + name: "project", + branch: "refs/pull/42/head", + }); + + await git.raw([ + "config", + "branch.fixture.merge", + "refs/heads/refs/pull/42/head", + ]); + const ordinary = (await readWorkspaceRefs(git)).upstream; + expect(ordinary).toEqual({ + owner: "fork", + name: "project", + branch: "refs/heads/refs/pull/42/head", + }); + } finally { + rmSync(path, { recursive: true, force: true }); + } +}); diff --git a/packages/host-service/src/runtime/pull-requests/utils/workspace-refs.ts b/packages/host-service/src/runtime/pull-requests/utils/workspace-refs.ts index 6ec67bf8f09..a28f1cbe201 100644 --- a/packages/host-service/src/runtime/pull-requests/utils/workspace-refs.ts +++ b/packages/host-service/src/runtime/pull-requests/utils/workspace-refs.ts @@ -19,6 +19,27 @@ export interface WorkspaceUpstream { branch: string; } +export function pullRequestRefNumber(ref: string): number | null { + const match = /^refs\/pull\/([1-9]\d*)\/head$/.exec(ref); + const number = match ? Number(match[1]) : NaN; + return Number.isSafeInteger(number) ? number : null; +} + +// Preserve the namespace for ordinary branches whose short names look like pull refs. +export function encodeHeadBranch(branch: string): string { + return pullRequestRefNumber(branch.replace(/^(?:refs\/heads\/)+/, "")) !== + null + ? `refs/heads/${branch}` + : branch; +} + +export function decodeHeadBranch(branch: string): string { + return pullRequestRefNumber(branch.replace(/^(?:refs\/heads\/)+/, "")) !== + null + ? branch.replace(/^refs\/heads\//, "") + : branch; +} + export interface WorkspaceRefsSnapshot { branch: string | null; headSha: string | null; @@ -79,6 +100,15 @@ async function resolveWorkspaceUpstream( git: SimpleGit, localBranch: string, ): Promise { + const mergeRef = await tryConfig(git, `branch.${localBranch}.merge`); + if (mergeRef && pullRequestRefNumber(mergeRef) !== null) { + const remote = await tryConfig(git, `branch.${localBranch}.remote`); + const url = remote ? await resolveRemoteValueToUrl(git, remote) : null; + const parsed = url ? parseGitHubRemote(url) : null; + return parsed + ? { owner: parsed.owner, name: parsed.name, branch: mergeRef } + : null; + } // `@{push}` resolves remote+branch respecting all config precedence in one call. const pushRef = await tryRaw(git, [ "rev-parse", @@ -94,7 +124,7 @@ async function resolveWorkspaceUpstream( return { owner: parsed.owner, name: parsed.name, - branch: pushRef.slice(slash + 1), + branch: encodeHeadBranch(pushRef.slice(slash + 1)), }; } } @@ -103,7 +133,6 @@ async function resolveWorkspaceUpstream( // Fallback when `@{push}` isn't configured — mirrors gh's config chain. // Require `branch..merge`; without it, `remote.pushDefault` alone would // re-open the same-name collision hole on untracked branches. - const mergeRef = await tryConfig(git, `branch.${localBranch}.merge`); const trackedBranch = mergeRef?.replace(/^refs\/heads\//, ""); if (!trackedBranch) return null; @@ -120,7 +149,11 @@ async function resolveWorkspaceUpstream( // `gh pr checkout` renames the local branch on collision (`main` → // `quueli-main`) but the PR's headRefName stays `main`, so we key on the // tracked remote branch, not the local name. - return { owner: parsed.owner, name: parsed.name, branch: trackedBranch }; + return { + owner: parsed.owner, + name: parsed.name, + branch: encodeHeadBranch(trackedBranch), + }; } async function tryRaw(git: SimpleGit, args: string[]): Promise {