Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
178 changes: 178 additions & 0 deletions apps/server/src/pullRequest/PullRequestService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3288,6 +3288,184 @@ it.effect("asks on its own for a repository a search could not vouch for", () =>
);
}),
);
// A search page filled by acme/web, silent about the others. `pages` adds rows to later pages.
const quietWorkspace = (input: {
readonly reads: Array<string>;
readonly quiet?: ReadonlyArray<string>;
readonly failing?: string;
readonly pages?: Array<ReadonlyArray<ReturnType<typeof batchedChangeRequest>> | "fails">;
}) =>
makeService({
projects: [
project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
project({ id: "p2", title: "docs", workspaceRoot: "/b", repository: "acme/docs" }),
project({ id: "p3", title: "api", workspaceRoot: "/c", repository: "acme/api" }),
project({ id: "p4", title: "docs worktree", workspaceRoot: "/d", repository: "acme/docs" }),
],
providers: [
fakePullRequestProvider(SourceControlProviderKind.make("github"), {
listChangeRequests: ({ repository }) => {
input.reads.push(repository);
return repository === input.failing
? Effect.fail(requestFailed)
: Effect.succeed({
items: [changeRequest(repository === "acme/docs" ? 7 : 8, "2026-06-01T00:00:00Z")],
truncated: false,
continues: false,
});
},
listChangeRequestsAcross: () => {
const extra = input.pages?.shift() ?? [];
if (extra === "fails") return Effect.fail(requestFailed);
const silent = ["acme/docs", "acme/api"].filter(
(repository) => !extra.some((row) => row.repository === repository),
);
return Effect.succeed({
items: [batchedChangeRequest(1, "acme/web", "2026-07-03T00:00:00Z"), ...extra],
truncated: true,
unresolved: silent,
quiet: silent.filter((repository) => (input.quiet ?? silent).includes(repository)),
});
},
}),
],
});
// What mobile sends with nothing chosen: an empty filters object, not an omitted one.
const everyListing = {
state: "all" as const,
involvement: "all" as const,
filters: {},
limit: 30,
};
const pastListingCache = TestClock.adjust("31 seconds");

it.effect("reuses a quiet repository's own read until a turn, a refresh or ten minutes", () =>
Effect.gen(function* () {
const reads: string[] = [];
const service = yield* quietWorkspace({ reads });

yield* service.list(everyListing);
assert.deepStrictEqual(reads.toSorted(), ["acme/api", "acme/docs"]);

reads.length = 0;
yield* pastListingCache;
const again = yield* service.list(everyListing);
assert.deepStrictEqual(reads, []);
assert.deepStrictEqual(
again.entries.map((entry) => entry.number),
[1, 7, 8],
);

// The listing reads acme/docs through p2; the turn ran in its other checkout.
yield* service.refreshAfterTurn("p4" as ProjectId);
yield* pastListingCache;
yield* service.list(everyListing);
assert.deepStrictEqual(reads, ["acme/docs"]);

reads.length = 0;
yield* service.invalidate({});
yield* service.list(everyListing);
assert.deepStrictEqual(reads.toSorted(), ["acme/api", "acme/docs"]);

reads.length = 0;
yield* TestClock.adjust("10 minutes");
yield* service.list(everyListing);
assert.deepStrictEqual(reads.toSorted(), ["acme/api", "acme/docs"]);
}),
);

it.effect("hands a reused read to the checkout the listing chose", () =>
Effect.gen(function* () {
const reads: string[] = [];
const service = yield* quietWorkspace({ reads });

yield* service.list({ ...everyListing, projectIds: ["p1", "p2"] as Array<ProjectId> });
const other = yield* service.list({
...everyListing,
projectIds: ["p1", "p4"] as Array<ProjectId>,
});
assert.deepStrictEqual(reads, ["acme/docs"]);
assert.deepStrictEqual(
other.entries.map((entry) => [entry.number, entry.projectId, entry.projectTitle]),
[
[1, "p1", "web"],
[7, "p4", "docs worktree"],
],
);
}),
);

