Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usageTranscriptReader.ts

380 lines13.9 KB

1// @effect-diagnostics nodeBuiltinImport:off
2/**
3 * Raw filesystem access for transcript scanning.
4 *
5 * Isolated here so the rest of the usage code stays on Effect's `FileSystem`.
6 * The direct `node:fs` streaming is deliberate: a cold 30-day window is ~1.4 GB
7 * across ~1,500 files, and buffer-level streaming is roughly an order of
8 * magnitude cheaper than materialising each file. The equivalent Effect stream
9 * pipeline is idiomatic but not fast enough to sit behind a page load.
10 *
11 * Transcripts are append-only, so a parse also reports the byte position it
12 * stopped at. A later scan of the same file resumes from that position and
13 * parses only the appended bytes, which is what keeps a warm scan cheap while a
14 * session is actively writing a multi-hundred-megabyte rollout.
15 *
16 * @module usageTranscriptReader
17 */
18import * as NodeFSP from "node:fs/promises";
19import * as NodePath from "node:path";
20import * as NodeStringDecoder from "node:string_decoder";
21​
22import type {
23 SelectedFields,
24 TranscriptUsageFormat,
25 UsageRecord,
26} from "@t3tools/provider-core/server/usage";
27import * as Option from "effect/Option";
28import * as Schema from "effect/Schema";
29​
30import { createTranscriptJsonReader } from "../project/AgentSessionJson.ts";
31​
32export interface TranscriptFile {
33 readonly path: string;
34 readonly size: number;
35 readonly mtimeMs: number;
37​
38/**
39 * Where a parse stopped, with enough state to continue from there.
40 *
41 * The guard hash fingerprints the bytes immediately before `resumeOffset`. A
42 * resume only proceeds when those bytes still match: transcripts are
43 * append-only by design, but a rotated or rewritten file silently mis-parsed
44 * from the middle would corrupt usage totals. The window is a cheap tripwire
45 * for those realistic failure shapes, all of which disturb the file's tail at
46 * that exact offset; it deliberately does not hash the whole prefix, which
47 * would cost the full re-read the resume exists to avoid.
48 */
49export interface TranscriptParsePosition {
50 /** Byte offset just past the last newline-terminated line consumed. */
51 readonly resumeOffset: number;
52 /** Length of the fingerprinted window ending at `resumeOffset`. */
53 readonly guardLength: number;
54 /** FNV-1a hash of that window. */
55 readonly guardHash: number;
56 /**
57 * The format's reducer state as of `resumeOffset`, encoded by its schema;
58 * `null` for stateless formats.
59 */
60 readonly state: unknown;
62​
63export interface TranscriptParseResult {
64 /** Records from newline-terminated lines at or after the parse start. */
65 readonly records: readonly UsageRecord[];
66 /**
67 * Records from a trailing segment the writer has not newline-terminated yet.
68 * Kept out of `records` because `position` deliberately excludes that
69 * segment: the next scan re-reads it once the writer finishes the line.
70 */
71 readonly tailRecords: readonly UsageRecord[];
72 readonly position: TranscriptParsePosition;
73 /** Whether the parse continued from `resumeFrom` rather than byte 0. */
74 readonly resumed: boolean;
76​
77/** 64 bytes of JSONL tail is ample to distinguish a replaced file. */
78export const GUARD_LENGTH = 64;
79// Native parsing is faster for common 1–4 MiB context/tool records. Above
80// 8 MiB, project usage without allocating the whole record. This switches
81// readers; it never discards a record because of its size.
82const STREAMING_THRESHOLD_BYTES = 8 * 1024 * 1024;
83const NEWLINE = 0x0a;
84/** `stat` calls one transcript walk keeps in flight. The libuv pool has 4 threads. */
85const STAT_CONCURRENCY = 32;
86const CARRIAGE_RETURN = 0x0d;
87​
88function selectUsageFields(fields: SelectedFields) {
89 return (path: ReadonlyArray<string | number | null>): boolean => {
90 let selected: true | SelectedFields = fields;
91 for (const key of path) {
92 if (selected === true) return true;
93 if (typeof key !== "string" || !Object.hasOwn(selected, key)) return false;
94 selected = selected[key]!;
95 }
96 return true;
97 };
99​
100function fnv1a(buffer: Buffer): number {
101 let hash = 0x811c9dc5;
102 for (let index = 0; index < buffer.length; index += 1) {
103 hash ^= buffer[index]!;
104 hash = Math.imul(hash, 0x01000193);
105 }
106 return hash >>> 0;
108​
109/**
110 * Lists `.jsonl` transcripts under `root` last modified at or after `sinceMs`.
111 *
112 * Unreadable directories and files are counted in `failedPaths` rather than
113 * failing the page, so the source can report incomplete usage. Files that
114 * vanish between `readdir` and `stat` are ordinary rotation and not counted.
115 *
116 * `fileName` restricts the walk to a single basename (Grok's `updates.jsonl`).
117 * Grok sessions also ship multi-megabyte `chat_history` and `events` logs that
118 * never carry usage, so the basename filter keeps a cold scan off those files.
119 *
120 * Directories are listed depth-first, one at a time, then the candidates are
121 * stat'd by a fixed pool of workers: a warm scan stats thousands of files, and
122 * one at a time each waits its own trip through the thread pool. Results keep
123 * `readdir` order, which the aggregator's first-seen dedupe relies on.
124 */
125export async function listTranscriptFiles(
126 root: string,
127 sinceMs: number,
128 options?: { readonly fileName?: string },
129): Promise<{ readonly files: readonly TranscriptFile[]; readonly failedPaths: number }> {
130 const fileName = options?.fileName;
131 const candidates: string[] = [];
132 let failedPaths = 0;
133 const walk = async (dir: string): Promise<void> => {
134 let entries;
135 try {
136 entries = await NodeFSP.readdir(dir, { withFileTypes: true });
137 } catch {
138 failedPaths += 1;
139 return;
140 }
141 for (const entry of entries) {
142 const child = NodePath.join(dir, entry.name);
143 if (entry.isDirectory()) await walk(child);
144 else if (fileName !== undefined ? entry.name === fileName : entry.name.endsWith(".jsonl")) {
145 candidates.push(child);
146 }
147 }
148 };
149 await walk(root);
150​
151 const found: Array<TranscriptFile | undefined> = Array.from({ length: candidates.length });
152 // Each worker pulls the next candidate from one shared iterator.
153 const queue = candidates.entries();
154 const statQueued = async (): Promise<void> => {
155 for (const [index, path] of queue) {
156 try {
157 const stats = await NodeFSP.stat(path);
158 if (stats.mtimeMs >= sinceMs) {
159 found[index] = { path, size: stats.size, mtimeMs: stats.mtimeMs };
160 }
161 } catch (error) {
162 if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) {
163 failedPaths += 1;
164 }
165 }
166 }
167 };
168 await Promise.all(
169 Array.from({ length: Math.min(STAT_CONCURRENCY, candidates.length) }, statQueued),
170 );
171 return { files: found.filter((file) => file !== undefined), failedPaths };
173​
174/**
175 * Filesystem identity of a directory, as `device:inode`.
176 *
177 * Used to tell "two servers reading the same transcript directory" apart from
178 * "two machines whose hostname and home path happen to match". Returns an empty
179 * string when the directory cannot be stat'd.
180 */
181export async function readDirectoryVolumeId(path: string): Promise<string> {
182 try {
183 const stats = await NodeFSP.stat(path);
184 return `${stats.dev}:${stats.ino}`;
185 } catch {
186 return "";
187 }
189​
190async function guardMatches(
191 handle: NodeFSP.FileHandle,
192 position: TranscriptParsePosition,
193): Promise<boolean> {
194 if (position.guardLength <= 0 || position.guardLength > GUARD_LENGTH) return false;
195 try {
196 const window = Buffer.alloc(position.guardLength);
197 const { bytesRead } = await handle.read(
198 window,
199 0,
200 position.guardLength,
201 position.resumeOffset - position.guardLength,
202 );
203 return bytesRead === position.guardLength && fnv1a(window) === position.guardHash;
204 } catch {
205 return false;
206 }
208​
209/**
210 * Streams one transcript and returns the usage records it contains, or `null`
211 * when the file could not be read.
212 *
213 * The distinction matters to the caller's cache: a genuinely empty transcript
214 * is a stable fact worth memoising, while a transient read failure memoised
215 * under the same `(size, mtime)` key would silently drop that file's usage
216 * until the file next changes.
217 *
218 * With `resumeFrom`, parsing continues from that position when its guard bytes
219 * still match, so only appended lines are read; otherwise the whole file is
220 * re-parsed from the start and `resumed` reports `false`.
221 *
222 * A stateful format resumes with the state saved at that position; a saved
223 * state its schema rejects re-parses the file whole.
224 */
225export async function readTranscriptRecords<State>(
226 filePath: string,
227 format: TranscriptUsageFormat<State>,
228 resumeFrom?: TranscriptParsePosition,
229 options?: { readonly streamingThresholdBytes?: number },
230): Promise<TranscriptParseResult | null> {
231 const streamingThresholdBytes = options?.streamingThresholdBytes ?? STREAMING_THRESHOLD_BYTES;
232 let handle: NodeFSP.FileHandle;
233 try {
234 handle = await NodeFSP.open(filePath, "r");
235 } catch {
236 return null;
237 }
238​
239 try {
240 const codec = format.state;
241 const decodeState = codec === undefined ? undefined : Schema.decodeUnknownOption(codec.schema);
242 const encodeState = codec === undefined ? undefined : Schema.encodeSync(codec.schema);
243 // Stateless formats never read their state argument.
244 let state = codec === undefined ? (undefined as State) : codec.initial();
245 let resumed = false;
246 let start = 0;
247 const savedState =
248 resumeFrom === undefined || decodeState === undefined || resumeFrom.state === null
249 ? Option.none()
250 : decodeState(resumeFrom.state);
251 if (
252 resumeFrom !== undefined &&
253 resumeFrom.resumeOffset > 0 &&
254 (codec === undefined || Option.isSome(savedState)) &&
255 (await guardMatches(handle, resumeFrom))
256 ) {
257 if (Option.isSome(savedState)) state = savedState.value;
258 start = resumeFrom.resumeOffset;
259 resumed = true;
260 }
261​
262 const parseLine = (line: string, lineState: State, out: UsageRecord[]): void => {
263 if (!format.mightCarryUsage(line)) return;
264 for (const record of format.parseLine(line, lineState)) out.push(record);
265 };
266​
267 const toLineString = (lineBuffer: Buffer): string => {
268 const content =
269 lineBuffer.length > 0 && lineBuffer[lineBuffer.length - 1] === CARRIAGE_RETURN
270 ? lineBuffer.subarray(0, -1)
271 : lineBuffer;
272 return content.toString("utf8");
273 };
274​
275 const records: UsageRecord[] = [];
276 // Byte offsets remain independent of UTF-8 decoding. Only complete lines
277 // commit the resume point; an unfinished tail is replayed on the next scan.
278 let resumeOffset = start;
279 let scanOffset = start;
280 let pendingChunks: Buffer[] = [];
281 let pendingBytes = 0;
282 let streaming: ReturnType<typeof createTranscriptJsonReader> | undefined;
283 let decoder: NodeStringDecoder.StringDecoder | undefined;
284 const selectPath = selectUsageFields(format.selectFields);
285​
286 const append = (segment: Buffer) => {
287 if (!streaming && pendingBytes + segment.length <= streamingThresholdBytes) {
288 if (segment.length > 0) pendingChunks.push(segment);
289 pendingBytes += segment.length;
290 return;
291 }
292 if (!streaming) {
293 // Usage has no import-history budget: retain all selected usage fields,
294 // regardless of the size of the surrounding unselected tool content.
295 streaming = createTranscriptJsonReader(() => {}, selectPath, { maxDepth: Infinity });
296 decoder = new NodeStringDecoder.StringDecoder("utf8");
297 for (const pending of pendingChunks) streaming.write(decoder.write(pending));
298 pendingChunks = [];
299 pendingBytes = 0;
300 }
301 streaming.write(decoder!.write(segment));
302 };
303 const finish = (lineState: State, out: UsageRecord[]) => {
304 if (streaming) {
305 streaming.write(decoder!.end());
306 const projected = streaming.finish();
307 for (const record of format.parseProjected(projected, lineState)) out.push(record);
308 } else if (pendingBytes > 0) {
309 const line =
310 pendingChunks.length === 1
311 ? pendingChunks[0]!
312 : Buffer.concat(pendingChunks, pendingBytes);
313 parseLine(toLineString(line), lineState, out);
314 }
315 pendingChunks = [];
316 pendingBytes = 0;
317 streaming = undefined;
318 decoder = undefined;
319 };
320 const stream = handle.createReadStream({
321 start,
322 autoClose: false,
323 highWaterMark: 256 * 1024,
324 }) as AsyncIterable<Buffer>;
325 for await (const chunk of stream) {
326 let lineStart = 0;
327 while (lineStart < chunk.length) {
328 const newlineIndex = chunk.indexOf(NEWLINE, lineStart);
329 if (newlineIndex === -1) {
330 append(chunk.subarray(lineStart));
331 break;
332 }
333 // Most lines fit in the current chunk. Avoid buffering/streaming
334 // machinery on this hot path.
335 if (!streaming && pendingBytes === 0) {
336 parseLine(toLineString(chunk.subarray(lineStart, newlineIndex)), state, records);
337 } else {
338 append(chunk.subarray(lineStart, newlineIndex));
339 finish(state, records);
340 }
341 lineStart = newlineIndex + 1;
342 resumeOffset = scanOffset + lineStart;
343 }
344 scanOffset += chunk.length;
345 }
346​
347 // The unfinished tail parses against a copy, so the saved state stays at
348 // `resumeOffset` and the next scan replays the tail from it.
349 const encodedState = encodeState === undefined ? null : encodeState(state);
350 const tailRecords: UsageRecord[] = [];
351 finish(
352 decodeState === undefined ? state : Option.getOrThrow(decodeState(encodedState)),
353 tailRecords,
354 );
355​
356 const guardLength = Math.min(GUARD_LENGTH, resumeOffset);
357 let guardHash = 0;
358 if (guardLength > 0) {
359 const window = Buffer.alloc(guardLength);
360 await handle.read(window, 0, guardLength, resumeOffset - guardLength);
361 guardHash = fnv1a(window);
362 }
363​
364 return {
365 records,
366 tailRecords,
367 position: {
368 resumeOffset,
369 guardLength,
370 guardHash,
371 state: encodedState,
372 },
373 resumed,
374 };
375 } catch {
376 return null;
377 } finally {
378 await handle.close().catch(() => undefined);
379 }