perf(server): PR watches spend ~90% fewer GitHub points by checking a 1-point fingerprint first (#16270)

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-05 17:46:52 -07:00
1 parent dcbaf05279
commit 758dc290e9
12 files changed
+715 -44

No files matched your search

@@ -532,6 +532,53 @@ layer("GitHubPullRequestCli.layer", (it) => {
}),
);
it.effect("fingerprints watched pull requests on one host in one read", () =>
Effect.gen(function* () {
const node = (comments: number) => ({
state: "OPEN",
mergeable: "MERGEABLE",
headRefOid: "abc123",
comments: { totalCount: comments, nodes: [] },
reviews: { totalCount: 0, nodes: [] },
reviewThreads: { totalCount: 0 },
commits: { nodes: [{ commit: { statusCheckRollup: null } }] },
});
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({
data: { w0: { pullRequest: node(1) }, w1: { pullRequest: null } },
}),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const reads = yield* Effect.forEach(
[7, 8],
(number) =>
cli.getPullRequestWatchFingerprint({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number,
}),
{ concurrency: "unbounded" },
).pipe(Effect.forkChild);
yield* TestClock.adjust("10 millis");
const [seven, eight] = yield* Fiber.join(reads);
expect(seven?.remarks.startsWith("1 ")).toBe(true);
// GitHub had no answer for #8, so its watch reads it in full.
expect(eight).toBeNull();
expect(mockedExecute).toHaveBeenCalledOnce();
expect(callAt(0).args.at(-1) ?? "").toContain(
'w1: repository(owner: "acme", name: "web") { pullRequest(number: 8)',
);
}),
);
it.effect("reads a pull request the batch said nothing about on its own", () =>
Effect.gen(function* () {
mockedExecute
@@ -56,6 +56,7 @@ import {
pullRequestCoreGraphQlQuery,
type GitHubPullRequestCore,
type GitHubPullRequestSummary,
type GitHubPullRequestWatchFingerprint,
decodePullRequestPreviewJson,
PULL_REQUEST_PREVIEW_GRAPHQL_QUERY,
decodePullRequestFilesJson,
@@ -67,6 +68,7 @@ import {
decodePullRequestStacksJson,
decodePullRequestStatsJson,
decodePullRequestSummariesJson,
decodePullRequestWatchFingerprintsJson,
decodeReactionSubjectScopeJson,
decodeReviewerCandidatesJson,
decodeLabelCandidatesJson,
@@ -77,6 +79,7 @@ import {
decodeReviewThreadsJson,
buildPullRequestStatsGraphQlQuery,
buildPullRequestSummariesGraphQlQuery,
buildPullRequestWatchFingerprintsGraphQlQuery,
buildPullRequestStackMembershipsGraphQlQuery,
decodePullRequestStackMembershipsJson,
encodeGraphQlRequestJson,
@@ -447,6 +450,17 @@ class PullRequestSummaryRead extends Request.Class<
GitHubPullRequestCliError
> {}
class PullRequestWatchFingerprintRead extends Request.Class<
{
readonly cwd: string;
readonly repository: string;
readonly host: string;
readonly number: number;
},
GitHubPullRequestWatchFingerprint | null,
GitHubPullRequestCliError
> {}
export interface GitHubPullRequestSearchBatch {
/** Rows across every repository asked for, newest update first, each naming its own. */
readonly items: ReadonlyArray<GitHubPullRequestSearchItem>;
@@ -543,6 +557,16 @@ export class GitHubPullRequestCli extends Context.Service<
readonly host: string;
readonly number: number;
}) => Effect.Effect<ProviderChangeRequestSummary, GitHubPullRequestCliError>;
/**
* What a watch compares between passes, batched like summaries. Null when GitHub gave no
* answer for this pull request, so the watch reads it in full instead.
*/
readonly getPullRequestWatchFingerprint: (input: {
readonly cwd: string;
readonly repository: string;
readonly host: string;
readonly number: number;
}) => Effect.Effect<GitHubPullRequestWatchFingerprint | null, GitHubPullRequestCliError>;
readonly revalidateChecks: Effect.Success<typeof makeChecksRevalidator>;
@@ -1918,6 +1942,60 @@ export const make = Effect.gen(function* () {
const getPullRequestSummary: GitHubPullRequestCli["Service"]["getPullRequestSummary"] = (input) =>
Effect.request(new PullRequestSummaryRead(input), summaryResolver);
// Every watched pull request on a host in one read per pass. A pull request the batch has no
// answer for gets null, and its watch reads it in full; a failed batch fails every entry.
const watchFingerprintResolver = RequestResolver.makeGrouped<
PullRequestWatchFingerprintRead,
string
>({
key: ({ request, context }) =>
JSON.stringify([
request.host.toLowerCase(),
Context.getOrElse(context, GitHubCli.PinnedGitHubCredential, () => null)
?.credentialFingerprint ?? null,
Context.getOrElse(context, SourceControlRateLimit.CredentialScope, () => ""),
]),
resolver: (entries) => {
const [first] = entries;
const batchable = entries.filter(
(entry) => buildPullRequestWatchFingerprintsGraphQlQuery([entry.request]) !== null,
);
const query = buildPullRequestWatchFingerprintsGraphQlQuery(
batchable.map((entry) => entry.request),
);
const read =
query === null
? Effect.succeed(new Map<number, GitHubPullRequestWatchFingerprint>())
: graphqlRead({
cwd: first.request.cwd,
host: first.request.host,
operation: "getPullRequestWatchFingerprint",
query,
decode: decodePullRequestWatchFingerprintsJson,
});
return read.pipe(
Effect.map((fingerprints) => {
for (const entry of entries) {
const index = batchable.indexOf(entry);
entry.completeUnsafe(
Exit.succeed(index === -1 ? null : (fingerprints.get(index) ?? null)),
);
}
}),
Effect.catchCause((cause) =>
Effect.sync(() => {
for (const entry of entries) entry.completeUnsafe(Exit.failCause(cause));
}),
),
);
},
}).pipe(
RequestResolver.setDelay(SUMMARY_BATCH_WINDOW),
RequestResolver.batchN(STAT_ALIASES_PER_REQUEST),
);
const getPullRequestWatchFingerprint: GitHubPullRequestCli["Service"]["getPullRequestWatchFingerprint"] =
(input) => Effect.request(new PullRequestWatchFingerprintRead(input), watchFingerprintResolver);
return GitHubPullRequestCli.of({
withVerifiedCredential,
revalidateChecks,
@@ -2125,6 +2203,7 @@ export const make = Effect.gen(function* () {
},
getPullRequestSummary,
getPullRequestWatchFingerprint,
getPullRequestDetail,
getPullRequestPreview: (input) => {
@@ -360,6 +360,11 @@ export const make = Effect.gen(function* () {
getChangeRequestStack: (input) =>
cli.getPullRequestStack(input).pipe(Effect.mapError(fail("getChangeRequestStack"))),
getChangeRequestWatchFingerprint: (input) =>
cli
.getPullRequestWatchFingerprint(input)
.pipe(Effect.mapError(fail("getChangeRequestWatchFingerprint"))),
getChangeRequestPreview: (input) =>
cli.getPullRequestPreview(input).pipe(Effect.mapError(fail("getChangeRequestPreview"))),
@@ -69,6 +69,15 @@ export class PullRequestProviderError extends Schema.TaggedError<PullRequestProv
}
}
/**
* `status` moves with the state, mergeability, head, or checks, which the detail read reports;
* `remarks` moves with comments and reviews, which only the activity read reports.
*/
export interface ProviderChangeRequestWatchFingerprint {
readonly status: string;
readonly remarks: string;
}
export interface PullRequestProviderFailure {
readonly reason: PullRequestProviderError["reason"];
readonly retryAt?: number | undefined;
@@ -436,6 +445,15 @@ export interface PullRequestProviderApi {
input: ProviderRepositoryRef & { readonly number: number },
) => Effect.Effect<ProviderChangeRequestSummary, PullRequestProviderError>;
/**
* A cheap fingerprint of what a pull request watch reports, so it reads the change request in
* full only when this moves. Null when the host gave no answer for it. Optional: a host
* without one has its watched change requests read in full on every pass.
*/
readonly getChangeRequestWatchFingerprint?: (
input: ProviderRepositoryRef & { readonly number: number },
) => Effect.Effect<ProviderChangeRequestWatchFingerprint | null, PullRequestProviderError>;
/**
* The host-native stack a change request belongs to, or null when it is not stacked. Optional
* because most hosts have no such object; the service derives chains from base branches there.
@@ -85,6 +85,7 @@ import * as SourceControlRateLimit from "../sourceControl/SourceControlRateLimit
import {
type ProviderChangeRequest,
type ProviderListCursor,
type ProviderChangeRequestWatchFingerprint,
type PullRequestProviderApi,
PullRequestProviderError,
} from "./PullRequestProvider.ts";
@@ -218,6 +219,13 @@ export class PullRequestService extends Context.Service<
readonly checks: (
input: PullRequestRef,
) => Effect.Effect<PullRequestChecks | null, PullRequestError>;
/**
* What a pull request watch compares between passes, so it reads detail and activity only
* when something moved. Null when the host has no fingerprint or gave none for this one.
*/
readonly watchFingerprint: (
input: PullRequestRef,
) => Effect.Effect<ProviderChangeRequestWatchFingerprint | null, PullRequestError>;
readonly activity: (
input: PullRequestRef,
) => Effect.Effect<PullRequestActivity, PullRequestError>;
@@ -581,6 +589,14 @@ function withRateLimitBackoff(
...(api.getChangeRequestStack === undefined
? {}
: { getChangeRequestStack: wrap("getChangeRequestStack", api.getChangeRequestStack) }),
...(api.getChangeRequestWatchFingerprint === undefined
? {}
: {
getChangeRequestWatchFingerprint: wrap(
"getChangeRequestWatchFingerprint",
api.getChangeRequestWatchFingerprint,
),
}),
getChangeRequestActivity: wrap("getChangeRequestActivity", api.getChangeRequestActivity),
...(api.getReviewThreadComments === undefined
? {}
@@ -2949,6 +2965,30 @@ export const make = Effect.gen(function* () {
},
);
const watchFingerprintCache = yield* Cache.makeWith(
(key: string) => {
const input = refOfCacheKey(key);
return requireProject(input).pipe(
Effect.flatMap((project) =>
project.api.getChangeRequestWatchFingerprint === undefined
? Effect.succeed(null)
: project.api
.getChangeRequestWatchFingerprint({
cwd: project.project.workspaceRoot,
repository: project.repository,
host: project.host,
number: input.number,
})
.pipe(Effect.mapError(toPullRequestError("watchFingerprint"))),
),
);
},
{
capacity: DETAIL_CACHE_CAPACITY,
timeToLive: (exit) => (Exit.isSuccess(exit) ? DETAIL_CACHE_TTL : Duration.zero),
},
);
const detailCache = yield* Cache.makeWith(
(key: string) => {
const statsKey = statsCacheKey(key);
@@ -3321,6 +3361,9 @@ export const make = Effect.gen(function* () {
refreshAfterTurn,
detail: credentialCached(detail),
checks: credentialCached((input) => Cache.get(checksCache, refCacheKey(input))),
watchFingerprint: credentialCached((input) =>
Cache.get(watchFingerprintCache, refCacheKey(input)),
),
activity: credentialCached(activity),
preview: credentialCached(preview),
threadComments,
@@ -3,7 +3,9 @@ import { describe, expect, it } from "vite-plus/test";
import {
buildPullRequestSummariesGraphQlQuery,
buildPullRequestWatchFingerprintsGraphQlQuery,
decodePullRequestSummariesJson,
decodePullRequestWatchFingerprintsJson,
buildReviewSubmissionJson,
buildPullRequestStackMembershipsGraphQlQuery,
decodePullRequestStackMembershipsJson,
@@ -2026,3 +2028,81 @@ describe("batched pull request summaries", () => {
expect(decoded.get(1)?.stack).toEqual({ number: 3, size: 2, base: "main", position: 2 });
});
});
describe("pull request watch fingerprints", () => {
it("asks for every pull request in one aliased read, and refuses an unsafe selector", () => {
const query = buildPullRequestWatchFingerprintsGraphQlQuery([
{ repository: "pingdotgg/t3code", number: 7 },
{ repository: "pingdotgg/lakebed", number: 8 },
]);
expect(query).toContain(
'w0: repository(owner: "pingdotgg", name: "t3code") { pullRequest(number: 7)',
);
expect(query).toContain(
'w1: repository(owner: "pingdotgg", name: "lakebed") { pullRequest(number: 8)',
);
expect(
buildPullRequestWatchFingerprintsGraphQlQuery([{ repository: 'evil") { x', number: 1 }]),
).toBeNull();
});
it("moves status with checks and remarks with comments, each without the other", () => {
const pullRequest = (input: {
readonly running: number;
readonly failed: number;
readonly commentEditedAt: string | null;
readonly reviews: number;
}) => ({
state: "OPEN",
mergeable: "MERGEABLE",
headRefOid: "abc123",
comments: { totalCount: 1, nodes: [{ lastEditedAt: input.commentEditedAt }] },
reviews: { totalCount: input.reviews, nodes: [] },
reviewThreads: { totalCount: 0 },
commits: {
nodes: [
{
commit: {
statusCheckRollup: {
contexts: {
checkRunCountsByState: [
{ state: "IN_PROGRESS", count: input.running },
{ state: "FAILURE", count: input.failed },
{ state: "SUCCESS", count: 0 },
],
statusContextCountsByState: null,
},
},
},
},
],
},
});
const decode = (...pullRequests: ReadonlyArray<object | null>) => {
const decoded = decodePullRequestWatchFingerprintsJson(
JSON.stringify({
data: Object.fromEntries(
pullRequests.map((value, index) => [`w${index}`, { pullRequest: value }]),
),
}),
);
if (!Result.isSuccess(decoded)) throw new Error("fingerprints did not decode");
return decoded.success;
};
const base = { running: 2, failed: 0, commentEditedAt: null, reviews: 1 };
const fingerprint = (input: Parameters<typeof pullRequest>[0]) =>
decode(pullRequest(input)).get(0)!;
const before = fingerprint(base);
const checkFinished = fingerprint({ ...base, running: 1, failed: 1 });
const summaryEdited = fingerprint({ ...base, commentEditedAt: "2026-10-05T23:47:43Z" });
const replied = fingerprint({ ...base, reviews: 2 });
expect(checkFinished.status).not.toBe(before.status);
expect(checkFinished.remarks).toBe(before.remarks);
expect(summaryEdited.remarks).not.toBe(before.remarks);
expect(summaryEdited.status).toBe(before.status);
expect(replied.remarks).not.toBe(before.remarks);
// A pull request GitHub had no answer for is left for a full read.
expect(decode(null, pullRequest(base)).has(0)).toBe(false);
});
});
@@ -1993,6 +1993,139 @@ export function decodePullRequestSummariesJson(
return Result.succeed(summaries);
}
const WATCH_FINGERPRINT_EDITS = "totalCount nodes { lastEditedAt }";
const WATCH_FINGERPRINT_CHECK_COUNTS =
"checkRunCountsByState { state count } statusContextCountsByState { state count }";
/**
* What a pull request watch needs to notice, priced by GitHub at one point for twenty-five pull
* requests, where the detail and activity reads it gates cost sixteen for one. Counts and the
* newest edit cover new comments, reviews (a reply in a review thread is a review), threads, and
* a bot rewriting its summary; check counts by state move whenever a check starts or finishes.
* Comments come most recently updated first, since an edit moves `updatedAt`, so an edit to an
* old comment on a long pull request is still in the page. Reviews have no such order: an edit
* to a review older than the last hundred waits for the watch's periodic full read, as do edits
* to comments inside review threads, which cost a point per pull request to ask for.
*/
const PULL_REQUEST_WATCH_FINGERPRINT_SELECTION =
"state mergeable headRefOid " +
`comments(first: 100, orderBy: { field: UPDATED_AT, direction: DESC }) { ${WATCH_FINGERPRINT_EDITS} } ` +
`reviews(last: 100) { ${WATCH_FINGERPRINT_EDITS} } ` +
"reviewThreads { totalCount } " +
`commits(last: 1) { nodes { commit { statusCheckRollup { contexts { ${WATCH_FINGERPRINT_CHECK_COUNTS} } } } } }`;
/** Watch fingerprints for pull requests on one host, one aliased lookup each; null when unsafe. */
export function buildPullRequestWatchFingerprintsGraphQlQuery(
changeRequests: ReadonlyArray<{ readonly repository: string; readonly number: number }>,
): string | null {
if (changeRequests.length === 0) return null;
const selections: string[] = [];
for (const [index, changeRequest] of changeRequests.entries()) {
const [owner, name, ...rest] = changeRequest.repository.trim().split("/");
if (rest.length > 0 || owner === undefined || name === undefined) return null;
if (!REPOSITORY_PART.test(owner) || !REPOSITORY_PART.test(name)) return null;
if (!Number.isSafeInteger(changeRequest.number) || changeRequest.number <= 0) return null;
selections.push(
` w${index}: repository(owner: "${owner}", name: "${name}") { pullRequest(number: ${changeRequest.number}) { ${PULL_REQUEST_WATCH_FINGERPRINT_SELECTION} } }`,
);
}
return `query PullRequestWatchFingerprints {\n${selections.join("\n")}\n}`;
}
/**
* Two parts, so a watch reads only what moved: `status` (state, mergeability, head, and checks)
* needs the detail read, and `remarks` also needs the far costlier activity read.
*/
export interface GitHubPullRequestWatchFingerprint {
readonly status: string;
readonly remarks: string;
}
const RawEditedSchema = Schema.Struct({
totalCount: Schema.Int,
nodes: Schema.Array(Schema.NullOr(Schema.Struct({ lastEditedAt: Schema.NullOr(Schema.String) }))),
});
const RawStateCountsSchema = Schema.NullOr(
Schema.Array(Schema.Struct({ state: Schema.String, count: Schema.Int })),
);
const decodeWatchFingerprintEntry = Schema.decodeUnknownExit(
Schema.Struct({
state: Schema.String,
mergeable: Schema.NullOr(Schema.String),
headRefOid: Schema.String,
comments: RawEditedSchema,
reviews: RawEditedSchema,
reviewThreads: Schema.Struct({ totalCount: Schema.Int }),
commits: Schema.Struct({
nodes: Schema.Array(
Schema.NullOr(
Schema.Struct({
commit: Schema.Struct({
statusCheckRollup: Schema.NullOr(
Schema.Struct({
contexts: Schema.Struct({
checkRunCountsByState: RawStateCountsSchema,
statusContextCountsByState: RawStateCountsSchema,
}),
}),
),
}),
}),
),
),
}),
}),
);
// An edit only ever moves `lastEditedAt` forward, so the newest one stands for them all.
const newestEdit = (connection: typeof RawEditedSchema.Type) =>
connection.nodes.reduce(
(newest, node) =>
node?.lastEditedAt != null && node.lastEditedAt > newest ? node.lastEditedAt : newest,
"",
);
const stateCounts = (counts: typeof RawStateCountsSchema.Type) =>
(counts ?? [])
.filter(({ count }) => count > 0)
.map(({ state, count }) => `${state}:${count}`)
.toSorted()
.join(",");
/** Fingerprints by alias index; a pull request GitHub returned nothing for is left out. */
export function decodePullRequestWatchFingerprintsJson(
raw: string,
): Result.Result<ReadonlyMap<number, GitHubPullRequestWatchFingerprint>, DecodeFailure> {
const decoded = decodeSummaries(raw);
if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
const fingerprints = new Map<number, GitHubPullRequestWatchFingerprint>();
for (const [alias, value] of Object.entries(decoded.success.data ?? {})) {
const index = /^w(\d+)$/.exec(alias)?.[1];
if (index === undefined || value?.pullRequest == null) continue;
const entry = decodeWatchFingerprintEntry(value.pullRequest);
if (!Exit.isSuccess(entry)) continue;
const pr = entry.value;
const contexts = pr.commits.nodes[0]?.commit.statusCheckRollup?.contexts;
fingerprints.set(Number(index), {
status: [
pr.state,
pr.mergeable ?? "",
pr.headRefOid,
stateCounts(contexts?.checkRunCountsByState ?? null),
stateCounts(contexts?.statusContextCountsByState ?? null),
].join(" "),
remarks: [
pr.comments.totalCount,
newestEdit(pr.comments),
pr.reviews.totalCount,
newestEdit(pr.reviews),
pr.reviewThreads.totalCount,
].join(" "),
});
}
return Result.succeed(fingerprints);
}
export interface GitHubPullRequestCore extends GitHubPullRequestDetail {
readonly viewerAccess: GitHubViewerAccess & GitHubRepositoryAccess;
readonly comparison: GitHubBaseComparison | null;