Open History to see the last commit
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;
36}
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;
61}
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;
75}
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 };
98}
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;
107}
108
109/**
110 * Lists `.jsonl` transcripts under `root` last modified at or after `sinceMs`.
111 *
112 * Errors on individual entries are swallowed: session files rotate and get
113 * removed while the walk is in flight, and a partial listing is far better than
114 * failing the page.
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 TranscriptFile[]> {
130 const fileName = options?.fileName;
131 const candidates: string[] = [];
132 const walk = async (dir: string): Promise<void> => {
133 let entries;
134 try {
135 entries = await NodeFSP.readdir(dir, { withFileTypes: true });
136 } catch {
137 return;
138 }
139 for (const entry of entries) {
140 const child = NodePath.join(dir, entry.name);
141 if (entry.isDirectory()) await walk(child);
142 else if (fileName !== undefined ? entry.name === fileName : entry.name.endsWith(".jsonl")) {
143 candidates.push(child);
144 }
145 }
146 };
147 await walk(root);
148
149 const found: Array<TranscriptFile | undefined> = Array.from({ length: candidates.length });
150 // Each worker pulls the next candidate from one shared iterator.
151 const queue = candidates.entries();
152 const statQueued = async (): Promise<void> => {
153 for (const [index, path] of queue) {
154 try {
155 const stats = await NodeFSP.stat(path);
156 if (stats.mtimeMs >= sinceMs) {
157 found[index] = { path, size: stats.size, mtimeMs: stats.mtimeMs };
158 }
159 } catch {
160 // Vanished between readdir and stat.
161 }
162 }
163 };
164 await Promise.all(
165 Array.from({ length: Math.min(STAT_CONCURRENCY, candidates.length) }, statQueued),
166 );
167 return found.filter((file) => file !== undefined);
168}
169
170/**
171 * Filesystem identity of a directory, as `device:inode`.
172 *
173 * Used to tell "two servers reading the same transcript directory" apart from
174 * "two machines whose hostname and home path happen to match". Returns an empty
175 * string when the directory cannot be stat'd.
176 */
177export async function readDirectoryVolumeId(path: string): Promise<string> {
178 try {
179 const stats = await NodeFSP.stat(path);
180 return `${stats.dev}:${stats.ino}`;
181 } catch {
182 return "";
183 }
184}
185
186async function guardMatches(
187 handle: NodeFSP.FileHandle,
188 position: TranscriptParsePosition,
189): Promise<boolean> {
190 if (position.guardLength <= 0 || position.guardLength > GUARD_LENGTH) return false;
191 try {
192 const window = Buffer.alloc(position.guardLength);
193 const { bytesRead } = await handle.read(
194 window,
195 0,
196 position.guardLength,
197 position.resumeOffset - position.guardLength,
198 );
199 return bytesRead === position.guardLength && fnv1a(window) === position.guardHash;
200 } catch {
201 return false;
202 }
203}
204
205/**
206 * Builds the byte-level test for a format's `usageMarkers`: whether a line
207 * contains any of them.
208 *
209 * One marker is a single `Buffer` search. Several would be one pass over the
210 * line each, so they are matched together as one alternation over the line's
211 * latin1 view instead: latin1 maps every byte to one character without
212 * validating it, so an ASCII marker matches exactly where its bytes do.
213 */
214export function transcriptLineGate(markers: readonly [string, ...string[]]) {
215 if (markers.length === 1) {
216 const marker = Buffer.from(markers[0]);
217 return (line: Buffer) => line.includes(marker);
218 }
219 const pattern = new RegExp(
220 markers.map((marker) => marker.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"),
221 );
222 return (line: Buffer) => pattern.test(line.toString("latin1"));
223}
224
225/**
226 * Streams one transcript and returns the usage records it contains, or `null`
227 * when the file could not be read.
228 *
229 * The distinction matters to the caller's cache: a genuinely empty transcript
230 * is a stable fact worth memoising, while a transient read failure memoised
231 * under the same `(size, mtime)` key would silently drop that file's usage
232 * until the file next changes.
233 *
234 * With `resumeFrom`, parsing continues from that position when its guard bytes
235 * still match, so only appended lines are read; otherwise the whole file is
236 * re-parsed from the start and `resumed` reports `false`.
237 *
238 * A stateful format resumes with the state saved at that position; a saved
239 * state its schema rejects re-parses the file whole.
240 */
241export async function readTranscriptRecords<State>(
242 filePath: string,
243 format: TranscriptUsageFormat<State>,
244 resumeFrom?: TranscriptParsePosition,
245 options?: { readonly streamingThresholdBytes?: number },
246): Promise<TranscriptParseResult | null> {
247 const streamingThresholdBytes = options?.streamingThresholdBytes ?? STREAMING_THRESHOLD_BYTES;
248 let handle: NodeFSP.FileHandle;
249 try {
250 handle = await NodeFSP.open(filePath, "r");
251 } catch {
252 return null;
253 }
254
255 try {
256 const codec = format.state;
257 const decodeState = codec === undefined ? undefined : Schema.decodeUnknownOption(codec.schema);
258 const encodeState = codec === undefined ? undefined : Schema.encodeSync(codec.schema);
259 // Stateless formats never read their state argument.
260 let state = codec === undefined ? (undefined as State) : codec.initial();
261 let resumed = false;
262 let start = 0;
263 const savedState =
264 resumeFrom === undefined || decodeState === undefined || resumeFrom.state === null
265 ? Option.none()
266 : decodeState(resumeFrom.state);
267 if (
268 resumeFrom !== undefined &&
269 resumeFrom.resumeOffset > 0 &&
270 (codec === undefined || Option.isSome(savedState)) &&
271 (await guardMatches(handle, resumeFrom))
272 ) {
273 if (Option.isSome(savedState)) state = savedState.value;
274 start = resumeFrom.resumeOffset;
275 resumed = true;
276 }
277
278 const toLineString = (lineBuffer: Buffer): string => {
279 const content =
280 lineBuffer.length > 0 && lineBuffer[lineBuffer.length - 1] === CARRIAGE_RETURN
281 ? lineBuffer.subarray(0, -1)
282 : lineBuffer;
283 return content.toString("utf8");
284 };
285
286 // Gate on the raw bytes so the lines that fail it, which is most of them,
287 // are never decoded.
288 const mightCarryUsage = transcriptLineGate(format.usageMarkers);
289 const parseLine = (lineBuffer: Buffer, lineState: State, out: UsageRecord[]): void => {
290 if (!mightCarryUsage(lineBuffer)) return;
291 for (const record of format.parseLine(toLineString(lineBuffer), lineState)) out.push(record);
292 };
293
294 const records: UsageRecord[] = [];
295 // Byte offsets remain independent of UTF-8 decoding. Only complete lines
296 // commit the resume point; an unfinished tail is replayed on the next scan.
297 let resumeOffset = start;
298 let scanOffset = start;
299 let pendingChunks: Buffer[] = [];
300 let pendingBytes = 0;
301 let streaming: ReturnType<typeof createTranscriptJsonReader> | undefined;
302 let decoder: NodeStringDecoder.StringDecoder | undefined;
303 const selectPath = selectUsageFields(format.selectFields);
304
305 const append = (segment: Buffer) => {
306 if (!streaming && pendingBytes + segment.length <= streamingThresholdBytes) {
307 if (segment.length > 0) pendingChunks.push(segment);
308 pendingBytes += segment.length;
309 return;
310 }
311 if (!streaming) {
312 // Usage has no import-history budget: retain all selected usage fields,
313 // regardless of the size of the surrounding unselected tool content.
314 streaming = createTranscriptJsonReader(() => {}, selectPath, { maxDepth: Infinity });
315 decoder = new NodeStringDecoder.StringDecoder("utf8");
316 for (const pending of pendingChunks) streaming.write(decoder.write(pending));
317 pendingChunks = [];
318 pendingBytes = 0;
319 }
320 streaming.write(decoder!.write(segment));
321 };
322 const finish = (lineState: State, out: UsageRecord[]) => {
323 if (streaming) {
324 streaming.write(decoder!.end());
325 const projected = streaming.finish();
326 for (const record of format.parseProjected(projected, lineState)) out.push(record);
327 } else if (pendingBytes > 0) {
328 const line =
329 pendingChunks.length === 1
330 ? pendingChunks[0]!
331 : Buffer.concat(pendingChunks, pendingBytes);
332 parseLine(line, lineState, out);
333 }
334 pendingChunks = [];
335 pendingBytes = 0;
336 streaming = undefined;
337 decoder = undefined;
338 };
339 const stream = handle.createReadStream({
340 start,
341 autoClose: false,
342 highWaterMark: 256 * 1024,
343 }) as AsyncIterable<Buffer>;
344 for await (const chunk of stream) {
345 let lineStart = 0;
346 while (lineStart < chunk.length) {
347 const newlineIndex = chunk.indexOf(NEWLINE, lineStart);
348 if (newlineIndex === -1) {
349 append(chunk.subarray(lineStart));
350 break;
351 }
352 // Most lines fit in the current chunk. Avoid buffering/streaming
353 // machinery on this hot path.
354 if (!streaming && pendingBytes === 0) {
355 parseLine(chunk.subarray(lineStart, newlineIndex), state, records);
356 } else {
357 append(chunk.subarray(lineStart, newlineIndex));
358 finish(state, records);
359 }
360 lineStart = newlineIndex + 1;
361 resumeOffset = scanOffset + lineStart;
362 }
363 scanOffset += chunk.length;
364 }
365
366 // The unfinished tail parses against a copy, so the saved state stays at
367 // `resumeOffset` and the next scan replays the tail from it.
368 const encodedState = encodeState === undefined ? null : encodeState(state);
369 const tailRecords: UsageRecord[] = [];
370 finish(
371 decodeState === undefined ? state : Option.getOrThrow(decodeState(encodedState)),
372 tailRecords,
373 );
374
375 const guardLength = Math.min(GUARD_LENGTH, resumeOffset);
376 let guardHash = 0;
377 if (guardLength > 0) {
378 const window = Buffer.alloc(guardLength);
379 await handle.read(window, 0, guardLength, resumeOffset - guardLength);
380 guardHash = fnv1a(window);
381 }
382
383 return {
384 records,
385 tailRecords,
386 position: {
387 resumeOffset,
388 guardLength,
389 guardHash,
390 state: encodedState,
391 },
392 resumed,
393 };
394 } catch {
395 return null;
396 } finally {
397 await handle.close().catch(() => undefined);
398 }
399}