Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
151 changes: 151 additions & 0 deletions packages/host-service/src/runtime/pull-requests/pull-requests.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,157 @@ describe("PullRequestRuntimeManager refresh", () => {
});
});

// Builds a REST PR node with an explicit state (open/closed/merged), unlike
// `makePrNode` which is always open.
function makePrNodeWithState(pr: {
number: number;
headRef: string;
headSha: string;
state: "open" | "closed" | "merged";
title?: string;
}) {
return {
...makePrNode({
number: pr.number,
headRef: pr.headRef,
headSha: pr.headSha,
title: pr.title,
}),
state: pr.state === "merged" ? "closed" : pr.state,
merged_at: pr.state === "merged" ? "2026-05-01T00:00:00Z" : null,
};
}

// Routes the per-head PR lookup plus its review/check detail fetches to a
// single PR node, so a link is established iff the manager decides to.
function routeSinglePr(node: unknown) {
return async (args: string[]): Promise<unknown> => {
if (args.includes("graphql")) {
return {
data: { repository: { pullRequest: { mergeQueueEntry: null } } },
};
}
const path = args.find(
(arg) => typeof arg === "string" && arg.startsWith("repos/"),
);
if (path?.endsWith("/reviews")) return [];
if (path?.endsWith("/check-runs")) return { check_runs: [] };
if (path?.endsWith("/statuses")) return [];
if (path === `repos/${REPO.owner}/${REPO.name}/pulls`) {
return [node];
}
throw new Error(`unexpected gh path: ${path}`);
};
}

describe("default branch stale PR isolation", () => {
// #4508 / #4260 / #4513.1: someone opened a throwaway PR *from* the default
// branch (head=main) and closed it. The default-branch workspace has since
// advanced past that PR's head commit, so the closed PR must not attach.
test("does not link the default branch to a closed PR it has advanced past", async () => {
const db = createRealDb();
seedProject(db);
seedWorkspace(db, {
id: "ws-main",
branch: "main",
headSha: "current-main-sha",
upstreamOwner: REPO.owner,
upstreamRepo: REPO.name,
upstreamBranch: "main",
});
const manager = createManager(db, {
execGh: routeSinglePr(
makePrNodeWithState({
number: 10,
headRef: "main",
headSha: "old-main-sha",
state: "closed",
title: "Merge main into feature",
}),
),
});

await withSilencedWarnings(() =>
manager.refreshPullRequestsByWorkspaces(["ws-main"]),
);

expect(getWorkspace(db, "ws-main")?.pullRequestId).toBeNull();
});

// Guard against over-clearing: a merged/closed PR must still show while the
// workspace is still sitting on that exact head commit.
test("keeps a closed PR linked while the workspace HEAD still matches its head", async () => {
const db = createRealDb();
seedProject(db);
seedWorkspace(db, {
id: "ws-feature",
branch: "feature",
headSha: "feature-head-sha",
upstreamOwner: REPO.owner,
upstreamRepo: REPO.name,
upstreamBranch: "feature",
});
const manager = createManager(db, {
execGh: routeSinglePr(
makePrNodeWithState({
number: 11,
headRef: "feature",
headSha: "feature-head-sha",
state: "closed",
title: "Closed feature PR",
}),
),
});

await withSilencedWarnings(() =>
manager.refreshPullRequestsByWorkspaces(["ws-feature"]),
);

expect(getWorkspace(db, "ws-feature")?.pullRequestId).toBe(
getPrByNumber(db, 11)?.id,
);
});

// Also clears a stale link that a previous (buggy) run persisted.
test("clears an existing link to a closed PR once the workspace HEAD moves on", async () => {
const db = createRealDb();
seedProject(db);
seedPullRequest(db, {
id: "pr-stale",
prNumber: 10,
headBranch: "main",
headSha: "old-main-sha",
state: "closed",
});
seedWorkspace(db, {
id: "ws-main",
branch: "main",
headSha: "current-main-sha",
upstreamOwner: REPO.owner,
upstreamRepo: REPO.name,
upstreamBranch: "main",
pullRequestId: "pr-stale",
});
const manager = createManager(db, {
execGh: routeSinglePr(
makePrNodeWithState({
number: 10,
headRef: "main",
headSha: "old-main-sha",
state: "closed",
title: "Merge main into feature",
}),
),
});

await withSilencedWarnings(() =>
manager.refreshPullRequestsByWorkspaces(["ws-main"]),
);

expect(getWorkspace(db, "ws-main")?.pullRequestId).toBeNull();
});
});