it.effect("search rows of a quiet repository end the reuse of its earlier read", () =>
Effect.gen(function* () {
const reads: string[] = [];
const service = yield* quietWorkspace({
reads,
pages: [[], [batchedChangeRequest(9, "acme/docs", "2026-07-04T00:00:00Z")]],
});

yield* service.list(everyListing);
yield* pastListingCache;
yield* service.list(everyListing);
yield* pastListingCache;
yield* service.list(everyListing);
assert.deepStrictEqual(reads.toSorted(), ["acme/api", "acme/docs", "acme/docs"]);
}),
);

it.effect("a failed search reads only the repositories without a reusable quiet read", () =>
Effect.gen(function* () {
const reads: string[] = [];
const service = yield* quietWorkspace({ reads, pages: [[], "fails", "fails", []] });

yield* service.list(everyListing);
reads.length = 0;
yield* pastListingCache;
const fallback = yield* service.list(everyListing);
assert.deepStrictEqual(reads, ["acme/web"]);
assert.deepStrictEqual(fallback.entries.map((entry) => entry.number).toSorted(), [7, 8, 8]);

// A filtered listing reuses nothing in the fallback, and the kept reads outlive it.
reads.length = 0;
yield* service.list({ ...everyListing, state: "open" as const });
assert.deepStrictEqual(reads.toSorted(), ["acme/api", "acme/docs", "acme/web"]);
reads.length = 0;
yield* pastListingCache;
yield* service.list(everyListing);
assert.deepStrictEqual(reads, []);
}),
);

it.effect("reads a silent repository every time when its read cannot be reused", () =>
Effect.gen(function* () {
const reads: string[] = [];
const service = yield* quietWorkspace({ reads, quiet: ["acme/docs"], failing: "acme/docs" });

yield* service.list(everyListing);
yield* pastListingCache;
yield* service.list(everyListing);
assert.deepStrictEqual(
reads.toSorted(),
["acme/api", "acme/api", "acme/docs", "acme/docs"],
"search does not vouch for acme/api, and the read of acme/docs failed",
);

// A pull request can leave a narrower search without a newer row arriving on its page.
const narrowed = yield* quietWorkspace({ reads });
for (const narrower of [
{ ...everyListing, state: "open" as const },
{ ...everyListing, involvement: "authored" as const },
{ ...everyListing, filters: { draft: "hide" as const } },
{ ...everyListing, query: "fix" },
]) {
reads.length = 0;
yield* narrowed.list(narrower);
yield* pastListingCache;
yield* narrowed.list(narrower);
assert.deepStrictEqual(reads.toSorted(), ["acme/api", "acme/api", "acme/docs", "acme/docs"]);
}
}),
);

