diff --git a/scripts/codemod-async.ts b/scripts/codemod-async.ts index e461e4209..6f5f4c6c8 100644 --- a/scripts/codemod-async.ts +++ b/scripts/codemod-async.ts @@ -58,7 +58,9 @@ export type Report = { rmw: Record; }; -const DEFAULT_LOCAL = ["src/itemtools/", "src/reference-search.ts", "src/reference-score-worker.ts"]; +// src/remote/tools.ts keeps the item-tools snapshot on a synchronous DatabaseSync, and src/github/read.ts opens its +// read-only DatabaseSync before wrapping it with dbFor; the rest of both files is async already. +const DEFAULT_LOCAL = ["src/itemtools/", "src/reference-search.ts", "src/reference-score-worker.ts", "src/remote/tools.ts", "src/github/read.ts"]; const DEFAULT_NO_EDIT = ["src/db/", "src/async-seq.ts", "test/db-layer.test.ts"]; const under = (rel: string, ps: string[]) => ps.some((p) => rel === p || (p.endsWith("/") && rel.startsWith(p))); const RENAME: Record = { DatabaseSync: "Db", StatementSync: "Statement" }; diff --git a/src/async-seq.ts b/src/async-seq.ts index 47150efc5..47699a468 100644 --- a/src/async-seq.ts +++ b/src/async-seq.ts @@ -90,3 +90,24 @@ async function mergeSort(xs: T[], cmp: (a: T, b: T) => number | Promise Promise): { skip(): Promise; run(): Promise } { + let cur: Promise | null = null; + const start = (): Promise => { + const p: Promise = fn().finally(() => { if (cur === p) cur = null; }); + cur = p; + return p; + }; + return { + skip: () => (cur ? Promise.resolve() : start()), + run: async () => { + while (cur) await cur.catch(() => {}); + return start(); + }, + }; +} diff --git a/src/classify/settled.ts b/src/classify/settled.ts index 0ffc54c9a..8d2427ef8 100644 --- a/src/classify/settled.ts +++ b/src/classify/settled.ts @@ -230,7 +230,14 @@ const VERDICTS = `SELECT k.repo, k.number, j.type_label AS jl, j.flags AS jf, j. AND s.at >= j.at AND s.at >= h.at AND json_extract(CASE WHEN json_valid(s.probs) THEN s.probs END, '$.sure') IS NOT NULL WHERE 1 = 1`; -export async function settledTable(db: Db, run: string | null): Promise { +// The table belongs to the connection, and so to every async context on it: a caller runs this and its own queries on +// temp.item_settled inside one db.read (or db.write), so no other context rebuilds the table for another run between +// them. The refresh is itself one read snapshot, so it joins either; it writes only the temp table. +export function settledTable(db: Db, run: string | null): Promise { + return db.read(() => refreshSettled(db, run)); +} + +async function refreshSettled(db: Db, run: string | null): Promise { const now = await db.prepare("SELECT COALESCE(MAX(rowid), 0) AS maxRowid, COUNT(*) AS count FROM main.classifications").get() as { maxRowid: number; count: number }; const prev = seen.get(db); if (prev && prev.run === run && prev.maxRowid === now.maxRowid && prev.count === now.count) return; @@ -250,27 +257,25 @@ export async function settledTable(db: Db, run: string | null): Promise { const cols = Array.from({ length: 15 }, (_, i) => `value ->> ${i}`).join(", "); await db.prepare(`INSERT OR REPLACE INTO temp.item_settled SELECT ${cols} FROM json_each(?)`).run(JSON.stringify(rows)); }; - await db.write(async () => { - const fresh = prev && prev.run === run - ? (await db.prepare("SELECT DISTINCT repo, number FROM main.classifications WHERE rowid > ? AND run_id = ?").all(prev.maxRowid, run) as { repo: string; number: number }[]) - : null; - const added = prev ? (await db.prepare("SELECT COUNT(*) AS n FROM main.classifications WHERE rowid > ?").get(prev.maxRowid) as { n: number }).n : 0; - // INSERT OR REPLACE removes one row for each it adds, so the count only falls when something was deleted. - if (fresh && run && now.count >= prev!.count && now.count <= prev!.count + added) { - if (fresh.length) { - const keys = JSON.stringify(fresh.map((k) => [k.repo, k.number])); - const found = await db.prepare(`${VERDICTS} AND (k.repo, k.number) IN (SELECT value ->> 0, value ->> 1 FROM json_each(:keys))`).all({ run, keys }) as VerdictRow[]; - const have = new Set(found.map((r) => `${r.repo}#${r.number}`)); - const gone = fresh.filter((k) => !have.has(`${k.repo}#${k.number}`)).map((k) => [k.repo, k.number]); - if (gone.length) await db.prepare("DELETE FROM temp.item_settled WHERE (repo, number) IN (SELECT value ->> 0, value ->> 1 FROM json_each(?))").run(JSON.stringify(gone)); - for (const r of found) put(r); - } - } else { - await db.script("DELETE FROM temp.item_settled"); - if (run) for (const r of await db.prepare(VERDICTS).all({ run }) as VerdictRow[]) put(r); + const fresh = prev && prev.run === run + ? (await db.prepare("SELECT DISTINCT repo, number FROM main.classifications WHERE rowid > ? AND run_id = ?").all(prev.maxRowid, run) as { repo: string; number: number }[]) + : null; + const added = prev ? (await db.prepare("SELECT COUNT(*) AS n FROM main.classifications WHERE rowid > ?").get(prev.maxRowid) as { n: number }).n : 0; + // INSERT OR REPLACE removes one row for each it adds, so the count only falls when something was deleted. + if (fresh && run && now.count >= prev!.count && now.count <= prev!.count + added) { + if (fresh.length) { + const keys = JSON.stringify(fresh.map((k) => [k.repo, k.number])); + const found = await db.prepare(`${VERDICTS} AND (k.repo, k.number) IN (SELECT value ->> 0, value ->> 1 FROM json_each(:keys))`).all({ run, keys }) as VerdictRow[]; + const have = new Set(found.map((r) => `${r.repo}#${r.number}`)); + const gone = fresh.filter((k) => !have.has(`${k.repo}#${k.number}`)).map((k) => [k.repo, k.number]); + if (gone.length) await db.prepare("DELETE FROM temp.item_settled WHERE (repo, number) IN (SELECT value ->> 0, value ->> 1 FROM json_each(?))").run(JSON.stringify(gone)); + for (const r of found) put(r); } - await insertAll(); - }); + } else { + await db.script("DELETE FROM temp.item_settled"); + if (run) for (const r of await db.prepare(VERDICTS).all({ run }) as VerdictRow[]) put(r); + } + await insertAll(); seen.set(db, { run, ...now }); } diff --git a/src/dash/api/items.ts b/src/dash/api/items.ts index 16d417a7c..f50b4de8f 100644 --- a/src/dash/api/items.ts +++ b/src/dash/api/items.ts @@ -247,37 +247,43 @@ async function statusCounts(db: Db, b: Built & { run: string | null }, sql: stri } export async function listItems(db: Db, req: Req): Promise { - const b = await build(db, req, await hiddenRepos(db, req)); - const limit = Math.min(100, Math.max(1, Number(req.query.get("limit")) || 50)); - const offset = Math.max(0, Number(req.query.get("offset")) || 0); - const from = (scored: boolean) => (b.text - ? `WITH ${scored ? HITS_SCORED : HIT_IDS} SELECT %COLS FROM hits h JOIN items i ON i.rowid = h.rid` - : "SELECT %COLS FROM items i") + " LEFT JOIN temp.item_settled s ON s.repo = i.repo AND s.number = i.number"; - const whereSql = (w: string[]) => (w.length ? ` WHERE ${w.join(" AND ")}` : ""); + const hidden = await hiddenRepos(db, req); + // build() fills the connection's temp tables (item_settled, flow_pick) that the counts and the page read, so all of + // it runs in one snapshot. + const { b, total, byStatus, rows } = await db.read(async () => { + const b = await build(db, req, hidden); + const limit = Math.min(100, Math.max(1, Number(req.query.get("limit")) || 50)); + const offset = Math.max(0, Number(req.query.get("offset")) || 0); + const from = (scored: boolean) => (b.text + ? `WITH ${scored ? HITS_SCORED : HIT_IDS} SELECT %COLS FROM hits h JOIN items i ON i.rowid = h.rid` + : "SELECT %COLS FROM items i") + " LEFT JOIN temp.item_settled s ON s.repo = i.repo AND s.number = i.number"; + const whereSql = (w: string[]) => (w.length ? ` WHERE ${w.join(" AND ")}` : ""); - // Counts per status under every filter but the status one; the total follows from them. - const byStatus = await statusCounts(db, b, from(false).replace("%COLS", "s.status, COUNT(*) AS n") + whereSql(b.where) + " GROUP BY 1", req.query.get("flow")); - const total = (b.statuses.length ? b.statuses : STATUSES).reduce((a, s) => a + byStatus[s], 0); + // Counts per status under every filter but the status one; the total follows from them. + const byStatus = await statusCounts(db, b, from(false).replace("%COLS", "s.status, COUNT(*) AS n") + whereSql(b.where) + " GROUP BY 1", req.query.get("flow")); + const total = (b.statuses.length ? b.statuses : STATUSES).reduce((a, s) => a + byStatus[s], 0); - // The page as rowids first, so only its rows are read in full. - const where = [...b.where, ...(b.statusWhere ? [b.statusWhere] : [])]; - // bm25 is lower for better matches, so "most relevant first" sorts it ascending. - const order = b.sort === "relevance" ? `h.score ${b.desc ? "ASC" : "DESC"}` : `${ORDER[b.sort]} ${b.desc ? "DESC" : "ASC"}`; - // Newest first within a state: main.items with its index named, because through the - // scoping view the planner walks the repo index and sorts every open item. - const byUpdated = !b.text && b.sort === "updated" && b.params.state !== undefined; - const pageFrom = byUpdated - ? from(false).replace("FROM items i", "FROM main.items AS i INDEXED BY items_state_updated") - : from(b.sort === "relevance"); - const pageWhere = byUpdated ? [...where, "i.repo IN (SELECT name FROM main.tracked_repos)"] : where; - const ids = (await db.prepare(pageFrom.replace("%COLS", "i.rowid AS rid") + whereSql(pageWhere) + - ` ORDER BY ${order}, i.repo, i.number DESC LIMIT :limit OFFSET :offset`).all({ ...b.params, limit, offset }) as { rid: number }[]).map((r) => r.rid); - const byId = new Map((ids.length ? await db.prepare(`SELECT i.rowid AS rid, i.repo, i.number, i.kind, i.state, i.title, i.author, - i.created_at, i.updated_at, i.comments_count, s.status, s.label, s.source, s.top, s.jev_label, s.haiku_label, s.flags, - s.referee_label, s.referee_sure, s.referee_reason, ${MERGED_AT} AS merged_by_us_at - FROM items i LEFT JOIN temp.item_settled s ON s.repo = i.repo AND s.number = i.number WHERE i.rowid IN (${ids.map(() => "?").join(",")})`).all(...ids) as Row[] : []) - .map((r) => [r.rid, r])); - const rows = ids.map((id) => byId.get(id)).filter((r): r is Row => !!r); + // The page as rowids first, so only its rows are read in full. + const where = [...b.where, ...(b.statusWhere ? [b.statusWhere] : [])]; + // bm25 is lower for better matches, so "most relevant first" sorts it ascending. + const order = b.sort === "relevance" ? `h.score ${b.desc ? "ASC" : "DESC"}` : `${ORDER[b.sort]} ${b.desc ? "DESC" : "ASC"}`; + // Newest first within a state: main.items with its index named, because through the + // scoping view the planner walks the repo index and sorts every open item. + const byUpdated = !b.text && b.sort === "updated" && b.params.state !== undefined; + const pageFrom = byUpdated + ? from(false).replace("FROM items i", "FROM main.items AS i INDEXED BY items_state_updated") + : from(b.sort === "relevance"); + const pageWhere = byUpdated ? [...where, "i.repo IN (SELECT name FROM main.tracked_repos)"] : where; + const ids = (await db.prepare(pageFrom.replace("%COLS", "i.rowid AS rid") + whereSql(pageWhere) + + ` ORDER BY ${order}, i.repo, i.number DESC LIMIT :limit OFFSET :offset`).all({ ...b.params, limit, offset }) as { rid: number }[]).map((r) => r.rid); + const byId = new Map((ids.length ? await db.prepare(`SELECT i.rowid AS rid, i.repo, i.number, i.kind, i.state, i.title, i.author, + i.created_at, i.updated_at, i.comments_count, s.status, s.label, s.source, s.top, s.jev_label, s.haiku_label, s.flags, + s.referee_label, s.referee_sure, s.referee_reason, ${MERGED_AT} AS merged_by_us_at + FROM items i LEFT JOIN temp.item_settled s ON s.repo = i.repo AND s.number = i.number WHERE i.rowid IN (${ids.map(() => "?").join(",")})`).all(...ids) as Row[] : []) + .map((r) => [r.rid, r])); + const rows = ids.map((id) => byId.get(id)).filter((r): r is Row => !!r); + return { b, total, byStatus, rows }; + }); const stages = await stagesOf(db, rows); const snips = b.text ? await snippets(db, b.params.q as string, rows) : new Map(); diff --git a/src/dash/api/stats.ts b/src/dash/api/stats.ts index 129673e2c..ba0f7e118 100644 --- a/src/dash/api/stats.ts +++ b/src/dash/api/stats.ts @@ -28,21 +28,23 @@ export type FunnelRow = { // "classified" counts settled type labels (src/classify/settled.ts) in the latest run. export async function funnelByRepo(db: Db, repo?: string): Promise { - await settledTable(db, await latestRun(db)); - return (await db.prepare(`WITH ${latestCte(repo)} - SELECT i.repo, COUNT(*) AS open, - SUM(st.status = 'settled') AS classified, SUM(st.status = 'waiting') AS second_opinion, SUM(st.status = 'disagree') AS disagreement, - SUM(COALESCE(l.reviewed, 0) - OR EXISTS (SELECT 1 FROM main.classifications c WHERE c.repo = i.repo AND c.number = i.number AND c.classifier = 'sonnet')) AS reviewed, - SUM(l.stage IN ('take', 'verified') OR (l.stage LIKE 'verify-%' AND l.stage <> 'verify-failed')) AS take, SUM(l.stage = 'hold') AS hold, SUM(l.stage = 'close') AS close, - SUM(l.stage = 'needs-decision') AS needs_decision, SUM(l.stage = 'batched') AS batched - FROM items i LEFT JOIN latest l ON l.repo = i.repo AND l.number = i.number - LEFT JOIN temp.item_settled st ON st.repo = i.repo AND st.number = i.number - WHERE i.state = 'OPEN' ${repo ? "AND i.repo = :repo" : ""} - GROUP BY i.repo`).all(p(repo))).map((r) => ({ - ...r, classified: r.classified ?? 0, second_opinion: r.second_opinion ?? 0, disagreement: r.disagreement ?? 0, - take: r.take ?? 0, hold: r.hold ?? 0, close: r.close ?? 0, needs_decision: r.needs_decision ?? 0, batched: r.batched ?? 0, - })) as FunnelRow[]; + return await db.read(async () => { + await settledTable(db, await latestRun(db)); + return (await db.prepare(`WITH ${latestCte(repo)} + SELECT i.repo, COUNT(*) AS open, + SUM(st.status = 'settled') AS classified, SUM(st.status = 'waiting') AS second_opinion, SUM(st.status = 'disagree') AS disagreement, + SUM(COALESCE(l.reviewed, 0) + OR EXISTS (SELECT 1 FROM main.classifications c WHERE c.repo = i.repo AND c.number = i.number AND c.classifier = 'sonnet')) AS reviewed, + SUM(l.stage IN ('take', 'verified') OR (l.stage LIKE 'verify-%' AND l.stage <> 'verify-failed')) AS take, SUM(l.stage = 'hold') AS hold, SUM(l.stage = 'close') AS close, + SUM(l.stage = 'needs-decision') AS needs_decision, SUM(l.stage = 'batched') AS batched + FROM items i LEFT JOIN latest l ON l.repo = i.repo AND l.number = i.number + LEFT JOIN temp.item_settled st ON st.repo = i.repo AND st.number = i.number + WHERE i.state = 'OPEN' ${repo ? "AND i.repo = :repo" : ""} + GROUP BY i.repo`).all(p(repo))).map((r) => ({ + ...r, classified: r.classified ?? 0, second_opinion: r.second_opinion ?? 0, disagreement: r.disagreement ?? 0, + take: r.take ?? 0, hold: r.hold ?? 0, close: r.close ?? 0, needs_decision: r.needs_decision ?? 0, batched: r.batched ?? 0, + })) as FunnelRow[]; + }); } export type DoneRow = { repo: string; merged_pipeline: number; closed_pipeline: number; closed_others: number; total: number }; diff --git a/src/dash/server/index.ts b/src/dash/server/index.ts index 11476b731..a2d751d76 100644 --- a/src/dash/server/index.ts +++ b/src/dash/server/index.ts @@ -51,6 +51,8 @@ import { startLiveness } from "../../remote/liveness.ts"; import { archiveOf, callTaskTool, TASK_TOOLS, taskLease, type TaskLease, type ToolResult } from "../../remote/tools.ts"; import { handleDelivery, WEBHOOK_BODY_LIMIT, WEBHOOK_PATH } from "../../github/webhooks.ts"; import { esc, HttpError, parseCookies, plainPage, previewTags, RateLimiter, safeReturnTo } from "./util.ts"; +import { exclusive } from "../../async-seq.ts"; +import { refreshReadIdentity } from "../../github/read.ts"; import type { Db } from "../../db/index.ts"; export const SESSION_COOKIE = "__Host-craft_session"; @@ -288,14 +290,17 @@ export async function createApp(opts: AppOptions & { routes: Route[] }) { // Ended remote calls, finished check relays and the status of deleted tokens, once a minute; a busy database skips a round. // The same pass withdraws queued calls no Task Runner has been able to take for a while and marks repos without one (takers.ts). - const maintenance = setInterval(async () => { + const maintain = exclusive(async () => { try { await remote.pruneRemote(rdb); await sweepTakers(rdb); + // The live hub refreshes it only while a page is open. + await refreshReadIdentity(rdb); } catch (e) { if (!isBusy(e)) console.log(`remote maintenance failed: ${(e as Error).message}`); } - }, scaled(60_000)); + }); + const maintenance = setInterval(() => void maintain.skip(), scaled(60_000)); maintenance.unref(); function secure(headers: Record, csp: string): Record { diff --git a/src/dash/server/live.ts b/src/dash/server/live.ts index b216958c6..9c918313a 100644 --- a/src/dash/server/live.ts +++ b/src/dash/server/live.ts @@ -3,6 +3,8 @@ // carries topic names and counters only, never data: browsers refetch through the API. import type { ServerResponse } from "node:http"; import { readSeqs } from "../../live.ts"; +import { exclusive } from "../../async-seq.ts"; +import { refreshReadIdentity } from "../../github/read.ts"; import type { Db } from "../../db/index.ts"; export type LiveOptions = { @@ -20,6 +22,9 @@ export class LiveHub { private last: Record = {}; private timer?: NodeJS.Timeout; private beat?: NodeJS.Timeout; + // Passes never overlap: two checks at once could set `last` back to the older markers and announce a change twice. + private checks = exclusive(() => this.check().catch((e: unknown) => console.error(`live: ${(e as Error).message}`))); + private beats = exclusive(() => this.heartbeat().catch((e: unknown) => console.error(`live heartbeat: ${(e as Error).message}`))); private readonly pollMs: number; private readonly heartbeatMs: number; private readonly maxClients: number; @@ -62,7 +67,7 @@ export class LiveHub { /** Checks the markers now, for the answer to a write the dashboard just handled. */ async poke(): Promise { - if (this.clients.size) await this.check(); + if (this.clients.size) await this.checks.run(); } close(): void { @@ -84,8 +89,9 @@ export class LiveHub { private async start(): Promise { this.last = await readSeqs(this.db); - this.timer = setInterval(() => void this.check().catch((e: unknown) => console.error(`live: ${(e as Error).message}`)), this.pollMs); - this.beat = setInterval(() => void this.heartbeat().catch((e: unknown) => console.error(`live heartbeat: ${(e as Error).message}`)), this.heartbeatMs); + await this.identity(this.last); + this.timer = setInterval(() => void this.checks.skip(), this.pollMs); + this.beat = setInterval(() => void this.beats.skip(), this.heartbeatMs); this.timer.unref(); this.beat.unref(); } @@ -110,6 +116,16 @@ export class LiveHub { const seqs: Record = {}; for (const t of topics) seqs[t] = now[t]!; this.send(`event: change\ndata: ${JSON.stringify({ topics, seqs })}\n\n`); + if (topics.includes("settings")) await this.identity(now); + } + + /** The GitHub read identity this process holds follows the `settings` counter. */ + private async identity(seqs: Record): Promise { + try { + await refreshReadIdentity(this.db, seqs.settings); + } catch (e) { + console.error(`live: GitHub identity not refreshed: ${(e as Error).message}`); + } } private async heartbeat(): Promise { diff --git a/src/discord/alerts.ts b/src/discord/alerts.ts index 01da1105d..733d6c164 100644 --- a/src/discord/alerts.ts +++ b/src/discord/alerts.ts @@ -21,7 +21,7 @@ import { loginOf } from "./links.ts"; import type { Call, Interactions } from "./interactions.ts"; import { RestError, type DiscordRest, type EditBody } from "./rest.ts"; import { ghPermission, type PermissionReader } from "../fixup/author-permission.ts"; -import { everySeq, filterSeq, someSeq } from "../async-seq.ts"; +import { everySeq, exclusive, filterSeq, someSeq } from "../async-seq.ts"; import type { Db } from "../db/index.ts"; /** What the alerts need from Discord beyond messages: the direct-message channel of a user. */ @@ -174,7 +174,7 @@ export class DecisionAlerts { /** Polls the change markers of the decision topics; a change runs one pass. Runs a first pass at once. */ start(signal: AbortSignal): void { void this.sync(); - const t = setInterval(async () => { + const poll = exclusive(async () => { try { const seqs = await readSeqs(this.#d.db); const sig = TOPICS.map((k) => seqs[k] ?? 0).join(","); @@ -190,7 +190,8 @@ export class DecisionAlerts { } catch (e) { this.#d.log(`discord: alert poll failed: ${(e as Error).message}`); } - }, POLL_MS); + }); + const t = setInterval(() => void poll.skip(), POLL_MS); t.unref(); signal.addEventListener("abort", () => clearInterval(t), { once: true }); } diff --git a/src/flow/count.ts b/src/flow/count.ts index 618922bfd..8ef05c331 100644 --- a/src/flow/count.ts +++ b/src/flow/count.ts @@ -81,10 +81,12 @@ export class Ctx { /** Every open item with its settled status in the current run. */ async open(): Promise { if (!this.openRows) { - await settledTable(this.db, this.run); - this.openRows = await this.db.prepare(`SELECT i.repo, i.number, i.kind, s.status, s.referee_sure, s.jev_label, s.haiku_label FROM items i - LEFT JOIN temp.item_settled s ON s.repo = i.repo AND s.number = i.number - WHERE i.state = 'OPEN' ${this.andRepo("i.repo")}`).all(this.rp) as OpenRow[]; + this.openRows = await this.db.read(async () => { + await settledTable(this.db, this.run); + return await this.db.prepare(`SELECT i.repo, i.number, i.kind, s.status, s.referee_sure, s.jev_label, s.haiku_label FROM items i + LEFT JOIN temp.item_settled s ON s.repo = i.repo AND s.number = i.number + WHERE i.state = 'OPEN' ${this.andRepo("i.repo")}`).all(this.rp) as OpenRow[]; + }); } return this.openRows; } diff --git a/src/github/identity.ts b/src/github/identity.ts index c229641a3..be2cfafa0 100644 --- a/src/github/identity.ts +++ b/src/github/identity.ts @@ -13,6 +13,7 @@ import { AppError, call, GITHUB_API } from "./app.ts"; import { AppNotInstalledError, installationToken, readAppSecrets, RepoNotInInstallationError } from "./install-token.ts"; import { setting } from "../settings-read.ts"; import type { Db } from "../db/index.ts"; +import { noteReadIdentity } from "./read.ts"; export type Identity = "app" | `user:${string}`; export type GithubIdentity = "box" | "app"; @@ -43,6 +44,7 @@ export async function setGithubIdentity(db: Db, by: string, value: unknown): Pro const at = new Date().toISOString(); for (const t of stored) await queue.run(t.login, t.token_enc, at); }); + noteReadIdentity(value === "app"); return true; } diff --git a/src/github/read.ts b/src/github/read.ts index 0c5634605..b023140b9 100644 --- a/src/github/read.ts +++ b/src/github/read.ts @@ -2,7 +2,9 @@ // Under the `box` identity nothing is added: the child inherits this process's environment and the box account's // login. Under `app` the child's whole environment is the inherited basics plus an installation token (never the // box account's credentials), and a failure to mint one is an error, not a fallback to the box account. -// The setting is read at every call, so a switch takes effect in the runner and the dashboard without a restart. +// The setting is held in memory: the runner's tick and the dashboard's live hub refresh it when the `settings` change +// counter moves (refreshReadIdentity), so a switch takes effect there without a restart; a one-shot CLI command reads it +// once, on first use. import { existsSync } from "node:fs"; import { DatabaseSync } from "node:sqlite"; import { dbPath } from "../db.ts"; @@ -14,24 +16,34 @@ import { dbFor } from "../db/open.ts"; export type ReadEnv = Record; export type ReadDeps = { db?: Db; mint?: (owner: string) => Promise; defaultOwner?: () => Promise }; -let shared: { path: string; db: Db } | null = null; +// The promise is kept, so two first calls at once share one open. +let shared: { path: string; db: Promise } | null = null; /** * A read-only handle on the instance database, opened on first use. Null only when there is no database file (nothing * configured the identity); a file that cannot be opened is an error, never a silent read as the box account. */ async function sharedDb(): Promise { const path = dbPath(); - if (shared?.path === path) return shared.db; + if (shared?.path === path) return await shared.db; if (!existsSync(path)) return null; + const mine = { path, db: openShared(path) }; + shared = mine; + try { + return await mine.db; + } catch (e) { + if (shared === mine) shared = null; + throw e; + } +} + +async function openShared(path: string): Promise { let last: unknown; for (let i = 0; i < 3; i++) { let sync: DatabaseSync; try { sync = new DatabaseSync(path, { readOnly: true, timeout: 5_000 }); } catch (e) { last = e; continue; } - const db = await dbFor(sync); - shared = { path, db }; - return db; + return await dbFor(sync); } throw new Error(`cannot read the GitHub identity setting: ${String((last as Error)?.message ?? last).slice(0, 120)}`); } @@ -46,10 +58,43 @@ async function settingOf(db: Db): Promise { throw new Error(`cannot read the GitHub identity setting: ${String((last as Error)?.message ?? last).slice(0, 120)}`); } -/** Whether reads go through the GitHub App right now. Throws when the setting exists to be read but cannot be. */ +/** The identity setting as this process holds it, with the `settings` change counter it was read at (null: unknown). */ +let held: { app: boolean; seq: number | null } | null = null; +let firstRead: Promise | null = null; + +/** + * Brings the held identity up to date when the `settings` change counter moved (`seq`: the counter as the caller already + * read it). Long-running loops call it every pass. The counter is read before the value, so a write between the two + * only makes the next pass read again. + */ +export async function refreshReadIdentity(db: Db, seq?: number): Promise { + const at = seq ?? (await db.prepare("SELECT seq FROM main.change_seq WHERE topic = 'settings'").get() as { seq: number } | undefined)?.seq ?? null; + if (at !== null && held?.seq === at) return; + const app = await settingOf(db) === "app"; + // Another pass may have stored a later reading while this one awaited. + if (at !== null && held && held.seq !== null && held.seq > at) return; + held = { app, seq: at }; +} + +/** Records a switch this process just wrote, so its own next read uses it before any refresh. */ +export function noteReadIdentity(app: boolean): void { + held = { app, seq: null }; +} + +/** + * Whether reads go through the GitHub App right now: the held value, read once on first use when no loop refreshed it. + * With `db`, that database's setting. Throws when the setting exists to be read but cannot be. + */ export async function readsUseApp(db?: Db): Promise { - const d = db ?? await sharedDb(); - return d !== null && await settingOf(d) === "app"; + if (db) return await settingOf(db) === "app"; + if (held) return held.app; + firstRead ??= (async () => { + const d = await sharedDb(); + return d !== null && await settingOf(d) === "app"; + })().catch((e: unknown) => { firstRead = null; throw e; }); + const app = await firstRead; + held ??= { app, seq: null }; + return held.app; } /** The owner of the tracked repos: the default owner when it has any, else the first tracked one. */ diff --git a/src/owners.ts b/src/owners.ts index 167aaccc7..b341bf0e3 100644 --- a/src/owners.ts +++ b/src/owners.ts @@ -11,16 +11,22 @@ const REFRESH_MS = 30_000; let cache = new Map(); let source: DatabaseSync | null = null; let loadedAt = 0; +// Counts loads. An async reload stores its rows only when no load started after it, so a reload whose read finished +// late never puts back an older owner list. +let loads = 0; /** Reads the owners from the `repos` table; the most recently loaded database also refreshes the cache later. */ export function loadOwners(db: DatabaseSync): void { source = db; + loads++; setOwners(db.prepare(OWNERS_SQL).all() as OwnerRow[]); } /** loadOwners() through the async handle, after a write to `repos`. The cache refreshes later from the connection loaded last. */ export async function reloadOwners(db: { prepare(sql: string): { all(...params: never[]): Promise } }): Promise { - setOwners(await db.prepare(OWNERS_SQL).all() as OwnerRow[]); + const mine = ++loads; + const rows = await db.prepare(OWNERS_SQL).all() as OwnerRow[]; + if (mine === loads) setOwners(rows); } const OWNERS_SQL = "SELECT name, owner FROM main.repos"; diff --git a/src/priority/reach.ts b/src/priority/reach.ts index 97f6e4f76..c1349e21f 100644 --- a/src/priority/reach.ts +++ b/src/priority/reach.ts @@ -29,9 +29,11 @@ export async function reachOfOpenItems(db: Db, nowMs: number = Date.now()): Prom for (const r of await db.prepare("SELECT repo, number, COUNT(DISTINCT author) AS n FROM comments WHERE kind = 'comment' GROUP BY repo, number").all() as { repo: string; number: number; n: number }[]) commenters.set(key(r.repo, r.number), r.n); const security = new Set(); - await settledTable(db, await latestRun(db)); - for (const r of await db.prepare("SELECT repo, number FROM temp.item_settled WHERE security = 1").all() as { repo: string; number: number }[]) - security.add(key(r.repo, r.number)); + await db.read(async () => { + await settledTable(db, await latestRun(db)); + for (const r of await db.prepare("SELECT repo, number FROM temp.item_settled WHERE security = 1").all() as { repo: string; number: number }[]) + security.add(key(r.repo, r.number)); + }); // A PR that closes issues counts for the PR and for each issue. const linked = new Map(); const bump = (k: string) => linked.set(k, (linked.get(k) ?? 0) + 1); diff --git a/src/remote/calls.ts b/src/remote/calls.ts index ed51f3835..42a7fcb07 100644 --- a/src/remote/calls.ts +++ b/src/remote/calls.ts @@ -453,15 +453,19 @@ const queueSig = (n: number, m: number | null): string => `${n}:${m}`; function takeFromQueueCache(db: Db, id: number): void { const c = queueCaches.get(db); if (!c) return; - const drop = (l: Cand[]): boolean => { const i = l.findIndex((r) => r.id === id); if (i >= 0) l.splice(i, 1); return i >= 0; }; - if (!drop(c.followUps) && !drop(c.ordered)) return dropQueueCache(db); + // New arrays, not splices: another claim may be walking the old ones across its awaits (claimOrder), and a splice + // would shift an element past its loop index. + const followUps = c.followUps.filter((r) => r.id !== id), ordered = c.ordered.filter((r) => r.id !== id); + if (followUps.length === c.followUps.length && ordered.length === c.ordered.length) return dropQueueCache(db); + c.followUps = followUps; + c.ordered = ordered; let m: number | null = null; for (const r of c.followUps) if (m === null || r.id > m) m = r.id; for (const r of c.ordered) if (m === null || r.id > m) m = r.id; c.sig = queueSig(c.followUps.length + c.ordered.length, m); } -/** Every queued call, read once per QUEUE_CACHE_MS: follow-ups by age, the rest in queue order. Callers filter it and must not change it; only takeFromQueueCache does. */ +/** Every queued call, read once per QUEUE_CACHE_MS: follow-ups by age, the rest in queue order. Callers filter it and must not change it; only takeFromQueueCache replaces its arrays. */ async function queuedCalls(db: Db, nowMs: number): Promise { const q = await db.prepare("SELECT COUNT(*) AS n, MAX(id) AS m FROM main.remote_calls WHERE state = 'queued'").get() as { n: number; m: number | null }; const sig = queueSig(Number(q.n), q.m === null ? null : Number(q.m)); diff --git a/src/remote/claim-wait.ts b/src/remote/claim-wait.ts index c4a2514b9..b4739a287 100644 --- a/src/remote/claim-wait.ts +++ b/src/remote/claim-wait.ts @@ -70,6 +70,12 @@ type Waiter = { resolve: (r: ClaimReply) => void; reject: (e: unknown) => void; done: boolean; + /** + * A try is in progress. The client leaving or shutdown does not answer such a claim: the try may be past its `live` + * check and leasing a call, and an empty answer then would leave that lease with no one told of it. The pass answers + * it when the try ends. + */ + trying: boolean; }; /** How long each held reply waited, for the `X-Held-Ms` header. */ @@ -101,10 +107,10 @@ export class ClaimWaits { hold(ticket: Ticket, deadline: number, w: Pick): Promise { return new Promise((resolve, reject) => { const now = Date.now(); - const waiter: Waiter = { ...w, ticket, deadline, nextTry: now + this.#retryMs, seq: null, from: now, resolve, reject, done: false }; + const waiter: Waiter = { ...w, ticket, deadline, nextTry: now + this.#retryMs, seq: null, from: now, resolve, reject, done: false, trying: false }; const prev = ticket.onGone; ticket.onGone = () => { - if (!waiter.done) { + if (!waiter.done && !waiter.trying) { void waiter.empty(Date.now(), false).then((r) => this.#settle(waiter, r), (e: unknown) => this.#settle(waiter, null, e)); } prev?.(); @@ -120,11 +126,15 @@ export class ClaimWaits { this.#closed = true; const now = Date.now(); for (const w of [...this.#waiters]) { - if (w.done) continue; - void w.empty(now, false).then((r) => this.#settle(w, { ...r, retryAfter: scaledS(1 + Math.floor(Math.random() * 5)) }), (e: unknown) => this.#settle(w, null, e)); + if (w.done || w.trying) continue; + void this.#closing(w, now).then((r) => this.#settle(w, r), (e: unknown) => this.#settle(w, null, e)); } } + async #closing(w: Waiter, now: number): Promise { + return { ...await w.empty(now, false), retryAfter: scaledS(1 + Math.floor(Math.random() * 5)) }; + } + #settle(w: Waiter, r: ClaimReply | null, err?: unknown): void { if (w.done) return; w.done = true; @@ -160,11 +170,19 @@ export class ClaimWaits { w.seq = seq; if (full) w.nextTry = now + this.#retryMs; try { - // A claim answered meanwhile (its client left, or shutdown answered it) must not lease the call it found. - const r = await w.attempt(now, { quick: !full, live: () => !w.ticket.gone && !w.done && !this.#closed }); + // A claim whose client left, or that shutdown or a pass answered meanwhile, must not lease the call it found. + let r: ClaimReply | null; + w.trying = true; + try { + r = await w.attempt(now, { quick: !full, live: () => !w.ticket.gone && !w.done && !this.#closed }); + } finally { + w.trying = false; + } if (w.done) continue; if (r) this.#settle(w, r); - else if (w.blocked()) this.#settle(w, await w.empty(now, false)); + // Shutdown or the client leaving during the try, which leased nothing, gets the answer they skipped. + else if (this.#closed) this.#settle(w, await this.#closing(w, now)); + else if (w.ticket.gone || w.blocked()) this.#settle(w, await w.empty(now, false)); else if (final) { await w.idle(now); this.#settle(w, await w.empty(now, true)); diff --git a/src/remote/liveness.ts b/src/remote/liveness.ts index c11e2b00f..6cdbd15e2 100644 --- a/src/remote/liveness.ts +++ b/src/remote/liveness.ts @@ -3,6 +3,7 @@ // `remote_liveness` row every ALIVE_EVERY_MS; job processes, which expire leases (calls.ts expireLeases), read it. import { isBusy } from "../db.ts"; import { scaled } from "./time-scale.ts"; +import { exclusive } from "../async-seq.ts"; import type { Db } from "../db/index.ts"; export const ALIVE_EVERY_MS = scaled(5_000); @@ -45,8 +46,9 @@ export async function startLiveness(db: Db): Promise<() => void> { const tick = async (): Promise => { try { await stampAlive(db); } catch (e) { if (!isBusy(e)) console.log(`liveness stamp not written: ${(e as Error).message}`); } }; - await tick(); - const t = setInterval(() => void tick(), ALIVE_EVERY_MS); + const stamp = exclusive(tick); + await stamp.run(); + const t = setInterval(() => void stamp.skip(), ALIVE_EVERY_MS); t.unref(); return () => clearInterval(t); } diff --git a/src/runner/runner.ts b/src/runner/runner.ts index b65b7a7ff..77127f059 100644 --- a/src/runner/runner.ts +++ b/src/runner/runner.ts @@ -31,6 +31,8 @@ import { stepDeadlineMin, stepNoProgressMin } from "./deadlines.ts"; import { envVar } from "../env.ts"; import { anyRepinDue } from "../repin/due.ts"; import { jobRemoteQueue, REMOTE_WAIT_CAP_MS, withdrawJobCalls } from "../remote/calls.ts"; +import { exclusive } from "../async-seq.ts"; +import { refreshReadIdentity } from "../github/read.ts"; import type { Db } from "../db/index.ts"; export const logsDir = (): string => envVar("RUNNER_LOGS") ?? join(homedir(), ".cache/autocraft-logs/jobs"); @@ -172,6 +174,11 @@ export class Runner { } await this.cancels(); if (this.stopping) return; + try { + await refreshReadIdentity(this.db); + } catch (e) { + this.o.log(`GitHub identity not refreshed: ${(e as Error).message}`); + } try { const lost = await reapLost(this.db); if (lost) this.o.log(`${lost} build tasks lost their worker`); @@ -519,8 +526,9 @@ export class Runner { /** Stops every running job (SIGTERM, then SIGKILL after the grace time) and waits for them. */ async stop(): Promise { this.stopping = true; - const timer = setInterval(() => void this.cancels().catch((e) => this.o.log(`cancels: ${(e as Error).message}`)), 500); - await this.cancels(); + const cancels = exclusive(() => this.cancels()); + const timer = setInterval(() => void cancels.skip().catch((e) => this.o.log(`cancels: ${(e as Error).message}`)), 500); + await cancels.run(); await this.idle(); clearInterval(timer); await Promise.all([this.planThread.close(), this.flowThread.close()]);