Skip to content

Commit a0844ea

Browse files
perf(server): merged-PR threads no longer re-read git state every minute (pingdotgg#24099)
Co-authored-by: Julius Marminge <[email protected]>
1 parent 13034bf commit a0844ea

6 files changed

Lines changed: 368 additions & 6 deletions

File tree

‎apps/server/src/git/GitManager.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1152,6 +1152,12 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
11521152
"for-each-ref",
11531153
]);
11541154
expect(freshLookups()).toBe(0);
1155+
gitCommands.length = 0;
1156+
yield* manager.branchPullRequest(
1157+
{ cwd: repoDir, branch: "feature/settled" },
1158+
{ confirmTerminal: false },
1159+
);
1160+
expect(gitCommands).toEqual([]);
11551161

11561162
NodeFS.writeFileSync(NodePath.join(repoDir, "settled.txt"), "new work\n");
11571163
yield* runGit(repoDir, ["add", "settled.txt"]);

‎apps/server/src/git/GitManager.ts‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -136,10 +136,18 @@ export class GitManager extends Context.Service<
136136
input: VcsStatusInput,
137137
options?: GitRemoteStatusOptions,
138138
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
139-
/** refresh queries the host; freshGitState rereads only git state and is required before persisting. */
139+
/**
140+
* refresh queries the host; freshGitState rereads only git state and is required before persisting.
141+
* A merged or closed answer is confirmed against git state unless confirmTerminal is false;
142+
* callers that opt out confirm before acting on it.
143+
*/
140144
readonly branchPullRequest: (
141145
input: { readonly cwd: string; readonly branch: string },
142-
options?: { readonly refresh?: boolean; readonly freshGitState?: boolean },
146+
options?: {
147+
readonly refresh?: boolean;
148+
readonly freshGitState?: boolean;
149+
readonly confirmTerminal?: boolean;
150+
},
143151
) => Effect.Effect<GitBranchPullRequest | null, GitManagerServiceError>;
144152
/** Whether T3 checked this pull request out onto the branch, which ties it to later threads. */
145153
readonly checkedOutPullRequest: (input: {
@@ -2492,7 +2500,8 @@ export const make = Effect.gen(function* () {
24922500
});
24932501
return mergeGitStatusParts(local, remote);
24942502
});
2495-
// Closed PR results can settle threads or remove worktrees; confirm fresh git state before persisting.
2503+
// Closed PR results can settle threads or remove worktrees; confirm fresh git state before
2504+
// persisting, and before acting when a caller skipped confirmation (`confirmTerminal: false`).
24962505
const prLookupGitStateByKey = new Map<
24972506
string,
24982507
{ readonly readAtMs: number; readonly value: string | null }
@@ -2789,7 +2798,14 @@ export const make = Effect.gen(function* () {
27892798
refresh,
27902799
freshGitState,
27912800
});
2792-
if (pullRequest === null || pullRequest.state === "open" || freshGitState) return pullRequest;
2801+
if (
2802+
pullRequest === null ||
2803+
pullRequest.state === "open" ||
2804+
freshGitState ||
2805+
options?.confirmTerminal === false
2806+
) {
2807+
return pullRequest;
2808+
}
27932809
// A confirmed closed or merged result stays final until the branch or remotes change,
27942810
// with a periodic fresh lookup so a new PR from a reused branch still shows up.
27952811
const settledKey = `${cacheCwd}\u0000${branch}`;

‎apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts‎

