From 071e5cd3a112f070598125cc1acdb7475037c18c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B8=D0=BA=D1=82=D0=BE=D1=80=20=D0=91=D1=8B=D1=81?= =?UTF-8?q?=D1=82=D1=80=D0=BE=D0=B2?= Date: Sat, 14 Nov 2026 11:31:54 +0500 Subject: [PATCH 1/6] fix(host-service): link PR checkouts that track synthetic refs --- .../pull-requests/pull-requests.test.ts | 103 ++++++++++++++++++ .../runtime/pull-requests/pull-requests.ts | 74 ++++++++++--- .../utils/github-query/github-query.test.ts | 52 +++++++++ .../utils/github-query/github-query.ts | 27 +++++ 4 files changed, 238 insertions(+), 18 deletions(-) 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..ac51c9c864e 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 @@ -342,6 +342,109 @@ 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 manager = createManager(db, { + readWorkspaceRefs: async () => { + const workspace = getWorkspace(db, "ws"); + return { + branch: workspace?.branch ?? null, + headSha: workspace?.headSha ?? null, + upstream: { + owner: workspace?.upstreamOwner ?? REPO.owner, + name: workspace?.upstreamRepo ?? REPO.name, + branch: workspace?.upstreamBranch ?? "refs/pull/42/head", + }, + }; + }, + execGh: async (args) => { + const path = args.find((arg) => arg.startsWith("repos/")) ?? ""; + paths.push(path); + if (path === `repos/${REPO.owner}/${REPO.name}/pulls/42`) { + return makePrNode({ + number: 42, + headRef: "deleted-feature", + headSha: "abc123", + state: "closed", + mergedAt: "2026-05-01T10:00:00Z", + }); + } + if (path?.endsWith("/check-runs")) return { check_runs: [] }; + return []; + }, + }); + return { db, manager, paths }; + } + + 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("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`); + }); +}); + describe("PullRequestRuntimeManager mergedAt attribution", () => { const MERGED_AT_ISO = "2026-05-01T10:00:00Z"; const MERGED_AT = Date.parse(MERGED_AT_ISO); 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..24b3ffc5709 100644 --- a/packages/host-service/src/runtime/pull-requests/pull-requests.ts +++ b/packages/host-service/src/runtime/pull-requests/pull-requests.ts @@ -97,6 +97,21 @@ 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; + } + const match = /^refs\/pull\/([1-9]\d*)\/head$/.exec(head.branch); + const number = match ? Number(match[1]) : NaN; + return Number.isSafeInteger(number) ? number : null; +} + type RepoProvider = "github"; export interface PullRequestStateSnapshot { @@ -1088,6 +1103,12 @@ export class PullRequestRuntimeManager { continue; } const rawMatch = keyToPullRequest.get(key); + const head = wantedRefs.get(key); + const checkoutHeadChanged = + !!rawMatch && + !!head && + syntheticPullRequestNumber(head, repo) !== null && + !this.pullRequestHeadMatches(rawMatch.id, workspace.headSha); // 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,7 +1120,9 @@ 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) { @@ -1484,11 +1507,12 @@ export class PullRequestRuntimeManager { return entry.promise; } - private async getCachedPullRequestByHead( + private async getCachedPullRequestForRef( repo: NormalizedRepoIdentity, head: GitHubPullRequestHeadRef, options: { bypassCache?: boolean } = {}, ): Promise { + const prNumber = syntheticPullRequestNumber(head, repo); // Branch stays case-sensitive so two case-variant branches can't share // a cache entry and return each other's PR. const cacheKey = [ @@ -1504,20 +1528,24 @@ export class PullRequestRuntimeManager { options, () => this.fetchFromGitHub( - "PR head lookup", + prNumber === null ? "PR head lookup" : "PR number lookup", { owner: repo.owner, name: repo.name, head }, () => - fetchPullRequestByHeadFromGh( - this.execGh, - { owner: repo.owner, name: repo.name }, - head, - ), + prNumber !== null + ? fetchPullRequestByNumberFromGh(this.execGh, repo, prNumber) + : fetchPullRequestByHeadFromGh( + this.execGh, + { owner: repo.owner, name: repo.name }, + head, + ), async () => - fetchPullRequestByHead( - await this.github(), - { owner: repo.owner, name: repo.name }, - head, - ), + prNumber !== null + ? fetchPullRequestByNumber(await this.github(), repo, prNumber) + : fetchPullRequestByHead( + await this.github(), + { owner: repo.owner, name: repo.name }, + head, + ), { probe: options.bypassCache === true }, ), ); @@ -1771,7 +1799,7 @@ export class PullRequestRuntimeManager { await Promise.all( Array.from(wantedRefs.entries()).map(async ([key, head]) => { try { - const node = await this.getCachedPullRequestByHead( + const node = await this.getCachedPullRequestForRef( repo, head, options, @@ -1783,7 +1811,12 @@ export class PullRequestRuntimeManager { node.headRepository?.name ?? null, node.headRefName, ); - if (nodeKey === key) latestByKey.set(key, node); + if ( + nodeKey === key || + node.number === syntheticPullRequestNumber(head, repo) + ) { + latestByKey.set(key, node); + } } catch (error) { failedKeys.add(key); console.warn( @@ -1804,9 +1837,14 @@ 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); 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/github-query/github-query.ts b/packages/host-service/src/runtime/pull-requests/utils/github-query/github-query.ts index 1404b9ba20a..9f9c73e1bc1 100644 --- a/packages/host-service/src/runtime/pull-requests/utils/github-query/github-query.ts +++ b/packages/host-service/src/runtime/pull-requests/utils/github-query/github-query.ts @@ -229,6 +229,33 @@ function toStatusContextNode( }; } +export async function fetchPullRequestByNumberFromGh( + execGh: ExecGh, + repository: { owner: string; name: string }, + prNumber: number, +): Promise { + const raw = await execGh([ + "api", + "--method", + "GET", + `repos/${repository.owner}/${repository.name}/pulls/${prNumber}`, + ]); + return normalizePullRequest(raw); +} + +export async function fetchPullRequestByNumber( + octokit: Octokit, + repository: { owner: string; name: string }, + prNumber: number, +): Promise { + const response = await octokit.rest.pulls.get({ + owner: repository.owner, + repo: repository.name, + pull_number: prNumber, + }); + return normalizePullRequest(response.data); +} + export async function fetchPullRequestByHeadFromGh( execGh: ExecGh, repository: { From 8896e4a75075f0396672c0bc7b36d6a99017e110 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B8=D0=BA=D1=82=D0=BE=D1=80=20=D0=91=D1=8B=D1=81?= =?UTF-8?q?=D1=82=D1=80=D0=BE=D0=B2?= Date: Sun, 15 Nov 2026 16:16:52 +0500 Subject: [PATCH 2/6] fix(host-service): clear mismatched checkout links while offline --- .../pull-requests/pull-requests.test.ts | 29 ++++++++++++++++++- .../runtime/pull-requests/pull-requests.ts | 14 ++++++++- 2 files changed, 41 insertions(+), 2 deletions(-) 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 ac51c9c864e..3a1c56b37b5 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 @@ -355,6 +355,7 @@ describe("PullRequestRuntimeManager synthetic PR refs", () => { upstreamBranch: "refs/pull/42/head", }); const paths: string[] = []; + const network = { offline: false }; const manager = createManager(db, { readWorkspaceRefs: async () => { const workspace = getWorkspace(db, "ws"); @@ -369,6 +370,11 @@ describe("PullRequestRuntimeManager synthetic PR refs", () => { }; }, 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`) { @@ -384,7 +390,7 @@ describe("PullRequestRuntimeManager synthetic PR refs", () => { return []; }, }); - return { db, manager, paths }; + return { db, manager, paths, network }; } test("discovers a merged PR by its synthetic ref without an existing link", async () => { @@ -431,6 +437,27 @@ describe("PullRequestRuntimeManager synthetic PR refs", () => { 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) 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 24b3ffc5709..5970d4a3aca 100644 --- a/packages/host-service/src/runtime/pull-requests/pull-requests.ts +++ b/packages/host-service/src/runtime/pull-requests/pull-requests.ts @@ -1139,7 +1139,19 @@ export class PullRequestRuntimeManager { continue; } - if (failedKeys.has(key)) continue; + if (failedKeys.has(key)) { + const linkedPr = workspace.pullRequestId + ? this.findPullRequestRowById(workspace.pullRequestId) + : undefined; + const knownCheckoutMismatch = + !!head && + syntheticPullRequestNumber(head, repo) !== null && + !!workspace.headSha && + !!linkedPr?.headSha && + linkedPr.headSha.toLowerCase() !== + workspace.headSha.trim().toLowerCase(); + if (!knownCheckoutMismatch) continue; + } if (workspace.pullRequestId) { this.db From 32965cad527e2c0bdefa24c4813a8ec46cde52d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B8=D0=BA=D1=82=D0=BE=D1=80=20=D0=91=D1=8B=D1=81?= =?UTF-8?q?=D1=82=D1=80=D0=BE=D0=B2?= Date: Mon, 16 Nov 2026 13:50:52 +0500 Subject: [PATCH 3/6] fix(host-service): preserve links from newer PR refreshes --- .../pull-requests/pull-requests.test.ts | 45 ++++++++++++++++++- .../runtime/pull-requests/pull-requests.ts | 45 ++++++++++++++++--- 2 files changed, 83 insertions(+), 7 deletions(-) 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 3a1c56b37b5..aadaf4156a6 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 @@ -355,7 +355,11 @@ describe("PullRequestRuntimeManager synthetic PR refs", () => { upstreamBranch: "refs/pull/42/head", }); const paths: string[] = []; - const network = { offline: false }; + const network = { + offline: false, + headSha: "abc123", + beforeLookup: undefined as (() => Promise) | undefined, + }; const manager = createManager(db, { readWorkspaceRefs: async () => { const workspace = getWorkspace(db, "ws"); @@ -378,10 +382,11 @@ describe("PullRequestRuntimeManager synthetic PR refs", () => { 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: "abc123", + headSha: network.headSha, state: "closed", mergedAt: "2026-05-01T10:00:00Z", }); @@ -470,6 +475,42 @@ describe("PullRequestRuntimeManager synthetic PR refs", () => { 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"); + }); }); describe("PullRequestRuntimeManager mergedAt attribution", () => { 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 5970d4a3aca..b55baa58cee 100644 --- a/packages/host-service/src/runtime/pull-requests/pull-requests.ts +++ b/packages/host-service/src/runtime/pull-requests/pull-requests.ts @@ -1140,17 +1140,52 @@ export class PullRequestRuntimeManager { } if (failedKeys.has(key)) { - const linkedPr = workspace.pullRequestId - ? this.findPullRequestRowById(workspace.pullRequestId) + const current = this.db + .select() + .from(workspaces) + .where(eq(workspaces.id, workspace.id)) + .get(); + if ( + !current || + current.pullRequestId !== workspace.pullRequestId || + this.effectiveUpstreamKey(current, repo) !== key + ) + continue; + const linkedPr = current.pullRequestId + ? this.findPullRequestRowById(current.pullRequestId) : undefined; const knownCheckoutMismatch = !!head && syntheticPullRequestNumber(head, repo) !== null && - !!workspace.headSha && + !!current.headSha && !!linkedPr?.headSha && linkedPr.headSha.toLowerCase() !== - workspace.headSha.trim().toLowerCase(); - if (!knownCheckoutMismatch) continue; + current.headSha.trim().toLowerCase(); + if (knownCheckoutMismatch && current.pullRequestId && current.headSha) { + this.db + .update(workspaces) + .set({ pullRequestId: null }) + .where( + and( + eq(workspaces.id, current.id), + isNull(workspaces.archivedAt), + eq(workspaces.branch, current.branch), + eq(workspaces.headSha, current.headSha), + eq(workspaces.pullRequestId, current.pullRequestId), + current.upstreamOwner === null + ? isNull(workspaces.upstreamOwner) + : eq(workspaces.upstreamOwner, current.upstreamOwner), + current.upstreamRepo === null + ? isNull(workspaces.upstreamRepo) + : eq(workspaces.upstreamRepo, current.upstreamRepo), + current.upstreamBranch === null + ? isNull(workspaces.upstreamBranch) + : eq(workspaces.upstreamBranch, current.upstreamBranch), + ), + ) + .run(); + } + continue; } if (workspace.pullRequestId) { From 364a20c70c4abeb5c18919b0b58bdf3cb1f5ab66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B8=D0=BA=D1=82=D0=BE=D1=80=20=D0=91=D1=8B=D1=81?= =?UTF-8?q?=D1=82=D1=80=D0=BE=D0=B2?= Date: Wed, 18 Nov 2026 15:22:19 +0500 Subject: [PATCH 4/6] fix(host-service): ignore stale synthetic PR lookup results --- .../pull-requests/pull-requests.test.ts | 27 +++++ .../runtime/pull-requests/pull-requests.ts | 113 +++++++++--------- 2 files changed, 84 insertions(+), 56 deletions(-) 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 aadaf4156a6..e36290c7bee 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 @@ -511,6 +511,33 @@ describe("PullRequestRuntimeManager synthetic PR refs", () => { 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([]); + }); }); describe("PullRequestRuntimeManager mergedAt attribution", () => { 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 b55baa58cee..220b095f5e5 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, @@ -1104,11 +1104,46 @@ export class PullRequestRuntimeManager { } const rawMatch = keyToPullRequest.get(key); const head = wantedRefs.get(key); + const isSyntheticCheckout = + head !== undefined && syntheticPullRequestNumber(head, repo) !== null; + const lookupFailed = failedKeys.has(key); + 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 || + (!lookupFailed && current.headSha !== workspace.headSha) + ) { + continue; + } + headSha = current.headSha; + linkCondition = and( + sameCheckout, + sql`${workspaces.headSha} IS ${headSha}`, + ); + } const checkoutHeadChanged = !!rawMatch && - !!head && - syntheticPullRequestNumber(head, repo) !== null && - !this.pullRequestHeadMatches(rawMatch.id, workspace.headSha); + isSyntheticCheckout && + !this.pullRequestHeadMatches(rawMatch.id, headSha); // 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 = @@ -1126,75 +1161,41 @@ export class PullRequestRuntimeManager { ? 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)) { - const current = this.db - .select() - .from(workspaces) - .where(eq(workspaces.id, workspace.id)) - .get(); + if (lookupFailed) { + if (!isSyntheticCheckout || !workspace.pullRequestId || !headSha) { + continue; + } + const linkedPr = this.findPullRequestRowById(workspace.pullRequestId); if ( - !current || - current.pullRequestId !== workspace.pullRequestId || - this.effectiveUpstreamKey(current, repo) !== key - ) + !linkedPr?.headSha || + linkedPr.headSha.toLowerCase() === headSha.trim().toLowerCase() + ) { continue; - const linkedPr = current.pullRequestId - ? this.findPullRequestRowById(current.pullRequestId) - : undefined; - const knownCheckoutMismatch = - !!head && - syntheticPullRequestNumber(head, repo) !== null && - !!current.headSha && - !!linkedPr?.headSha && - linkedPr.headSha.toLowerCase() !== - current.headSha.trim().toLowerCase(); - if (knownCheckoutMismatch && current.pullRequestId && current.headSha) { - this.db - .update(workspaces) - .set({ pullRequestId: null }) - .where( - and( - eq(workspaces.id, current.id), - isNull(workspaces.archivedAt), - eq(workspaces.branch, current.branch), - eq(workspaces.headSha, current.headSha), - eq(workspaces.pullRequestId, current.pullRequestId), - current.upstreamOwner === null - ? isNull(workspaces.upstreamOwner) - : eq(workspaces.upstreamOwner, current.upstreamOwner), - current.upstreamRepo === null - ? isNull(workspaces.upstreamRepo) - : eq(workspaces.upstreamRepo, current.upstreamRepo), - current.upstreamBranch === null - ? isNull(workspaces.upstreamBranch) - : eq(workspaces.upstreamBranch, current.upstreamBranch), - ), - ) - .run(); } - continue; } if (workspace.pullRequestId) { this.db .update(workspaces) .set({ pullRequestId: null }) - .where( - and(eq(workspaces.id, workspace.id), isNull(workspaces.archivedAt)), - ) + .where(linkCondition) .run(); } } From e590abb8a2a832a3e7b359c1e16974ccb9fd8256 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B8=D0=BA=D1=82=D0=BE=D1=80=20=D0=91=D1=8B=D1=81?= =?UTF-8?q?=D1=82=D1=80=D0=BE=D0=B2?= Date: Wed, 18 Nov 2026 15:52:56 +0500 Subject: [PATCH 5/6] fix(host-service): preserve the latest PR head observation --- .../pull-requests/pull-requests.test.ts | 173 ++++++++++--- .../runtime/pull-requests/pull-requests.ts | 228 +++++++++++------- .../utils/github-query/github-query.ts | 27 --- 3 files changed, 274 insertions(+), 154 deletions(-) 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 e36290c7bee..15292c2227a 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. @@ -359,17 +365,25 @@ describe("PullRequestRuntimeManager synthetic PR refs", () => { offline: false, headSha: "abc123", beforeLookup: undefined as (() => Promise) | undefined, + beforeChecks: undefined as (() => Promise) | undefined, + branchHeadSha: null as string | null, }; const manager = createManager(db, { - readWorkspaceRefs: async () => { - const workspace = getWorkspace(db, "ws"); + readWorkspaceRefs: async (worktreePath) => { + const workspace = getWorkspace( + db, + worktreePath.split("/").at(-1) ?? "", + ); return { branch: workspace?.branch ?? null, headSha: workspace?.headSha ?? null, upstream: { owner: workspace?.upstreamOwner ?? REPO.owner, name: workspace?.upstreamRepo ?? REPO.name, - branch: workspace?.upstreamBranch ?? "refs/pull/42/head", + branch: + workspace?.upstreamBranch ?? + workspace?.branch ?? + "refs/pull/42/head", }, }; }, @@ -391,7 +405,22 @@ describe("PullRequestRuntimeManager synthetic PR refs", () => { mergedAt: "2026-05-01T10:00:00Z", }); } - if (path?.endsWith("/check-runs")) return { check_runs: [] }; + 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 []; }, }); @@ -538,6 +567,90 @@ describe("PullRequestRuntimeManager synthetic PR refs", () => { 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); + }); }); describe("PullRequestRuntimeManager mergedAt attribution", () => { @@ -1240,22 +1353,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); }); }); @@ -1283,26 +1389,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 220b095f5e5..878dba460f4 100644 --- a/packages/host-service/src/runtime/pull-requests/pull-requests.ts +++ b/packages/host-service/src/runtime/pull-requests/pull-requests.ts @@ -185,6 +185,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; @@ -262,11 +277,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 @@ -274,29 +285,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; @@ -659,6 +659,7 @@ export class PullRequestRuntimeManager { error: null, now, }); + this.appliedPullRequestSequence.set(rowId, ++this.requestSequence); const upstream = deriveCheckoutPullRequestUpstream(repo, pullRequest); this.db @@ -1064,8 +1065,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, @@ -1102,6 +1106,7 @@ export class PullRequestRuntimeManager { } continue; } + if (supersededKeys.has(key)) continue; const rawMatch = keyToPullRequest.get(key); const head = wantedRefs.get(key); const isSyntheticCheckout = @@ -1113,6 +1118,13 @@ export class PullRequestRuntimeManager { isNull(workspaces.archivedAt), ); if (isSyntheticCheckout) { + if ( + rawMatch && + (this.appliedPullRequestSequence.get(rawMatch.id) ?? 0) > + rawMatch.sequence && + !this.pullRequestHeadMatches(rawMatch.id, rawMatch.headSha) + ) + continue; const sameCheckout = and( linkCondition, eq(workspaces.projectId, projectId), @@ -1135,6 +1147,7 @@ export class PullRequestRuntimeManager { continue; } headSha = current.headSha; + if (!headSha) continue; linkCondition = and( sameCheckout, sql`${workspaces.headSha} IS ${headSha}`, @@ -1143,7 +1156,7 @@ export class PullRequestRuntimeManager { const checkoutHeadChanged = !!rawMatch && isSyntheticCheckout && - !this.pullRequestHeadMatches(rawMatch.id, headSha); + 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 = @@ -1491,20 +1504,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 @@ -1519,13 +1524,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, @@ -1552,15 +1558,17 @@ export class PullRequestRuntimeManager { }, ); cache.set(cacheKey, entry); - return entry.promise; + return entry; } - private async getCachedPullRequestForRef( + 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); // Branch stays case-sensitive so two case-variant branches can't share // a cache entry and return each other's PR. const cacheKey = [ @@ -1570,30 +1578,37 @@ export class PullRequestRuntimeManager { head.repo.toLowerCase(), head.branch, ].join("/"); - return this.cachedGitHubFetch( + return this.cachedGitHubRequest( this.pullRequestHeadCache, cacheKey, options, () => this.fetchFromGitHub( - prNumber === null ? "PR head lookup" : "PR number lookup", + "PR head lookup", { owner: repo.owner, name: repo.name, head }, - () => - prNumber !== null - ? fetchPullRequestByNumberFromGh(this.execGh, repo, prNumber) - : fetchPullRequestByHeadFromGh( - this.execGh, - { owner: repo.owner, name: repo.name }, - head, - ), + () => fetchPullRequestByHeadFromGh(this.execGh, repo, head), + async () => fetchPullRequestByHead(await this.github(), repo, head), + { 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 () => - prNumber !== null - ? fetchPullRequestByNumber(await this.github(), repo, prNumber) - : fetchPullRequestByHead( - await this.github(), - { owner: repo.owner, name: repo.name }, - head, - ), + fetchPullRequestByNumber(await this.github(), repo, prNumber), { probe: options.bypassCache === true }, ), ); @@ -1613,7 +1628,7 @@ export class PullRequestRuntimeManager { name: repo.name, prNumber: node.number, }; - return this.cachedGitHubFetch( + return this.cachedGitHubRequest( this.pullRequestDetailsCache, cacheKey, { ...options, fingerprint: node.headRefOid }, @@ -1678,18 +1693,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, @@ -1774,20 +1789,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. @@ -1795,6 +1802,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; @@ -1822,6 +1830,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", @@ -1836,22 +1845,24 @@ 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.getCachedPullRequestForRef( - repo, - head, - options, - ); + const request = this.getCachedPullRequestForRef(repo, head, options); + const node = await request.promise; if (!node) return; const nodeKey = upstreamKey( @@ -1863,7 +1874,7 @@ export class PullRequestRuntimeManager { nodeKey === key || node.number === syntheticPullRequestNumber(head, repo) ) { - latestByKey.set(key, node); + latestByKey.set(key, { node, sequence: request.sequence }); } } catch (error) { failedKeys.add(key); @@ -1895,7 +1906,8 @@ export class PullRequestRuntimeManager { .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. @@ -1913,7 +1925,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 @@ -1927,10 +1939,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, @@ -1951,8 +1973,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 @@ -1984,9 +2028,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.ts b/packages/host-service/src/runtime/pull-requests/utils/github-query/github-query.ts index 9f9c73e1bc1..1404b9ba20a 100644 --- a/packages/host-service/src/runtime/pull-requests/utils/github-query/github-query.ts +++ b/packages/host-service/src/runtime/pull-requests/utils/github-query/github-query.ts @@ -229,33 +229,6 @@ function toStatusContextNode( }; } -export async function fetchPullRequestByNumberFromGh( - execGh: ExecGh, - repository: { owner: string; name: string }, - prNumber: number, -): Promise { - const raw = await execGh([ - "api", - "--method", - "GET", - `repos/${repository.owner}/${repository.name}/pulls/${prNumber}`, - ]); - return normalizePullRequest(raw); -} - -export async function fetchPullRequestByNumber( - octokit: Octokit, - repository: { owner: string; name: string }, - prNumber: number, -): Promise { - const response = await octokit.rest.pulls.get({ - owner: repository.owner, - repo: repository.name, - pull_number: prNumber, - }); - return normalizePullRequest(response.data); -} - export async function fetchPullRequestByHeadFromGh( execGh: ExecGh, repository: { From 75f1e93f6e0538676a753ac2b554d05500461b38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B8=D0=BA=D1=82=D0=BE=D1=80=20=D0=91=D1=8B=D1=81?= =?UTF-8?q?=D1=82=D1=80=D0=BE=D0=B2?= Date: Wed, 18 Nov 2026 16:15:53 +0500 Subject: [PATCH 6/6] fix(host-service): distinguish tracked PR refs from branch names --- .../pull-requests/pull-requests.test.ts | 51 +++++++++++++- .../runtime/pull-requests/pull-requests.ts | 69 +++++++++++-------- .../utils/workspace-refs.test.ts | 50 ++++++++++++++ .../pull-requests/utils/workspace-refs.ts | 39 ++++++++++- 4 files changed, 177 insertions(+), 32 deletions(-) create mode 100644 packages/host-service/src/runtime/pull-requests/utils/workspace-refs.test.ts 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 15292c2227a..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 @@ -366,6 +366,8 @@ describe("PullRequestRuntimeManager synthetic PR refs", () => { 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, { @@ -374,8 +376,9 @@ describe("PullRequestRuntimeManager synthetic PR refs", () => { db, worktreePath.split("/").at(-1) ?? "", ); + await network.beforeRefs?.(); return { - branch: workspace?.branch ?? null, + branch: network.overrideBranch ?? workspace?.branch ?? null, headSha: workspace?.headSha ?? null, upstream: { owner: workspace?.upstreamOwner ?? REPO.owner, @@ -651,6 +654,52 @@ describe("PullRequestRuntimeManager synthetic PR refs", () => { ); 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", () => { 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 878dba460f4..4dedc089605 100644 --- a/packages/host-service/src/runtime/pull-requests/pull-requests.ts +++ b/packages/host-service/src/runtime/pull-requests/pull-requests.ts @@ -58,6 +58,9 @@ import { type ReviewDecision, } from "./utils/pull-request-mappers"; import { + decodeHeadBranch, + encodeHeadBranch, + pullRequestRefNumber, readWorkspaceRefs, type WorkspaceRefsSnapshot, } from "./utils/workspace-refs"; @@ -107,9 +110,7 @@ function syntheticPullRequestNumber( ) { return null; } - const match = /^refs\/pull\/([1-9]\d*)\/head$/.exec(head.branch); - const number = match ? Number(match[1]) : NaN; - return Number.isSafeInteger(number) ? number : null; + return pullRequestRefNumber(head.branch); } type RepoProvider = "github"; @@ -230,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 { @@ -890,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 && @@ -902,7 +906,7 @@ export class PullRequestRuntimeManager { upstreamOwner === workspace.upstreamOwner && upstreamRepo === workspace.upstreamRepo && upstreamBranch === workspace.upstreamBranch && - pullRequestId === workspace.pullRequestId + !shouldClearLink ) { return null; } @@ -915,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; @@ -1106,25 +1114,28 @@ export class PullRequestRuntimeManager { } continue; } - if (supersededKeys.has(key)) 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 lookupFailed = failedKeys.has(key); + 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) { - if ( - rawMatch && - (this.appliedPullRequestSequence.get(rawMatch.id) ?? 0) > - rawMatch.sequence && - !this.pullRequestHeadMatches(rawMatch.id, rawMatch.headSha) - ) - continue; const sameCheckout = and( linkCondition, eq(workspaces.projectId, projectId), @@ -1142,7 +1153,7 @@ export class PullRequestRuntimeManager { .get(); if ( !current || - (!lookupFailed && current.headSha !== workspace.headSha) + (!useStoredHead && current.headSha !== workspace.headSha) ) { continue; } @@ -1191,7 +1202,7 @@ export class PullRequestRuntimeManager { continue; } - if (lookupFailed) { + if (useStoredHead) { if (!isSyntheticCheckout || !workspace.pullRequestId || !headSha) { continue; } @@ -1569,6 +1580,7 @@ export class PullRequestRuntimeManager { 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 = [ @@ -1586,8 +1598,9 @@ export class PullRequestRuntimeManager { this.fetchFromGitHub( "PR head lookup", { owner: repo.owner, name: repo.name, head }, - () => fetchPullRequestByHeadFromGh(this.execGh, repo, head), - async () => fetchPullRequestByHead(await this.github(), repo, head), + () => fetchPullRequestByHeadFromGh(this.execGh, repo, branchHead), + async () => + fetchPullRequestByHead(await this.github(), repo, branchHead), { probe: options.bypassCache === true }, ), ); @@ -1868,7 +1881,7 @@ export class PullRequestRuntimeManager { const nodeKey = upstreamKey( node.headRepositoryOwner?.login ?? null, node.headRepository?.name ?? null, - node.headRefName, + encodeHeadBranch(node.headRefName), ); if ( nodeKey === key || @@ -1916,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(); 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 {