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

An imported session opens by reading its stored gzip line by line, not as one decoded string #18387

opened this

Merged 3h 34m ago, live in production

scout/forge:scout/18384-an-imported-session-opens-by-reading-its → main 0 commits fork

  • Merged. scout/18384-an-imported-session-opens-by-reading-its was merged into main as a3b5b3e.

Review

Sign in to review this change.
12 files changed +168 −36
docs/features/traces.md −2
@@ -40,8 +40,6 @@ MCP: the `trace` tool, `action` `list`, `read`, `compare` (`with`), `share`, `un
4040
4141 Modules: `src/trace/model.ts` (the shape and totals), `src/trace/claude_code.ts` and `src/trace/codex.ts` (the readers), `src/trace/session.ts` (which one), `src/trace/otlp.ts` (the export). Not yet: cost per step or per import (prices change; the file holds none).
4242
43 The file is read whole, then parsed, so the 256 MB limit is memory-bound: a session near it holds a few copies at once. Streaming the read is a later step.
44
4543 ## Listing traces (#18021)
4644
4745 `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`.
src/trace/claude_code.ts +5 −4
@@ -5,6 +5,7 @@
55 * of a model reply, each repeating the reply's `message.id` and usage, so a
66 * reply is counted once. A line that is not a record is counted in `skipped`.
77 */
8 import { asLines, own, type SessionInput } from "./lines.ts";
89 import type { Outcome, Step, Trace, Turn } from "./model.ts";
910
1011 const MAX_LINE = 4 * 1024 * 1024;
@@ -12,13 +13,13 @@ const LINE_CHARS = 120;
1213
1314 type Json = Record<string, unknown>;
1415 const obj = (v: unknown): Json | undefined => (typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Json) : undefined);
15 const str = (v: unknown): string | undefined => (typeof v === "string" ? v : undefined);
16 const str = (v: unknown): string | undefined => (typeof v === "string" ? own(v) : undefined);
1617 const num = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.floor(v) : 0);
1718
1819 /** A terminal line is one line of printable text, cut to a width. */
1920 export function oneLine(text: string, max = LINE_CHARS): string {
2021 const flat = text.replace(/[\x00-\x1f\x7f-\x9f\u00a0\u2028\u2029]+/g, " ").trim();
21 return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
22 return own(flat.length > max ? `${flat.slice(0, max - 1)}…` : flat);
2223 }
2324
2425 const lines = (s: string): number => (s === "" ? 0 : s.split("\n").length);
@@ -40,7 +41,7 @@ const textOf = (content: unknown): string => {
4041 return content.map((b) => (str(obj(b)?.type) === "text" ? (str(obj(b)?.text) ?? "") : "")).join("\n");
4142 };
4243
43 export function parseClaudeSession(text: string): Trace {
44 export function parseClaudeSession(input: SessionInput): Trace {
4445 const trace: Trace = { source: "claude-code", id: "", cwd: undefined, turns: [], skipped: 0 };
4546 const open = new Map<string, Step>();
4647 const replies = new Map<string, Step>();
@@ -55,7 +56,7 @@ export function parseClaudeSession(text: string): Trace {
5556 return turn;
5657 };
5758
58 for (const raw of text.split("\n")) {
59 for (const raw of asLines(input)) {
5960 if (raw.trim() === "") continue;
6061 let rec: Json | undefined;
6162 if (raw.length <= MAX_LINE) {
src/trace/codex.ts +8 −5
@@ -6,13 +6,14 @@
66 * made. A line that is not a record is counted in `skipped`.
77 */
88 import type { Step, Trace, Turn } from "./model.ts";
9 import { asLines, own, type SessionInput } from "./lines.ts";
910 import { oneLine } from "./claude_code.ts";
1011
1112 const MAX_LINE = 4 * 1024 * 1024;
1213
1314 type Json = Record<string, unknown>;
1415 const obj = (v: unknown): Json | undefined => (typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Json) : undefined);
15 const str = (v: unknown): string | undefined => (typeof v === "string" ? v : undefined);
16 const str = (v: unknown): string | undefined => (typeof v === "string" ? own(v) : undefined);
1617 const num = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.floor(v) : 0);
1718
1819 const textOf = (content: unknown): string =>
@@ -43,8 +44,10 @@ export function isCodexRecord(rec: Json | undefined): boolean {
4344 }
4445
4546 /** True when the first record of a file (within its first lines) is Codex's. */
46 export function isCodexFile(text: string): boolean {
47 for (const raw of text.split("\n", 20)) {
47 export function isCodexFile(input: SessionInput): boolean {
48 let seen = 0;
49 for (const raw of asLines(input)) {
50 if (++seen > 20) return false;
4851 if (raw.trim() === "") continue;
4952 try {
5053 const rec: unknown = JSON.parse(raw);
@@ -56,7 +59,7 @@ export function isCodexFile(text: string): boolean {
5659 return false;
5760 }
5861
59 export function parseCodexSession(text: string): Trace {
62 export function parseCodexSession(input: SessionInput): Trace {
6063 const trace: Trace = { source: "codex", id: "", cwd: undefined, turns: [], skipped: 0 };
6164 const open = new Map<string, Step>();
6265 let turn: Turn | undefined;
@@ -72,7 +75,7 @@ export function parseCodexSession(text: string): Trace {
7275 return turn;
7376 };
7477
75 for (const raw of text.split("\n")) {
78 for (const raw of asLines(input)) {
7679 if (raw.trim() === "") continue;
7780 let rec: Json | undefined;
7881 if (raw.length <= MAX_LINE) {
src/trace/import.ts +6 −5
@@ -7,12 +7,13 @@
77 */
88 import type { Database } from "bun:sqlite";
99 import { createHash, randomUUID } from "node:crypto";
10 import { createWriteStream, mkdirSync, readFileSync, renameSync, rmSync, statSync } from "node:fs";
10 import { createWriteStream, mkdirSync, renameSync, rmSync, statSync } from "node:fs";
1111 import { dirname, join } from "node:path";
1212 import { pipeline } from "node:stream/promises";
1313 import { Readable } from "node:stream";
14 import { createGzip, gunzipSync } from "node:zlib";
14 import { createGzip } from "node:zlib";
1515 import { ADAPTERS } from "./import_adapter.ts";
16 import { gzipLines } from "./lines.ts";
1617 import { stepsOf, totalsOf } from "./model.ts";
1718 import { putTouches, touchesOf } from "./touched.ts";
1819 import { putTraceRow, type TraceRow } from "./index_table.ts";
@@ -69,9 +70,9 @@ export function stampOf(dataDir: string, id: string): string | undefined {
6970 }
7071 }
7172
72 /** The raw session as it was sent, from the stored file. */
73 export function readImported(dataDir: string, id: string): string {
74 return gunzipSync(readFileSync(fileOf(dataDir, id))).toString("utf8");
73 /** The raw session as it was sent, from the stored file, as lines: never one string. */
74 export function importedLines(dataDir: string, id: string): Iterable<string> {
75 return gzipLines(fileOf(dataDir, id));
7576 }
7677
7778 /**
src/trace/imported_read.ts +9 −11
@@ -6,7 +6,7 @@
66 */
77 import type { App } from "../app.ts";
88 import type { TraceRow } from "./index_table.ts";
9 import { readImported, stampOf } from "./import.ts";
9 import { importedLines, stampOf } from "./import.ts";
1010 import type { Step, Trace } from "./model.ts";
1111 import { stepsOf, totalsOf } from "./model.ts";
1212 import { MAX_STEPS } from "./run_log.ts";
@@ -18,8 +18,6 @@ export interface ImportedParse {
1818 readonly timed: boolean;
1919 /** The session held more than `MAX_STEPS` steps; the rest are not read. */
2020 readonly truncated: boolean;
21 /** The file as stored, for a step's raw lines on demand. */
22 readonly text: string;
2321 }
2422
2523 /** Parses made, for a test to count: a page view and its step opens share one. */
@@ -27,7 +25,7 @@ export const parseCount = { n: 0 };
2725
2826 /**
2927 * The latest parses of a forge, by id and file stamp; a re-import changes the stamp. Few, as each
30 * holds a file.
28 * holds a trace.
3129 */
3230 const KEEP = 2;
3331 const kept = new WeakMap<App, Map<string, ImportedParse>>();
@@ -53,14 +51,14 @@ export function parseImported(app: App, row: Pick<TraceRow, "id">): ImportedPars
5351 }
5452
5553 function parseFresh(app: App, row: Pick<TraceRow, "id">): ImportedParse | undefined {
56 let text: string;
54 let trace: Trace;
5755 try {
58 text = readImported(app.config.dataDir, row.id);
56 const lines = importedLines(app.config.dataDir, row.id);
57 parseCount.n++;
58 trace = parseSession(lines);
5959 } catch {
6060 return undefined;
6161 }
62 parseCount.n++;
63 const trace = parseSession(text);
6462 const t0 = totalsOf(trace).startMs;
6563 let left = MAX_STEPS;
6664 let cut = false;
@@ -74,7 +72,7 @@ function parseFresh(app: App, row: Pick<TraceRow, "id">): ImportedParse | undefi
7472 }
7573 }
7674 const all = stepsOf(trace);
77 return { trace, timed: all.length > 0 && all[all.length - 1]!.endMs > 0, truncated: cut, text };
75 return { trace, timed: all.length > 0 && all[all.length - 1]!.endMs > 0, truncated: cut };
7876 }
7977
8078 /** Most raw lines of one step, and most characters of each, the on-demand route answers. */
@@ -82,10 +80,10 @@ const RAW_LINES = 40;
8280 const RAW_CHARS = 8000;
8381
8482 /** The lines of the file that name this step's id (a reply's, a tool call's and its result's). */
85 export function rawLinesOf(text: string, step: Pick<Step, "id">): string[] {
83 export function rawLinesOf(lines: Iterable<string>, step: Pick<Step, "id">): string[] {
8684 const needle = JSON.stringify(step.id);
8785 const out: string[] = [];
88 for (const line of text.split("\n")) {
86 for (const line of lines) {
8987 if (!line.includes(needle)) continue;
9088 out.push(line.length > RAW_CHARS ? `${line.slice(0, RAW_CHARS)}…` : line);
9189 if (out.length === RAW_LINES) break;
src/trace/lines.ts added +45
@@ -0,0 +1,45 @@
1 /**
2 * A session as a stream of lines (#18384): what the readers of `claude_code.ts` and `codex.ts`
3 * walk, so an imported session is never held as one decoded string. A string (a file just read,
4 * a test's fixture) is its `split("\n")`; stored bytes are cut at each newline byte and one line
5 * is decoded at a time. Plain data in, plain data out.
6 */
7 import { readFileSync } from "node:fs";
8 import { gunzipSync } from "node:zlib";
9
10 /** What a reader takes: the text itself or its lines. */
11 export type SessionInput = string | Iterable<string>;
12
13 /** The lines of `input`, the same as `text.split("\n")` would give. */
14 export const asLines = (input: SessionInput): Iterable<string> => (typeof input === "string" ? input.split("\n") : input);
15
16 /**
17 * A copy of a short string cut from a line. A piece of a parsed line keeps the whole line alive
18 * for as long as the piece is, so a step's name would hold 4 KB; a copy lets the line go.
19 */
20 export const own = (s: string): string => (s.length > 512 ? s : Buffer.from(s).toString());
21
22 /**
23 * The lines of UTF-8 `bytes`, each decoded as it is reached. It can be walked again (the format
24 * sniff walks the first few, the parse all) and the bytes are held once, not as a string.
25 */
26 export function bytesLines(bytes: Uint8Array): Iterable<string> {
27 return {
28 *[Symbol.iterator]() {
29 // `Buffer`'s decoder gives a one-byte string for ASCII, which a `TextDecoder`'s does not.
30 const whole = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.length);
31 for (let at = 0; ; ) {
32 const end = bytes.indexOf(10, at);
33 if (end === -1) {
34 yield whole.toString("utf8", at);
35 return;
36 }
37 yield whole.toString("utf8", at, end);
38 at = end + 1;
39 }
40 },
41 };
42 }
43
44 /** The lines of a stored gzip file; throws when it cannot be read. */
45 export const gzipLines = (file: string): Iterable<string> => bytesLines(gunzipSync(readFileSync(file)));
src/trace/session.ts +2 −1
@@ -4,8 +4,9 @@
44 */
55 import { parseClaudeSession } from "./claude_code.ts";
66 import { isCodexFile, parseCodexSession } from "./codex.ts";
7 import type { SessionInput } from "./lines.ts";
78 import type { Trace } from "./model.ts";
89
9 export function parseSession(text: string): Trace {
10 export function parseSession(text: SessionInput): Trace {
1011 return isCodexFile(text) ? parseCodexSession(text) : parseClaudeSession(text);
1112 }
src/trace/touched_fill.ts +2 −2
@@ -6,7 +6,7 @@
66 */
77 import type { Database } from "bun:sqlite";
88 import { readRunLog, readRunTimes } from "../runs/log.ts";
9 import { readImported } from "./import.ts";
9 import { importedLines } from "./import.ts";
1010 import { putTouches, touchesOf } from "./touched.ts";
1111 import { parseRunLog } from "./run_log.ts";
1212 import { parseSession } from "./session.ts";
@@ -20,7 +20,7 @@ export function fillTouches(db: Database, dataDir: string, batch = FILL_BATCH):
2020 for (const r of rows) {
2121 let touches = { tools: [] as string[], files: [] as string[] };
2222 try {
23 if (r.owner !== "") touches = touchesOf(parseSession(readImported(dataDir, r.id)));
23 if (r.owner !== "") touches = touchesOf(parseSession(importedLines(dataDir, r.id)));
2424 else {
2525 const { lines } = readRunLog(dataDir, r.id);
2626 touches = touchesOf(parseRunLog(r.id, r.title, lines, readRunTimes(dataDir, r.id, lines.length)).trace);
src/web/pages/trace_imported.ts +2 −1
@@ -6,6 +6,7 @@
66 */
77 import type { Ctx } from "../../http/context.ts";
88 import { securityFloor } from "../../http/respond.ts";
9 import { importedLines } from "../../trace/import.ts";
910 import { parseImported, rawLinesOf } from "../../trace/imported_read.ts";
1011 import type { TraceRow } from "../../trace/index_table.ts";
1112 import { stepsOf } from "../../trace/model.ts";
@@ -57,7 +58,7 @@ export function importedStep(ctx: Ctx, row: TraceRow): Response {
5758 const read = n === undefined ? undefined : parseImported(ctx.app, row);
5859 const step = read === undefined ? undefined : stepsOf(read.trace)[n! - 1];
5960 if (read === undefined || step === undefined) return notFoundPage(ctx);
60 const raw = rawLinesOf(read.text, step);
61 const raw = rawLinesOf(importedLines(ctx.app.config.dataDir, row.id), step);
6162 return securityFloor(
6263 new Response(`${stepLine(step, n!, stepsOf(read.trace).length, read.timed)}\n${raw.length === 0 ? "No raw line of the file names this step." : raw.join("\n")}\n`, {
6364 headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "private, no-store" },
test/trace-imported-open.test.ts added +83
@@ -0,0 +1,83 @@
1 /**
2 * Opening a big imported session (#18384): read line by line from its gzip, flat in memory, fast.
3 */
4 import { afterAll, beforeAll, expect, test } from "bun:test";
5 import { mkdtemp, rm } from "node:fs/promises";
6 import { tmpdir } from "node:os";
7 import { join } from "node:path";
8 import { createApp, type App } from "../src/app.ts";
9 import { importedLines, importSession } from "../src/trace/import.ts";
10 import { parseImported, parseCount, rawLinesOf } from "../src/trace/imported_read.ts";
11 import { parseSession } from "../src/trace/session.ts";
12
13 const rec = (o: object): string => JSON.stringify({ sessionId: "sess-open", cwd: "/w", ...o });
14 const line = (i: number): string =>
15 rec({ type: i % 2 ? "assistant" : "user", timestamp: new Date(Date.UTC(2026, 11, 1) + i * 1000).toISOString(), message: i % 2 ? { id: `m${i}`, model: "x", role: "assistant", content: [{ type: "text", text: "y".repeat(2000) }] } : { role: "user", content: "z".repeat(2000) } });
16
17 let dir = "";
18 let app: App;
19 let id = "";
20 let bytes = 0;
21
22 beforeAll(async () => {
23 dir = await mkdtemp(join(tmpdir(), "forge-trace-open-"));
24 app = createApp({ dataDir: dir, port: 0 });
25 const lines: string[] = [];
26 for (let n = 0, i = 0; n < 30 * 1048576; i++) {
27 const l = line(i);
28 lines.push(l);
29 n += l.length + 1;
30 }
31 const body = new TextEncoder().encode(lines.join("\n"));
32 bytes = body.length;
33 const done = await importSession(app.db, dir, "owner", body);
34 if (!done.ok) throw new Error(done.reason);
35 id = done.row.id;
36 }, 60_000);
37
38 afterAll(async () => {
39 app.db.close();
40 await rm(dir, { recursive: true, force: true });
41 });
42
43 test("a ~30 MiB session opens in under 500 ms and the parse holds the file once, not as a string", () => {
44 Bun.gc(true);
45 const before = process.memoryUsage();
46 const base = before.heapUsed + before.arrayBuffers;
47 let peak = 0;
48 let count = 0;
49 const source = importedLines(dir, id);
50 Bun.gc(true);
51 const watched: Iterable<string> = {
52 *[Symbol.iterator]() {
53 for (const l of source) {
54 if (++count % 500 === 0) {
55 Bun.gc(true);
56 const m = process.memoryUsage();
57 peak = Math.max(peak, m.heapUsed + m.arrayBuffers - base);
58 }
59 yield l;
60 }
61 },
62 };
63 const t = performance.now();
64 const trace = parseSession(watched);
65 expect(performance.now() - t).toBeLessThan(500);
66 expect(trace.id).toBe("sess-open");
67 // Live set, collected at each sample: the inflated bytes once (30 MiB) and the steps. The read of
68 // the whole text held them and the lines cut from it (about 60 MiB).
69 expect(peak).toBeLessThan(bytes + 15 * 1048576);
70 const opened = performance.now();
71 const before2 = parseCount.n;
72 expect(parseImported(app, { id })?.trace.turns.length).toBeGreaterThan(0);
73 expect(performance.now() - opened).toBeLessThan(500);
74 parseImported(app, { id });
75 expect(parseCount.n - before2).toBe(1);
76 });
77
78 test("a step's raw lines come from the stored lines, and an invalid line degrades to skipped", () => {
79 const lines = ["{not json", line(0), line(1), "[1]"];
80 const trace = parseSession(lines);
81 expect(trace.skipped).toBe(2);
82 expect(rawLinesOf(lines, { id: "m1" })).toEqual([line(1)]);
83 });
test/trace-imported-page.test.ts +1 −1
@@ -103,5 +103,5 @@ test("one parse of a near-cap session is measured", async () => {
103103 const bigId = out.id;
104104 const t = performance.now();
105105 expect(parseImported(app, { id: bigId })).toBeDefined();
106 expect(performance.now() - t).toBeLessThan(2000);
106 expect(performance.now() - t).toBeLessThan(500);
107107 }, 60_000);
test/traces-import.test.ts +5 −4
@@ -12,7 +12,7 @@ import { createUser } from "../src/core/users.ts";
1212 import { listTraceIndex } from "../src/trace/index_table.ts";
1313 import { serve, type Servers } from "../src/http/server.ts";
1414 import { BODY_CAPS } from "../src/kernel/body_caps.ts";
15 import { IMPORT_QUOTA_BYTES, importSession, importedId, readImported } from "../src/trace/import.ts";
15 import { IMPORT_QUOTA_BYTES, importSession, importedId, importedLines } from "../src/trace/import.ts";
1616 import { stepsOf, totalsOf } from "../src/trace/model.ts";
1717 import { parseSession } from "../src/trace/session.ts";
1818 import { seedAdmin } from "./helpers/admin.ts";
@@ -65,7 +65,7 @@ test("a session is kept, listed to its sender alone, and read back with turns, t
6565 expect(mine[0].kind).toBe("imported");
6666 expect(await list(bob)).toEqual([]);
6767 // The stored raw file, through the reader.
68 const trace = parseSession(readImported(dir, made.id));
68 const trace = parseSession(importedLines(dir, made.id));
6969 expect(trace.id).toBe("sess-1");
7070 expect(trace.turns.length).toBe(1);
7171 expect(trace.turns[0]!.prompt).toBe("fix the login bug");
@@ -140,7 +140,7 @@ test("two imports of one session at once both finish and leave one readable file
140140 const bytes = new TextEncoder().encode(SESSION);
141141 const done = await Promise.all([importSession(app.db, dir, id, bytes), importSession(app.db, dir, id, bytes)]);
142142 expect(done.every((d) => d.ok)).toBe(true);
143 expect(parseSession(readImported(dir, importedId(id, "claude-code", "sess-1"))).id).toBe("sess-1");
143 expect(parseSession(importedLines(dir, importedId(id, "claude-code", "sess-1"))).id).toBe("sess-1");
144144 });
145145
146146 test("no query through listTraceIndex shows an imported row without asking for it as imported", () => {
@@ -211,7 +211,8 @@ test("a ~30 MiB session is stored with bounded extra memory and read back whole"
211211 // The decoded text (about the file's size again) and the parsed steps; never also the packed
212212 // copy.
213213 expect(peak).toBeLessThan(100 * 1048576);
214 expect(readImported(dir, done.row.id).length).toBe(bytes.length);
214 const stored = [...importedLines(dir, done.row.id)];
215 expect(stored.reduce((n, l) => n + new TextEncoder().encode(l).length, stored.length - 1)).toBe(bytes.length);
215216 });
216217
217218 test("a hostile file is a 422 that says which: one huge line, invalid UTF-8 mid-file", async () => {

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

Keyboard shortcuts

Docs