Lines changed: 246 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -832,4 +832,250 @@ describe("ThreadPullRequestServiceV2 reads", () => {
832832
}),
833833
),
834834
);
835+
836+
it.effect("a saved merged branch PR rereads no git state on each sweep", () =>
837+
Effect.scoped(
838+
Effect.gen(function* () {
839+
const savedReference = {
840+
projectId: ProjectId.make("project-1"),
841+
repository: "acme/project",
842+
number: 42,
843+
url: "https://github.com/acme/project/pull/42",
844+
};
845+
const thread = {
846+
...threadShell("merged-branch-thread"),
847+
branch: "feature/merged",
848+
branchPullRequest: savedReference,
849+
};
850+
const project: OrchestrationProjectShell = {
851+
id: thread.projectId,
852+
title: "Project",
853+
workspaceRoot: "/workspace/project",
854+
defaultModelSelection: null,
855+
scripts: [],
856+
createdAt: "2026-08-01T00:00:00.000Z",
857+
updatedAt: "2026-08-01T00:00:00.000Z",
858+
};
859+
const activation = yield* Deferred.make<void>();
860+
const sweeps = yield* Queue.unbounded<void>();
861+
const commands: Array<OrchestrationV2ServerCommand> = [];
862+
const lookups: Array<Parameters<GitManager.GitManager["Service"]["branchPullRequest"]>[1]> =
863+
[];
864+
const dependencies = Layer.mergeAll(
865+
Layer.mock(Orchestrator.OrchestratorV2)({
866+
streamDomainEvents: Stream.never,
867+
getPullRequestSnapshot: () =>
868+
Queue.offer(sweeps, undefined).pipe(
869+
Effect.as({
870+
schemaVersion: 2,
871+
snapshotSequence: 1,
872+
threads: [thread],
873+
archivedThreads: [],
874+
}),
875+
),
876+
dispatch: (command) =>
877+
Effect.sync(() => {
878+
commands.push(command);
879+
return { sequence: 2, storedEvents: [] };
880+
}),
881+
}),
882+
Layer.mock(ProjectStore.ProjectStoreV2)({
883+
listShells: () => Effect.succeed([project]),
884+
getShell: () => Effect.succeedSome(project),
885+
}),
886+
Layer.mock(GitManager.GitManager)({
887+
branchPullRequest: (_input, options) =>
888+
Effect.sync(() => {
889+
lookups.push(options);
890+
return {
891+
number: 42,
892+
title: "Merged work",
893+
url: savedReference.url,
894+
baseRef: "main",
895+
headRef: thread.branch,
896+
state: "merged" as const,
897+
repositoryKey: "github.com/acme/project",
898+
updatedAt: "2026-09-19T00:00:00.000Z",
899+
closedAt: null,
900+
mergedAt: "2026-09-19T00:00:00.000Z",
901+
};
902+
}),
903+
}),
904+
Layer.mock(PullRequestService.PullRequestService)({}),
905+
Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
906+
resolve: () =>
907+
Effect.succeed({
908+
canonicalKey: "github.com/acme/project",
909+
locator: {
910+
source: "git-remote" as const,
911+
remoteName: "origin",
912+
remoteUrl: "[email protected]:acme/project.git",
913+
},
914+
provider: SourceControlProviderKind.make("github"),
915+
owner: "acme",
916+
name: "project",
917+
}),
918+
}),
919+
// A connected client keeps the periodic sweep running.
920+
Layer.mock(BackgroundPolicy.BackgroundPolicy)({
921+
shouldRunOpportunisticWork: Effect.succeed(true),
922+
}),
923+
Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
924+
Layer.succeed(
925+
SecureRandom.SecureRandom,
926+
SecureRandom.make((size) => new Uint8Array(size).fill(1)),
927+
),
928+
FileSystem.layerNoop({}),
929+
Path.layer,
930+
);
931+
yield* Effect.gen(function* () {
932+
const service = yield* ThreadPullRequestService.make;
933+
yield* service.start();
934+
yield* Deferred.succeed(activation, undefined);
935+
yield* Queue.take(sweeps);
936+
yield* service.drain;
937+
yield* TestClock.adjust("1 minute");
938+
yield* Queue.take(sweeps);
939+
yield* service.drain;
940+
}).pipe(Effect.provide(dependencies));
941+
942+
expect(commands).toEqual([]);
943+
expect(lookups).toHaveLength(2);
944+
// GitManager rereads git state on request, and by default whenever its
945+
// remembered answer is merged or closed.
946+
expect(
947+
lookups.filter(
948+
(options) =>
949+
options?.refresh === true ||
950+
options?.freshGitState === true ||
951+
options?.confirmTerminal !== false,
952+
),
953+
).toEqual([]);
954+
}),
955+
),
956+
);
957+
958+
const mergedPullRequest43 = {
959+
number: 43,
960+
title: "Replacement work",
961+
url: "https://github.com/acme/project/pull/43",
962+
baseRef: "main",
963+
headRef: "feature/replaced",
964+
state: "merged" as const,
965+
repositoryKey: "github.com/acme/project",
966+
updatedAt: "2026-09-19T00:00:00.000Z",
967+
closedAt: null,
968+
mergedAt: "2026-09-19T00:00:00.000Z",
969+
};
970+
971+
it.effect.each([
972+
{ name: "reopened", fresh: { ...mergedPullRequest43, state: "open" as const }, writes: false },
973+
{ name: "the same merged PR", fresh: mergedPullRequest43, writes: true },
974+
])("saves a remembered merged PR only when fresh git state finds $name", ({ fresh, writes }) =>
975+
Effect.scoped(
976+
Effect.gen(function* () {
977+
const savedReference = {
978+
projectId: ProjectId.make("project-1"),
979+
repository: "acme/project",
980+
number: 42,
981+
url: "https://github.com/acme/project/pull/42",
982+
};
983+
const thread = {
984+
...threadShell("replaced-branch-thread"),
985+
createdAt: DateTime.makeUnsafe("2026-09-01T00:00:00.000Z"),
986+
branch: mergedPullRequest43.headRef,
987+
branchPullRequest: savedReference,
988+
};
989+
const project: OrchestrationProjectShell = {
990+
id: thread.projectId,
991+
title: "Project",
992+
workspaceRoot: "/workspace/project",
993+
defaultModelSelection: null,
994+
scripts: [],
995+
createdAt: "2026-08-01T00:00:00.000Z",
996+
updatedAt: "2026-08-01T00:00:00.000Z",
997+
};
998+
const activation = yield* Deferred.make<void>();
999+
const sweeps = yield* Queue.unbounded<void>();
1000+
const commands: Array<OrchestrationV2ServerCommand> = [];
1001+
const dependencies = Layer.mergeAll(
1002+
Layer.mock(Orchestrator.OrchestratorV2)({
1003+
streamDomainEvents: Stream.never,
1004+
getPullRequestSnapshot: () =>
1005+
Queue.offer(sweeps, undefined).pipe(
1006+
Effect.as({
1007+
schemaVersion: 2,
1008+
snapshotSequence: 1,
1009+
threads: [thread],
1010+
archivedThreads: [],
1011+
}),
1012+
),
1013+
dispatch: (command) =>
1014+
Effect.sync(() => {
1015+
commands.push(command);
1016+
return { sequence: 2, storedEvents: [] };
1017+
}),
1018+
}),
1019+
Layer.mock(ProjectStore.ProjectStoreV2)({
1020+
listShells: () => Effect.succeed([project]),
1021+
getShell: () => Effect.succeedSome(project),
1022+
}),
1023+
// Only the fresh read disagrees with the remembered detection.
1024+
Layer.mock(GitManager.GitManager)({
1025+
branchPullRequest: (_input, options) =>
1026+
Effect.succeed(options?.freshGitState === true ? fresh : mergedPullRequest43),
1027+
}),
1028+
Layer.mock(PullRequestService.PullRequestService)({}),
1029+
Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
1030+
resolve: () =>
1031+
Effect.succeed({
1032+
canonicalKey: "github.com/acme/project",
1033+
locator: {
1034+
source: "git-remote" as const,
1035+
remoteName: "origin",
1036+
remoteUrl: "[email protected]:acme/project.git",
1037+
},
1038+
provider: SourceControlProviderKind.make("github"),
1039+
owner: "acme",
1040+
name: "project",
1041+
}),
1042+
}),
1043+
Layer.mock(BackgroundPolicy.BackgroundPolicy)({
1044+
shouldRunOpportunisticWork: Effect.succeed(true),
1045+
}),
1046+
Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
1047+
Layer.succeed(
1048+
SecureRandom.SecureRandom,
1049+
SecureRandom.make((size) => new Uint8Array(size).fill(1)),
1050+
),
1051+
FileSystem.layerNoop({}),
1052+
Path.layer,
1053+
);
1054+
yield* Effect.gen(function* () {
1055+
const service = yield* ThreadPullRequestService.make;
1056+
yield* service.start();
1057+
yield* Deferred.succeed(activation, undefined);
1058+
yield* Queue.take(sweeps);
1059+
yield* service.drain;
1060+
}).pipe(Effect.provide(dependencies));
1061+
1062+
expect(
1063+
commands.map((command) =>
1064+
command.type === "thread.pull-request.sync" ? command.branchPullRequest : command.type,
1065+
),
1066+
).toEqual(
1067+
writes
1068+
? [
1069+
{
1070+
projectId: project.id,
1071+
repository: "acme/project",
1072+
number: 43,
1073+
url: mergedPullRequest43.url,
1074+
},
1075+
]
1076+
: [],
1077+
);
1078+
}),
1079+
),
1080+
);
8351081
});

‎apps/server/src/orchestration-v2/ThreadPullRequestService.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,12 +204,13 @@ export const make = Effect.gen(function* () {
204204
.pipe(Effect.orElseSucceed(() => true)))
205205
? first.worktreePath
206206
: project.workspaceRoot;
207+
// A detected PR is confirmed against fresh git state before it is saved.
207208
const detected =
208209
first.branch === null
209210
? null
210211
: yield* git.branchPullRequest(
211212
{ cwd, branch: first.branch },
212-
{ refresh: request.refresh },
213+
{ refresh: request.refresh, confirmTerminal: false },
213214
);
214215
if (detected !== null && !pullRequestMatchesProject(detected, resolvedProject)) {
215216
return finishBackfill(group);

0 commit comments

Comments
 (0)