Feature code's Db has no query methods; effects inside a transaction or wave throw in tests; reads of bytes in a wave must be alone; idle transactions end after 10 s

This commit is contained in:
aiongg committed 2026-11-25 14:25:01 +00:00
1 parent ff5fed0596
commit f2c76aa9e5
205 files changed
+787 -481

No files matched your search

+2 -2
View File
@@ -932,7 +932,7 @@ When the lease connection fails, the next renewal opens another. A lease that ex
Why nothing is written twice: every write of a fenced process runs under the writer lock (a write under a named lock takes the writer lock as well there), and the new leader moves the epoch in a write transaction. A write of the old leader or of one of its jobs either committed before the epoch moved, or sees the new epoch and fails. Every GitHub write first records its audit row in a write transaction, so a fenced job cannot start one either, and the pod launcher and the jobs' workspace sessions check the epoch before every Kubernetes change (pod and volume creates and deletes, commands in pods). GitHub and Kubernetes calls already in flight when the epoch moves finish; the old leader kills the jobs that made them when it notices the loss. With two or more replicas the old leader gives up after 8 seconds without a successful renewal, while its lease lasts 10 seconds from its last one, both measured from the renewal; the lease's end is on the server's clock, so the hosts' clocks do not need to agree. With one replica the old leader does not give up on its own; a copy that wins meanwhile (the new pod of a deploy) moves the epoch, so the old leader's writes and Kubernetes changes are refused from then on, and it stops at its next renewal or fenced write. GitHub calls its jobs make without a write to the database in between are not fenced.
Every database connection (the pools as well as the lease connection) sets `tcp_keepalives_idle` 5, `tcp_keepalives_interval` 2, `tcp_keepalives_count` 3 and `tcp_user_timeout` 10 s, so a server that the client reaches directly drops a client that went silent after about 11 seconds, and `idle_in_transaction_session_timeout` 60 s, so a transaction whose client stopped sending ends after a minute. Behind a proxy the keepalives cover only the proxy's own connection to the server: a client that is frozen while its host still answers (or whose silence the proxy does not notice) keeps its session, so only the idle-transaction timeout frees its writer lock. The pools and the lease connection set them with `SET` when a connection opens, before its first statement; a setting the server refuses (or, on the lease connection, does not answer within 3 seconds) is logged once per process and keeps the server's default. Only `statement_timeout` is a startup parameter.
Every database connection (the pools as well as the lease connection) sets `tcp_keepalives_idle` 5, `tcp_keepalives_interval` 2, `tcp_keepalives_count` 3 and `tcp_user_timeout` 10 s, so a server that the client reaches directly drops a client that went silent after about 11 seconds, and `idle_in_transaction_session_timeout` 10 s, so a transaction whose client stopped sending ends after ten seconds. Behind a proxy the keepalives cover only the proxy's own connection to the server: a client that is frozen while its host still answers (or whose silence the proxy does not notice) keeps its session, so only the idle-transaction timeout frees its writer lock. The pools and the lease connection set them with `SET` when a connection opens, before its first statement; a setting the server refuses (or, on the lease connection, does not answer within 3 seconds) is logged once per process and keeps the server's default. Only `statement_timeout` is a startup parameter.
How long a failover takes, until the new leader starts its recovery:
@@ -940,7 +940,7 @@ How long a failover takes, until the new leader starts its recovery:
|---|---|---|
| Clean stop (rolling update, pod deleted, node drained) | after the leader has stopped its jobs (at most `AUTOCRAFT_STOP_TIMEOUT`, 25 seconds) and ended its lease | at most 2 seconds later |
| Process or container killed, out of memory | when the lease expires, at most 10 seconds after the last renewal | at most 12 seconds |
| Node lost, network split, process frozen | when the lease expires, at most 10 seconds after the last renewal; a leader still running stopped itself after 8, a frozen one stops when it runs again | at most 12 seconds, when the lost leader had no write transaction open. Otherwise the takeover waits for the writer lock until that transaction ends: about 11 seconds when the server reaches the client directly and drops it, up to 60 seconds (`idle_in_transaction_session_timeout`) behind a proxy; the takeover's lock wait gives up after 30 seconds and tries again |
| Node lost, network split, process frozen | when the lease expires, at most 10 seconds after the last renewal; a leader still running stopped itself after 8, a frozen one stops when it runs again | at most 12 seconds, when the lost leader had no write transaction open. Otherwise the takeover waits for the writer lock until that transaction ends: about 11 seconds when the server reaches the client directly and drops it, and up to 10 seconds (`idle_in_transaction_session_timeout`) behind a proxy; the takeover's lock wait gives up after 30 seconds and tries again |
| Lease connection dropped, leader still running | the leader renews on a new connection at its next renewal | none |
Before enabling two replicas on PlanetScale:
-65
View File
@@ -1,65 +0,0 @@
// The data-layer boundary scan (test/data-layer.test.ts) and the list of files that still break it.
//
// node scripts/data-layer-allow.ts prints the files that query the database outside src/data/ and src/db/
// node scripts/data-layer-allow.ts --write writes them, sorted, to test/data-layer-allow.json
//
// Run with --write after files move into src/data/; the list must be empty when the data layer is finished.
import { readdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join, relative, resolve } from "node:path";
const ROOT = new URL("..", import.meta.url).pathname;
export const ALLOW_FILE = join(ROOT, "test/data-layer-allow.json");
/** src/db.ts holds the SQLite migrations: infrastructure, like src/db/. */
const INFRA = ["src/data/", "src/db/", "src/db.ts"];
const QUERY_CALLS = /\b(?:selectFrom|selectNoFrom|insertInto|updateTable|deleteFrom|replaceInto|mergeInto|queryDb)\(|\.prepare\(|\.script\(|\bdb\.k\b|\.k\./;
const SQL_TEXT = /\bsql(?:<(?:[^<>\n]|<(?:[^<>\n]|<[^<>\n]*>)*>)*>)?`|\bsql\.(?:raw|ref)\b|["'`]\s*(?:SELECT|INSERT|UPDATE|DELETE|WITH)\s+[A-Za-z_*(]/;
const FROM = /(?:\bfrom\s+|\bimport\s*\(\s*)["']([^"']+)["']/g;
const INFRA_FILES = new Set(["src/db/kx.ts", "src/db/sql.ts", "src/db/portable.ts", "src/db/search.ts", "src/db/types.ts"]);
const MODULE_PUBLIC = new Set(["index.ts", "types.ts"]);
/** Why `text` of the file `file` (a path from the repo root) breaks the boundary, or null. */
export function violation(file: string, text: string): string | null {
const call = QUERY_CALLS.exec(text);
if (call) return `query call ${call[0]}`;
const lit = SQL_TEXT.exec(text);
if (lit) return `SQL text ${lit[0]}`;
for (const m of text.matchAll(FROM)) {
const spec = m[1];
if (spec === "kysely") return "imports kysely";
if (!spec.startsWith(".")) continue;
const target = relative(ROOT, resolve(ROOT, dirname(file), spec));
if (INFRA_FILES.has(target)) return `imports ${target}`;
const mod = /^src\/data\/([^/]+)\/(.+)$/.exec(target);
if (mod && mod[1] !== "views" && !MODULE_PUBLIC.has(mod[2])) return `imports ${target}`;
}
return null;
}
/** Every .ts file under src/ outside src/data/ and src/db/ that breaks the boundary, with the reason, sorted. */
export function offenders(): { file: string; why: string }[] {
const out: { file: string; why: string }[] = [];
const walk = (dir: string) => {
for (const e of readdirSync(dir, { withFileTypes: true })) {
const p = join(dir, e.name);
if (e.isDirectory()) walk(p);
else if (p.endsWith(".ts")) {
const file = relative(ROOT, p);
if (INFRA.some((i) => file === i || file.startsWith(i))) continue;
const why = violation(file, readFileSync(p, "utf8"));
if (why) out.push({ file, why });
}
}
};
walk(join(ROOT, "src"));
return out.sort((a, b) => (a.file < b.file ? -1 : 1));
}
if (import.meta.main) {
const files = offenders().map((o) => o.file);
if (process.argv.includes("--write")) {
writeFileSync(ALLOW_FILE, `${JSON.stringify(files, null, 2)}\n`);
console.log(`${files.length} files written to ${relative(ROOT, ALLOW_FILE)}`);
} else console.log(files.join("\n"));
}
+5 -1
View File
@@ -7,6 +7,7 @@
// NOT NULL is `| null`; an INTEGER PRIMARY KEY of a rowid table or a column with a default is `Generated<>`, so inserts may
// leave it out. Virtual tables (full-text search) are left out: queries reach them only through src/db/kx.ts.
//
// `BYTES_COLUMNS` lists the columns that hold bytes (bytea on Postgres), for src/db/bytes-read.ts.
// `COLUMNS` lists each table's and view's columns in table order, without rowid or dropped columns, for `kx.cols`.
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
@@ -52,7 +53,7 @@ export function renderDbTypes(): string {
"",
];
const names: Rel[] = [];
const columns: string[] = [];
const columns: string[] = [], bytes: string[] = [];
for (const r of rels) {
if (virtual.includes(r.name) || shadow(r.name)) continue;
const cols = db.prepare(`PRAGMA table_info(${JSON.stringify(r.name)})`).all() as Col[];
@@ -70,6 +71,7 @@ export function renderDbTypes(): string {
if (!c.notnull && !c.pk && t !== "unknown") t += " | null";
const intKey = rowidTable && pks.length === 1 && c.pk === 1 && c.type.toUpperCase() === "INTEGER";
if (intKey || c.dflt_value !== null) t = `Generated<${t}>`;
if (t.includes("Uint8Array") && r.type === "table") bytes.push(where);
out.push(` ${key(c.name)}: ${t};`);
}
out.push("}", "");
@@ -82,6 +84,8 @@ export function renderDbTypes(): string {
out.push("}", "");
out.push("/** Each table's and view's columns in table order (no rowid), for selecting a whole row: `kx.cols`. */");
out.push("export const COLUMNS = {", ...columns, "} as const;", "");
out.push("/** The columns that hold bytes: BLOB on SQLite, bytea on Postgres. */");
out.push(`export const BYTES_COLUMNS = [${bytes.map((b) => JSON.stringify(b)).join(", ")}] as const;`, "");
return out.join("\n");
} finally {
db.close();
+2 -1
View File
@@ -8,11 +8,12 @@ import { createToken } from "../src/dash/mcp/tokens.ts";
import { claimCall, enqueueCall, type Caller } from "../src/remote/calls.ts";
import { PROTOCOL_VERSION, type Claim, type TaskBundle } from "../src/remote/protocol.ts";
import { connectDb } from "../src/db/open.ts";
import { queryDb } from "../src/db/query-db.ts";
const CALLS = 500, REPOS = 25, IDLE = 50, ROUNDS = 40;
const dir = mkdtempSync(join(tmpdir(), "claim-bench-"));
try {
const db = await connectDb(join(dir, "bench.db"));
const db = queryDb(await connectDb(join(dir, "bench.db")));
const now = Date.now(), iso = new Date(now).toISOString();
const bundle: Omit<TaskBundle, "callId"> = { promptId: "review.opus", promptVersion: "1", tier: "top", effort: "medium", timeoutSeconds: 600, maxTurns: 10, stdin: "x".repeat(20_000), system: null, mounts: [], mcpServers: [], keepSession: false, hints: {} };
const perm = db.prepare("INSERT OR REPLACE INTO repo_permissions (login, repo, permission, checked_at) VALUES (?, ?, ?, ?)");
+2
View File
@@ -39,6 +39,7 @@ import { appendLog, finishTask, loseTask, pickTasks, satisfies, type ClaimFit, M
import { appendTaskLogs, claimRun, failQueuedTasks, loadClaimInputs, loadEnvPass, loadEnvTasks, loadTasks, reportKubeEnv, releaseClaims, removePodRuns, savePodRuns, touchTasks } from "../data/build/index.ts";
import type { ClaimInputs, EnvRecord, PodRun, PodRunPatch } from "../data/build/index.ts";
import type { Db } from "../db/index.ts";
import { effect } from "../db/effects.ts";
export const PASS_MS = 5000;
/** Beyond a deadline Kubernetes should have enforced, the runner gives up on the pod itself. */
@@ -505,6 +506,7 @@ async function createPod(c: EnvCtx, run: Run, stage: number, spec: (ctx: PodCtx)
const at = new Date(now).toISOString();
await patchRun(c.d.db, run.task_id, { stage, pod: name, pod_created_at: at });
Object.assign(run, { stage, pod: name, pod_created_at: at });
effect("build-launch");
await c.api!.createPod(c.s.namespace, spec(ctx));
}
+2
View File
@@ -16,6 +16,7 @@ import {
FETCH_CONTAINER, FETCH_DEADLINE_SEC, FETCH_LIMIT_SEC, FETCH_LOG_TAIL, FETCH_START_MS, fetchPodName, fetchSelector, workspaceFetchPodSpec,
} from "./workspace-pods.ts";
import { cleanOutput, execInWorkspace, getWorkspace, type WorkspaceRow } from "./workspaces.ts";
import { effect } from "../db/effects.ts";
/** How long the call may take in all: the pod's start, its deadline and the diff, as the call row's deadline. */
export const FETCH_CALL_MS = FETCH_START_MS + FETCH_DEADLINE_SEC * 1000 + 60_000;
@@ -52,6 +53,7 @@ export async function fetchDependencies(db: Db, api: KubeApi, workspaceId: numbe
const prior = (await api.listPods(ns, fetchSelector(w.id))).find((p) => p.metadata.name === name && !p.metadata.deletionTimestamp);
if (!prior) {
const ci = ciLayoutOf(w) ?? undefined;
effect("build-launch");
await api.createPod(ns, workspaceFetchPodSpec({ s, envId: w.env_id, id: w.id, ...images, name, pvc: w.pvc, ...(ci ? { ci } : {}), dir }));
}
try {
+2
View File
@@ -42,6 +42,7 @@ import { resolveGate, resolveI18nRev } from "../worker/gate.ts";
import { EXT_ARCHIVE_MAX_BYTES, gateStepEnv } from "../worker/environment.ts";
import { changedFrom, parseLsTree, type CopyMark } from "../worker/warm-copy.ts";
import { describeHeader, execInWorkspace, execWs, getCheckpoint, getWorkspace, limitsOf, LIVE_STATES, moveWorkspace, POD_STATES, RESUME_TRIES, resumeWorkspace, type WorkspaceRow, type WorkspaceStateName, type WsCallResult } from "./workspaces.ts";
import { effect } from "../db/effects.ts";
export const SEED_LIMIT_MS = 10 * 60_000;
export const IDLE_PARK_MS = 30 * 60_000;
@@ -393,6 +394,7 @@ async function create(c: Ctx, row: WorkspaceRow, images: Images): Promise<boolea
await c.api.createPvc(ns, workspacePvcSpec(c.s, c.env.id, w.id, w.pvc ?? undefined, warmOf(w)?.storageBytes)).catch((e: unknown) => {
if (!conflict(e)) throw e;
});
effect("build-launch");
await c.api.createPod(ns, workspacePodSpec({ s: c.s, envId: c.env.id, id: w.id, ...images, limits: limitsOf(w), pod: w.pod ?? undefined, pvc: w.pvc ?? undefined, ci: ciLayoutOf(w) ?? undefined })).catch(async (e: unknown) => {
if (!conflict(e)) throw e;
const old = (await c.api.listPods(ns, workspaceSelector(w.id))).find((p) => p.metadata.name === w.pod);
+3
View File
@@ -37,6 +37,7 @@ import type { Db } from "../db/index.ts";
import { loadItems as loadMirrorItems, loadRepos } from "../data/mirror/index.ts";
import { loadRunsById, recordUsage, type UsageRow } from "../data/inference/index.ts";
import { saveJevChunk, saveVerdicts as saveVerdictRows, type JevFailed, type VerdictInput } from "../data/triage/index.ts";
import { effect } from "../db/effects.ts";
export function loadRefs(file: string): { repo: string; number: number }[] {
const out: { repo: string; number: number }[] = [];
@@ -395,6 +396,7 @@ async function lintTail(reply: Reply, lint: Lint, canFix: boolean, fixTurn: (mes
}
export async function askClaude<K extends ClaudePromptId>(id: K, model: string, input: ClaudeInput[K], db: Db, opts: AskOptions = {}): Promise<LintedReply | null> {
effect("model-call", id);
const ses = opts.session;
if (ses?.resume) {
const r = await askRemote(id, model, input, db, opts);
@@ -526,6 +528,7 @@ async function askRemote<K extends ClaudePromptId>(id: K, model: string, input:
/** Sends a registered Jev request (src/prompts) for one item to `jev ask`; the same rule as `askClaude`. Recorded as an agent run without an account. */
export async function askJev(id: JevPromptId, item: Item | DupePair | { ref: string }, db: Db, body: string = renderJev(id, item as Item | DupePair), perCallUsage = true): Promise<Proc> {
effect("model-call", id);
const runId = await startJevRun(db, { promptId: id, promptVersion: promptVersion(id), provider: "jev", model: "jev", items: refsOf([item]), prompt: body });
const start = now();
try {
+7 -6
View File
@@ -3,6 +3,7 @@ import type { NotNull } from "kysely";
import type { Classification, RelatedItem, Relation } from "../../../web/src/api/types.ts";
import type { Db } from "../../db/index.ts";
import * as kx from "../../db/kx.ts";
import { queryDb } from "../../db/query-db.ts";
import { itemState } from "./shown.ts";
const json = <T>(s: string | null | undefined, d: T): T => {
@@ -15,7 +16,7 @@ const json = <T>(s: string | null | undefined, d: T): T => {
export async function classificationsOf(db: Db, repo: string, n: number): Promise<Classification[]> {
// Latest verdict per classifier, picked here: a correlated MAX(at) subquery makes SQLite walk the (classifier, at) index.
const all = await db.all(db.k.selectFrom("classifications").select(["classifier", "at", "type_label", "want", "reference", "reason", "dup_of"])
const all = await queryDb(db).all(queryDb(db).k.selectFrom("classifications").select(["classifier", "at", "type_label", "want", "reference", "reason", "dup_of"])
.where("repo", "=", repo).where("number", "=", n).orderBy("classifier"));
const latest = new Map<string, string>();
for (const r of all) if (!latest.has(r.classifier) || r.at > latest.get(r.classifier)!) latest.set(r.classifier, r.at);
@@ -32,19 +33,19 @@ export async function relatedOf(db: Db, repo: string, n: number): Promise<Relate
const add = (number: number, relation: Relation) => {
if (number !== n && Number.isInteger(number) && !out.has(number)) out.set(number, { number, relation });
};
for (const d of await db.all(db.k.selectFrom("classifications").select("dup_of").distinct().where("repo", "=", repo).where("number", "=", n).where("dup_of", "is not", null).$narrowType<{ dup_of: NotNull }>().limit(10)))
for (const d of await queryDb(db).all(queryDb(db).k.selectFrom("classifications").select("dup_of").distinct().where("repo", "=", repo).where("number", "=", n).where("dup_of", "is not", null).$narrowType<{ dup_of: NotNull }>().limit(10)))
add(d.dup_of, "duplicate-of");
for (const x of await db.all(db.k.selectFrom("classifications").select("number").distinct().where("repo", "=", repo).where("dup_of", "=", n).limit(10))) add(x.number, "duplicated-by");
const it = await db.get(db.k.selectFrom("items").select(["kind", "closing_issues"]).where("repo", "=", repo).where("number", "=", n));
for (const x of await queryDb(db).all(queryDb(db).k.selectFrom("classifications").select("number").distinct().where("repo", "=", repo).where("dup_of", "=", n).limit(10))) add(x.number, "duplicated-by");
const it = await queryDb(db).get(queryDb(db).k.selectFrom("items").select(["kind", "closing_issues"]).where("repo", "=", repo).where("number", "=", n));
for (const x of json<unknown[]>(it?.closing_issues, [])) if (typeof x === "number") add(x, "fixes");
if (it?.kind === "issue") {
const prs = await db.all(db.k.selectFrom("items").select(["number", "closing_issues"]).where("repo", "=", repo).where("kind", "=", "pr")
const prs = await queryDb(db).all(queryDb(db).k.selectFrom("items").select(["number", "closing_issues"]).where("repo", "=", repo).where("kind", "=", "pr")
.where((eb) => kx.like(db, "closing_issues", eb.val(`%${n}%`))).$narrowType<{ closing_issues: NotNull }>().limit(50));
for (const p of prs) if (json<unknown[]>(p.closing_issues, []).includes(n)) add(p.number, "links");
}
const res: RelatedItem[] = [];
for (const { number, relation } of [...out.values()].slice(0, 10)) {
const row = await db.get(db.k.selectFrom("items").select(["title", "state", "kind"]).where("repo", "=", repo).where("number", "=", number));
const row = await queryDb(db).get(queryDb(db).k.selectFrom("items").select(["title", "state", "kind"]).where("repo", "=", repo).where("number", "=", number));
if (row) res.push({ repo, number, relation, title: row.title ?? "", state: itemState(row.state), kind: row.kind === "pr" ? "pr" : "issue" });
}
return res;
+3 -3
View File
@@ -1,4 +1,4 @@
import type { Selectable, SelectQueryBuilder } from "kysely";
import type { Insertable, Selectable, SelectQueryBuilder } from "kysely";
import type {
BuildEnv, BuildSummary, BuildTask, BuildTaskDetail, CacheReport, EnvTask, ItemShown, Requires, SandboxEnv, TaskFilter, TaskPage, TaskResult, TaskStep, WorkspacePage,
} from "../../../web/src/api/types.ts";
@@ -68,7 +68,7 @@ export type PodRunPatch = Partial<Omit<PodRun, "task_id">>;
export type WorkspaceRow = Omit<Selectable<DB["workspaces"]>, "checkpoint"> & { checkpoint?: Uint8Array | null };
export type SessionRow = Selectable<DB["workspace_sessions"]>;
export type WorkspaceCallRow = Selectable<DB["workspace_calls"]>;
export type NewSession = import("kysely").Insertable<DB["workspace_sessions"]>;
export type NewSession = Insertable<DB["workspace_sessions"]>;
export type ArtifactRow = { taskId: number; name: string; bytes: number; contentType: string; file: string };
export type TaskCard = {
@@ -150,7 +150,7 @@ export type WarmNote = { warm: string | null; warmCommit: string | null };
/** `ciCheckout`: the repository works at the CI paths when it has a warm target (the caller knows whether it has a CI checkout path). */
export type WorkspaceRequest = { repo: string; baseSha: string; envId: string; app?: string | null; limits?: { deadlineSec?: number }; owner: string | null; ciCheckout: boolean };
export type WorkspaceMove = { id: number; from: WorkspaceStateName[]; to: WorkspaceStateName; set?: Partial<Omit<WorkspaceRow, "id">> };
export type WorkspaceSource = { ids: number[] } | { env: string; states: WorkspaceStateName[] } | { remoteCallIds: number[] } | { idsFrom: import("kysely").SelectQueryBuilder<any, any, { id: number }> };
export type WorkspaceSource = { ids: number[] } | { env: string; states: WorkspaceStateName[] } | { remoteCallIds: number[] } | { idsFrom: SelectQueryBuilder<any, any, { id: number }> };
/** `running`: calls in `running` state within their deadline. `background`: the done shell, shell_status and shell_kill calls since the pod was created, with the bookkeeping of `result.acct`. */
export type CallActivity = {
running: { id: number; tool: string; deadlineAt: string }[];
+3 -1
View File
@@ -1,9 +1,11 @@
import type { Db } from "../../db/index.ts";
import { queryDb } from "../../db/query-db.ts";
/** True when the database answers a trivial query. */
export async function pingDb(db: Db): Promise<boolean> {
try {
await db.get(db.k.selectNoFrom((eb) => eb.lit(1).as("one")));
const q = queryDb(db);
await q.get(q.k.selectNoFrom((eb) => eb.lit(1).as("one")));
return true;
} catch {
return false;
-9
View File
@@ -1,7 +1,6 @@
// Run records: write and lifecycle (`agent_runs`, `agent_run_items`, `agent_run_texts`, `agent_run_tools`). No writer opens a transaction or a named lock.
// reads: runners.remote_calls
import type { Db } from "../../db/index.ts";
import { effect } from "../../db/effects.ts";
import * as kx from "../../db/kx.ts";
import { queryDb } from "../../db/query-db.ts";
import { keptRuns } from "../runners/fragments.ts";
@@ -179,11 +178,3 @@ export async function pruneRuns(db: Db, nowMs: number): Promise<{ texts: number;
const runs = Number((await q.run(q.k.deleteFrom("main.agent_runs").where("id", "<=", old))).changes);
return { texts, runs };
}
/** Guard, not a query: counts a model call in the meter and reports it when a transaction is open. */
export function enterModelCall(db: Db, kind: "claude" | "jev" | "workspace"): void {
const where = db.inTransaction()
? (new Error().stack ?? "").split("\n").slice(2).map((l) => l.trim()).find((l) => !/node_modules|\(node:|at node:/.test(l))?.replace(/^at (async )?/, "") ?? ""
: undefined;
effect(db, "model-call", where === undefined ? undefined : `${kind} call: ${where}`);
}
+1 -1
View File
@@ -2,7 +2,7 @@
import type { Db } from "../../db/index.ts";
import { queryDb } from "../../db/query-db.ts";
import * as kx from "../../db/kx.ts";
import { sql } from "kysely";
import { sql } from "../../db/sql.ts";
import { MAX_RESUMES, MAX_TOTAL_RESUMES } from "../../runner/resuming.ts";
import { flushJobItems } from "./items.ts";
import { nowIso } from "./sql.ts";
+2 -1
View File
@@ -1,8 +1,9 @@
// Statement pieces shared by the module's own files (not re-exported by index.ts).
import { sql, type RawBuilder } from "kysely";
import type { RawBuilder } from "kysely";
import type { Db } from "../../db/index.ts";
import type { AnyEb } from "../../db/kx.ts";
import * as kx from "../../db/kx.ts";
import { sql } from "../../db/sql.ts";
import { hiddenRepos } from "../control/fragments.ts";
import type { HiddenRepos } from "./types.ts";
+8 -8
View File
@@ -33,7 +33,7 @@ export async function saveChecks(db: Db, rows: PrChecksRow[], at: string): Promi
const q = queryDb(db);
await db.write(async () => {
for (const part of kx.batches(last)) {
await db.run(q.k.insertInto("pr_checks").values(part.map((r) => ({
await q.run(q.k.insertInto("pr_checks").values(part.map((r) => ({
repo: r.repo, number: r.number, head_oid: r.head_oid, state: r.state, is_draft: r.is_draft, overall: r.overall, checks: r.checks,
mergeable: r.mergeable, maintainer_can_modify: r.maintainer_can_modify, fetched_at: at,
}))).onConflict((oc) => oc.columns(["repo", "number"]).doUpdateSet((eb) => ({
@@ -111,7 +111,7 @@ export async function saveGates(db: Db, rows: GateRead[]): Promise<void> {
const q = queryDb(db);
await db.write(async () => {
for (const part of kx.batches(last)) {
await db.run(q.k.insertInto("review_gates").values(part.map((r) => ({ repo: r.repo, number: r.number, blocked: r.blocked, by_login: r.by_login, read_at: r.read_at, failures: 0 })))
await q.run(q.k.insertInto("review_gates").values(part.map((r) => ({ repo: r.repo, number: r.number, blocked: r.blocked, by_login: r.by_login, read_at: r.read_at, failures: 0 })))
.onConflict((oc) => oc.columns(["repo", "number"]).doUpdateSet(kx.excluded(["blocked", "by_login", "read_at", "failures"]))));
}
});
@@ -125,7 +125,7 @@ export async function markGateFailures(db: Db, keys: RefKey[]): Promise<void> {
const q = queryDb(db);
await db.write(async () => {
for (const part of kx.batches([...counts])) {
await db.run(q.k.insertInto("review_gates").values(part.map(([k, n]) => ({ ...splitKey(k), failures: n })))
await q.run(q.k.insertInto("review_gates").values(part.map(([k, n]) => ({ ...splitKey(k), failures: n })))
.onConflict((oc) => oc.columns(["repo", "number"]).doUpdateSet((eb) => ({ failures: eb("review_gates.failures", "+", eb.ref("excluded.failures")) }))));
}
});
@@ -163,7 +163,7 @@ export async function saveDiffFacts(db: Db, rows: DiffFactsRow[], mode: "upsert-
await db.write(async () => {
for (const part of kx.batches(last)) {
const ins = q.k.insertInto("diff_facts").values(part.map((r) => ({ repo: r.repo, number: r.number, head_oid: r.head_oid, reasons: r.reasons, lines: r.lines, pending: r.pending, last_read: r.last_read })));
await db.run(mode === "insert-ignore" ? ins.onConflict((oc) => oc.columns(["repo", "number", "head_oid"]).doNothing())
await q.run(mode === "insert-ignore" ? ins.onConflict((oc) => oc.columns(["repo", "number", "head_oid"]).doNothing())
: ins.onConflict((oc) => oc.columns(["repo", "number", "head_oid"]).doUpdateSet(kx.excluded(["reasons", "lines", "pending", "last_read"]))
.where((eb) => eb.or(["reasons", "lines", "pending", "last_read"].map((c) => eb(`diff_facts.${c}` as "diff_facts.lines", "is distinct from", eb.ref(`excluded.${c}` as "excluded.lines")))))));
}
@@ -181,7 +181,7 @@ export async function setDiffFactsIf(db: Db, rows: { key: DiffFactsKey; was: Dif
let changed = 0;
const fresh = rows.filter((r) => !r.was).map((r) => r.to);
for (const part of kx.batches(fresh)) {
changed += (await db.run(q.k.insertInto("diff_facts").values(part.map((r) => ({ repo: r.repo, number: r.number, head_oid: r.head_oid, reasons: r.reasons, lines: r.lines, pending: r.pending, last_read: r.last_read })))
changed += (await q.run(q.k.insertInto("diff_facts").values(part.map((r) => ({ repo: r.repo, number: r.number, head_oid: r.head_oid, reasons: r.reasons, lines: r.lines, pending: r.pending, last_read: r.last_read })))
.onConflict((oc) => oc.columns(["repo", "number", "head_oid"]).doNothing()))).changes;
}
const guarded = rows.filter((r) => r.was).map((r) => ({
@@ -190,7 +190,7 @@ export async function setDiffFactsIf(db: Db, rows: { key: DiffFactsKey; was: Dif
}));
for (const part of kx.chunks(guarded)) {
const v = kx.valuesTable(db, part, { repo: "text", number: "bigint", head_oid: "text", reasons: "text", lines: "bigint", pending: "bigint", last_read: "bigint", w_reasons: "text", w_lines: "bigint", w_pending: "bigint", w_last_read: "bigint" }, "v");
changed += (await db.run((q.k.updateTable("diff_facts") as any).from(v)
changed += (await q.run((q.k.updateTable("diff_facts") as any).from(v)
.set((eb: kx.AnyEb) => ({ reasons: eb.ref("v.reasons"), lines: eb.ref("v.lines"), pending: eb.ref("v.pending"), last_read: eb.ref("v.last_read") }))
.where((eb: kx.AnyEb) => eb.and([
eb("diff_facts.repo", "=", eb.ref("v.repo")), eb("diff_facts.number", "=", eb.ref("v.number")), eb("diff_facts.head_oid", "=", eb.ref("v.head_oid")),
@@ -206,12 +206,12 @@ export async function setDiffFactsIf(db: Db, rows: { key: DiffFactsKey; was: Dif
export async function markDiffRead(db: Db, heads: DiffFactsKey[], at: number): Promise<void> {
if (!heads.length) return;
const q = queryDb(db);
await db.write(async () => { for (const c of kx.chunks(heads)) await db.run(q.k.updateTable("diff_facts").set({ last_read: at }).where(headIn(db, "diff_facts", c))); });
await db.write(async () => { for (const c of kx.chunks(heads)) await q.run(q.k.updateTable("diff_facts").set({ last_read: at }).where(headIn(db, "diff_facts", c))); });
}
/** Batched delete. */
export async function removeDiffFacts(db: Db, heads: DiffFactsKey[]): Promise<void> {
if (!heads.length) return;
const q = queryDb(db);
await db.write(async () => { for (const c of kx.chunks(heads)) await db.run(q.k.deleteFrom("diff_facts").where(headIn(db, "diff_facts", c))); });
await db.write(async () => { for (const c of kx.chunks(heads)) await q.run(q.k.deleteFrom("diff_facts").where(headIn(db, "diff_facts", c))); });
}
+7 -7
View File
@@ -73,7 +73,7 @@ export async function applyLocal(db: Db, patches: LocalPatch[]): Promise<{ chang
const moved = base.filter((p) => was.has(refKey(p.repo, p.number)) && was.get(refKey(p.repo, p.number)) !== p.baseRef);
const dropped = base.filter((p) => !p.keepDiff);
if (dropped.length) {
for (const c of kx.chunks(dropped)) await db.run(q.k.deleteFrom("main.diff_facts").where(kx.tupleIn(db, ["repo", "number", "head_oid"], c.map((p) => [p.repo, p.number, p.head] as const), ["text", "bigint", "text"])));
for (const c of kx.chunks(dropped)) await q.run(q.k.deleteFrom("main.diff_facts").where(kx.tupleIn(db, ["repo", "number", "head_oid"], c.map((p) => [p.repo, p.number, p.head] as const), ["text", "bigint", "text"])));
}
if (moved.length) {
add(await updateItemsFrom(db, moved.map((p) => ({ repo: p.repo, number: p.number, base: p.baseRef })), { ...ONE, base: "text" }, (eb) => ({ base_ref: eb.ref("v.base") })));
@@ -156,7 +156,7 @@ export async function saveItems(db: Db, entries: ItemEntry[], o: SaveItemsOption
return !s || !ITEM_COLUMNS.every((c) => (s[c] ?? null) === ((e.row as Record<string, unknown>)[c] ?? null));
});
if (changed.length) {
await db.run(q.k.insertInto("main.items").values(changed.map((e) => Object.fromEntries(ITEM_COLUMNS.map((c) => [c, (e.row as Record<string, unknown>)[c] ?? null])) as never))
await q.run(q.k.insertInto("main.items").values(changed.map((e) => Object.fromEntries(ITEM_COLUMNS.map((c) => [c, (e.row as Record<string, unknown>)[c] ?? null])) as never))
.onConflict((oc) => oc.columns(["repo", "number"]).doUpdateSet((eb) => ({ ...kx.excluded(ITEM_UPSERT)(eb), mergeable: keepKnownMergeableExpr(eb, "items") }))));
stored += changed.length;
// After the upsert, which clears the stored refs of a row whose text was written (schema trigger items_text_refs_stale).
@@ -171,18 +171,18 @@ export async function saveItems(db: Db, entries: ItemEntry[], o: SaveItemsOption
const unbound = new Set((await q.all(q.k.selectFrom("main.items").select("author").distinct().where(kx.inList(db, "author", [...ids.keys()]))
.where("kind", "=", "pr").where("state", "in", ["MERGED", "CLOSED"]).where("author_id", "is", null), { label: "mirror.saveItems" })).map((r) => r.author));
const bind = [...ids].filter(([login]) => !unbound.has(login)).map(([login, id]) => ({ login, id }));
for (const b of kx.batches(bind)) await db.run(q.k.insertInto("main.author_ids").values(b).onConflict((oc) => oc.doNothing()));
for (const b of kx.batches(bind)) await q.run(q.k.insertInto("main.author_ids").values(b).onConflict((oc) => oc.doNothing()));
}
const full = changed.filter((e) => e.detail === "full");
if (full.length) {
const comments = [...new Map(full.flatMap((e) => e.comments).map((c) => [c.id, c])).values()];
// A forced re-read of an unchanged item upserts in place: an identical comment bumps no topic. Comments the read no longer lists go.
if (o.force) await db.run(q.k.deleteFrom("main.comments").where(isRef(full)).where((eb) => eb.not(kx.tupleIn(db, ["repo", "number", "id"], full.flatMap((e) => e.comments.map((c) => [e.repo, e.row.number, c.id] as const)), ["text", "bigint", "text"]))));
else await db.run(q.k.deleteFrom("main.comments").where(isRef(full)));
for (const b of kx.batches(comments)) await db.run(q.k.insertInto("main.comments").values(b as never).onConflict((oc) => oc.column("id").doUpdateSet(kx.excluded(COMMENT_UPSERT))));
if (o.force) await q.run(q.k.deleteFrom("main.comments").where(isRef(full)).where((eb) => eb.not(kx.tupleIn(db, ["repo", "number", "id"], full.flatMap((e) => e.comments.map((c) => [e.repo, e.row.number, c.id] as const)), ["text", "bigint", "text"]))));
else await q.run(q.k.deleteFrom("main.comments").where(isRef(full)));
for (const b of kx.batches(comments)) await q.run(q.k.insertInto("main.comments").values(b as never).onConflict((oc) => oc.column("id").doUpdateSet(kx.excluded(COMMENT_UPSERT))));
}
if (current.length) {
await db.run(q.k.insertInto("main.item_reads").values(current.map((e) => ({ repo: e.repo, number: e.row.number, synced_at: readAt(e) })))
await q.run(q.k.insertInto("main.item_reads").values(current.map((e) => ({ repo: e.repo, number: e.row.number, synced_at: readAt(e) })))
.onConflict((oc) => oc.columns(["repo", "number"]).doUpdateSet(kx.excluded(["synced_at"]))
.where((eb) => eb(eb.fn<number>("julianday", [eb.ref("excluded.synced_at")]), ">=", eb.fn<number>("julianday", [eb.ref("main.item_reads.synced_at")])))));
}
+2 -1
View File
@@ -1,8 +1,9 @@
// Predicates other modules embed.
import { sql, type Expression, type RawBuilder, type SelectQueryBuilder, type SqlBool } from "kysely";
import type { Expression, RawBuilder, SelectQueryBuilder, SqlBool } from "kysely";
import type { Db } from "../../db/index.ts";
import { queryDb } from "../../db/query-db.ts";
import { exprOf, ref, schemaEb, type AnyEb, type Eb, type Ex } from "../../db/kx.ts";
import { sql } from "../../db/sql.ts";
import { earlierRunCall as jobsEarlierRunCall, resumingJobs } from "../jobs/fragments.ts";
+1 -1
View File
@@ -2,10 +2,10 @@
import type { Db } from "../../db/index.ts";
import * as kx from "../../db/kx.ts";
import { queryDb } from "../../db/query-db.ts";
import { sql } from "../../db/sql.ts";
// reads: control.hiddenRepos (fragment, tracked_repos hidden list)
import { hiddenRepos } from "../control/fragments.ts";
import { jobsOfItems, liveJobOfFinding } from "../jobs/fragments.ts";
import { sql } from "kysely";
import { briefCols, nowIso, severityRank } from "./internal.ts";
import {
ENV_WAIT_NOTE, INTERNAL_FINDING_STATES, TRANSITIONS, findingKey,
+9 -7
View File
@@ -5,6 +5,7 @@ import type { Expression, SelectQueryBuilder, SqlBool } from "kysely";
import { GITHUB_ACTIONS } from "../../github/actions.ts";
import type { Db } from "../../db/index.ts";
import * as kx from "../../db/kx.ts";
import { queryDb, type QueryDb } from "../../db/query-db.ts";
import { privateStepExpr } from "../build/fragments.ts";
import { runVisible } from "../inference/fragments.ts";
import type { Scope, TraceKind } from "./types.ts";
@@ -22,14 +23,14 @@ const T = "t";
type Def = {
id: SourceId; kinds: TraceKind[]; table: string; time: string;
q: (db: Db, c: Ctx) => SelectQueryBuilder<any, any, any>;
q: (db: QueryDb, c: Ctx) => SelectQueryBuilder<any, any, any>;
repoCol?: string | null; tie?: () => kx.Ex; one?: (r: any) => string;
/** With Only AutoCraft: null skips the source (its events are people's), a condition narrows it to AutoCraft's rows, EVERY means every row is AutoCraft's. */
only?: (c: Ctx) => Cond | null;
/** Rows without a repo column (audit targets) name their item here; null drops the row. */
of?: (r: any, c: Ctx) => { repo: string; number: number } | null;
};
type Ctx = ActivityScope & { db: Db; only: boolean; repo: string | null; limit: number; before: ActivityQuery["before"]; writeActions: string[] | null };
type Ctx = ActivityScope & { db: QueryDb; only: boolean; repo: string | null; limit: number; before: ActivityQuery["before"]; writeActions: string[] | null };
const byOwn = (col: string): Def["only"] => (c) => (c.own.size ? () => kx.inList(c.db, col, [...c.own]) : null);
@@ -126,17 +127,18 @@ async function newest(c: Ctx, s: Def): Promise<{ source: SourceId; rows: Activit
/** One round: every wanted source's newest rows before the cursor, in one wave. */
export async function loadActivityRound(db: Db, scope: ActivityScope, q: ActivityQuery): Promise<ActivityRows> {
const c: Ctx = { ...scope, db, only: q.only, repo: q.repo, limit: q.limit, before: q.before, writeActions: q.writeActions };
const c: Ctx = { ...scope, db: queryDb(db), only: q.only, repo: q.repo, limit: q.limit, before: q.before, writeActions: q.writeActions };
return { bySource: await db.together(() => Promise.all(sourcesOf(q.kinds).map((s) => newest(c, s)))) };
}
/** The newest time of each wanted source's table and the counts of running calls, active jobs and active tasks, in one statement. */
export async function loadActivityStamp(db: Db, key: ActivityStampKey): Promise<unknown[]> {
const { k } = queryDb(db);
const probes = [
...sourcesOf(key.kinds).map((s) => db.k.selectFrom(s.table as "items").select((eb) => eb.fn.max<string | null>(kx.ref(s.time.replace(/^\w+\./, ""))).as("m"))),
db.k.selectFrom("agent_runs").select((eb) => eb.fn.countAll<number>().as("n")).where("state", "=", "running"),
db.k.selectFrom("jobs").select((eb) => [eb.fn.countAll<number>().as("n"), eb.fn.max<number | null>("id").as("newest")]).where("state", "in", ["queued", "running"]),
db.k.selectFrom("build_tasks").select((eb) => eb.fn.countAll<number>().as("n")).where("state", "in", ["queued", "claimed", "running"]),
...sourcesOf(key.kinds).map((s) => k.selectFrom(s.table as "items").select((eb) => eb.fn.max<string | null>(kx.ref(s.time.replace(/^\w+\./, ""))).as("m"))),
k.selectFrom("agent_runs").select((eb) => eb.fn.countAll<number>().as("n")).where("state", "=", "running"),
k.selectFrom("jobs").select((eb) => [eb.fn.countAll<number>().as("n"), eb.fn.max<number | null>("id").as("newest")]).where("state", "in", ["queued", "running"]),
k.selectFrom("build_tasks").select((eb) => eb.fn.countAll<number>().as("n")).where("state", "in", ["queued", "claimed", "running"]),
];
return (await kx.rowValues(db, probes as SelectQueryBuilder<any, any, any>[]));
}
+4 -2
View File
@@ -2,6 +2,7 @@
import type { Expression, SqlBool } from "kysely";
import type { Db, Param } from "../../db/index.ts";
import * as kx from "../../db/kx.ts";
import { queryDb } from "../../db/query-db.ts";
type Types = Record<string, kx.ElemType>;
@@ -14,12 +15,13 @@ export async function patchRows(
db: Db, table: string, key: Types, set: Types, rows: readonly Record<string, Param>[],
o: { also?: (eb: kx.AnyEb) => Record<string, Expression<any>>; when?: (eb: kx.AnyEb) => Expression<SqlBool>; guard?: Types } = {},
): Promise<number> {
const qdb = queryDb(db);
let changed = 0;
for (const part of kx.chunks(rows)) {
const q = (db as any).k.updateTable(table).from(kx.valuesTable(db, part, { ...key, ...set, ...o.guard }, "v"))
const q = (qdb.k as any).updateTable(table).from(kx.valuesTable(db, part, { ...key, ...set, ...o.guard }, "v"))
.set((eb: kx.AnyEb) => ({ ...Object.fromEntries(Object.keys(set).map((c) => [c, eb.ref(`v.${c}`)])), ...o.also?.(eb) }))
.where((eb: kx.AnyEb) => eb.and([...Object.keys(key).map((c) => eb(`${table}.${c}`, "=", eb.ref(`v.${c}`))), ...(o.when ? [o.when(eb)] : [])]));
changed += (await db.run(q)).changes;
changed += (await qdb.run(q)).changes;
}
return changed;
}
+116
View File
@@ -0,0 +1,116 @@
// Which reads return bytes. A fused wave (Db.together on Postgres) carries its rows as JSON, where a bytea column arrives
// as hex text instead of bytes, so the handle refuses such a read in a wave unless it is marked `alone`.
import type { OperationNode, SelectQueryNode } from "kysely";
import { BYTES_COLUMNS } from "./types.ts";
const BYTES = new Set<string>(BYTES_COLUMNS);
// Nodes are read as plain objects: this module must not load kysely.
type N = { readonly kind: string } & Record<string, any>;
/** One FROM entry: the name its columns go by, and its bytes columns under their output names (`of` says where they come from). */
type Source = { name: string; of: (column: string) => string | null; all: () => string | null };
const NONE: Source = { name: "", of: () => null, all: () => null };
/** Functions that return one of their arguments as it is. */
const PASSES = new Set(["coalesce", "max", "min", "nullif"]);
const tableName = (n: N): string => n.table.identifier.name as string;
function tableSource(table: string, name: string): Source {
const of = (c: string): string | null => (BYTES.has(`${table}.${c}`) ? `${table}.${c}` : null);
return { name, of, all: () => BYTES_COLUMNS.find((b) => b.startsWith(`${table}.`)) ?? null };
}
/** A subquery or CTE: its outputs that are bytes, by output name. */
function querySource(q: N, name: string, outer: readonly Source[], ctes: readonly Source[]): Source {
const out = outputs(q, outer, ctes);
return { name, of: (c) => out.get(c) ?? null, all: () => out.values().next().value ?? null };
}
function sourceOf(n: N, outer: readonly Source[], ctes: readonly Source[], alias?: string): Source {
if (n.kind === "AliasNode") return sourceOf(n.node, outer, ctes, n.alias?.name ?? alias);
if (n.kind === "ParensNode") return sourceOf(n.node, outer, ctes, alias);
if (n.kind === "TableNode") {
const table = tableName(n);
const cte = n.table.schema ? undefined : ctes.find((c) => c.name === table);
return cte ? { ...cte, name: alias ?? table } : tableSource(table, alias ?? table);
}
if (n.kind === "SelectQueryNode") return querySource(n, alias ?? "", outer, ctes);
return { ...NONE, name: alias ?? "" };
}
/** The bytes column an expression returns as it is, or null. Raw SQL with text of its own is taken to transform it. */
function bytesOf(n: N, sources: readonly Source[], ctes: readonly Source[]): string | null {
switch (n.kind) {
case "AliasNode": case "ParensNode": return bytesOf(n.node, sources, ctes);
case "SelectionNode": return bytesOf(n.selection, sources, ctes);
case "ColumnNode": return first(sources, (s) => s.of(n.column.name));
case "ReferenceNode": {
const from = n.table ? sources.filter((s) => s.name === tableName(n.table)) : sources;
return n.column.kind === "SelectAllNode" ? first(from, (s) => s.all()) : first(from, (s) => s.of(n.column.column.name));
}
case "SelectAllNode": return first(sources, (s) => s.all());
case "FunctionNode": return PASSES.has(String(n.func).toLowerCase()) ? first(n.arguments as N[], (a) => bytesOf(a, sources, ctes)) : null;
case "CaseNode": return first([...(n.when ?? []).map((w: N) => w.result), n.else].filter(Boolean) as N[], (a) => (a.kind ? bytesOf(a, sources, ctes) : null));
case "RawNode": return (n.sqlFragments as string[]).every((f) => !f.trim()) ? first(n.parameters as N[], (a) => bytesOf(a, sources, ctes)) : null;
case "SelectQueryNode": return outputs(n, sources, ctes).values().next().value ?? null;
default: return null;
}
}
function first<T>(xs: readonly T[], f: (x: T) => string | null): string | null {
for (const x of xs) {
const r = f(x);
if (r) return r;
}
return null;
}
const nameOf = (n: N): string => {
if (n.kind === "SelectionNode") return nameOf(n.selection);
if (n.kind === "AliasNode") return n.alias?.name ?? "";
if (n.kind === "ReferenceNode") return n.column?.column?.name ?? "";
return n.kind === "ColumnNode" ? n.column.name : "";
};
/** The bytes columns `q` returns, by output name ("*" for those of a select-all). */
function outputs(q: N, outer: readonly Source[], outerCtes: readonly Source[]): Map<string, string> {
const ctes = [...outerCtes];
for (const e of (q.with?.expressions ?? []) as N[]) ctes.unshift(querySource(e.expression, e.name.table.table.identifier.name, outer, ctes));
const out = new Map<string, string>();
if (q.kind !== "SelectQueryNode") return out;
const own = [...((q.from?.froms ?? []) as N[]).map((f) => sourceOf(f, outer, ctes)), ...((q.joins ?? []) as N[]).map((j) => sourceOf(j.table, outer, ctes))];
const sources = [...own, ...outer];
for (const s of (q.selections ?? []) as N[]) {
const star = s.selection?.kind === "SelectAllNode" || s.selection?.column?.kind === "SelectAllNode";
if (star) {
// Every bytes column of the sources, under its own name.
const from = s.selection.table ? own.filter((x) => x.name === tableName(s.selection.table)) : own;
for (const b of BYTES) {
const c = b.slice(b.indexOf(".") + 1);
const hit = first(from, (x) => x.of(c));
if (hit) out.set(c, hit);
}
continue;
}
const b = bytesOf(s, sources, ctes);
if (b) out.set(nameOf(s) || "*", b);
}
for (const s of (q.setOperations ?? []) as N[]) for (const [c, b] of outputs(s.expression, outer, ctes)) out.set(c, b);
return out;
}
/** Most statements whose answer is kept: their texts, which the parameters are not part of. */
const CACHE_MAX = 5_000;
const cache = new Map<string, string | null>();
/** The bytes column (`table.column`) among what the read `node` returns, or null; `sql` is its compiled text. */
export function bytesRead(node: SelectQueryNode, sql: string): string | null {
let r = cache.get(sql);
if (r === undefined) {
r = outputs(node as OperationNode as N, [], []).values().next().value ?? null;
if (cache.size >= CACHE_MAX) cache.clear();
cache.set(sql, r);
}
return r;
}
+20 -19
View File
@@ -13,9 +13,10 @@ import { existsSync, rmSync } from "node:fs";
import { DatabaseSync } from "node:sqlite";
import { gunzipSync, gzipSync } from "node:zlib";
import { planChangesSql } from "./plan-triggers.ts";
import type { Db, Param, Row, Value } from "./index.ts";
import type { Param, Row, Value } from "./index.ts";
import { connect } from "../db.ts";
import { connectDb, dbFor, isPgUrl, loadPg } from "./open.ts";
import { queryDb, type QueryDb } from "./query-db.ts";
import { MIGRATION_LOCK_KEY, pgSchemaSql } from "./pg-migrate.ts";
import { migratePg } from "./pg-triggers.ts";
import { pgConnectionString } from "./postgres.ts";
@@ -61,7 +62,7 @@ interface Table {
}
interface Side {
db: Db;
db: QueryDb;
label: string;
tables: Map<string, Table>;
}
@@ -76,7 +77,7 @@ export function describeTarget(target: string): string {
return u.toString();
}
async function sqliteTables(db: Db): Promise<Map<string, Table>> {
async function sqliteTables(db: QueryDb): Promise<Map<string, Table>> {
const out = new Map<string, Table>();
const list = (await db.prepare("PRAGMA main.table_list").all()) as { name: string; type: string; wr: number }[];
for (const t of list) {
@@ -102,7 +103,7 @@ async function sqliteTables(db: Db): Promise<Map<string, Table>> {
return out;
}
async function pgTables(db: Db): Promise<Map<string, Table>> {
async function pgTables(db: QueryDb): Promise<Map<string, Table>> {
const cols = (await db.prepare(`SELECT c.relname AS t, a.attname AS c, a.attgenerated AS gen, format_type(a.atttypid, a.atttypmod) AS type
FROM pg_class c JOIN pg_attribute a ON a.attrelid = c.oid
WHERE c.relnamespace = current_schema()::regnamespace AND c.relkind = 'r' AND a.attnum > 0 AND NOT a.attisdropped
@@ -130,16 +131,16 @@ async function pgTables(db: Db): Promise<Map<string, Table>> {
return out;
}
const tablesOf = (db: Db): Promise<Map<string, Table>> => (db.dialect === "postgres" ? pgTables(db) : sqliteTables(db));
const tablesOf = (db: QueryDb): Promise<Map<string, Table>> => (db.dialect === "postgres" ? pgTables(db) : sqliteTables(db));
async function openSide(target: string, opts: { readOnly: boolean }): Promise<Side> {
let db: Db;
let db: QueryDb;
// Postgres opens as it is: the target gets its triggers after the rows are in, and a source is never migrated.
if (isPgUrl(target)) db = await connectDb(target, { role: "cli", migrate: false });
if (isPgUrl(target)) db = queryDb(await connectDb(target, { role: "cli", migrate: false }));
else if (opts.readOnly) {
if (!existsSync(target)) throw new Error(`no SQLite database at ${target}`);
db = await dbFor(new DatabaseSync(target, { readOnly: true }));
} else db = await dbFor(connect(target)); // The file itself, also where a test hook makes connectDb open Postgres for a path.
db = queryDb(await dbFor(new DatabaseSync(target, { readOnly: true })));
} else db = queryDb(await dbFor(connect(target))); // The file itself, also where a test hook makes connectDb open Postgres for a path.
return { db, label: describeTarget(target), tables: new Map() };
}
@@ -196,7 +197,7 @@ function matchTables(a: Pick<Side, "label" | "tables">, b: Pick<Side, "label" |
}
/** The table's rows in key order, `batch` at a time. Inside a db.read every page comes from one snapshot. */
async function* pages(db: Db, t: Table, batch: number): AsyncGenerator<Row[]> {
async function* pages(db: QueryDb, t: Table, batch: number): AsyncGenerator<Row[]> {
const sqlite = db.dialect === "sqlite";
const keyRef = (k: string) => (sqlite && k === "rowid" && !t.select.includes(qi("rowid")) ? "rowid" : qi(k));
const keys = t.key.map(keyRef);
@@ -285,7 +286,7 @@ async function copyTable(src: Side, dst: Side, from: Table, to: Table, batch: nu
* The last key handed out per table, where the backend keeps a counter: SQLite AUTOINCREMENT tables (the larger of
* sqlite_sequence and the largest rowid), Postgres identity sequences (0 before the first value).
*/
async function sequences(db: Db): Promise<Map<string, number>> {
async function sequences(db: QueryDb): Promise<Map<string, number>> {
const out = new Map<string, number>();
if (db.dialect === "sqlite") {
const auto = (await db.prepare("SELECT name FROM main.sqlite_master WHERE type = 'table' AND sql LIKE '%AUTOINCREMENT%'").all()) as { name: string }[];
@@ -301,7 +302,7 @@ async function sequences(db: Db): Promise<Map<string, number>> {
return out;
}
async function pgIdentities(db: Db): Promise<{ t: string; col: string; seq: string; v: number | null }[]> {
async function pgIdentities(db: QueryDb): Promise<{ t: string; col: string; seq: string; v: number | null }[]> {
return (await db.prepare(`SELECT c.relname AS t, a.attname AS col, s.seq,
(SELECT p.last_value FROM pg_sequences p WHERE format('%I.%I', p.schemaname, p.sequencename) = s.seq) AS v
FROM pg_class c JOIN pg_attribute a ON a.attrelid = c.oid
@@ -311,7 +312,7 @@ async function pgIdentities(db: Db): Promise<{ t: string; col: string; seq: stri
}
/** Sets each identity sequence of the copied tables past the copied keys and the source's own counter. */
async function setPgSequences(db: Db, copied: Set<string>, source: Map<string, number>): Promise<void> {
async function setPgSequences(db: QueryDb, copied: Set<string>, source: Map<string, number>): Promise<void> {
await db.write(async () => {
for (const { t, col, seq } of await pgIdentities(db)) {
if (!copied.has(t)) continue;
@@ -324,7 +325,7 @@ async function setPgSequences(db: Db, copied: Set<string>, source: Map<string, n
}
/** Sets sqlite_sequence of the copied AUTOINCREMENT tables to at least the source's counter. */
async function setSqliteSequences(db: Db, copied: Set<string>, source: Map<string, number>): Promise<void> {
async function setSqliteSequences(db: QueryDb, copied: Set<string>, source: Map<string, number>): Promise<void> {
const auto = (await db.prepare("SELECT name FROM main.sqlite_master WHERE type = 'table' AND sql LIKE '%AUTOINCREMENT%'").all()) as { name: string }[];
await db.write(async () => {
for (const { name } of auto) {
@@ -372,7 +373,7 @@ async function migratePgTarget(url: string): Promise<void> {
}
}
async function hasRows(db: Db, tables: Iterable<string>): Promise<string | undefined> {
async function hasRows(db: QueryDb, tables: Iterable<string>): Promise<string | undefined> {
for (const t of tables) if (await db.prepare(`SELECT 1 AS x FROM ${qi(t)} LIMIT 1`).get()) return t;
return undefined;
}
@@ -418,7 +419,7 @@ async function prepareTarget(target: string, replace: boolean, match: (tables: M
const probe = new DatabaseSync(target, { readOnly: true });
let full: string | undefined;
try {
const pdb = await dbFor(probe);
const pdb = queryDb(await dbFor(probe));
full = await hasRows(pdb, (await sqliteTables(pdb)).keys());
} finally {
probe.close();
@@ -451,7 +452,7 @@ async function prepareTarget(target: string, replace: boolean, match: (tables: M
* read here and written back by the returned function after the copy, under new rowids, since the copied rows bring
* theirs and may take the old ones.
*/
async function clearTables(db: Db, tables: string[]): Promise<() => Promise<void>> {
async function clearTables(db: QueryDb, tables: string[]): Promise<() => Promise<void>> {
const kept: { table: string; rows: Row[] }[] = [];
if (!tables.length) return async () => undefined;
await db.write(async () => {
@@ -473,7 +474,7 @@ async function clearTables(db: Db, tables: string[]): Promise<() => Promise<void
});
}
async function finishSqlite(db: Db, triggers: string[]): Promise<void> {
async function finishSqlite(db: QueryDb, triggers: string[]): Promise<void> {
const sync = db.sync;
if (!sync) throw new Error("SQLite target without a connection");
const fts = (await db.prepare("SELECT name FROM main.sqlite_master WHERE type = 'table' AND sql LIKE 'CREATE VIRTUAL TABLE%fts5%'").all()) as { name: string }[];
@@ -605,7 +606,7 @@ export interface TableDigest {
* The table's row count and digest. Rows hash as canonical JSON with columns in name order; the table digest is over the
* sorted row digests, so it does not depend on how each backend orders equal-looking keys (citext against NOCASE).
*/
async function digestTable(db: Db, t: Table, batch: number): Promise<TableDigest> {
async function digestTable(db: QueryDb, t: Table, batch: number): Promise<TableDigest> {
const cols = [...t.columns].sort();
const rowHashes: Buffer[] = [];
for await (const page of pages(db, t, batch)) {
+20 -14
View File
@@ -1,12 +1,12 @@
// External effects (GitHub calls, model calls, build launches, child processes, HTTP) as the database sees them: each is
// counted in the current `db.meter`, and one made inside a database transaction is reported, since a transaction holds
// its locks (and on Postgres a snapshot) while the effect waits on the network.
import { callSite, Handle, siteError } from "./handle.ts";
import type { Db } from "./index.ts";
// counted in the current `db.meter`, and one made inside a database transaction or a `together` wave is refused in tests
// and counted in production, since a transaction holds its locks (and on Postgres a snapshot) while the effect waits on
// the network, and a wave's callers expect database time only.
import { busyScopes, callSite, siteError, testing } from "./handle.ts";
export type EffectKind = "github-write" | "github-read" | "model-call" | "build-launch" | "process" | "http";
/** How often one site's effect inside a transaction is logged again. */
/** How often one site's effect inside a transaction or wave is logged again. */
const LOG_EVERY_MS = 60 * 60 * 1000;
/** Most sites kept: they are code locations, so a few dozen at most. */
const MAX_SITES = 200;
@@ -22,14 +22,20 @@ let inTxCount = 0;
const inTxSites = new Map<string, { kind: EffectKind; count: number; lastAt: number; loggedAt: number }>();
/**
* Tells the database layer that the caller is about to make an external effect on behalf of work on `db`. Call it before
* the effect's first await, in the wrapper that makes it. It counts the effect in the current `db.meter`. Inside a
* transaction it counts the call site (`effectsInTx`) and logs it, once per site per hour.
* Tells the database layer that the caller is about to make an external effect. Call it before the effect's first await,
* in the wrapper that makes it. It counts the effect in the meters of the current async context, on every handle (a child
* process is local work and not counted). Inside a transaction or a `together` wave it throws in tests; in production it
* counts the call site (`effectsInTx`) and logs it, once per site per hour.
*/
export function effect(db: Db, kind: EffectKind, site?: string): void {
if (db instanceof Handle) db.noteEffect();
if (!db.inTransaction()) return;
const where = site ?? callSite(siteError());
export function effect(kind: EffectKind, site?: string): void {
const scope = busyScopes(kind !== "process");
if (scope) note(kind, scope, site ?? callSite(siteError()), testing());
}
/** What `effect` does inside `scope`; `strict` is whether it throws. */
export function note(kind: EffectKind, scope: string, where: string, strict: boolean): void {
const what = `effect "${kind}" inside ${scope} (${where})`;
if (strict) throw new Error(`db: ${what}: make it before or after, with a guard read and a write of its own`);
const now = Date.now();
inTxCount++;
let s = inTxSites.get(where);
@@ -39,10 +45,10 @@ export function effect(db: Db, kind: EffectKind, site?: string): void {
s.lastAt = now;
if (now - s.loggedAt < LOG_EVERY_MS) return;
s.loggedAt = now;
console.warn(`db: effect "${kind}" inside a database transaction (${where})`);
console.warn(`db: ${what}`);
}
/** Effects this process made inside a database transaction: the total and each site, for the health checks. */
/** Effects this process made inside a database transaction or wave: the total and each site, for the health checks. */
export function effectsInTx(): { count: number; sites: EffectInTx[] } {
return { count: inTxCount, sites: [...inTxSites].map(([site, s]) => ({ site, kind: s.kind, count: s.count, lastAt: s.lastAt })) };
}
+3 -1
View File
@@ -4,6 +4,7 @@
// AUTOCRAFT_FENCE, so a job's writes are fenced with its runner's.
import { envVar } from "../env.ts";
import type { Db } from "./index.ts";
import { queryDb } from "./query-db.ts";
export type LeaderRole = "runner" | "periodic";
export const LEADER_ROLES: readonly LeaderRole[] = ["runner", "periodic"];
@@ -58,6 +59,7 @@ export class FencedError extends Error {
export async function assertFence(db: Db): Promise<void> {
const f = currentFence();
if (!f || db.dialect !== "postgres") return;
const r = await db.get(db.k.selectFrom("leader_leases").select("epoch").where("role", "=", f.role));
const q = queryDb(db);
const r = await q.get(q.k.selectFrom("leader_leases").select("epoch").where("role", "=", f.role));
if (r === undefined || Number(r.epoch) !== f.epoch) throw new FencedError(`this process no longer leads the ${f.role}: another copy took over`);
}
+38 -10
View File
@@ -3,6 +3,7 @@
import { AsyncLocalStorage } from "node:async_hooks";
import type { Compilable, CompiledQuery, DatabaseConnection, Kysely, OperationNode, OperationNodeSource, SelectQueryNode, TransactionBuilder } from "kysely";
import type { DatabaseSync } from "node:sqlite";
import { bytesRead } from "./bytes-read.ts";
import type { DB, DbEvent, DbStats, Dialect, NamedParams, Param, QueryOpts, Row, RunResult, Statement, Subscription, WriteOptions } from "./index.ts";
import type { QueryDb } from "./query-db.ts";
@@ -123,8 +124,29 @@ export function withoutInsertId(changes: number): RunResult {
}) as RunResult;
}
/** Whether a call that outlived its transaction throws (tests) or falls back to autocommit with a warning. */
const strayThrows = (): boolean => process.env.NODE_TEST_CONTEXT !== undefined;
/** Whether this process runs under the test runner, where a misuse throws; in production it is logged instead. */
export const testing = (): boolean => process.env.NODE_TEST_CONTEXT !== undefined;
/** The handles with a meter, a transaction or a `together` scope open, with how many: the ones an effect may concern. */
const busy = new Map<Handle, number>();
async function whileBusy<T>(h: Handle, fn: () => Promise<T>): Promise<T> {
busy.set(h, (busy.get(h) ?? 0) + 1);
try {
return await fn();
} finally {
const n = busy.get(h)! - 1;
if (n) busy.set(h, n);
else busy.delete(h);
}
}
/** The transaction or `together` wave open in this async context, on any handle, as text; `count` counts an effect in its meters. */
export function busyScopes(count: boolean): string | undefined {
let scope: string | undefined;
for (const h of busy.keys()) scope = h.effectScope(count) ?? scope;
return scope;
}
/** The most statements one shareReads scope keeps. */
const SHARED_READS_MAX = 2000;
@@ -232,7 +254,7 @@ export class Handle implements QueryDb {
const tx = this.#als.getStore();
if (!tx || tx.state !== "closed") return tx?.state === "open" ? tx : undefined;
const msg = "database call after its transaction ended: a promise started inside db.write/db.read was left running";
if (strayThrows()) throw new Error(msg);
if (testing()) throw new Error(msg);
const site = callSite(siteError());
if (!this.#warned.has(site)) {
this.#warned.add(site);
@@ -305,6 +327,10 @@ export class Handle implements QueryDb {
}
// A locking read (FOR UPDATE) or an EXPLAIN cannot be a subquery.
const alone = !!o?.alone || !!node.endModifiers?.length || !!node.explain;
if (!alone && (this.#engine.fuse || testing())) {
const bytes = bytesRead(node, c.sql);
if (bytes) throw new Error(`${o?.label ? `${o.label}: ` : ""}a read of bytes (${bytes}) inside db.together must be marked \`alone\`: a fused wave would return them as hex text`);
}
const site = this.#observers.size ? (o?.label ?? callSite(siteError())) : undefined;
const members = wave.members;
return new Promise((resolve, reject) => members.push({ node, c, alone, label: o?.label, site, resolve, reject }));
@@ -474,7 +500,7 @@ export class Handle implements QueryDb {
if (this.#together.getStore()?.open) return await fn();
const store: Together = { open: true, waves: new Map() };
try {
return await this.#together.run(store, fn);
return await whileBusy(this, () => this.#together.run(store, fn));
} finally {
store.open = false;
}
@@ -484,7 +510,7 @@ export class Handle implements QueryDb {
const parent = this.#meters.getStore();
const stats: DbStats = { statements: 0, roundTrips: 0, rows: 0, ms: 0, effects: 0 };
try {
const value = await this.#meters.run(stats, fn);
const value = await whileBusy(this, () => this.#meters.run(stats, fn));
return { value, stats: { ...stats } };
} finally {
if (parent) {
@@ -503,10 +529,12 @@ export class Handle implements QueryDb {
else void runAfterCommit(fn);
}
/** Counts an external effect in the current meter: `effect()` in src/db/effects.ts. */
noteEffect(): void {
/** For `effect()` (src/db/effects.ts): the transaction or wave open in this async context; `count` counts an effect in its meter. */
effectScope(count: boolean): string | undefined {
const m = this.#meters.getStore();
if (m) m.effects++;
if (m && count) m.effects++;
if (this.#als.getStore()?.state === "open") return "a database transaction";
return this.#together.getStore()?.open ? "a db.together wave" : undefined;
}
async run(q: Compilable<unknown>): Promise<RunResult> {
@@ -598,7 +626,7 @@ export class Handle implements QueryDb {
let lockedAt: number | undefined;
let value: T;
try {
value = await this.#als.run(tx, () =>
value = await whileBusy(this, () => this.#als.run(tx, () =>
this.#engine.configure(this.#engine.kysely.transaction(), mode).execute(async (trx) => {
tx.trx = trx as unknown as Kysely<DB>;
tx.state = "open";
@@ -609,7 +637,7 @@ export class Handle implements QueryDb {
tx.state = "closed";
}
}),
);
));
} finally {
tx.state = "closed";
if (settingsWriteHook && this.#settingsTx.has(tx)) settingsWriteHook(this);
+5 -56
View File
@@ -8,25 +8,15 @@
* - `await connectDb(target, { busyTimeoutMs, role })`: a handle of its own (tests, the dashboard's second handle, worker
* threads). `target` is a SQLite path or a postgres:// URL.
* - `await dbFor(sync)`: the handle over a `DatabaseSync` that `connect()` (src/db.ts) returned, memoized per connection.
* Code that still holds a `DatabaseSync` reaches the async API this way while the rest of the call graph is converted.
*
* Target shape of the sync → async conversion (statement API mirrors node:sqlite's, but every call returns a promise):
* - `db: DatabaseSync` → `db: Db`
* - `db.prepare(X).get(a)` / `.all` / `.run` → `await db.prepare(X).get(a)` / ... (`?` and `:name` parameters as today)
* - `db.prepare(X).iterate(a)` in `for` → `for await (... of db.prepare(X).iterate(a))`
* - `db.exec(X)` → `await db.script(X)`
* - `db.isTransaction` → `db.inTransaction()`
* - `BEGIN IMMEDIATE; ...; COMMIT` → `await db.write(async () => { ... })`
* - `BEGIN; ...; COMMIT` (read snapshot) → `await db.read(async () => { ... })`
* - `connect(path, opts)` → `await connectDb(path, opts)`; the default database → `await openDb()`
* `db.sync` is the underlying `DatabaseSync` on SQLite, for residue that cannot await yet; it bypasses transaction
* routing (it runs on the same connection, so inside whatever transaction is open on it) and goes away after the move.
* A `Db` carries transactions, waves, locks and notifications and has no query methods: the statements live in the data
* modules (src/data/**) and in infrastructure (src/db/**), which take the query surface of a handle with `queryDb`
* (src/db/query-db.ts; test/data-layer.test.ts keeps it there).
*
* Transactions are routed through AsyncLocalStorage: every call made inside `db.write(fn)` / `db.read(fn)`, at any depth
* of awaits, runs in that transaction. Read `db.k` at each use; a `Kysely` captured outside a transaction stays outside it.
* of awaits, runs in that transaction.
*/
import type { Compilable, Kysely } from "kysely";
import type { DatabaseSync, SQLInputValue, SQLOutputValue } from "node:sqlite";
import type { SQLInputValue, SQLOutputValue } from "node:sqlite";
export type Dialect = "sqlite" | "postgres";
@@ -35,7 +25,6 @@ export type DbRole = "dashboard" | "dashboard-remote" | "runner" | "job" | "plan
/** The table types Kysely queries are checked against, generated from the migrated schema (scripts/gen-db-types.ts). */
export type { DB } from "./types.ts";
import type { DB } from "./types.ts";
export type Value = SQLOutputValue;
export type Row = Record<string, Value>;
@@ -114,31 +103,6 @@ export interface Subscription {
export interface Db {
readonly dialect: Dialect;
/**
* Kysely, routed to the transaction open in the current async context.
* @deprecated Queries belong in the data modules, which reach them through `queryDb` (src/db/query-db.ts).
*/
readonly k: Kysely<DB>;
/**
* Runs a Kysely query: its first row.
* @deprecated Queries belong in the data modules, which reach them through `queryDb` (src/db/query-db.ts).
*/
get<O>(q: Compilable<O>): Promise<O | undefined>;
/**
* Runs a Kysely query: all rows.
* @deprecated Queries belong in the data modules, which reach them through `queryDb` (src/db/query-db.ts).
*/
all<O>(q: Compilable<O>): Promise<O[]>;
/**
* Runs a Kysely write.
* @deprecated Queries belong in the data modules, which reach them through `queryDb` (src/db/query-db.ts).
*/
run(q: Compilable<unknown>): Promise<RunResult>;
/**
* Transitional raw SQL in the SQLite dialect, with `?` and `:name` parameters.
* @deprecated Queries belong in the data modules, which reach them through `queryDb` (src/db/query-db.ts).
*/
prepare(text: string): Statement;
/**
* Runs `fn` with its Kysely SELECTs outside a transaction shared: one with the same text and parameters as an earlier
* one in this async context gets that read's rows (fresh copies) instead of another round trip. A write through the
@@ -188,14 +152,6 @@ export interface Db {
* synchronously. An error from `fn`, thrown or rejected, is logged and never reaches the caller.
*/
afterCommit(fn: () => void | Promise<void>): void;
/**
* Runs `fn` so that a statement error inside it leaves the open transaction usable: on Postgres, where a failed
* statement aborts the whole transaction, `fn` runs under a savepoint that is rolled back when it throws; on SQLite, and
* outside a transaction, it is a plain call. The error still reaches the caller, which catches it and carries on.
* Attempts in one transaction run one at a time, like its statements.
* @deprecated Queries belong in the data modules, which reach them through `queryDb` (src/db/query-db.ts).
*/
attempt<T>(fn: () => Promise<T>): Promise<T>;
/** Whether a transaction is open in the current async context; with `mode`, one of that kind (a read snapshot or a write). */
inTransaction(mode?: "read" | "write"): boolean;
/**
@@ -205,11 +161,6 @@ export interface Db {
* opening, outside any transaction.
*/
scope(): Promise<void>;
/**
* Runs several statements with no parameters (schema scripts, PRAGMAs).
* @deprecated Queries belong in the data modules, which reach them through `queryDb` (src/db/query-db.ts).
*/
script(text: string): Promise<void>;
/**
* Postgres: NOTIFY `channel` with `payload` for every process listening; inside a write transaction it is sent when the
* transaction commits. SQLite: nothing, since its processes poll.
@@ -230,6 +181,4 @@ export interface Db {
/** Calls `fn` for every round trip and write-lock release; returns the function that stops it. */
observe(fn: (e: DbEvent) => void): () => void;
close(): Promise<void>;
/** The underlying SQLite connection, for code that cannot await yet. Absent on Postgres. */
readonly sync?: DatabaseSync;
}
+12 -11
View File
@@ -16,6 +16,7 @@
import type { AliasedRawBuilder, Expression, ExpressionBuilder, InsertObject, RawBuilder, SelectQueryBuilder, SqlBool } from "kysely";
import type { Db, Dialect, Param } from "./index.ts";
import { nowParam, pgPath, quote, rowidOf } from "./portable.ts";
import { queryDb } from "./query-db.ts";
import { fts5Query, tsQueryText, type Search } from "./search.ts";
import { sql } from "./sql.ts";
import { COLUMNS, type DB } from "./types.ts";
@@ -171,7 +172,7 @@ export async function updateFrom(db: Db, table: string, keyCols: readonly string
if (rows.length === 0) return 0;
const set = setCols ?? Object.keys(rows[0]).filter((c) => !keyCols.includes(c));
if (set.length === 0 || keyCols.length === 0) throw new Error("updateFrom needs key columns and columns to set");
const k = db.k as any;
const qdb = queryDb(db), k = qdb.k as any;
const names = [...keyCols, ...set].map(ident);
let changed = 0;
for (const chunk of chunks(rows)) {
@@ -181,7 +182,7 @@ export async function updateFrom(db: Db, table: string, keyCols: readonly string
const q = k.updateTable(table).from(v)
.set((eb: ExpressionBuilder<any, any>) => Object.fromEntries(set.map((c) => [c, eb.ref(`v.${c}`)])))
.where((eb: ExpressionBuilder<any, any>) => eb.and(keyCols.map((c) => eb(`${table}.${c}`, "=", eb.ref(`v.${c}`)))));
changed += (await db.run(q)).changes;
changed += (await qdb.run(q)).changes;
}
return changed;
}
@@ -390,13 +391,13 @@ export const batches = <T>(rows: readonly T[]): T[][] => Array.from({ length: Ma
* rowid only increases. Postgres runs two statements: call it inside `db.write`.
*/
export async function replaceRow<T extends keyof DB & string>(db: Db, table: T, key: readonly string[], row: InsertObject<DB, T>): Promise<void> {
const k = db.k as any;
const q = queryDb(db), k = q.k as any;
if (db.dialect !== "postgres") {
await db.run(k.insertInto(table).orReplace().values(row));
await q.run(k.insertInto(table).orReplace().values(row));
return;
}
await db.run(k.deleteFrom(table).where((eb: ExpressionBuilder<any, any>) => eb.and(key.map((c) => eb(c, "=", (row as Record<string, unknown>)[c])))));
await db.run(k.insertInto(table).values(row));
await q.run(k.deleteFrom(table).where((eb: ExpressionBuilder<any, any>) => eb.and(key.map((c) => eb(c, "=", (row as Record<string, unknown>)[c])))));
await q.run(k.insertInto(table).values(row));
}
/**
@@ -404,14 +405,14 @@ export async function replaceRow<T extends keyof DB & string>(db: Db, table: T,
* rowids in the order given. Call inside `db.write`.
*/
export async function replaceRows<T extends keyof DB & string>(db: Db, table: T, key: readonly string[], rows: readonly InsertObject<DB, T>[]): Promise<void> {
const k = db.k as any;
const q = queryDb(db), k = q.k as any;
for (const chunk of batches(rows)) {
if (db.dialect !== "postgres") {
await db.run(k.insertInto(table).orReplace().values(chunk));
await q.run(k.insertInto(table).orReplace().values(chunk));
continue;
}
await db.run(k.deleteFrom(table).where((eb: ExpressionBuilder<any, any>) => eb.or(chunk.map((row) => eb.and(key.map((c) => eb(c, "=", (row as Record<string, unknown>)[c])))))));
await db.run(k.insertInto(table).values(chunk));
await q.run(k.deleteFrom(table).where((eb: ExpressionBuilder<any, any>) => eb.or(chunk.map((row) => eb.and(key.map((c) => eb(c, "=", (row as Record<string, unknown>)[c])))))));
await q.run(k.insertInto(table).values(chunk));
}
}
@@ -538,7 +539,7 @@ export function rowArray(d: D, q: SelectQueryBuilder<any, any, any>): RawBuilder
* Every value is an integer, text or null, which a JSON array carries unchanged.
*/
export async function rowValues(db: Db, queries: readonly SelectQueryBuilder<any, any, any>[]): Promise<unknown[][]> {
const row: Record<string, string | null> | undefined = await db.get(db.k.selectNoFrom(queries.map((q, k) => rowArray(db, q).as(`c${k}`))));
const row: Record<string, string | null> | undefined = await queryDb(db).get(queryDb(db).k.selectNoFrom(queries.map((q, k) => rowArray(db, q).as(`c${k}`))));
return queries.map((_, k) => { const v = row?.[`c${k}`]; return v === null || v === undefined ? [] : (JSON.parse(v) as unknown[]); });
}
+8 -5
View File
@@ -26,6 +26,7 @@ import type { Db } from "./index.ts";
import { dbTarget, isPgUrl, loadPg } from "./open.ts";
import { pgConnectionString, SERVER_KEEPALIVE, setSession, within } from "./postgres.ts";
import { isFenced, type LeaderRole } from "./fence.ts";
import { queryDb, type QueryDb } from "./query-db.ts";
import { sql } from "./sql.ts";
/**
@@ -111,7 +112,7 @@ const pause = (ms: number, signal?: AbortSignal): Promise<void> => new Promise((
signal?.addEventListener("abort", done, { once: true });
});
async function putSetting(db: Db, key: string, value: string): Promise<void> {
async function putSetting(db: QueryDb, key: string, value: string): Promise<void> {
await db.prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(key, value);
}
@@ -121,7 +122,7 @@ const serverMs = (plus = 0) => sql<number>`CAST(EXTRACT(EPOCH FROM clock_timesta
type LeaseConn = { client: Pg.Client; info: ConnInfo; run: <O>(q: Compilable<O>) => Promise<O[]> };
/** The lease connection: errors and its end go to `onLost`, so a dropped connection never crashes the process. */
async function leaseClient(pg: typeof Pg.default, db: Db, url: string, role: LeaderRole, log: (l: string) => void, onLost: (c: Pg.Client, why: string) => void): Promise<LeaseConn> {
async function leaseClient(pg: typeof Pg.default, db: QueryDb, url: string, role: LeaderRole, log: (l: string) => void, onLost: (c: Pg.Client, why: string) => void): Promise<LeaseConn> {
const c = new pg.Client({
connectionString: pgConnectionString(url), application_name: `autocraft-leader-${role}`, keepAlive: true, keepAliveInitialDelayMillis: 5_000,
connectionTimeoutMillis: CONNECT_MS,
@@ -152,7 +153,8 @@ async function leaseClient(pg: typeof Pg.default, db: Db, url: string, role: Lea
* Waits until this copy leads `role`, then resolves its lease; null when `signal` aborted first. The caller fences its
* process to `lease.epoch` (setFence) before it starts work and stops at once when `lease.lost` aborts.
*/
export async function elect(db: Db, role: LeaderRole, o: ElectOptions = {}): Promise<Lease | null> {
export async function elect(handle: Db, role: LeaderRole, o: ElectOptions = {}): Promise<Lease | null> {
const db = queryDb(handle);
const holder = o.holder ?? `${hostname()}:${process.pid}`;
const log = o.log ?? ((l: string) => console.log(l));
const url = o.url ?? dbTarget();
@@ -331,7 +333,7 @@ export async function elect(db: Db, role: LeaderRole, o: ElectOptions = {}): Pro
}
/** Removes the rows of standbys that stopped writing them. */
async function pruneStandbys(db: Db, role: LeaderRole): Promise<void> {
async function pruneStandbys(db: QueryDb, role: LeaderRole): Promise<void> {
const rows = await db.prepare("SELECT key, value FROM settings WHERE key LIKE ?").all(`${standbyPrefix(role)}%`) as { key: string; value: string }[];
for (const r of rows) {
let at = NaN;
@@ -346,7 +348,8 @@ async function pruneStandbys(db: Db, role: LeaderRole): Promise<void> {
* copy was ever elected (SQLite).
*/
export async function leaderStatus(db: Db, role: LeaderRole, freshMs: number, nowMs = Date.now()): Promise<{ leader: LeaderStatus | null; standbys: number; unwatched: boolean } | null> {
const rows = await db.all(db.k.selectFrom("settings").select(["key", "value"]).where("key", "like", `${leaderKey(role)}%`));
const q = queryDb(db);
const rows = await q.all(q.k.selectFrom("settings").select(["key", "value"]).where("key", "like", `${leaderKey(role)}%`));
const lead = rows.find((r) => r.key === leaderKey(role));
if (!lead) return null;
const parse = <T>(v: string | null): T | null => { try { return v ? JSON.parse(v) as T : null; } catch { return null; } };
+4 -2
View File
@@ -10,6 +10,7 @@ import { Handle } from "./handle.ts";
import type { Db, DbRole } from "./index.ts";
import { migratePg, newerPgSchema, pgStamp, storedPgStamp } from "./pg-triggers.ts";
import { pgConnectionString, postgresEngine } from "./postgres.ts";
import { queryDb } from "./query-db.ts";
import { bindSql } from "./sql.ts";
import { sqliteEngine } from "./sqlite.ts";
@@ -95,7 +96,7 @@ export interface ConnectOptions {
role?: DbRole;
/** Postgres: bring the schema and triggers up to date first (default). False opens the database as it is. */
migrate?: boolean;
/** Postgres: how long a transaction may sit idle before the server ends its session (default 60 s). */
/** Postgres: how long a transaction may sit idle before the server ends its session (default 10 s). */
idleInTransactionMs?: number;
/**
* Postgres: write statements outside a transaction run under their row locks only, not as a transaction under the writer
@@ -152,7 +153,8 @@ export async function openDb(): Promise<Db> {
// A process without the file never reads the keys by design (a build worker); say so only when a stored app is going unread.
const file = envVar("SECRETS_FILE");
if (!file || !existsSync(file)) return;
const stored = await db.get(db.k.selectFrom("github_app").select("id").where("id", "=", 1).where("keys_enc", "is not", null)).catch(() => undefined);
const q = queryDb(db);
const stored = await q.get(q.k.selectFrom("github_app").select("id").where("id", "=", 1).where("keys_enc", "is not", null)).catch(() => undefined);
if (stored) console.error(`GitHub App keys not read: ${e.message}`);
});
return { db, close };
+1 -1
View File
@@ -28,7 +28,7 @@ const EXCLUSIVE_LOCKS = 0x61636578; // "acex"
const DEFAULT_LOCK_TIMEOUT_MS = 30_000;
/** A transaction whose client sends nothing for this long is ended by the server, so a dead process cannot keep the writer lock. */
const DEFAULT_IDLE_IN_TRANSACTION_MS = 60_000;
const DEFAULT_IDLE_IN_TRANSACTION_MS = 10_000;
/**
* Server-side TCP settings of every connection: the server drops a client that went silent (a lost node) after about
+8 -5
View File
@@ -6,7 +6,7 @@ import type { DB, Db, QueryOpts, RunResult, Statement } from "./index.ts";
export type { QueryOpts };
export interface QueryDb extends Db {
/** Kysely, routed to the transaction open in the current async context. Read it at each use. */
/** Kysely, routed to the transaction open in the current async context. Read it at each use: one captured outside a transaction stays outside it. */
readonly k: Kysely<DB>;
/** Runs a Kysely query: its first row. Inside `together` a SELECT joins the current wave. */
get<O>(q: Compilable<O>, o?: QueryOpts): Promise<O | undefined>;
@@ -16,11 +16,14 @@ export interface QueryDb extends Db {
run(q: Compilable<unknown>): Promise<RunResult>;
/** Runs several statements with no parameters (schema scripts, PRAGMAs). */
script(text: string): Promise<void>;
/** See `Db.attempt`: a statement error inside `fn` leaves the open transaction usable. */
/**
* Runs `fn` so that a statement error inside it leaves the open transaction usable: on Postgres, where a failed
* statement aborts the whole transaction, `fn` runs under a savepoint that is rolled back when it throws; on SQLite, and
* outside a transaction, it is a plain call. The error still reaches the caller, which catches it and carries on.
* Attempts in one transaction run one at a time, like its statements.
*/
attempt<T>(fn: () => Promise<T>): Promise<T>;
/** See `Db.scope`. */
scope(): Promise<void>;
/** Transitional raw SQL in the SQLite dialect, with `?` and `:name` parameters. It never joins a `together` wave. */
/** Raw SQL in the SQLite dialect, with `?` and `:name` parameters. It never joins a `together` wave. */
prepare(text: string): Statement;
/** The underlying SQLite connection, for code that cannot await yet. Absent on Postgres. */
readonly sync?: DatabaseSync;
+9 -8
View File
@@ -13,6 +13,7 @@ import { planChangesSql } from "./plan-triggers.ts";
import { PIN_SEARCH_PATH, withMigrationLock, readCatalog, type MigrationOpts, type PgClient } from "./pg-migrate.ts";
import { PG_COLUMNS_SQL, pgColumns, pgTriggerParts } from "./pg-triggers.ts";
import { pgConnectionString } from "./postgres.ts";
import { queryDb } from "./query-db.ts";
import { pgScopeViews, SCOPED_SCHEMA } from "./scoped.ts";
import { COPIED_SETTINGS } from "./state-copy.ts";
import { archiveActions, archiveDecisions, SWITCH_KEY, type SwitchReport } from "./switch-over.ts";
@@ -42,8 +43,8 @@ function columnsLeft(has: (column: string) => boolean): Map<string, string[]> {
*/
export async function dropRetired(db: Db, o: { force?: boolean; target?: string; now?: string } & MigrationOpts = {}): Promise<string[]> {
if (!DROP_RETIRED && !o.force) return [];
const k = db.k as any;
const marker = (await db.get(k.selectFrom("main.settings").select("value").where("key", "=", SWITCH_KEY))) as { value: string } | undefined;
const q = queryDb(db), k = q.k as any;
const marker = (await q.get(k.selectFrom("main.settings").select("value").where("key", "=", SWITCH_KEY))) as { value: string } | undefined;
if (!marker) return [];
const now = o.now ?? new Date().toISOString();
const sweep = async (left: Set<string>): Promise<void> => {
@@ -54,7 +55,7 @@ export async function dropRetired(db: Db, o: { force?: boolean; target?: string;
};
let dropped: string[];
if (db.dialect === "sqlite") {
const sync = db.sync!;
const sync = q.sync!;
const tables = sqliteTables(sync);
await sweep(new Set(RETIRED_TABLES.filter((t) => tables.has(t))));
dropped = dropSqlite(sync);
@@ -73,15 +74,15 @@ export async function dropRetired(db: Db, o: { force?: boolean; target?: string;
}
}
await db.write(async () => {
const w = db.k as any;
await db.run(w.deleteFrom("main.settings").where((eb: any) => eb.or([eb("key", "in", SETTING_KEYS),
const w = q.k as any;
await q.run(w.deleteFrom("main.settings").where((eb: any) => eb.or([eb("key", "in", SETTING_KEYS),
...SETTING_PREFIXES.map((p) => eb(eb.fn("substr", ["key", eb.lit(1), eb.lit(p.length)]), "=", p))])));
// The older release took "started" for all items, so the value is renamed only now; the reader takes both (src/data/runners/user-settings.ts).
await db.run(w.updateTable("main.user_settings").set({ value: "started", updated_at: now }).where("key", "=", "task_items").where("value", "=", "fast"));
await q.run(w.updateTable("main.user_settings").set({ value: "started", updated_at: now }).where("key", "=", "task_items").where("value", "=", "fast"));
// The older runner's heartbeat is gone with the rest, and no older release can run again: the switch stays done.
const at = (JSON.parse(marker.value) as { at?: string }).at ?? now;
await db.run(w.updateTable("main.settings").set({ value: JSON.stringify({ at, heartbeat: null }) }).where("key", "=", SWITCH_KEY));
if (dropped.length) await db.run(w.insertInto("main.audit").values({ at: now, login: "pipeline", action: "retired-drop", target: null, details: JSON.stringify({ dropped }) }));
await q.run(w.updateTable("main.settings").set({ value: JSON.stringify({ at, heartbeat: null }) }).where("key", "=", SWITCH_KEY));
if (dropped.length) await q.run(w.insertInto("main.audit").values({ at: now, login: "pipeline", action: "retired-drop", target: null, details: JSON.stringify({ dropped }) }));
});
return dropped;
}
+7 -5
View File
@@ -5,6 +5,7 @@ import { markFull, BULK_ROWS } from "./plan-triggers.ts";
import { BATCH, FIELD_COLUMNS, SCHEME_ID, classifyHash, embedHash, type Fields } from "../itemhash.ts";
import { textRefs } from "../core/open-prs.ts";
import type { Db } from "./index.ts";
import { queryDb } from "./query-db.ts";
const FIELDS = FIELD_COLUMNS.join(", ");
@@ -79,12 +80,13 @@ export function fillTextRefs(db: DatabaseSync): void {
export async function dropPlanChanges(db: Db): Promise<number> {
// Postgres has no release before the change log; its triggers serve the live topics too (src/db/pg-triggers.ts).
if (db.dialect === "postgres") throw new Error("dropping the change log is for SQLite databases only");
const triggers = await db.prepare("SELECT name FROM main.sqlite_master WHERE type = 'trigger' AND name LIKE 'plan\\_%' ESCAPE '\\'").all() as { name: string }[];
const q = queryDb(db);
const triggers = await q.prepare("SELECT name FROM main.sqlite_master WHERE type = 'trigger' AND name LIKE 'plan\\_%' ESCAPE '\\'").all() as { name: string }[];
await db.write(async () => {
for (const { name } of triggers) await db.script(`DROP TRIGGER IF EXISTS main.${name}`);
for (const t of ["item_changes", "plan_full", "plan_full_causes", "plan_bulk", "plan_shadow_diffs", "plan_pass_stats", "review_blockers"] as const) await db.run(db.k.schema.dropTable(`main.${t}`).ifExists());
await db.script("DELETE FROM main.sqlite_sequence WHERE name = 'item_changes'");
await db.run(db.k.deleteFrom("main.settings").where("key", "=", "schema_stamp"));
for (const { name } of triggers) await q.script(`DROP TRIGGER IF EXISTS main.${name}`);
for (const t of ["item_changes", "plan_full", "plan_full_causes", "plan_bulk", "plan_shadow_diffs", "plan_pass_stats", "review_blockers"] as const) await q.run(q.k.schema.dropTable(`main.${t}`).ifExists());
await q.script("DELETE FROM main.sqlite_sequence WHERE name = 'item_changes'");
await q.run(q.k.deleteFrom("main.settings").where("key", "=", "schema_stamp"));
});
return triggers.length;
}
+14 -12
View File
@@ -28,8 +28,9 @@
import type { ReviewWorkflow } from "../data/review/types.ts";
import { afterSteps, atBlocker, type ReviewView } from "../workflow/recommend.ts";
import { WEIGHT_NORMAL, type Parsed, type PlanPart } from "../workflow/types.ts";
import type { Db } from "./index.ts";
import type { Db, Statement } from "./index.ts";
import * as kx from "./kx.ts";
import { queryDb } from "./query-db.ts";
import { ACTIVE_LEG_STATES, backfills, boundsSql, settingsState, spans, STATE_COPY_DONE, type StateRows, type Task, type Value } from "./state-copy.ts";
export const SWITCH_KEY = "workflow_switch";
@@ -121,10 +122,11 @@ export function reportLines(r: SwitchReport): string[] {
type Row = Record<string, any>;
/** Read at each use: the builder of the open transaction. */
const q = (db: Db): any => db.k;
const all = (db: Db, x: any): Promise<Row[]> => db.all(x) as Promise<Row[]>;
const get = (db: Db, x: any): Promise<Row | undefined> => db.get(x) as Promise<Row | undefined>;
const run = (db: Db, x: any): Promise<{ changes: number }> => db.run(x);
const q = (db: Db): any => queryDb(db).k;
const all = (db: Db, x: any): Promise<Row[]> => queryDb(db).all(x) as Promise<Row[]>;
const get = (db: Db, x: any): Promise<Row | undefined> => queryDb(db).get(x) as Promise<Row | undefined>;
const run = (db: Db, x: any): Promise<{ changes: number }> => queryDb(db).run(x);
const prepare = (db: Db, text: string): Statement => queryDb(db).prepare(text);
const key = (r: { repo: string; number: number | string }): string => `${r.repo}#${r.number}`;
const setting = async (db: Db, name: string): Promise<string | null> =>
@@ -269,9 +271,9 @@ async function carryLimits(db: Db, resets: [string, string][], perDay: Record<st
}
async function carryJevFailed(db: Db, o: CarryOptions): Promise<number> {
const gone = await db.prepare(`DELETE FROM main.classify_state WHERE kind = 'jev_failed' AND (CAST(? AS TEXT) IS NULL OR at <= ?)
const gone = await prepare(db, `DELETE FROM main.classify_state WHERE kind = 'jev_failed' AND (CAST(? AS TEXT) IS NULL OR at <= ?)
AND NOT EXISTS (SELECT 1 FROM main.items i WHERE i.repo = classify_state.repo AND i.number = classify_state.number AND i.jev_failed_hash = classify_state.value)`).run(o.keepAfter, o.keepAfter);
const put = await db.prepare(`INSERT INTO main.classify_state (kind, repo, number, value, at)
const put = await prepare(db, `INSERT INTO main.classify_state (kind, repo, number, value, at)
SELECT 'jev_failed', repo, number, jev_failed_hash, CAST(? AS TEXT) FROM main.items WHERE jev_failed_hash IS NOT NULL
ON CONFLICT (kind, repo, number) DO UPDATE SET value = excluded.value, at = excluded.at WHERE classify_state.value <> excluded.value`).run(o.now);
return Number(gone.changes) + Number(put.changes);
@@ -286,20 +288,20 @@ async function carryColumns(db: Db, r: SwitchReport, since: string): Promise<voi
await backfill(db, t.agentRuns, (await get(db, q(db).selectFrom("main.agent_runs").select((eb: any) => [eb.fn.min("id").as("lo"), eb.fn.max("id").as("hi")]).where("started_at", ">=", from))));
for (const task of [t.callItems, t.batchPrs, t.batchForks, t.alerts, t.groups, t.groupItems]) await backfill(db, task);
const idle = (col: string): string => `(SELECT t.${col} FROM main.mcp_tokens t WHERE t.id = remote_helpers.token_id)`;
r.carried.remote_helpers = await db.write(async () => Number((await db.prepare(`UPDATE main.remote_helpers
r.carried.remote_helpers = await db.write(async () => Number((await prepare(db, `UPDATE main.remote_helpers
SET idle_claim_at = ${idle("idle_claim_at")}, idle_tiers = ${idle("idle_tiers")}, idle_repos = ${idle("idle_repos")}
WHERE ${idle("idle_claim_at")} > COALESCE(idle_claim_at, 0)`).run()).changes)
+ Number((await db.prepare(`UPDATE main.remote_helpers SET machine = ${idle("machine")} WHERE machine IS NULL AND ${idle("machine")} IS NOT NULL`).run()).changes));
+ Number((await prepare(db, `UPDATE main.remote_helpers SET machine = ${idle("machine")} WHERE machine IS NULL AND ${idle("machine")} IS NOT NULL`).run()).changes));
}
/** Runs a backfill of the state copy again, one write transaction per unit. */
async function backfill(db: Db, t: Task, bounds?: Row): Promise<void> {
const b = t.range ? bounds ?? await db.prepare(boundsSql(t, "main.")).get() : undefined;
const b = t.range ? bounds ?? await prepare(db, boundsSql(t, "main.")).get() : undefined;
for (const [lo, hi] of spans(t, b)) {
await db.write(async () => {
const read = t.read?.(lo, hi);
const rows = read ? await db.prepare(read.sql).all(...read.params as Value[]) : [];
for (const w of t.writes(rows, lo, hi)) await db.prepare(w.sql).run(...w.params as Value[]);
const rows = read ? await prepare(db, read.sql).all(...read.params as Value[]) : [];
for (const w of t.writes(rows, lo, hi)) await prepare(db, w.sql).run(...w.params as Value[]);
});
}
}
+3
View File
@@ -3151,3 +3151,6 @@ export const COLUMNS = {
workspace_sessions: ["id", "kind", "repo", "base_sha", "item", "prompt", "env_id", "keep", "deadline_sec", "state", "outcome", "workspace_id", "remote_call_id", "job_id", "requested_by", "for_login", "created_at", "updated_at", "ended_at"],
workspaces: ["id", "repo", "base_sha", "base_commit", "app", "env_id", "state", "state_at", "pod", "pod_created_at", "create_tries", "pvc", "node", "limits", "checkpoint", "checkpoint_at", "last_call_at", "next_call", "error", "owner", "created_at", "updated_at", "ended_at", "remote_call_id", "volume_fresh", "resume_tries", "checkpoint_error", "restored", "restored_at", "layout", "prepared", "warm", "warm_commit"],
} as const;
/** The columns that hold bytes: BLOB on SQLite, bytea on Postgres. */
export const BYTES_COLUMNS = ["agent_run_texts.prompt", "agent_run_texts.output", "item_embeddings.vec", "owner_statements.embedding", "workspaces.checkpoint"] as const;
+2
View File
@@ -9,6 +9,7 @@ import { join, resolve } from "node:path";
import { envVar } from "../env.ts";
import { APP_CREDENTIAL_ARGS } from "../github/install-token.ts";
import { readEnvFor } from "../github/read.ts";
import { effect } from "../db/effects.ts";
/** `sent: false`: the command failed before any request went out (the app lane could not get its token), so nothing reached GitHub. */
export type ExecResult = { code: number; stdout: string; stderr: string; sent?: false };
@@ -19,6 +20,7 @@ export type ExecOpts = { cwd?: string; env?: Record<string, string>; input?: str
export type Exec = (cmd: string, args: string[], opts?: ExecOpts) => Promise<ExecResult>;
export const exec: Exec = async (cmd, args, opts = {}) => {
effect("process", `${cmd} ${args[0] ?? ""}`);
// A command that brings its own whole environment (a write lane) or asks to inherit keeps it. Any other gh command and
// the network reads of git (fetch, ls-remote, clone, pull) read as the current identity: the app's installation token
// under `app`, the inherited login under `box`. Local git commands and pushes get no token.
+2
View File
@@ -8,6 +8,7 @@
// caller that writes them to the secrets file.
import { createSign } from "node:crypto";
import type { AppOwner, AppSecrets } from "../dash/server/config.ts";
import { effect } from "../db/effects.ts";
export const GITHUB_API = "https://api.github.com";
export const REPO_URL = "https://github.com/storytold/autocraft";
@@ -74,6 +75,7 @@ export function appJwt(app: Pick<AppSecrets, "clientId" | "privateKey">, nowMs =
}
export async function call(base: string, path: string, token: string | null, method = "GET", body?: unknown): Promise<unknown> {
effect("http");
const r = await fetch(`${base}${path}`, {
method,
headers: {
+4
View File
@@ -27,6 +27,7 @@ import { filterSeq, forEachSeq } from "../async-seq.ts";
import type { Db } from "../db/index.ts";
import { abandonWrites, addOwnCommits, addPushOutcomes, beginWrite, finishWrite, loadMadeBefore, loadPaceWaits } from "../data/control/index.ts";
import { openDb } from "../db/open.ts";
import { effect } from "../db/effects.ts";
export { GITHUB_ACTIONS } from "./actions.ts";
export type { Note } from "./note.ts";
@@ -342,6 +343,7 @@ async function recorded<T>(w: Writer, identity: string, action: string, target:
}
}
const details = { ...details0, identity, ...jobOf(), ...(once && { writeKey: once.key }), ...(repeats !== undefined && { repeats }) };
effect("github-write");
const id = await begin(w, action, target, details, owner);
let r: T;
try {
@@ -531,6 +533,7 @@ export async function addLabels(w: Writer, q: Querier, repo: string, items: Labe
await abandonWrites(w.db, ids);
};
try {
effect("github-write");
for (const it of items) ids.push(await begin(w, "labels-apply", refOf(repo, it.number), await det(it), undefined, unsent));
} catch (e) {
await unsent();
@@ -972,6 +975,7 @@ export async function mergeViaCommand(w: Writer, run: (cmd: string, args: string
const method: string = o.method;
const base = { ...details, method, identity: await idOf(w, g, "merge"), ...jobOf() };
const target = refOf(repo, g.number);
effect("github-write");
const id = await begin(w, "merge", target, base);
let r: CommandResult;
try {
+3
View File
@@ -20,6 +20,7 @@ import { isFenced } from "./db/fence.ts";
import type { Db } from "./db/index.ts";
import { dbLockName, openDb, setDbRole } from "./db/open.ts";
import { loadTrackedRepos } from "./data/control/index.ts";
import { effect } from "./db/effects.ts";
import {
advanceOrgHighWater, advanceRepoHighWater, applyLocal, clearRepoFailures, closeGoneItems, countItemsByRepo, finishSyncRun, listItems, loadRepos, loadSyncPlan, loadSyncState,
markReposReconciled, markReposRead, markReposSyncedByError, saveItems, saveRepoList, saveSyncState, startSyncRun,
@@ -179,6 +180,8 @@ export class Client {
}
async query(query: string, variables: object): Promise<Node> {
// Mutations are counted where they are recorded (src/github/write.ts).
if (!/^\s*mutation\b/.test(query)) effect("github-read");
const { env, key } = await this.childEnv(ownerOfVariables(variables));
this.useRate(key);
if (this.remaining !== null && this.remaining < this.reserve) {
+1 -2
View File
@@ -4,8 +4,7 @@ import { insertRun } from "../src/agents/runs.ts";
import { activity } from "../src/dash/api/activity.ts";
import type { Req } from "../src/dash/types.ts";
import type { ActivityPage } from "../web/src/api/types.ts";
import type { Db } from "../src/db/index.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb, type Db } from "./helpers/raw-db.ts";
const as = (role: "viewer" | "operator", query: Record<string, string> = {}): Req => ({
method: "GET", path: "", params: {}, query: new URLSearchParams(query), form: new URLSearchParams(), csrf: "", nonce: "",
+1 -1
View File
@@ -13,7 +13,7 @@ import { loadConfig } from "../src/dash/server/config.ts";
import { startServer } from "../src/dash/server/index.ts";
import { FakeProvider } from "../src/dash/server/provider.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
const NOTE = "OVERRIDE-NOTE-m4x";
mkdirSync(SCRATCH, { recursive: true });
+1 -2
View File
@@ -2,8 +2,7 @@ import assert from "node:assert/strict";
import { test } from "node:test";
import { finishRun, getRun, insertRun, pruneRuns, rates, RUN_KEEP_MS, runTools } from "../src/agents/runs.ts";
import { saveTools } from "../src/agents/tools.ts";
import type { Db } from "../src/db/index.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb, type Db } from "./helpers/raw-db.ts";
const start = async (db: Db) => await insertRun(db, { jobId: null, step: "fixup", stage: 1, promptId: "p", promptVersion: "1", provider: "claude", model: "m", items: [{ repo: "app", number: 1 }], prompt: "the prompt" });
const use = (id: string, name: string, input: unknown) => ({ type: "assistant", message: { content: [{ type: "tool_use", id, name, input }] } });
+1 -1
View File
@@ -10,7 +10,7 @@ import { join } from "node:path";
import { after, before, test } from "node:test";
import { ackRemovals, AllowedOwnerError, allowedOwners, allowOwner, installationEvent, removeOwner, sweepInstallations, unackedRemovals } from "../src/github/allowed-owners.ts";
import type { AppSecrets } from "../src/dash/server/config.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
import { SCRATCH } from "./scratch.ts";
mkdirSync(SCRATCH, { recursive: true });
+1 -1
View File
@@ -18,7 +18,7 @@ import { loadConfig } from "../src/dash/server/config.ts";
import { startServer } from "../src/dash/server/index.ts";
import { FakeProvider } from "../src/dash/server/provider.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
import * as kx from "../src/db/kx.ts";
const MARKER = "OPINION-MARKER-k3v";
+1 -1
View File
@@ -11,7 +11,7 @@ import { ghComment, pushOwnBranch } from "../src/github/write.ts";
import type { GuardedItem, GuardedRepo } from "../src/core/guard.ts";
import type { ExecOpts } from "../src/fixup/git.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
import * as kx from "../src/db/kx.ts";
const BOX = "ghp_box_account_token";
+1 -2
View File
@@ -4,8 +4,7 @@ import { mkdirSync } from "node:fs";
import { join } from "node:path";
import { test } from "node:test";
import { acceptProposal, decideSuggestion, editAreas, listAreaVersions, loadAreaLists, loadAreaOverview, loadItemAreas, loadProposals, saveItemAreas, saveProposal } from "../src/data/triage/index.ts";
import { connectDb } from "../src/db/open.ts";
import type { Db } from "../src/db/index.ts";
import { connectDb, type Db } from "./helpers/raw-db.ts";
import { SCRATCH } from "./scratch.ts";
const T0 = "2026-01-01T00:00:00.000Z";
+1 -1
View File
@@ -12,7 +12,7 @@ import { FakeProvider } from "../src/dash/server/provider.ts";
import { OPERATOR_SESSION_MAX, SESSION_MAX, loadSession } from "../src/dash/server/sessions.ts";
import { safeReturnTo } from "../src/dash/server/util.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
mkdirSync(SCRATCH, { recursive: true });
const dir = mkdtempSync(join(SCRATCH, "hardening-test-"));
+1 -1
View File
@@ -8,7 +8,7 @@ import { decidePr } from "../src/core/decide.ts";
import { authorWrites, ensureAuthorWrites } from "../src/fixup/author-permission.ts";
import { prFacts } from "./world.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
mkdirSync(SCRATCH, { recursive: true });
const dir = mkdtempSync(join(SCRATCH, "base-binding-"));
+1 -1
View File
@@ -8,7 +8,7 @@ import { FEATURES_REPO_ONLY_DONE, featuresRepoOnlySqlite } from "../src/db/featu
import { connect } from "../src/db.ts";
import { INPUT_TOPICS } from "../src/runner/autopilot.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb, dbFor } from "../src/db/open.ts";
import { connectDb, dbFor } from "./helpers/raw-db.ts";
import { rowid } from "../src/db/kx.ts";
mkdirSync(SCRATCH, { recursive: true });
+1 -1
View File
@@ -5,7 +5,7 @@ import { join } from "node:path";
import { test } from "node:test";
import { memorySummary, parseResults } from "../src/build/tasks.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
const R = { exitCode: 0, durationMs: 5, timedOut: false };
+1 -1
View File
@@ -19,7 +19,7 @@ import { createWorkspace } from "../src/build/workspaces.ts";
import { warmPlan } from "../src/worker/rust.ts";
import { startWorkerServer } from "../src/build/worker-api.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
mkdirSync(SCRATCH, { recursive: true });
const dir = mkdtempSync(join(SCRATCH, "build-pods-"));
+1 -1
View File
@@ -3,7 +3,7 @@
// published version's size.
import assert from "node:assert/strict";
import { test } from "node:test";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
import { groupsOf, parseSettings, quantity, stepPod, taskRequest, type Prepared } from "../src/build/pods.ts";
import { createEnv } from "../src/build/envs.ts";
import { raiseAfterOom, repoMemory, repoSizing, repoWarmTarget, setWarmTarget } from "../src/build/sizing.ts";
+1 -1
View File
@@ -17,7 +17,7 @@ import { startServer } from "../src/dash/server/index.ts";
import { FakeProvider } from "../src/dash/server/provider.ts";
import { scopeToTracked } from "../src/repos.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
mkdirSync(SCRATCH, { recursive: true });
const dir = mkdtempSync(join(SCRATCH, "build-test-"));
+1 -1
View File
@@ -5,7 +5,7 @@ import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
import { join } from "node:path";
import { after, test } from "node:test";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
import { sqliteOnly } from "./test-db.ts";
const { connect } = await import("../src/db.ts");
+1 -1
View File
@@ -13,7 +13,7 @@ import { take } from "../src/runner/leases.ts";
import { validating } from "./gql.ts";
import { reportingTaskRunner } from "./fake-runner.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
mkdirSync(SCRATCH, { recursive: true });
const dir = mkdtempSync(join(SCRATCH, "cifix-pool-"));
+1 -2
View File
@@ -20,8 +20,7 @@ import type { Querier } from "../src/mirror.ts";
import { saveOpus } from "../src/review/opus.ts";
import { validating } from "./gql.ts";
import { SCRATCH } from "./scratch.ts";
import type { Db } from "../src/db/index.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb, type Db } from "./helpers/raw-db.ts";
import { rowid } from "../src/db/kx.ts";
mkdirSync(SCRATCH, { recursive: true });
+1 -1
View File
@@ -6,7 +6,7 @@ import { carriedReview } from "../src/review/carry.ts";
import { changedHunks, ownDiffKey } from "../src/review/own-diff.ts";
import { prepareOpusInput, type OpusDeps } from "../src/review/opus.ts";
import { conflictBucket } from "../src/fixup/conflict-state.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
process.env.AUTOCRAFT_DIFF_CACHE = join(tmpdir("conflict-cost-diffs"), "cache");
+1 -2
View File
@@ -20,8 +20,7 @@ import { createToken } from "../src/dash/mcp/tokens.ts";
import { allocation } from "../src/agents/call.ts";
import { setEnabled } from "../src/runner/autopilot.ts";
import type { Req } from "../src/dash/types.ts";
import type { Db } from "../src/db/index.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb, type Db } from "./helpers/raw-db.ts";
mkdirSync(SCRATCH, { recursive: true });
const quiet = () => {};
+1 -1
View File
@@ -5,7 +5,7 @@ import { barOf } from "../src/dash/api/item-bar.ts";
import { loadItemPage } from "../src/data/views/item-page.ts";
import { classifiersReport, cost, disagreements } from "../src/dash/api/insight.ts";
import type { Req } from "../src/dash/types.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
const req = (query: Record<string, string> = {}): Req => ({
method: "GET", path: "", params: {}, query: new URLSearchParams(query), form: new URLSearchParams(), user: { login: "op", role: "operator", canWrite: async () => true, canRead: async () => true },
-5
View File
@@ -1,5 +0,0 @@
[
"src/build/tasks.ts",
"src/dash/api/related.ts",
"src/itemtools/server/tools.ts"
]
+59 -8
View File
@@ -1,14 +1,64 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { ALLOW_FILE, offenders, violation } from "../scripts/data-layer-allow.ts";
import { readdirSync, readFileSync } from "node:fs";
import { dirname, join, relative, resolve } from "node:path";
// Warn mode: files that still query the database outside src/data/ and src/db/ are listed in test/data-layer-allow.json
// (node scripts/data-layer-allow.ts --write). The list shrinks as modules move; it is empty when the data layer is done.
test("only files in the allow-list query the database outside src/data and src/db", () => {
const allowed = new Set(JSON.parse(readFileSync(ALLOW_FILE, "utf8")) as string[]);
const bad = offenders().filter((o) => !allowed.has(o.file)).map((o) => `${o.file}: ${o.why}`);
assert.deepEqual(bad, []);
// Queries live in the data modules (src/data/**) and in infrastructure (src/db/**, src/db.ts): feature code holds a `Db`,
// which has no query methods, and this scan keeps the ways around the type out of it.
const ROOT = new URL("..", import.meta.url).pathname;
/** src/db.ts holds the SQLite migrations: infrastructure, like src/db/. */
const INFRA = ["src/data/", "src/db/", "src/db.ts"];
/** Files the scan passes over, each with the reason. */
const EXCEPTIONS: Record<string, string> = {
"src/itemtools/server/tools.ts": "reads the item snapshot file in the sandbox with node built-ins only: no Db and no Kysely there",
"src/dash/api/related.ts": "the item page's relations, moving into the data modules",
"src/build/tasks.ts": "build task rows, moving into the data modules",
};
const QUERY_CALLS = /\b(?:selectFrom|selectNoFrom|insertInto|updateTable|deleteFrom|replaceInto|mergeInto|queryDb)\(|\.prepare\(|\.script\(|\bdb\.k\b|\.k\./;
const SQL_TEXT = /\bsql(?:<(?:[^<>\n]|<(?:[^<>\n]|<[^<>\n]*>)*>)*>)?`|\bsql\.(?:raw|ref)\b|["'`]\s*(?:SELECT|INSERT|UPDATE|DELETE|WITH)\s+[A-Za-z_*(]/;
const FROM = /(?:\bfrom\s+|\bimport\s*\(\s*)["']([^"']+)["']/g;
const INFRA_FILES = new Set(["src/db/kx.ts", "src/db/sql.ts", "src/db/portable.ts", "src/db/query-db.ts", "src/db/search.ts", "src/db/types.ts"]);
const MODULE_PUBLIC = new Set(["index.ts", "types.ts"]);
/** Why `text` of the file `file` (a path from the repo root) breaks the boundary, or null. */
function violation(file: string, text: string): string | null {
const call = QUERY_CALLS.exec(text);
if (call) return `query call ${call[0]}`;
const lit = SQL_TEXT.exec(text);
if (lit) return `SQL text ${lit[0]}`;
for (const m of text.matchAll(FROM)) {
const spec = m[1];
if (spec === "kysely") return "imports kysely";
if (!spec.startsWith(".")) continue;
const target = relative(ROOT, resolve(ROOT, dirname(file), spec));
if (INFRA_FILES.has(target)) return `imports ${target}`;
const mod = /^src\/data\/([^/]+)\/(.+)$/.exec(target);
if (mod && mod[1] !== "views" && !MODULE_PUBLIC.has(mod[2])) return `imports ${target}`;
}
return null;
}
test("nothing outside src/data and src/db queries the database, and no exception is out of date", () => {
const found = new Map<string, string>();
const walk = (dir: string) => {
for (const e of readdirSync(dir, { withFileTypes: true })) {
const p = join(dir, e.name);
if (e.isDirectory()) walk(p);
else if (p.endsWith(".ts")) {
const file = relative(ROOT, p);
if (INFRA.some((i) => file === i || file.startsWith(i))) continue;
const why = violation(file, readFileSync(p, "utf8"));
if (why) found.set(file, why);
}
}
};
walk(join(ROOT, "src"));
assert.deepEqual([...found].filter(([f]) => !(f in EXCEPTIONS)).map(([f, why]) => `${f}: ${why}`), []);
assert.deepEqual(Object.keys(EXCEPTIONS).filter((f) => !found.has(f)), [], "exceptions that are not needed");
});
test("the scan flags query calls, SQL text and imports of query internals, and passes plain code", () => {
@@ -17,6 +67,7 @@ test("the scan flags query calls, SQL text and imports of query internals, and p
assert.match(violation("src/x.ts", 'const q = "SELECT a FROM t"') ?? "", /SQL text/);
assert.match(violation("src/x.ts", 'import { sql } from "kysely";') ?? "", /kysely/);
assert.match(violation("src/x.ts", 'import * as kx from "./db/kx.ts";') ?? "", /kx\.ts/);
assert.match(violation("src/x.ts", 'import type { QueryDb } from "./db/query-db.ts";') ?? "", /query-db\.ts/);
assert.match(violation("src/x.ts", 'import { f } from "./data/mirror/fragments.ts";') ?? "", /fragments/);
assert.equal(violation("src/x.ts", 'import { f } from "./data/mirror/index.ts";\nconst s = "select an item";'), null);
assert.equal(violation("src/x.ts", 'import { v } from "./data/views/snapshot.ts";'), null);
+1 -1
View File
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import { loadAllDiffFacts, loadChecks, loadCheckSamples, loadDiffFacts, loadGates, loadRepoCiSignals, markDiffRead, markGateFailures, removeDiffFacts, saveChecks, saveDiffFacts, saveGates, setDiffFactsIf } from "../../src/data/mirror/index.ts";
import type { PrChecksRow } from "../../src/data/mirror/index.ts";
import type { Db } from "../../src/db/index.ts";
import type { Db } from "../helpers/raw-db.ts";
import { both, bothFlat } from "./mirror-fixture.ts";
const check = (repo: string, number: number, o: Partial<PrChecksRow> = {}): PrChecksRow =>
+1 -1
View File
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import { loadActivityByLogins, loadAuthoredIn, loadCommentHeads, loadComments, loadCommentStats, loadFormalReviews, loadNewerComments, loadSpokenComments, newerKey, searchComments } from "../../src/data/mirror/index.ts";
import type { Db } from "../../src/db/index.ts";
import type { Db } from "../helpers/raw-db.ts";
import { both, bothFlat, comment, seedItems } from "./mirror-fixture.ts";
const put = (db: Db, rows: ReturnType<typeof comment>[]) => db.write(async () => { await db.run(db.k.insertInto("main.comments").values(rows as never)); });
+2 -1
View File
@@ -1,7 +1,8 @@
// Shared setup of the mirror data-layer tests: a database with the app schema on SQLite, and on Postgres too when AUTOCRAFT_TEST_PG_URL names a server.
import { test } from "node:test";
import assert from "node:assert/strict";
import type { Db, Dialect } from "../../src/db/index.ts";
import type { Dialect } from "../../src/db/index.ts";
import type { Db } from "../helpers/raw-db.ts";
import type { FlatUnit } from "../helpers/query-count.ts";
import { expectFlat } from "../helpers/query-count.ts";
import { TEST_PG_URL, testDatabase } from "../test-db.ts";
+1 -1
View File
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import { applyLocal, closeGoneItems, fillItemHashes, loadChecks, loadItems, saveChecks, saveDiffFacts, saveItems } from "../../src/data/mirror/index.ts";
import type { ItemEntry } from "../../src/data/mirror/index.ts";
import type { Db } from "../../src/db/index.ts";
import type { Db } from "../helpers/raw-db.ts";
import { both, bothFlat, comment, entry, seedItems } from "./mirror-fixture.ts";
const item = async (db: Db, number: number, repo = "app") => (await loadItems(db, [{ repo, number }], "full")).get(`${repo}#${number}`)!;
+2 -2
View File
@@ -6,8 +6,8 @@ import { setTimeout as sleep } from "node:timers/promises";
import { SCRATCH } from "./scratch.ts";
import { isBusy } from "../src/db.ts";
import { countQueries } from "../src/db/counter.ts";
import type { Db } from "../src/db/index.ts";
import { closeDb, dbFor, openDb } from "../src/db/open.ts";
import { dbFor, openDb, type Db } from "./helpers/raw-db.ts";
import { closeDb } from "../src/db/open.ts";
import { bindParams, parseParams } from "../src/db/params.ts";
import { sql } from "../src/db/sql.ts";
import type { Generated, Kysely } from "kysely";
+1 -1
View File
@@ -4,7 +4,7 @@ import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
import { join } from "node:path";
import { after, test } from "node:test";
import { eventCounts, recordEvent } from "../src/discord/events.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
import { SCRATCH } from "./scratch.ts";
mkdirSync(SCRATCH, { recursive: true });
+1 -1
View File
@@ -14,7 +14,7 @@ import { TokenBox } from "../src/dash/server/crypto.ts";
import type { Provider, Tokens } from "../src/dash/server/provider.ts";
import { reporterSignIn } from "../src/dash/server/reporter-signin.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
mkdirSync(SCRATCH, { recursive: true });
const dir = mkdtempSync(join(SCRATCH, "discord-file-"));
+1 -1
View File
@@ -13,7 +13,7 @@ import { publicRepoNames } from "../src/public/status.ts";
import { slugOf } from "../src/owners.ts";
import { trackRepo, trackedNames } from "../src/repos.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
mkdirSync(SCRATCH, { recursive: true });
const dir = mkdtempSync(join(SCRATCH, "discord-filing-"));
+1 -1
View File
@@ -22,7 +22,7 @@ import type { CallbackData, CommandDef, DiscordRest, EditBody, MessageBody } fro
import { Search } from "../src/discord/search.ts";
import { installSearchCommands } from "../src/discord/search-commands.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
import { excluded } from "../src/db/kx.ts";
mkdirSync(SCRATCH, { recursive: true });
+1 -1
View File
@@ -7,7 +7,7 @@ import { DiscordKeys } from "../src/discord/keys.ts";
import { CODE_TTL_MS, createLinkCode, forgetLink, loginOf, redeemLinkCode } from "../src/discord/links.ts";
import { publicStats, publicStatus } from "../src/public/status.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
import { cols } from "../src/db/kx.ts";
mkdirSync(SCRATCH, { recursive: true });
+1 -1
View File
@@ -12,7 +12,7 @@ import { handleMeta } from "../src/discord/index.ts";
import { setup } from "../src/dash/api/discord.ts";
import { countOf, forgetAuthor, handleDispatch, linksOf } from "../src/discord/store.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
import { cols, excluded } from "../src/db/kx.ts";
mkdirSync(SCRATCH, { recursive: true });
+1 -1
View File
@@ -8,7 +8,7 @@ import { dispatcher } from "../src/discord/index.ts";
import { Reactor, setReactEmoji } from "../src/discord/react.ts";
import { RestError } from "../src/discord/rest.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
mkdirSync(SCRATCH, { recursive: true });
const dir = mkdtempSync(join(SCRATCH, "discord-react-"));
+1 -1
View File
@@ -19,7 +19,7 @@ import { Search } from "../src/discord/search.ts";
import { installSearchCommands } from "../src/discord/search-commands.ts";
import { SCRATCH } from "./scratch.ts";
import { mapSeq } from "../src/async-seq.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
import { excluded } from "../src/db/kx.ts";
import { sqliteOnly } from "./test-db.ts";
+1 -1
View File
@@ -9,7 +9,7 @@ import { SIGNAL_CAP_KEY, Signals, signalCountOf, signalLinks, type Judge } from
import { handleDispatch } from "../src/discord/store.ts";
import type { Req } from "../src/dash/types.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
import { excluded } from "../src/db/kx.ts";
mkdirSync(SCRATCH, { recursive: true });
+1 -1
View File
@@ -9,7 +9,7 @@ import { Interactions } from "../src/discord/interactions.ts";
import { DiscordKeys } from "../src/discord/keys.ts";
import { createLinkCode, redeemLinkCode } from "../src/discord/links.ts";
import type { EditBody, MessageBody } from "../src/discord/rest.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
import { SCRATCH } from "./scratch.ts";
mkdirSync(SCRATCH, { recursive: true });
+1 -2
View File
@@ -2,8 +2,7 @@ import assert from "node:assert/strict";
import { test } from "node:test";
import { pollReleases, type GhRelease, type RepoReleases } from "../src/downloads/poll.ts";
import { downloadsReport } from "../src/downloads/report.ts";
import type { Db } from "../src/db/index.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb, type Db } from "./helpers/raw-db.ts";
const T0 = Date.parse("2026-11-01T10:20:00Z");
const H = 3600_000;
+1 -1
View File
@@ -4,7 +4,7 @@ import { currentComparison, kindSets } from "../src/dupes/plan.ts";
import { loadDupeState, saveComparisons, type ComparisonPut } from "../src/data/triage/index.ts";
import { fillEmbedHashes } from "../src/itemhash.ts";
import { T0, world } from "./world-db.ts";
import type { Db } from "../src/db/index.ts";
import type { Db } from "./helpers/raw-db.ts";
/**
* A confirmed duplicate pair of PRs 1 and 2 at their current text, so the two form a group in the stored state. An edit outside
+1 -1
View File
@@ -5,7 +5,7 @@ import { join } from "node:path";
import { test } from "node:test";
import { scanChunk } from "../src/dupes/scan.ts";
import type { VectorIndex } from "../src/embed/vectors.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
import { SCRATCH } from "./scratch.ts";
const T0 = "2026-01-01T00:00:00.000Z";
+1 -1
View File
@@ -5,7 +5,7 @@ import { createToken } from "../src/dash/mcp/tokens.ts";
import { bundleOf, claimCall, heartbeat, submitCall, type Caller } from "../src/remote/calls.ts";
import { parseStatus, storeStatus } from "../src/remote/helpers.ts";
import { PROTOCOL_VERSION, type TaskBundle, type SubmitTool } from "../src/remote/protocol.ts";
import type { Db } from "../src/db/index.ts";
import type { Db } from "./helpers/raw-db.ts";
/** What a call hands the runner: its bundle, with the call id. `beat` sends a heartbeat with a progress line. */
export type FakeCall = TaskBundle;
+1 -1
View File
@@ -8,7 +8,7 @@ import { runFixup, type FixupDeps } from "../src/fixup/index.ts";
import { selectFixups } from "../src/fixup/select.ts";
import { SCRATCH } from "./scratch.ts";
import { validating } from "./gql.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
mkdirSync(SCRATCH, { recursive: true });
const dir = mkdtempSync(join(SCRATCH, "fixup-conflict-skip-"));
+1 -2
View File
@@ -10,8 +10,7 @@ import { CancelledError, StoppedError } from "../src/agents/call.ts";
import { reportingTaskRunner } from "./fake-runner.ts";
import { SCRATCH } from "./scratch.ts";
import { validating } from "./gql.ts";
import type { Db } from "../src/db/index.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb, type Db } from "./helpers/raw-db.ts";
mkdirSync(SCRATCH, { recursive: true });
const dir = mkdtempSync(join(SCRATCH, "fixup-pool-"));
+1 -2
View File
@@ -13,8 +13,7 @@ import { validatePatch, type FixupPr } from "../src/fixup/patch.ts";
import { REPO_PATH } from "../src/sandbox/command.ts";
import { SCRATCH } from "./scratch.ts";
import { validating } from "./gql.ts";
import type { Db } from "../src/db/index.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb, type Db } from "./helpers/raw-db.ts";
import * as kx from "../src/db/kx.ts";
mkdirSync(SCRATCH, { recursive: true });
+1 -1
View File
@@ -8,7 +8,7 @@ import type { PlanSet } from "../src/core/plan-set.ts";
import { planned } from "../src/core/select.ts";
import { carriedReview } from "../src/review/carry.ts";
import { prFacts } from "./world.ts";
import { connectDb, dbFor } from "../src/db/open.ts";
import { connectDb, dbFor } from "./helpers/raw-db.ts";
import { sqliteOnly } from "./test-db.ts";
test("selection order: our broken push, then work in flight, then score", { skip: sqliteOnly("raw DatabaseSync handle (convert to connectDb)") }, async () => {
+2 -1
View File
@@ -4,7 +4,8 @@
import { after, before, test } from "node:test";
import assert from "node:assert/strict";
import type { Compilable, Expression, SqlBool } from "kysely";
import type { Db, NamedParams, Param } from "../src/db/index.ts";
import type { NamedParams, Param } from "../src/db/index.ts";
import type { Db } from "./helpers/raw-db.ts";
import type { AnyEb } from "../src/db/kx.ts";
import { pilotExpr, pilotExprFor, pilotSql, pilotSqlFor } from "../src/pilot.ts";
import { backlogHeldExpr, backlogHeldSql } from "../src/dupes/held.ts";
+2 -2
View File
@@ -3,8 +3,8 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { join } from "node:path";
import type { Db, Param } from "../src/db/index.ts";
import { connectDb } from "../src/db/open.ts";
import type { Param } from "../src/db/index.ts";
import { connectDb, type Db } from "./helpers/raw-db.ts";
import { hiddenTestExpr, type HiddenRepos } from "../src/hidden-sql.ts";
import { quietPrExpr } from "../src/data/security/fragments.ts";
import { latestCteExpr, trackedExpr } from "../src/dash/api/stats.ts";
+1 -1
View File
@@ -17,7 +17,7 @@ import { startServer } from "../src/dash/server/index.ts";
import { FakeProvider } from "../src/dash/server/provider.ts";
import type { Route } from "../src/dash/types.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
import * as kx from "../src/db/kx.ts";
mkdirSync(SCRATCH, { recursive: true });
+1 -1
View File
@@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync } from "node:fs";
import { join } from "node:path";
import { test } from "node:test";
import { pushedByAutoCraft, writesOf } from "../src/dash/api/github-writes.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
import { SCRATCH } from "./scratch.ts";
mkdirSync(SCRATCH, { recursive: true });
+1 -1
View File
@@ -12,7 +12,7 @@ import { mergeDecisionId } from "../src/merge/queue.ts";
import { parseSafeMergeArgs, safeMerge } from "../src/merge/safe-merge.ts";
import { world } from "./world-db.ts";
import { prFacts } from "./world.ts";
import type { Db } from "../src/db/index.ts";
import type { Db } from "./helpers/raw-db.ts";
const ref = { repo: "app", number: 1 };
const open: LiveRead = { state: "OPEN", head: "sha1", draft: false, mergeable: "MERGEABLE" };
+9 -7
View File
@@ -1,7 +1,7 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import type { Kysely } from "kysely";
import { effect, effectsInTx } from "../src/db/effects.ts";
import { effect, effectsInTx, note } from "../src/db/effects.ts";
import { queryDb } from "../src/db/query-db.ts";
import { expectFlat } from "./helpers/query-count.ts";
import { testDatabase } from "./test-db.ts";
@@ -10,7 +10,7 @@ type T = { t: { id: number; v: string | null } };
const SCHEMA = "CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)";
test("a meter counts its own context's statements, rows and effects; an inner meter adds to it; an effect inside a transaction is reported", async () => {
test("a meter counts its own context's statements, rows and effects; an inner meter adds to it; an effect inside a transaction or a wave throws in tests and is counted in production", async () => {
const tdb = await testDatabase(SCHEMA);
try {
const db = queryDb(await tdb.open());
@@ -26,20 +26,22 @@ test("a meter counts its own context's statements, rows and effects; an inner me
const rows = await db.all(k.selectFrom("t").selectAll());
const inner = await db.meter(async () => {
await db.prepare("SELECT 1 AS x").get();
effect(db, "http", "test outside a transaction");
effect("http", "test outside a transaction");
});
await db.write(async () => {
await db.run(k.updateTable("t").set({ v: "c" }).where("id", "=", 1));
effect(db, "github-write", "test inside a transaction");
assert.throws(() => effect("github-write", "test inside a transaction"), /inside a database transaction \(test inside a transaction\)/);
});
return { rows: rows.length, stats: inner.stats };
});
await outside;
await db.together(async () => assert.throws(() => effect("model-call"), /inside a db\.together wave/));
note("github-write", "a database transaction", "test in production", false);
assert.ok(stats.statements > inner.stats.statements, "the outer meter counts the inner one's statements and its own");
assert.equal(stats.effects, inner.stats.effects + 1);
assert.ok(stats.rows >= inner.rows + inner.stats.rows);
assert.equal(effectsInTx().count, reported + 1, "only the effect inside the transaction is reported");
assert.ok(effectsInTx().sites.some((s) => s.site === "test inside a transaction" && s.kind === "github-write"));
assert.equal(effectsInTx().count, reported + 1);
assert.ok(effectsInTx().sites.some((s) => s.site === "test in production" && s.kind === "github-write"));
} finally {
await tdb.close();
}
@@ -56,7 +58,7 @@ test("expectFlat fails a unit that reads per item and passes a set-based one, al
if (style === "per-item") return await Promise.all(ids.map((id) => db.get(k.selectFrom("t").selectAll().where("id", "=", id))));
const rows = await db.all(k.selectFrom("t").selectAll().where("id", "in", ids));
if (style === "set with writes") for (const r of rows) {
effect(db, "github-write", "test");
effect("github-write", "test");
await db.run(k.updateTable("t").set({ v: "b" }).where("id", "=", r.id));
}
return rows;
+1 -1
View File
@@ -9,7 +9,7 @@ import { addLogin, checkGithubId } from "../src/access.ts";
import { setGithubIdentity } from "../src/github/identity.ts";
import { parseWorkerConfig } from "../src/worker/config.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
const KEY = "hardening-session-key-hardening-0";
+1 -1
View File
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
import { test } from "node:test";
import { health } from "../src/dash/api/health.ts";
import type { Req } from "../src/dash/types.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
import * as kx from "../src/db/kx.ts";
const req = (role: "operator" | "viewer"): Req => ({
+14
View File
@@ -0,0 +1,14 @@
// The database as tests use it: the app's handle with its query methods (`QueryDb`), which feature code holds without
// them. Tests seed and read tables directly through it.
import type { DatabaseSync } from "node:sqlite";
import * as open from "../../src/db/open.ts";
import { queryDb, type QueryDb } from "../../src/db/query-db.ts";
export type Db = QueryDb;
/** `connectDb` of src/db/open.ts, with the query methods. */
export const connectDb = async (...args: Parameters<typeof open.connectDb>): Promise<Db> => queryDb(await open.connectDb(...args));
/** `dbFor` of src/db/open.ts, with the query methods. */
export const dbFor = async (sync: DatabaseSync): Promise<Db> => queryDb(await open.dbFor(sync));
/** `openDb` of src/db/open.ts, with the query methods. */
export const openDb = async (): Promise<Db> => queryDb(await open.openDb());
+1 -1
View File
@@ -11,7 +11,7 @@ import { writeItemNode } from "../src/mirror.ts";
import { contributors, isWhitelisted, setOverride, tierKey, tiersOf } from "../src/whitelist.ts";
import { SCRATCH } from "./scratch.ts";
import { T0, world, type World } from "./world-db.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
let current: World | null = null;
afterEach(() => current?.close());
+1 -1
View File
@@ -11,7 +11,7 @@ import { closeItem } from "../src/github/write.ts";
import type { GuardedItem } from "../src/core/guard.ts";
import type { Querier } from "../src/mirror.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
import * as kx from "../src/db/kx.ts";
const grant = (as: string): GuardedItem => ({ scope: "item", action: { kind: "act" }, repo: "app", number: 7, as }) as unknown as GuardedItem;
+2 -2
View File
@@ -73,7 +73,7 @@ function withCallRows(s: Awaited<ReturnType<typeof setup>>) {
const queue = s.deps.calls.queue;
s.deps.calls.queue = async (db, r) => {
const id = await queue(db, r), now = Date.now();
await db.run(db.k.insertInto("main.remote_calls").values({
await s.db.run(s.db.k.insertInto("main.remote_calls").values({
id, step: "implement", stage: 0, prompt_id: r.promptId, prompt_version: r.promptVersion, tier: r.tier, effort: r.effort, asked_model: r.model, bundle: "{}",
state: "queued", since: now, seen_at: now, max_attempts: 2, timeout_ms: 1000, parent_id: r.parentId ?? null,
} as never));
@@ -127,7 +127,7 @@ test("a restart after a turn's reply was read asks the same session for the repo
const normal = s.deps.calls.await;
s.deps.calls.await = async (db, id) => {
// The reply is read (and dropped from the call) and the runner stops before the round is written.
await db.run(db.k.updateTable("main.remote_calls").set({ state: "done", reply: null, consumed_at: Date.now() }).where("id", "=", id));
await s.db.run(s.db.k.updateTable("main.remote_calls").set({ state: "done", reply: null, consumed_at: Date.now() }).where("id", "=", id));
throw new Error(RESTART);
};
await assert.rejects(runBuild(s.run, "app", 7, s.deps), new RegExp(RESTART));
+1 -1
View File
@@ -7,7 +7,7 @@ import { parsePlanReply, recordPlan } from "../src/implement/plan.ts";
import { currentImplementation, roundsOf, startImplementation } from "./implement-rows.ts";
import type { PlanReply, QuestionRound } from "../src/implement/types.ts";
import { join } from "node:path";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
import { OPERATOR, tmpdir, world } from "./world-db.ts";
import { loadItemFact } from "../src/core/issue-facts.ts";
import { rememberSlug } from "../src/github/identity.ts";
+1 -1
View File
@@ -6,7 +6,7 @@ import { chmodSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "n
import { join } from "node:path";
import { test } from "node:test";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
import { compileTimeChanges, DIFF_FLAGS, MAX_IMPLEMENTATION_FILES, MAX_IMPLEMENTATION_LINES, validateImplementation } from "../src/implement/diff.ts";
import { implBranch, implPrBody, implTitle } from "../src/implement/template.ts";
import { openImplementationPr } from "../src/implement/pr.ts";
+1 -1
View File
@@ -1,5 +1,5 @@
// The implement tests' reads and writes of attempts by id, over the implement module and its row shapes.
import type { Db } from "../src/db/index.ts";
import type { Db } from "./helpers/raw-db.ts";
import { recordSteps, startAttempt } from "../src/data/implement/index.ts";
import { IMPL_COLS, ofRow, roundOf, type ImplRow, type RoundRow } from "../src/data/implement/rows.ts";
import { currentAttempt } from "../src/implement/attempt.ts";
+1 -1
View File
@@ -7,7 +7,7 @@ import { createToken } from "../src/dash/mcp/tokens.ts";
import { computeChecks } from "../src/health-checks.ts";
import { parseStatus, storeStatus } from "../src/remote/helpers.ts";
import { SCRATCH } from "./scratch.ts";
import { connectDb } from "../src/db/open.ts";
import { connectDb } from "./helpers/raw-db.ts";
mkdirSync(SCRATCH, { recursive: true });
Loaded 100 of 205 files, more files were not shown because too many files have changed in this diff. Show more