From 5b909204324da2bd20d6b69446687edb59ee14d4 Mon Sep 17 00:00:00 2001 From: sickerine Date: Sat, 28 Nov 2026 08:44:30 +0000 Subject: [PATCH 1/2] fix(convex): a work pool's completion handler writes through the app's triggers From the cross-family review of #1617. `defineOnComplete` builds its handler with Convex's own mutation builder, so its writes skipped every trigger: a model's reading that came back left its vote counted as waiting in the screening counts kept since #1616, and the pool's other completions skipped the cards and list counts the same way. - `withAppWrites` (lib/functions.ts) runs such a handler with the writes the app's builders give a mutation: through the triggers and the caps, its counts queued when it ends. The three completion handlers use it. - A model's vote is cast before the bookkeeping works out its decision: until then it counts as `cast`, so every vote cast is counted. - migrations/screeningFacets:readVotes takes out the waiting counts such readings left, and counts each vote as it stands; `verify` now finds those stale counts too. - facets.test.ts: a model's readings coming back failed or read keep its counts (fails without the wrapper), and the repair takes out what was left (verify 0). --- convex/lib/functions.ts | 24 ++++++-- convex/migrations/screeningFacets.ts | 23 +++++-- convex/screening/facets.test.ts | 90 ++++++++++++++++++++-------- convex/screening/facets.ts | 20 ++++++- convex/screening/files.ts | 7 ++- convex/screening/mutations.ts | 7 ++- convex/screening/readings.ts | 7 ++- 7 files changed, 130 insertions(+), 48 deletions(-) diff --git a/convex/lib/functions.ts b/convex/lib/functions.ts index c04575dae..83f450502 100644 --- a/convex/lib/functions.ts +++ b/convex/lib/functions.ts @@ -20,18 +20,30 @@ export * from "../_generated/server"; * gather are queued once, when the mutation ends (./countQueue.ts). A developer app's call * is checked and put on the person's list of sites first (`recordAppUse`). */ +const appWrites = (ctx: MutationCtx) => { + const countQueue: CountQueue = new Map(); + return { db: triggers.wrapDB({ ...ctx, db: capWrites(ctx.db), countQueue }).db, countQueue }; +}; const writes = { args: {}, input: async (ctx: MutationCtx) => { await recordAppUse(ctx); - const countQueue: CountQueue = new Map(); - return { - ctx: { db: triggers.wrapDB({ ...ctx, db: capWrites(ctx.db), countQueue }).db, countQueue }, - args: {}, - onSuccess: () => flushCountQueue(ctx, countQueue), - }; + const wrapped = appWrites(ctx); + return { ctx: wrapped, args: {}, onSuccess: () => flushCountQueue(ctx, wrapped.countQueue) }; }, }; +/** + * Runs a mutation that another library built, such as a work pool's `defineOnComplete` handler, with the app's + * writes: through the triggers and the caps, its counts queued when it ends. Without it, its writes skip every + * trigger, and what they keep (cards, list counts, the screening counts) falls behind for good. + */ +export async function withAppWrites(ctx: Ctx, run: (ctx: Ctx) => Promise): Promise { + const wrapped = appWrites(ctx); + const result = await run({ ...ctx, ...wrapped }); + await flushCountQueue(ctx, wrapped.countQueue); + return result; +} + export const mutation = customMutation(rawMutation, writes); export const internalMutation = customMutation(rawInternalMutation, writes); diff --git a/convex/migrations/screeningFacets.ts b/convex/migrations/screeningFacets.ts index 2660962a2..75db8e7da 100644 --- a/convex/migrations/screeningFacets.ts +++ b/convex/migrations/screeningFacets.ts @@ -4,7 +4,7 @@ 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"; +import { countEntries, paperEntries, recountVote, screeningCounts, voteEntries } from "../screening/facets"; /** * Counts the papers and votes of every screening with reviewers that predate their counts (screening/facets.ts): each @@ -14,6 +14,8 @@ import { countEntries, paperEntries, screeningCounts, voteEntries } from "../scr * npx convex run migrations/screeningFacets:run '{"dryRun": true}' * npx convex run migrations/screeningFacets:run * npx convex run migrations/screeningFacets:verify + * + * `verify` finds counts missing. `readVotes` takes out the stale ones a model's reading left (#1617). */ const migrations = new Migrations(components.migrations, { internalMutation }); @@ -33,11 +35,20 @@ export const votes = migrations.define({ }, }); -export const run = migrations.runner([internal.migrations.screeningFacets.papers, internal.migrations.screeningFacets.votes]); +/** Votes counted as waiting after a model's reading came back through the pool without the triggers (#1617): counted again as they stand. */ +export const readVotes = migrations.define({ + table: "screeningVotes", + batchSize: 200, + migrateOne: async (ctx, vote) => { + if (vote.status !== "waiting") await recountVote(ctx, vote, await ctx.db.get("screeningResults", vote.resultId)); + }, +}); + +export const run = migrations.runner([internal.migrations.screeningFacets.papers, internal.migrations.screeningFacets.votes, internal.migrations.screeningFacets.readVotes]); const tableValidator = v.union(v.literal("screeningResults"), v.literal("screeningVotes")); -/** Entries one page of `table` should have that the counts don't. */ +/** Entries one page of `table` should have that the counts don't, and waiting entries its votes no longer waiting still have. */ 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() }), @@ -51,11 +62,13 @@ export const verifyPage = internalQuery({ } 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 }; + const stale = page.page.filter((vote) => vote.status !== "waiting").flatMap((vote) => ["include", "maybe", "exclude", "conflict", "waiting"].map((result) => ({ namespace: `${vote.reviewerId}`, key: `waiting|${result}`, id: vote._id }))); + const left = (await screeningCounts.countBatch(ctx, stale.map(({ namespace, key, id }) => ({ namespace, bounds: { lower: { key, id, inclusive: true }, upper: { key, id, inclusive: true } } })) as never, { stale: true })).filter((count) => count > 0).length; + return { missing: (await missing(entries)) + left, isDone: page.isDone, continueCursor: page.continueCursor }; }, }); -/** How many entries `verifyPage` finds missing across both tables; 0 when the backfill is done. */ +/** How many entries `verifyPage` finds missing or stale across both tables; 0 when the counts are right. */ export const verify = internalAction({ args: {}, returns: v.number(), diff --git a/convex/screening/facets.test.ts b/convex/screening/facets.test.ts index 00c281c6c..ddb3e0ff4 100644 --- a/convex/screening/facets.test.ts +++ b/convex/screening/facets.test.ts @@ -1,15 +1,35 @@ // 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 { api, internal } from "../_generated/api"; import type { Id } from "../_generated/dataModel"; -import { tallyOfReviewer, type Way } from "./facets"; -import { runAll, started, team } from "./reviewers.test-support"; +import { recountVote, tallyOfReviewer, type Way } from "./facets"; +import { runUntriggered } from "../../tests/convex-test-with-limits"; +import { runAll, started, team, type Team } from "./reviewers.test-support"; beforeEach(() => vi.useFakeTimers()); afterEach(() => vi.useRealTimers()); -const WAYS: Way[] = ["include", "maybe", "exclude", "waiting", "failed"]; +const WAYS: Way[] = ["include", "maybe", "exclude", "cast", "waiting", "failed"]; + +/** Each way each reviewer stands, counted as the facets count it and as their votes and the cards say it, read whole. */ +async function agree(t: Team["t"], reviewers: Id<"screeningReviewers">[]) { + await runAll(t, vi.runAllTimers); + for (const reviewer of reviewers) { + 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 && (vote.status === "cast" ? (vote.decision ?? "cast") : 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, [way]), tally]; + }); + expect({ reviewer, way, ...counted }).toEqual({ reviewer, way, ...read }); + } + } +} it("keeps a reviewer's counts with the papers moved to them, voted on and settled", async () => { const made = await team(["ann", "ben"]); @@ -19,34 +39,54 @@ it("keeps a reviewer's counts with the papers moved to them, voted on and settle 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(); + const agreed = () => agree(t, [ann._id, ben._id]); + await agreed(); // 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(); + await agreed(); // 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(); + await agreed(); expect(papers).toHaveLength(8); }); + +it("keeps a model's counts as its readings come back from the pool, failed or read", async () => { + const made = await team(["ann"]); + const { t } = made; + const { jobId, papers } = await started(made, ["ann"], 2, { rule: { each: 1, settle: "all", blind: "after" } }); + // A model on both papers, each reading out in the pool. + const model = await t.run(async (ctx) => { + const reviewerId = await ctx.db.insert("screeningReviewers", { jobId, kind: "model", addedAt: 1, addedBy: made.ids.ann!, dealt: 2 }); + for (const [place, paper] of papers.entries()) await ctx.db.insert("screeningVotes", { jobId, resultId: paper._id, reviewerId, place, status: "waiting", workId: `reading ${place}` }); + return reviewerId; + }); + await agree(t, [model]); + // The pool's completion is its own mutation: its writes reach the counts too. + await t.mutation(internal.screening.readings.done, { workId: "reading 0", context: {}, result: { kind: "failed", error: "The model gave no answer" } } as never); + await t.mutation(internal.screening.readings.done, { workId: "reading 1", context: {}, result: { kind: "success", returnValue: { read: true, answers: {}, confidences: {}, credits: 3 } } } as never); + const statuses = await t.run(async (ctx) => (await ctx.db.query("screeningVotes").withIndex("by_reviewer_and_status_and_place").collect()).filter((vote) => vote.reviewerId === model).map((vote) => vote.status).sort()); + expect(statuses).not.toEqual(["waiting", "waiting"]); + await agree(t, [model]); +}); + +it("takes out the waiting count a reading left when it came back without the triggers, and verify finds none left", async () => { + const made = await team(["ann"]); + const { t } = made; + const { jobId, papers } = await started(made, ["ann"], 1, { rule: { each: 1, settle: "all", blind: "after" } }); + const vote = await t.run(async (ctx) => { + const reviewerId = await ctx.db.insert("screeningReviewers", { jobId, kind: "model", addedAt: 1, addedBy: made.ids.ann!, dealt: 1 }); + return { reviewerId, id: await ctx.db.insert("screeningVotes", { jobId, resultId: papers[0]!._id, reviewerId, place: 0, status: "waiting", workId: "reading" }) }; + }); + await runAll(t, vi.runAllTimers); + // As the pool's completion wrote it before it ran with the triggers: cast, and still counted as waiting. + await runUntriggered(t, (ctx) => ctx.db.patch("screeningVotes", vote.id, { status: "cast", decision: "include", at: 5 })); + const wrong = async () => t.query(internal.migrations.screeningFacets.verifyPage, { table: "screeningVotes", cursor: null }); + expect((await wrong()).missing).toBeGreaterThan(0); + await t.run(async (ctx) => recountVote(ctx, (await ctx.db.get("screeningVotes", vote.id))!, await ctx.db.get("screeningResults", papers[0]!._id))); + await agree(t, [vote.reviewerId]); + expect((await wrong()).missing).toBe(0); +}); diff --git a/convex/screening/facets.ts b/convex/screening/facets.ts index f878ca21f..a0be4110b 100644 --- a/convex/screening/facets.ts +++ b/convex/screening/facets.ts @@ -28,8 +28,11 @@ export const screeningCounts = new DirectAggregate<{ Namespace: string; Key: Key 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"; +/** + * How a reviewer stands on a paper: the way they voted, or that they haven't (`waiting`), or that a model couldn't + * (`failed`). A model's vote is cast before the bookkeeping works out its decision: until then it is `cast`. + */ +export type Way = "include" | "maybe" | "exclude" | "cast" | "waiting" | "failed"; const sourceOf = (jobId: Id<"screeningJobs">, sourceId: Id<"screeningSources">) => `${jobId}:source:${sourceId}`; const checkOf = (jobId: Id<"screeningJobs">, checkId: Id<"screeningChecks">) => `${jobId}:check:${checkId}`; @@ -67,7 +70,7 @@ type Vote = Pick, "_id" | "reviewerId" | "status" | "decis /** 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; + const way = vote.status === "cast" ? (vote.decision ?? "cast") : 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 }] : []), @@ -119,6 +122,17 @@ export async function countVoteFacets(ctx: QueueingCtx, change: Change move(ctx, [], entries); +/** + * Takes out what a vote no longer waiting may still be counted as waiting under, and counts it as it stands. A model's + * reading that came back through the pool before its completion ran with the triggers (../lib/functions.ts + * `withAppWrites`) left its vote counted as waiting. + */ +export async function recountVote(ctx: QueueingCtx, vote: Vote, paper: Pick | null) { + if (vote.status === "waiting") return; + await queueCounts(ctx, screeningCounts, RESULTS.map((result) => ({ type: "deleteIfExists" as const, namespace: reviewerOf(vote.reviewerId), key: `waiting|${result}`, id: vote._id }))); + await countEntries(ctx, voteEntries(vote, paper)); +} + 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[]) => diff --git a/convex/screening/files.ts b/convex/screening/files.ts index 84a32e127..45c732867 100644 --- a/convex/screening/files.ts +++ b/convex/screening/files.ts @@ -15,7 +15,7 @@ import { internal } from "../_generated/api"; import type { Doc, Id } from "../_generated/dataModel"; import type { MutationCtx, QueryCtx } from "../_generated/server"; import { createError } from "../lib/errors"; -import { internalMutation, internalQuery } from "../lib/functions"; +import { internalMutation, internalQuery, withAppWrites } from "../lib/functions"; import { countOf, screeningFilesOf, type PdfStanding } from "../lib/listCounts"; import { workspaceMutation, workspaceQuery } from "../lib/userActions"; import { screeningPool } from "../workpool"; @@ -115,9 +115,10 @@ export const landed = internalMutation({ /** The pool's callback for a first reading. The pool's own context has no triggers, so the row is written by `landed`, which keeps the drop's counts. */ export const done = screeningPool.defineOnComplete({ context: v.object({}), - handler: async (ctx, { workId, result }) => { + // Its writes go through the app's triggers, as a mutation built by the app's builders would (../lib/functions.ts). + handler: (raw, { workId, result }) => withAppWrites(raw, async (ctx) => { await ctx.runMutation(internal.screening.files.landed, { workId, read: result.kind === "success" ? (result.returnValue as typeof pdfReadValidator.type) : null }); - }, + }), }); /** How many PDFs a drop holds. */ diff --git a/convex/screening/mutations.ts b/convex/screening/mutations.ts index 884726326..56c0f5351 100644 --- a/convex/screening/mutations.ts +++ b/convex/screening/mutations.ts @@ -1,4 +1,4 @@ -import { internalMutation } from "../lib/functions"; +import { internalMutation, withAppWrites } from "../lib/functions"; import { identityOf } from "../lib/paperRef"; import { paperIdOf, parsePaperKey } from "../../lib/papers/paper-ref"; import { internal } from "../_generated/api"; @@ -490,7 +490,8 @@ export const handleScreeningComplete = screeningPool.defineOnComplete({ resultId: v.optional(v.id("screeningResults")), jobId: v.optional(v.id("screeningJobs")), }), - handler: async (ctx, { workId, result }) => { + // Its writes go through the app's triggers, as a mutation built by the app's builders would (../lib/functions.ts). + handler: (raw, { workId, result }) => withAppWrites(raw, async (ctx) => { const screeningResult = await ctx.db .query("screeningResults") .withIndex("by_workId", (q) => q.eq("workId", workId)) @@ -579,5 +580,5 @@ export const handleScreeningComplete = screeningPool.defineOnComplete({ }); } await bookkeepLater(ctx); - }, + }), }); diff --git a/convex/screening/readings.ts b/convex/screening/readings.ts index c7ea70f88..e94af7f21 100644 --- a/convex/screening/readings.ts +++ b/convex/screening/readings.ts @@ -9,7 +9,7 @@ import { internal } from "../_generated/api"; import type { Doc, Id } from "../_generated/dataModel"; import type { MutationCtx } from "../_generated/server"; import { availableCredits } from "../billing/accounts"; -import { internalMutation, internalQuery } from "../lib/functions"; +import { internalMutation, internalQuery, withAppWrites } from "../lib/functions"; import { screeningPool } from "../workpool"; import { readsPdfs } from "../../lib/assistant/files"; import { effortValidator, longPromptValidator } from "../aiModelConfig/validators"; @@ -80,7 +80,8 @@ const ERROR_SHOWN = 300; */ export const done = screeningPool.defineOnComplete({ context: v.object({}), - handler: async (ctx, { workId, result }) => { + // Its writes go through the app's triggers, as a mutation built by the app's builders would (../lib/functions.ts). + handler: (raw, { workId, result }) => withAppWrites(raw, async (ctx) => { // The pool's callback is typed without the app's tables. const vote = (await ctx.db.query("screeningVotes").withIndex("by_workId", (q) => q.eq("workId", workId)).unique()) as Doc<"screeningVotes"> | null; if (!vote) return; @@ -115,7 +116,7 @@ export const done = screeningPool.defineOnComplete({ } await ctx.db.patch("screeningResults", vote.resultId, { doneAt: ctx.db.vars.commitTs }); await bookkeepLater(ctx); - }, + }), }); /** Rows one step of a sweep over a screening's readings handles. */ From 8e4b7ecefb6a82b493b798ffc08989dbc4ab20ea Mon Sep 17 00:00:00 2001 From: sickerine Date: Sat, 28 Nov 2026 08:51:31 +0000 Subject: [PATCH 2/2] fix(screening): the repair takes out every stale waiting count, on votes that have waited again too From the cross-family review of #1618: a vote left counted as waiting can wait again later (a new criterion asks the model to read its paper once more), by when its paper may stand elsewhere, and then it counts twice. The repair and verify skipped waiting votes. Both now look at every vote, and keep only the waiting count it should have. --- convex/migrations/screeningFacets.ts | 11 ++++++----- convex/screening/facets.test.ts | 22 ++++++++++++++++++++++ convex/screening/facets.ts | 15 ++++++++++----- 3 files changed, 38 insertions(+), 10 deletions(-) diff --git a/convex/migrations/screeningFacets.ts b/convex/migrations/screeningFacets.ts index 75db8e7da..50d4e5361 100644 --- a/convex/migrations/screeningFacets.ts +++ b/convex/migrations/screeningFacets.ts @@ -4,7 +4,7 @@ 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, recountVote, screeningCounts, voteEntries } from "../screening/facets"; +import { countEntries, paperEntries, recountVote, screeningCounts, staleWaiting, voteEntries } from "../screening/facets"; /** * Counts the papers and votes of every screening with reviewers that predate their counts (screening/facets.ts): each @@ -35,12 +35,12 @@ export const votes = migrations.define({ }, }); -/** Votes counted as waiting after a model's reading came back through the pool without the triggers (#1617): counted again as they stand. */ +/** Votes left counted as waiting by a model's reading that came back through the pool without the triggers (#1618), whatever they have done since: counted again as they stand. */ export const readVotes = migrations.define({ table: "screeningVotes", batchSize: 200, migrateOne: async (ctx, vote) => { - if (vote.status !== "waiting") await recountVote(ctx, vote, await ctx.db.get("screeningResults", vote.resultId)); + await recountVote(ctx, vote, await ctx.db.get("screeningResults", vote.resultId)); }, }); @@ -61,8 +61,9 @@ export const verifyPage = internalQuery({ 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(); - const stale = page.page.filter((vote) => vote.status !== "waiting").flatMap((vote) => ["include", "maybe", "exclude", "conflict", "waiting"].map((result) => ({ namespace: `${vote.reviewerId}`, key: `waiting|${result}`, id: vote._id }))); + const read = await Promise.all(page.page.map(async (vote) => ({ vote, paper: await ctx.db.get("screeningResults", vote.resultId) }))); + const entries = read.flatMap(({ vote, paper }) => voteEntries(vote, paper)); + const stale = read.flatMap(({ vote, paper }) => staleWaiting(vote, paper)); const left = (await screeningCounts.countBatch(ctx, stale.map(({ namespace, key, id }) => ({ namespace, bounds: { lower: { key, id, inclusive: true }, upper: { key, id, inclusive: true } } })) as never, { stale: true })).filter((count) => count > 0).length; return { missing: (await missing(entries)) + left, isDone: page.isDone, continueCursor: page.continueCursor }; }, diff --git a/convex/screening/facets.test.ts b/convex/screening/facets.test.ts index ddb3e0ff4..232aff380 100644 --- a/convex/screening/facets.test.ts +++ b/convex/screening/facets.test.ts @@ -90,3 +90,25 @@ it("takes out the waiting count a reading left when it came back without the tri await agree(t, [vote.reviewerId]); expect((await wrong()).missing).toBe(0); }); + +it("takes out the waiting count a reading left on a vote that has waited again since, under where its paper stands now", async () => { + const made = await team(["ann"]); + const { t } = made; + const { jobId, papers } = await started(made, ["ann"], 1, { rule: { each: 1, settle: "all", blind: "after" } }); + const paperId = papers[0]!._id; + const vote = await t.run(async (ctx) => { + const reviewerId = await ctx.db.insert("screeningReviewers", { jobId, kind: "model", addedAt: 1, addedBy: made.ids.ann!, dealt: 1 }); + return { reviewerId, id: await ctx.db.insert("screeningVotes", { jobId, resultId: paperId, reviewerId, place: 0, status: "waiting", workId: "reading" }) }; + }); + await runAll(t, vi.runAllTimers); + // Cast without the triggers, as the pool wrote it; its paper then goes into conflict, and a new criterion asks the model to read it again. + await runUntriggered(t, (ctx) => ctx.db.patch("screeningVotes", vote.id, { status: "cast", at: 5 })); + await t.run((ctx) => ctx.db.patch("screeningResults", paperId, { result: "conflict" })); + await t.run((ctx) => ctx.db.patch("screeningVotes", vote.id, { status: "waiting", at: undefined })); + await runAll(t, vi.runAllTimers); + const wrong = async () => (await t.query(internal.migrations.screeningFacets.verifyPage, { table: "screeningVotes", cursor: null })).missing; + expect(await wrong()).toBeGreaterThan(0); + await t.run(async (ctx) => recountVote(ctx, (await ctx.db.get("screeningVotes", vote.id))!, await ctx.db.get("screeningResults", paperId))); + await agree(t, [vote.reviewerId]); + expect(await wrong()).toBe(0); +}); diff --git a/convex/screening/facets.ts b/convex/screening/facets.ts index a0be4110b..e6f556b8f 100644 --- a/convex/screening/facets.ts +++ b/convex/screening/facets.ts @@ -123,13 +123,18 @@ export async function countVoteFacets(ctx: QueueingCtx, change: Change move(ctx, [], entries); /** - * Takes out what a vote no longer waiting may still be counted as waiting under, and counts it as it stands. A model's - * reading that came back through the pool before its completion ran with the triggers (../lib/functions.ts - * `withAppWrites`) left its vote counted as waiting. + * The waiting entries a vote has that it shouldn't: a model's reading that came back through the pool before its + * completion ran with the triggers (../lib/functions.ts `withAppWrites`) left its vote counted as waiting, under where + * its paper stood then, whatever the vote has done since, waited again included. */ +export const staleWaiting = (vote: Vote, paper: Pick | null): Entry[] => { + const kept = voteEntries(vote, paper).find((entry) => entry.namespace === reviewerOf(vote.reviewerId))?.key; + return RESULTS.map((result) => `waiting|${result}`).filter((key) => key !== kept).map((key) => ({ namespace: reviewerOf(vote.reviewerId), key, id: vote._id })); +}; + +/** Takes out a vote's stale waiting entries, and counts it as it stands. */ export async function recountVote(ctx: QueueingCtx, vote: Vote, paper: Pick | null) { - if (vote.status === "waiting") return; - await queueCounts(ctx, screeningCounts, RESULTS.map((result) => ({ type: "deleteIfExists" as const, namespace: reviewerOf(vote.reviewerId), key: `waiting|${result}`, id: vote._id }))); + await queueCounts(ctx, screeningCounts, staleWaiting(vote, paper).map((entry) => ({ type: "deleteIfExists" as const, ...entry }))); await countEntries(ctx, voteEntries(vote, paper)); }