fix(server): background GitHub polling uses ~74% fewer calls with batched GraphQL (#14673)

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Theo BrowneandClaude Opus 5.5 authored and GitHub committed 2026-10-01 16:48:29 -07:00
1 parent a3abb52660
commit 10ac2f2ba4
15 files changed
+1039 -213

No files matched your search

@@ -754,6 +754,88 @@ describe("PullRequestSyncReactor", () => {
),
);
it.effect("reads a burst of requested links in one sweep", () =>
Effect.scoped(
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
const reading = yield* Deferred.make<void>();
const release = yield* Deferred.make<void>();
const fixture = yield* makeHarness({
snapshot: makeSnapshot([]),
summary: (input) =>
Effect.gen(function* () {
if (input.number === 1) {
yield* Deferred.succeed(reading, undefined);
yield* Deferred.await(release);
}
return makeSummary(input);
}),
});
yield* Effect.gen(function* () {
const reactor = yield* startAndSweep(fixture);
yield* Ref.set(
fixture.snapshots,
makeSnapshot(
[1, 2, 3, 4].map((number) =>
makeThread(`thread-${number}`, { pullRequests: [makeLink(number)] }),
),
),
);
const request = (number: number) =>
reactor.requestSync({ host: "github.com", repository: "owner/repository", number });
yield* request(1);
yield* Deferred.await(reading);
yield* Effect.forEach([2, 3, 4], request, { discard: true });
yield* Deferred.succeed(release, undefined);
yield* reactor.drain;
// One sweep for the first link and one for the three that arrived while it read.
assert.strictEqual(yield* Queue.size(fixture.snapshotReads), 2);
assert.deepStrictEqual(
(yield* Ref.get(fixture.summaryCalls)).map((ref) => ref.number).toSorted(),
[1, 2, 3, 4],
);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("skips the stack read for a pull request the summary places in no stack", () =>
Effect.scoped(
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
const fixture = yield* makeHarness({
snapshot: makeSnapshot([
makeThread("unstacked", { pullRequests: [makeLink(1)] }),
makeThread("stacked", { pullRequests: [makeLink(2)] }),
makeThread("unknown", { pullRequests: [makeLink(3)] }),
]),
summary: (input) =>
Effect.succeed(
makeSummary(
input,
input.number === 1
? { stack: null }
: input.number === 2
? { stack: { number: 9, position: 1, size: 2, base: "main" } }
: {},
),
),
});
yield* Effect.gen(function* () {
yield* startAndSweep(fixture);
assert.deepStrictEqual(
(yield* Ref.get(fixture.stackCalls)).map((ref) => ref.number).toSorted(),
[2, 3],
);
assert.deepStrictEqual(
(yield* Ref.get(fixture.syncCommands)).map((command) => command.number).toSorted(),
[1, 2, 3],
);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("polls open pull requests on settled threads every fifteen minutes", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -133,6 +133,9 @@ export const make = Effect.gen(function* () {
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
// linking dozens of pull requests) is read together and shares the summary batches.
let requestedSweepQueued = false;
const retryStacks = new Set<string>();
const isDue = (key: string, entries: ReadonlyArray<LinkEntry>, nowMs: number): boolean => {
@@ -151,7 +154,8 @@ export const make = Effect.gen(function* () {
<E>(cause: Cause.Cause<E>): Effect.Effect<void, E> =>
Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logWarning(message, fields);
const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* (requestedKey?: string) {
/** `requested` reads only keys asked for through `requestSync`; `all` is the periodic pass. */
const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* (scope: "all" | "requested") {
const threads = yield* snapshots.listThreadsWithPullRequests();
const now = yield* DateTime.now;
const nowMs = DateTime.toEpochMillis(now);
@@ -250,22 +254,31 @@ export const make = Effect.gen(function* () {
retryStacks.has(key) ||
entries.some(
(entry) =>
entry.link.snapshot === null || !snapshotFieldsEqual(entry.link.snapshot, fields),
entry.link.snapshot === null ||
!snapshotFieldsEqual(entry.link.snapshot, fields) ||
(summary.stack !== undefined &&
(entry.link.stack?.number ?? null) !== (summary.stack?.number ?? null)),
);
const fetchedStack = needsStack
? yield* pullRequests.stack(ref, { includeDetails: false }).pipe(
Effect.map((stack) => ({
stack: stack === null ? null : ({ kind: "native", ...stack } as const),
})),
Effect.catchCauseIf(
(cause) => !Cause.hasInterruptsOnly(cause),
() =>
Effect.logWarning("pull request stack lookup failed", {
key,
}).pipe(Effect.as(null)),
),
)
: null;
// A summary that says the pull request is in no stack, for links that hold none, already
// answers what the stack read would.
const knownUnstacked =
summary.stack === null && entries.every((entry) => entry.link.stack === null);
const fetchedStack = !needsStack
? null
: knownUnstacked
? { stack: null }
: yield* pullRequests.stack(ref, { includeDetails: false }).pipe(
Effect.map((stack) => ({
stack: stack === null ? null : ({ kind: "native", ...stack } as const),
})),
Effect.catchCauseIf(
(cause) => !Cause.hasInterruptsOnly(cause),
() =>
Effect.logWarning("pull request stack lookup failed", {
key,
}).pipe(Effect.as(null)),
),
);
if (needsStack) {
if (fetchedStack === null) {
retryStacks.add(key);
@@ -296,7 +309,7 @@ export const make = Effect.gen(function* () {
yield* Effect.forEach(
groups,
([key, entries]) =>
(requestedKey === undefined || requestedKey === key) && isDue(key, entries, nowMs)
(scope === "all" || requested.has(key)) && isDue(key, entries, nowMs)
? syncGroup(key, entries).pipe(
Effect.catchCause(logSkipped("pull request sync skipped", { key })),
)
@@ -307,8 +320,12 @@ export const make = Effect.gen(function* () {
);
});
const worker = yield* makeDrainableWorker((key: string | undefined) =>
sweep(key).pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
const worker = yield* makeDrainableWorker((scope: "all" | "requested") =>
Effect.suspend(() => {
// Requests from here on queue another sweep; the ones already recorded are read by this.
if (scope === "requested") requestedSweepQueued = false;
return sweep(scope);
}).pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
);
const start: PullRequestSyncReactor["Service"]["start"] = Effect.fn(
@@ -322,7 +339,7 @@ export const make = Effect.gen(function* () {
);
yield* forkParked(
Effect.gen(function* () {
yield* worker.enqueue(undefined);
yield* worker.enqueue("all");
yield* worker.drain;
}).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
);
@@ -330,9 +347,10 @@ export const make = Effect.gen(function* () {
const requestSync: PullRequestSyncReactor["Service"]["requestSync"] = (key) =>
Effect.suspend(() => {
const syncKey = threadPullRequestKeyOf(key);
requested.set(syncKey, ++requestGeneration);
return worker.enqueue(syncKey);
requested.set(threadPullRequestKeyOf(key), ++requestGeneration);
if (requestedSweepQueued) return Effect.void;
requestedSweepQueued = true;
return worker.enqueue("requested");
});
return { start, drain: worker.drain, requestSync } satisfies PullRequestSyncReactor["Service"];
@@ -348,7 +348,9 @@ export const make = Effect.gen(function* () {
}).pipe(Effect.tap(() => Effect.sync(() => failBackfill(group)))),
),
),
{ concurrency: 8, discard: true },
// Wide enough that a sweep's GitHub branch lookups reach GitHubCli together and share one
// GraphQL document, instead of one `gh pr list` per branch.
{ concurrency: 32, discard: true },
);
});