it.effect("believes a search's silence about a repository it vouches for", () =>
Effect.gen(function* () {
const separately: string[] = [];
Expand Down
140 changes: 131 additions & 9 deletions apps/server/src/pullRequest/PullRequestService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,8 @@ const VIEWER_CACHE_TTL = Duration.minutes(10);
const STALE_DETAIL_WINDOW = Duration.minutes(10);
const isPullRequestProviderError = Schema.is(PullRequestProviderError);
const LIST_CACHE_CAPACITY = 64;
const QUIET_READ_TTL = Duration.minutes(10);
const QUIET_READ_CAPACITY = 512;
const LIST_STATS_CACHE_CAPACITY = 32;
const DETAIL_CACHE_CAPACITY = 128;
const DIFF_CACHE_CAPACITY = 128;
Expand Down Expand Up @@ -389,6 +391,20 @@ interface RepositoryBatch {
readonly nextCursor: string | null;
}

// Clients send `{}` or empty label lists when nothing is chosen: that is the unfiltered listing.
const filtersInUse = (
filters: PullRequestListFilters | undefined,
): PullRequestListFilters | undefined =>
filters !== undefined &&
(filters.draft !== undefined ||
filters.review !== undefined ||
filters.checks !== undefined ||
filters.author !== undefined ||
(filters.labels?.length ?? 0) > 0 ||
(filters.excludedLabels?.length ?? 0) > 0)
? filters
: undefined;

interface ListCursor extends ProviderListCursor {
readonly seenAt: ReadonlyArray<number>;
}
Expand Down Expand Up @@ -1374,6 +1390,25 @@ export const make = Effect.gen(function* () {
};
};

// First-page reads of quiet repositories, kept by `quietRead` in `listUncached`.
const quietReads = new Map<
string,
{
readonly at: number;
readonly listingsEpoch: number;
readonly generation: number;
readonly batch: RepositoryBatch;
}
>();
// Moves for a repository when its kept read may no longer hold: search returned rows of it, or
// a turn ran in one of its checkouts. The floor moves them all.
const quietGenerations = new Map<string, number>();
let quietGenerationFloor = 0;
const quietGeneration = (cursorKey: string) =>
quietGenerationFloor + (quietGenerations.get(cursorKey) ?? 0);
const endQuietReuse = (cursorKey: string) =>
quietGenerations.set(cursorKey, (quietGenerations.get(cursorKey) ?? 0) + 1);

const listUncached: PullRequestService["Service"]["list"] = Effect.fn(
"PullRequestService.listUncached",
)(function* (input) {
Expand Down Expand Up @@ -1575,13 +1610,84 @@ export const make = Effect.gen(function* () {
return readSlice(project, cursorOf(project)).pipe(Effect.flatMap((batch) => fill(batch, 1)));
};

// A quiet repository has no row newer than the search page, and in the unconstrained listing
// any change to one of its pull requests brings that row onto the page, so its own read holds
// until then. A narrower search can lose a row (a close, a new label) without gaining one.
const reusesQuietReads =
input.state === "all" &&
involvement === "all" &&
input.filters === undefined &&
(input.query?.trim() ?? "") === "" &&
(yield* routingCredential) === null;
const quietKey = (project: SupportedProject) =>
`${project.cursorKey}\n${viewers[project.host]}\n${limit}`;
const heldQuietRead = (project: SupportedProject, now: number): RepositoryBatch | undefined => {
const held = quietReads.get(quietKey(project));
if (
held === undefined ||
held.listingsEpoch !== listingsEpoch ||
held.generation !== quietGeneration(project.cursorKey) ||
now - held.at >= Duration.toMillis(QUIET_READ_TTL)
) {
return undefined;
}
// Checkouts of one repository share the read; the rows belong to the one listed now.
return {
...held.batch,
entries: held.batch.entries.map((entry) => ({
...entry,
projectId: project.project.id,
projectTitle: project.project.title,
})),
};
};
const quietRead = Effect.fn("PullRequestService.quietRead")(function* (
project: SupportedProject,
) {
const key = quietKey(project);
const generation = quietGeneration(project.cursorKey);
const now = yield* Clock.currentTimeMillis;
const held = heldQuietRead(project, now);
if (held !== undefined) return held;
const epochBefore = epochCounter;
const batch = yield* readRepository(project);
// Not kept if it failed, or if a turn, refresh or search row arrived while it was read.
if (
batch.errors.length === 0 &&
epochCounter === epochBefore &&
quietGeneration(project.cursorKey) === generation
) {
quietReads.delete(key);
quietReads.set(key, { at: now, listingsEpoch, generation, batch });
if (quietReads.size > QUIET_READ_CAPACITY) {
const oldest = quietReads.keys().next().value;
if (oldest !== undefined) quietReads.delete(oldest);
}
}
return batch;
});

const readTogether = (
chunk: ReadonlyArray<SupportedProject>,
): Effect.Effect<ReadonlyArray<RepositoryBatch>> => {
const first = chunk[0]!;
const readAcross = first.api.listChangeRequestsAcross;
// A failed search says nothing new about a repository, so a read kept since a page last
// named it quiet still stands in for it. What is read here is not kept: nothing vouches.
const separately = () =>
Effect.forEach(chunk, readRepository, { concurrency: REPOSITORY_CONCURRENCY });
Effect.flatMap(Clock.currentTimeMillis, (now) =>
Effect.forEach(
chunk,
(project): Effect.Effect<RepositoryBatch> => {
const held =
reusesQuietReads && cursorOf(project) === undefined
? heldQuietRead(project, now)
: undefined;
return held === undefined ? readRepository(project) : Effect.succeed(held);
},
{ concurrency: REPOSITORY_CONCURRENCY },
),
);
if (readAcross === undefined) return separately();
const viewer = viewers[first.host]!;
const cursor = cursorOf(first);
Expand Down Expand Up @@ -1622,6 +1728,9 @@ export const make = Effect.gen(function* () {
const unresolved = new Set(
(page.unresolved ?? []).map((repository) => repository.trim().toLowerCase()),
);
const quiet = new Set(
(page.quiet ?? []).map((repository) => repository.trim().toLowerCase()),
);
const boundary = page.items.reduce<string | null>(
(oldest, item) =>
oldest === null || item.updatedAt < oldest ? item.updatedAt : oldest,
Expand All @@ -1632,7 +1741,12 @@ export const make = Effect.gen(function* () {
(project): Effect.Effect<RepositoryBatch> => {
const key = project.repository.trim().toLowerCase();
const fetched = rows.get(key) ?? [];
if (fetched.length === 0 && unresolved.has(key)) return readRepository(project);
if (fetched.length > 0) endQuietReuse(project.cursorKey);
if (fetched.length === 0 && unresolved.has(key)) {
return reusesQuietReads && quiet.has(key) && cursorOf(project) === undefined
? quietRead(project)
: readRepository(project);
}
const cursorHere = cursorOf(project);
const items =
cursorHere === undefined
Expand Down Expand Up @@ -3268,19 +3382,20 @@ export const make = Effect.gen(function* () {
},
);
const list: PullRequestService["Service"]["list"] = (input) => {
const filters = filtersInUse(input.filters);
const key = JSON.stringify([
listingsEpoch,
input.state,
input.involvement ?? null,
input.filters === undefined
filters === undefined
? null
: [
input.filters.draft ?? null,
input.filters.review ?? null,
input.filters.checks ?? null,
input.filters.author ?? null,
input.filters.labels ?? null,
input.filters.excludedLabels ?? null,
filters.draft ?? null,
filters.review ?? null,
filters.checks ?? null,
filters.author ?? null,
filters.labels ?? null,
filters.excludedLabels ?? null,
],
input.projectId ?? null,
input.projectIds === undefined ? null : [...input.projectIds].sort(),
Expand Down Expand Up @@ -3804,6 +3919,13 @@ export const make = Effect.gen(function* () {
// change request reached through another repository, and no epoch may move until those
// reads are gone, or a reader in between keeps the old one under the new epoch.
yield* forgetProviderReads();
if (quietReads.size > 0) {
// Resolved as the list resolves it: the list keeps one checkout per repository, so the
// turn's project need not be the one a kept read was made through.
const turned = yield* listWorkspaceProjects({ projectId }).pipe(Effect.option);
if (Option.isNone(turned)) quietGenerationFloor += 1;
else for (const { cursorKey } of turned.value.supported) endQuietReuse(cursorKey);
}
const epoch = ++epochCounter;
// A push can open or move a PR; a plain turn waits for the listing TTL to spare the API quota.
if (options?.pushed === true) listingsEpoch = epoch;
Expand Down
Loading
Loading