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

A big session is stored without holding the whole file twice: the import writes it to gzip in chunks and checks UTF-8 as it goes #18385

opened this

Merged 3h 41m ago, live in production

torque/forge:torque/18383-a-big-session-is-stored-without-holding → main 0 commits fork 3 threads · 3 unresolved

  • Merged. torque/18383-a-big-session-is-stored-without-holding was merged into main as 8ceefc1.

Review

Sign in to review this change.
2 files changed +119 −14
src/trace/import.ts +61 −13
@@ -7,16 +7,20 @@
77 */
88 import type { Database } from "bun:sqlite";
99 import { createHash, randomUUID } from "node:crypto";
10 import { mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
10 import { createWriteStream, mkdirSync, readFileSync, renameSync, rmSync, statSync } from "node:fs";
1111 import { dirname, join } from "node:path";
12 import { promisify } from "node:util";
13 import { gunzipSync, gzip } from "node:zlib";
12 import { pipeline } from "node:stream/promises";
13 import { Readable } from "node:stream";
14 import { createGzip, gunzipSync } from "node:zlib";
1415 import { ADAPTERS } from "./import_adapter.ts";
1516 import { stepsOf, totalsOf } from "./model.ts";
1617 import { putTouches, touchesOf } from "./touched.ts";
1718 import { putTraceRow, type TraceRow } from "./index_table.ts";
1819
19 const gzipped = promisify(gzip);
20 /** The bytes fed to the compressor and the decoder at a time. */
21 const CHUNK_BYTES = 1024 * 1024;
22 /** The longest line of a session file: past it the file is refused, not read. */
23 const MAX_LINE_BYTES = 16 * 1024 * 1024;
outdated

Nothing outside this file imports this. Drop export; the dead-code check will flag it, and the test uses a literal.

2024
2125 export type ImportResult =
2226 | { readonly ok: true; readonly row: TraceRow; readonly session: string; readonly source: string; readonly updated: boolean }
@@ -70,14 +74,62 @@ export function readImported(dataDir: string, id: string): string {
7074 return gunzipSync(readFileSync(fileOf(dataDir, id))).toString("utf8");
7175 }
7276
77 /**
78 * One pass over the body in chunks: each goes through a streaming UTF-8 decoder (a character split
79 * between two chunks is whole to it) and into a gzip stream written to `part`, so the packed copy
80 * is never in memory. The longest line is counted on the way. Gives the text, or why the file is
81 * refused.
82 */
83 async function packAndRead(bytes: Uint8Array, part: string): Promise<{ text: string } | { refused: string }> {
84 const decoder = new TextDecoder("utf-8", { fatal: true });
85 let refused = "";
86 let line = 0;
87 function* chunks(): Generator<Uint8Array> {
88 for (let at = 0; at < bytes.length && refused === ""; at += CHUNK_BYTES) {
89 const chunk = bytes.subarray(at, Math.min(at + CHUNK_BYTES, bytes.length));
90 try {
91 decoder.decode(chunk, { stream: true });
92 } catch {
93 refused = `the file is not UTF-8 text (invalid bytes in the ${CHUNK_BYTES / 1048576} MiB at byte ${at})`;
94 return;
95 }
96 for (let i = 0; i < chunk.length; i++) {
97 if (chunk[i] === 10) line = 0;
98 else if (++line > MAX_LINE_BYTES) {
99 refused = `a line of the file is longer than ${MAX_LINE_BYTES / 1048576} MiB (near byte ${at + i})`;
100 return;
101 }
102 }
103 yield chunk;
104 }
105 }
106 await pipeline(Readable.from(chunks(), { objectMode: false }), createGzip(), createWriteStream(part));
107 if (refused !== "") return { refused };
108 try {
109 decoder.decode();
110 } catch {
111 return { refused: "the file is not UTF-8 text (it ends inside a character)" };
112 }
113 // The bytes are valid now: one decode, so the text is held once, not as pieces and a join.
114 return { text: new TextDecoder().decode(bytes) };
115 }
116
73117 /** Read `bytes` as a session of some source, keep it, and index it for `owner`. */
74118 export async function importSession(db: Database, dataDir: string, owner: string, bytes: Uint8Array): Promise<ImportResult> {
75 let text: string;
119 const dir = dirname(fileOf(dataDir, "x"));
120 mkdirSync(dir, { recursive: true });
121 const part = join(dir, `${randomUUID()}.part`);
76122 try {
77 text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
78 } catch {
79 return { ok: false, reason: "the file is not UTF-8 text" };
123 return await importPacked(db, dataDir, owner, bytes, part);
124 } finally {
125 rmSync(part, { force: true });
80126 }
127 }
128
129 async function importPacked(db: Database, dataDir: string, owner: string, bytes: Uint8Array, part: string): Promise<ImportResult> {
130 const read0 = await packAndRead(bytes, part);
131 if ("refused" in read0) return { ok: false, reason: read0.refused };
132 const text = read0.text;
81133 if (text.trim() === "") return { ok: false, reason: "the file is empty" };
82134 let refused = "";
83135 for (const adapter of ADAPTERS) {
@@ -90,15 +142,11 @@ export async function importSession(db: Database, dataDir: string, owner: string
90142 const { trace } = read;
91143 const id = importedId(owner, adapter.source, trace.id);
92144 const file = fileOf(dataDir, id);
93 mkdirSync(dirname(file), { recursive: true });
94 const packed = await gzipped(bytes);
95145 // What the account keeps, less the copy this replaces, plus this one, stays under the quota.
96146 const kept = importedIdsOf(db, owner).reduce((n, other) => n + (other === id ? 0 : sizeOf(fileOf(dataDir, other))), 0);
97 if (kept + packed.length > IMPORT_QUOTA_BYTES) {
147 if (kept + sizeOf(part) > IMPORT_QUOTA_BYTES) {
98148 return { ok: false, quota: true, reason: `the account's imported sessions are at most ${IMPORT_QUOTA_BYTES / 1048576} MiB stored` };
99149 }
100 const part = `${file}.${randomUUID()}.part`;
101 writeFileSync(part, packed);
102150 renameSync(part, file);
103151 const t = totalsOf(trace);
104152 const model = stepsOf(trace).find((s) => s.model !== undefined)?.model ?? "";
test/traces-import.test.ts +58 −1
@@ -96,7 +96,7 @@ test("a malformed or empty file is refused with its reason", async () => {
9696 expect(body.error).toBe("invalid_session");
9797 expect(body.message).toContain("no Claude Code records");
9898 expect(((await (await send(alice, "")).json()) as any).message).toBe("the file is empty");
99 expect(((await (await send(alice, new Uint8Array([0xff, 0xfe, 0x41]))).json()) as any).message).toBe("the file is not UTF-8 text");
99 expect(((await (await send(alice, new Uint8Array([0xff, 0xfe, 0x41]))).json()) as any).message).toContain("the file is not UTF-8 text");
100100 const noId = await send(alice, JSON.stringify({ type: "user", timestamp: "2026-12-01T09:00:00Z", message: { role: "user", content: "hi" } }));
101101 expect(noId.status).toBe(422);
102102 expect(((await noId.json()) as any).message).toContain("sessionId");
@@ -175,3 +175,60 @@ test("a Codex rollout is 201 first, 200 on resend with one row; no session id is
175175 expect(JSON.stringify(await bad.json())).toContain("session_meta");
176176 expect((await send(alice, SESSION)).status).toBeLessThan(300);
177177 });
178
179 test("stored bytes are what a one-shot gzip of the file gives, and the id is unchanged", async () => {
180 const { gzipSync } = await import("node:zlib");
181 const { readFileSync } = await import("node:fs");
182 const owner = "stored-bytes-owner";
183 const bytes = new TextEncoder().encode(SESSION);
184 const done = await importSession(app.db, dir, owner, bytes);
185 if (!done.ok) throw new Error(done.reason);
186 expect(done.row.id).toBe(importedId(owner, "claude-code", "sess-1"));
187 const stored = readFileSync(join(dir, "traces", "imported", `${done.row.id}.jsonl.gz`));
188 expect(Buffer.compare(stored, gzipSync(bytes))).toBe(0);
189 const again = await importSession(app.db, dir, owner, bytes);
190 expect(again.ok && again.updated).toBe(true);
191 });
192
193 test("a ~30 MiB session is stored with bounded extra memory and read back whole", async () => {
194 const filler = "x".repeat(60_000);
195 const lines = [SESSION];
196 for (let i = 0; lines.length * 60_000 < 30 * 1048576; i++) {
197 lines.push(rec({ type: "user", timestamp: "2026-12-01T09:10:00Z", message: { role: "user", content: `${i} ${filler}` } }));
198 }
199 const bytes = new TextEncoder().encode(lines.join("\n"));
200 expect(bytes.length).toBeGreaterThan(29 * 1048576);
201 Bun.gc(true);
202 const before = process.memoryUsage();
203 let peak = 0;
204 const timer = setInterval(() => {
205 const m = process.memoryUsage();

Non-blocking: a 2 ms sampling timer can miss a short spike. The bound has wide margin, so it is fine.

206 peak = Math.max(peak, m.heapUsed + m.external + m.arrayBuffers - before.heapUsed - before.external - before.arrayBuffers);
207 }, 2);
208 const done = await importSession(app.db, dir, "big-owner", bytes);
209 clearInterval(timer);
210 if (!done.ok) throw new Error(done.reason);
211 // The decoded text (about the file's size again) and the parsed steps; never also the packed

200 MiB also passes on main for a 30 MiB file. Measure main and set the bound between the two peaks so this test fails without the change.

212 // copy.
213 expect(peak).toBeLessThan(100 * 1048576);
214 expect(readImported(dir, done.row.id).length).toBe(bytes.length);
215 });
216
217 test("a hostile file is a 422 that says which: one huge line, invalid UTF-8 mid-file", async () => {
218 const huge = await send(alice, rec({ type: "user", message: { role: "user", content: "y".repeat(30 * 1048576) } }));
219 expect(huge.status).toBe(422);
220 expect(((await huge.json()) as any).message).toContain("longer than 16 MiB");
221 const bad = new Uint8Array([...new TextEncoder().encode(SESSION), 10, 0xc3, 0x28, 10]);
222 const res = await send(alice, bad);
223 expect(res.status).toBe(422);
224 expect(JSON.stringify(await res.json())).toContain("not UTF-8");
225 });
226
227 test("a character split between two chunks is valid", async () => {
228 const pad = "a".repeat(1048576 - 1);
229 const text = rec({ type: "user", timestamp: "2026-12-01T09:00:00Z", message: { role: "user", content: `${pad}é tail` } });
230 const bytes = new TextEncoder().encode(text);
231 expect(bytes.indexOf(0xc3)).toBeGreaterThan(0);
232 const done = await importSession(app.db, dir, "split-owner", bytes);
233 expect(done.ok).toBe(true);
234 });

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

Keyboard shortcuts

Docs