From d18d7b8771dfe5af44f072ae8934ff8e0d328fb6 Mon Sep 17 00:00:00 2001 From: sickerine Date: Sat, 28 Nov 2026 07:49:11 +0000 Subject: [PATCH 1/2] perf(screening): keep the counts Papers narrows by, and read a reviewer's papers by their cards Step one of two (widen, migrate, narrow). Nothing reads the new counts yet: once the backfill has run and checked clean on shared dev, the tab counts and the overview's votes of the last days read them (the next PR). - screeningFacetCounts, an aggregate kept by triggers on papers and votes (convex/screening/facets.ts): each paper under its source, its check and its reason, each vote under its reviewer with where its paper stands, and each cast vote by when. A tab's count under one narrowing becomes a few counted reads. - migrations/screeningFacets counts every paper and vote from before, with `verify` to check none is missing. - One reviewer's papers on Papers are filtered by each paper's card, a few facts, rather than the paper with its abstract: 555 KB read for a page of Included at 5,000 papers before, 235 KB after. - A vote's trigger reads its paper once a mutation: a step of a reading deals 2,000 votes on 200 papers it just made, and read 2,000 times they passed a transaction's 4,096 index ranges (the size tests caught it). - convex/bench/screening-team.bench.ts measures what the pages read on a screening with two reviewers, and checks each count against the cards and votes. - The size tests move time a second a turn: jumped to every timer at once, the watch on a reading woke over and over while the counts were written in batches, and took the reading for one gone quiet. --- convex/_generated/api.d.ts | 5 + convex/bench/screening-team.bench.ts | 132 ++++++++++++++++++ convex/convex.config.ts | 2 + convex/lib/triggers.ts | 4 + convex/limits/maxSizeScreening.test.ts | 11 +- convex/migrations/screeningFacets.ts | 74 ++++++++++ convex/screening/facets.ts | 150 +++++++++++++++++++++ convex/screening/paperViews.ts | 9 +- convex/screening/reviewers.test-support.ts | 5 +- 9 files changed, 384 insertions(+), 8 deletions(-) create mode 100644 convex/bench/screening-team.bench.ts create mode 100644 convex/migrations/screeningFacets.ts create mode 100644 convex/screening/facets.ts diff --git a/convex/_generated/api.d.ts b/convex/_generated/api.d.ts index d1e048e6f..e20ca2252 100644 --- a/convex/_generated/api.d.ts +++ b/convex/_generated/api.d.ts @@ -367,6 +367,7 @@ import type * as migrations_recordApprovedQueries from "../migrations/recordAppr import type * as migrations_reportIntake from "../migrations/reportIntake.js"; import type * as migrations_revokeDeletedOrganizationMemberships from "../migrations/revokeDeletedOrganizationMemberships.js"; import type * as migrations_rotateKeptFiles from "../migrations/rotateKeptFiles.js"; +import type * as migrations_screeningFacets from "../migrations/screeningFacets.js"; import type * as migrations_screeningOutcomes from "../migrations/screeningOutcomes.js"; import type * as migrations_screeningPeopleFirst from "../migrations/screeningPeopleFirst.js"; import type * as migrations_screeningReviewers from "../migrations/screeningReviewers.js"; @@ -459,6 +460,7 @@ import type * as screening_doiRecords from "../screening/doiRecords.js"; import type * as screening_drain from "../screening/drain.js"; import type * as screening_effects from "../screening/effects.js"; import type * as screening_estimate from "../screening/estimate.js"; +import type * as screening_facets from "../screening/facets.js"; import type * as screening_files from "../screening/files.js"; import type * as screening_filesMail from "../screening/filesMail.js"; import type * as screening_gathering from "../screening/gathering.js"; @@ -924,6 +926,7 @@ declare const fullApi: ApiFromModules<{ "migrations/reportIntake": typeof migrations_reportIntake; "migrations/revokeDeletedOrganizationMemberships": typeof migrations_revokeDeletedOrganizationMemberships; "migrations/rotateKeptFiles": typeof migrations_rotateKeptFiles; + "migrations/screeningFacets": typeof migrations_screeningFacets; "migrations/screeningOutcomes": typeof migrations_screeningOutcomes; "migrations/screeningPeopleFirst": typeof migrations_screeningPeopleFirst; "migrations/screeningReviewers": typeof migrations_screeningReviewers; @@ -1016,6 +1019,7 @@ declare const fullApi: ApiFromModules<{ "screening/drain": typeof screening_drain; "screening/effects": typeof screening_effects; "screening/estimate": typeof screening_estimate; + "screening/facets": typeof screening_facets; "screening/files": typeof screening_files; "screening/filesMail": typeof screening_filesMail; "screening/gathering": typeof screening_gathering; @@ -1154,6 +1158,7 @@ export declare const components: { listCounts: import("@convex-dev/aggregate/_generated/component.js").ComponentApi<"listCounts">; libraryFacetCounts: import("@convex-dev/aggregate/_generated/component.js").ComponentApi<"libraryFacetCounts">; extractionFacetCounts: import("@convex-dev/aggregate/_generated/component.js").ComponentApi<"extractionFacetCounts">; + screeningFacetCounts: import("@convex-dev/aggregate/_generated/component.js").ComponentApi<"screeningFacetCounts">; batchWorker: import("@convex-dev/batch-worker/_generated/component.js").ComponentApi<"batchWorker">; presence: import("@convex-dev/presence/_generated/component.js").ComponentApi<"presence">; }; diff --git a/convex/bench/screening-team.bench.ts b/convex/bench/screening-team.bench.ts new file mode 100644 index 000000000..443c50458 --- /dev/null +++ b/convex/bench/screening-team.bench.ts @@ -0,0 +1,132 @@ +// What a screening with reviewers costs to read as it grows: the pages its people open (Screen's queues, Papers +// with its tabs and filters, a paper, the screening's header), the counts beside them, and what the rail and the +// list of screenings read. Seeded through the real mutations, so its cards, counts and settled results are the ones +// the product writes. `npm run bench`, BENCH_SIZES to change the sizes, BENCH_LABEL to name a run. +import { afterAll, afterEach, beforeEach, describe, it, vi } from "vitest"; +import { api, internal } from "../_generated/api"; +import type { Id } from "../_generated/dataModel"; +import { text } from "../lib/maxSize.test-support"; +import { paper, papersOf, started, team } from "../screening/reviewers.test-support"; +import { measure, save } from "./measure.test-support"; +import { tallyOfReviewer, tallyUnder } from "../screening/facets"; +import * as view from "../screening/view"; +import * as paperViews from "../screening/paperViews"; + +const SIZES = (process.env.BENCH_SIZES ?? "5000").split(",").map(Number); +/** The rows one page of Papers and of Screen's queue holds, as the pages ask for them. */ +const PAGE = 50; +const QUEUE_PAGE = 25; + +type Handler = { _handler: (ctx: unknown, args: Record) => Promise }; +/** A query's own handler, run in the transaction `measure` reads the metrics of, signed in as whoever `t` is. */ +const call = (fn: unknown, args: Record) => (ctx: unknown) => (fn as Handler)._handler(ctx, args); +const page = (options: { cursor: string | null; numItems: number }) => ({ paginationOpts: options }); +const rows = (read: unknown) => `${(read as { page?: unknown[] } | null)?.page?.length ?? 0} rows`; +/** What a count said, so two runs can be checked to agree. */ +const said = (read: unknown) => JSON.stringify(read, read && typeof read === "object" ? Object.keys(read).sort() : undefined); + +describe("a screening with reviewers, read by its pages", () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => { + vi.clearAllTimers(); + vi.useRealTimers(); + }); + afterAll(() => save(__filename)); + + for (const size of SIZES) { + it(`${size} papers, two people on each`, async () => { + const made = await team(["ann", "ben"]); + const { t, as, workspaceId } = made; + // A plan with no limit on the papers one screening holds, so the size asked for is the size read. + await t.run(async (ctx) => { + const account = (await ctx.db.query("billingAccounts").withIndex("by_workspace", (q) => q.eq("workspaceId", workspaceId)).unique())!; + await ctx.db.patch("billingAccounts", account._id, { limits: { ...account.limits, request_papers: null } }); + }); + const { jobId } = await started(made, ["ann", "ben"], 0); + // Its source gives the papers a step at a time, as its reading does, each with an abstract of a real one's length. + const { checkId, sourceId } = await t.run(async (ctx) => ({ + checkId: (await ctx.db.query("screeningChecks").withIndex("by_job", (q) => q.eq("jobId", jobId)).first())!._id, + sourceId: (await ctx.db.query("screeningSources").withIndex("by_job", (q) => q.eq("jobId", jobId)).first())!._id, + })); + await t.mutation(internal.screening.gathering.begin, { sourceId }); + for (let from = 0; from < size; from += 200) { + const step = Array.from({ length: Math.min(200, size - from) }, (_, n) => paper(from + n + 1, { title: `Paper ${from + n + 1}: ${text(100, from + n)}`, abstract: text(1_400, from + n) })); + await t.mutation(internal.screening.gathering.fill, { checkId, sourceId, papers: step, read: step.length, ended: from + 200 >= size }); + } + const ids = (await papersOf(t, jobId)).map((one) => one._id as Id<"screeningResults">); + // Ann votes on every paper, a third each way; Ben on the first half, agreeing on most, so some are in conflict. + const ways = ["include", "maybe", "exclude"] as const; + const voteAll = async (who: "ann" | "ben", papers: Id<"screeningResults">[], way: (at: number) => (typeof ways)[number]) => { + for (const decision of ways) { + const picked = papers.filter((_, at) => way(at) === decision); + for (let from = 0; from < picked.length; from += 100) await as[who]!.mutation(api.screening.voting.voteMany, { workspaceId, jobId, paperIds: picked.slice(from, from + 100), decision, ...(decision === "exclude" ? { reason: "other" } : {}) }); + } + }; + await voteAll("ann", ids, (at) => ways[at % 3]!); + await voteAll("ben", ids.slice(0, size / 2), (at) => (at % 10 === 0 ? ways[(at + 1) % 3]! : ways[at % 3]!)); + // The bookkeeping settles what the votes decide, as its worker does. + for (let pass = 0; ; pass++) { + const work = await t.query(internal.screening.bookkeeping.nextFinished, { name: "screening" }); + if (work.kind !== "work") break; + if (pass > 5_000) throw new Error("The bookkeeping never ran out of papers"); + await t.mutation(internal.screening.bookkeeping.bookkeep, work.batch); + } + const { annRow, annReviewer } = await t.run(async (ctx) => { + const row = (await ctx.db.query("screeningReviewers").withIndex("by_job", (q) => q.eq("jobId", jobId)).collect()).find((one) => one.kind === "person")!; + return { annRow: row.userId!, annReviewer: row._id }; + }); + // Each count as the cards and votes say it, read whole: what the counted reads must agree with. + const truth = await t.run(async (ctx) => { + const cards = (await ctx.db.query("screeningCards").withIndex("by_job", (q) => q.eq("jobId", jobId)).collect()).filter((card) => !card.withdrawn); + const byPaper = new Map(cards.map((card) => [card.resultId, card.result])); + const votes = await ctx.db.query("screeningVotes").withIndex("by_reviewer_and_status_and_at", (q) => q.eq("reviewerId", annReviewer).eq("status", "cast")).collect(); + const tally = (results: Array) => said(Object.fromEntries(["include", "maybe", "exclude", "conflict", "waiting"].map((result) => [result, results.filter((one) => one === result).length]))); + return { + source: tally(cards.filter((card) => card.sourceId === sourceId).map((card) => card.result)), + reviewer: tally(votes.map((vote) => byPaper.get(vote.resultId))), + include: tally(votes.filter((vote) => vote.decision === "include").map((vote) => byPaper.get(vote.resultId))), + }; + }); + // Counts kept by a worker a moment after each change are caught up before anything is read: until they agree with + // the cards and votes. The screening's own loops reschedule themselves for good, so the worker is given turns, not + // run until nothing is left. + for (let turn = 0; ; turn++) { + vi.advanceTimersByTime(2_000); + await t.finishInProgressScheduledFunctions(); + if (turn % 20 === 19 && (await t.run(async (ctx) => said(await tallyOfReviewer(ctx as never, annReviewer, ["include", "maybe", "exclude"])) === truth.reviewer && said(await tallyUnder(ctx as never, jobId, { source: sourceId })) === truth.source))) { console.log(`counts caught up after ${turn + 1} turns`); break; } + if (turn > 4_000) throw new Error("The counts never caught up"); + } + const ann = as.ann!; + const ben = as.ben!; + const at = (scenario: string) => ({ area: "screening team", scenario, size }); + const first = { cursor: null, numItems: PAGE }; + const job = { workspaceId, jobId }; + + // The screening's own page: its header and figures, read on every tab. + await measure(ann, at("screening header (view.get)"), call(view.get, job)); + await measure(ann, at("overview figures"), call(view.figures, { ...job, since: 0 }), (read) => JSON.stringify((read as { recent?: unknown } | null)?.recent)); + // Papers: a page of each tab, then narrowed to one reviewer, the way the reviewer chips narrow it. + await measure(ann, at("papers, all"), call(paperViews.list, { ...job, ...page(first) }), rows); + await measure(ann, at("papers, excluded tab"), call(paperViews.list, { ...job, result: "exclude", ...page(first) }), rows); + await measure(ann, at("papers, in conflict tab"), call(paperViews.list, { ...job, result: "conflict", ...page(first) }), rows); + await measure(ann, at("papers, one reviewer"), call(paperViews.list, { ...job, reviewer: annRow, ...page(first) }), rows); + await measure(ann, at("papers, one reviewer, included tab"), call(paperViews.list, { ...job, reviewer: annRow, result: "include", ...page(first) }), rows); + await measure(ann, at("papers, one reviewer voted exclude"), call(paperViews.list, { ...job, reviewer: annRow, voted: "exclude", ...page(first) }), rows); + await measure(ann, at("papers, searched"), call(paperViews.list, { ...job, text: "randomized", ...page(first) }), rows); + await measure(ann, at("papers, by title"), call(paperViews.list, { ...job, sort: "title", ...page(first) }), rows); + // The counts beside the tabs, whole and for one reviewer. + await measure(ann, at("tab counts, one source"), call(paperViews.counts, { ...job, source: sourceId }), said, (read) => said(read) === truth.source); + await measure(ann, at("tab counts, one reviewer"), call(paperViews.counts, { ...job, reviewer: annRow }), said, (read) => said(read) === truth.reviewer); + await measure(ann, at("tab counts, one reviewer voted include"), call(paperViews.counts, { ...job, reviewer: annRow, voted: "include" }), said, (read) => said(read) === truth.include); + // Screen's queues, as Ben (half his papers still to do) and Ann (all done). + await measure(ben, at("Screen, to do"), call(paperViews.queue, { ...job, queue: "todo", order: "dealt", ...page({ cursor: null, numItems: QUEUE_PAGE }) }), rows); + await measure(ann, at("Screen, done"), call(paperViews.queue, { ...job, queue: "done", ...page({ cursor: null, numItems: QUEUE_PAGE }) }), rows); + await measure(ann, at("Screen, conflicts"), call(paperViews.queue, { ...job, queue: "conflicts", ...page({ cursor: null, numItems: QUEUE_PAGE }) }), rows); + await measure(ann, at("one paper"), call(paperViews.paper, { ...job, paperId: ids[1]! })); + // What every page of the app reads: the rail's count, and the list of screenings. + await measure(ben, at("rail"), call(view.rail, { workspaceId })); + await measure(ann, at("screenings list"), call(view.list, { workspaceId, show: "all", sort: "active", ...page({ cursor: null, numItems: 20 }) }), rows); + await measure(ann, at("screenings waiting for me"), call(view.mine, { workspaceId }), rows); + }); + } +}); diff --git a/convex/convex.config.ts b/convex/convex.config.ts index ebb46dbc1..29f068b23 100644 --- a/convex/convex.config.ts +++ b/convex/convex.config.ts @@ -27,6 +27,8 @@ app.use(aggregate, { name: "listCounts" }); app.use(aggregate, { name: "libraryFacetCounts" }); // extractionFacetCounts: each extraction job's papers by confidence, status tags and answers (convex/extraction/facets.ts). app.use(aggregate, { name: "extractionFacetCounts" }); +// screeningFacetCounts: a screening's papers by source, check and reason, and each reviewer's papers by how they stand on them (convex/screening/facets.ts). +app.use(aggregate, { name: "screeningFacetCounts" }); // Queues whose one worker each does shared bookkeeping in batches, so parallel work only // writes its own rows: Screen all's results (convex/screening/bookkeeping.ts) and the // usage ledger (convex/billing/ledger.ts). diff --git a/convex/lib/triggers.ts b/convex/lib/triggers.ts index 4725ff86f..2dca51030 100644 --- a/convex/lib/triggers.ts +++ b/convex/lib/triggers.ts @@ -19,6 +19,7 @@ import { countAnswerChange, countPaperChange as countPaperFacets } from "../extr import { tallyAnswerChange } from "../extraction/tallies"; import { adminText, jobText, keepSearchText, keepTextOfUser, memberText, searchText, shortcutText } from "./searchText"; import { keepCard } from "../screening/cards"; +import { countPaperFacets as countScreeningPaper, countVoteFacets as countScreeningVote } from "../screening/facets"; import { ADMIN_LIST, countList, libraryVersionList, personWaitingApplicationsOf, screeningFileList, screeningList, waitingApplicationsOf, walletKeyList, workspaceLibrariesOf } from "./listCounts"; import { followShared, itemGuestsOf, sharedWithOf } from "../sharing/items"; import { refreshOnSearch } from "../research/suggestionRefresh"; @@ -97,6 +98,9 @@ triggers.register("screeningJobs", followShared("screening")); triggers.register("screeningJobs", countList(screeningList)); triggers.register("screeningFiles", countList(screeningFileList)); triggers.register("screeningResults", keepCard); +// A screening's Papers counts under one narrowing read what these keep (../screening/facets.ts). +triggers.register("screeningResults", countScreeningPaper); +triggers.register("screeningVotes", countScreeningVote); // A guest who edits a screening is one of its reviewers, and one who only looks, or has it no more, is not (../screening/reviewers.ts). triggers.register("itemAccess", async (ctx, change) => { const grant = change.newDoc ?? change.oldDoc; diff --git a/convex/limits/maxSizeScreening.test.ts b/convex/limits/maxSizeScreening.test.ts index 5b36cf390..dd2ab95db 100644 --- a/convex/limits/maxSizeScreening.test.ts +++ b/convex/limits/maxSizeScreening.test.ts @@ -20,6 +20,11 @@ const saved = (made: Team, items: number) => journal: text(40, i), citedByCount: i % 500, paperData: text(1_700, i), searchableText: text(160, i), savedAt: 1_700_000_000_000 + i, updatedAt: 1, abstract: text(2_000, i), })), 500); +// Time moves a second a turn while scheduled work runs, as it does: jumped to every timer at once, the watch on a +// reading (../screening/gathering.ts `watch`) wakes over and over while the counts beside its papers are still being written, +// and takes the reading for one gone quiet. +const tick = () => vi.advanceTimersByTime(1_000); + describe("a screening with reviewers at the largest sizes the product allows", { tags: ["size"] }, () => { let made: Team; let jobId: Id<"screeningJobs">; @@ -30,7 +35,7 @@ describe("a screening with reviewers at the largest sizes the product allows", { await saved(made, PAPERS); // Ten people, each on every paper: its sources are read by the screening's own reading, a step at a time, and every paper dealt as it arrives. ({ jobId } = await started(made, PEOPLE, 0, { rule: { each: "all", settle: "all", blind: "after" } })); - await runAll(made.t, vi.runAllTimers); + await runAll(made.t, tick); }, 900_000); afterAll(() => { vi.clearAllTimers(); @@ -65,7 +70,7 @@ describe("a screening with reviewers at the largest sizes the product allows", { const { workspaceId } = made; const first = (await made.as.ann!.query(api.screening.paperViews.queue, { workspaceId, jobId, queue: "todo", ...page(100) })).page.map((one) => one.id); for (const name of PEOPLE) await made.as[name]!.mutation(api.screening.voting.voteMany, { workspaceId, jobId, paperIds: first, decision: "include" }); - await runAll(made.t, vi.runAllTimers); + await runAll(made.t, tick); expect((await made.as.ann!.query(api.screening.view.get, { workspaceId, jobId }))!.counts).toMatchObject({ include: 100, waiting: PAPERS - 100 }); // What a change would do is counted over all 5,000, a step at a time: here, that one vote settles a paper. const preview = await made.as.ann!.action(api.screening.effects.preview, { workspaceId, jobId, change: { rule: { each: "all", settle: "one", blind: "after" } } }); @@ -87,7 +92,7 @@ describe("a step of papers that goes to many reviewers", { tags: ["size"] }, () await ctx.db.insert("screeningReviewers", { jobId, kind: "person", userId, addedAt: 2 + i, addedBy: made.ids.ann!, dealt: 0 }); } }); - await runAll(made.t, vi.runAllTimers); + await runAll(made.t, tick); const view = (await made.as.ann!.query(api.screening.view.get, { workspaceId: made.workspaceId, jobId }))!; expect(view).toMatchObject({ total: 400, forYou: 400 }); expect(view.reviewers.map((one) => one.dealt)).toEqual(Array(121).fill(400)); diff --git a/convex/migrations/screeningFacets.ts b/convex/migrations/screeningFacets.ts new file mode 100644 index 000000000..2660962a2 --- /dev/null +++ b/convex/migrations/screeningFacets.ts @@ -0,0 +1,74 @@ +import { Migrations } from "@convex-dev/migrations"; +import { v } from "convex/values"; +import { components, internal } from "../_generated/api"; +import type { DataModel } from "../_generated/dataModel"; +import { internalAction, internalQuery } from "../_generated/server"; +import { internalMutation } from "../lib/functions"; +import { countEntries, paperEntries, screeningCounts, voteEntries } from "../screening/facets"; + +/** + * Counts the papers and votes of every screening with reviewers that predate their counts (screening/facets.ts): each + * paper under its source, its check and its reason, each vote under its reviewer with where its paper stands, and + * each cast vote by when. Rows written since are kept by their triggers; a row is counted once however often this runs. + * + * npx convex run migrations/screeningFacets:run '{"dryRun": true}' + * npx convex run migrations/screeningFacets:run + * npx convex run migrations/screeningFacets:verify + */ +const migrations = new Migrations(components.migrations, { internalMutation }); + +export const papers = migrations.define({ + table: "screeningResults", + batchSize: 200, + migrateOne: async (ctx, paper) => { + await countEntries(ctx, paperEntries(paper)); + }, +}); + +export const votes = migrations.define({ + table: "screeningVotes", + batchSize: 200, + migrateOne: async (ctx, vote) => { + await countEntries(ctx, voteEntries(vote, await ctx.db.get("screeningResults", vote.resultId))); + }, +}); + +export const run = migrations.runner([internal.migrations.screeningFacets.papers, internal.migrations.screeningFacets.votes]); + +const tableValidator = v.union(v.literal("screeningResults"), v.literal("screeningVotes")); + +/** Entries one page of `table` should have that the counts don't. */ +export const verifyPage = internalQuery({ + args: { table: tableValidator, cursor: v.union(v.string(), v.null()) }, + returns: v.object({ missing: v.number(), isDone: v.boolean(), continueCursor: v.string() }), + handler: async (ctx, { table, cursor }) => { + const opts = { cursor, numItems: 100 }; + const missing = async (entries: ReturnType) => + (await screeningCounts.countBatch(ctx, entries.map(({ namespace, key, id }) => ({ namespace, bounds: { lower: { key, id, inclusive: true }, upper: { key, id, inclusive: true } } })) as never, { stale: true })).filter((count) => count !== 1).length; + if (table === "screeningResults") { + const page = await ctx.db.query("screeningResults").paginate(opts); + return { missing: await missing(page.page.flatMap(paperEntries)), isDone: page.isDone, continueCursor: page.continueCursor }; + } + const page = await ctx.db.query("screeningVotes").paginate(opts); + const entries = (await Promise.all(page.page.map(async (vote) => voteEntries(vote, await ctx.db.get("screeningResults", vote.resultId))))).flat(); + return { missing: await missing(entries), isDone: page.isDone, continueCursor: page.continueCursor }; + }, +}); + +/** How many entries `verifyPage` finds missing across both tables; 0 when the backfill is done. */ +export const verify = internalAction({ + args: {}, + returns: v.number(), + handler: async (ctx): Promise => { + let missing = 0; + for (const table of ["screeningResults", "screeningVotes"] as const) { + for (let cursor: string | null = null; ;) { + const page: { missing: number; isDone: boolean; continueCursor: string } = await ctx.runQuery(internal.migrations.screeningFacets.verifyPage, { table, cursor }); + missing += page.missing; + if (page.isDone) break; + cursor = page.continueCursor; + } + } + return missing; + }, +}); diff --git a/convex/screening/facets.ts b/convex/screening/facets.ts new file mode 100644 index 000000000..feb01a8a9 --- /dev/null +++ b/convex/screening/facets.ts @@ -0,0 +1,150 @@ +/** + * A screening's papers and votes counted by what its Papers page narrows to, so a tab's count under any one narrowing + * is a few counted reads, never a read of every paper (plans/screening-reviewers). Namespaces of the + * `screeningFacetCounts` aggregate: + * + * - `${jobId}:source:${sourceId}` and `${jobId}:check:${checkId}`: each paper by where it stands. + * - `${jobId}:reason`: each excluded paper by why. + * - `${reviewerId}`: each paper a reviewer is on, by how they stand on it and where the paper stands: + * `include|conflict` is a paper they voted include on that is in conflict. + * - `${reviewerId}:at`: each vote they cast, by when. + * + * A paper that left with its source counts nowhere but in its reviewers' votes by when, as its card does + * (./cards.ts). Triggers on screeningResults and screeningVotes keep them, queued once per mutation + * (../lib/countQueue.ts). This module holds no Convex functions, so the triggers can load it. + */ +import { DirectAggregate } from "@convex-dev/aggregate"; +import type { Change } from "convex-helpers/server/triggers"; +import { components } from "../_generated/api"; +import type { DataModel, Doc, Id } from "../_generated/dataModel"; +import type { QueryCtx } from "../_generated/server"; +import { queueCounts, type QueueingCtx } from "../lib/countQueue"; +import { NO_REASON } from "../../lib/screening/rules"; +import { MAX_REVIEWERS } from "./validators"; + +type Key = string | number; +export const screeningCounts = new DirectAggregate<{ Namespace: string; Key: Key; Id: string }>(components.screeningFacetCounts); + +const RESULTS = ["include", "maybe", "exclude", "conflict", "waiting"] as const; +type Result = (typeof RESULTS)[number]; +export type Tally = Record; +/** How a reviewer stands on a paper: the way they voted, or that they haven't (`waiting`), or that a model couldn't (`failed`). */ +export type Way = "include" | "maybe" | "exclude" | "waiting" | "failed"; + +const sourceOf = (jobId: Id<"screeningJobs">, sourceId: Id<"screeningSources">) => `${jobId}:source:${sourceId}`; +const checkOf = (jobId: Id<"screeningJobs">, checkId: Id<"screeningChecks">) => `${jobId}:check:${checkId}`; +const reasonsOf = (jobId: Id<"screeningJobs">) => `${jobId}:reason`; +const reviewerOf = (reviewerId: Id<"screeningReviewers">) => `${reviewerId}`; +const castOf = (reviewerId: Id<"screeningReviewers">) => `${reviewerId}:at`; + +type Entry = { namespace: string; key: Key; id: string }; +type Paper = Pick, "_id" | "jobId" | "place" | "withdrawn" | "result" | "sourceId" | "checkId" | "reason">; +const resultOf = (paper: Pick): Result => paper.result ?? "waiting"; +/** Whether a paper counts in its screening's lists: one with a place, still in it. */ +const counted = (paper: Pick | null): paper is Pick => Boolean(paper && paper.place !== undefined && !paper.withdrawn); + +const same = (a: Entry, b: Entry) => a.namespace === b.namespace && a.key === b.key && a.id === b.id; +/** Queues what moved between two sets of entries. Inserting twice or deleting what isn't there does nothing, so a backfill just counts every row again. */ +async function move(ctx: QueueingCtx, was: Entry[], now: Entry[]) { + await queueCounts(ctx, screeningCounts, [ + ...was.filter((entry) => !now.some((other) => same(entry, other))).map((entry) => ({ type: "deleteIfExists" as const, ...entry })), + ...now.filter((entry) => !was.some((other) => same(entry, other))).map((entry) => ({ type: "insertIfDoesNotExist" as const, ...entry })), + ]); +} + +/** A paper's entries: where it stands under its source and its check, and why it is excluded. */ +export function paperEntries(paper: Paper | null): Entry[] { + if (!paper || !counted(paper)) return []; + const result = resultOf(paper); + return [ + ...(paper.sourceId ? [{ namespace: sourceOf(paper.jobId, paper.sourceId), key: result, id: paper._id }] : []), + ...(paper.checkId ? [{ namespace: checkOf(paper.jobId, paper.checkId), key: result, id: paper._id }] : []), + ...(result === "exclude" ? [{ namespace: reasonsOf(paper.jobId), key: paper.reason ?? NO_REASON, id: paper._id }] : []), + ]; +} + +type Vote = Pick, "_id" | "reviewerId" | "status" | "decision" | "at">; +/** A vote's entries: how its reviewer stands on its paper with where the paper stands, and, cast, when it was. */ +export function voteEntries(vote: Vote | null, paper: Pick | null): Entry[] { + if (!vote) return []; + const way = vote.status === "cast" ? vote.decision : vote.status; + return [ + ...(way && counted(paper) ? [{ namespace: reviewerOf(vote.reviewerId), key: `${way}|${resultOf(paper)}`, id: vote._id }] : []), + ...(vote.status === "cast" && vote.at !== undefined ? [{ namespace: castOf(vote.reviewerId), key: vote.at, id: vote._id }] : []), + ]; +} + +/** + * The papers one mutation has written or read, by id, while it runs: a step of a reading deals hundreds of votes on + * the papers it just made, and each vote's entries need its paper. Read once each, a step stays inside a + * transaction's reads (4,096 index ranges). Kept by the mutation's count queue, which lives as long as it does, and + * kept current by the papers' own trigger. + */ +const papersOf = new WeakMap>(); +const known = (ctx: QueueingCtx) => { + if (!ctx.countQueue) return null; + let papers = papersOf.get(ctx.countQueue); + if (!papers) papersOf.set(ctx.countQueue, (papers = new Map())); + return papers; +}; +async function paperOf(ctx: QueueingCtx, id: Id<"screeningResults">) { + const papers = known(ctx); + if (papers?.has(id)) return papers.get(id)!; + const paper = await ctx.db.get("screeningResults", id); + papers?.set(id, paper); + return paper; +} + +/** Keeps a paper's entries, and its votes' where the paper's standing in them moved. */ +export async function countPaperFacets(ctx: QueueingCtx, change: Change) { + const [was, now] = [change.oldDoc, change.newDoc]; + known(ctx)?.set(change.id, now); + await move(ctx, paperEntries(was), paperEntries(now)); + const before = counted(was) ? resultOf(was!) : null; + const after = counted(now) ? resultOf(now!) : null; + // A paper just made has no votes yet: they are dealt after it, and counted by their own trigger. + if (before === after || !was) return; + const votes = await ctx.db.query("screeningVotes").withIndex("by_result", (q) => q.eq("resultId", change.id)).take(MAX_REVIEWERS); + await move(ctx, votes.flatMap((vote) => voteEntries(vote, was)), votes.flatMap((vote) => voteEntries(vote, now))); +} + +/** Keeps a vote's entries where how it stands, or when it was cast, changed. */ +export async function countVoteFacets(ctx: QueueingCtx, change: Change) { + const [was, now] = [change.oldDoc, change.newDoc]; + if (was && now && was.status === now.status && was.decision === now.decision && was.at === now.at) return; + const paper = await paperOf(ctx, (now ?? was)!.resultId); + await move(ctx, voteEntries(was, paper), voteEntries(now, paper)); +} + +/** Counts every entry of a row that may predate the counts: what the backfill does. */ +export const countEntries = (ctx: QueueingCtx, entries: Entry[]) => move(ctx, [], entries); + +const none = (): Tally => ({ include: 0, maybe: 0, exclude: 0, conflict: 0, waiting: 0 }); +/** One count for each key, in order. A moment behind the writes. */ +const countEach = (ctx: QueryCtx, namespace: string, keys: Key[]) => + screeningCounts.countBatch(ctx, keys.map((key) => ({ namespace, bounds: { eq: key } })) as never, { stale: true }); + +/** How many of a screening's papers stand each way under one source, or one check. */ +export async function tallyUnder(ctx: QueryCtx, jobId: Id<"screeningJobs">, under: { source: Id<"screeningSources"> } | { check: Id<"screeningChecks"> }): Promise { + const counts = await countEach(ctx, "source" in under ? sourceOf(jobId, under.source) : checkOf(jobId, under.check), [...RESULTS]); + return Object.fromEntries(RESULTS.map((result, at) => [result, counts[at]!])) as Tally; +} + +/** How many of a screening's papers are excluded for `reason`: they are the only ones that stand that way. */ +export async function tallyForReason(ctx: QueryCtx, jobId: Id<"screeningJobs">, reason: string): Promise { + const [excluded] = await countEach(ctx, reasonsOf(jobId), [reason]); + return { ...none(), exclude: excluded! }; +} + +/** How many of the papers a reviewer stands one of `ways` on stand each way. */ +export async function tallyOfReviewer(ctx: QueryCtx, reviewerId: Id<"screeningReviewers">, ways: Way[]): Promise { + const keys = ways.flatMap((way) => RESULTS.map((result) => `${way}|${result}`)); + const counts = await countEach(ctx, reviewerOf(reviewerId), keys); + const tally = none(); + keys.forEach((key, at) => (tally[key.split("|")[1] as Result] += counts[at]!)); + return tally; +} + +/** How many votes a reviewer cast from `since` on. */ +export const castSince = (ctx: QueryCtx, reviewerId: Id<"screeningReviewers">, since: number) => + screeningCounts.count(ctx, { namespace: castOf(reviewerId), bounds: { lower: { key: since, inclusive: true } }, stale: true }); diff --git a/convex/screening/paperViews.ts b/convex/screening/paperViews.ts index c9fc8b17f..59aca4315 100644 --- a/convex/screening/paperViews.ts +++ b/convex/screening/paperViews.ts @@ -302,7 +302,7 @@ export const listAction = defineUserQuery({ const sort = kept && (asked_sort === "split" || asked_sort === "points") ? "added" : asked_sort; const rowOf = (id: string) => [...looking.reviewers.values()].find((one) => viewId(one) === id || one._id === id); const others = (also ?? []).flatMap((id) => rowOf(id)?._id ?? []); - const keeps = (paper: Paper) => !paper.withdrawn && (!result || (paper.result ?? "waiting") === result) && (!source || paper.sourceId === source) && (!check || paper.checkId === check) && (!reason || (paper.result === "exclude" && (paper.reason ?? NO_REASON) === reason)); + const keeps = (paper: Pick) => !paper.withdrawn && (!result || (paper.result ?? "waiting") === result) && (!source || paper.sourceId === source) && (!check || paper.checkId === check) && (!reason || (paper.result === "exclude" && (paper.reason ?? NO_REASON) === reason)); // The papers every one of those reviewers voted on. const shared = async (paperId: Id<"screeningResults">) => !others.length || others.every((id) => castOn.get(paperId)?.has(id)); const castOn = new Map, Set>>(); @@ -359,11 +359,12 @@ export const listAction = defineUserQuery({ // The paper's own filters (a result, a source, a reason) are asked of each vote before the page is cut, so a page is never empty while papers that match lie further on. ).filterWith(async (vote) => { if (!(await open(vote))) return false; - const paper = await ctx.db.get("screeningResults", vote.resultId); - if (!paper || !keeps(paper)) return false; + // Asked of the paper's card, its few facts, not of the paper with its abstract: only the page's papers are read whole. + const card = await ctx.db.query("screeningCards").withIndex("by_result", (q) => q.eq("resultId", vote.resultId)).unique(); + if (!card || !keeps(card)) return false; // The papers every one of the reviewers compared with them voted on too (an agreement cell's list), asked here as well. if (!others.length) return true; - const cast = new Set((await votesOf(ctx, paper._id)).filter((one) => one.status === "cast").map((one) => one.reviewerId)); + const cast = new Set((await votesOf(ctx, vote.resultId)).filter((one) => one.status === "cast").map((one) => one.reviewerId)); return others.every((id) => cast.has(id)); }).paginate({ ...options, maximumRowsRead: FILTER_ROWS }); // A model's decision is kept on its row as the worker last read it; the page shows it as it reads now. diff --git a/convex/screening/reviewers.test-support.ts b/convex/screening/reviewers.test-support.ts index 2f68d3a79..c59f3b1dd 100644 --- a/convex/screening/reviewers.test-support.ts +++ b/convex/screening/reviewers.test-support.ts @@ -79,9 +79,12 @@ export async function settleAll(t: T) { } /** Runs everything a change sets off, sweeps and worker alike, until nothing is left to run. `runTimers` is the test's `vi.runAllTimers`. */ +// Room for the counts a screening keeps beside its papers (../screening/facets.ts), applied a batch at a time: ten people on 5,000 papers is fifty batches. +const SCHEDULED_TURNS = 1_000; + export async function runAll(t: T, runTimers: () => void) { for (let pass = 0; pass < 20; pass++) { - await t.finishAllScheduledFunctions(runTimers); + await t.finishAllScheduledFunctions(runTimers, SCHEDULED_TURNS); await settleAll(t); } } From dc487ed166eb1c9ffbd3245af5986be3c0083f56 Mon Sep 17 00:00:00 2001 From: sickerine Date: Sat, 28 Nov 2026 08:12:59 +0000 Subject: [PATCH 2/2] fix(screening): counts follow a paper moved to another reviewer, and settling takes as many papers as its votes fit From Codex's review of this PR and the cross-family review: - A paper moved from one reviewer to another (move, and a reviewer joining) changes only the vote's reviewer; its counts stayed with the first. The vote trigger now moves them. facets.test.ts checks each reviewer's counts against their votes and the cards, read whole, as papers are moved, voted on and settled. - The vote trigger reads every row written back twice, and settling may write a row twice. Thirty people on every paper, then "settled by the first vote", closed 1,450 rows in one batch and passed a transaction's 4,096 index ranges (a new size test; dev without the trigger passes it). Bookkeeping's batches and the steps after a save now take as many papers as 400 vote writes leave room for (VOTE_WRITES, measured: 800 passed, 1,000 didn't). --- convex/limits/maxSizeScreening.test.ts | 24 ++++++++++++ convex/screening/bookkeeping.ts | 8 +++- convex/screening/dealing.ts | 10 +++++ convex/screening/facets.test.ts | 52 ++++++++++++++++++++++++++ convex/screening/facets.ts | 2 +- convex/screening/settings.ts | 4 +- 6 files changed, 95 insertions(+), 5 deletions(-) create mode 100644 convex/screening/facets.test.ts diff --git a/convex/limits/maxSizeScreening.test.ts b/convex/limits/maxSizeScreening.test.ts index dd2ab95db..bf0edc29f 100644 --- a/convex/limits/maxSizeScreening.test.ts +++ b/convex/limits/maxSizeScreening.test.ts @@ -101,4 +101,28 @@ describe("a step of papers that goes to many reviewers", { tags: ["size"] }, () vi.useRealTimers(); } }, 900_000); + + it("settles papers with many reviewers each in batches their votes fit", async () => { + vi.useFakeTimers(); + try { + const people = ["ann", ...Array.from({ length: 29 }, (_, i) => `p${i}`)]; + const made = await team(people); + await saved(made, 50); + // Thirty people on every paper, Ann's vote on each, then "settled by the first vote": each paper settles on her vote + // and closes the places of the 29 others, 1,450 rows written by one settling, each read back for its counts. + const { jobId } = await started(made, people, 0, { rule: { each: "all", settle: "all", blind: "after" } }); + await runAll(made.t, tick); + const { workspaceId } = made; + const papers = (await made.as.ann!.query(api.screening.paperViews.queue, { workspaceId, jobId, queue: "todo", ...page(50) })).page.map((one) => one.id); + expect(papers).toHaveLength(50); + await made.as.ann!.mutation(api.screening.voting.voteMany, { workspaceId, jobId, paperIds: papers, decision: "include" }); + await runAll(made.t, tick); + await made.as.ann!.mutation(api.screening.settings.save, { workspaceId, jobId, change: { rule: { each: "all", settle: "one", blind: "after" } } }); + await runAll(made.t, tick); + expect((await made.as.ann!.query(api.screening.view.get, { workspaceId, jobId }))!.counts).toMatchObject({ include: 50, waiting: 0 }); + } finally { + vi.clearAllTimers(); + vi.useRealTimers(); + } + }, 900_000); }); diff --git a/convex/screening/bookkeeping.ts b/convex/screening/bookkeeping.ts index e060c3b81..3efcf2c7f 100644 --- a/convex/screening/bookkeeping.ts +++ b/convex/screening/bookkeeping.ts @@ -21,7 +21,7 @@ import { upsertLibraryItem } from "../library/mutations"; import { findItem } from "../library/find"; import { addCollectionMembership, removeCollectionMembership } from "../library/collectionMembership"; -import { votesOf } from "./dealing"; +import { reviewersOf, VOTE_WRITES, votesOf } from "./dealing"; import { moveResultAnswers } from "./drain"; import { account, FAILED, standing, withDeltas, type Delta, type Move } from "./accounting"; import { readStartFacts, startWaitingPapers, startWaitingVotes } from "./slots"; @@ -62,10 +62,14 @@ export const nextFinished = internalQuery({ args: vQueryArgs, returns: vQueryReturns, handler: async (ctx, { cursor }) => { - const rows = await ctx.db + const read = await ctx.db .query("screeningResults") .withIndex("by_doneAt", (q) => q.gte("doneAt", cursor ?? 0n)) .take(BATCH); + // As many as their votes leave room for (./dealing.ts `papersAStep`): a paper of a screening with many reviewers counts for each. The rest come in the next batch. + const reviewers = new Map(await Promise.all([...new Set(read.map((row) => row.jobId))].map(async (jobId) => [jobId, (await reviewersOf(ctx, jobId)).length] as const))); + let room = VOTE_WRITES; + const rows = read.filter((row, at) => (room -= reviewers.get(row.jobId) || 1) >= 0 || at === 0); const last = rows.length ? doneAtOf(rows.at(-1)!) : undefined; if (last === undefined) return { kind: "idle" as const }; const jobs = await Promise.all([...new Set(rows.map((row) => row.jobId))].map((jobId) => ctx.db.get("screeningJobs", jobId))); diff --git a/convex/screening/dealing.ts b/convex/screening/dealing.ts index a8a14bccc..fc723b30f 100644 --- a/convex/screening/dealing.ts +++ b/convex/screening/dealing.ts @@ -24,6 +24,16 @@ export const votesOf = (ctx: Pick, resultId: Id<"screeningResult /** A screening's sources in the order they were added, the ones taken out included. */ export const sourcesOf = (ctx: Pick, jobId: Id<"screeningJobs">) => ctx.db.query("screeningSources").withIndex("by_job", (q) => q.eq("jobId", jobId)).take(MAX_SOURCE_ROWS); +/** + * Votes one transaction writes at most where it works through papers a step at a time: each paper has a row for + * every reviewer on it, each row written is read back twice for its trigger (./facets.ts), and settling may write a + * row twice (closed, then counted), against a transaction's 4,096 index ranges. Measured on settling papers of thirty + * reviewers each under "settled by the first vote" (convex/limits/maxSizeScreening.test.ts): 1,000 passed the limit, + * 800 didn't; 400 leaves room. A step takes as many papers as that leaves room for, at least one. + */ +export const VOTE_WRITES = 400; +export const papersAStep = (reviewers: number, most: number) => Math.max(1, Math.min(most, Math.floor(VOTE_WRITES / Math.max(1, reviewers)))); + /** A screening's reviewers in the order they were added, whoever has left included. */ export const reviewersOf = (ctx: Pick, jobId: Id<"screeningJobs">) => ctx.db.query("screeningReviewers").withIndex("by_job", (q) => q.eq("jobId", jobId)).take(MAX_REVIEWERS); diff --git a/convex/screening/facets.test.ts b/convex/screening/facets.test.ts new file mode 100644 index 000000000..00c281c6c --- /dev/null +++ b/convex/screening/facets.test.ts @@ -0,0 +1,52 @@ +// The counts Papers narrows by (./facets.ts) agree with the votes and cards they count, read whole, as papers move +// between reviewers, are voted on and settled. +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { api } from "../_generated/api"; +import type { Id } from "../_generated/dataModel"; +import { tallyOfReviewer, type Way } from "./facets"; +import { runAll, started, team } from "./reviewers.test-support"; + +beforeEach(() => vi.useFakeTimers()); +afterEach(() => vi.useRealTimers()); + +const WAYS: Way[] = ["include", "maybe", "exclude", "waiting", "failed"]; + +it("keeps a reviewer's counts with the papers moved to them, voted on and settled", async () => { + const made = await team(["ann", "ben"]); + const { t, workspaceId } = made; + // One person on each paper, so papers can be moved from one to the other. + const { jobId, papers } = await started(made, ["ann", "ben"], 8, { rule: { each: 1, settle: "all", blind: "after" } }); + const rows = await t.run(async (ctx) => (await ctx.db.query("screeningReviewers").withIndex("by_job", (q) => q.eq("jobId", jobId)).collect()).filter((one) => one.kind === "person")); + const [ann, ben] = [rows.find((one) => one.userId === made.ids.ann)!, rows.find((one) => one.userId === made.ids.ben)!]; + + /** Each way a reviewer stands, counted as the facets count it and as their votes and the cards say it. */ + const agree = async () => { + await runAll(t, vi.runAllTimers); + for (const reviewer of [ann, ben]) { + for (const way of WAYS) { + const [counted, read] = await t.run(async (ctx) => { + const votes = (await ctx.db.query("screeningVotes").withIndex("by_result").collect()).filter((vote) => vote.reviewerId === reviewer._id && (vote.status === "cast" ? vote.decision : vote.status) === way); + const tally = { include: 0, maybe: 0, exclude: 0, conflict: 0, waiting: 0 }; + for (const vote of votes) { + const card = await ctx.db.query("screeningCards").withIndex("by_result", (q) => q.eq("resultId", vote.resultId)).unique(); + if (card && !card.withdrawn) tally[card.result]++; + } + return [await tallyOfReviewer(ctx, reviewer._id, [way]), tally]; + }); + expect({ reviewer: reviewer.userId, way, ...counted }).toEqual({ reviewer: reviewer.userId, way, ...read }); + } + } + }; + await agree(); + + // Two of Ann's papers go to Ben: only who is on them changes. + await made.as.ann!.mutation(api.screening.reviewers.move, { workspaceId, jobId, from: ann._id, to: ben._id, papers: 2 }); + await agree(); + + // Ben votes on what he has, and the papers are settled on his votes. + const theirs = await t.run(async (ctx) => (await ctx.db.query("screeningVotes").withIndex("by_result").collect()).filter((vote) => vote.reviewerId === ben._id && vote.status === "waiting").map((vote) => vote.resultId as Id<"screeningResults">)); + await made.as.ben!.mutation(api.screening.voting.voteMany, { workspaceId, jobId, paperIds: theirs.slice(0, 2), decision: "include" }); + await made.as.ben!.mutation(api.screening.voting.voteMany, { workspaceId, jobId, paperIds: theirs.slice(2), decision: "exclude", reason: "other" }); + await agree(); + expect(papers).toHaveLength(8); +}); diff --git a/convex/screening/facets.ts b/convex/screening/facets.ts index feb01a8a9..f878ca21f 100644 --- a/convex/screening/facets.ts +++ b/convex/screening/facets.ts @@ -111,7 +111,7 @@ export async function countPaperFacets(ctx: QueueingCtx, change: Change) { const [was, now] = [change.oldDoc, change.newDoc]; - if (was && now && was.status === now.status && was.decision === now.decision && was.at === now.at) return; + if (was && now && was.reviewerId === now.reviewerId && was.status === now.status && was.decision === now.decision && was.at === now.at) return; const paper = await paperOf(ctx, (now ?? was)!.resultId); await move(ctx, voteEntries(was, paper), voteEntries(now, paper)); } diff --git a/convex/screening/settings.ts b/convex/screening/settings.ts index 509933641..12705fc78 100644 --- a/convex/screening/settings.ts +++ b/convex/screening/settings.ts @@ -18,7 +18,7 @@ import { type Criterion } from "../../lib/screening/rules"; import { requireMember } from "./access"; import { pdfBand } from "../../lib/pricing/estimate"; import { bookkeepLater, progressRow, saveQualified } from "./bookkeeping"; -import { keepVersion, keeperOf, readAgain, dealable, settlerFor, modelRow, nameOf, readingModel, reviewersOf, sourcesOf, touched, votesOf } from "./dealing"; +import { keepVersion, keeperOf, readAgain, dealable, papersAStep, settlerFor, modelRow, nameOf, readingModel, reviewersOf, sourcesOf, touched, votesOf } from "./dealing"; import { startCheck } from "./checks"; import { check } from "./living"; import { logChange, type Line } from "./log"; @@ -258,7 +258,7 @@ export const follow = internalMutation({ if (!job || !result) return null; const open = result === "waiting" || result === "conflict"; const reviewers = new Map((await reviewersOf(ctx, jobId)).map((one) => [one._id, one])); - const page = await ctx.db.query("screeningResults").withIndex("by_job_and_result", (q) => q.eq("jobId", jobId).eq("result", result)).paginate({ cursor, numItems: FOLLOW }); + const page = await ctx.db.query("screeningResults").withIndex("by_job_and_result", (q) => q.eq("jobId", jobId).eq("result", result)).paginate({ cursor, numItems: papersAStep(reviewers.size, FOLLOW) }); let queued = 0; for (const paper of page.page) { if (open && (stricter.length || reread)) {