Public: anyone can read this; the crew can change it.
Traces 1a: a trace index table, filled when a run or Talk turn ends and backfilled once off the serving thread #18061
Merged 13h 44m ago, live in production
torque/forge:torque/18020-traces-1a-a-trace-index-table-filled-whe → main 0 commits fork
7 files
changed +573
−0
src/actions/runs.ts +10
| @@ -25,6 +25,7 @@ import { canEnterApp, canSeeOwnerFacts, getRepoById, onCrew, type Repo } from ". | ||
| 25 | 25 | import { |
| 26 | 26 | cancelRun as markCancelled, |
| 27 | 27 | getRun, |
| 28 | isTerminal, | |
| 28 | 29 | listRuns as queryRuns, |
| 29 | 30 | runningAbout, |
| 30 | 31 | runningCount, |
| @@ -50,6 +51,7 @@ import { cancelledBy } from "../runs/cancelled.ts"; | ||
| 50 | 51 | import { requireReader, requireWriter, type AccessError } from "./access.ts"; |
| 51 | 52 | import { deskForRun } from "../crew/desk_posts.ts"; |
| 52 | 53 | import { takeSeatNote } from "../crew/seat_note.ts"; |
| 54 | import { indexRun } from "../trace/index_table.ts"; | |
| 53 | 55 | import { claimedRunners } from "../checks/runner_jobs.ts"; |
| 54 | 56 | |
| 55 | 57 | const log = createLog("runs"); |
| @@ -83,6 +85,14 @@ export function announceRun(app: App, run: Run, actorId?: string): void { | ||
| 83 | 85 | // The desk follows every run's state: posted while it works, cleared when it ends |
| 84 | 86 | // however it ends. |
| 85 | 87 | deskForRun(app.db, run); |
| 88 | // An agent run that has ended gets its row in the trace index; a failure here never stops the | |
| 89 | // announcement. | |
| 90 | if (run.kind === "agent" && isTerminal(run.state)) | |
| 91 | try { | |
| 92 | indexRun(app.db, app.config.dataDir, run.id); | |
| 93 | } catch (error) { | |
| 94 | app.log.warn("trace index: could not index a run", { run: run.id, error: String(error) }); | |
| 95 | } | |
| 86 | 96 | const kind = |
| 87 | 97 | run.state === "queued" |
| 88 | 98 | ? "run.queued" |
src/core/migration-pins/20261204052000-trace-index.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 3aaeab535243485d7e99a3bcb8681c6b45d2192841316dda2836561dfdcc3890 |
src/core/migrations/20261204052000-trace-index.ts added +34
| @@ -0,0 +1,34 @@ | ||
| 1 | // The trace index (#18020, part of #17991): one row per ended crew run or Talk turn, so traces can | |
| 2 | // be listed without opening each raw record. Additive (two new tables, nothing altered), and a | |
| 3 | // derived index: the row holds figures and a title, never the content, which stays in the run log. | |
| 4 | // `repository` is the repository's id ('' for a Talk turn, which has none); `account` is the | |
| 5 | // subscription id the run was paid from. Listing walks `trace_index_recent` (newest first) or | |
| 6 | // `trace_index_by_repository`. `trace_index_backfill` remembers how far the one-time backfill | |
| 7 | // of each source got, so a restart resumes instead of starting again. | |
| 8 | export default ` | |
| 9 | CREATE TABLE trace_index ( | |
| 10 | id TEXT PRIMARY KEY, | |
| 11 | kind TEXT NOT NULL CHECK (kind IN ('run','talk','review')), | |
| 12 | repository TEXT NOT NULL DEFAULT '', | |
| 13 | title TEXT NOT NULL DEFAULT '', | |
| 14 | model TEXT NOT NULL DEFAULT '', | |
| 15 | account TEXT NOT NULL DEFAULT '', | |
| 16 | steps INTEGER NOT NULL DEFAULT 0, | |
| 17 | errors INTEGER NOT NULL DEFAULT 0, | |
| 18 | tokens_in INTEGER NOT NULL DEFAULT 0, | |
| 19 | tokens_cached INTEGER NOT NULL DEFAULT 0, | |
| 20 | tokens_out INTEGER NOT NULL DEFAULT 0, | |
| 21 | cost_usd REAL NOT NULL DEFAULT 0, | |
| 22 | outcome TEXT NOT NULL DEFAULT '', | |
| 23 | started TEXT NOT NULL, | |
| 24 | ended TEXT NOT NULL | |
| 25 | ) WITHOUT ROWID; | |
| 26 | CREATE INDEX trace_index_recent ON trace_index(started DESC, id DESC); | |
| 27 | CREATE INDEX trace_index_by_repository ON trace_index(repository, started DESC, id DESC); | |
| 28 | ||
| 29 | CREATE TABLE trace_index_backfill ( | |
| 30 | source TEXT PRIMARY KEY CHECK (source IN ('run','talk')), | |
| 31 | after TEXT NOT NULL DEFAULT '', | |
| 32 | done_at TEXT | |
| 33 | ) WITHOUT ROWID; | |
| 34 | `; |
src/crew/conversation.ts +15
| @@ -55,6 +55,7 @@ import { running } from "../kernel/version.ts"; | ||
| 55 | 55 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 56 | 56 | import { storedText } from "../kernel/blocked.ts"; |
| 57 | 57 | import { appendRunLog } from "../runs/log.ts"; |
| 58 | import { indexTalkTurn } from "../trace/index_table.ts"; | |
| 58 | 59 | import { |
| 59 | 60 | BUDGET_REACHED, |
| 60 | 61 | TURNS_REACHED, |
| @@ -774,6 +775,18 @@ function connectionPick(app: App, on: Connection, key: string): Pick { | ||
| 774 | 775 | return { kind: "ready", subscription, envName: "OPENAI_API_KEY", token: key, apiBase: on.base, ...(cap === undefined || on.scope === "yours" ? {} : { capUsd: cap }) }; |
| 775 | 776 | } |
| 776 | 777 | |
| 778 | /** | |
| 779 | * An ended turn's row in the trace index; a failure to write it never costs the person their | |
| 780 | * answer. | |
| 781 | */ | |
| 782 | function indexTurn(app: App, runId: string): void { | |
| 783 | try { | |
| 784 | indexTalkTurn(app.db, app.config.dataDir, runId); | |
| 785 | } catch (error) { | |
| 786 | app.log.warn("trace index: could not index a turn", { run: runId, error: String(error) }); | |
| 787 | } | |
| 788 | } | |
| 789 | ||
| 777 | 790 | /** |
| 778 | 791 | * The most turns the forge starts on its own for one plan, and what they may cost, before it stops. |
| 779 | 792 | */ |
| @@ -1110,6 +1123,7 @@ function begin( | ||
| 1110 | 1123 | app.db |
| 1111 | 1124 | .query("UPDATE conversation_run SET state = 'stopped', stopped = 1, tokens_in = ?2, tokens_out = ?3, cost_usd = ?4, finished_at = ?5, context_tokens = ?6, context_window = ?7, reported_usd = ?8 WHERE id = ?1") |
| 1112 | 1125 | .run(runId, outcome?.tokensIn ?? 0, outcome?.tokensOut ?? 0, cost, new Date().toISOString(), outcome?.contextTokens ?? 0, outcome?.contextWindow ?? 0, reported); |
| 1126 | indexTurn(app, runId); | |
| 1113 | 1127 | app.db.query("UPDATE subscription SET spent_usd = spent_usd + ?2 WHERE id = ?1").run(subscriptionId, cost); |
| 1114 | 1128 | return; |
| 1115 | 1129 | } |
| @@ -1159,6 +1173,7 @@ function begin( | ||
| 1159 | 1173 | "UPDATE conversation_run SET state = ?2, tokens_in = ?3, tokens_out = ?4, cost_usd = ?5, finished_at = ?6, context_tokens = ?7, context_window = ?8, reported_usd = ?9 WHERE id = ?1", |
| 1160 | 1174 | ) |
| 1161 | 1175 | .run(runId, outcome?.ok === true && !toolless.signal.aborted ? "ok" : "failed", outcome?.tokensIn ?? 0, outcome?.tokensOut ?? 0, cost, new Date().toISOString(), outcome?.contextTokens ?? 0, outcome?.contextWindow ?? 0, reported); |
| 1176 | indexTurn(app, runId); | |
| 1162 | 1177 | // Against the account's lifetime budget, like a run's cost (`subscription.spent_usd`). |
| 1163 | 1178 | app.db.query("UPDATE subscription SET spent_usd = spent_usd + ?2 WHERE id = ?1").run(subscriptionId, cost); |
| 1164 | 1179 | ended = { how: outcome === undefined ? "error" : outcome.ok ? "ok" : outcome.reason, usd: cost }; |
src/main.ts +9
| @@ -44,6 +44,7 @@ import { announceSandboxed } from "./spawn/sandboxed.ts"; | ||
| 44 | 44 | import { keepSandboxing } from "./spawn/move_cell.ts"; |
| 45 | 45 | import { applyBootDefaults, stopCellChildren } from "./spawn/cell.ts"; |
| 46 | 46 | import { backfillChildren } from "./spawn/forge_code_backfill.ts"; |
| 47 | import { backfillTraceIndex } from "./trace/index_table.ts"; | |
| 47 | 48 | import { firstBoot } from "./spawn/first-boot.ts"; |
| 48 | 49 | import { previewIdentityKey } from "./spawn/preview-owner.ts"; |
| 49 | 50 | import { PREVIEW_ADMIN } from "./spawn/preview-looks.ts"; |
| @@ -668,6 +669,14 @@ void backfillChildren(app) | ||
| 668 | 669 | if (Object.keys(done).length > 0) app.log.info("forge-code backfill", { done: JSON.stringify(done) }); |
| 669 | 670 | }) |
| 670 | 671 | .catch((error) => app.log.error("could not backfill children's forge code", { error: String(error) })); |
| 672 | // Runs and Talk turns that ended before the trace index existed are indexed once, in batches that | |
| 673 | // yield (#18020). | |
| 674 | if (!readOnly) | |
| 675 | void backfillTraceIndex(app.db, app.config.dataDir) | |
| 676 | .then((n) => { | |
| 677 | if (n > 0) app.log.info("trace index backfill", { rows: n }); | |
| 678 | }) | |
| 679 | .catch((error) => app.log.error("could not backfill the trace index", { error: String(error) })); | |
| 671 | 680 | // A forge still draining on this database keeps writing for its gates and |
| 672 | 681 | // runs; starting ours beside it stalls the listener behind its write lock |
| 673 | 682 | // (#6957). The listener answers meanwhile; a signal now stops what is up. |
src/trace/index_table.ts added +310
| @@ -0,0 +1,310 @@ | ||
| 1 | /** | |
| 2 | * The trace index (#18020): one row per ended crew run or Talk turn, written when it ends and, for | |
| 3 | * the ones that ended before this existed, by a one-time backfill in small batches that yield. A | |
| 4 | * row is figures and a title read from the raw record (`parseRunLog`, `totalsOf`); the log stays | |
| 5 | * the only record of what happened. The list is read through a gated route in a later slice, never | |
| 6 | * here: `listTraceIndex` knows nothing of who may see a row. | |
| 7 | * | |
| 8 | * A run log holds no tokens, so a row's tokens and cost are the ones the run recorded (`run`, | |
| 9 | * `conversation_run`), the same the run page states; its step and failed-step counts are | |
| 10 | * `totalsOf` of the parsed log, the same the trace page counts. A Talk turn's log is a run log. | |
| 11 | */ | |
| 12 | import type { Database } from "bun:sqlite"; | |
| 13 | import { getIssueById } from "../core/issues.ts"; | |
| 14 | import { getRun, isTerminal } from "../core/runs.ts"; | |
| 15 | import { readRunLog, readRunTimes } from "../runs/log.ts"; | |
| 16 | import { totalsOf } from "./model.ts"; | |
| 17 | import { parseRunLog } from "./run_log.ts"; | |
| 18 | ||
| 19 | export type TraceKind = "run" | "talk" | "review"; | |
| 20 | ||
| 21 | export interface TraceRow { | |
| 22 | readonly id: string; | |
| 23 | readonly kind: TraceKind; | |
| 24 | /** The repository's id; empty for a Talk turn. */ | |
| 25 | readonly repository: string; | |
| 26 | readonly title: string; | |
| 27 | readonly model: string; | |
| 28 | /** The subscription the work was paid from; empty when none was picked. */ | |
| 29 | readonly account: string; | |
| 30 | readonly steps: number; | |
| 31 | readonly errors: number; | |
| 32 | readonly tokensIn: number; | |
| 33 | readonly tokensCached: number; | |
| 34 | readonly tokensOut: number; | |
| 35 | /** US dollars. */ | |
| 36 | readonly costUsd: number; | |
| 37 | /** `ok`, `failed`, `cancelled` or `stopped`: the state the work ended in. */ | |
| 38 | readonly outcome: string; | |
| 39 | /** ISO 8601 UTC. */ | |
| 40 | readonly started: string; | |
| 41 | readonly ended: string; | |
| 42 | } | |
| 43 | ||
| 44 | interface Raw { | |
| 45 | id: string; | |
| 46 | kind: TraceKind; | |
| 47 | repository: string; | |
| 48 | title: string; | |
| 49 | model: string; | |
| 50 | account: string; | |
| 51 | tokensIn: number; | |
| 52 | tokensOut: number; | |
| 53 | costUsd: number; | |
| 54 | outcome: string; | |
| 55 | started: string; | |
| 56 | ended: string; | |
| 57 | } | |
| 58 | ||
| 59 | const TITLE_MAX = 120; | |
| 60 | const clip = (text: string): string => { | |
| 61 | const one = text.replace(/\s+/g, " ").trim(); | |
| 62 | return one.length > TITLE_MAX ? `${one.slice(0, TITLE_MAX - 1)}…` : one; | |
| 63 | }; | |
| 64 | ||
| 65 | /** | |
| 66 | * The figures of the parsed log laid beside what the work recorded, and written (replacing a row). | |
| 67 | */ | |
| 68 | function write(db: Database, dataDir: string, raw: Raw): void { | |
| 69 | const { lines } = readRunLog(dataDir, raw.id); | |
| 70 | const { trace } = parseRunLog(raw.id, raw.title, lines, readRunTimes(dataDir, raw.id, lines.length)); | |
| 71 | const t = totalsOf(trace); | |
| 72 | db.query( | |
| 73 | `INSERT OR REPLACE INTO trace_index | |
| 74 | (id, kind, repository, title, model, account, steps, errors, tokens_in, tokens_cached, tokens_out, cost_usd, outcome, started, ended) | |
| 75 | VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15)`, | |
| 76 | ).run( | |
| 77 | raw.id, | |
| 78 | raw.kind, | |
| 79 | raw.repository, | |
| 80 | clip(raw.title), | |
| 81 | raw.model.slice(0, 100), | |
| 82 | raw.account, | |
| 83 | t.steps, | |
| 84 | t.errors, | |
| 85 | Math.max(t.tokensIn, raw.tokensIn), | |
| 86 | t.tokensCached, | |
| 87 | Math.max(t.tokensOut, raw.tokensOut), | |
| 88 | raw.costUsd, | |
| 89 | raw.outcome, | |
| 90 | raw.started, | |
| 91 | raw.ended, | |
| 92 | ); | |
| 93 | } | |
| 94 | ||
| 95 | /** Index a crew run that has ended; false for a run that is not an agent run or has not ended. */ | |
| 96 | export function indexRun(db: Database, dataDir: string, runId: string): boolean { | |
| 97 | const run = getRun(db, runId); | |
| 98 | if (run === undefined || run.kind !== "agent" || !isTerminal(run.state)) return false; | |
| 99 | const issue = run.issueId === null ? undefined : getIssueById(db, run.issueId); | |
| 100 | const account = db.query<{ subscription_id: string | null }, [string]>("SELECT subscription_id FROM run WHERE id = ?1").get(runId)?.subscription_id ?? ""; | |
| 101 | const started = run.startedAt ?? run.createdAt; | |
| 102 | write(db, dataDir, { | |
| 103 | id: run.id, | |
| 104 | kind: "run", | |
| 105 | repository: run.repoId, | |
| 106 | // The title the trace page gives it (`readTrace`). | |
| 107 | title: issue?.title ?? (run.summary === "" ? `${run.kind} run` : run.summary), | |
| 108 | model: run.model, | |
| 109 | account, | |
| 110 | tokensIn: run.tokensIn ?? 0, | |
| 111 | tokensOut: run.tokensOut ?? 0, | |
| 112 | costUsd: run.costUsd, | |
| 113 | outcome: run.state, | |
| 114 | started, | |
| 115 | ended: run.finishedAt ?? started, | |
| 116 | }); | |
| 117 | return true; | |
| 118 | } | |
| 119 | ||
| 120 | interface TalkRun { | |
| 121 | id: string; | |
| 122 | state: string; | |
| 123 | subscription_id: string | null; | |
| 124 | prompt: string; | |
| 125 | tokens_in: number; | |
| 126 | tokens_out: number; | |
| 127 | cost_usd: number; | |
| 128 | started_at: string; | |
| 129 | finished_at: string | null; | |
| 130 | model: string; | |
| 131 | } | |
| 132 | ||
| 133 | /** Index a Talk turn that has ended (`conversation_run`); false while it is still running. */ | |
| 134 | export function indexTalkTurn(db: Database, dataDir: string, runId: string): boolean { | |
| 135 | const row = db | |
| 136 | .query<TalkRun, [string]>( | |
| 137 | "SELECT id, state, subscription_id, prompt, tokens_in, tokens_out, cost_usd, started_at, finished_at, model FROM conversation_run WHERE id = ?1", | |
| 138 | ) | |
| 139 | .get(runId); | |
| 140 | if (row === null || row.state === "running") return false; | |
| 141 | write(db, dataDir, { | |
| 142 | id: row.id, | |
| 143 | kind: "talk", | |
| 144 | repository: "", | |
| 145 | title: row.prompt, | |
| 146 | model: row.model, | |
| 147 | account: row.subscription_id ?? "", | |
| 148 | tokensIn: row.tokens_in, | |
| 149 | tokensOut: row.tokens_out, | |
| 150 | costUsd: row.cost_usd, | |
| 151 | outcome: row.state, | |
| 152 | started: row.started_at, | |
| 153 | ended: row.finished_at ?? row.started_at, | |
| 154 | }); | |
| 155 | return true; | |
| 156 | } | |
| 157 | ||
| 158 | /** | |
| 159 | * Rows read between two yields: a log read each, so a batch is a few milliseconds of the thread. | |
| 160 | */ | |
| 161 | export const BACKFILL_BATCH = 25; | |
| 162 | ||
| 163 | const SOURCES = { | |
| 164 | run: { ids: "SELECT id FROM run WHERE kind = 'agent' AND state IN ('ok','failed','cancelled') AND id > ?1 AND id NOT IN (SELECT id FROM trace_index) ORDER BY id LIMIT ?2", index: indexRun }, | |
| 165 | talk: { ids: "SELECT id FROM conversation_run WHERE state <> 'running' AND id > ?1 AND id NOT IN (SELECT id FROM trace_index) ORDER BY id LIMIT ?2", index: indexTalkTurn }, | |
| 166 | } as const; | |
| 167 | ||
| 168 | const yieldThread = (): Promise<void> => new Promise((resolve) => setImmediate(resolve)); | |
| 169 | ||
| 170 | /** | |
| 171 | * Index the runs and Talk turns that ended before the index existed, once: `batch` rows at a time | |
| 172 | * in one transaction, the place reached stored with it (`trace_index_backfill`), then a yield so | |
| 173 | * requests are answered between batches. Done sources are skipped on the next boot. Returns how | |
| 174 | * many rows it wrote. | |
| 175 | */ | |
| 176 | export async function backfillTraceIndex( | |
| 177 | db: Database, | |
| 178 | dataDir: string, | |
| 179 | options: { batch?: number; yieldNow?: () => Promise<void> } = {}, | |
| 180 | ): Promise<number> { | |
| 181 | const batch = options.batch ?? BACKFILL_BATCH; | |
| 182 | const pause = options.yieldNow ?? yieldThread; | |
| 183 | let written = 0; | |
| 184 | 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)!; | |
| 187 | if (state.done_at !== null) continue; | |
| 188 | let after = state.after; | |
| 189 | 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; | |
| 199 | } | |
| 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; | |
| 207 | await pause(); | |
| 208 | } | |
| 209 | } | |
| 210 | return written; | |
| 211 | } | |
| 212 | ||
| 213 | export interface TraceQuery { | |
| 214 | repository?: string | undefined; | |
| 215 | kind?: TraceKind | undefined; | |
| 216 | model?: string | undefined; | |
| 217 | outcome?: string | undefined; | |
| 218 | /** Started at or after this ISO instant. */ | |
| 219 | since?: string | undefined; | |
| 220 | /** Started before this ISO instant. */ | |
| 221 | until?: string | undefined; | |
| 222 | /** What `next` of the last page said. */ | |
| 223 | cursor?: string | undefined; | |
| 224 | limit?: number | undefined; | |
| 225 | } | |
| 226 | ||
| 227 | export interface TracePage { | |
| 228 | readonly rows: TraceRow[]; | |
| 229 | /** Pass as `cursor` for the next page; undefined on the last. */ | |
| 230 | readonly next: string | undefined; | |
| 231 | } | |
| 232 | ||
| 233 | export const DEFAULT_LIMIT = 50; | |
| 234 | export const MAX_LIMIT = 200; | |
| 235 | ||
| 236 | /** `<started>|<id>`: where the last row of a page was; anything else is no cursor. */ | |
| 237 | const CURSOR = /^(\d{4}-\d\d-\d\dT[0-9:.]{8,12}Z)\|([0-9a-z]{1,40})$/; | |
| 238 | ||
| 239 | interface Stored { | |
| 240 | id: string; | |
| 241 | kind: TraceKind; | |
| 242 | repository: string; | |
| 243 | title: string; | |
| 244 | model: string; | |
| 245 | account: string; | |
| 246 | steps: number; | |
| 247 | errors: number; | |
| 248 | tokens_in: number; | |
| 249 | tokens_cached: number; | |
| 250 | tokens_out: number; | |
| 251 | cost_usd: number; | |
| 252 | outcome: string; | |
| 253 | started: string; | |
| 254 | ended: string; | |
| 255 | } | |
| 256 | ||
| 257 | /** | |
| 258 | * The index newest first (started, then id), a page at a time. Every filter is a bound parameter; | |
| 259 | * a malformed cursor is ignored (the first page). Who may see a row is the caller's to decide. | |
| 260 | */ | |
| 261 | export function listTraceIndex(db: Database, query: TraceQuery = {}): TracePage { | |
| 262 | const limit = Math.min(MAX_LIMIT, Math.max(1, Math.trunc(query.limit ?? DEFAULT_LIMIT) || DEFAULT_LIMIT)); | |
| 263 | const where: string[] = []; | |
| 264 | const args: (string | number)[] = []; | |
| 265 | const add = (clause: string, value: string | undefined): void => { | |
| 266 | if (value === undefined) return; | |
| 267 | args.push(value); | |
| 268 | where.push(clause.replace("?", `?${args.length}`)); | |
| 269 | }; | |
| 270 | add("repository = ?", query.repository); | |
| 271 | add("kind = ?", query.kind); | |
| 272 | add("model = ?", query.model); | |
| 273 | add("outcome = ?", query.outcome); | |
| 274 | add("started >= ?", query.since); | |
| 275 | add("started < ?", query.until); | |
| 276 | const at = query.cursor === undefined ? null : CURSOR.exec(query.cursor); | |
| 277 | if (at !== null) { | |
| 278 | args.push(at[1]!, at[2]!); | |
| 279 | where.push(`(started < ?${args.length - 1} OR (started = ?${args.length - 1} AND id < ?${args.length}))`); | |
| 280 | } | |
| 281 | args.push(limit + 1); | |
| 282 | const rows = db | |
| 283 | .query<Stored, (string | number)[]>( | |
| 284 | `SELECT * FROM trace_index ${where.length === 0 ? "" : `WHERE ${where.join(" AND ")}`} ORDER BY started DESC, id DESC LIMIT ?${args.length}`, | |
| 285 | ) | |
| 286 | .all(...args); | |
| 287 | const more = rows.length > limit; | |
| 288 | const page = rows.slice(0, limit); | |
| 289 | const last = page[page.length - 1]; | |
| 290 | return { | |
| 291 | rows: page.map((r) => ({ | |
| 292 | id: r.id, | |
| 293 | kind: r.kind, | |
| 294 | repository: r.repository, | |
| 295 | title: r.title, | |
| 296 | model: r.model, | |
| 297 | account: r.account, | |
| 298 | steps: r.steps, | |
| 299 | errors: r.errors, | |
| 300 | tokensIn: r.tokens_in, | |
| 301 | tokensCached: r.tokens_cached, | |
| 302 | tokensOut: r.tokens_out, | |
| 303 | costUsd: r.cost_usd, | |
| 304 | outcome: r.outcome, | |
| 305 | started: r.started, | |
| 306 | ended: r.ended, | |
| 307 | })), | |
| 308 | next: more && last !== undefined ? `${last.started}|${last.id}` : undefined, | |
| 309 | }; | |
| 310 | } |
test/trace-index.test.ts added +194
| @@ -0,0 +1,194 @@ | ||
| 1 | /** | |
| 2 | * The trace index (#18020): rows written as a run or a Talk turn ends, a bounded backfill, a | |
| 3 | * listing. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { announceRun } from "../src/actions/runs.ts"; | |
| 11 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 12 | import { newConversation } from "../src/core/conversations.ts"; | |
| 13 | import { claimRun, createRun, finishRun, getRun, noteRunProgress } from "../src/core/runs.ts"; | |
| 14 | import type { Repo } from "../src/core/repos.ts"; | |
| 15 | import type { User } from "../src/core/users.ts"; | |
| 16 | import { appendRunLog, flushRunLogs } from "../src/runs/log.ts"; | |
| 17 | import { readTrace } from "../src/trace/read.ts"; | |
| 18 | import { stepsOf, totalsOf } from "../src/trace/model.ts"; | |
| 19 | import { backfillTraceIndex, indexRun, indexTalkTurn, listTraceIndex } from "../src/trace/index_table.ts"; | |
| 20 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 21 | ||
| 22 | let dir = ""; | |
| 23 | let app: App; | |
| 24 | let alice: User; | |
| 25 | let repo: Repo; | |
| 26 | ||
| 27 | const LOG = ["I will read the README first.", "→ Read README.md", "Now the footer.", "→ Edit footer.txt", "→ Bash bun test", "! exit 1", "Done."]; | |
| 28 | ||
| 29 | beforeAll(async () => { | |
| 30 | dir = await mkdtemp(join(tmpdir(), "forge-trace-index-")); | |
| 31 | app = createApp({ dataDir: dir, port: 0 }); | |
| 32 | const admin = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" }); | |
| 33 | if (!admin.ok) throw new Error(admin.error); | |
| 34 | alice = admin.value; | |
| 35 | const made = await createRepo(app, alice, { name: "notes", visibility: "public", description: "" }); | |
| 36 | if (!made.ok) throw new Error(String(made.error)); | |
| 37 | repo = made.value; | |
| 38 | const seeded = await commitToBranch(app, alice, repo, { message: "Start", files: [{ path: "README.md", content: "# notes\n" }] }); | |
| 39 | if (!seeded.ok) throw new Error(JSON.stringify(seeded.error)); | |
| 40 | }, 30_000); | |
| 41 | ||
| 42 | afterAll(async () => { | |
| 43 | app.close(); | |
| 44 | await rm(dir, { recursive: true, force: true }); | |
| 45 | }); | |
| 46 | ||
| 47 | test("a run that ends is indexed with the steps, failures and cost its trace page shows", async () => { | |
| 48 | const run = createRun(app.db, { repoId: repo.id, kind: "agent", actorId: alice.id }); | |
| 49 | for (const line of LOG) appendRunLog(dir, run.id, line); | |
| 50 | flushRunLogs(); | |
| 51 | noteRunProgress(app.db, run.id, { costUsd: 1.25, model: "claude-opus-5-5", subscriptionId: "platform" }); | |
| 52 | expect(listTraceIndex(app.db).rows).toEqual([]); // nothing before it ends | |
| 53 | claimRun(app.db, run.id); | |
| 54 | finishRun(app.db, run.id, { state: "ok", summary: "opened a pull", tokensIn: 1200, tokensOut: 340 }); | |
| 55 | const ended = getRun(app.db, run.id)!; | |
| 56 | announceRun(app, ended); | |
| 57 | ||
| 58 | const row = listTraceIndex(app.db).rows[0]!; | |
| 59 | const view = (await readTrace(app, alice, repo, run.id))!; | |
| 60 | const totals = totalsOf(view.trace); | |
| 61 | expect(stepsOf(view.trace).length).toBe(7); // hand count: 3 texts, Read, Edit, Bash, the failure | |
| 62 | expect(row).toMatchObject({ | |
| 63 | id: run.id, | |
| 64 | kind: "run", | |
| 65 | repository: repo.id, | |
| 66 | title: "opened a pull", | |
| 67 | model: "claude-opus-5-5", | |
| 68 | account: "platform", | |
| 69 | steps: totals.steps, | |
| 70 | errors: 1, | |
| 71 | tokensIn: 1200, | |
| 72 | tokensCached: 0, | |
| 73 | tokensOut: 340, | |
| 74 | costUsd: view.costUsd!, | |
| 75 | outcome: "ok", | |
| 76 | }); | |
| 77 | expect(row.costUsd).toBe(1.25); | |
| 78 | expect(row.started <= row.ended).toBe(true); | |
| 79 | }); | |
| 80 | ||
| 81 | test("a deploy run, and a run still going, are not indexed", () => { | |
| 82 | const deploy = createRun(app.db, { repoId: repo.id, kind: "deploy" }); | |
| 83 | claimRun(app.db, deploy.id); | |
| 84 | finishRun(app.db, deploy.id, { state: "ok", summary: "" }); | |
| 85 | const going = createRun(app.db, { repoId: repo.id, kind: "agent" }); | |
| 86 | expect(indexRun(app.db, dir, deploy.id)).toBe(false); | |
| 87 | expect(indexRun(app.db, dir, going.id)).toBe(false); | |
| 88 | expect(indexRun(app.db, dir, "nope")).toBe(false); | |
| 89 | expect(getRun(app.db, going.id)?.state).toBe("queued"); | |
| 90 | expect(listTraceIndex(app.db, { kind: "run" }).rows.map((r) => r.id)).not.toContain(deploy.id); | |
| 91 | }); | |
| 92 | ||
| 93 | test("a Talk turn is indexed from its record with its own figures", () => { | |
| 94 | const conversation = newConversation(app.db, alice.id); | |
| 95 | const turn = (id: string, state: string, finished: string | null): void => { | |
| 96 | app.db | |
| 97 | .query( | |
| 98 | "INSERT INTO conversation_run (id, conversation_id, user_id, state, prompt, tokens_in, tokens_out, cost_usd, started_at, finished_at, model, subscription_id) VALUES (?1,?2,?3,?4,'what changed today?',900,150,0.4,'2026-12-04T10:00:00.000Z',?5,'claude-sonnet-5-5','sub1')", | |
| 99 | ) | |
| 100 | .run(id, conversation.id, alice.id, state, finished); | |
| 101 | }; | |
| 102 | turn("talkrunning", "running", null); | |
| 103 | for (const line of ["Let me look.", "→ forge_issues list", "→ forge_runs list", "There are two."]) appendRunLog(dir, "talkdone", line); | |
| 104 | turn("talkdone", "ok", "2026-12-04T10:00:09.000Z"); | |
| 105 | flushRunLogs(); | |
| 106 | expect(indexTalkTurn(app.db, dir, "talkrunning")).toBe(false); | |
| 107 | expect(indexTalkTurn(app.db, dir, "talkdone")).toBe(true); | |
| 108 | const row = listTraceIndex(app.db, { kind: "talk" }).rows[0]!; | |
| 109 | expect(row).toMatchObject({ | |
| 110 | id: "talkdone", | |
| 111 | kind: "talk", | |
| 112 | repository: "", | |
| 113 | title: "what changed today?", | |
| 114 | model: "claude-sonnet-5-5", | |
| 115 | account: "sub1", | |
| 116 | steps: 4, // hand count: text, two calls, text | |
| 117 | errors: 0, | |
| 118 | tokensIn: 900, | |
| 119 | tokensOut: 150, | |
| 120 | costUsd: 0.4, | |
| 121 | outcome: "ok", | |
| 122 | started: "2026-12-04T10:00:00.000Z", | |
| 123 | ended: "2026-12-04T10:00:09.000Z", | |
| 124 | }); | |
| 125 | }); | |
| 126 | ||
| 127 | test("the list is newest first, filtered, and pages by a cursor", () => { | |
| 128 | const put = (id: string, kind: string, model: string, outcome: string, started: string, repository = "r1"): void => { | |
| 129 | app.db | |
| 130 | .query("INSERT INTO trace_index (id, kind, repository, model, outcome, started, ended) VALUES (?1,?2,?3,?4,?5,?6,?6)") | |
| 131 | .run(id, kind, repository, model, outcome, started); | |
| 132 | }; | |
| 133 | put("pg1", "run", "m-a", "ok", "2030-01-01T00:00:01.000Z"); | |
| 134 | put("pg2", "run", "m-b", "failed", "2030-01-01T00:00:02.000Z"); | |
| 135 | put("pg3", "talk", "m-a", "ok", "2030-01-01T00:00:03.000Z", ""); | |
| 136 | put("pg4", "run", "m-a", "ok", "2030-01-01T00:00:03.000Z"); | |
| 137 | put("pg5", "run", "m-a", "ok", "2030-01-01T00:00:05.000Z"); | |
| 138 | const ids = (q: Parameters<typeof listTraceIndex>[1]): string[] => listTraceIndex(app.db, { since: "2030-01-01T00:00:00.000Z", ...q }).rows.map((r) => r.id); | |
| 139 | expect(ids({})).toEqual(["pg5", "pg4", "pg3", "pg2", "pg1"]); // ties on time break by id, newest first | |
| 140 | expect(ids({ repository: "r1" })).toEqual(["pg5", "pg4", "pg2", "pg1"]); | |
| 141 | expect(ids({ kind: "talk" })).toEqual(["pg3"]); | |
| 142 | expect(ids({ model: "m-a", outcome: "ok" })).toEqual(["pg5", "pg4", "pg3", "pg1"]); | |
| 143 | expect(ids({ outcome: "failed" })).toEqual(["pg2"]); | |
| 144 | expect(ids({ until: "2030-01-01T00:00:03.000Z" })).toEqual(["pg2", "pg1"]); | |
| 145 | const first = listTraceIndex(app.db, { since: "2030-01-01T00:00:00.000Z", limit: 2 }); | |
| 146 | expect(first.rows.map((r) => r.id)).toEqual(["pg5", "pg4"]); | |
| 147 | const second = listTraceIndex(app.db, { since: "2030-01-01T00:00:00.000Z", limit: 2, cursor: first.next }); | |
| 148 | expect(second.rows.map((r) => r.id)).toEqual(["pg3", "pg2"]); | |
| 149 | const third = listTraceIndex(app.db, { since: "2030-01-01T00:00:00.000Z", limit: 2, cursor: second.next }); | |
| 150 | expect(third.rows.map((r) => r.id)).toEqual(["pg1"]); | |
| 151 | expect(third.next).toBeUndefined(); | |
| 152 | // A cursor that is not one is the first page, never an error or an injection. | |
| 153 | expect(listTraceIndex(app.db, { since: "2030-01-01T00:00:00.000Z", limit: 1, cursor: "x' OR 1=1 --" }).rows.map((r) => r.id)).toEqual(["pg5"]); | |
| 154 | }); | |
| 155 | ||
| 156 | test("the backfill of 10,000 runs never runs longer than one batch between yields, and a page lists from the index", async () => { | |
| 157 | const before = (app.db.query("SELECT COUNT(*) AS n FROM trace_index").get() as { n: number }).n; | |
| 158 | app.db.transaction(() => { | |
| 159 | const insert = app.db.query( | |
| 160 | "INSERT INTO run (id, repo_id, kind, state, summary, cost_usd, created_at, started_at, finished_at) VALUES (?1,?2,'agent','ok','old run',0.01,?3,?3,?3)", | |
| 161 | ); | |
| 162 | for (let i = 0; i < 10_000; i++) insert.run(`bf${String(i).padStart(6, "0")}`, repo.id, new Date(Date.UTC(2026, 0, 1) + i * 1000).toISOString()); | |
| 163 | })(); | |
| 164 | const count = (): number => (app.db.query("SELECT COUNT(*) AS n FROM trace_index").get() as { n: number }).n; | |
| 165 | const gaps: number[] = []; | |
| 166 | let last = count(); | |
| 167 | const written = await backfillTraceIndex(app.db, dir, { | |
| 168 | yieldNow: async () => { | |
| 169 | gaps.push(count() - last); | |
| 170 | last = count(); | |
| 171 | }, | |
| 172 | }); | |
| 173 | gaps.push(count() - last); | |
| 174 | expect(written).toBe(10_000); | |
| 175 | expect(count() - before).toBe(10_000); | |
| 176 | expect(Math.max(...gaps)).toBeLessThanOrEqual(25); // BACKFILL_BATCH | |
| 177 | expect(gaps.length).toBeGreaterThanOrEqual(400); | |
| 178 | const page = listTraceIndex(app.db, { repository: repo.id, limit: 50 }); | |
| 179 | expect(page.rows.length).toBe(50); | |
| 180 | expect(page.next).toBeDefined(); | |
| 181 | // Once only: the second call finds both sources done. | |
| 182 | expect(await backfillTraceIndex(app.db, dir, { yieldNow: async () => {} })).toBe(0); | |
| 183 | }, 60_000); | |
| 184 | ||
| 185 | test("the list reads through an index, never a scan or a sort", () => { | |
| 186 | const plan = (sql: string, ...args: null[]): string => | |
| 187 | (app.db.query(`EXPLAIN QUERY PLAN ${sql}`).all(...args) as { detail: string }[]).map((r) => r.detail).join("\n"); | |
| 188 | const recent = plan("SELECT * FROM trace_index ORDER BY started DESC, id DESC LIMIT 51"); | |
| 189 | expect(recent).toContain("trace_index_recent"); | |
| 190 | expect(recent).not.toContain("TEMP B-TREE"); | |
| 191 | const byRepo = plan("SELECT * FROM trace_index WHERE repository = ?1 ORDER BY started DESC, id DESC LIMIT 51", null); | |
| 192 | expect(byRepo).toContain("trace_index_by_repository"); | |
| 193 | expect(byRepo).not.toContain("TEMP B-TREE"); | |
| 194 | }); |
new above
offline