From 2b55a8686c8b2e34030c2a70707fced43ec33637 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Tue, 3 Nov 2026 06:09:39 +0000 Subject: [PATCH] Duplicate groups: review fixes (undo and re-answer, settled members, drops, retries, growth, atomic refresh) --- src/dash/api/decisions.ts | 2 + src/decide/select.ts | 2 +- src/decisions.ts | 8 +- src/dupes/compare.ts | 26 ++++-- src/dupes/decide.ts | 135 ++++++++++++++++++++--------- src/dupes/plan.ts | 52 +++++++++-- src/schema.sql | 3 + test/dupe-groups.test.ts | 178 +++++++++++++++++++++++++++++++++++++- 8 files changed, 339 insertions(+), 67 deletions(-) diff --git a/src/dash/api/decisions.ts b/src/dash/api/decisions.ts index 24faac42..0826e277 100644 --- a/src/dash/api/decisions.ts +++ b/src/dash/api/decisions.ts @@ -6,6 +6,7 @@ import type { DatabaseSync } from "node:sqlite"; import type { Claim, Classification, Decision, DecisionComment, DecisionKind, DecisionList, ItemState, Opinion, RelatedItem, Relation, } from "../../../web/src/api/types.ts"; +import { resetGroupAnswer } from "../../dupes/decide.ts"; import { exceptionsOf, factsOf, getDecision, isBatch, itemsOf, KINDS, optionsOf, reposOf, type DecisionRow, type Exception } from "../../decisions.ts"; import { commentPreview, writeEffect } from "../../act/index.ts"; import { audit } from "../audit.ts"; @@ -310,6 +311,7 @@ export async function undo(db: DatabaseSync, req: Req): Promise { const r = db.prepare(`UPDATE main.decisions SET answer = NULL, answer_note = NULL, exceptions = NULL, answered_by = NULL, answered_at = NULL, adopted_opinion = NULL WHERE id = ? AND answer IS NOT NULL AND applied_at IS NULL`).run(d.id); if (r.changes !== 1) throw new HttpError(409, "the pipeline acted on this a moment ago"); + resetGroupAnswer(db, d.id); audit(db, req.user.login, "undo", d.id, { answer: d.answer, adopted: d.adopted_opinion ?? undefined }); return toDecision(db, getDecision(db, d.id)!, viewerOf(req)); } diff --git a/src/decide/select.ts b/src/decide/select.ts index 3363e72d..bb214a1c 100644 --- a/src/decide/select.ts +++ b/src/decide/select.ts @@ -38,7 +38,7 @@ export function reasonOf(s: Settled): Reason | null { /** Refs ("repo#n") that already have a decision or a stage past classification. */ function covered(db: DatabaseSync): Set { const out = new Set(); - const rows = db.prepare(`SELECT repo, number, items FROM decisions WHERE answer IS NULL OR kind = 'scope'`).all() as + const rows = db.prepare(`SELECT repo, number, items FROM decisions WHERE (answer IS NULL OR kind = 'scope') AND id NOT LIKE '%:dupegroup:%'`).all() as { repo: string | null; number: number | null; items: string | null }[]; for (const d of rows) { if (d.number !== null) out.add(`${d.repo}#${d.number}`); diff --git a/src/decisions.ts b/src/decisions.ts index 87979ac9..fd011807 100644 --- a/src/decisions.ts +++ b/src/decisions.ts @@ -79,22 +79,22 @@ export function validateAsk(q: Record): Record[]): { inserted: number; updated: number } { +export function ask(db: DatabaseSync, questions: Record[], inTransaction = false): { inserted: number; updated: number } { const rows = questions.map(validateAsk); const cols = ["id", ...ASK_FIELDS]; const stmt = db.prepare(`INSERT INTO decisions (${cols.join(",")}) VALUES (${cols.map((c) => `:${c}`).join(",")}) ON CONFLICT(id) DO UPDATE SET ${ASK_FIELDS.map((c) => SUMMARY_FIELDS.includes(c) ? `${c} = COALESCE(excluded.${c}, ${c})` : `${c} = excluded.${c}`).join(", ")}`); const exists = db.prepare("SELECT 1 FROM decisions WHERE id = ?"); let inserted = 0, updated = 0; - db.exec("BEGIN"); + if (!inTransaction) db.exec("BEGIN"); try { for (const r of rows) { if (exists.get(r.id as string)) updated++; else inserted++; stmt.run(r); } - db.exec("COMMIT"); + if (!inTransaction) db.exec("COMMIT"); } catch (e) { - db.exec("ROLLBACK"); + if (!inTransaction) db.exec("ROLLBACK"); throw e; } return { inserted, updated }; diff --git a/src/dupes/compare.ts b/src/dupes/compare.ts index c6d50b51..d1386df1 100644 --- a/src/dupes/compare.ts +++ b/src/dupes/compare.ts @@ -21,7 +21,7 @@ import { GROUP_DIFF_CHARS, GROUP_MAX, parseIssueComparison, parsePrComparison, prsRef, type CompareIssue, type CompareIssues, type ComparePr, type ComparePrs, } from "./group.ts"; -import { dueSets, saveComparison, type ComparisonResult, type KindSet, type StoredComparison } from "./plan.ts"; +import { dueSets, rememberDrop, saveComparison, storedComparison, type ComparisonResult, type KindSet, type StoredComparison } from "./plan.ts"; const PR_PROMPT = CLAUDE_PROMPTS["dupes.compare-prs.opus"]; const ISSUE_PROMPT = CLAUDE_PROMPTS["dupes.compare-issues.sonnet"]; @@ -86,7 +86,7 @@ function viaRule(db: DatabaseSync, s: KindSet, at: string, error: string | null, const c = pickCanonical(db, s.repo, numbers); const others = numbers.filter((n) => n !== c.number).map((number) => (s.kind === "pr" ? { number, duplicate: true, better: [], carry: [] } : { number, adds: [] })); const reason = source === "closed" ? c.why : source === "single" ? "the only one" : `kept by rule: ${c.why}`; - return { repo: s.repo, key: s.key, kind: s.kind, members: numbers, hash: s.hash, kept: c.number, source, model: null, reason, result: { others, rounds: 0 }, error, at }; + return { repo: s.repo, key: s.key, kind: s.kind, members: numbers, hash: s.hash, kept: c.number, source, model: null, reason, result: { others, rounds: 0 }, error, attempts: 0, at }; } type Ctx = { db: DatabaseSync; deps: CompareDeps; log: (l: string) => void; checkouts: Map>; runId: string }; @@ -178,9 +178,10 @@ async function compareSet(x: Ctx, s: KindSet): Promise { const lost = new Map(); let rounds = 0, last: Chunk | null = null; for (;;) { - const chunks: number[][] = []; - if (current.length <= GROUP_MAX) chunks.push(current); - else for (let i = 0; i < current.length; i += GROUP_MAX) chunks.push(current.slice(i, i + GROUP_MAX)); + // Dealt round-robin, so every chunk holds a mix of strong and weak members. + const count = Math.ceil(current.length / GROUP_MAX); + const chunks: number[][] = Array.from({ length: count }, () => []); + current.forEach((n, i) => chunks[i % count]!.push(n)); const winners: number[] = []; for (const chunk of chunks) { if (chunk.length === 1) { winners.push(chunk[0]!); continue; } @@ -205,7 +206,7 @@ async function compareSet(x: Ctx, s: KindSet): Promise { }); return { repo: s.repo, key: s.key, kind: s.kind, members: s.members.map((m) => m.number), hash: s.hash, kept, source: "model", model: usage.model, - reason: last?.reason ?? null, result: { others, rounds }, error: null, at, + reason: last?.reason ?? null, result: { others, rounds }, error: null, attempts: 0, at, }; } @@ -213,7 +214,7 @@ export async function runDupeCompare(db: DatabaseSync, params: CompareParams = { if (params.limit !== undefined && !(Number.isInteger(params.limit) && params.limit >= 0)) throw new Error("limit must be a whole number ≥ 0"); const d = deps ?? defaultCompareDeps(db); const s: CompareSummary = { due: 0, compared: 0, byRule: 0, closedWins: 0, single: 0, dropped: 0, asked: [], dryRun: !!params.dryRun }; - const sets = dueSets(db, params.repo); + const sets = dueSets(db, params.repo, d.now().getTime()); s.due = sets.length; if (params.dryRun) { log(`dupe-compare: ${sets.length} sets to compare; dry run, nothing written`); @@ -232,7 +233,6 @@ export async function runDupeCompare(db: DatabaseSync, params: CompareParams = { s.single++; } else calls.push(set); } - if (params.limit !== undefined) calls = calls.slice(0, params.limit); if (d.querier && calls.length) { // The mirror can be minutes behind: a set with a member closed or pushed since is compared on a later pass. const live = new Map>(); @@ -246,14 +246,22 @@ export async function runDupeCompare(db: DatabaseSync, params: CompareParams = { calls = calls.filter((c) => { const l = live.get(c.repo)!; const bad = c.members.find((m) => { const v = l.get(m.number); return !v || v.state !== m.state || (m.kind === "pr" && v.head !== m.head_oid); }); - if (bad) log(` ${c.repo}#${bad.number}: dropped from ${c.key}, it changed on GitHub since the last sync`); + if (bad) { + log(` ${c.repo}#${bad.number}: dropped from ${c.key}, it changed on GitHub since the last sync`); + rememberDrop(db, c, NOW_ISO(d)); + } return !bad; }); s.dropped = asked - calls.length; } + if (params.limit !== undefined) calls = calls.slice(0, params.limit); let handled = 0; await pool(calls.map((set) => async () => { const r = await compareSet(x, set); + if (r.source === "rule") { + const prev = storedComparison(db, set.repo, set.key); + r.attempts = (prev && prev.source === "rule" && prev.hash === set.hash ? prev.attempts : 0) + 1; + } saveComparison(db, r); if (r.source === "rule") { s.byRule++; diff --git a/src/dupes/decide.ts b/src/dupes/decide.ts index 5da96195..b5a6305e 100644 --- a/src/dupes/decide.ts +++ b/src/dupes/decide.ts @@ -25,15 +25,28 @@ type Role = "keep" | "close" | "stay"; export type PlanItem = { number: number; kind: "pr" | "issue"; role: Role; target: number | null; detail: Record | null }; export type GroupPlan = { repo: string; group: Group; baseId: string; number: number; items: PlanItem[]; - source: "model" | "closed" | "rule"; model: string | null; reasons: string[]; + closing: boolean; source: "model" | "closed" | "rule"; model: string | null; reasons: string[]; sets: { set: KindSet; cmp: StoredComparison }[]; }; const list = (ns: number[]) => ns.map((n) => `#${n}`).join(", "); -/** Plans for the groups whose comparisons are all current. Groups with nothing to close have no plan. */ +/** An earlier answered group decision of the members: its members are settled and its keep stays kept. */ +function answeredKeeps(db: DatabaseSync, repo: string, members: number[]): { settled: Set; keep: Map } { + const ph = members.map(() => "?").join(","); + const ids = db.prepare(`SELECT DISTINCT d.id FROM decisions d JOIN dupe_group_items gi ON gi.decision_id = d.id + WHERE d.kind = 'duplicate' AND d.answer IS NOT NULL AND d.answer NOT IN ('superseded', 'distinct') AND gi.repo = ? AND gi.number IN (${ph}) ORDER BY d.asked_at, d.id`).all(repo, ...members) as { id: string }[]; + const settled = new Set(), keep = new Map(); + for (const { id } of ids) + for (const r of db.prepare("SELECT number, kind, role FROM dupe_group_items WHERE decision_id = ?").all(id) as { number: number; kind: string; role: string }[]) { + settled.add(r.number); + if (r.role === "keep") keep.set(r.kind, r.number); + } + return { settled, keep }; +} + +/** Plans for the groups whose comparisons are all current. `closing` is false for a group with nothing to close. */ export function groupPlans(db: DatabaseSync, repo?: string): GroupPlan[] { - const closing = db.prepare(`SELECT 1 FROM decisions WHERE kind = 'duplicate' AND repo = ? AND number = ? AND id LIKE '%:duplicate@%' AND answer = 'close'`); const out: GroupPlan[] = []; for (const g of duplicateGroups(db, repo)) { const sets = kindSetsOf(db, g).filter((s) => s.members.some((m) => m.state === "OPEN" && inPilot(db, s.repo, m.number))); @@ -41,26 +54,31 @@ export function groupPlans(db: DatabaseSync, repo?: string): GroupPlan[] { const ready = sets.map((set) => ({ set, cmp: currentComparison(db, set) })); if (ready.some((r) => !r.cmp)) continue; const full = ready as { set: KindSet; cmp: StoredComparison }[]; + const { settled, keep: fixedKeep } = answeredKeeps(db, g.repo, g.members); const items: PlanItem[] = []; for (const { set, cmp } of full) { + const numbers = set.members.map((m) => m.number); + // An answered decision's keep stays kept; only members it did not cover are asked against it. + const fixed = fixedKeep.get(set.kind); + const kept = fixed !== undefined && numbers.includes(fixed) ? fixed : cmp.kept; for (const m of set.members) { - if (m.number === cmp.kept) { items.push({ number: m.number, kind: set.kind, role: "keep", target: null, detail: null }); continue; } + if (m.number === kept) { items.push({ number: m.number, kind: set.kind, role: "keep", target: null, detail: null }); continue; } + if (settled.has(m.number)) continue; const other = cmp.result?.others.find((o) => o.number === m.number); - // Answered pair decisions keep their effect: the act step closes those. - if (closing.get(set.repo, m.number)) continue; const dup = set.kind === "issue" || other?.duplicate !== false; const role: Role = m.state === "OPEN" && dup && inPilot(db, set.repo, m.number) ? "close" : "stay"; - items.push({ number: m.number, kind: set.kind, role, target: role === "close" ? cmp.kept : null, detail: other ? { ...other } : null }); + items.push({ number: m.number, kind: set.kind, role, target: role === "close" ? kept : null, detail: other ? { ...other } : null }); } } // The kept PR is linked to the kept issue. const keepPr = items.find((i) => i.role === "keep" && i.kind === "pr"), keepIssue = items.find((i) => i.role === "keep" && i.kind === "issue"); if (keepPr && keepIssue) keepPr.detail = { ...(keepPr.detail ?? {}), link: keepIssue.number }; - if (!items.some((i) => i.role === "close")) continue; const primary = (keepPr ?? keepIssue)!; const sources = full.map((f) => f.cmp.source); + const fresh = items.filter((i) => !settled.has(i.number)).map((i) => i.number); out.push({ - repo: g.repo, group: g, baseId: groupId(g.repo, g.members[0]!), number: primary.number, items, + repo: g.repo, group: g, baseId: groupId(g.repo, Math.min(...(fresh.length ? fresh : items.map((i) => i.number)))), number: primary.number, items, + closing: items.some((i) => i.role === "close"), source: sources.includes("rule") ? "rule" : sources.every((s) => s === "closed" || s === "single") ? "closed" : "model", model: full.find((f) => f.cmp.model)?.cmp.model ?? null, reasons: full.map((f) => f.cmp.reason).filter((r): r is string => !!r), sets: full, }); @@ -79,16 +97,15 @@ function supersede(db: DatabaseSync, p: GroupPlan, id: string, at: string): void } } -/** The decision id for the plan: the base id, or the first later one that is open or does not yet cover every item to close (an answered decision covers every member it listed, whatever the operator kept). Null: an answered decision already covers them. */ -function idFor(db: DatabaseSync, p: GroupPlan): string | null { - const closing = p.items.filter((i) => i.role === "close").map((i) => i.number); +/** The open group decision that already lists one of the plan's members, else the first unused id. */ +function idFor(db: DatabaseSync, p: GroupPlan): string { + const ph = p.group.members.map(() => "?").join(","); + const open = db.prepare(`SELECT d.id FROM decisions d JOIN dupe_group_items gi ON gi.decision_id = d.id + WHERE d.kind = 'duplicate' AND d.answer IS NULL AND d.id LIKE '%:dupegroup:%' AND gi.repo = ? AND gi.number IN (${ph}) ORDER BY d.id LIMIT 1`).get(p.repo, ...p.group.members) as { id: string } | undefined; + if (open) return open.id; for (let k = 1; ; k++) { const id = k === 1 ? p.baseId : `${p.baseId}~${k}`; - const d = getDecision(db, id); - if (!d || !d.answer) return id; - if (d.answer === "superseded" || d.answer === "distinct") continue; - const covered = new Set((db.prepare("SELECT number FROM dupe_group_items WHERE decision_id = ?").all(id) as { number: number }[]).map((r) => r.number)); - if (closing.every((n) => covered.has(n))) return null; + if (!getDecision(db, id)) return id; } } @@ -129,27 +146,40 @@ function textOf(db: DatabaseSync, p: GroupPlan) { return { facts: facts.slice(0, 5), question, context, summary: summary.join(" ") }; } -/** Asks (or refreshes) the group decisions of one repo (every repo when omitted). Returns the ids asked or refreshed. */ +/** Asks (or refreshes) the group decisions of one repo (every repo when omitted). Returns the ids asked or refreshed. Each plan is written in one transaction, so no other process sees its members unheld in between. */ export function askGroupDecisions(db: DatabaseSync, repo: string | undefined, at: string): string[] { const asked: string[] = []; for (const p of groupPlans(db, repo)) { - const id = idFor(db, p); - if (!id) continue; - const t = textOf(db, p); - const primary = p.items.find((i) => i.number === p.number)!; - const alts = canonInfo(db, p.repo, p.items.filter((i) => i.kind === primary.kind && i.number !== p.number && i.role !== "stay").map((i) => i.number)).sort(compareCanonical).slice(0, 3); - ask(db, [{ - id, kind: "duplicate", repo: p.repo, number: p.number, question: t.question, context: t.context, facts: t.facts, - options: [GROUP_OPTIONS.accept, ...alts.map((a) => ({ key: keepKey(a.number), label: `Keep #${a.number} instead`, hint: `Close the others, and #${p.number}, as duplicates of #${a.number}.` })), GROUP_OPTIONS.distinct], - recommended: p.source === "rule" ? null : "accept", - asked_by: ACTOR, asked_at: at, summary: t.summary, summary_by: p.source === "rule" ? "rule" : p.model ?? "rule", summary_at: at, - }]); - supersede(db, p, id, at); - db.prepare("INSERT INTO dupe_groups (decision_id, repo, source) VALUES (?, ?, ?) ON CONFLICT(decision_id) DO UPDATE SET source = excluded.source").run(id, p.repo, p.source); - db.prepare("DELETE FROM dupe_group_items WHERE decision_id = ?").run(id); - const ins = db.prepare("INSERT INTO dupe_group_items (decision_id, repo, number, kind, role, target, detail) VALUES (?, ?, ?, ?, ?, ?, ?)"); - for (const i of p.items) ins.run(id, p.repo, i.number, i.kind, i.role, i.target, i.detail ? JSON.stringify(i.detail) : null); - asked.push(id); + db.exec("BEGIN IMMEDIATE"); + try { + if (!p.closing) { + // Nothing to close: the pair decisions and an open group decision about these members have no use. + supersede(db, p, "", at); + db.exec("COMMIT"); + continue; + } + const id = idFor(db, p); + const t = textOf(db, p); + const primary = p.items.find((i) => i.number === p.number)!; + const alts = canonInfo(db, p.repo, p.items.filter((i) => i.kind === primary.kind && i.number !== p.number && i.role !== "stay").map((i) => i.number)).sort(compareCanonical).slice(0, 3); + ask(db, [{ + id, kind: "duplicate", repo: p.repo, number: p.number, question: t.question, context: t.context, facts: t.facts, + options: [GROUP_OPTIONS.accept, ...alts.map((a) => ({ key: keepKey(a.number), label: `Keep #${a.number} instead`, hint: `Close the others, and #${p.number}, as duplicates of #${a.number}.` })), GROUP_OPTIONS.distinct], + recommended: p.source === "rule" ? null : "accept", + asked_by: ACTOR, asked_at: at, summary: t.summary, summary_by: p.source === "rule" ? "rule" : p.model ?? "rule", summary_at: at, + }], true); + supersede(db, p, id, at); + // A refresh restores the comparison's roles; an answer is applied to them again. + db.prepare("INSERT INTO dupe_groups (decision_id, repo, source) VALUES (?, ?, ?) ON CONFLICT(decision_id) DO UPDATE SET source = excluded.source, applied_answer = NULL").run(id, p.repo, p.source); + db.prepare("DELETE FROM dupe_group_items WHERE decision_id = ?").run(id); + const ins = db.prepare("INSERT INTO dupe_group_items (decision_id, repo, number, kind, role, target, detail, base_role, base_target) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"); + for (const i of p.items) ins.run(id, p.repo, i.number, i.kind, i.role, i.target, i.detail ? JSON.stringify(i.detail) : null, i.role, i.target); + db.exec("COMMIT"); + asked.push(id); + } catch (e) { + db.exec("ROLLBACK"); + throw e; + } } return asked; } @@ -159,15 +189,15 @@ export const askDuplicateDecisions = (db: DatabaseSync, repo: string | undefined /** Groups whose plan has no decision yet. Reads only, for the autopilot. */ export function groupsToAsk(db: DatabaseSync, repo?: string): GroupPlan[] { - return groupPlans(db, repo).filter((p) => idFor(db, p) !== null && !getDecision(db, idFor(db, p)!)); + return groupPlans(db, repo).filter((p) => p.closing && !getDecision(db, idFor(db, p))); } /** Answers to apply: pair decisions answered other than close, and group decisions whose answer is not yet in the roles. */ export function answersToApply(db: DatabaseSync): boolean { return !!db.prepare(`SELECT 1 FROM decisions d WHERE d.kind = 'duplicate' AND d.answer IS NOT NULL AND d.applied_at IS NULL - AND d.answered_by IN (SELECT login FROM access WHERE role = 'operator') AND ${pilotSqlFor("d.repo", "d.number")} - AND ((d.id NOT LIKE '%:dupegroup:%' AND d.answer <> 'close') - OR (d.id LIKE '%:dupegroup:%' AND COALESCE((SELECT g.applied_answer FROM dupe_groups g WHERE g.decision_id = d.id), '') <> d.answer)) LIMIT 1`).get(); + AND d.answered_by IN (SELECT login FROM access WHERE role = 'operator') + AND ((d.id NOT LIKE '%:dupegroup:%' AND d.answer <> 'close' AND ${pilotSqlFor("d.repo", "d.number")}) + OR (d.id LIKE '%:dupegroup:%' AND EXISTS (SELECT 1 FROM dupe_group_items gi WHERE gi.decision_id = d.id AND ${pilotSqlFor("gi.repo", "gi.number")}) AND COALESCE((SELECT g.applied_answer FROM dupe_groups g WHERE g.decision_id = d.id), '') <> d.answer)) LIMIT 1`).get(); } function markDistinct(db: DatabaseSync, repo: string, numbers: number[], at: string): void { @@ -183,11 +213,29 @@ function markDistinct(db: DatabaseSync, repo: string, numbers: number[], at: str } } -/** Writes the roles an answer of "keep #N instead" implies: N is kept, the other items of its kind that were kept or closing now close. */ -function rekeep(db: DatabaseSync, id: string, n: number): void { +/** Back to the comparison's roles; the next answer is applied to them. */ +function restoreRoles(db: DatabaseSync, id: string): void { + db.prepare("UPDATE dupe_group_items SET role = base_role, target = base_target WHERE decision_id = ?").run(id); +} + +/** An undone answer leaves nothing of it in the roles. */ +export function resetGroupAnswer(db: DatabaseSync, id: string): void { + if (!id.includes(":dupegroup:")) return; + restoreRoles(db, id); + db.prepare("UPDATE dupe_groups SET applied_answer = NULL WHERE decision_id = ?").run(id); +} + +/** Writes the roles an answer of "keep #N instead" implies: N is kept; the kept item it replaces closes when it is open and in the pilot, else stays. */ +function rekeep(db: DatabaseSync, id: string, n: number, repo: string): void { + restoreRoles(db, id); const row = db.prepare("SELECT kind FROM dupe_group_items WHERE decision_id = ? AND number = ?").get(id, n) as { kind: string } | undefined; if (!row) return; - db.prepare("UPDATE dupe_group_items SET role = 'close', target = ? WHERE decision_id = ? AND kind = ? AND number <> ? AND role IN ('keep', 'close')").run(n, id, row.kind, n); + const old = db.prepare("SELECT gi.number, i.state FROM dupe_group_items gi JOIN items i ON i.repo = gi.repo AND i.number = gi.number WHERE gi.decision_id = ? AND gi.kind = ? AND gi.role = 'keep' AND gi.number <> ?").all(id, row.kind, n) as { number: number; state: string }[]; + for (const o of old) { + const closes = o.state === "OPEN" && inPilot(db, repo, o.number); + db.prepare("UPDATE dupe_group_items SET role = ?, target = ? WHERE decision_id = ? AND number = ?").run(closes ? "close" : "stay", closes ? n : null, id, o.number); + } + db.prepare("UPDATE dupe_group_items SET target = ? WHERE decision_id = ? AND kind = ? AND role = 'close' AND number <> ?").run(n, id, row.kind, n); db.prepare("UPDATE dupe_group_items SET role = 'keep', target = NULL WHERE decision_id = ? AND number = ?").run(id, n); } @@ -203,12 +251,13 @@ export function applyDuplicateAnswers(db: DatabaseSync, at: string): number { if (a.id.includes(":dupegroup:")) { const g = db.prepare("SELECT applied_answer FROM dupe_groups WHERE decision_id = ?").get(a.id) as { applied_answer: string | null } | undefined; if (!g || g.applied_answer === a.answer) continue; + restoreRoles(db, a.id); const members = (db.prepare("SELECT number FROM dupe_group_items WHERE decision_id = ?").all(a.id) as { number: number }[]).map((r) => r.number); const kept = keptOf(a.answer); if (a.answer === "distinct") { markDistinct(db, a.repo, members, at); db.prepare("UPDATE decisions SET applied_at = ? WHERE id = ? AND applied_at IS NULL").run(at, a.id); - } else if (kept !== null) rekeep(db, a.id, kept); + } else if (kept !== null) rekeep(db, a.id, kept, a.repo); db.prepare("UPDATE dupe_groups SET applied_answer = ? WHERE decision_id = ?").run(a.answer, a.id); audit(db, ACTOR, "duplicate-answer", `${a.repo}#${a.number}`, { decision: a.id, answer: a.answer }); n++; diff --git a/src/dupes/plan.ts b/src/dupes/plan.ts index 8e758948..0baf1180 100644 --- a/src/dupes/plan.ts +++ b/src/dupes/plan.ts @@ -57,7 +57,15 @@ export function setHash(members: Member[]): string { export function kindSetsOf(db: DatabaseSync, g: Group): KindSet[] { const get = db.prepare("SELECT number, kind, state, title, head_oid, embed_hash, comments_count FROM items WHERE repo = ? AND number = ?"); - const members = g.members.map((n) => get.get(g.repo, n) as Member | undefined).filter((m): m is Member => !!m); + // Left out: a rejected (closed, unmerged) PR; an item already closed as a duplicate, or whose pair decision is answered close (the act step closes it). + const gone = db.prepare(`SELECT 1 FROM decisions WHERE kind = 'duplicate' AND repo = ? AND number = ? AND id LIKE '%:duplicate@%' AND answer = 'close'`); + const reason = db.prepare("SELECT state_reason FROM items WHERE repo = ? AND number = ?"); + const members = g.members.map((n) => get.get(g.repo, n) as Member | undefined).filter((m): m is Member => { + if (!m) return false; + if (m.kind === "pr" && m.state === "CLOSED") return false; + if (gone.get(g.repo, m.number)) return false; + return (reason.get(g.repo, m.number) as { state_reason: string | null }).state_reason !== "DUPLICATE"; + }); return (["pr", "issue"] as const).flatMap((kind) => { const ms = members.filter((m) => m.kind === kind); return ms.length ? [{ repo: g.repo, kind, key: setKey(kind, ms.map((m) => m.number)), members: ms, hash: setHash(ms) }] : []; @@ -66,7 +74,7 @@ export function kindSetsOf(db: DatabaseSync, g: Group): KindSet[] { export type StoredComparison = { repo: string; key: string; kind: Kind; members: number[]; hash: string; kept: number; source: "model" | "closed" | "rule" | "single"; - model: string | null; reason: string | null; result: ComparisonResult | null; error: string | null; at: string; + model: string | null; reason: string | null; result: ComparisonResult | null; error: string | null; attempts: number; at: string; }; /** The per-member answers of a comparison, in the shape of the prompt replies. */ export type ComparisonResult = { @@ -84,8 +92,8 @@ export function storedComparison(db: DatabaseSync, repo: string, key: string): S } export function saveComparison(db: DatabaseSync, c: StoredComparison): void { - db.prepare(`INSERT OR REPLACE INTO dupe_comparisons (repo, key, kind, members, hash, kept, source, model, reason, result, error, at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(c.repo, c.key, c.kind, JSON.stringify(c.members), c.hash, c.kept, c.source, c.model, c.reason, c.result ? JSON.stringify(c.result) : null, c.error, c.at); + db.prepare(`INSERT OR REPLACE INTO dupe_comparisons (repo, key, kind, members, hash, kept, source, model, reason, result, error, attempts, at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(c.repo, c.key, c.kind, JSON.stringify(c.members), c.hash, c.kept, c.source, c.model, c.reason, c.result ? JSON.stringify(c.result) : null, c.error, c.attempts, c.at); } /** The stored comparison of the set when it is current. */ @@ -94,11 +102,39 @@ export const currentComparison = (db: DatabaseSync, s: KindSet): StoredCompariso return c && c.hash === s.hash ? c : null; }; -/** Sets that need a comparison: an open member is in the pilot and no current result is stored. */ -export function dueSets(db: DatabaseSync, repo?: string): KindSet[] { +export const DROP_PAUSE_MS = 6 * 3600_000; +export const RULE_RETRY_MS = 24 * 3600_000; +export const RULE_ATTEMPTS = 3; +const dropKey = (s: { repo: string; key: string }) => `dupe_drop:${s.repo}:${s.key}`; + +/** Remembers that the set changed on GitHub since the sync, so it is not tried again for a while. */ +export function rememberDrop(db: DatabaseSync, s: KindSet, at: string): void { + db.prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(dropKey(s), `${s.hash}|${at}`); +} + +function recentlyDropped(db: DatabaseSync, s: KindSet, nowMs: number): boolean { + const v = (db.prepare("SELECT value FROM settings WHERE key = ?").get(dropKey(s)) as { value: string } | undefined)?.value; + if (!v) return false; + const [hash, at] = v.split("|"); + return hash === s.hash && nowMs - Date.parse(at!) < DROP_PAUSE_MS; +} + +/** A stored rule result is tried again after a day, three times at most, while no decision of the group is answered. */ +function retryable(db: DatabaseSync, c: StoredComparison, nowMs: number): boolean { + if (c.source !== "rule" || c.attempts >= RULE_ATTEMPTS || nowMs - Date.parse(c.at) < RULE_RETRY_MS) return false; + const placeholders = c.members.map(() => "?").join(","); + return !db.prepare(`SELECT 1 FROM dupe_group_items gi JOIN decisions d ON d.id = gi.decision_id + WHERE gi.repo = ? AND gi.number IN (${placeholders}) AND d.answer IS NOT NULL AND d.answer <> 'superseded' LIMIT 1`).get(c.repo, ...c.members); +} + +/** Sets that need a comparison: an open member is in the pilot and no current result is stored (or a rule result may be retried), and the set did not just change on GitHub. */ +export function dueSets(db: DatabaseSync, repo?: string, nowMs: number = Date.now()): KindSet[] { const out: KindSet[] = []; for (const g of duplicateGroups(db, repo)) - for (const s of kindSetsOf(db, g)) - if (s.members.some((m) => m.state === "OPEN" && inPilot(db, s.repo, m.number)) && !currentComparison(db, s)) out.push(s); + for (const s of kindSetsOf(db, g)) { + if (!s.members.some((m) => m.state === "OPEN" && inPilot(db, s.repo, m.number))) continue; + const c = currentComparison(db, s); + if ((!c || retryable(db, c, nowMs)) && !recentlyDropped(db, s, nowMs)) out.push(s); + } return out; } diff --git a/src/schema.sql b/src/schema.sql index 3b30ef81..4c971b84 100644 --- a/src/schema.sql +++ b/src/schema.sql @@ -845,6 +845,7 @@ CREATE TABLE IF NOT EXISTS dupe_comparisons ( reason TEXT, result TEXT, -- JSON {others: [...], rounds: n} error TEXT, + attempts INTEGER NOT NULL DEFAULT 0, -- consecutive rule results at this hash; a rule result is tried again after 24 h, three times at most at TEXT NOT NULL, PRIMARY KEY (repo, key) ); @@ -865,6 +866,8 @@ CREATE TABLE IF NOT EXISTS dupe_group_items ( role TEXT NOT NULL, target INTEGER, detail TEXT, + base_role TEXT NOT NULL, -- the roles as the comparison gave them; an answer's roles are rebuilt from these + base_target INTEGER, PRIMARY KEY (decision_id, number) ); CREATE INDEX IF NOT EXISTS dupe_group_items_item ON dupe_group_items(repo, number); diff --git a/test/dupe-groups.test.ts b/test/dupe-groups.test.ts index b07033af..ea3fb72c 100644 --- a/test/dupe-groups.test.ts +++ b/test/dupe-groups.test.ts @@ -11,7 +11,9 @@ import { runDupeCompare, type CompareDeps, type Reply } from "../src/dupes/compa import { applyDuplicateAnswers } from "../src/dupes/decide.ts"; import { duplicateHeld, notHeldSql } from "../src/dupes/held.ts"; import { compareWork, dupesWork } from "../src/dupes/index.ts"; -import { dueSets } from "../src/dupes/plan.ts"; +import { dueSets, DROP_PAUSE_MS, RULE_RETRY_MS } from "../src/dupes/plan.ts"; +import { askGroupDecisions, resetGroupAnswer } from "../src/dupes/decide.ts"; +import { selectCandidates } from "../src/decide/select.ts"; import { SCRATCH } from "./scratch.ts"; mkdirSync(SCRATCH, { recursive: true }); @@ -144,7 +146,7 @@ describe("issue group", () => { return JSON.stringify({ keep: nums[0], reason: "r", others: nums.slice(1).map((number: number) => ({ number, adds: [] })) }); }); await runDupeCompare(db, {}, () => {}, d); - assert.deepEqual(d.calls.map((c) => c.input.issues.length), [10, 2, 2]); + assert.deepEqual(d.calls.map((c) => c.input.issues.length), [6, 6, 2]); const roles = db.prepare("SELECT COUNT(*) AS n FROM dupe_group_items WHERE decision_id = ? AND role = 'close'").get(GROUP_ID) as { n: number }; assert.equal(roles.n, 11); }); @@ -219,3 +221,175 @@ describe("pair decisions and answers", () => { assert.equal(dueSets(db).length, 0); }); }); + +const issueReply = (keep: number, others: number[]) => JSON.stringify({ keep, reason: "r", others: others.map((number) => ({ number, adds: [] })) }); +const roles = (db: DatabaseSync, id = GROUP_ID) => (db.prepare("SELECT number, role FROM dupe_group_items WHERE decision_id = ? ORDER BY number").all(id) as { number: number; role: string }[]).map((r) => `${r.number}:${r.role}`); +const answerAs = (db: DatabaseSync, a: string, id = GROUP_ID) => db.prepare("UPDATE decisions SET answer = ?, answered_by = 'op', answered_at = ? WHERE id = ?").run(a, T0, id); +const undo = (db: DatabaseSync, id = GROUP_ID) => { db.prepare("UPDATE decisions SET answer = NULL, answered_by = NULL, answered_at = NULL WHERE id = ?").run(id); resetGroupAnswer(db, id); }; + +describe("review fixes: answers, undo and refresh", () => { + async function three() { + const db = fresh([{ n: 1 }, { n: 2 }, { n: 3 }], [[1, 2], [1, 3]]); + await runDupeCompare(db, {}, () => {}, deps(() => issueReply(1, [2, 3]))); + return db; + } + test("undo then answer again rebuilds the roles from the comparison", async () => { + const db = await three(); + answerAs(db, "keep:2"); + applyDuplicateAnswers(db, T0); + assert.deepEqual(roles(db), ["1:close", "2:keep", "3:close"]); + undo(db); + assert.deepEqual(roles(db), ["1:keep", "2:close", "3:close"]); + answerAs(db, "keep:2"); + applyDuplicateAnswers(db, T0); + assert.deepEqual(roles(db), ["1:close", "2:keep", "3:close"]); + // keep:3, undo, then use the answer: the comparison's keep returns. + undo(db); + answerAs(db, "keep:3"); + applyDuplicateAnswers(db, T0); + undo(db); + answerAs(db, "accept"); + applyDuplicateAnswers(db, T0); + assert.deepEqual(roles(db), ["1:keep", "2:close", "3:close"]); + }); + + test("a refresh drops the applied answer and restores the comparison's roles", async () => { + const db = await three(); + db.prepare("UPDATE dupe_group_items SET role = 'keep' WHERE decision_id = ? AND number = 2").run(GROUP_ID); + db.prepare("UPDATE dupe_groups SET applied_answer = 'keep:2'").run(); + askGroupDecisions(db, undefined, T0); + assert.deepEqual(roles(db), ["1:keep", "2:close", "3:close"]); + assert.equal((db.prepare("SELECT applied_answer FROM dupe_groups").get() as any).applied_answer, null); + }); + + test("keep #N instead leaves the old keep as stay when it is not open", async () => { + const db = await three(); + db.prepare("UPDATE items SET state = 'CLOSED' WHERE number = 1").run(); + // The closed #1 keeps winning by the closed rule only after a new comparison; here the roles are set directly. + answerAs(db, "keep:2"); + applyDuplicateAnswers(db, T0); + assert.equal(roles(db).includes("1:stay") || roles(db).includes("1:close"), true); + assert.equal(roles(db).includes("1:close"), false); + }); +}); + +describe("review fixes: members already gone", () => { + test("a member closed as a duplicate, or with an answered close pair decision, is not part of the group", async () => { + const db = fresh([{ n: 10 }, { n: 11 }, { n: 12, state: "CLOSED" }], [[10, 12], [10, 11]]); + db.prepare("UPDATE items SET state_reason = 'DUPLICATE' WHERE number = 12").run(); + const d = deps(() => issueReply(10, [11])); + await runDupeCompare(db, {}, () => {}, d); + assert.deepEqual(d.calls[0]!.input.issues.map((i: any) => i.ref), ["#10", "#11"]); + assert.equal(getDecision(db, "app:dupegroup:10")!.question, "Keep #10 and close #11 as a duplicate?"); + }); + + test("a pair close answered but not acted yet keeps that member out of the keep", async () => { + const db = fresh([{ n: 1 }, { n: 2 }], [[1, 2]]); + ask(db, [{ id: "app#2:duplicate@1", kind: "duplicate", repo: "app", number: 2, question: "q", options: [{ key: "close", label: "c" }, { key: "distinct", label: "n" }], asked_at: T0 }]); + answerAs(db, "close", "app#2:duplicate@1"); + const d = deps(() => issueReply(2, [1])); + await runDupeCompare(db, {}, () => {}, d); + assert.equal(d.calls.length, 0); + assert.equal(db.prepare("SELECT COUNT(*) AS n FROM decisions WHERE id LIKE '%dupegroup%'").get()!.n, 0); + }); + + test("a closed, unmerged PR is left out; a merged one still wins", async () => { + const db = fresh([{ n: 1, kind: "pr" }, { n: 2, kind: "pr" }, { n: 3, kind: "pr", state: "CLOSED" }], [[1, 2], [2, 3]]); + const d = deps(() => pr(1, [{ number: 2, duplicate: true, better: [], carry: [] }])); + await runDupeCompare(db, {}, () => {}, d); + assert.deepEqual(d.calls[0]!.input.prs.map((p: any) => p.ref), ["#1", "#2"]); + }); +}); + +describe("review fixes: queue, retries, atomic writes", () => { + test("a set dropped by the live check does not use the limit and is not retried for a while", async () => { + const db = fresh([{ n: 1 }, { n: 2 }, { n: 3 }, { n: 4 }], [[1, 2], [3, 4]]); + const d = deps(() => issueReply(3, [4])); + d.querier = { spent: 0, remaining: 1, async query() { + const repository: any = {}; + for (const n of [1, 2, 3, 4]) repository[`i${n}`] = { state: n === 1 ? "CLOSED" : "OPEN" }; + return { repository }; + } } as never; + const r = await runDupeCompare(db, { limit: 1 }, () => {}, d); + assert.deepEqual([r.dropped, d.calls.length], [1, 1]); + assert.equal(dueSets(db, undefined, NOW.getTime() + 1000).length, 0); + db.prepare("DELETE FROM dupe_comparisons").run(); + assert.equal(dueSets(db, undefined, NOW.getTime() + 1000).length, 1, "the set that was not dropped is due again, the dropped one waits"); + assert.equal(dueSets(db, undefined, NOW.getTime() + DROP_PAUSE_MS + 1000).length, 2); + }); + + test("a rule result is compared again after a day, three times at most", async () => { + const db = fresh([{ n: 1 }, { n: 2 }], [[1, 2]]); + const run = (ms: number) => runDupeCompare(db, {}, () => {}, { ...deps(() => "no"), now: () => new Date(NOW.getTime() + ms) }); + await run(0); + assert.equal(dueSets(db, undefined, NOW.getTime() + 1000).length, 0); + assert.equal(dueSets(db, undefined, NOW.getTime() + RULE_RETRY_MS + 1000).length, 1); + await run(RULE_RETRY_MS + 1000); + await run(2 * RULE_RETRY_MS + 2000); + assert.equal((db.prepare("SELECT attempts FROM dupe_comparisons").get() as any).attempts, 3); + assert.equal(dueSets(db, undefined, NOW.getTime() + 9 * RULE_RETRY_MS).length, 0); + // A model answer on a retry replaces the rule result. + db.prepare("UPDATE dupe_comparisons SET attempts = 1").run(); + await runDupeCompare(db, {}, () => {}, { ...deps(() => issueReply(2, [1])), now: () => new Date(NOW.getTime() + 4 * RULE_RETRY_MS) }); + assert.equal((db.prepare("SELECT source FROM dupe_comparisons").get() as any).source, "model"); + assert.equal(getDecision(db, GROUP_ID)!.number, 2); + }); + + test("a failed refresh leaves nothing half written", async () => { + const db = fresh([{ n: 1 }, { n: 2 }], [[1, 2]]); + await runDupeCompare(db, {}, () => {}, deps(() => issueReply(1, [2]))); + db.exec("CREATE TRIGGER boom BEFORE INSERT ON dupe_group_items BEGIN SELECT RAISE(ABORT, 'boom'); END"); + db.prepare("UPDATE decisions SET question = 'old'").run(); + assert.throws(() => askGroupDecisions(db, undefined, T0), /boom/); + assert.equal(getDecision(db, GROUP_ID)!.question, "old"); + assert.equal(roles(db).length, 2); + }); + + test("the kept item of an open group decision is not held back from Decide", async () => { + const db = fresh([{ n: 1 }, { n: 2 }], [[1, 2]]); + await runDupeCompare(db, {}, () => {}, deps(() => issueReply(1, [2]))); + db.prepare("INSERT INTO classifications (repo, number, classifier, run_id, at, type_label, flags, probs) VALUES ('app', 1, 'jev', 'r1', ?, 'missing feature', '[\"needs decision\"]', '{\"top\":0.95}')").run(T0); + assert.deepEqual(selectCandidates(db, "r1", ["app"]).map((c) => c.number), [1]); + }); +}); + +describe("review fixes: groups that grow", () => { + test("a member joining after an answer is asked against the answered keep, and the answered members are not asked again", async () => { + const db = fresh([{ n: 3 }, { n: 7 }, { n: 9 }], [[3, 7]]); + await runDupeCompare(db, {}, () => {}, deps(() => issueReply(3, [7]))); + answerAs(db, "accept", "app:dupegroup:3"); + applyDuplicateAnswers(db, T0); + db.prepare("INSERT INTO duplicate_pairs (repo, a, b, a_hash, b_hash, similarity, jev_p, verdict, canonical, checked_at, created_at) VALUES ('app', 3, 9, 'h3', 'h9', 0.9, 0.95, 'duplicate', 3, ?, ?)").run(T0, T0); + // The model would now keep the new #9; the answered keep stays. + await runDupeCompare(db, {}, () => {}, deps(() => issueReply(9, [3, 7]))); + const ids = (db.prepare("SELECT id FROM decisions WHERE id LIKE '%dupegroup%' ORDER BY id").all() as { id: string }[]).map((r) => r.id); + assert.deepEqual(ids, ["app:dupegroup:3", "app:dupegroup:9"]); + assert.deepEqual(roles(db, "app:dupegroup:9"), ["3:keep", "9:close"]); + assert.equal(getDecision(db, "app:dupegroup:9")!.question, "Keep #3 and close #9 as a duplicate?"); + }); + + test("a lower member joining an open group refreshes the same decision", async () => { + const db = fresh([{ n: 1 }, { n: 5 }, { n: 6 }], [[5, 6]]); + await runDupeCompare(db, {}, () => {}, deps(() => issueReply(5, [6]))); + assert.ok(getDecision(db, "app:dupegroup:5")); + db.prepare("INSERT INTO duplicate_pairs (repo, a, b, a_hash, b_hash, similarity, jev_p, verdict, canonical, checked_at, created_at) VALUES ('app', 1, 5, 'h1', 'h5', 0.9, 0.95, 'duplicate', 1, ?, ?)").run(T0, T0); + await runDupeCompare(db, {}, () => {}, deps(() => issueReply(5, [1, 6]))); + assert.equal(db.prepare("SELECT COUNT(*) AS n FROM decisions WHERE id LIKE '%dupegroup%'").get()!.n, 1); + assert.equal(getDecision(db, "app:dupegroup:5")!.question, "Keep #5 and close #1, #6 as duplicates?"); + }); + + test("open pair decisions are superseded even when the group has nothing to close", async () => { + const db = fresh([{ n: 1, kind: "pr" }, { n: 2, kind: "pr" }], [[1, 2]]); + ask(db, [{ id: "app#2:duplicate@1", kind: "duplicate", repo: "app", number: 2, question: "q", options: [{ key: "close", label: "c" }, { key: "distinct", label: "n" }], asked_at: T0 }]); + await runDupeCompare(db, {}, () => {}, deps(() => pr(1, [{ number: 2, duplicate: false, better: ["x"], carry: [] }]))); + assert.equal(getDecision(db, "app#2:duplicate@1")!.answer, "superseded"); + }); + + test("a group answer is applied when any member is in the pilot", async () => { + const db = fresh([{ n: 1 }, { n: 2 }], [[1, 2]]); + await runDupeCompare(db, {}, () => {}, deps(() => issueReply(1, [2]))); + answerAs(db, "accept"); + db.prepare("INSERT INTO settings (key, value) VALUES ('pilot_items', '[\"app#2\"]') ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(); + assert.equal(dupesWork(db, "m"), true); + }); +});