TypeScript
fix(server): isolate pull request sync reads by project (#18854)
Alex Southwell382bf4d90623
diff --git a/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts b/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.tsindex ea8080f1158..9418de49d9f 100644--- a/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts+++ b/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts@@ -499,7 +499,7 @@ describe("PullRequestSyncReactor", () => {),);- it.effect("asks the host once for a pull request shared by two threads", () =>+ it.effect("asks the host once for a pull request shared by two threads in one project", () =>Effect.scoped(Effect.gen(function* () {yield* TestClock.setTime(Date.parse(NOW));@@ -516,6 +516,7 @@ describe("PullRequestSyncReactor", () => {yield* startAndSweep(fixture);assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);+ assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);const commands = yield* Ref.get(fixture.syncCommands);assert.deepStrictEqual(commands@@ -531,6 +532,86 @@ describe("PullRequestSyncReactor", () => {),);+ it.effect.each(["summary", "stack"] as const)(+ "isolates a failed project %s refresh and retries it after the other project succeeds",+ (operation) =>+ Effect.scoped(+ Effect.gen(function* () {+ yield* TestClock.setTime(Date.parse(NOW));+ const otherProject = ProjectId.make("other-project");+ const link = makeLink(42, { state: "merged", mergedAt: NOW });+ let failing = true;+ const failure = new PullRequestOperationError({ operation, detail: "checkout missing" });+ const fixture = yield* makeHarness({+ snapshot: makeSnapshot([+ makeThread("failing", { pullRequests: [link] }),+ makeThread("healthy", { projectId: otherProject, pullRequests: [link] }),+ makeThread("same-project", { projectId: otherProject, pullRequests: [link] }),+ ]),+ summary: (input) =>+ failing && input.projectId === PROJECT_ID && operation === "summary"+ ? Effect.fail(failure)+ : Effect.succeed(+ makeSummary(input, {+ state: "merged",+ mergedAt: NOW,+ title: input.projectId,+ }),+ ),+ stack: (input) =>+ failing && input.projectId === PROJECT_ID && operation === "stack"+ ? Effect.fail(failure)+ : Effect.succeed({+ id: input.projectId,+ number: 42,+ url: "https://github.com/owner/repository/stacks/42",+ base: "main",+ layers: [{ number: 42, headBranch: "feature", state: "merged" }],+ }),+ });+ yield* Effect.gen(function* () {+ const reactor = yield* startAndSweep(fixture);+ assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);+ yield* reactor.requestSync(link);+ yield* Queue.take(fixture.snapshotReads);+ yield* reactor.drain;+ const commands = yield* Ref.get(fixture.syncCommands);+ assert.sameDeepMembers(+ commands.map((command) => [+ command.threadId,+ command.snapshot.title,+ command.stack?.id,+ ]),+ [+ ["healthy", otherProject, otherProject],+ ["same-project", otherProject, otherProject],+ ],+ );+ assert.sameMembers(+ (yield* Ref.get(fixture.summaryCalls)).map((call) => call.projectId),+ [PROJECT_ID, otherProject],+ );+ assert.sameMembers(+ (yield* Ref.get(fixture.stackCalls)).map((call) => call.projectId),+ operation === "stack" ? [PROJECT_ID, otherProject] : [otherProject],+ );+ yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));+ failing = false;+ yield* sweepAgain(fixture, reactor);+ assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 3);+ assert.strictEqual(+ (yield* Ref.get(fixture.summaryCalls)).at(-1)?.projectId,+ PROJECT_ID,+ );+ const retried = (yield* Ref.get(fixture.syncCommands)).at(-1);+ assert.strictEqual(retried?.threadId, ThreadId.make("failing"));+ assert.strictEqual(retried?.snapshot.title, PROJECT_ID);+ assert.strictEqual(retried?.stack?.id, PROJECT_ID);+ }).pipe(Effect.provide(fixture.layer));+ }),+ ),+ );+it.effect("recovers the HTTP port when syncing an older Forgejo link", () =>Effect.scoped(Effect.gen(function* () {@@ -580,11 +661,11 @@ describe("PullRequestSyncReactor", () => {),);- it.effect("refreshes closed links through the reactor's project after reopening elsewhere", () =>+ it.effect("refreshes closed links through each project after reopening elsewhere", () =>Effect.scoped(Effect.gen(function* () {yield* TestClock.setTime(Date.parse(NOW));- const stale = yield* Ref.make(true);+ const invalidated = yield* Ref.make<ReadonlyArray<ProjectId>>([]);const fixture = yield* makeHarness({snapshot: makeSnapshot([makeThread("first", { pullRequests: [makeLink(42, { state: "closed" })] }),@@ -594,17 +675,21 @@ describe("PullRequestSyncReactor", () => {}),]),invalidate: ({ reference }) =>- reference?.projectId === makeProject().id && reference.host === "github.com"- ? Ref.set(stale, false)+ reference !== undefined+ ? Ref.update(invalidated, (projects) => [...projects, reference.projectId]): Effect.void,summary: (input) =>- Ref.get(stale).pipe(- Effect.map((cached) => makeSummary(input, { state: cached ? "closed" : "open" })),+ Ref.get(invalidated).pipe(+ Effect.map((projects) =>+ makeSummary(input, {+ state: projects.includes(input.projectId) ? "open" : "closed",+ }),+ ),),});yield* Effect.gen(function* () {const reactor = yield* startAndSweep(fixture);- assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);+ assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);yield* reactor.requestSync({host: "github.com",repository: "owner/repository",@@ -612,6 +697,14 @@ describe("PullRequestSyncReactor", () => {});yield* Queue.take(fixture.snapshotReads);yield* reactor.drain;+ assert.sameMembers(+ [...(yield* Ref.get(invalidated))],+ [PROJECT_ID, ProjectId.make("second-project")],+ );+ assert.sameMembers(+ (yield* Ref.get(fixture.stackCalls)).map((call) => call.projectId),+ [PROJECT_ID, ProjectId.make("second-project")],+ );const commands = yield* Ref.get(fixture.syncCommands);yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));const snapshot = yield* Ref.get(fixture.snapshots);diff --git a/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts b/apps/server/src/orchestration-v2/PullRequestSyncReactor.tsindex 6bde4404fb7..398b788c03b 100644--- a/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts+++ b/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts@@ -152,9 +152,10 @@ export const make = Effect.gen(function* () {const crypto = yield* Crypto.Crypto;const lastSyncedAt = new Map<string, number>();- const requested = new Map<string, number>();- let requestGeneration = 0;- // Requested keys wait in `requested` for one queued sweep, so a burst of links (an agent+ const requested = new Set<string>();+ // Requests arriving during a host read wait for the next sweep.+ const pendingRequests = new Set<string>();+ // PR keys wait in `pendingRequests` for one queued sweep, so a burst of links (an agent// linking dozens of pull requests) is read together and shares the summary batches.let requestedSweepQueued = false;const retryStacks = new Set<string>();@@ -195,13 +196,20 @@ export const make = Effect.gen(function* () {const groups = new Map<string, Array<LinkEntry>>();for (const thread of threads) {for (const link of visibleThreadPullRequests(thread.pullRequests ?? [])) {- const key = threadPullRequestKeyOf(link);+ // Reads depend on the project's checkout and credentials, including their failures.+ const key = `${thread.projectId}\0${threadPullRequestKeyOf(link)}`;const entries = groups.get(key) ?? [];entries.push({ thread, link });groups.set(key, entries);}}+ // A host-level refresh reaches every project, each retaining its own pending retry.+ for (const [key, entries] of groups) {+ if (pendingRequests.has(threadPullRequestKeyOf(entries[0]!.link))) requested.add(key);+ }+ pendingRequests.clear();+for (const key of lastSyncedAt.keys()) if (!groups.has(key)) lastSyncedAt.delete(key);for (const key of retryStacks) if (!groups.has(key)) retryStacks.delete(key);for (const key of requested.keys()) if (!groups.has(key)) requested.delete(key);@@ -278,19 +286,19 @@ export const make = Effect.gen(function* () {repository: first.link.repository,number: first.link.number,};- const generation = requested.get(key);+ const refreshRequested = requested.has(key);// A held merged summary is served without asking the host, so a snapshot still missing its// merge time has to drop it or the slow-cadence re-read would hand back the same gap.const missingMergedAt = entries.some((entry) => entry.link.snapshot?.state === "merged" && entry.link.snapshot.mergedAt == null,);- if (generation !== undefined || missingMergedAt) {+ if (refreshRequested || missingMergedAt) {yield* pullRequests.invalidate({ reference: ref });}const summary = yield* pullRequests.summary(ref, { recoverTransientFailure: false });const fields = snapshotFieldsOf(summary);const needsStack =- generation !== undefined ||+ refreshRequested ||retryStacks.has(key) ||entries.some((entry) =>@@ -330,8 +338,7 @@ export const make = Effect.gen(function* () {}// The host answered, so the cadence clock ticks even if a dispatch below is rejected.lastSyncedAt.set(key, nowMs);- // A refresh requested while the host read was in flight belongs to the next sweep.- if (requested.get(key) === generation) requested.delete(key);+ requested.delete(key);yield* Effect.forEach(entries,(entry) =>@@ -473,7 +480,7 @@ export const make = Effect.gen(function* () {const requestSync: PullRequestSyncReactor["Service"]["requestSync"] = (key) =>Effect.suspend(() => {- requested.set(threadPullRequestKeyOf(key), ++requestGeneration);+ pendingRequests.add(threadPullRequestKeyOf(key));if (requestedSweepQueued) return Effect.void;requestedSweepQueued = true;return worker.enqueue("requested");