Public: anyone can read this; the crew can change it.

Trace index backfill stands aside when the database is locked (the hold on v0.7.729) #18082

opened this

Merged 34h 47m ago, live in production

trace-backfill-waits → main 0 commits

  • Merged. trace-backfill-waits was merged into main as 52a26e1.

Review

Sign in to review this change.
3 files changed +86 −19
src/trace/index_table.ts +53 −19
@@ -12,6 +12,8 @@
1212 import type { Database } from "bun:sqlite";
1313 import { getIssueById } from "../core/issues.ts";
1414 import { getRun, isTerminal } from "../core/runs.ts";
15 import { isBusy, withoutWaiting } from "../kernel/db.ts";
16 import { background } from "../perf/jobs.ts";
1517 import { readRunLog, readRunTimes } from "../runs/log.ts";
1618 import { totalsOf } from "./model.ts";
1719 import { parseRunLog } from "./run_log.ts";
@@ -167,43 +169,75 @@ const SOURCES = {
167169
168170 const yieldThread = (): Promise<void> => new Promise((resolve) => setImmediate(resolve));
169171
172 /** How long the backfill stands aside when another writer holds the database, before it tries again. */
173 export const BACKFILL_BUSY_WAIT_MS = 250;
174
175 const standAside = (): Promise<void> =>
176 new Promise((resolve) => setTimeout(() => background("trace-index-backfill-wait", resolve), BACKFILL_BUSY_WAIT_MS));
177
170178 /**
171179 * Index the runs and Talk turns that ended before the index existed, once: `batch` rows at a time
172180 * in one transaction, the place reached stored with it (`trace_index_backfill`), then a yield so
173181 * requests are answered between batches. Done sources are skipped on the next boot. Returns how
174182 * many rows it wrote.
183 *
184 * It never waits for the write lock on the serving thread, and a held lock never ends it: each
185 * step tries the lock once (`withoutWaiting`), and when another writer has it (the engine worker,
186 * or a forge still draining on this data during a release) the backfill stands aside (`wait`) and
187 * takes the same step again from the place it had reached. A release was held on this at 05:50 on
188 * 2026-12-04: the first step met a locked database and the backfill ended with an error.
175189 */
176190 export async function backfillTraceIndex(
177191 db: Database,
178192 dataDir: string,
179 options: { batch?: number; yieldNow?: () => Promise<void> } = {},
193 options: { batch?: number; yieldNow?: () => Promise<void>; wait?: () => Promise<void> } = {},
180194 ): Promise<number> {
181195 const batch = options.batch ?? BACKFILL_BATCH;
182196 const pause = options.yieldNow ?? yieldThread;
197 const wait = options.wait ?? standAside;
198 const whenFree = async <T>(step: () => T): Promise<T> => {
199 for (;;) {
200 try {
201 return withoutWaiting(db, step);
202 } catch (error) {
203 if (!isBusy(error)) throw error;
204 await wait();
205 }
206 }
207 };
183208 let written = 0;
184209 for (const source of ["run", "talk"] as const) {
185 db.query("INSERT OR IGNORE INTO trace_index_backfill (source) VALUES (?1)").run(source);
186 const state = db.query<{ after: string; done_at: string | null }, [string]>("SELECT after, done_at FROM trace_index_backfill WHERE source = ?1").get(source)!;
210 const state = await whenFree(() => {
211 db.query("INSERT OR IGNORE INTO trace_index_backfill (source) VALUES (?1)").run(source);
212 return db.query<{ after: string; done_at: string | null }, [string]>("SELECT after, done_at FROM trace_index_backfill WHERE source = ?1").get(source)!;
213 });
187214 if (state.done_at !== null) continue;
188215 let after = state.after;
189216 for (;;) {
190 const ids = db.query<{ id: string }, [string, number]>(SOURCES[source].ids).all(after, batch);
191 db.transaction(() => {
192 for (const { id } of ids) {
193 // One unreadable record is skipped, never the batch: it would stop the backfill at that
194 // id for good.
195 try {
196 if (SOURCES[source].index(db, dataDir, id)) written += 1;
197 } catch {
198 continue;
217 // A busy database is met at the transaction's BEGIN, before any row is written, so a step
218 // taken again counts nothing twice.
219 const read = await whenFree(() => {
220 const ids = db.query<{ id: string }, [string, number]>(SOURCES[source].ids).all(after, batch);
221 let wrote = 0;
222 db.transaction(() => {
223 for (const { id } of ids) {
224 // One unreadable record is skipped, never the batch: it would stop the backfill at that
225 // id for good.
226 try {
227 if (SOURCES[source].index(db, dataDir, id)) wrote += 1;
228 } catch {
229 continue;
230 }
199231 }
200 }
201 const last = ids[ids.length - 1]?.id;
202 if (last !== undefined) after = last;
203 if (ids.length < batch) db.query("UPDATE trace_index_backfill SET after = ?2, done_at = ?3 WHERE source = ?1").run(source, after, new Date().toISOString());
204 else db.query("UPDATE trace_index_backfill SET after = ?2 WHERE source = ?1").run(source, after);
205 })();
206 if (ids.length < batch) break;
232 const last = ids[ids.length - 1]?.id ?? after;
233 if (ids.length < batch) db.query("UPDATE trace_index_backfill SET after = ?2, done_at = ?3 WHERE source = ?1").run(source, last, new Date().toISOString());
234 else db.query("UPDATE trace_index_backfill SET after = ?2 WHERE source = ?1").run(source, last);
235 })();
236 return { n: ids.length, wrote, last: ids[ids.length - 1]?.id };
237 });
238 written += read.wrote;
239 if (read.last !== undefined) after = read.last;
240 if (read.n < batch) break;
207241 await pause();
208242 }
209243 }
test/job-slices.test.ts +1
@@ -331,6 +331,7 @@ const UNTIMED: Record<string, string> = {
331331 "bring-wait": "a one-shot timer that only resolves a promise when a bring's mirror is still copying after 60 s, so the answer says it is copying (actions/bring.ts, bringToWork); no work of its own; talk-bring.test.ts brings a repository that settles first",
332332 "pinned-watch": "a one-shot timer between the pinned watch's looks at a pinned deploy (actions/pinned_watch.ts WATCH.sleep); it only resolves the sleep, no work of its own; pinned-watch tests drive the watch with a short sleep",
333333 "runner-wait": "one-shot timers that only resolve a promise: a runner's claim held open, a check's look at its job each second (checks/runner_jobs.ts, runner_step.ts) and the runner program's own pauses; off unless FORGE_CHECKS_PLACEMENT=runner, and checks-runner-placement.test.ts drives all three",
334 "trace-index-backfill-wait": "a one-shot timer that only resolves a promise: the trace index backfill standing aside 250 ms while another writer holds the database (trace/index_table.ts); trace-index.test.ts drives the wait",
334335 "git-pace": "a one-shot timer in git/pace.ts that only resolves the promise a paced pack write waits on: no work of its own, armed per pack chunk while a page response is in flight; git-pace.test.ts drives the pacer with a fake clock",
335336 "search-warm-start": "a one-shot zero-delay timer that starts the search warm-up once, after the first search a forge answers (actions/search.ts onFirstSearch); the work itself is search/warm.ts, timed by its own tests; search warm-on-first-use tests drive it",
336337 "dataset-export": "every 10 minutes reads the last export's time and returns unless a night has passed; the publish itself runs once a night in actions/dataset.ts publishDataset and is off without a dataset repository; dataset tests drive publishDataset directly",
test/trace-index.test.ts +32
@@ -2,6 +2,7 @@
22 * The trace index (#18020): rows written as a run or a Talk turn ends, a bounded backfill, a
33 * listing.
44 */
5 import { Database } from "bun:sqlite";
56 import { afterAll, beforeAll, expect, test } from "bun:test";
67 import { mkdtemp, rm } from "node:fs/promises";
78 import { tmpdir } from "node:os";
@@ -182,6 +183,37 @@ test("the backfill of 10,000 runs never runs longer than one batch between yield
182183 expect(await backfillTraceIndex(app.db, dir, { yieldNow: async () => {} })).toBe(0);
183184 }, 60_000);
184185
186 test("a database another writer holds does not end the backfill: it stands aside and goes on from its place", async () => {
187 app.db.query("DELETE FROM trace_index_backfill").run();
188 const stamp = new Date(Date.UTC(2026, 5, 1)).toISOString();
189 app.db
190 .query("INSERT INTO run (id, repo_id, kind, state, summary, cost_usd, created_at, started_at, finished_at) VALUES ('zzbusy1',?1,'agent','ok','late run',0.01,?2,?2,?2)")
191 .run(repo.id, stamp);
192 const other = new Database(join(dir, "forge.db"));
193 other.exec("BEGIN IMMEDIATE");
194 let waits = 0;
195 let held = true;
196 const began = performance.now();
197 const written = await backfillTraceIndex(app.db, dir, {
198 yieldNow: async () => {},
199 wait: async () => {
200 waits += 1;
201 if (waits === 3) {
202 other.exec("COMMIT");
203 held = false;
204 }
205 },
206 });
207 if (held) other.exec("ROLLBACK");
208 other.close();
209 expect(waits).toBe(3);
210 expect(written).toBe(1);
211 expect((app.db.query("SELECT COUNT(*) AS n FROM trace_index WHERE id = 'zzbusy1'").get() as { n: number }).n).toBe(1);
212 // It asked for the lock and stood aside; it never sat on the thread for the handle's busy timeout.
213 expect(performance.now() - began).toBeLessThan(5_000);
214 expect((app.db.query("PRAGMA busy_timeout").get() as { timeout: number }).timeout).toBeGreaterThan(0);
215 }, 30_000);
216
185217 test("the list reads through an index, never a scan or a sort", () => {
186218 const plan = (sql: string, ...args: null[]): string =>
187219 (app.db.query(`EXPLAIN QUERY PLAN ${sql}`).all(...args) as { detail: string }[]).map((r) => r.detail).join("\n");

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs