Skip to content

Commit f8fbc19

Browse files
fix(server): one finished turn looks up its branch's pull request once (pingdotgg#33752)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 7171fdd commit f8fbc19

2 files changed

Lines changed: 156 additions & 4 deletions

File tree

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

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,139 @@ describe("ThreadPullRequestServiceV2 reads", () => {
181181
),
182182
);
183183

184+
it.effect("looks up a finished turn's branch once for all its turn-end events", () =>
185+
Effect.scoped(
186+
Effect.gen(function* () {
187+
const thread = { ...threadShell("turn-end-thread"), branch: "t3/turn-end" };
188+
const otherThread = {
189+
...threadShell("other-turn-end-thread"),
190+
branch: "t3/other-turn-end",
191+
};
192+
const project: OrchestrationProjectShell = {
193+
id: thread.projectId,
194+
title: "Project",
195+
workspaceRoot: "/workspace/project",
196+
defaultModelSelection: null,
197+
scripts: [],
198+
createdAt: "2026-08-01T00:00:00.000Z",
199+
updatedAt: "2026-08-01T00:00:00.000Z",
200+
};
201+
// A turn end commits its checkpoints and the run's end together. The queued
202+
// non-refresh request ahead of them must still become a refresh when they join it.
203+
const turnEnd = [
204+
{ type: "thread.metadata-updated", threadId: thread.id },
205+
{ type: "checkpoint.captured", threadId: thread.id },
206+
{ type: "checkpoint.captured", threadId: thread.id },
207+
{ type: "run.updated", threadId: thread.id, payload: { status: "completed" } },
208+
{ type: "checkpoint.captured", threadId: otherThread.id },
209+
{ type: "run.updated", threadId: otherThread.id, payload: { status: "completed" } },
210+
] as Array<OrchestrationV2DomainEvent>;
211+
// Arrives during the thread's own lookup, which may already have read the old host state.
212+
const duringLookup = [
213+
{ type: "checkpoint.captured", threadId: thread.id },
214+
{ type: "thread.metadata-updated", threadId: thread.id },
215+
] as Array<OrchestrationV2DomainEvent>;
216+
const activation = yield* Deferred.make<void>();
217+
const sweepStarted = yield* Deferred.make<void>();
218+
const turnEndQueued = yield* Deferred.make<void>();
219+
const lookupStarted = yield* Deferred.make<void>();
220+
const followUpQueued = yield* Deferred.make<void>();
221+
const lookups: Array<{ readonly branch: string; readonly refresh: boolean }> = [];
222+
const dependencies = Layer.mergeAll(
223+
Layer.mock(Orchestrator.OrchestratorV2)({
224+
// The batch arrives while the worker is busy with the startup sweep.
225+
streamDomainEvents: Stream.fromEffect(Deferred.await(sweepStarted)).pipe(
226+
Stream.drain,
227+
Stream.concat(Stream.fromIterable(turnEnd)),
228+
Stream.concat(
229+
Stream.fromEffect(Deferred.succeed(turnEndQueued, undefined)).pipe(Stream.drain),
230+
),
231+
Stream.concat(Stream.fromEffect(Deferred.await(lookupStarted)).pipe(Stream.drain)),
232+
Stream.concat(Stream.fromIterable(duringLookup)),
233+
Stream.concat(
234+
Stream.fromEffect(Deferred.succeed(followUpQueued, undefined)).pipe(Stream.drain),
235+
),
236+
Stream.concat(Stream.never),
237+
),
238+
getPullRequestSnapshot: ({ threadId }) =>
239+
Effect.succeed({
240+
schemaVersion: 2,
241+
snapshotSequence: 1,
242+
threads: [thread, otherThread].filter(
243+
(candidate) => threadId === undefined || candidate.id === threadId,
244+
),
245+
archivedThreads: [],
246+
}),
247+
}),
248+
Layer.mock(ProjectStore.ProjectStoreV2)({
249+
listShells: () => Effect.succeed([project]),
250+
getShell: () => Effect.succeedSome(project),
251+
}),
252+
Layer.mock(GitManager.GitManager)({
253+
branchPullRequest: (input, options) =>
254+
Effect.gen(function* () {
255+
lookups.push({ branch: input.branch, refresh: options?.refresh ?? false });
256+
if (!(yield* Deferred.isDone(turnEndQueued))) {
257+
yield* Deferred.succeed(sweepStarted, undefined);
258+
yield* Deferred.await(turnEndQueued);
259+
} else if (
260+
input.branch === thread.branch &&
261+
!(yield* Deferred.isDone(followUpQueued))
262+
) {
263+
yield* Deferred.succeed(lookupStarted, undefined);
264+
yield* Deferred.await(followUpQueued);
265+
}
266+
return null;
267+
}),
268+
}),
269+
Layer.mock(PullRequestService.PullRequestService)({}),
270+
Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
271+
resolve: () =>
272+
Effect.succeed({
273+
canonicalKey: "github.com/acme/project",
274+
locator: {
275+
source: "git-remote" as const,
276+
remoteName: "origin",
277+
remoteUrl: "[email protected]:acme/project.git",
278+
},
279+
provider: SourceControlProviderKind.make("github"),
280+
owner: "acme",
281+
name: "project",
282+
}),
283+
}),
284+
Layer.mock(BackgroundPolicy.BackgroundPolicy)({
285+
shouldRunScopeWork: () => Effect.succeed(false),
286+
shouldRunOpportunisticWork: Effect.succeed(false),
287+
}),
288+
Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
289+
Layer.succeed(
290+
SecureRandom.SecureRandom,
291+
SecureRandom.make((size) => new Uint8Array(size).fill(1)),
292+
),
293+
FileSystem.layerNoop({}),
294+
Path.layer,
295+
);
296+
yield* Effect.gen(function* () {
297+
const service = yield* ThreadPullRequestService.make;
298+
yield* service.start();
299+
yield* Deferred.succeed(activation, undefined);
300+
yield* Deferred.await(followUpQueued);
301+
yield* service.drain;
302+
}).pipe(Effect.provide(dependencies));
303+
304+
// The startup sweep, one refresh lookup per thread for its turn-end batch, then one
305+
// follow-up refresh for the events that arrived during the thread's lookup.
306+
expect(lookups).toEqual([
307+
{ branch: thread.branch, refresh: false },
308+
{ branch: otherThread.branch, refresh: false },
309+
{ branch: thread.branch, refresh: true },
310+
{ branch: otherThread.branch, refresh: true },
311+
{ branch: thread.branch, refresh: true },
312+
]);
313+
}),
314+
),
315+
);
316+
184317
it.effect.each([
185318
{
186319
worktree: "a linked worktree",

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

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -346,8 +346,15 @@ export const make = Effect.gen(function* () {
346346
);
347347
});
348348

349+
// At most one queued request per thread, so a turn end's events share one lookup.
350+
// A request after that lookup starts queues another, so later host changes are still read.
351+
const queuedThreadRequests = new Map<ThreadId, { threadId: ThreadId; refresh: boolean }>();
352+
349353
const worker = yield* makeDrainableWorker((request: RefreshRequest) =>
350-
synchronize(request).pipe(
354+
Effect.suspend(() => {
355+
if (request.threadId !== null) queuedThreadRequests.delete(request.threadId);
356+
return synchronize(request);
357+
}).pipe(
351358
Effect.provideService(GitVcsDriver.BackgroundGitWork, true),
352359
Effect.catchCauseIf(
353360
(cause) => !Cause.hasInterruptsOnly(cause),
@@ -359,23 +366,35 @@ export const make = Effect.gen(function* () {
359366
),
360367
);
361368

369+
const enqueueThread = (threadId: ThreadId, refresh: boolean) =>
370+
Effect.suspend(() => {
371+
const queued = queuedThreadRequests.get(threadId);
372+
if (queued !== undefined) {
373+
queued.refresh ||= refresh;
374+
return Effect.void;
375+
}
376+
const request = { threadId, refresh };
377+
queuedThreadRequests.set(threadId, request);
378+
return worker.enqueue(request);
379+
});
380+
362381
const processEvent = (event: OrchestrationV2DomainEvent) => {
363382
switch (event.type) {
364383
case "thread.created":
365384
case "thread.unarchived":
366385
case "thread.metadata-updated":
367-
return worker.enqueue({ threadId: event.threadId, refresh: false });
386+
return enqueueThread(event.threadId, false);
368387
case "thread.unsettled":
369388
case "checkpoint.captured":
370-
return worker.enqueue({ threadId: event.threadId, refresh: true });
389+
return enqueueThread(event.threadId, true);
371390
case "run.updated":
372391
if (
373392
event.payload.status === "completed" ||
374393
event.payload.status === "failed" ||
375394
event.payload.status === "cancelled" ||
376395
event.payload.status === "interrupted"
377396
) {
378-
return worker.enqueue({ threadId: event.threadId, refresh: true });
397+
return enqueueThread(event.threadId, true);
379398
}
380399
break;
381400
}

0 commit comments

Comments
 (0)