From f2c76aa9e5fa4bb5f00f8ca6d3bfb798970cc093 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:25:01 +0000 Subject: [PATCH] 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 --- docs/operations.md | 4 +- scripts/data-layer-allow.ts | 65 --------- scripts/gen-db-types.ts | 6 +- scripts/remote-claim-bench.ts | 3 +- src/build/launcher.ts | 2 + src/build/workspace-fetch.ts | 2 + src/build/workspace-launch.ts | 2 + src/classify/run.ts | 3 + src/dash/api/related.ts | 13 +- src/data/build/types.ts | 6 +- src/data/control/ping.ts | 4 +- src/data/inference/runs.ts | 9 -- src/data/jobs/lifecycle.ts | 2 +- src/data/jobs/sql.ts | 3 +- src/data/mirror/checks.ts | 16 +-- src/data/mirror/local.ts | 14 +- src/data/runners/fragments.ts | 3 +- src/data/security/findings.ts | 2 +- src/data/views/activity.ts | 16 ++- src/data/workflow/update.ts | 6 +- src/db/bytes-read.ts | 116 ++++++++++++++++ src/db/copy.ts | 39 +++--- src/db/effects.ts | 34 +++-- src/db/fence.ts | 4 +- src/db/handle.ts | 48 +++++-- src/db/index.ts | 61 +-------- src/db/kx.ts | 23 ++-- src/db/leader.ts | 13 +- src/db/open.ts | 6 +- src/db/postgres.ts | 2 +- src/db/query-db.ts | 13 +- src/db/retired.ts | 17 +-- src/db/sqlite-backfill.ts | 12 +- src/db/switch-over.ts | 26 ++-- src/db/types.ts | 3 + src/fixup/git.ts | 2 + src/github/app.ts | 2 + src/github/write.ts | 4 + src/mirror.ts | 3 + test/activity.test.ts | 3 +- test/admin.test.ts | 2 +- test/agent-run-trace.test.ts | 3 +- test/allowed-owners.test.ts | 2 +- test/api.test.ts | 2 +- test/app-lane.test.ts | 2 +- test/areas-store.test.ts | 3 +- test/auth-hardening.test.ts | 2 +- test/base-binding.test.ts | 2 +- test/build-features.test.ts | 2 +- test/build-mem.test.ts | 2 +- test/build-pods.test.ts | 2 +- test/build-sizing.test.ts | 2 +- test/build.test.ts | 2 +- test/ci-first-migration.test.ts | 2 +- test/cifix-pool.test.ts | 2 +- test/cifix.test.ts | 3 +- test/conflict-merge-cost.test.ts | 2 +- test/conversations.test.ts | 3 +- test/dash-insight.test.ts | 2 +- test/data-layer-allow.json | 5 - test/data-layer.test.ts | 67 +++++++-- test/data/mirror-checks.test.ts | 2 +- test/data/mirror-comments.test.ts | 2 +- test/data/mirror-fixture.ts | 3 +- test/data/mirror-local.test.ts | 2 +- test/db-layer.test.ts | 4 +- test/discord-events.test.ts | 2 +- test/discord-file-issue.test.ts | 2 +- test/discord-filing-repos.test.ts | 2 +- test/discord-issue-new.test.ts | 2 +- test/discord-links.test.ts | 2 +- test/discord-mentions.test.ts | 2 +- test/discord-react.test.ts | 2 +- test/discord-search.test.ts | 2 +- test/discord-signals.test.ts | 2 +- test/discord-workflow-alerts.test.ts | 2 +- test/downloads-report.test.ts | 3 +- test/dupes-current.test.ts | 2 +- test/dupes-scan.test.ts | 2 +- test/fake-runner.ts | 2 +- test/fixup-conflict-skip.test.ts | 2 +- test/fixup-pool.test.ts | 3 +- test/fixup.test.ts | 3 +- test/flight.test.ts | 2 +- test/fragments-a.test.ts | 3 +- test/fragments-b.test.ts | 4 +- test/github-app.test.ts | 2 +- test/github-writes.test.ts | 2 +- test/guard.test.ts | 2 +- test/handle-meter.test.ts | 16 ++- test/hardening-lead-a.test.ts | 2 +- test/health-api.test.ts | 2 +- test/helpers/raw-db.ts | 14 ++ test/identity-sec3.test.ts | 2 +- test/identity.test.ts | 2 +- test/implement-build.test.ts | 4 +- test/implement-plan.test.ts | 2 +- test/implement-pr.test.ts | 2 +- test/implement-rows.ts | 2 +- test/interactive-no-taker.test.ts | 2 +- test/issue-stalls.test.ts | 2 +- test/item-settled.test.ts | 3 +- test/item-status.test.ts | 2 +- test/item-trace.test.ts | 3 +- test/itemtools-pg.test.ts | 2 +- test/itemtools-safety.test.ts | 2 +- test/itemtools.test.ts | 2 +- test/jevcost.test.ts | 2 +- test/job-items.test.ts | 2 +- test/job-log.test.ts | 2 +- test/kx.test.ts | 6 +- test/leader-pg.test.ts | 2 +- test/leases.test.ts | 2 +- test/lint-fix-turn.test.ts | 2 +- test/live-board.test.ts | 2 +- test/live-topics.test.ts | 2 +- test/mainfix-pr.test.ts | 3 +- test/maintain-home.test.ts | 2 +- test/maintain-item.test.ts | 2 +- test/maintainer-repo-actions.test.ts | 2 +- test/maintainer-run-actions.test.ts | 2 +- test/mcp-settings.test.ts | 2 +- test/mcp.test.ts | 2 +- test/migration.test.ts | 3 +- test/mirror.test.ts | 3 +- test/next-page.test.ts | 2 +- test/nightly-api.test.ts | 2 +- test/nightly.test.ts | 2 +- test/operator-actions.test.ts | 2 +- test/outside-limits.test.ts | 3 +- test/pg-db.test.ts | 2 +- test/pg-triggers.test.ts | 2 +- test/pg-upgrade.test.ts | 2 +- test/pipeline.test.ts | 2 +- test/plan-cache.test.ts | 3 +- test/plan-changes.test.ts | 3 +- test/planner-taker.test.ts | 2 +- test/pool-skip.test.ts | 2 +- test/portable.test.ts | 3 +- test/pr-builds.test.ts | 3 +- test/prompts.test.ts | 2 +- test/push-outcome.test.ts | 2 +- test/push-tests.test.ts | 3 +- test/query-count.test.ts | 190 ++++++++++++++++++++++++++ test/rank.test.ts | 2 +- test/read-env.test.ts | 3 +- test/reference.test.ts | 2 +- test/remote-calls.test.ts | 2 +- test/remote-claim-timeout.test.ts | 2 +- test/remote-helper-visibility.test.ts | 2 +- test/remote-longpoll.test.ts | 2 +- test/remote-no-taker.test.ts | 2 +- test/remote-permission.test.ts | 2 +- test/remote-picks.test.ts | 3 +- test/remote-refusal.test.ts | 2 +- test/remote-room-repos.test.ts | 2 +- test/remote-tools.test.ts | 2 +- test/repo-owners.test.ts | 2 +- test/retired-drop.test.ts | 3 +- test/review-followups.test.ts | 2 +- test/review-migration.test.ts | 3 +- test/runner-credentials.test.ts | 2 +- test/runner-steps.ts | 3 +- test/runner.test.ts | 2 +- test/sandbox.test.ts | 2 +- test/scoped.test.ts | 2 +- test/screenshot-config.test.ts | 2 +- test/screenshots-plan.test.ts | 3 +- test/screenshots.test.ts | 3 +- test/search.test.ts | 2 +- test/secfix-rounds.test.ts | 2 +- test/security-cli.test.ts | 2 +- test/security-fix-land.test.ts | 3 +- test/security-scan-tests.test.ts | 2 +- test/security-scan.test.ts | 2 +- test/server.test.ts | 2 +- test/step-health.test.ts | 2 +- test/step-repo.test.ts | 2 +- test/stream-progress.test.ts | 3 +- test/stuck-jobs.test.ts | 2 +- test/switch-over.test.ts | 3 +- test/sync-health.test.ts | 2 +- test/test-db.ts | 3 +- test/test-repo-trip.test.ts | 3 +- test/trip-resume-maintainer.test.ts | 3 +- test/unsent-comment.test.ts | 2 +- test/vault.test.ts | 2 +- test/views-lists.test.ts | 2 +- test/visibility-sec3.test.ts | 2 +- test/visibility.test.ts | 2 +- test/warm-caches.test.ts | 2 +- test/warm-repos.test.ts | 2 +- test/webhooks.test.ts | 2 +- test/worker-hardening.test.ts | 2 +- test/worker-output-sec3.test.ts | 2 +- test/worker-trust.test.ts | 2 +- test/workspace-fetch.test.ts | 2 +- test/workspace-pods.test.ts | 2 +- test/workspace-relay.test.ts | 2 +- test/workspace-sessions.test.ts | 2 +- test/workspace-tools.test.ts | 2 +- test/workspace-warm.test.ts | 2 +- test/workspaces-api.test.ts | 2 +- test/world-db.ts | 3 +- test/write-pacing.test.ts | 2 +- 205 files changed, 787 insertions(+), 481 deletions(-) delete mode 100644 scripts/data-layer-allow.ts create mode 100644 src/db/bytes-read.ts delete mode 100644 test/data-layer-allow.json create mode 100644 test/helpers/raw-db.ts create mode 100644 test/query-count.test.ts diff --git a/docs/operations.md b/docs/operations.md index ba0b6a73..f81c1669 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -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: diff --git a/scripts/data-layer-allow.ts b/scripts/data-layer-allow.ts deleted file mode 100644 index 5a16e055..00000000 --- a/scripts/data-layer-allow.ts +++ /dev/null @@ -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")); -} diff --git a/scripts/gen-db-types.ts b/scripts/gen-db-types.ts index 02add9fd..7817bb50 100644 --- a/scripts/gen-db-types.ts +++ b/scripts/gen-db-types.ts @@ -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(); diff --git a/scripts/remote-claim-bench.ts b/scripts/remote-claim-bench.ts index 36ee7e35..180224b0 100644 --- a/scripts/remote-claim-bench.ts +++ b/scripts/remote-claim-bench.ts @@ -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 = { 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 (?, ?, ?, ?)"); diff --git a/src/build/launcher.ts b/src/build/launcher.ts index d62f6193..f61f763f 100644 --- a/src/build/launcher.ts +++ b/src/build/launcher.ts @@ -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)); } diff --git a/src/build/workspace-fetch.ts b/src/build/workspace-fetch.ts index 8b7e5c6d..5098a33e 100644 --- a/src/build/workspace-fetch.ts +++ b/src/build/workspace-fetch.ts @@ -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 { diff --git a/src/build/workspace-launch.ts b/src/build/workspace-launch.ts index 1798fd7b..d47bb62f 100644 --- a/src/build/workspace-launch.ts +++ b/src/build/workspace-launch.ts @@ -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 { 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); diff --git a/src/classify/run.ts b/src/classify/run.ts index 4f5041c5..df752c68 100644 --- a/src/classify/run.ts +++ b/src/classify/run.ts @@ -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(id: K, model: string, input: ClaudeInput[K], db: Db, opts: AskOptions = {}): Promise { + 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(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 { + 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 { diff --git a/src/dash/api/related.ts b/src/dash/api/related.ts index 58ddf1ec..767d3b24 100644 --- a/src/dash/api/related.ts +++ b/src/dash/api/related.ts @@ -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 = (s: string | null | undefined, d: T): T => { @@ -15,7 +16,7 @@ const json = (s: string | null | undefined, d: T): T => { export async function classificationsOf(db: Db, repo: string, n: number): Promise { // 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(); 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 { 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(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(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; diff --git a/src/data/build/types.ts b/src/data/build/types.ts index 6fe1925d..ce250cde 100644 --- a/src/data/build/types.ts +++ b/src/data/build/types.ts @@ -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>; export type WorkspaceRow = Omit, "checkpoint"> & { checkpoint?: Uint8Array | null }; export type SessionRow = Selectable; export type WorkspaceCallRow = Selectable; -export type NewSession = import("kysely").Insertable; +export type NewSession = Insertable; 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> }; -export type WorkspaceSource = { ids: number[] } | { env: string; states: WorkspaceStateName[] } | { remoteCallIds: number[] } | { idsFrom: import("kysely").SelectQueryBuilder }; +export type WorkspaceSource = { ids: number[] } | { env: string; states: WorkspaceStateName[] } | { remoteCallIds: number[] } | { idsFrom: SelectQueryBuilder }; /** `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 }[]; diff --git a/src/data/control/ping.ts b/src/data/control/ping.ts index 0e7feae7..791b66bc 100644 --- a/src/data/control/ping.ts +++ b/src/data/control/ping.ts @@ -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 { 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; diff --git a/src/data/inference/runs.ts b/src/data/inference/runs.ts index 1dc61824..5b3f89f8 100644 --- a/src/data/inference/runs.ts +++ b/src/data/inference/runs.ts @@ -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}`); -} diff --git a/src/data/jobs/lifecycle.ts b/src/data/jobs/lifecycle.ts index 13cb5f4d..72326400 100644 --- a/src/data/jobs/lifecycle.ts +++ b/src/data/jobs/lifecycle.ts @@ -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"; diff --git a/src/data/jobs/sql.ts b/src/data/jobs/sql.ts index 7eebb2a0..95533f7d 100644 --- a/src/data/jobs/sql.ts +++ b/src/data/jobs/sql.ts @@ -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"; diff --git a/src/data/mirror/checks.ts b/src/data/mirror/checks.ts index 99ec81f4..c712e5b7 100644 --- a/src/data/mirror/checks.ts +++ b/src/data/mirror/checks.ts @@ -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 { 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 { 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 { 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 { 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))); }); } diff --git a/src/data/mirror/local.ts b/src/data/mirror/local.ts index 054cd787..fbd61a2a 100644 --- a/src/data/mirror/local.ts +++ b/src/data/mirror/local.ts @@ -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)[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)[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)[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("julianday", [eb.ref("excluded.synced_at")]), ">=", eb.fn("julianday", [eb.ref("main.item_reads.synced_at")]))))); } diff --git a/src/data/runners/fragments.ts b/src/data/runners/fragments.ts index df00893a..8db4b906 100644 --- a/src/data/runners/fragments.ts +++ b/src/data/runners/fragments.ts @@ -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"; diff --git a/src/data/security/findings.ts b/src/data/security/findings.ts index 9dfb6f83..7ba06e21 100644 --- a/src/data/security/findings.ts +++ b/src/data/security/findings.ts @@ -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, diff --git a/src/data/views/activity.ts b/src/data/views/activity.ts index 9a951375..c4225b9e 100644 --- a/src/data/views/activity.ts +++ b/src/data/views/activity.ts @@ -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; + q: (db: QueryDb, c: Ctx) => SelectQueryBuilder; 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 { - 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 { + const { k } = queryDb(db); const probes = [ - ...sourcesOf(key.kinds).map((s) => db.k.selectFrom(s.table as "items").select((eb) => eb.fn.max(kx.ref(s.time.replace(/^\w+\./, ""))).as("m"))), - db.k.selectFrom("agent_runs").select((eb) => eb.fn.countAll().as("n")).where("state", "=", "running"), - db.k.selectFrom("jobs").select((eb) => [eb.fn.countAll().as("n"), eb.fn.max("id").as("newest")]).where("state", "in", ["queued", "running"]), - db.k.selectFrom("build_tasks").select((eb) => eb.fn.countAll().as("n")).where("state", "in", ["queued", "claimed", "running"]), + ...sourcesOf(key.kinds).map((s) => k.selectFrom(s.table as "items").select((eb) => eb.fn.max(kx.ref(s.time.replace(/^\w+\./, ""))).as("m"))), + k.selectFrom("agent_runs").select((eb) => eb.fn.countAll().as("n")).where("state", "=", "running"), + k.selectFrom("jobs").select((eb) => [eb.fn.countAll().as("n"), eb.fn.max("id").as("newest")]).where("state", "in", ["queued", "running"]), + k.selectFrom("build_tasks").select((eb) => eb.fn.countAll().as("n")).where("state", "in", ["queued", "claimed", "running"]), ]; return (await kx.rowValues(db, probes as SelectQueryBuilder[])); } diff --git a/src/data/workflow/update.ts b/src/data/workflow/update.ts index 9ac37c79..8894e2be 100644 --- a/src/data/workflow/update.ts +++ b/src/data/workflow/update.ts @@ -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; @@ -14,12 +15,13 @@ export async function patchRows( db: Db, table: string, key: Types, set: Types, rows: readonly Record[], o: { also?: (eb: kx.AnyEb) => Record>; when?: (eb: kx.AnyEb) => Expression; guard?: Types } = {}, ): Promise { + 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; } diff --git a/src/db/bytes-read.ts b/src/db/bytes-read.ts new file mode 100644 index 00000000..5ebca9e3 --- /dev/null +++ b/src/db/bytes-read.ts @@ -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(BYTES_COLUMNS); + +// Nodes are read as plain objects: this module must not load kysely. +type N = { readonly kind: string } & Record; +/** 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(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 { + 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(); + 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(); + +/** 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; +} diff --git a/src/db/copy.ts b/src/db/copy.ts index 90b8827f..b7a37178 100644 --- a/src/db/copy.ts +++ b/src/db/copy.ts @@ -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; } @@ -76,7 +77,7 @@ export function describeTarget(target: string): string { return u.toString(); } -async function sqliteTables(db: Db): Promise> { +async function sqliteTables(db: QueryDb): Promise> { const out = new Map(); 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> { return out; } -async function pgTables(db: Db): Promise> { +async function pgTables(db: QueryDb): Promise> { 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> { return out; } -const tablesOf = (db: Db): Promise> => (db.dialect === "postgres" ? pgTables(db) : sqliteTables(db)); +const tablesOf = (db: QueryDb): Promise> => (db.dialect === "postgres" ? pgTables(db) : sqliteTables(db)); async function openSide(target: string, opts: { readOnly: boolean }): Promise { - 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, b: Pick { +async function* pages(db: QueryDb, t: Table, batch: number): AsyncGenerator { 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> { +async function sequences(db: QueryDb): Promise> { const out = new Map(); 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> { 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, source: Map): Promise { +async function setPgSequences(db: QueryDb, copied: Set, source: Map): Promise { 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, source: Map, source: Map): Promise { +async function setSqliteSequences(db: QueryDb, copied: Set, source: Map): Promise { 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 { } } -async function hasRows(db: Db, tables: Iterable): Promise { +async function hasRows(db: QueryDb, tables: Iterable): Promise { 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> { +async function clearTables(db: QueryDb, tables: string[]): Promise<() => Promise> { 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 { +async function finishSqlite(db: QueryDb, triggers: string[]): Promise { 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 { +async function digestTable(db: QueryDb, t: Table, batch: number): Promise { const cols = [...t.columns].sort(); const rowHashes: Buffer[] = []; for await (const page of pages(db, t, batch)) { diff --git a/src/db/effects.ts b/src/db/effects.ts index cd05ea62..47eba34f 100644 --- a/src/db/effects.ts +++ b/src/db/effects.ts @@ -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(); /** - * 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 })) }; } diff --git a/src/db/fence.ts b/src/db/fence.ts index 3eb3c2df..517f8938 100644 --- a/src/db/fence.ts +++ b/src/db/fence.ts @@ -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 { 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`); } diff --git a/src/db/handle.ts b/src/db/handle.ts index 1344957d..20faa1bc 100644 --- a/src/db/handle.ts +++ b/src/db/handle.ts @@ -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(); + +async function whileBusy(h: Handle, fn: () => Promise): Promise { + 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): Promise { @@ -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; 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); diff --git a/src/db/index.ts b/src/db/index.ts index 0ad0fed8..25207eda 100644 --- a/src/db/index.ts +++ b/src/db/index.ts @@ -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; @@ -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; - /** - * 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(q: Compilable): Promise; - /** - * Runs a Kysely query: all rows. - * @deprecated Queries belong in the data modules, which reach them through `queryDb` (src/db/query-db.ts). - */ - all(q: Compilable): Promise; - /** - * Runs a Kysely write. - * @deprecated Queries belong in the data modules, which reach them through `queryDb` (src/db/query-db.ts). - */ - run(q: Compilable): Promise; - /** - * 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; - /** - * 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(fn: () => Promise): Promise; /** 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; - /** - * 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; /** * 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; - /** The underlying SQLite connection, for code that cannot await yet. Absent on Postgres. */ - readonly sync?: DatabaseSync; } diff --git a/src/db/kx.ts b/src/db/kx.ts index f877ab21..824ece91 100644 --- a/src/db/kx.ts +++ b/src/db/kx.ts @@ -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) => Object.fromEntries(set.map((c) => [c, eb.ref(`v.${c}`)]))) .where((eb: ExpressionBuilder) => 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 = (rows: readonly T[]): T[][] => Array.from({ length: Ma * rowid only increases. Postgres runs two statements: call it inside `db.write`. */ export async function replaceRow(db: Db, table: T, key: readonly string[], row: InsertObject): Promise { - 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) => eb.and(key.map((c) => eb(c, "=", (row as Record)[c]))))); - await db.run(k.insertInto(table).values(row)); + await q.run(k.deleteFrom(table).where((eb: ExpressionBuilder) => eb.and(key.map((c) => eb(c, "=", (row as Record)[c]))))); + await q.run(k.insertInto(table).values(row)); } /** @@ -404,14 +405,14 @@ export async function replaceRow(db: Db, table: T, * rowids in the order given. Call inside `db.write`. */ export async function replaceRows(db: Db, table: T, key: readonly string[], rows: readonly InsertObject[]): Promise { - 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) => eb.or(chunk.map((row) => eb.and(key.map((c) => eb(c, "=", (row as Record)[c]))))))); - await db.run(k.insertInto(table).values(chunk)); + await q.run(k.deleteFrom(table).where((eb: ExpressionBuilder) => eb.or(chunk.map((row) => eb.and(key.map((c) => eb(c, "=", (row as Record)[c]))))))); + await q.run(k.insertInto(table).values(chunk)); } } @@ -538,7 +539,7 @@ export function rowArray(d: D, q: SelectQueryBuilder): RawBuilder * Every value is an integer, text or null, which a JSON array carries unchanged. */ export async function rowValues(db: Db, queries: readonly SelectQueryBuilder[]): Promise { - const row: Record | undefined = await db.get(db.k.selectNoFrom(queries.map((q, k) => rowArray(db, q).as(`c${k}`)))); + const row: Record | 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[]); }); } diff --git a/src/db/leader.ts b/src/db/leader.ts index 599ed065..3898cd1a 100644 --- a/src/db/leader.ts +++ b/src/db/leader.ts @@ -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 => new Promise(( signal?.addEventListener("abort", done, { once: true }); }); -async function putSetting(db: Db, key: string, value: string): Promise { +async function putSetting(db: QueryDb, key: string, value: string): Promise { 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`CAST(EXTRACT(EPOCH FROM clock_timesta type LeaseConn = { client: Pg.Client; info: ConnInfo; run: (q: Compilable) => Promise }; /** 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 { +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 { 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 { +export async function elect(handle: Db, role: LeaderRole, o: ElectOptions = {}): Promise { + 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 { +async function pruneStandbys(db: QueryDb, role: LeaderRole): Promise { 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 { * 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 = (v: string | null): T | null => { try { return v ? JSON.parse(v) as T : null; } catch { return null; } }; diff --git a/src/db/open.ts b/src/db/open.ts index c4f03d09..70cfb77f 100644 --- a/src/db/open.ts +++ b/src/db/open.ts @@ -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 { // 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 }; diff --git a/src/db/postgres.ts b/src/db/postgres.ts index 415062e7..3111e23e 100644 --- a/src/db/postgres.ts +++ b/src/db/postgres.ts @@ -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 diff --git a/src/db/query-db.ts b/src/db/query-db.ts index a10116cb..f7707cca 100644 --- a/src/db/query-db.ts +++ b/src/db/query-db.ts @@ -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; /** Runs a Kysely query: its first row. Inside `together` a SELECT joins the current wave. */ get(q: Compilable, o?: QueryOpts): Promise; @@ -16,11 +16,14 @@ export interface QueryDb extends Db { run(q: Compilable): Promise; /** Runs several statements with no parameters (schema scripts, PRAGMAs). */ script(text: string): Promise; - /** 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(fn: () => Promise): Promise; - /** See `Db.scope`. */ - scope(): Promise; - /** 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; diff --git a/src/db/retired.ts b/src/db/retired.ts index e9c3cc6f..7e6c6276 100644 --- a/src/db/retired.ts +++ b/src/db/retired.ts @@ -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 { */ export async function dropRetired(db: Db, o: { force?: boolean; target?: string; now?: string } & MigrationOpts = {}): Promise { 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): Promise => { @@ -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; } diff --git a/src/db/sqlite-backfill.ts b/src/db/sqlite-backfill.ts index 494762c7..2cfc4da8 100644 --- a/src/db/sqlite-backfill.ts +++ b/src/db/sqlite-backfill.ts @@ -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 { // 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; } diff --git a/src/db/switch-over.ts b/src/db/switch-over.ts index dc9265b5..a53fdbb5 100644 --- a/src/db/switch-over.ts +++ b/src/db/switch-over.ts @@ -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; /** Read at each use: the builder of the open transaction. */ -const q = (db: Db): any => db.k; -const all = (db: Db, x: any): Promise => db.all(x) as Promise; -const get = (db: Db, x: any): Promise => db.get(x) as Promise; -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 => queryDb(db).all(x) as Promise; +const get = (db: Db, x: any): Promise => queryDb(db).get(x) as Promise; +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 => @@ -269,9 +271,9 @@ async function carryLimits(db: Db, resets: [string, string][], perDay: Record { - 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 [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 { - 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[]); }); } } diff --git a/src/db/types.ts b/src/db/types.ts index 2580b983..bdd60407 100644 --- a/src/db/types.ts +++ b/src/db/types.ts @@ -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; diff --git a/src/fixup/git.ts b/src/fixup/git.ts index 73956754..79988289 100644 --- a/src/fixup/git.ts +++ b/src/fixup/git.ts @@ -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; input?: str export type Exec = (cmd: string, args: string[], opts?: ExecOpts) => Promise; 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. diff --git a/src/github/app.ts b/src/github/app.ts index 10bc1eb4..7aa4dc8e 100644 --- a/src/github/app.ts +++ b/src/github/app.ts @@ -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, nowMs = } export async function call(base: string, path: string, token: string | null, method = "GET", body?: unknown): Promise { + effect("http"); const r = await fetch(`${base}${path}`, { method, headers: { diff --git a/src/github/write.ts b/src/github/write.ts index bb0e1491..14eae358 100644 --- a/src/github/write.ts +++ b/src/github/write.ts @@ -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(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 { diff --git a/src/mirror.ts b/src/mirror.ts index ceea60bc..8a0b8c01 100644 --- a/src/mirror.ts +++ b/src/mirror.ts @@ -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 { + // 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) { diff --git a/test/activity.test.ts b/test/activity.test.ts index 5fc44fc0..dff6d4e4 100644 --- a/test/activity.test.ts +++ b/test/activity.test.ts @@ -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 = {}): Req => ({ method: "GET", path: "", params: {}, query: new URLSearchParams(query), form: new URLSearchParams(), csrf: "", nonce: "", diff --git a/test/admin.test.ts b/test/admin.test.ts index 4fa8b870..6d55fa8e 100644 --- a/test/admin.test.ts +++ b/test/admin.test.ts @@ -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 }); diff --git a/test/agent-run-trace.test.ts b/test/agent-run-trace.test.ts index c60d1ed9..8b6b6931 100644 --- a/test/agent-run-trace.test.ts +++ b/test/agent-run-trace.test.ts @@ -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 }] } }); diff --git a/test/allowed-owners.test.ts b/test/allowed-owners.test.ts index 16fe051b..5c3dcddd 100644 --- a/test/allowed-owners.test.ts +++ b/test/allowed-owners.test.ts @@ -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 }); diff --git a/test/api.test.ts b/test/api.test.ts index e0ed93f7..77095b13 100644 --- a/test/api.test.ts +++ b/test/api.test.ts @@ -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"; diff --git a/test/app-lane.test.ts b/test/app-lane.test.ts index 6adf60b5..f395f772 100644 --- a/test/app-lane.test.ts +++ b/test/app-lane.test.ts @@ -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"; diff --git a/test/areas-store.test.ts b/test/areas-store.test.ts index 6ee7cea7..a4c301c3 100644 --- a/test/areas-store.test.ts +++ b/test/areas-store.test.ts @@ -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"; diff --git a/test/auth-hardening.test.ts b/test/auth-hardening.test.ts index b9f36e8d..4e1ea1bf 100644 --- a/test/auth-hardening.test.ts +++ b/test/auth-hardening.test.ts @@ -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-")); diff --git a/test/base-binding.test.ts b/test/base-binding.test.ts index d660ce45..f7aee1f4 100644 --- a/test/base-binding.test.ts +++ b/test/base-binding.test.ts @@ -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-")); diff --git a/test/build-features.test.ts b/test/build-features.test.ts index 0dd69a3a..7e4674c2 100644 --- a/test/build-features.test.ts +++ b/test/build-features.test.ts @@ -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 }); diff --git a/test/build-mem.test.ts b/test/build-mem.test.ts index 0dbfa1ca..49a50543 100644 --- a/test/build-mem.test.ts +++ b/test/build-mem.test.ts @@ -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 }; diff --git a/test/build-pods.test.ts b/test/build-pods.test.ts index 3fabcda7..21f2b39f 100644 --- a/test/build-pods.test.ts +++ b/test/build-pods.test.ts @@ -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-")); diff --git a/test/build-sizing.test.ts b/test/build-sizing.test.ts index 95ad6bef..4f09526e 100644 --- a/test/build-sizing.test.ts +++ b/test/build-sizing.test.ts @@ -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"; diff --git a/test/build.test.ts b/test/build.test.ts index 087dc35b..895ab269 100644 --- a/test/build.test.ts +++ b/test/build.test.ts @@ -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-")); diff --git a/test/ci-first-migration.test.ts b/test/ci-first-migration.test.ts index 00436fa5..bf905fe9 100644 --- a/test/ci-first-migration.test.ts +++ b/test/ci-first-migration.test.ts @@ -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"); diff --git a/test/cifix-pool.test.ts b/test/cifix-pool.test.ts index 4e9b10ea..3899c305 100644 --- a/test/cifix-pool.test.ts +++ b/test/cifix-pool.test.ts @@ -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-")); diff --git a/test/cifix.test.ts b/test/cifix.test.ts index 524a9a74..f9077d97 100644 --- a/test/cifix.test.ts +++ b/test/cifix.test.ts @@ -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 }); diff --git a/test/conflict-merge-cost.test.ts b/test/conflict-merge-cost.test.ts index f9b259f4..d62c7335 100644 --- a/test/conflict-merge-cost.test.ts +++ b/test/conflict-merge-cost.test.ts @@ -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"); diff --git a/test/conversations.test.ts b/test/conversations.test.ts index 77df0b63..0e308211 100644 --- a/test/conversations.test.ts +++ b/test/conversations.test.ts @@ -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 = () => {}; diff --git a/test/dash-insight.test.ts b/test/dash-insight.test.ts index 44804c20..e726bb3c 100644 --- a/test/dash-insight.test.ts +++ b/test/dash-insight.test.ts @@ -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 = {}): Req => ({ method: "GET", path: "", params: {}, query: new URLSearchParams(query), form: new URLSearchParams(), user: { login: "op", role: "operator", canWrite: async () => true, canRead: async () => true }, diff --git a/test/data-layer-allow.json b/test/data-layer-allow.json deleted file mode 100644 index 9f9671ac..00000000 --- a/test/data-layer-allow.json +++ /dev/null @@ -1,5 +0,0 @@ -[ - "src/build/tasks.ts", - "src/dash/api/related.ts", - "src/itemtools/server/tools.ts" -] diff --git a/test/data-layer.test.ts b/test/data-layer.test.ts index 67f3bd8f..8e2aac1a 100644 --- a/test/data-layer.test.ts +++ b/test/data-layer.test.ts @@ -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 = { + "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(); + 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); diff --git a/test/data/mirror-checks.test.ts b/test/data/mirror-checks.test.ts index 17ee870a..cccd0f1b 100644 --- a/test/data/mirror-checks.test.ts +++ b/test/data/mirror-checks.test.ts @@ -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 => diff --git a/test/data/mirror-comments.test.ts b/test/data/mirror-comments.test.ts index 4a93d96d..144319b8 100644 --- a/test/data/mirror-comments.test.ts +++ b/test/data/mirror-comments.test.ts @@ -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[]) => db.write(async () => { await db.run(db.k.insertInto("main.comments").values(rows as never)); }); diff --git a/test/data/mirror-fixture.ts b/test/data/mirror-fixture.ts index 599f67e5..50c70762 100644 --- a/test/data/mirror-fixture.ts +++ b/test/data/mirror-fixture.ts @@ -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"; diff --git a/test/data/mirror-local.test.ts b/test/data/mirror-local.test.ts index 33879fb9..3fc42124 100644 --- a/test/data/mirror-local.test.ts +++ b/test/data/mirror-local.test.ts @@ -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}`)!; diff --git a/test/db-layer.test.ts b/test/db-layer.test.ts index b951c3be..c3701f86 100644 --- a/test/db-layer.test.ts +++ b/test/db-layer.test.ts @@ -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"; diff --git a/test/discord-events.test.ts b/test/discord-events.test.ts index 488ec77f..b8cf0e73 100644 --- a/test/discord-events.test.ts +++ b/test/discord-events.test.ts @@ -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 }); diff --git a/test/discord-file-issue.test.ts b/test/discord-file-issue.test.ts index 1cc4e76d..609a6597 100644 --- a/test/discord-file-issue.test.ts +++ b/test/discord-file-issue.test.ts @@ -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-")); diff --git a/test/discord-filing-repos.test.ts b/test/discord-filing-repos.test.ts index 8c4ff107..45293739 100644 --- a/test/discord-filing-repos.test.ts +++ b/test/discord-filing-repos.test.ts @@ -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-")); diff --git a/test/discord-issue-new.test.ts b/test/discord-issue-new.test.ts index ec88cbfb..8beb8be6 100644 --- a/test/discord-issue-new.test.ts +++ b/test/discord-issue-new.test.ts @@ -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 }); diff --git a/test/discord-links.test.ts b/test/discord-links.test.ts index c8d0d020..04700c90 100644 --- a/test/discord-links.test.ts +++ b/test/discord-links.test.ts @@ -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 }); diff --git a/test/discord-mentions.test.ts b/test/discord-mentions.test.ts index 14e8ea08..75038985 100644 --- a/test/discord-mentions.test.ts +++ b/test/discord-mentions.test.ts @@ -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 }); diff --git a/test/discord-react.test.ts b/test/discord-react.test.ts index 724ec480..0fb747ac 100644 --- a/test/discord-react.test.ts +++ b/test/discord-react.test.ts @@ -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-")); diff --git a/test/discord-search.test.ts b/test/discord-search.test.ts index 2d54403b..cb0a7385 100644 --- a/test/discord-search.test.ts +++ b/test/discord-search.test.ts @@ -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"; diff --git a/test/discord-signals.test.ts b/test/discord-signals.test.ts index 335e55dc..cde98433 100644 --- a/test/discord-signals.test.ts +++ b/test/discord-signals.test.ts @@ -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 }); diff --git a/test/discord-workflow-alerts.test.ts b/test/discord-workflow-alerts.test.ts index 216dd395..2a1d1369 100644 --- a/test/discord-workflow-alerts.test.ts +++ b/test/discord-workflow-alerts.test.ts @@ -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 }); diff --git a/test/downloads-report.test.ts b/test/downloads-report.test.ts index 7b7200e0..e71bae11 100644 --- a/test/downloads-report.test.ts +++ b/test/downloads-report.test.ts @@ -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; diff --git a/test/dupes-current.test.ts b/test/dupes-current.test.ts index f1ddceb1..32197ca1 100644 --- a/test/dupes-current.test.ts +++ b/test/dupes-current.test.ts @@ -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 diff --git a/test/dupes-scan.test.ts b/test/dupes-scan.test.ts index dbdc52dd..8f3570ce 100644 --- a/test/dupes-scan.test.ts +++ b/test/dupes-scan.test.ts @@ -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"; diff --git a/test/fake-runner.ts b/test/fake-runner.ts index 3b0fd2dd..75d4493a 100644 --- a/test/fake-runner.ts +++ b/test/fake-runner.ts @@ -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; diff --git a/test/fixup-conflict-skip.test.ts b/test/fixup-conflict-skip.test.ts index 7f9ee9b2..dd0ddf6b 100644 --- a/test/fixup-conflict-skip.test.ts +++ b/test/fixup-conflict-skip.test.ts @@ -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-")); diff --git a/test/fixup-pool.test.ts b/test/fixup-pool.test.ts index def4d251..551aef4e 100644 --- a/test/fixup-pool.test.ts +++ b/test/fixup-pool.test.ts @@ -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-")); diff --git a/test/fixup.test.ts b/test/fixup.test.ts index 7ca8974a..70a80415 100644 --- a/test/fixup.test.ts +++ b/test/fixup.test.ts @@ -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 }); diff --git a/test/flight.test.ts b/test/flight.test.ts index b3692ff4..8d6ac191 100644 --- a/test/flight.test.ts +++ b/test/flight.test.ts @@ -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 () => { diff --git a/test/fragments-a.test.ts b/test/fragments-a.test.ts index c392fbc5..f72a506c 100644 --- a/test/fragments-a.test.ts +++ b/test/fragments-a.test.ts @@ -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"; diff --git a/test/fragments-b.test.ts b/test/fragments-b.test.ts index f0e5cb4b..778033a6 100644 --- a/test/fragments-b.test.ts +++ b/test/fragments-b.test.ts @@ -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"; diff --git a/test/github-app.test.ts b/test/github-app.test.ts index 36151bdb..890727cc 100644 --- a/test/github-app.test.ts +++ b/test/github-app.test.ts @@ -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 }); diff --git a/test/github-writes.test.ts b/test/github-writes.test.ts index 3624dfc7..d0ba131a 100644 --- a/test/github-writes.test.ts +++ b/test/github-writes.test.ts @@ -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 }); diff --git a/test/guard.test.ts b/test/guard.test.ts index ccd53793..2617b78a 100644 --- a/test/guard.test.ts +++ b/test/guard.test.ts @@ -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" }; diff --git a/test/handle-meter.test.ts b/test/handle-meter.test.ts index 997b3199..a30d20cd 100644 --- a/test/handle-meter.test.ts +++ b/test/handle-meter.test.ts @@ -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; diff --git a/test/hardening-lead-a.test.ts b/test/hardening-lead-a.test.ts index 3addc44e..fb7b160e 100644 --- a/test/hardening-lead-a.test.ts +++ b/test/hardening-lead-a.test.ts @@ -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"; diff --git a/test/health-api.test.ts b/test/health-api.test.ts index 123b14c1..00b95eca 100644 --- a/test/health-api.test.ts +++ b/test/health-api.test.ts @@ -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 => ({ diff --git a/test/helpers/raw-db.ts b/test/helpers/raw-db.ts new file mode 100644 index 00000000..4a4bc84b --- /dev/null +++ b/test/helpers/raw-db.ts @@ -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): Promise => queryDb(await open.connectDb(...args)); +/** `dbFor` of src/db/open.ts, with the query methods. */ +export const dbFor = async (sync: DatabaseSync): Promise => queryDb(await open.dbFor(sync)); +/** `openDb` of src/db/open.ts, with the query methods. */ +export const openDb = async (): Promise => queryDb(await open.openDb()); diff --git a/test/identity-sec3.test.ts b/test/identity-sec3.test.ts index 18a98a77..3bab3a91 100644 --- a/test/identity-sec3.test.ts +++ b/test/identity-sec3.test.ts @@ -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()); diff --git a/test/identity.test.ts b/test/identity.test.ts index 693f0c2b..c638d257 100644 --- a/test/identity.test.ts +++ b/test/identity.test.ts @@ -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; diff --git a/test/implement-build.test.ts b/test/implement-build.test.ts index 82fae4fd..97fc261a 100644 --- a/test/implement-build.test.ts +++ b/test/implement-build.test.ts @@ -73,7 +73,7 @@ function withCallRows(s: Awaited>) { 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)); diff --git a/test/implement-plan.test.ts b/test/implement-plan.test.ts index a25417a7..23060b62 100644 --- a/test/implement-plan.test.ts +++ b/test/implement-plan.test.ts @@ -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"; diff --git a/test/implement-pr.test.ts b/test/implement-pr.test.ts index 47899450..e059d9a4 100644 --- a/test/implement-pr.test.ts +++ b/test/implement-pr.test.ts @@ -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"; diff --git a/test/implement-rows.ts b/test/implement-rows.ts index 0811b732..f7372f8b 100644 --- a/test/implement-rows.ts +++ b/test/implement-rows.ts @@ -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"; diff --git a/test/interactive-no-taker.test.ts b/test/interactive-no-taker.test.ts index b39beb86..0a286fe9 100644 --- a/test/interactive-no-taker.test.ts +++ b/test/interactive-no-taker.test.ts @@ -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 }); diff --git a/test/issue-stalls.test.ts b/test/issue-stalls.test.ts index 6cca0497..005aab05 100644 --- a/test/issue-stalls.test.ts +++ b/test/issue-stalls.test.ts @@ -4,7 +4,7 @@ import assert from "node:assert/strict"; import { decideItem } from "../src/core/decide-item.ts"; import { issuesWithOpenPr, textRefs } from "../src/core/open-prs.ts"; import { itemFacts } from "./world.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; const needsDecision = { classification: { flags: ["needs decision"] }, labels: { existing: ["bugfix", "needs decision"] } }; diff --git a/test/item-settled.test.ts b/test/item-settled.test.ts index fa1db5a3..fb1bb922 100644 --- a/test/item-settled.test.ts +++ b/test/item-settled.test.ts @@ -2,8 +2,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { ensureSettled, loadSettled } from "../src/data/triage/index.ts"; import { connect } from "../src/db.ts"; -import type { Db } from "../src/db/index.ts"; -import { connectDb, dbFor } from "../src/db/open.ts"; +import { connectDb, dbFor, type Db } from "./helpers/raw-db.ts"; const RUN = "r1"; diff --git a/test/item-status.test.ts b/test/item-status.test.ts index d3a8c0ea..242b8ad2 100644 --- a/test/item-status.test.ts +++ b/test/item-status.test.ts @@ -7,7 +7,7 @@ import { phaseOf, statusFromItem, statusOf, type StatusInput } from "../src/core import { writePlanCache, type PlanView } from "../src/core/plan-cache.ts"; import { loadPlanSet } from "../src/core/plan-set.ts"; import { SCRATCH } from "./scratch.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; const input = (p: Partial): StatusInput => ({ state: null, itemState: null, wait: null, next: null, ...p }); diff --git a/test/item-trace.test.ts b/test/item-trace.test.ts index 69779ebb..f7cf3ffa 100644 --- a/test/item-trace.test.ts +++ b/test/item-trace.test.ts @@ -7,8 +7,7 @@ import { trace, traceDetail } from "../src/dash/api/trace.ts"; import { itemPage } from "../src/dash/api/item-page.ts"; import type { Req } from "../src/dash/types.ts"; import type { ItemTrace } 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"; import { rowid } from "../src/db/kx.ts"; const req = (n: number, query: Record = {}, extra: Record = {}): Req => ({ diff --git a/test/itemtools-pg.test.ts b/test/itemtools-pg.test.ts index baf46572..a9a62947 100644 --- a/test/itemtools-pg.test.ts +++ b/test/itemtools-pg.test.ts @@ -6,7 +6,7 @@ import { mkdirSync, mkdtempSync } from "node:fs"; import { join } from "node:path"; import { DatabaseSync } from "node:sqlite"; import { test } from "node:test"; -import type { Db } from "../src/db/index.ts"; +import type { Db } from "./helpers/raw-db.ts"; import { writeSnapshot, writeSnapshotFromDb } from "../src/itemtools/snapshot.ts"; import { SCRATCH } from "./scratch.ts"; import { needsPg, testDatabase } from "./test-db.ts"; diff --git a/test/itemtools-safety.test.ts b/test/itemtools-safety.test.ts index 955b8f6c..16b9606b 100644 --- a/test/itemtools-safety.test.ts +++ b/test/itemtools-safety.test.ts @@ -9,7 +9,7 @@ import { after, describe, test } from "node:test"; import { buildSnapshot } from "../src/itemtools/snapshot.ts"; import { callTool, frame, openDb } from "../src/itemtools/server/tools.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, "itemtools-safety-")); diff --git a/test/itemtools.test.ts b/test/itemtools.test.ts index a1179aa4..d4cad570 100644 --- a/test/itemtools.test.ts +++ b/test/itemtools.test.ts @@ -8,7 +8,7 @@ import { join } from "node:path"; import { DatabaseSync } from "node:sqlite"; import { before, describe, test } from "node:test"; import { fileURLToPath } from "node:url"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import type { SnapshotStats } from "../src/itemtools/snapshot.ts"; import { writeTestSnapshot } from "./test-db.ts"; import { callTool, openDb } from "../src/itemtools/server/tools.ts"; diff --git a/test/jevcost.test.ts b/test/jevcost.test.ts index aaa1a9d5..dbb891b1 100644 --- a/test/jevcost.test.ts +++ b/test/jevcost.test.ts @@ -4,7 +4,7 @@ import { join } from "node:path"; import { test } from "node:test"; import { askJev, runJev, saveUsage, setRunner } from "../src/classify/run.ts"; 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 answers = { diff --git a/test/job-items.test.ts b/test/job-items.test.ts index c9fc7fbb..bfc59d2c 100644 --- a/test/job-items.test.ts +++ b/test/job-items.test.ts @@ -10,7 +10,7 @@ import { flushJobItems } from "../src/data/jobs/index.ts"; import { JOB_KEEP_MS, pruneJobs } from "../src/runner/jobs.ts"; import { SCRATCH } from "./scratch.ts"; import { world } from "./world-db.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; mkdirSync(SCRATCH, { recursive: true }); const db = await connectDb(join(mkdtempSync(join(SCRATCH, "job-items-")), "t.db")); diff --git a/test/job-log.test.ts b/test/job-log.test.ts index 249be9d1..0714f3cb 100644 --- a/test/job-log.test.ts +++ b/test/job-log.test.ts @@ -5,7 +5,7 @@ import { appendFileSync, mkdtempSync, rmSync } from "node:fs"; 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 { copyLogs, JOB_LOG_KEEP_BYTES, JOB_LOG_KEEP_MS, JobLogCopy, pruneJobLogs } from "../src/runner/job-log.ts"; import { jobDetail } from "../src/runner/jobs.ts"; diff --git a/test/kx.test.ts b/test/kx.test.ts index 3172e2a8..85b4e0d6 100644 --- a/test/kx.test.ts +++ b/test/kx.test.ts @@ -3,7 +3,9 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import type { Generated } from "kysely"; -import type { Db, Dialect } from "../src/db/index.ts"; +import type { Dialect } from "../src/db/index.ts"; +import { queryDb } from "../src/db/query-db.ts"; +import type { Db } from "./helpers/raw-db.ts"; import * as kx from "../src/db/kx.ts"; import { namedKeys, registerKeySource, resolveKeys, type KeySource } from "../src/data/keys.ts"; import { parseSearch } from "../src/db/search.ts"; @@ -307,7 +309,7 @@ test("chunks slices a list, 10,000 by default", () => { assert.equal(kx.chunks(Array.from({ length: 25_000 }, (_, i) => i)).length, 3); }); -registerKeySource("test.repoKeys", (d, args: { repo: string }) => d.k.withTables().selectFrom("r").select(["repo", "number"]).where("repo", "=", args.repo) as never); +registerKeySource("test.repoKeys", (d, args: { repo: string }) => queryDb(d).k.withTables().selectFrom("r").select(["repo", "number"]).where("repo", "=", args.repo) as never); both("resolveKeys turns a ref list or a registered descriptor into a (repo, number) table", async (db) => { const keys = async (ks: KeySource) => await db.all(k(db).selectFrom(resolveKeys(db, ks, "ks")).select(["ks.repo", "ks.number"]).orderBy("ks.repo").orderBy("ks.number")); diff --git a/test/leader-pg.test.ts b/test/leader-pg.test.ts index 144d24da..498a8c8c 100644 --- a/test/leader-pg.test.ts +++ b/test/leader-pg.test.ts @@ -7,7 +7,7 @@ import { spawn } from "node:child_process"; import { createInterface } from "node:readline"; import { elect, type Lease } from "../src/db/leader.ts"; import { isFenced, setFence } from "../src/db/fence.ts"; -import type { Db } from "../src/db/index.ts"; +import type { Db } from "./helpers/raw-db.ts"; import { needsPg, testDatabase } from "./test-db.ts"; const FAST = { retryMs: 100, checkMs: 100, leaseMs: 2_000, lossMs: 1_500, beatMs: 200, log: () => {} }; diff --git a/test/leases.test.ts b/test/leases.test.ts index 89710ae9..ad08d155 100644 --- a/test/leases.test.ts +++ b/test/leases.test.ts @@ -9,7 +9,7 @@ import { endJob } from "../src/runner/jobs.ts"; import { leaseItem, leaseSkips, take } from "../src/runner/leases.ts"; import type { StepDef } from "../src/runner/steps.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"; after(() => setCallContext(null)); diff --git a/test/lint-fix-turn.test.ts b/test/lint-fix-turn.test.ts index cf8186bc..6d4dbd38 100644 --- a/test/lint-fix-turn.test.ts +++ b/test/lint-fix-turn.test.ts @@ -9,7 +9,7 @@ import { SAMPLE_OPUS_PRS } from "../src/prompts/samples.ts"; import { mergeFixFields, type Lint } from "../src/replylint.ts"; import { fakeTaskRunner } 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, "lint-fix-")); diff --git a/test/live-board.test.ts b/test/live-board.test.ts index f9a36956..e3c7ebcb 100644 --- a/test/live-board.test.ts +++ b/test/live-board.test.ts @@ -3,7 +3,7 @@ import assert from "node:assert/strict"; import { buildKind, live } from "../src/dash/api/live.ts"; import { insertRun } from "../src/agents/runs.ts"; import type { Req } from "../src/dash/types.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { parseStatus, storeStatus } from "../src/remote/helpers.ts"; import { setSettings } from "../src/dash/api/user-settings.ts"; diff --git a/test/live-topics.test.ts b/test/live-topics.test.ts index 11171208..3daa0f60 100644 --- a/test/live-topics.test.ts +++ b/test/live-topics.test.ts @@ -5,7 +5,7 @@ import { mkdirSync, mkdtempSync } from "node:fs"; import { join } from "node:path"; import { test } from "node:test"; import { TOPICS, liveTriggers } from "../src/db/live.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { SCRATCH } from "./scratch.ts"; import { sqliteOnly } from "./test-db.ts"; diff --git a/test/mainfix-pr.test.ts b/test/mainfix-pr.test.ts index 46e5042c..7431da80 100644 --- a/test/mainfix-pr.test.ts +++ b/test/mainfix-pr.test.ts @@ -9,8 +9,7 @@ import { HARDENING, type Exec } from "../src/fixup/git.ts"; import { mainFixDue, onCodeVerdict, runMainFix, setMainFixApproval, type FixRow, type MainFixDeps } from "../src/mainfix/index.ts"; import { CLIPPY_ARTIFACT } from "../src/prepush/index.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"; mkdirSync(SCRATCH, { recursive: true }); const dir = mkdtempSync(join(SCRATCH, "mainfix-pr-")); diff --git a/test/maintain-home.test.ts b/test/maintain-home.test.ts index ad05f7a7..2645cd76 100644 --- a/test/maintain-home.test.ts +++ b/test/maintain-home.test.ts @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { home } from "../src/dash/api/maintain.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { addEvent, insertWorkflow } from "../src/workflow/store.ts"; const T = "2026-11-01T00:00:00.000Z"; diff --git a/test/maintain-item.test.ts b/test/maintain-item.test.ts index 86da53bb..81ad3605 100644 --- a/test/maintain-item.test.ts +++ b/test/maintain-item.test.ts @@ -4,7 +4,7 @@ import { join } from "node:path"; import { test } from "node:test"; import { item } from "../src/dash/api/maintain-item.ts"; import type { Req } from "../src/dash/types.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { insertWorkflow } from "../src/workflow/store.ts"; import { SCRATCH } from "./scratch.ts"; diff --git a/test/maintainer-repo-actions.test.ts b/test/maintainer-repo-actions.test.ts index 4a0b9afc..13ddf8d5 100644 --- a/test/maintainer-repo-actions.test.ts +++ b/test/maintainer-repo-actions.test.ts @@ -4,7 +4,7 @@ import { labelsApproval } from "../src/dash/api/admin.ts"; import { cancel } from "../src/dash/api/pipeline.ts"; import { actOnFinding, continueScan, startScan } from "../src/dash/api/security.ts"; import type { Req } from "../src/dash/types.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; // A maintainer who writes to `alpha` (and no other repo). const as = (login: string, role: "viewer" | "maintainer" | "operator", json: unknown = {}, params: Record = {}): Req => ({ diff --git a/test/maintainer-run-actions.test.ts b/test/maintainer-run-actions.test.ts index 475bd5cd..da042eba 100644 --- a/test/maintainer-run-actions.test.ts +++ b/test/maintainer-run-actions.test.ts @@ -1,7 +1,7 @@ // Per-repo and per-item actions are for whoever runs the repo (operator, or maintainer with GitHub write); instance-wide ones stay with operators. import { test } from "node:test"; import assert from "node:assert/strict"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { reviewItemAgain } from "../src/dash/api/operator.ts"; import { mergeHoldPr } from "../src/dash/api/queue-page.ts"; import { release, releaseAll } from "../src/dash/api/outside.ts"; diff --git a/test/mcp-settings.test.ts b/test/mcp-settings.test.ts index 424b265a..3c79c48f 100644 --- a/test/mcp-settings.test.ts +++ b/test/mcp-settings.test.ts @@ -7,7 +7,7 @@ import { handleMcp, type McpEnv } from "../src/dash/mcp/index.ts"; import type { Role } from "../src/dash/types.ts"; import { userReserve } from "../src/remote/reserve.ts"; import { RateLimiter } from "../src/dash/server/util.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { SCRATCH } from "./scratch.ts"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/mcp.test.ts b/test/mcp.test.ts index 7516f84a..f7df70cf 100644 --- a/test/mcp.test.ts +++ b/test/mcp.test.ts @@ -16,7 +16,7 @@ import { startServer } from "../src/dash/server/index.ts"; import { FakeProvider } from "../src/dash/server/provider.ts"; import { MCP_TOKENS_PER_LOGIN } from "../src/dash/mcp/tokens.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 }); diff --git a/test/migration.test.ts b/test/migration.test.ts index 377757f4..d5909b69 100644 --- a/test/migration.test.ts +++ b/test/migration.test.ts @@ -6,8 +6,7 @@ import { DatabaseSync } from "node:sqlite"; import { readFileSync } from "node:fs"; import { test } from "node:test"; import { tmpdir } from "./world-db.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 { sqliteOnly } from "./test-db.ts"; const cols = async (db: Db, table: string): Promise => (await db.prepare(`PRAGMA main.table_info(${table})`).all() as { name: string }[]).map((c) => c.name); diff --git a/test/mirror.test.ts b/test/mirror.test.ts index fc641708..a5a9f327 100644 --- a/test/mirror.test.ts +++ b/test/mirror.test.ts @@ -197,8 +197,7 @@ test("search results GitHub refuses for lack of access are dropped; other errors // ---- mergeable keeps its known value at one head ---- import { tmpdir } from "node:os"; import { saveChecks, type PrChecks } from "../src/review/checks.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"; test("saveChecks keeps a known mergeable at the same head and replaces it at a new head", async () => { const db = await connectDb(join(mkdtempSync(join(tmpdir(), "mergeable-")), "t.db")); diff --git a/test/next-page.test.ts b/test/next-page.test.ts index 74c81eec..799242ae 100644 --- a/test/next-page.test.ts +++ b/test/next-page.test.ts @@ -7,7 +7,7 @@ import { plannedItems } from "../src/core/select-items.ts"; import { nextPage } from "../src/dash/api/next.ts"; import { detectAutopilot, INPUT_TOPICS, LANE_KINDS, LANES, NO_ITEM_LANES, setEnabled, setLimit } from "../src/runner/autopilot.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 }); diff --git a/test/nightly-api.test.ts b/test/nightly-api.test.ts index 93870abb..0c73cbe8 100644 --- a/test/nightly-api.test.ts +++ b/test/nightly-api.test.ts @@ -8,7 +8,7 @@ import { TOPICS } from "../src/db/live.ts"; import { INPUT_TOPICS } from "../src/runner/autopilot.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"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/nightly.test.ts b/test/nightly.test.ts index e4ac150b..49cb84be 100644 --- a/test/nightly.test.ts +++ b/test/nightly.test.ts @@ -8,7 +8,7 @@ import { setFeature } from "../src/build/features.ts"; import { LANES } from "../src/runner/autopilot.ts"; import { nightlyDue, nightlyRepos, openNightlyIssue, runNightly, setSelection, recentRuns, benchSeries, parseBench, pruneBench, type NightlyDeps } from "../src/nightly/index.ts"; import { SCRATCH } from "./scratch.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { like } from "../src/db/kx.ts"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/operator-actions.test.ts b/test/operator-actions.test.ts index 23eb270f..f1b30878 100644 --- a/test/operator-actions.test.ts +++ b/test/operator-actions.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { ActionError, actionsOf, batchAgain, reviewAgain, verifyAgain } from "../src/operator-actions.ts"; import { optionalChecks, optionalChecksOf, seenChecks, setOptionalCheck } from "../src/optional-checks.ts"; diff --git a/test/outside-limits.test.ts b/test/outside-limits.test.ts index fae31e8a..73837bfa 100644 --- a/test/outside-limits.test.ts +++ b/test/outside-limits.test.ts @@ -3,9 +3,8 @@ import { test } from "node:test"; import { inScopeExpr } from "../src/data/workflow/fragments.ts"; import { refreshOutsideHolds, releaseOutside, setOutsideLimits } from "../src/outside.ts"; import { resumeStage } from "../src/data/control/index.ts"; -import type { Db } from "../src/db/index.ts"; +import { connectDb, type Db } from "./helpers/raw-db.ts"; import { everySeq, mapSeq } from "../src/async-seq.ts"; -import { connectDb } from "../src/db/open.ts"; /** The item is in the pipeline's scope (the workflow scope fragment), read as the planner reads it. */ const inPilot = async (db: Db, repo: string, number: number): Promise => diff --git a/test/pg-db.test.ts b/test/pg-db.test.ts index 8c44f759..3eba8d59 100644 --- a/test/pg-db.test.ts +++ b/test/pg-db.test.ts @@ -5,7 +5,7 @@ import assert from "node:assert/strict"; import { countQueries } from "../src/db/counter.ts"; import { isLockTimeout } from "../src/db/errors.ts"; import { rewriteScriptForPostgres } from "../src/db/params.ts"; -import type { Db } from "../src/db/index.ts"; +import type { Db } from "./helpers/raw-db.ts"; import { needsPg, testDatabase } from "./test-db.ts"; import type { Generated } from "kysely"; diff --git a/test/pg-triggers.test.ts b/test/pg-triggers.test.ts index 08cfc3ef..8bb85e52 100644 --- a/test/pg-triggers.test.ts +++ b/test/pg-triggers.test.ts @@ -7,7 +7,7 @@ import "../src/trigger-sources.ts"; import { bulkWrites, changeCursor, changesSince, pruneChanges, type ChangeCursor } from "../src/core/plan-changes.ts"; import { planTriggers } from "../src/db/plan-triggers.ts"; import { pgExpr } from "../src/core/pg-expr.ts"; -import type { Db } from "../src/db/index.ts"; +import type { Db } from "./helpers/raw-db.ts"; import { loadPg } from "../src/db/open.ts"; import { PG_COLUMNS_SQL, pgColumns } from "../src/db/pg-triggers.ts"; import { liveTriggers } from "../src/db/live.ts"; diff --git a/test/pg-upgrade.test.ts b/test/pg-upgrade.test.ts index 7ecfe820..be856fc6 100644 --- a/test/pg-upgrade.test.ts +++ b/test/pg-upgrade.test.ts @@ -5,7 +5,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { gunzipSync } from "node:zlib"; -import type { Db } from "../src/db/index.ts"; +import type { Db } from "./helpers/raw-db.ts"; import { loadPg } from "../src/db/open.ts"; import { PG_SCHEMA_GENERATION } from "../src/db/pg-generation.ts"; import { STATE_COPY_DONE } from "../src/db/state-copy.ts"; diff --git a/test/pipeline.test.ts b/test/pipeline.test.ts index 5a19ef3d..e507b703 100644 --- a/test/pipeline.test.ts +++ b/test/pipeline.test.ts @@ -9,7 +9,7 @@ import { after, before, describe, test } from "node:test"; import { fileURLToPath } from "node:url"; import type { Job, JobDetail, JobList, PipelineOverview } from "../web/src/api/types.ts"; import { SCRATCH } from "./scratch.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; process.env.AUTOCRAFT_EXTRA_STEPS = fileURLToPath(new URL("./runner-steps.ts", import.meta.url)); diff --git a/test/plan-cache.test.ts b/test/plan-cache.test.ts index 40c5b0a4..70788e5a 100644 --- a/test/plan-cache.test.ts +++ b/test/plan-cache.test.ts @@ -5,11 +5,10 @@ import { join } from "node:path"; import { describe, test } from "node:test"; import { prunePlanHistory, refreshPlanCache } from "../src/core/plan-cache.ts"; import { loadPlanHistory } from "../src/data/planner/index.ts"; -import type { Db } from "../src/db/index.ts"; +import { connectDb, type Db } from "./helpers/raw-db.ts"; import { detectAutopilot, planDue, setEnabled } from "../src/runner/autopilot.ts"; import { SCRATCH } from "./scratch.ts"; import { mapSeq } from "../src/async-seq.ts"; -import { connectDb } from "../src/db/open.ts"; import { excluded } from "../src/db/kx.ts"; import { sqliteOnly } from "./test-db.ts"; diff --git a/test/plan-changes.test.ts b/test/plan-changes.test.ts index 9ef067f8..d96e883d 100644 --- a/test/plan-changes.test.ts +++ b/test/plan-changes.test.ts @@ -19,8 +19,7 @@ import { saveOpus } from "../src/review/opus.ts"; import { SCRATCH } from "./scratch.ts"; import { world } from "./world-db.ts"; import { everySeq, filterSeq } from "../src/async-seq.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 { sqliteOnly } from "./test-db.ts"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/planner-taker.test.ts b/test/planner-taker.test.ts index c8e50c53..ad56e499 100644 --- a/test/planner-taker.test.ts +++ b/test/planner-taker.test.ts @@ -6,7 +6,7 @@ import { join } from "node:path"; import { test } from "node:test"; import { fileURLToPath } from "node:url"; import { SCRATCH } from "./scratch.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; process.env.AUTOCRAFT_EXTRA_STEPS = fileURLToPath(new URL("./runner-steps.ts", import.meta.url)); diff --git a/test/pool-skip.test.ts b/test/pool-skip.test.ts index 434ad24a..0c074ae5 100644 --- a/test/pool-skip.test.ts +++ b/test/pool-skip.test.ts @@ -14,7 +14,7 @@ import { createToken } from "../src/dash/mcp/tokens.ts"; import { parseStatus, storeStatus } from "../src/remote/helpers.ts"; import { setUserRepos } from "../src/remote/my-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 }); diff --git a/test/portable.test.ts b/test/portable.test.ts index 351927e1..60e46c47 100644 --- a/test/portable.test.ts +++ b/test/portable.test.ts @@ -2,7 +2,8 @@ // AUTOCRAFT_TEST_PG_URL names a server (`pnpm test:pg test/portable.test.ts`) and skip otherwise. 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 * as P from "../src/db/portable.ts"; import { sql } from "../src/db/sql.ts"; import { needsPg, testDatabase } from "./test-db.ts"; diff --git a/test/pr-builds.test.ts b/test/pr-builds.test.ts index 1235eff1..e49f974b 100644 --- a/test/pr-builds.test.ts +++ b/test/pr-builds.test.ts @@ -6,8 +6,7 @@ import { setFeature } from "../src/build/features.ts"; import { collectPrBuilds, prBuildDue, runPrBuilds } from "../src/prbuild/index.ts"; import { selectPrBuilds, setPerDay, setScope } from "../src/prbuild/select.ts"; import { prBuildView } from "../src/prbuild/view.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 { cols } from "../src/db/kx.ts"; const sha = (c: string) => c.repeat(40); diff --git a/test/prompts.test.ts b/test/prompts.test.ts index a5ba85c8..6581ff06 100644 --- a/test/prompts.test.ts +++ b/test/prompts.test.ts @@ -12,7 +12,7 @@ import { JEV_ARGS, claudeArgs, claudeParts, renderClaude, renderJev, untrustedJs import { SAMPLE_ITEMS } from "../src/prompts/samples.ts"; import { SAMPLE_VERIFY_PLAN } from "../src/verify/types.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 db = await connectDb(join(mkdtempSync(join(SCRATCH, "prompts-test-")), "t.db")); diff --git a/test/push-outcome.test.ts b/test/push-outcome.test.ts index 63b56225..7dbb556d 100644 --- a/test/push-outcome.test.ts +++ b/test/push-outcome.test.ts @@ -4,7 +4,7 @@ import { breakerTripped, classifyPush, requiredResult } from "../src/core/push-o import { join } from "node:path"; import { tmpdir } from "./world-db.ts"; import { addPushOutcomes, pushesUnsettled, resolvePushes, UNSETTLED_PUSHES_MAX } from "../src/data/control/index.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; test("push outcome: green to red is broke, red to green is fixed, optional checks are ignored", () => { const green = [{ name: "gate", state: "success" }, { name: "sonar", state: "failure" }]; diff --git a/test/push-tests.test.ts b/test/push-tests.test.ts index 69387934..186982dd 100644 --- a/test/push-tests.test.ts +++ b/test/push-tests.test.ts @@ -9,8 +9,7 @@ import { CLIPPY_ARTIFACT, lintPlan, queueLintFor, readLint } from "../src/prepus import { lintVerdict, testCrates } from "../src/prepush/tests.ts"; import type { CratesFetcher } from "../src/verify/crates.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"; process.env.AUTOCRAFT_DIFF_CACHE = join(SCRATCH, "diffs"); const HEAD = "a".repeat(40); diff --git a/test/query-count.test.ts b/test/query-count.test.ts new file mode 100644 index 00000000..2145a966 --- /dev/null +++ b/test/query-count.test.ts @@ -0,0 +1,190 @@ +// The hot paths read the database in sets: each unit runs at two sizes inside db.meter, and its statement count must not +// grow with the size. The data modules' own loaders are covered in test/data; these are the whole paths over them. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { join } from "node:path"; +import { effect } from "../src/db/effects.ts"; +import { activity } from "../src/dash/api/activity.ts"; +import { itemPage } from "../src/dash/api/item-page.ts"; +import { live } from "../src/dash/api/live.ts"; +import { home, items } from "../src/dash/api/maintain.ts"; +import { item } from "../src/dash/api/maintain-item.ts"; +import { trace } from "../src/dash/api/trace.ts"; +import type { Req } from "../src/dash/types.ts"; +import { createToken } from "../src/dash/mcp/tokens.ts"; +import { awaitCall, claimCall, enqueueCall } from "../src/remote/calls.ts"; +import { detectAutopilot } from "../src/runner/autopilot.ts"; +import { JobLogCopy } from "../src/runner/job-log.ts"; +import { Runner } from "../src/runner/runner.ts"; +import { addEvent, insertWorkflow } from "../src/workflow/store.ts"; +import { expectFlat, type FlatUnit } from "./helpers/query-count.ts"; +import { PROTOCOL_VERSION, type Claim } from "../src/remote/protocol.ts"; +import { tmpdir, world, type World } from "./world-db.ts"; + +const iso = (minAgo: number): string => new Date(Date.now() - minAgo * 60_000).toISOString(); +const numbers = (n: number, from = 1): number[] => Array.from({ length: n }, (_, i) => from + i); + +const req = (query: Record = {}, params: Record = {}): Req => ({ + method: "GET", path: "", params, query: new URLSearchParams(query), form: new URLSearchParams(), csrf: "", nonce: "", + user: { login: "op", role: "operator", canRead: async () => true, canWrite: async () => true }, +}) as unknown as Req; + +/** A unit over a new database with the tracked repo "app": `seed` fills it and returns the work to count. */ +const unit = (seed: (w: World, size: number) => Promise<() => Promise>) => async (size: number): Promise => { + const w = await world(); + await w.repo(); + const run = await seed(w, size); + return { db: w.db, run, close: async () => { w.close(); await w.db.close(); } }; +}; + +/** Pull requests at each point of the pipeline, in turn: classified, reviewed, with a fix to make, verified, before the merge. */ +async function seedPrs(w: World, list: readonly number[]): Promise { + for (const n of list) { + await w.pr(n, { ci: n % 4 === 3 ? "failure" : "success", mergeable: n % 5 === 4 ? "CONFLICTING" : "MERGEABLE" }); + if (n % 2 === 0) await w.review(n, { verdict: n % 4 === 0 ? "take-fix" : "take" }); + if (n % 6 === 0) { await w.verified(n); await w.premerge(n, "clean"); } + if (n % 3 === 0) await insertWorkflow(w.db, { kind: "pr", entry: "review", startedBy: "op", startedAt: iso(60), startedVia: "github", repo: "app", number: n, state: "running" }); + } +} + +/** A job over `list` with one model call and one build task per item. */ +async function seedJob(w: World, state: "running" | "done", list: readonly number[]): Promise { + const { db } = w; + const ended = state === "done" ? iso(2) : null; + const id = Number((await db.get(db.k.insertInto("jobs").values({ step: "opus-review", params: JSON.stringify({ repo: "app" }), requested_by: "pipeline", requested_at: iso(6), state, started_at: iso(5), ended_at: ended }).returning("id")))!.id); + for (const n of list) { + await db.run(db.k.insertInto("job_items").values({ job_id: id, repo: "app", number: n, at: iso(5) })); + const run = Number((await db.get(db.k.insertInto("agent_runs").values({ + job_id: id, step: "opus-review", stage: 5, prompt_id: "review.opus", prompt_version: "1", provider: "claude", model: "opus", items: JSON.stringify([`app#${n}`]), state, started_at: iso(4), ended_at: ended, + }).returning("id")))!.id); + await db.run(db.k.insertInto("agent_run_items").values({ run_id: run, repo: "app", number: n })); + await db.run(db.k.insertInto("build_tasks").values({ job_id: id, step: "verify", repo: "app", number: n, head_sha: `sha${n}`, requires: "{}", plan: "[]", state: state === "done" ? "done" : "running", queued_at: iso(4) })); + } + return id; +} + +test("a full planner pass, and one over the items that changed, read in sets", async () => { + const full = unit(async (w, n) => { + await seedPrs(w, numbers(n)); + for (const i of numbers(n, 100)) await w.issue(i); + return () => detectAutopilot(w.db); + }); + await expectFlat(full, 2, 12); + const changed = unit(async (w, n) => { + await seedPrs(w, numbers(12)); + await detectAutopilot(w.db); + for (const i of numbers(n)) await w.db.run(w.db.k.updateTable("items").set({ title: "new title" }).where("number", "=", i)); + return () => detectAutopilot(w.db); + }); + await expectFlat(changed, 2, 12); +}); + +const bundle = { promptId: "review.opus", promptVersion: "1", tier: "top", effort: "medium", timeoutSeconds: 600, maxTurns: 10, stdin: "x", system: null, mounts: [], mcpServers: [], keepSession: false, hints: {} } as const; +const queueCall = (w: World, n: number): Promise => + enqueueCall(w.db, { promptId: "review.opus", promptVersion: "1", tier: "top", effort: "medium", askedModel: "opus", bundle: { ...bundle } as never, items: [{ repo: "app", number: n }], level: n % 5, maxAttempts: 2 }); + +test("a Task Runner's claim reads the queue and the other Task Runners in sets", async () => { + let k = 0; + const claims = (queued: number, runners: number, leases: boolean) => unit(async (w) => { + await seedPrs(w, numbers(queued)); + for (const n of numbers(queued)) await queueCall(w, n); + const tokens: number[] = []; + for (const i of numbers(runners)) { + const login = `m${i}`; + await w.db.run(w.db.k.insertInto("access").values({ login, role: "maintainer" })); + tokens.push((await createToken(w.db, login, "helper", { kind: "runner" })).row.id); + } + const claim: Claim = { requestId: `query-count-${++k}`, protocol: PROTOCOL_VERSION, helperVersion: "9.0.0", harness: "claude", harnessVersion: "2.1", tiers: { top: "opus" } } as Claim; + return async () => assert.equal((await claimCall(w.db, { tokenId: tokens[0]!, login: "m1", role: "maintainer" }, claim, async () => leases)).lease !== null, leases); + }); + for (const leases of [true, false]) { + await expectFlat((n) => claims(n, 1, leases)(n), 2, 10); + await expectFlat((n) => claims(2, n, leases)(n), 1, 4); + } +}); + +test("calls that wait for their result share one poll", async () => { + await expectFlat(unit(async (w, n) => { + await seedPrs(w, numbers(n)); + const ids: number[] = []; + for (const i of numbers(n)) ids.push(await queueCall(w, i)); + await w.db.run(w.db.k.updateTable("remote_calls").set({ state: "failed", error: "ended" })); + // Each await is one model call, which may open and close its own relays. + return () => Promise.all(ids.map((id) => { effect("model-call"); return awaitCall(w.db, id, { log: () => {} }); })); + }), 1, 8); +}); + +test("a runner tick reads its running and queued jobs in sets", async () => { + const ticks = (running: number, queued: number) => unit(async (w) => { + const logs = tmpdir("query-count-logs"); + const runner = new Runner({ db: w.db, logs, log: () => {}, detect: async () => ({ proposals: [], logs: [] }) }); + const insert = async (step: string, n: number, state: string): Promise => Number((await w.db.get(w.db.k.insertInto("jobs").values({ + step, params: JSON.stringify({ repo: "app", number: n }), repo: "app", requested_by: "pipeline", requested_at: iso(5), state, started_at: state === "running" ? iso(4) : null, + }).returning("id")))!.id); + for (const n of numbers(running)) { + const id = await insert("opus-review", n, "running"); + const logPath = join(logs, `job-${id}.log`); + runner.running.set(id, { + child: { pid: undefined }, termAt: null, exited: Promise.resolve(), startedAt: Date.now(), deadlineMin: 60, logPath, logCopy: JobLogCopy.open(id, logPath), flaggedAt: null, + noProgressMin: 60, stopMsg: null, remoteSeen: null, remoteWaitMs: 0, + } as never); + } + // No Task Runner is connected, so the queued jobs stay queued. + for (const n of numbers(queued, 100)) await insert("opus-review", n, "queued"); + // What runs once in a while (the hourly prunes, the first identity read) is done before the counted tick. + await runner.tick(); + return () => runner.tick(); + }); + await expectFlat((n) => ticks(n, 2)(n), 1, 6); + await expectFlat((n) => ticks(1, n)(n), 2, 12); +}); + +test("the live board reads its lanes in sets", async () => { + await expectFlat(unit(async (w, n) => { + await seedPrs(w, numbers(n)); + for (const i of numbers(n)) { await seedJob(w, "running", [i]); await seedJob(w, "done", [i]); } + return async () => assert.ok((await live(w.db, req())).lanes.length >= n); + }), 2, 12); +}); + +/** One PR with `n` of each thing its pages list. */ +async function seedBusyPr(w: World, n: number): Promise { + const { db } = w; + await w.pr(1); + await w.review(1, { verdict: "take-fix", fixes: numbers(n).map((i) => ({ file: `src/f${i}.rs`, change: "rename" })) }); + for (const i of numbers(n)) { + await w.issue(100 + i); + await seedJob(w, "done", [1]); + await db.run(db.k.insertInto("comments").values({ repo: "app", number: 1, id: `c${i}`, kind: "comment", author: "someone", created_at: iso(100 - i), body: `note ${i}, see #${100 + i}` })); + await db.run(db.k.insertInto("opus_review_history").values({ repo: "app", number: 1, head_oid: "sha1", at: iso(90 - i), model: "opus", mode: "full", verdict: "take", sure: 1, reason: "r" })); + const wf = await insertWorkflow(db, { kind: "pr", entry: "review", startedBy: "op", startedAt: iso(80 - i), startedVia: "github", repo: "app", number: 1, state: i === n ? "running" : "stopped" } as never); + await addEvent(db, { workflowId: wf, repo: "app", number: 1, login: "op", via: "github", kind: "answered" }); + } + await db.run(db.k.updateTable("items").set({ closing_issues: JSON.stringify(numbers(n, 101)) }).where("number", "=", 1)); +} + +test("an item's pages read its history in sets", async () => { + const at = { repo: "app", n: "1" }; + const page = (read: (w: World) => Promise) => unit(async (w, n) => { await seedBusyPr(w, n); return () => read(w); }); + await expectFlat(page((w) => itemPage(w.db, req({}, at))), 2, 12); + await expectFlat(page((w) => item(w.db, req({}, at))), 2, 12); + await expectFlat(page((w) => trace(w.db, req({}, at))), 2, 12); +}); + +test("the activity feed, Home and the Items page read their rows in sets", async () => { + const pages = (read: (w: World) => Promise) => unit(async (w, n) => { + await seedPrs(w, numbers(n)); + for (const i of numbers(n)) { + await seedJob(w, "done", [i]); + await w.issue(100 + i); + await insertWorkflow(w.db, { + kind: "issue", entry: "implement", startedBy: "op", startedAt: iso(50), startedVia: "github", repo: "app", number: 100 + i, state: "recommending", + rec: { text: "Fix 1, then merge?", parts: { fix: [1], drop: [] }, merges: true }, + }); + } + return () => read(w); + }); + await expectFlat(pages((w) => activity(w.db, req())), 2, 12); + await expectFlat(pages((w) => home(w.db, req())), 2, 12); + await expectFlat(pages((w) => items(w.db, req())), 2, 12); +}); diff --git a/test/rank.test.ts b/test/rank.test.ts index 02cce924..2a9ab4e7 100644 --- a/test/rank.test.ts +++ b/test/rank.test.ts @@ -1,6 +1,6 @@ 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 { rankOfItem, runRank } from "../src/rank/index.ts"; test("rank writes every open item past one statement's worth of rows, reads the settled label, drops closed items and rewrites nothing unchanged", async () => { diff --git a/test/read-env.test.ts b/test/read-env.test.ts index d283dccc..b5f10e0b 100644 --- a/test/read-env.test.ts +++ b/test/read-env.test.ts @@ -2,8 +2,7 @@ import assert from "node:assert/strict"; import { DatabaseSync } from "node:sqlite"; import { test } from "node:test"; import { ownerOfArgs, ownerOfVariables, readEnv, readEnvFor } from "../src/github/read.ts"; -import type { Db } from "../src/db/index.ts"; -import { dbFor } from "../src/db/open.ts"; +import { dbFor, type Db } from "./helpers/raw-db.ts"; import { sqliteOnly } from "./test-db.ts"; const dbWith = async (identity?: string): Promise => { diff --git a/test/reference.test.ts b/test/reference.test.ts index 9757e75c..5f6cd7ec 100644 --- a/test/reference.test.ts +++ b/test/reference.test.ts @@ -10,7 +10,7 @@ import { claudeArgs } from "../src/prompts/index.ts"; import { importReference, referenceDir } from "../src/reference.ts"; import { trackRepo } from "../src/repos.ts"; import { SCRATCH } from "./scratch.ts"; -import { openDb } from "../src/db/open.ts"; +import { openDb } from "./helpers/raw-db.ts"; import * as kx from "../src/db/kx.ts"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/remote-calls.test.ts b/test/remote-calls.test.ts index c0a82b95..ad3947de 100644 --- a/test/remote-calls.test.ts +++ b/test/remote-calls.test.ts @@ -24,7 +24,7 @@ import { setAcceptedModels } from "../src/remote/mode.ts"; import { PROTOCOL_VERSION, type Claim } from "../src/remote/protocol.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"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/remote-claim-timeout.test.ts b/test/remote-claim-timeout.test.ts index 8ce84ee9..f946ab69 100644 --- a/test/remote-claim-timeout.test.ts +++ b/test/remote-claim-timeout.test.ts @@ -9,7 +9,7 @@ import { claimCall, enqueueCall } from "../src/remote/calls.ts"; import { parseStatus, storeStatus } from "../src/remote/helpers.ts"; import { PROTOCOL_VERSION, type Claim } from "../src/remote/protocol.ts"; import { SCRATCH } from "./scratch.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/remote-helper-visibility.test.ts b/test/remote-helper-visibility.test.ts index 1698b939..e7defa32 100644 --- a/test/remote-helper-visibility.test.ts +++ b/test/remote-helper-visibility.test.ts @@ -8,7 +8,7 @@ import { createToken } from "../src/dash/mcp/tokens.ts"; import { computeChecks, THRESHOLDS } from "../src/health-checks.ts"; import { listHelpers, 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 }); diff --git a/test/remote-longpoll.test.ts b/test/remote-longpoll.test.ts index d903ea5c..381a29d0 100644 --- a/test/remote-longpoll.test.ts +++ b/test/remote-longpoll.test.ts @@ -6,7 +6,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { after, describe, test } from "node:test"; import { SCRATCH } from "./scratch.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; // Every user-local window, the hold included, at a fifth: a 25 s hold is 5 s, the full retry every second. Read on import. process.env.AUTOCRAFT_REMOTE_TIME_SCALE = "0.2"; diff --git a/test/remote-no-taker.test.ts b/test/remote-no-taker.test.ts index e8f70c56..7393821b 100644 --- a/test/remote-no-taker.test.ts +++ b/test/remote-no-taker.test.ts @@ -13,7 +13,7 @@ import { setManualOnly } from "../src/remote/manual-only.ts"; import { NO_TAKER_MS, sweepTakers } from "../src/remote/takers.ts"; import { leaseSkips } from "../src/runner/leases.ts"; import { SCRATCH } from "./scratch.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/remote-permission.test.ts b/test/remote-permission.test.ts index c1eba948..e9c0c65e 100644 --- a/test/remote-permission.test.ts +++ b/test/remote-permission.test.ts @@ -6,7 +6,7 @@ import { join } from "node:path"; import { test } from "node:test"; import { appPermission, clearPermissionCache } from "../src/remote/permission.ts"; import { SCRATCH } from "./scratch.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/remote-picks.test.ts b/test/remote-picks.test.ts index f3144094..bb6df8f8 100644 --- a/test/remote-picks.test.ts +++ b/test/remote-picks.test.ts @@ -29,8 +29,7 @@ import { STARTED_HOLD_MS } from "../src/remote/started.ts"; import { allocation, poolRoom, repoBatches } from "../src/agents/call.ts"; import { pool } from "../src/classify/run.ts"; import { SCRATCH } from "./scratch.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 { excluded, like } from "../src/db/kx.ts"; /** A started item: the workflow row a maintainer's start command writes. */ diff --git a/test/remote-refusal.test.ts b/test/remote-refusal.test.ts index ceb97c75..032645a2 100644 --- a/test/remote-refusal.test.ts +++ b/test/remote-refusal.test.ts @@ -12,7 +12,7 @@ import { SAMPLE_OPUS_PRS } from "../src/prompts/samples.ts"; import { claimCall, REFUSED_PREFIX, submitCall, type Caller } from "../src/remote/calls.ts"; import { parseStatus, storeStatus } from "../src/remote/helpers.ts"; import { PROTOCOL_VERSION } from "../src/remote/protocol.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { SCRATCH } from "./scratch.ts"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/remote-room-repos.test.ts b/test/remote-room-repos.test.ts index 73415c48..78df5a4c 100644 --- a/test/remote-room-repos.test.ts +++ b/test/remote-room-repos.test.ts @@ -12,7 +12,7 @@ import { setUserRepos } from "../src/remote/my-repos.ts"; import { setUserTasks, TASK_CHOICES } from "../src/remote/my-tasks.ts"; import { remoteRoom } from "../src/remote/room.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 }); diff --git a/test/remote-tools.test.ts b/test/remote-tools.test.ts index d62e39f0..d0d74021 100644 --- a/test/remote-tools.test.ts +++ b/test/remote-tools.test.ts @@ -22,7 +22,7 @@ import { buildReferenceIndex } from "../src/data/external/index.ts"; import { PASSAGES_PER_LEASE, referenceOptions } from "../src/remote/tools.ts"; import { SCRATCH } from "./scratch.ts"; import { writeTestSnapshot } from "./test-db.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { startWorkerServer } from "../src/build/worker-api.ts"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/repo-owners.test.ts b/test/repo-owners.test.ts index 0e0a306e..ffbe937a 100644 --- a/test/repo-owners.test.ts +++ b/test/repo-owners.test.ts @@ -11,7 +11,7 @@ import { runSync } from "../src/mirror.ts"; import { RepoError, trackRepo, trackRepoChecked } from "../src/repos.ts"; import { G } from "./guarded.ts"; import { SCRATCH } from "./scratch.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { saveSyncState, loadSyncState } from "../src/data/mirror/index.ts"; test("a tracked repo of another owner is written to under its own owner; storytold repos are unchanged", async () => { diff --git a/test/retired-drop.test.ts b/test/retired-drop.test.ts index c08fb397..22731c9d 100644 --- a/test/retired-drop.test.ts +++ b/test/retired-drop.test.ts @@ -2,11 +2,10 @@ // the switch moved, it archives what is left, drops everything and leaves a database that works. import { test } from "node:test"; import assert from "node:assert/strict"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb, type Db } from "./helpers/raw-db.ts"; import { dropRetired } from "../src/db/retired.ts"; import { DROP_RETIRED, RETIRED_COLUMNS, RETIRED_TABLES } from "../src/db/retired-names.ts"; import { switchOver } from "../src/db/switch-over.ts"; -import type { Db } from "../src/db/index.ts"; import { TEST_PG_URL } from "./test-db.ts"; const columns = async (db: Db, table: string): Promise => (await db.prepare(db.dialect === "postgres" diff --git a/test/review-followups.test.ts b/test/review-followups.test.ts index 42b5f507..4628d928 100644 --- a/test/review-followups.test.ts +++ b/test/review-followups.test.ts @@ -7,7 +7,7 @@ import { backfillAuthorIds } from "../src/author-ids.ts"; import { stripLinks } from "../src/review/post-template.ts"; import { tierKey, tiersOf } from "../src/whitelist.ts"; import { SCRATCH } from "./scratch.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; test("backfill binds logins with merge history, and a different account under the login is not whitelisted", async () => { mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/review-migration.test.ts b/test/review-migration.test.ts index e12f71dc..6240841c 100644 --- a/test/review-migration.test.ts +++ b/test/review-migration.test.ts @@ -5,8 +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 type { Db } from "../src/db/index.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb, type Db } from "./helpers/raw-db.ts"; import { sqliteOnly } from "./test-db.ts"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/runner-credentials.test.ts b/test/runner-credentials.test.ts index cb404586..09e133f0 100644 --- a/test/runner-credentials.test.ts +++ b/test/runner-credentials.test.ts @@ -19,7 +19,7 @@ import { parseClaim } from "../src/remote/calls.ts"; import { addressKey, MAX_PENDING_PER_ADDRESS, startLogin } from "../src/remote/device-login.ts"; import { PROTOCOL_VERSION, ROUTES, type LoginStartReply, type PendingRunnerLogin } from "../src/remote/protocol.ts"; 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"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/runner-steps.ts b/test/runner-steps.ts index 5ac9cb4d..3905d59c 100644 --- a/test/runner-steps.ts +++ b/test/runner-steps.ts @@ -1,6 +1,7 @@ // Fake pipeline steps for the runner and API tests (AUTOCRAFT_EXTRA_STEPS). // They call no model and touch nothing outside the test database. import { setTimeout as sleep } from "node:timers/promises"; +import { queryDb } from "../src/db/query-db.ts"; import type { StepDef } from "../src/runner/steps.ts"; export const FAKE_TOKEN = "ghp_" + "a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6q7R8"; @@ -24,7 +25,7 @@ export const steps: StepDef[] = [ if (ctx.params.mode === "fail") throw new Error("echo failed on purpose"); ctx.usageRun("test-run"); const t = new Date().toISOString(); - await ctx.db.prepare(`INSERT INTO token_usage (run_id, agent, stage, model, items, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, started_at, ended_at, cost_usd) + await queryDb(ctx.db).prepare(`INSERT INTO token_usage (run_id, agent, stage, model, items, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, started_at, ended_at, cost_usd) VALUES ('test-run', ?, 'test', 'fake', 1, 100, 10, 0, 0, ?, ?, 0.01)`).run(`echo-${ctx.job.id}`, t, t); return `echo ${ctx.params.n}`; }, diff --git a/test/runner.test.ts b/test/runner.test.ts index 81521acc..15551abf 100644 --- a/test/runner.test.ts +++ b/test/runner.test.ts @@ -8,7 +8,7 @@ import { join } from "node:path"; import { after, describe, test } from "node:test"; import { fileURLToPath } from "node:url"; import { SCRATCH } from "./scratch.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { rowid } from "../src/db/kx.ts"; process.env.AUTOCRAFT_EXTRA_STEPS = fileURLToPath(new URL("./runner-steps.ts", import.meta.url)); diff --git a/test/sandbox.test.ts b/test/sandbox.test.ts index a8554c11..8b2ffed9 100644 --- a/test/sandbox.test.ts +++ b/test/sandbox.test.ts @@ -16,7 +16,7 @@ import { REPO_PATH, sandboxCommand } from "../src/sandbox/command.ts"; import type { SessionAsk } from "../src/prepush/resume.ts"; import { fakeTaskRunner } from "./fake-runner.ts"; import { SCRATCH } from "./scratch.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { rowid } from "../src/db/kx.ts"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/scoped.test.ts b/test/scoped.test.ts index 4437794f..e81ae62a 100644 --- a/test/scoped.test.ts +++ b/test/scoped.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { SHADOWED_TABLES } from "../src/repos.ts"; test("a scoped handle sees tracked repos only and writes through main. to every repo", async () => { diff --git a/test/screenshot-config.test.ts b/test/screenshot-config.test.ts index 5be93e8c..1bcf1aa2 100644 --- a/test/screenshot-config.test.ts +++ b/test/screenshot-config.test.ts @@ -4,7 +4,7 @@ import { join } from "node:path"; import { test } from "node:test"; import { ScreenshotConfigError, deleteConfig, getConfig, paramValueError, parseScreenshotConfig, putConfig } from "../src/verify/screenshot-config.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 fresh = async () => await connectDb(join(mkdtempSync(join(SCRATCH, "sc-")), "t.db")); diff --git a/test/screenshots-plan.test.ts b/test/screenshots-plan.test.ts index 80e7e18e..d9bc1998 100644 --- a/test/screenshots-plan.test.ts +++ b/test/screenshots-plan.test.ts @@ -8,8 +8,7 @@ import { putConfig, type ScreenshotConfigBody } from "../src/verify/screenshot-c import { queueScreenshotTasks, screenshotTasks } from "../src/verify/tasks.ts"; import { runVerify, type VerifyDeps } from "../src/verify/index.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 * as kx from "../src/db/kx.ts"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/screenshots.test.ts b/test/screenshots.test.ts index fcd7e9df..27477316 100644 --- a/test/screenshots.test.ts +++ b/test/screenshots.test.ts @@ -12,9 +12,8 @@ import { runCollect, collectDue, type CollectDeps } from "../src/verify/results. import { putConfig, type ScreenshotConfigBody } from "../src/verify/screenshot-config.ts"; import { runVerify, type VerifyDeps } from "../src/verify/index.ts"; import { SCRATCH } from "./scratch.ts"; -import type { Db } from "../src/db/index.ts"; +import { connectDb, type Db } from "./helpers/raw-db.ts"; import { cols, excluded, like } from "../src/db/kx.ts"; -import { connectDb } from "../src/db/open.ts"; mkdirSync(SCRATCH, { recursive: true }); const dir = mkdtempSync(join(SCRATCH, "shots-collect-")); diff --git a/test/search.test.ts b/test/search.test.ts index feb5f5e2..be41173a 100644 --- a/test/search.test.ts +++ b/test/search.test.ts @@ -4,7 +4,7 @@ import { quickSearch } from "../src/dash/api/items.ts"; import { parseSearch } from "../src/db/search.ts"; import * as kx from "../src/db/kx.ts"; import type { Req } from "../src/dash/types.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; test("text search finds items by a body word, a comment word and a typed prefix, and leaves out the rest", async () => { const db = await connectDb(":memory:"); diff --git a/test/secfix-rounds.test.ts b/test/secfix-rounds.test.ts index fc56f6cf..70504551 100644 --- a/test/secfix-rounds.test.ts +++ b/test/secfix-rounds.test.ts @@ -13,7 +13,7 @@ import { sweepSessions } from "../src/prepush/resume.ts"; import { regressionName } from "../src/verify/types.ts"; import { patchFor } from "../src/verify/plan.ts"; import { SCRATCH } from "./scratch.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { jsonNum } from "../src/db/kx.ts"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/security-cli.test.ts b/test/security-cli.test.ts index f71a4f12..f7377d34 100644 --- a/test/security-cli.test.ts +++ b/test/security-cli.test.ts @@ -6,7 +6,7 @@ import { addLogin } from "../src/access.ts"; import { setTestRepo } from "../src/data/control/index.ts"; import { requireSessionOperator } from "../src/security/cli.ts"; import { SCRATCH } from "./scratch.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; test("the session refuses a repo that is not a test repo and a login that is not an operator", async () => { const db = await connectDb(join(SCRATCH, "cli.db")); diff --git a/test/security-fix-land.test.ts b/test/security-fix-land.test.ts index 0dd2ed16..5fac6bd7 100644 --- a/test/security-fix-land.test.ts +++ b/test/security-fix-land.test.ts @@ -12,7 +12,7 @@ import { PIPELINE_LOGIN_KEY } from "../src/core/rules.ts"; import { ownFixPrs } from "../src/core/facts.ts"; import { setPilot } from "../src/data/control/index.ts"; import { inScopeExpr } from "../src/data/workflow/fragments.ts"; -import type { Db } from "../src/db/index.ts"; +import { connectDb, type Db } from "./helpers/raw-db.ts"; import { fixOnMain, pollLanding, runAdvisory, stallReason, runLand, runPublish, type LandDeps } from "../src/security/land.ts"; import { runFix, type FixDeps } from "../src/security/fix.ts"; import { fixBranch, giveaway, parseFixReply, patchGiveaway, quietProblem } from "../src/security/rules.ts"; @@ -22,7 +22,6 @@ const isQuiet = async (db: Parameters[0], repo: string, n: num import { rawFinding } from "../src/security/store.ts"; import { Git } from "../src/fixup/git.ts"; import { SCRATCH } from "./scratch.ts"; -import { connectDb } from "../src/db/open.ts"; /** The item is in the pipeline's scope (the workflow scope fragment), read as the planner reads it. */ const inPilot = async (db: Db, repo: string, number: number): Promise => diff --git a/test/security-scan-tests.test.ts b/test/security-scan-tests.test.ts index e8a7920e..372cab8e 100644 --- a/test/security-scan-tests.test.ts +++ b/test/security-scan-tests.test.ts @@ -11,7 +11,7 @@ import { autoFixConfirmed } from "../src/security/actions.ts"; import { runScan, type Ask, type ScanDeps } from "../src/security/scan.ts"; import { advanceScanTests, NOT_SHOWN_NOTE } from "../src/security/scantest.ts"; import { SCRATCH } from "./scratch.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { cols, excluded, jsonNum } from "../src/db/kx.ts"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/security-scan.test.ts b/test/security-scan.test.ts index a3828b16..fe85e965 100644 --- a/test/security-scan.test.ts +++ b/test/security-scan.test.ts @@ -16,7 +16,7 @@ import { linkRepeatedFindings, runScan, type Ask, type ScanDeps } from "../src/s import { securityRepo } from "../src/security/rules.ts"; import { autoFixConfirmed } from "../src/security/actions.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 }); diff --git a/test/server.test.ts b/test/server.test.ts index 4986303d..675f82fe 100644 --- a/test/server.test.ts +++ b/test/server.test.ts @@ -10,7 +10,7 @@ import { loadConfig } from "../src/dash/server/config.ts"; import { defaultRoutes, SESSION_COOKIE, 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"; mkdirSync(SCRATCH, { recursive: true }); const dir = mkdtempSync(join(SCRATCH, "server-test-")); diff --git a/test/step-health.test.ts b/test/step-health.test.ts index 82c1e758..b52628ef 100644 --- a/test/step-health.test.ts +++ b/test/step-health.test.ts @@ -3,7 +3,7 @@ import { mkdtempSync } from "node:fs"; import { join } from "node:path"; import { test } from "node:test"; import { computeChecks } from "../src/health-checks.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { SCRATCH } from "./scratch.ts"; const NOW = Date.parse("2026-11-20T12:00:00Z"); diff --git a/test/step-repo.test.ts b/test/step-repo.test.ts index ad6e34e4..ab990044 100644 --- a/test/step-repo.test.ts +++ b/test/step-repo.test.ts @@ -7,7 +7,7 @@ import { after, test } from "node:test"; import { fileURLToPath } from "node:url"; import { SCRATCH } from "./scratch.ts"; import { everySeq } from "../src/async-seq.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { inList } from "../src/db/kx.ts"; process.env.AUTOCRAFT_EXTRA_STEPS = fileURLToPath(new URL("./runner-steps.ts", import.meta.url)); diff --git a/test/stream-progress.test.ts b/test/stream-progress.test.ts index 3123f9a5..c75f5077 100644 --- a/test/stream-progress.test.ts +++ b/test/stream-progress.test.ts @@ -7,8 +7,7 @@ import { fakeTaskRunner } from "./fake-runner.ts"; import { SCRATCH } from "./scratch.ts"; import { askClaude, setWorkspace } from "../src/classify/run.ts"; import { eventLines } from "../src/classify/progress.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, "stream-")); diff --git a/test/stuck-jobs.test.ts b/test/stuck-jobs.test.ts index 3a2355fe..06ce3056 100644 --- a/test/stuck-jobs.test.ts +++ b/test/stuck-jobs.test.ts @@ -8,7 +8,7 @@ import { fileURLToPath } from "node:url"; import { setCommentApproval } from "../src/act/approval.ts"; import { SCRATCH } from "./scratch.ts"; import { world } from "./world-db.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; process.env.AUTOCRAFT_EXTRA_STEPS = fileURLToPath(new URL("./runner-steps.ts", import.meta.url)); diff --git a/test/switch-over.test.ts b/test/switch-over.test.ts index d2710bae..0ed07d64 100644 --- a/test/switch-over.test.ts +++ b/test/switch-over.test.ts @@ -2,8 +2,7 @@ // it again changes nothing. Runs on either engine (connectDb). import { test } from "node:test"; import assert from "node:assert/strict"; -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 { STATE_COPY_DONE } from "../src/db/state-copy.ts"; import { SWITCH_KEY, switchOver } from "../src/db/switch-over.ts"; import { loadEvents, loadLastEventKinds, loadMergeApprovals } from "../src/data/workflow/index.ts"; diff --git a/test/sync-health.test.ts b/test/sync-health.test.ts index 246b0a99..02af7211 100644 --- a/test/sync-health.test.ts +++ b/test/sync-health.test.ts @@ -8,7 +8,7 @@ import { computeChecks, serveChecks } from "../src/health-checks.ts"; import { GithubError, reconcileNext, runSync } from "../src/mirror.ts"; import { reloadRepoOwners } from "../src/repos.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"; import { sqliteOnly } from "./test-db.ts"; import { saveSyncState, loadSyncState } from "../src/data/mirror/index.ts"; diff --git a/test/test-db.ts b/test/test-db.ts index d443fe41..9c2a1930 100644 --- a/test/test-db.ts +++ b/test/test-db.ts @@ -4,9 +4,8 @@ import { randomBytes } from "node:crypto"; import { join } from "node:path"; import { DatabaseSync } from "node:sqlite"; import { SCRATCH } from "./scratch.ts"; -import type { Db } from "../src/db/index.ts"; +import { connectDb, dbFor, type Db } from "./helpers/raw-db.ts"; import { connect } from "../src/db.ts"; -import { connectDb, dbFor } from "../src/db/open.ts"; import { pgSuite } from "./pg-suite.ts"; /** The Postgres server tests run against, if any. */ diff --git a/test/test-repo-trip.test.ts b/test/test-repo-trip.test.ts index 2089bb87..90f81cf4 100644 --- a/test/test-repo-trip.test.ts +++ b/test/test-repo-trip.test.ts @@ -3,8 +3,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { loadTrips, resumeStage, tripMergeBreakers } from "../src/data/control/index.ts"; import { loadMergedInfo } from "../src/data/merge/index.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"; /** A post-merge review of a PR we merged found defects, as the post-merge review records it. */ async function mergeDefect(db: Db, repo: string, number: number, defects: number, at: string): Promise { diff --git a/test/trip-resume-maintainer.test.ts b/test/trip-resume-maintainer.test.ts index f8728d93..3c798054 100644 --- a/test/trip-resume-maintainer.test.ts +++ b/test/trip-resume-maintainer.test.ts @@ -3,11 +3,10 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { evaluatePushBreakers, loadTrips, tripStage } from "../src/data/control/index.ts"; -import type { Db } from "../src/db/index.ts"; +import { connectDb, type Db } from "./helpers/raw-db.ts"; import { resumeTrip } from "../src/dash/api/pipeline.ts"; import { loadItemFact } from "../src/core/issue-facts.ts"; import { gates } from "../src/core/gates.ts"; -import { connectDb } from "../src/db/open.ts"; const trip = async (db: Db, key: string, reason: string, evidence: string[], at: string): Promise => void await tripStage(db, [{ key, reason, evidence, at }]); const evaluatePushBreaker = async (db: Db, stage: string, repo: string, at: string): Promise => void await evaluatePushBreakers(db, [{ stage, repo }], at); diff --git a/test/unsent-comment.test.ts b/test/unsent-comment.test.ts index d6a5036e..7f64d104 100644 --- a/test/unsent-comment.test.ts +++ b/test/unsent-comment.test.ts @@ -13,7 +13,7 @@ import type { ConflictCandidate } from "../src/fixup/conflict-state.ts"; import type { FixupDeps, FixupSummary } from "../src/fixup/index.ts"; import { setGithubIdentity } from "../src/github/identity.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 }); diff --git a/test/vault.test.ts b/test/vault.test.ts index e105f7ec..9da2d117 100644 --- a/test/vault.test.ts +++ b/test/vault.test.ts @@ -10,7 +10,7 @@ import { accessToken, createSession, openTokens, sealTokens } from "../src/dash/ import { dropSessionTokens, readUserTokens, saveUserTokens } from "../src/dash/server/user-tokens.ts"; import { Vault } from "../src/github/vault.ts"; import { SCRATCH } from "./scratch.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; const REDIRECT = "http://localhost/cb"; diff --git a/test/views-lists.test.ts b/test/views-lists.test.ts index 6f1d4f61..181eadc2 100644 --- a/test/views-lists.test.ts +++ b/test/views-lists.test.ts @@ -1,7 +1,7 @@ // The list views behind Home, Items, Repos, Stats and the top-bar search (src/data/views): filters, hidden repos and counts. 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 { loadMaintainRepos } from "../src/data/views/maintain.ts"; import { loadItemsBase } from "../src/data/views/maintain-items.ts"; import { loadMaintainStats } from "../src/data/views/stats.ts"; diff --git a/test/visibility-sec3.test.ts b/test/visibility-sec3.test.ts index b0858e5f..ed6ece58 100644 --- a/test/visibility-sec3.test.ts +++ b/test/visibility-sec3.test.ts @@ -12,7 +12,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"; mkdirSync(SCRATCH, { recursive: true }); const dir = mkdtempSync(join(SCRATCH, "visibility-sec3-")); diff --git a/test/visibility.test.ts b/test/visibility.test.ts index 0fa82021..b6e84635 100644 --- a/test/visibility.test.ts +++ b/test/visibility.test.ts @@ -17,7 +17,7 @@ import { startServer } from "../src/dash/server/index.ts"; import { ImageProxy } from "../src/dash/server/images.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 { like } from "../src/db/kx.ts"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/warm-caches.test.ts b/test/warm-caches.test.ts index a4acf6ed..569ece14 100644 --- a/test/warm-caches.test.ts +++ b/test/warm-caches.test.ts @@ -4,7 +4,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { cacheReport, type StoredCaches } from "../src/build/caches.ts"; import { warmKeyOf } from "../src/build/tasks.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { saveWarmReport } from "../src/data/build/index.ts"; import type { HiddenRepos } from "../src/hidden-sql.ts"; diff --git a/test/warm-repos.test.ts b/test/warm-repos.test.ts index 30ae6165..47dd85cf 100644 --- a/test/warm-repos.test.ts +++ b/test/warm-repos.test.ts @@ -4,7 +4,7 @@ import { test } from "node:test"; import { createEnv } from "../src/build/envs.ts"; import { parseSettings } from "../src/build/pods.ts"; import { changeWarmRepos, warmPass, warmRepos } from "../src/build/warm-queue.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; test("warmPass queues only repos that are in scope and in the allowlist", async () => { const d = await connectDb(":memory:"); diff --git a/test/webhooks.test.ts b/test/webhooks.test.ts index e1062d94..122b4762 100644 --- a/test/webhooks.test.ts +++ b/test/webhooks.test.ts @@ -7,7 +7,7 @@ import { drainSyncRequests, handleDelivery, signatureOf } from "../src/github/we import { writeItemNode } from "../src/mirror.ts"; import { validating } from "./gql.ts"; import { SCRATCH } from "./scratch.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; const SECRET = "hook-secret"; async function scratch() { diff --git a/test/worker-hardening.test.ts b/test/worker-hardening.test.ts index dcfdb869..e3598fa4 100644 --- a/test/worker-hardening.test.ts +++ b/test/worker-hardening.test.ts @@ -8,7 +8,7 @@ import { createEnv, hello } from "../src/build/envs.ts"; import { claim, createTask, warmKeyOf } from "../src/build/tasks.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"; test("warm keys: distinct repo names never share a key, and every key is valid", () => { const names = ["a.b", "a-b", "A.B", "x".repeat(70), "x".repeat(71), "---", "..."]; diff --git a/test/worker-output-sec3.test.ts b/test/worker-output-sec3.test.ts index 3cece535..319f916c 100644 --- a/test/worker-output-sec3.test.ts +++ b/test/worker-output-sec3.test.ts @@ -13,7 +13,7 @@ import { computeChecks } from "../src/health-checks.ts"; import { runFix, type FixDeps } from "../src/security/fix.ts"; import { advanceSecurityFixes } from "../src/security/actions.ts"; import { rustPlan } from "../src/worker/rust.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; const HEAD = [ "fn add(a: i32, b: i32) -> i32 { a + b }", diff --git a/test/worker-trust.test.ts b/test/worker-trust.test.ts index bc9f05a8..501c4d76 100644 --- a/test/worker-trust.test.ts +++ b/test/worker-trust.test.ts @@ -10,7 +10,7 @@ import { rustPlan } from "../src/worker/rust.ts"; import { resolveI18nRev } from "../src/worker/gate.ts"; import { crateFilesOf } from "../src/worker/cache.ts"; import { buildScripts, editable } from "../src/fixup/patch.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; const sha = (c: string) => c.repeat(40); diff --git a/test/workspace-fetch.test.ts b/test/workspace-fetch.test.ts index 99b56828..00fa93af 100644 --- a/test/workspace-fetch.test.ts +++ b/test/workspace-fetch.test.ts @@ -11,7 +11,7 @@ import { createEnv } from "../src/build/envs.ts"; import type { ExecOptions, ExecResult, KPod, KubeApi } from "../src/build/kube-api.ts"; import { WorkspaceSession } from "../src/build/workspace-tools.ts"; import { createWorkspace, moveWorkspace } from "../src/build/workspaces.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { SCRATCH } from "./scratch.ts"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/workspace-pods.test.ts b/test/workspace-pods.test.ts index 84f73b88..5378dd1a 100644 --- a/test/workspace-pods.test.ts +++ b/test/workspace-pods.test.ts @@ -15,7 +15,7 @@ import { queueWorkspaceCall } from "../src/build/workspace-call.ts"; import { IDLE_PARK_MS, NODE_LOST_MS, PARKED_VOLUME_MS, RESUME_PENDING_MS, workspacePass, WorkspaceState } from "../src/build/workspace-launch.ts"; import { createWorkspace, getCheckpoint, getWorkspace, RESUME_TRIES, resumeWorkspace } from "../src/build/workspaces.ts"; import { WS_POD_PATH } from "../src/build/workspace.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { SCRATCH } from "./scratch.ts"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/workspace-relay.test.ts b/test/workspace-relay.test.ts index a67c3457..4e8e9b77 100644 --- a/test/workspace-relay.test.ts +++ b/test/workspace-relay.test.ts @@ -14,7 +14,7 @@ import { calls, image } from "../src/dash/api/workspaces.ts"; import type { Req } from "../src/dash/types.ts"; import { mcpReply } from "../src/dash/mcp/index.ts"; import { createToken } from "../src/dash/mcp/tokens.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { awaitCall, claimCall, submitCall, type Caller } from "../src/remote/calls.ts"; import { PROTOCOL_VERSION, type TaskBundle } from "../src/remote/protocol.ts"; import { SCRATCH } from "./scratch.ts"; diff --git a/test/workspace-sessions.test.ts b/test/workspace-sessions.test.ts index 0e06003d..a099d9d0 100644 --- a/test/workspace-sessions.test.ts +++ b/test/workspace-sessions.test.ts @@ -10,7 +10,7 @@ import { parseStatus, storeStatus } from "../src/remote/helpers.ts"; import { setUserRepos } from "../src/remote/my-repos.ts"; import { noTakerFor } from "../src/remote/takers.ts"; import { world } from "./world-db.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { SCRATCH } from "./scratch.ts"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/workspace-tools.test.ts b/test/workspace-tools.test.ts index 1cdf22f9..cc4b2b41 100644 --- a/test/workspace-tools.test.ts +++ b/test/workspace-tools.test.ts @@ -14,7 +14,7 @@ import type { ExecOptions, ExecResult, KPod, KubeApi } from "../src/build/kube-a import { WS_POD_PATH } from "../src/build/workspace.ts"; import { SESSION_LIMITS, WorkspaceSession } from "../src/build/workspace-tools.ts"; import { createWorkspace, moveWorkspace } from "../src/build/workspaces.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { SCRATCH } from "./scratch.ts"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/workspace-warm.test.ts b/test/workspace-warm.test.ts index 5b36a2b0..fa20d2ef 100644 --- a/test/workspace-warm.test.ts +++ b/test/workspace-warm.test.ts @@ -19,7 +19,7 @@ import { workspacePass, WorkspaceState } from "../src/build/workspace-launch.ts" import { LAYOUT_CI, WARM_CHANGED_FILES, warmOf, workspaceEnvHash } from "../src/build/workspace-layout.ts"; import { WS_POD_PATH } from "../src/build/workspace.ts"; import { createWorkspace, getWorkspace } from "../src/build/workspaces.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; import { STATUS_DATA_KEY, STATUS_LABEL } from "../src/warm/sync-agent.ts"; import { SCRATCH } from "./scratch.ts"; diff --git a/test/workspaces-api.test.ts b/test/workspaces-api.test.ts index 4ce239bb..7223cad9 100644 --- a/test/workspaces-api.test.ts +++ b/test/workspaces-api.test.ts @@ -7,7 +7,7 @@ import { TOPICS } from "../src/db/live.ts"; import { INPUT_TOPICS } from "../src/runner/autopilot.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"; mkdirSync(SCRATCH, { recursive: true }); diff --git a/test/world-db.ts b/test/world-db.ts index a30a4822..da839d6f 100644 --- a/test/world-db.ts +++ b/test/world-db.ts @@ -23,8 +23,7 @@ import { savePremerge } from "../src/premerge/store.ts"; import type { PremergeFinding } from "../src/premerge/types.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"; export const T0 = "2026-01-01T00:00:00Z"; export const T1 = "2026-01-02T00:00:00Z"; diff --git a/test/write-pacing.test.ts b/test/write-pacing.test.ts index ae2e1564..3b71495b 100644 --- a/test/write-pacing.test.ts +++ b/test/write-pacing.test.ts @@ -7,7 +7,7 @@ import { SCRATCH } from "./scratch.ts"; import { addLabels, closeItem, commentOn, PACE_PER_MINUTE, WritePacedError, type Writer } from "../src/github/write.ts"; import type { Grant } from "../src/core/guard.ts"; import type { Querier } from "../src/mirror.ts"; -import { connectDb } from "../src/db/open.ts"; +import { connectDb } from "./helpers/raw-db.ts"; mkdirSync(SCRATCH, { recursive: true });