// Routes gh REST/GraphQL calls to fixtures keyed by the exact head branch, so
// a wrong-case cache hit or key collision surfaces as the wrong PR number.
function routeGh(prsByHeadRef: Record<string, ReturnType<typeof makePrNode>>) {
Expand Down
51 changes: 48 additions & 3 deletions packages/host-service/src/runtime/pull-requests/pull-requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,26 @@ function upstreamKey(
return `${owner.toLowerCase()}/${repo.toLowerCase()}#${branch}`;
}

// Closed and merged PRs are historical: they should only stay attached to a
// workspace whose HEAD still points at the PR's exact head commit. Reusing a
// branch name (most commonly the default branch after someone opens a throwaway
// PR *from* it — #4508, #4260, #4513) otherwise surfaces an old, unrelated PR.
function isHistoricalPullRequestState(
state: GitHubPullRequestNode["state"],
): boolean {
return state === "CLOSED" || state === "MERGED";
}

function headShaMatches(
workspaceHeadSha: string | null,
prHeadSha: string,
): boolean {
if (!workspaceHeadSha) return false;
return (
workspaceHeadSha.trim().toLowerCase() === prHeadSha.trim().toLowerCase()
);
}

type RepoProvider = "github";

export interface PullRequestStateSnapshot {
Expand Down Expand Up @@ -686,6 +706,24 @@ export class PullRequestRuntimeManager {
}
const match = keyToPullRequest.get(key);
if (match) {
// Historical (closed/merged) PRs only stay attached while the
// workspace HEAD still matches the PR head. Otherwise a reused
// branch name — e.g. the default branch after a throwaway PR was
// opened from it (#4508, #4260, #4513) — would show a stale PR.
if (
match.historical &&
!headShaMatches(workspace.headSha, match.headSha)
) {
if (workspace.pullRequestId) {
this.db
.update(workspaces)
.set({ pullRequestId: null })
.where(eq(workspaces.id, workspace.id))
.run();
}
continue;
}

this.db
.update(workspaces)
.set({ pullRequestId: match.id })
Expand Down Expand Up @@ -980,10 +1018,13 @@ export class PullRequestRuntimeManager {
wantedRefs: Map<string, GitHubPullRequestHeadRef>,
options: { bypassCache?: boolean } = {},
): Promise<{
matched: Map<string, { id: string }>;
matched: Map<string, { id: string; historical: boolean; headSha: string }>;
failedKeys: Set<string>;
}> {
const matched = new Map<string, { id: string }>();
const matched = new Map<
string,
{ id: string; historical: boolean; headSha: string }
>();
const failedKeys = new Set<string>();
if (wantedRefs.size === 0) return { matched, failedKeys };

Expand Down Expand Up @@ -1192,7 +1233,11 @@ export class PullRequestRuntimeManager {
now,
});

matched.set(key, { id: rowId });
matched.set(key, {
id: rowId,
historical: isHistoricalPullRequestState(node.state),
headSha: node.headRefOid,
});
}

return { matched, failedKeys };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,55 @@ describe("GitHub pull request REST queries", () => {
]);
});

// #4513.2: a branch can carry both an old closed PR and a live open PR. The
// REST list is sorted by `updated desc`, so if the closed PR was touched most
// recently it comes first — but we must surface the OPEN one.
test("prefers the open PR when a head branch has both closed and open PRs", async () => {
const { execGh } = createExecGh([
[
{
number: 50,
title: "Old closed PR",
html_url: "https://github.com/superset-sh/superset/pull/50",
state: "closed",
draft: false,
merged_at: null,
updated_at: "2026-05-09T12:00:00Z",
head: {
ref: "feature",
sha: "closedsha",
repo: { name: "superset", owner: { login: "superset-sh" } },
},
base: { repo: { full_name: "superset-sh/superset" } },
},
{
number: 51,
title: "Live open PR",
html_url: "https://github.com/superset-sh/superset/pull/51",
state: "open",
draft: false,
merged_at: null,
updated_at: "2026-05-08T12:00:00Z",
head: {
ref: "feature",
sha: "opensha",
repo: { name: "superset", owner: { login: "superset-sh" } },
},
base: { repo: { full_name: "superset-sh/superset" } },
},
],
]);

const result = await fetchPullRequestByHeadFromGh(
execGh,
{ owner: "superset-sh", name: "superset" },
{ owner: "superset-sh", repo: "superset", branch: "feature" },
);

expect(result?.number).toBe(51);
expect(result?.state).toBe("OPEN");
});

test("filters REST head candidates by exact upstream repository", async () => {
const { execGh } = createExecGh([
[
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,19 +125,24 @@ function normalizePullRequestCandidates(
head: GitHubPullRequestHeadRef,
): GitHubPullRequestNode | null {
const requestedKey = headKey(head.owner, head.repo, head.branch);
return (
asArray(raw)
.map((item) => normalizePullRequest(item))
.find(
(node) =>
node &&
headKey(
node.headRepositoryOwner?.login,
node.headRepository?.name,
node.headRefName,
) === requestedKey,
) ?? null
);
const matches = asArray(raw)
.map((item) => normalizePullRequest(item))
.filter(
(node): node is GitHubPullRequestNode =>
node !== null &&
headKey(
node.headRepositoryOwner?.login,
node.headRepository?.name,
node.headRefName,
) === requestedKey,
);
if (matches.length === 0) return null;

// A single head branch can carry both an old closed/merged PR and the live
// open one (#4513). The REST list is sorted by `updated desc`, so a recently
// touched closed PR would otherwise win — prefer the OPEN candidate, and only
// fall back to the most recently updated when none is open.
return matches.find((node) => node.state === "OPEN") ?? matches[0] ?? null;
}

function mapReviewDecision(
Expand Down