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

Traces 5a: compare two traces of one issue side by side, with the cost and time difference #18164

opened this

Merged 5h 33m ago, live in production

scout/forge:scout/18083-traces-5a-compare-two-traces-of-one-issu → main 0 commits fork

  • Merged. scout/18083-traces-5a-compare-two-traces-of-one-issu was merged into main as e7394aa.

Review

Sign in to review this change.
7 files changed +111 −3
docs/features/traces.md +1 −1
@@ -24,7 +24,7 @@ Not yet: Talk conversations and outside imports as rows (they wait for the trace
2424
2525 ## Compare two runs, and share one (#17995)
2626
27 `/traces/<run id>/compare/<other run id>` sets two runs of one issue side by side: steps, failed steps, time (each run's own clock, started to finished), tokens (said "not recorded": a run's log holds none), cost (for those who may see the owner's facts) and outcome, with B − A beside each. Runs of two issues, or one the viewer cannot read, are the not-found a missing run gets. A trace page lists the issue's other runs to compare with. Reader: `src/trace/compare.ts` (`compareViews`, `compareRows`); page: `src/web/pages/trace_compare.ts`.
27 `/traces/<run id>/compare/<other run id>` sets two runs of one issue side by side: steps, failed steps, time (each run's own clock, started to finished), tokens (said "not recorded": a run's log holds none), cost (for those who may see the owner's facts) and outcome, with B − A beside each. Runs of two issues, or one the viewer cannot read, are the not-found a missing run gets. A trace page lists the issue's other runs to compare with. Reader: `src/trace/compare.ts` (`compareViews`, `compareRows`); page: `src/web/pages/trace_compare.ts`. API: `GET /api/v1/traces/compare?a=<run id>&b=<run id>` (#18083) answers the same rows with `timeDiffMs` and `costDiffUsd` (B − A); each run is read through its own gate (one the caller may not read is a 404), and two runs that are not two runs of one issue are a 422 `not_one_issue`.
2828
2929 A share link is off until the repository's owner makes one (**Make a share link** on the trace; `POST /traces/<run id>/share`, same-origin). It is `/traces/shared/<secret>`, shown once (only its hash is kept, `src/trace/share.ts`), and read by anyone holding it with no sign-in: the steps and their raw lines, every one passed through the forge's redaction (`redactHeld`) on the way out, so a token the log's writer missed is `[redacted]`; no cost, no people. One live link a run: a new one ends the old, **Stop sharing** ends it, and the link is then the not-found any page gets. The gate is `src/actions/trace_share.ts`; pages `src/web/pages/trace_share.ts`, reader `src/trace/shared.ts`, which keeps the redacted trace for 30 seconds per link and allows one address 60 opens a minute (then a 429 with `Retry-After`).
3030
src/contract/openapi/routes/getApiV1TracesCompare.ts added +21
@@ -0,0 +1,21 @@
1 import { list, num, obj, str } from "../schema_kit.ts";
2 import type { Route } from "../shared.ts";
3
4 export const route: Route = {
5 method: "get",
6 path: "/api/v1/traces/compare",
7 summary: "Compare two runs of one issue: steps, time, tokens, cost and outcome with the difference",
8 detail:
9 "Compare run `a` with run `b`, two runs of one issue: { a, b: { id, title, outcome }, rows: [{ label, a, b, diff }] (Steps, Failed steps, Time, Tokens, Cost, Outcome; diff is b − a in words, empty where a side lacks the figure), timeDiffMs, costDiffUsd (b − a, null where a side lacks it; cost only for those who may see the owner's spend) }. Each run is read as its log is: one the caller may not read answers exactly as an unknown id does, 404 not_found. Two readable runs that are not two runs of one issue (or are one run) are a 422 not_one_issue; a missing or malformed a or b, or another parameter, is a 422",
10 auth: true,
11 role: "member",
12 query: { a: "string", b: "string" },
13 response: obj({
14 a: obj({ id: str, title: str, outcome: str }),
15 b: obj({ id: str, title: str, outcome: str }),
16 rows: list(obj({ label: str, a: str, b: str, diff: str })),
17 timeDiffMs: num,
18 costDiffUsd: num,
19 }),
20 refuses: [401, 404, 422],
21 };
src/contract/openapi/routes/index.ts +1
@@ -268,6 +268,7 @@ export { route as getApiV1TelemetrySystem } from "./getApiV1TelemetrySystem.ts";
268268 export { route as getApiV1Templates } from "./getApiV1Templates.ts";
269269 export { route as getApiV1Tokens } from "./getApiV1Tokens.ts";
270270 export { route as getApiV1Traces } from "./getApiV1Traces.ts";
271 export { route as getApiV1TracesCompare } from "./getApiV1TracesCompare.ts";
271272 export { route as getApiV1TracesId } from "./getApiV1TracesId.ts";
272273 export { route as getApiV1Usage } from "./getApiV1Usage.ts";
273274 export { route as getApiV1User } from "./getApiV1User.ts";
src/http/api/traces.ts +35
@@ -10,6 +10,9 @@ import { mayReadLogOfRun } from "../../actions/runs.ts";
1010 import { cursorRefusal, limitRefusal, parseLimit } from "../../contract/page_query.ts";
1111 import type { App } from "../../app.ts";
1212 import { getRepo, getRepoById, type Repo } from "../../core/repos.ts";
13 import { getRun } from "../../core/runs.ts";
14 import { compareViews, sameIssue } from "../../trace/compare.ts";
15 import { readTrace, type TraceView } from "../../trace/read.ts";
1316 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1417 import type { User } from "../../core/users.ts";
1518 import { readRunLog, readRunTimes } from "../../runs/log.ts";
@@ -179,7 +182,39 @@ export const readTraceTree: Handler = (ctx) => {
179182 return new Response(JSON.stringify(body), { headers: { "content-type": "application/json", "cache-control": "private, no-store", vary: "authorization, cookie" } });
180183 };
181184
185 /**
186 * GET /api/v1/traces/compare?a=ID&b=ID (#18083): two runs of one issue as `compareViews` gives them
187 * (the page's table). Each is read through the run's own gate (`readTrace`), so one the caller may
188 * not read is the 404 an unknown id gets; two readable runs that are not two runs of one issue are
189 * a 422 saying so.
190 */
191 export const compareTraces: Handler = async (ctx) => {
192 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
193 const denied = requireScope(ctx, "ro");
194 if (denied) return denied;
195 const q = ctx.url.searchParams;
196 const unknown = [...new Set(q.keys())].filter((k) => k !== "a" && k !== "b");
197 if (unknown.length > 0) return apiError("unknown_parameter", 422, "this route reads a and b, the ids of two runs of one issue");
198 const ids = [q.get("a") ?? "", q.get("b") ?? ""];
199 if (ids.some((id) => !TRACE_ID.test(id))) return apiError("invalid_trace", 422, "a and b are each the id of a run");
200 const views: (TraceView | undefined)[] = [];
201 for (const id of ids) {
202 const run = getRun(ctx.app.db, id);
203 const repo = run === undefined ? undefined : getRepoById(ctx.app.db, run.repoId);
204 views.push(repo === undefined ? undefined : await readTrace(ctx.app, ctx.auth.user, repo, id));
205 }
206 const [a, b] = views;
207 if (a === undefined || b === undefined) return apiError("not_found", 404, "no such trace");
208 if (!sameIssue(a.run, b.run)) return apiError("not_one_issue", 422, a.run.id === b.run.id ? "a and b are one run: name two" : "a and b must be two runs of one issue");
209 const c = compareViews(a, b);
210 const side = (v: TraceView) => ({ id: v.run.id, title: v.title, outcome: v.run.state });
211 return new Response(JSON.stringify({ a: side(a), b: side(b), rows: c.rows, timeDiffMs: c.timeDiffMs ?? null, costDiffUsd: c.costDiffUsd ?? null }), {
212 headers: { "content-type": "application/json", "cache-control": "private, no-store", vary: "authorization, cookie" },
213 });
214 };
215
182216 export function traceRoutes(router: Router<Handler>): void {
217 router.add("GET", "/api/v1/traces/compare", compareTraces);
183218 router.add("GET", "/api/v1/traces/:id", readTraceTree);
184219 router.add("GET", "/api/v1/traces", listTraces);
185220 }
src/http/lazy_lists.ts +1
@@ -1497,6 +1497,7 @@ export const API_ROUTES = [
14971497 ["GET", "/api/v1/models"],
14981498 ["POST", "/api/v1/conversations"],
14991499 ["PATCH", "/api/v1/conversations/:id"],
1500 ["GET", "/api/v1/traces/compare"],
15001501 ["GET", "/api/v1/traces/:id"],
15011502 ["GET", "/api/v1/traces"],
15021503 ["POST", "/api/v1/builds"],
test/openapi-errors.test.ts +6 −2
@@ -37,6 +37,9 @@ const doc = openapi(BASE, "v", "admin") as Doc;
3737 const answered = new Map<Route, Set<number>>();
3838 const limit = process.env["FORGE_RATE_LIMIT"];
3939
40 /** Query strings a probe needs to get past its route's own 422 to the refusal after it. */
41 const PROBE_QUERY: Record<string, string> = { "/api/v1/traces/compare": "?a=nosuchrun&b=nosuchrun2" };
42
4043 const fill = (path: string) =>
4144 path.replace(/\{(\w+)\}/g, (_, n: string) => (/number|id$|^id$|anchor|blocker/i.test(n) ? "999999" : "nobody"));
4245
@@ -52,7 +55,7 @@ beforeAll(async () => {
5255 for (const r of ROUTES) {
5356 if (NOT_CALLED.test(r.path)) continue;
5457 const seen = new Set<number>();
55 const call = async (cookie: string | undefined, origin: string) => {
58 const call = async (cookie: string | undefined, origin: string, query = PROBE_QUERY[r.path] ?? "") => {
5659 const headers: Record<string, string> = { origin, "user-agent": "Mozilla/5.0 (X11; Linux x86_64) forge-test" };
5760 if (cookie) headers.cookie = cookie;
5861 const init: RequestInit = { method: r.method.toUpperCase(), headers, redirect: "manual" };
@@ -60,13 +63,14 @@ beforeAll(async () => {
6063 headers["content-type"] = "application/json";
6164 init.body = "{}";
6265 }
63 const res = await http.handle(new Request(BASE + fill(r.path), init));
66 const res = await http.handle(new Request(BASE + fill(r.path) + query, init));
6467 await res.arrayBuffer();
6568 seen.add(res.status);
6669 };
6770 const cookie = r.role === "admin" ? admin : r.role === "member" ? member : undefined;
6871 await call(cookie, BASE);
6972 await call(undefined, BASE);
73 if (PROBE_QUERY[r.path] !== undefined) await call(cookie, BASE, "");
7074 if (r.method !== "get") await call(cookie, "http://elsewhere.test");
7175 answered.set(r, seen);
7276 }
test/traces-api.test.ts +46
@@ -215,3 +215,49 @@ test("a log past the step cap is reported truncated, and 5,000 steps answer fast
215215 indexRun(app.db, dir, big.id);
216216 expect((await readOne(alice, big.id)).body.truncated).toBe(true);
217217 });
218
219 // --- GET /api/v1/traces/compare (#18083) ---
220
221 const compare = async (token: string, a: string, b: string): Promise<{ status: number; body: any }> => {
222 const res = await fetch(`${servers.url}/api/v1/traces/compare?a=${a}&b=${b}`, { headers: { authorization: `Bearer ${token}` } });
223 return { status: res.status, body: await res.json() };
224 };
225
226 test("two runs of one issue are compared with the cost and time difference; two issues are a 422", async () => {
227 const { createIssue } = await import("../src/core/issues.ts");
228 const aliceId = (app.db.query("SELECT id FROM user WHERE username='alice'").get() as { id: string }).id;
229 const issueIn = (title: string): string => {
230 const made = createIssue(app.db, { repoId: notesId, authorId: aliceId, title });
231 if (!made.ok) throw new Error("issue");
232 return made.value.id;
233 };
234 const one = issueIn("compare me");
235 const two = issueIn("another");
236 const runOn = (issueId: string, secs: number, cost: number, lines: string[]): string => {
237 const run = createRun(app.db, { repoId: notesId, kind: "agent", actorId: aliceId, issueId });
238 for (const l of lines) appendRunLog(dir, run.id, l);
239 flushRunLogs();
240 claimRun(app.db, run.id);
241 finishRun(app.db, run.id, { state: "ok", summary: "r", costUsd: cost });
242 app.db.query("UPDATE run SET started_at = '2026-12-04T10:00:00.000Z', finished_at = ?2 WHERE id = ?1").run(run.id, new Date(Date.parse("2026-12-04T10:00:00.000Z") + secs * 1000).toISOString());
243 return run.id;
244 };
245 const first = runOn(one, 60, 0.5, ["→ Read a.ts", "Done."]);
246 const second = runOn(one, 90, 1.25, ["→ Read a.ts", "→ Edit a.ts +1 −0", "Done."]);
247 const elsewhere = runOn(two, 10, 0.1, ["Done."]);
248 const ok = await compare(alice, first, second);
249 expect(ok.status).toBe(200);
250 expect(ok.body.timeDiffMs).toBe(30_000);
251 expect(ok.body.costDiffUsd).toBe(0.75);
252 expect(ok.body.rows.find((r: { label: string }) => r.label === "Steps")).toMatchObject({ a: "2", b: "3", diff: "+1" });
253 const cross = await compare(alice, first, elsewhere);
254 expect(cross.status).toBe(422);
255 expect(cross.body.error).toBe("not_one_issue");
256 expect((await compare(alice, first, first)).status).toBe(422);
257 expect((await compare(alice, first, "BAD ID")).status).toBe(422);
258 // A run the caller may not read is the 404 an unknown id is, whichever the other.
259 const hidden = await compare(bob, first, second);
260 expect(hidden).toEqual(await compare(bob, first, "nosuchrun"));
261 expect(hidden.status).toBe(404);
262 expect((await fetch(`${servers.url}/api/v1/traces/compare?a=${first}&b=${second}`)).status).toBe(401);
263 });

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

Keyboard shortcuts

Docs