GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(prs): reuse GitHub data and defer optional reads (#9835) · incognitojam/styal@ef8bd91

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps
    • server/src
      • pullRequest
        • PullRequestService.test.ts
        • PullRequestService.ts
      • sourceControl
        • githubGraphQlBudget.test.ts
        • githubGraphQlBudget.ts
    • web/src
      • components/pullRequest
        • PullRequestDetailPanel.tsx
        • PullRequestRow.tsx
        • pullRequestList.logic.test.ts
        • pullRequestList.logic.ts
      • routes
        • _chat.pull-requests.tsx
      • state
        • pullRequests.ts
  • packages/client-runtime/src/state
    • pullRequests.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/server/src/pullRequest/PullRequestService.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/pullRequest/PullRequestService.test.ts
+123Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3250,6 +3250,114 @@ it.effect("fills in the line counts for the rows it is given", () =>
32503250
]);
32513251
}),
32523252
);
3253+
it.effect(
3254+
"reuses counts across overlapping pages until expiry, explicit invalidation, or a reference changes",
3255+
() =>
3256+
Effect.gen(function* () {
3257+
const asked: number[][] = [];
3258+
const ref = (number: number) => ({
3259+
projectId: "p1" as ProjectId,
3260+
repository: "acme/web",
3261+
number,
3262+
});
3263+
const service = yield* makeService({
3264+
projects: [
3265+
project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
3266+
],
3267+
providers: [
3268+
fakeProvider("github", {
3269+
listChangeRequestStats: (input) => {
3270+
asked.push(input.changeRequests.map((ref) => ref.number));
3271+
return Effect.succeed(
3272+
input.changeRequests.map((ref) => ({ ...ref, additions: 12, deletions: 3 })),
3273+
);
3274+
},
3275+
}),
3276+
],
3277+
});
3278+
3279+
yield* service.listStats({ refs: [ref(1), ref(2)] });
3280+
const overlapping = yield* service.listStats({ refs: [ref(2), ref(3)] });
3281+
assert.deepStrictEqual(
3282+
overlapping.stats.map((stat) => stat.number),
3283+
[2, 3],
3284+
);
3285+
yield* service.listStats({ refs: [ref(1), ref(2), ref(3)] });
3286+
assert.deepStrictEqual(asked, [[1, 2], [3]]);
3287+
3288+
yield* service.invalidate({ reference: ref(2) });
3289+
yield* service.listStats({ refs: [ref(1), ref(2), ref(3)] });
3290+
assert.deepStrictEqual(asked, [[1, 2], [3], [2]]);
3291+
3292+
yield* TestClock.adjust("61 seconds");
3293+
yield* service.listStats({ refs: [ref(1), ref(2), ref(3)] });
3294+
assert.deepStrictEqual(asked, [[1, 2], [3], [2], [1, 2, 3]]);
3295+
3296+
yield* service.refreshAfterTurn;
3297+
yield* service.listStats({ refs: [ref(1)] });
3298+
assert.deepStrictEqual(asked, [[1, 2], [3], [2], [1, 2, 3], [1]]);
3299+
3300+
yield* service.invalidate({});
3301+
yield* service.listStats({ refs: [ref(1)] });
3302+
assert.deepStrictEqual(asked, [[1, 2], [3], [2], [1, 2, 3], [1], [1]]);
3303+
}),
3304+
);
3305+
3306+
it.effect("reads the fresh diff when detail or summary discovers a changed revision", () =>
3307+
Effect.gen(function* () {
3308+
const summaryStarted = yield* Deferred.make<void>();
3309+
const releaseSummary = yield* Deferred.make<void>();
3310+
let revision = "2026-07-02T00:00:00Z";
3311+
let patch = "old patch";
3312+
let diffCalls = 0;
3313+
const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
3314+
const service = yield* makeService({
3315+
projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
3316+
providers: [
3317+
fakeProvider("github", {
3318+
getChangeRequest: () =>
3319+
Effect.sync(() => ({ ...hostedChangeRequest("body"), updatedAt: revision })),
3320+
getChangeRequestSummary: () =>
3321+
Effect.gen(function* () {
3322+
const result = changeRequest(1, revision);
3323+
yield* Deferred.succeed(summaryStarted, undefined);
3324+
yield* Deferred.await(releaseSummary);
3325+
return result;
3326+
}),
3327+
getDiff: () =>
3328+
Effect.sync(() => {
3329+
diffCalls += 1;
3330+
return { patch, truncated: false, nextCursor: null };
3331+
}),
3332+
}),
3333+
],
3334+
});
3335+
3336+
const coldSummary = yield* service.summary(reference).pipe(Effect.forkChild());
3337+
yield* Deferred.await(summaryStarted);
3338+
yield* service.detail(reference);
3339+
assert.strictEqual((yield* service.diff(reference)).patch, "old patch");
3340+
revision = "2026-07-02T00:01:00Z";
3341+
patch = "new patch";
3342+
yield* TestClock.adjust("16 seconds");
3343+
yield* service.detail(reference);
3344+
yield* Effect.yieldNow;
3345+
assert.strictEqual((yield* service.detail(reference)).updatedAt, revision);
3346+
yield* Deferred.succeed(releaseSummary, undefined);
3347+
yield* Fiber.join(coldSummary);
3348+
yield* service.summary(reference, { recoverTransientFailure: false });
3349+
assert.strictEqual((yield* service.diff(reference)).patch, "new patch");
3350+
assert.strictEqual(diffCalls, 2);
3351+
3352+
revision = "2026-07-02T00:02:00Z";
3353+
patch = "summary-discovered patch";
3354+
yield* TestClock.adjust("61 seconds");
3355+
yield* service.summary(reference, { recoverTransientFailure: false });
3356+
assert.strictEqual((yield* service.diff(reference)).patch, patch);
3357+
assert.strictEqual(diffCalls, 3);
3358+
}),
3359+
);
3360+
32533361
it.effect("keeps the rows when the line counts cannot be read", () =>
32543362
Effect.gen(function* () {
32553363
const service = yield* makeService({
@@ -3273,13 +3381,18 @@ it.effect(
32733381
Effect.gen(function* () {
32743382
let coreCalls = 0;
32753383
let activityCalls = 0;
3384+
let statsCalls = 0;
32763385
const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
32773386
const service = yield* makeService({
32783387
projects: [
32793388
project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
32803389
],
32813390
providers: [
32823391
fakeProvider("github", {
3392+
listChangeRequestStats: () => {
3393+
statsCalls += 1;
3394+
return Effect.succeed([]);
3395+
},
32833396
getChangeRequest: () => {
32843397
coreCalls += 1;
32853398
return Effect.succeed(changeRequestDetail(1));
@@ -3303,6 +3416,16 @@ it.effect(
33033416
assert.strictEqual(coreCalls, 1);
33043417
assert.strictEqual(activityCalls, 0);
33053418

3419+
const counts = yield* service.listStats({ refs: [reference] });
3420+
assert.strictEqual(statsCalls, 0);
3421+
assert.deepStrictEqual(counts.stats, [
3422+
{
3423+
...reference,
3424+
additions: core.additions,
3425+
deletions: core.deletions,
3426+
},
3427+
]);
3428+
33063429
yield* Effect.all([service.activity(reference), service.activity(reference)], {
33073430
concurrency: 2,
33083431
});
Collapse file

‎apps/server/src/pullRequest/PullRequestService.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/pullRequest/PullRequestService.ts
+84-19Lines changed: 84 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2197,6 +2197,21 @@ export const make = Effect.gen(function* () {
21972197
Math.max(turnRefreshEpoch, refEpochs.get(refScope(ref))?.[scope] ?? 0);
21982198
const refCacheKey = (ref: PullRequestRef) =>
21992199
JSON.stringify([refEpoch("detail", ref), ref.projectId, ref.repository, ref.number]);
2200+
// Counts belong to a PR, not a filtered page. Background reads and filter changes reuse
2201+
// them; explicit refreshes, mutations, and turns strand old and in-flight results.
2202+
const statsCacheKey = (key: string) => JSON.stringify([listingsEpoch, key]);
2203+
const recentStats = new Map<
2204+
string,
2205+
{ readonly at: number; readonly value: PullRequestDiffStat }
2206+
>();
2207+
const recordStats = (key: string, value: PullRequestDiffStat, at: number) => {
2208+
recentStats.delete(key);
2209+
recentStats.set(key, { at, value });
2210+
if (recentStats.size > REF_EPOCH_CAPACITY) {
2211+
const oldest = recentStats.keys().next().value;
2212+
if (oldest !== undefined) recentStats.delete(oldest);
2213+
}
2214+
};
22002215
const bumpRefEpoch = (ref: PullRequestRef, scope: PullRequestInvalidationScope = "all") => {
22012216
const key = refScope(ref);
22022217
if (!refEpochs.has(key) && refEpochs.size >= REF_EPOCH_CAPACITY) {
@@ -2241,13 +2256,15 @@ export const make = Effect.gen(function* () {
22412256
const summary: PullRequestService["Service"]["summary"] = (input, options) => {
22422257
const key = refCacheKey(input);
22432258
const cached = Cache.get(summaryCache, key);
2244-
if (options?.recoverTransientFailure !== false) {
2245-
return lastGoodSummary.serveHeld(key, cached, "reuse");
2246-
}
22472259
const held = lastGoodSummary.peek(key);
2248-
return held?.state === "merged"
2260+
return held !== undefined &&
2261+
(options?.recoverTransientFailure !== false || held.state === "merged")
22492262
? Effect.succeed(held)
2250-
: cached.pipe(Effect.tap((value) => lastGoodSummary.record(key, value)));
2263+
: cached.pipe(
2264+
Effect.tap((value) =>
2265+
shouldReplaceHeldSummary(key, value) ? lastGoodSummary.record(key, value) : Effect.void,
2266+
),
2267+
);
22512268
};
22522269

22532270
// Keys serialize positionally and parse back in the lookup, so the cache is the only holder
@@ -2329,8 +2346,25 @@ export const make = Effect.gen(function* () {
23292346

23302347
const detailCache = yield* Cache.makeWith(
23312348
(key: string) => {
2349+
const statsKey = statsCacheKey(key);
23322350
const [, projectId, repository, number] = JSON.parse(key) as [number, string, string, number];
2333-
return detailUncached({ projectId, repository, number } as PullRequestRef);
2351+
return detailUncached({ projectId, repository, number } as PullRequestRef).pipe(
2352+
Effect.tap(
2353+
Effect.fn("PullRequestService.recordDetailStats")(function* (value: PullRequestDetail) {
2354+
recordStats(
2355+
statsKey,
2356+
{
2357+
projectId: value.projectId,
2358+
repository: value.repository,
2359+
number: value.number,
2360+
additions: value.additions,
2361+
deletions: value.deletions,
2362+
},
2363+
yield* Clock.currentTimeMillis,
2364+
);
2365+
}),
2366+
),
2367+
);
23342368
},
23352369
{
23362370
capacity: DETAIL_CACHE_CAPACITY,
@@ -2426,38 +2460,69 @@ export const make = Effect.gen(function* () {
24262460
input.number,
24272461
input.cursor ?? null,
24282462
input.commit ?? null,
2463+
input.commit === undefined
2464+
? (lastGoodSummary.peek(refCacheKey(input))?.updatedAt ?? null)
2465+
: null,
24292466
]);
24302467
return staleDiff(key, Cache.get(diffCache, key));
24312468
};
24322469

24332470
const listStatsCache = yield* Cache.makeWith(
24342471
(key: string) => {
2435-
const [, refs] = JSON.parse(key) as [number, ReadonlyArray<[string, string, number]>];
2472+
const [, refs] = JSON.parse(key) as [number, ReadonlyArray<[string, string, number, number]>];
24362473
return listStatsUncached({
24372474
refs: refs.map(([projectId, repository, number]) => ({ projectId, repository, number })),
2438-
} as unknown as PullRequestListStatsInput);
2475+
} as unknown as PullRequestListStatsInput).pipe(
2476+
Effect.flatMap((result) =>
2477+
Clock.currentTimeMillis.pipe(Effect.map((at) => ({ result, at }))),
2478+
),
2479+
);
24392480
},
24402481
{
24412482
capacity: LIST_STATS_CACHE_CAPACITY,
24422483
timeToLive: (exit) => (Exit.isSuccess(exit) ? LIST_STATS_CACHE_TTL : Duration.zero),
24432484
},
24442485
);
2445-
// The stats read leans on the host's search API — the scarcest limit of them all — so it
2446-
// shares between clients like every other read. Refs are sorted so one page's worth of rows
2447-
// is one key however the client assembled them, and the listings epoch rides along so the
2448-
// refresh that forgets the listing forgets its decorations with it.
2449-
const listStats: PullRequestService["Service"]["listStats"] = (input) => {
2450-
if (input.refs.length === 0) return Effect.succeed({ stats: [] });
2451-
const key = JSON.stringify([
2486+
const statsBatchKey = (refs: Iterable<PullRequestRef>) =>
2487+
JSON.stringify([
24522488
listingsEpoch,
2453-
input.refs
2454-
.map((ref) => [ref.projectId, ref.repository, ref.number] as const)
2489+
[...refs]
2490+
.map((ref) => [ref.projectId, ref.repository, ref.number, refEpoch("detail", ref)] as const)
24552491
.toSorted((left, right) =>
24562492
`${left[0]} ${left[1]} ${left[2]}`.localeCompare(`${right[0]} ${right[1]} ${right[2]}`),
24572493
),
24582494
]);
2459-
return Cache.get(listStatsCache, key);
2460-
};
2495+
// Exact batches share in-flight reads; overlapping pages reuse each row already fetched.
2496+
const listStats: PullRequestService["Service"]["listStats"] = Effect.fn(
2497+
"PullRequestService.listStats",
2498+
)(function* (input: PullRequestListStatsInput) {
2499+
if (input.refs.length === 0) return { stats: [] };
2500+
const now = yield* Clock.currentTimeMillis;
2501+
const held: PullRequestDiffStat[] = [];
2502+
const missing = new Map<string, PullRequestRef>();
2503+
for (const ref of input.refs) {
2504+
const key = statsCacheKey(refCacheKey(ref));
2505+
const cached = recentStats.get(key);
2506+
if (cached !== undefined && now - cached.at < Duration.toMillis(LIST_STATS_CACHE_TTL)) {
2507+
held.push(cached.value);
2508+
} else {
2509+
missing.set(key, ref);
2510+
}
2511+
}
2512+
if (missing.size === 0) return { stats: held };
2513+
const key = statsBatchKey(missing.values());
2514+
const { result, at } = yield* Cache.get(listStatsCache, key);
2515+
for (const [key, ref] of missing) {
2516+
const stat = result.stats.find(
2517+
(stat) =>
2518+
stat.projectId === ref.projectId &&
2519+
stat.repository.toLowerCase() === ref.repository.toLowerCase() &&
2520+
stat.number === ref.number,
2521+
);
2522+
if (stat !== undefined) recordStats(key, stat, at);
2523+
}
2524+
return { stats: [...held, ...result.stats] };
2525+
});
24612526

24622527
const invalidate: PullRequestService["Service"]["invalidate"] = (input) => {
24632528
const reference = input.reference;
Collapse file

‎apps/server/src/sourceControl/githubGraphQlBudget.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/sourceControl/githubGraphQlBudget.test.ts
+23-2Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,11 @@ const NEXT_RESET_AT = "2026-08-13T15:00:00.000Z";
99
const BEFORE_RESET = Date.parse("2026-08-13T13:30:00.000Z");
1010
const AFTER_RESET = Date.parse("2026-08-13T14:00:01.000Z");
1111

12-
function rateLimit(remaining: number, limit = 5_000, resetAt = RESET_AT): string {
12+
function rateLimit(remaining: number, limit = 5_000, resetAt = RESET_AT, cost = 14): string {
1313
return JSON.stringify({
1414
data: {
1515
viewer: { login: "bilal" },
16-
rateLimit: { cost: 14, limit, remaining, resetAt },
16+
rateLimit: { cost, limit, remaining, resetAt },
1717
},
1818
});
1919
}
@@ -86,6 +86,27 @@ describe("GitHub GraphQL budget", () => {
8686
}).pipe(Effect.provide(GitHubGraphQlBudget.layer)),
8787
);
8888

89+
it.effect("learns a cheaper observed cost without restoring reserved quota", () =>
90+
Effect.gen(function* () {
91+
yield* TestClock.setTime(BEFORE_RESET);
92+
const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;
93+
const query = "query { viewer { login } }";
94+
yield* budget.observe("github.com", rateLimit(512, 5_000, RESET_AT, 8));
95+
yield* budget.query("github.com", query);
96+
// The admission reserved eight points, but the completed read only cost one.
97+
yield* budget.observe("github.com", rateLimit(511, 5_000, RESET_AT, 1));
98+
99+
for (let count = 0; count < 4; count += 1) {
100+
expect(yield* budget.query("github.com", query)).toContain("rateLimit");
101+
}
102+
const error = yield* Effect.flip(budget.query("github.com", query));
103+
expect(error).toMatchObject({
104+
_tag: "SourceControlRateLimitPausedError",
105+
retryAt: Date.parse(RESET_AT),
106+
});
107+
}).pipe(Effect.provide(GitHubGraphQlBudget.layer)),
108+
);
109+
89110
it.effect("ignores a response from an older reset window", () =>
90111
Effect.gen(function* () {
91112
yield* TestClock.setTime(BEFORE_RESET);
Collapse file

‎apps/server/src/sourceControl/githubGraphQlBudget.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/sourceControl/githubGraphQlBudget.ts
+11-6Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -122,15 +122,20 @@ export const make = Effect.gen(function* () {
122122
const previous = current.get(key);
123123
// Concurrent reads can finish out of order. Quota only falls within one reset window, and
124124
// an answer from an older window must not replace the current one.
125-
if (
126-
previous !== undefined &&
127-
(snapshot.resetAtMs < previous.resetAtMs ||
128-
(snapshot.resetAtMs === previous.resetAtMs && snapshot.remaining >= previous.remaining))
129-
) {
125+
if (previous !== undefined && snapshot.resetAtMs < previous.resetAtMs) {
130126
return current;
131127
}
132128
const next = new Map(current);
133-
next.set(key, snapshot);
129+
// Keep the conservative balance, but learn the observed cost even when our reservation
130+
// was larger. Otherwise one expensive read makes every later cheap read spend its cost.
131+
next.set(
132+
key,
133+
previous !== undefined &&
134+
snapshot.resetAtMs === previous.resetAtMs &&
135+
snapshot.remaining >= previous.remaining
136+
? { ...previous, cost: snapshot.cost }
137+
: snapshot,
138+
);
134139
return next;
135140
});
136141
});

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.