Public: anyone can read this; the crew can change it.
Traces 1c: GET /api/v1/traces/:id returns the thread, turns and steps as one tree #18128
Merged 8h 43m ago, live in production
scout/forge:scout/18022-traces-1c-get-api-v1-traces-id-returns-t → main 0 commits fork
9 files
changed +173
−1
docs/features/traces.md +4
| @@ -29,3 +29,7 @@ The file is read whole, then parsed, so the 256 MB limit is memory-bound: a sess | ||
| 29 | 29 | ## Listing traces (#18021) |
| 30 | 30 | |
| 31 | 31 | `GET /api/v1/traces` lists the trace index newest first as `{items, next_cursor}`: filters `repository` (an id or `owner/name`), `kind` (run, talk), `model`, `outcome` (ok, failed, cancelled, stopped), `since` and `until` (a date or an ISO instant with a zone); `limit` 1 to 200 (default 50) and `cursor`. A run is listed only to someone who may read its log (the rule the run page uses), a Talk turn to its person alone; any other row is absent, never a hint. Only the index is read, never a log. A bad filter value is a 400 (`invalid_since`, …); a bad limit or cursor, or an unknown parameter, a 422. Code: `src/http/api/traces.ts` over `listTraceIndex`. |
| 32 | ||
| 33 | ## One trace as a tree (#18022) | |
| 34 | ||
| 35 | `GET /api/v1/traces/:id` answers the thread, its turns and their steps as one tree, rebuilt from the raw log with `parseRunLog` (a Talk turn's log is a run log): the thread's figures are the list's row (model, account, tokens in, cached and out, cost, outcome, started, ended, steps, errors), each step has its start and end in ms, kind, name, line, model, tokens and outcome (a run log holds no tokens per step, so those are 0). `timed` is false where the log kept no times. `truncated` is true when the log's start was cut (it is read from its last 512 KB) or it holds more than `MAX_STEPS` (20,000) steps. A trace the caller may not see answers exactly as an unknown id: 404 `not_found`. The tree is answered whole (about 15 ms for 5,000 steps). Code: `readTraceTree` in `src/http/api/traces.ts`. |
src/contract/openapi/routes/getApiV1TracesId.ts added +21
| @@ -0,0 +1,21 @@ | ||
| 1 | import { bool, int, list, num, obj, str } from "../schema_kit.ts"; | |
| 2 | import type { Route } from "../shared.ts"; | |
| 3 | ||
| 4 | const step = obj({ id: str, kind: str, name: str, line: str, startMs: num, endMs: num, model: str, tokensIn: int, tokensCached: int, tokensOut: int, outcome: str }); | |
| 5 | ||
| 6 | export const route: Route = { | |
| 7 | method: "get", | |
| 8 | path: "/api/v1/traces/{id}", | |
| 9 | summary: "Read one trace as a tree: the thread, its turns and their steps", | |
| 10 | detail: | |
| 11 | "Read one trace (a run's or a Talk turn's id, as the list gives it) rebuilt from its raw log: { id, kind, repository, title, model, account, tokensIn, tokensCached, tokensOut, costUsd, outcome, started, ended, steps, errors, timed, truncated, turns: [{ index, prompt, startMs, steps: [{ id, kind (model, tool, subagent), name, line, startMs, endMs, model, tokensIn, tokensCached, tokensOut, outcome (ok, error, unknown) }] }] }. The figures of the thread are the list's; a run log holds none per step. timed is false where the log kept no times (a step's start and end are then 0); truncated is true when the log's start was cut (it is read from its last 512 KB) or it holds more steps than are read (20,000), never silently cut. A trace the caller may not see (a run whose log they may not read, another person's Talk turn) answers exactly as an unknown id does: 404 not_found", | |
| 12 | auth: true, | |
| 13 | role: "member", | |
| 14 | response: obj({ | |
| 15 | id: str, kind: str, repository: str, title: str, model: str, account: str, | |
| 16 | tokensIn: int, tokensCached: int, tokensOut: int, costUsd: num, outcome: str, started: str, ended: str, | |
| 17 | steps: int, errors: int, timed: bool, truncated: bool, | |
| 18 | turns: list(obj({ index: int, prompt: str, startMs: num, steps: list(step) })), | |
| 19 | }), | |
| 20 | refuses: [401, 404], | |
| 21 | }; |
src/contract/openapi/routes/index.ts +1
| @@ -267,6 +267,7 @@ export { route as getApiV1TelemetrySystem } from "./getApiV1TelemetrySystem.ts"; | ||
| 267 | 267 | export { route as getApiV1Templates } from "./getApiV1Templates.ts"; |
| 268 | 268 | export { route as getApiV1Tokens } from "./getApiV1Tokens.ts"; |
| 269 | 269 | export { route as getApiV1Traces } from "./getApiV1Traces.ts"; |
| 270 | export { route as getApiV1TracesId } from "./getApiV1TracesId.ts"; | |
| 270 | 271 | export { route as getApiV1Usage } from "./getApiV1Usage.ts"; |
| 271 | 272 | export { route as getApiV1User } from "./getApiV1User.ts"; |
| 272 | 273 | export { route as getApiV1UserAssigned } from "./getApiV1UserAssigned.ts"; |
src/http/api/traces.ts +55 −1
| @@ -12,7 +12,9 @@ import type { App } from "../../app.ts"; | ||
| 12 | 12 | import { getRepo, getRepoById, type Repo } from "../../core/repos.ts"; |
| 13 | 13 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; |
| 14 | 14 | import type { User } from "../../core/users.ts"; |
| 15 | import { cursorOf, DEFAULT_LIMIT, listTraceIndex, MAX_LIMIT, TRACE_CURSOR, type TraceKind, type TraceQuery, type TraceRow } from "../../trace/index_table.ts"; | |
| 15 | import { readRunLog, readRunTimes } from "../../runs/log.ts"; | |
| 16 | import { MAX_STEPS, parseRunLog } from "../../trace/run_log.ts"; | |
| 17 | import { cursorOf, DEFAULT_LIMIT, getTraceRow, listTraceIndex, MAX_LIMIT, TRACE_CURSOR, type TraceKind, type TraceQuery, type TraceRow } from "../../trace/index_table.ts"; | |
| 16 | 18 | import type { Handler } from "../context.ts"; |
| 17 | 19 | import { apiError, json, requireScope } from "../respond.ts"; |
| 18 | 20 | import type { Router } from "../router.ts"; |
| @@ -126,6 +128,58 @@ export const listTraces: Handler = (ctx) => { | ||
| 126 | 128 | }); |
| 127 | 129 | }; |
| 128 | 130 | |
| 131 | /** The ids a trace has: a run's or a Talk turn's, never more than this many characters. */ | |
| 132 | const TRACE_ID = /^[0-9a-z]{1,40}$/; | |
| 133 | ||
| 134 | /** | |
| 135 | * GET /api/v1/traces/:id (#18022): the thread, its turns and their steps as one tree, rebuilt from | |
| 136 | * the raw log with `parseRunLog` (a Talk turn's log is a run log). A trace the caller may not see | |
| 137 | * answers as one that does not exist. A log past `MAX_STEPS` steps, or cut at its start, says | |
| 138 | * `truncated`. | |
| 139 | */ | |
| 140 | export const readTraceTree: Handler = (ctx) => { | |
| 141 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 142 | const denied = requireScope(ctx, "ro"); | |
| 143 | if (denied) return denied; | |
| 144 | const id = ctx.params.id ?? ""; | |
| 145 | const row = TRACE_ID.test(id) ? getTraceRow(ctx.app.db, id) : undefined; | |
| 146 | if (row === undefined || !seeing(ctx.app, ctx.auth.user!)(row)) return apiError("not_found", 404, "no such trace"); | |
| 147 | let body: object = {}; | |
| 148 | timePhase(ctx.request, "traces", () => { | |
| 149 | const dataDir = ctx.app.config.dataDir; | |
| 150 | const { lines, truncated } = readRunLog(dataDir, row.id); | |
| 151 | const { trace, timed } = parseRunLog(row.id, row.title, lines, readRunTimes(dataDir, row.id, lines.length)); | |
| 152 | const steps = trace.turns.reduce((n, t) => n + t.steps.length, 0); | |
| 153 | body = { | |
| 154 | id: row.id, | |
| 155 | kind: row.kind, | |
| 156 | repository: row.repository, | |
| 157 | title: row.title, | |
| 158 | model: row.model, | |
| 159 | account: row.account, | |
| 160 | tokensIn: row.tokensIn, | |
| 161 | tokensCached: row.tokensCached, | |
| 162 | tokensOut: row.tokensOut, | |
| 163 | costUsd: row.costUsd, | |
| 164 | outcome: row.outcome, | |
| 165 | started: row.started, | |
| 166 | ended: row.ended, | |
| 167 | steps, | |
| 168 | errors: row.errors, | |
| 169 | timed, | |
| 170 | truncated: truncated || steps >= MAX_STEPS, | |
| 171 | turns: trace.turns.map((t) => ({ | |
| 172 | index: t.index, | |
| 173 | prompt: t.prompt, | |
| 174 | startMs: t.startMs, | |
| 175 | steps: t.steps.map((s) => ({ id: s.id, kind: s.kind, name: s.name, line: s.line, startMs: s.startMs, endMs: s.endMs, model: s.model ?? row.model, tokensIn: s.tokensIn, tokensCached: s.tokensCached, tokensOut: s.tokensOut, outcome: s.outcome })), | |
| 176 | })), | |
| 177 | }; | |
| 178 | }); | |
| 179 | return new Response(JSON.stringify(body), { headers: { "content-type": "application/json", "cache-control": "private, no-store", vary: "authorization, cookie" } }); | |
| 180 | }; | |
| 181 | ||
| 129 | 182 | export function traceRoutes(router: Router<Handler>): void { |
| 183 | router.add("GET", "/api/v1/traces/:id", readTraceTree); | |
| 130 | 184 | router.add("GET", "/api/v1/traces", listTraces); |
| 131 | 185 | } |
src/http/lazy_lists.ts +1
| @@ -1487,6 +1487,7 @@ export const API_ROUTES = [ | ||
| 1487 | 1487 | ["GET", "/api/v1/models"], |
| 1488 | 1488 | ["POST", "/api/v1/conversations"], |
| 1489 | 1489 | ["PATCH", "/api/v1/conversations/:id"], |
| 1490 | ["GET", "/api/v1/traces/:id"], | |
| 1490 | 1491 | ["GET", "/api/v1/traces"], |
| 1491 | 1492 | ["POST", "/api/v1/builds"], |
| 1492 | 1493 | ["GET", "/api/v1/conversations/:id/build"], |
src/trace/index_table.ts +6
| @@ -291,6 +291,12 @@ interface Stored { | ||
| 291 | 291 | ended: string; |
| 292 | 292 | } |
| 293 | 293 | |
| 294 | /** One row of the index by its id, or undefined where none was written. */ | |
| 295 | export function getTraceRow(db: Database, id: string): TraceRow | undefined { | |
| 296 | const r = db.query<Stored, [string]>("SELECT * FROM trace_index WHERE id = ?1").get(id); | |
| 297 | return r === null ? undefined : { id: r.id, kind: r.kind, repository: r.repository, title: r.title, model: r.model, account: r.account, steps: r.steps, errors: r.errors, tokensIn: r.tokens_in, tokensCached: r.tokens_cached, tokensOut: r.tokens_out, costUsd: r.cost_usd, outcome: r.outcome, started: r.started, ended: r.ended }; | |
| 298 | } | |
| 299 | ||
| 294 | 300 | /** |
| 295 | 301 | * The index newest first (started, then id), a page at a time. Every filter is a bound parameter; |
| 296 | 302 | * a malformed cursor is ignored (the first page). Who may see a row is the caller's to decide. |
test/budgets/unfixtured/api-v1-traces-id.json added +4
test/security-floor-routes.test.ts +1
| @@ -99,6 +99,7 @@ const UNSEEDED: Record<string, string> = { | ||
| 99 | 99 | "/pricing/orders/:id/receipt.html": "needs an order id the buyer's cookie names; the seed has no order (test/billing-order-receipt.test.ts covers it)", |
| 100 | 100 | "/status/:token": "needs a status token an outsider was handed on filing, which the seed has none of", |
| 101 | 101 | "/api/v1/status/:token": "needs a status token an outsider was handed on filing, which the seed has none of", |
| 102 | "/api/v1/traces/:id": "needs a trace id the seed holds none of", | |
| 102 | 103 | "/talk/:id": TALK, |
| 103 | 104 | "/talk/:id/download": TALK, |
| 104 | 105 | "/docs/:file": "a file name of the documentation folder; the seed supplies no :file", |
test/traces-api.test.ts +80
| @@ -14,6 +14,7 @@ import { claimRun, createRun, finishRun } from "../src/core/runs.ts"; | ||
| 14 | 14 | import { newConversation } from "../src/core/conversations.ts"; |
| 15 | 15 | import { serve, type Servers } from "../src/http/server.ts"; |
| 16 | 16 | import { indexRun, indexTalkTurn } from "../src/trace/index_table.ts"; |
| 17 | import { appendRunLog, flushRunLogs } from "../src/runs/log.ts"; | |
| 17 | 18 | import { seedAdmin } from "./helpers/admin.ts"; |
| 18 | 19 | |
| 19 | 20 | let dir = ""; |
| @@ -135,3 +136,82 @@ test("it answers a signed-in caller only, and names its session phase", async () | ||
| 135 | 136 | const res = await fetch(`${servers.url}/api/v1/traces`, { headers: { authorization: `Bearer ${alice}` } }); |
| 136 | 137 | expect(res.headers.get("server-timing") ?? "").toContain("session"); |
| 137 | 138 | }); |
| 139 | ||
| 140 | // --- GET /api/v1/traces/:id (#18022) --- | |
| 141 | ||
| 142 | const readOne = async (token: string, id: string): Promise<{ status: number; body: any }> => { | |
| 143 | const res = await fetch(`${servers.url}/api/v1/traces/${id}`, { headers: { authorization: `Bearer ${token}` } }); | |
| 144 | return { status: res.status, body: await res.json() }; | |
| 145 | }; | |
| 146 | ||
| 147 | const LOG = ["I will look.", "→ Read a.ts", "→ Edit a.ts +1 −0", "! Bash failed", "Done."]; | |
| 148 | ||
| 149 | test("a run's tree has the steps, tokens and cost the run page and the list give", async () => { | |
| 150 | const run = createRun(app.db, { repoId: notesId, kind: "agent", actorId: (app.db.query("SELECT id FROM user WHERE username='alice'").get() as { id: string }).id }); | |
| 151 | for (const l of LOG) appendRunLog(dir, run.id, l); | |
| 152 | flushRunLogs(); | |
| 153 | claimRun(app.db, run.id); | |
| 154 | finishRun(app.db, run.id, { state: "ok", summary: "a tree", tokensIn: 700, tokensOut: 90 }); | |
| 155 | indexRun(app.db, dir, run.id); | |
| 156 | const { status, body } = await readOne(alice, run.id); | |
| 157 | expect(status).toBe(200); | |
| 158 | const listed = (await get(alice, "?repository=" + notesId)).body.items.find((r: { id: string }) => r.id === run.id); | |
| 159 | const steps = body.turns.flatMap((t: { steps: unknown[] }) => t.steps); | |
| 160 | expect(body.turns.length).toBe(1); | |
| 161 | expect(steps.length).toBe(5); // hand count: text, Read, Edit, the failure, text | |
| 162 | expect(body.steps).toBe(listed.steps); | |
| 163 | expect(body.errors).toBe(1); | |
| 164 | expect(steps.filter((s: { outcome: string }) => s.outcome === "error").length).toBe(1); | |
| 165 | expect(body).toMatchObject({ id: run.id, kind: "run", outcome: "ok", tokensIn: 700, tokensOut: 90, costUsd: listed.costUsd, truncated: false }); | |
| 166 | expect(steps[1]).toMatchObject({ kind: "tool", name: "Read" }); | |
| 167 | }); | |
| 168 | ||
| 169 | test("a Talk turn's tree is its log's, and only its person reads it", async () => { | |
| 170 | appendRunLog(dir, "talk1", "→ Read x"); | |
| 171 | appendRunLog(dir, "talk1", "thinking"); | |
| 172 | flushRunLogs(); | |
| 173 | indexTalkTurn(app.db, dir, "talk1"); | |
| 174 | const mine = await readOne(alice, "talk1"); | |
| 175 | expect(mine.status).toBe(200); | |
| 176 | expect(mine.body.kind).toBe("talk"); | |
| 177 | expect(mine.body.steps).toBe(2); | |
| 178 | expect(mine.body.turns[0].prompt).toBe("hello"); | |
| 179 | }); | |
| 180 | ||
| 181 | test("a hidden id and an unknown id are the same 404", async () => { | |
| 182 | const hidden = await readOne(bob, "talk1"); | |
| 183 | const unknown = await readOne(bob, "nosuchtrace"); | |
| 184 | const bobRun = await readOne(bob, ids[0]!); | |
| 185 | expect(hidden.status).toBe(404); | |
| 186 | expect(hidden).toEqual(unknown); | |
| 187 | expect(bobRun).toEqual(unknown); | |
| 188 | expect((await readOne(alice, "NOT-AN-ID")).status).toBe(404); | |
| 189 | expect((await fetch(`${servers.url}/api/v1/traces/talk1`)).status).toBe(401); | |
| 190 | }); | |
| 191 | ||
| 192 | test("a log past the step cap is reported truncated, and 5,000 steps answer fast", async () => { | |
| 193 | const run = createRun(app.db, { repoId: notesId, kind: "agent" }); | |
| 194 | const lines = Array.from({ length: 5000 }, (_, i) => `→ Read f${i}.ts`); | |
| 195 | const { writeFileSync, mkdirSync } = await import("node:fs"); | |
| 196 | const { dirname } = await import("node:path"); | |
| 197 | const { runLogPath } = await import("../src/runs/log.ts"); | |
| 198 | mkdirSync(dirname(runLogPath(dir, run.id)), { recursive: true }); | |
| 199 | writeFileSync(runLogPath(dir, run.id), lines.join("\n") + "\n"); | |
| 200 | claimRun(app.db, run.id); | |
| 201 | finishRun(app.db, run.id, { state: "ok", summary: "long" }); | |
| 202 | indexRun(app.db, dir, run.id); | |
| 203 | await readOne(alice, ids[0]!); // the route's module loads on its first request | |
| 204 | // The server's own time (the client and the test share one loop, so wall time adds its lag). | |
| 205 | const res = await fetch(`${servers.url}/api/v1/traces/${run.id}`, { headers: { authorization: `Bearer ${alice}` } }); | |
| 206 | const body: any = await res.json(); | |
| 207 | expect(Number(/app;dur=([\d.]+)/.exec(res.headers.get("server-timing") ?? "")?.[1])).toBeLessThan(100); | |
| 208 | expect(body.steps).toBe(5000); | |
| 209 | expect(body.truncated).toBe(false); | |
| 210 | // A log whose start was cut (read from its last 512 KB) says so. | |
| 211 | const big = createRun(app.db, { repoId: notesId, kind: "agent" }); | |
| 212 | writeFileSync(runLogPath(dir, big.id), ("→ Read " + "x".repeat(1000) + "\n").repeat(700)); | |
| 213 | claimRun(app.db, big.id); | |
| 214 | finishRun(app.db, big.id, { state: "ok", summary: "cut" }); | |
| 215 | indexRun(app.db, dir, big.id); | |
| 216 | expect((await readOne(alice, big.id)).body.truncated).toBe(true); | |
| 217 | }); |
new above
offline