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

usageTranscriptReader.ts

488 lines17.2 KB

1// @effect-diagnostics nodeBuiltinImport:off
2// Cold windows span ~1.4 GB/1,500 files; node:fs buffer streaming is ~10x cheaper than materializing files.
3import * as NodeCrypto from "node:crypto";
4import * as NodeFS from "node:fs";
5import * as NodeFSP from "node:fs/promises";
6import * as NodePath from "node:path";
7import * as NodeStringDecoder from "node:string_decoder";
8import * as NodeUtil from "node:util";
9import * as NodeZlib from "node:zlib";
10​
11import type {
12 SelectedFields,
13 TranscriptUsageFormat,
14 UsageRecord,
15} from "@t3tools/provider-core/server/usage";
16import * as Option from "effect/Option";
17import * as Schema from "effect/Schema";
18​
19import { createTranscriptJsonReader } from "../project/AgentSessionJson.ts";
20​
21export interface TranscriptFile {
22 readonly path: string;
23 readonly size: number;
24 readonly mtimeMs: number;
26​
27/** Resume only if the same file's bytes before resumeOffset match the guard hash; rewritten files would corrupt totals. */
28export interface TranscriptParsePosition {
29 /** Device and inode, so a file renamed over the path never resumes on a matching guard. */
30 readonly fileId?: string;
31 readonly resumeOffset: number;
32 readonly guardLength: number;
33 readonly guardHash: number;
34 readonly state: unknown;
36​
37export interface TranscriptParseResult {
38 readonly records: readonly UsageRecord[];
39 /** Unterminated tail records stay outside records/position so the next scan rereads them. */
40 readonly tailRecords: readonly UsageRecord[];
41 /** Timestamps, including tentative tail diagnostics; position.state only includes committed lines. */
42 readonly malformedRecords: readonly number[];
43 readonly position: TranscriptParsePosition;
44 readonly resumed: boolean;
46​
47export const GUARD_LENGTH = 64;
48const STREAMING_THRESHOLD_BYTES = 8 * 1024 * 1024;
49const READ_CHUNK_BYTES = 256 * 1024;
50const NEWLINE = 0x0a;
51const STAT_CONCURRENCY = 32;
52const WALK_CONCURRENCY = 16;
53// Measured about 3x faster than the promise API's stat across 20,000 transcripts.
54const statFile = NodeUtil.promisify(NodeFS.stat);
55const CARRIAGE_RETURN = 0x0d;
56​
57function selectUsageFields(fields: SelectedFields) {
58 return (path: ReadonlyArray<string | number | null>): boolean => {
59 let selected: true | SelectedFields = fields;
60 for (const key of path) {
61 if (selected === true) return true;
62 if (typeof key !== "string" || !Object.hasOwn(selected, key)) return false;
63 selected = selected[key]!;
64 }
65 return true;
66 };
68​
69function fnv1a(buffer: Buffer): number {
70 let hash = 0x811c9dc5;
71 for (let index = 0; index < buffer.length; index += 1) {
72 hash ^= buffer[index]!;
73 hash = Math.imul(hash, 0x01000193);
74 }
75 return hash >>> 0;
77​
78/** Skips Grok logs without usage; preserves readdir order for first-seen deduplication. */
79export async function listTranscriptFiles(
80 root: string,
81 sinceMs: number,
82 options?: { readonly fileName?: string },
83): Promise<{
84 readonly files: readonly TranscriptFile[];
85 readonly walked: readonly string[];
86 readonly failedPaths: number;
87}> {
88 const fileName = options?.fileName;
89 let failedPaths = 0;
90 let reading = 0;
91 const waiting: Array<() => void> = [];
92 // Sibling directories read together; each returns its own list so the result keeps readdir order.
93 const walk = async (dir: string): Promise<readonly string[]> => {
94 if (reading < WALK_CONCURRENCY) reading += 1;
95 else await new Promise<void>((resume) => waiting.push(resume));
96 let entries;
97 try {
98 entries = await NodeFSP.readdir(dir, { withFileTypes: true });
99 } catch {
100 failedPaths += 1;
101 return [];
102 } finally {
103 // A waiting directory takes over this slot, so the count only drops when none waits.
104 const next = waiting.shift();
105 if (next === undefined) reading -= 1;
106 else next();
107 }
108 const found = await Promise.all(
109 entries.map((entry) => {
110 const child = NodePath.join(dir, entry.name);
111 if (entry.isDirectory()) return walk(child);
112 return (
113 fileName !== undefined
114 ? entry.name === fileName
115 : entry.name.endsWith(".jsonl") || entry.name.endsWith(".jsonl.zst")
116 )
117 ? [child]
118 : [];
119 }),
120 );
121 return found.flat();
122 };
123 const candidates = await walk(root);
124​
125 const found: Array<TranscriptFile | undefined> = Array.from({ length: candidates.length });
126 const queue = candidates.entries();
127 const statQueued = async (): Promise<void> => {
128 for (const [index, path] of queue) {
129 try {
130 const stats = await statFile(path);
131 // Opening a FIFO or device for reading can block forever; stat still follows symlinks.
132 if (stats.isFile() && stats.mtimeMs >= sinceMs) {
133 found[index] = { path, size: stats.size, mtimeMs: stats.mtimeMs };
134 }
135 } catch (error) {
136 if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) {
137 failedPaths += 1;
138 }
139 }
140 }
141 };
142 await Promise.all(
143 Array.from({ length: Math.min(STAT_CONCURRENCY, candidates.length) }, statQueued),
144 );
145 return { files: found.filter((file) => file !== undefined), walked: candidates, failedPaths };
147​
148export async function readDirectoryVolumeId(path: string): Promise<string> {
149 try {
150 const stats = await NodeFSP.stat(path);
151 return `${stats.dev}:${stats.ino}`;
152 } catch {
153 return "";
154 }
156​
157/**
158 * Set by the desktop app, from a value it persists, on its Windows server and
159 * the WSL server it manages, so both can name one Windows directory alike
160 * without merging separate machines that share a hostname and path.
161 */
162export const DESKTOP_HOST_SCOPE_ENV = "T3CODE_DESKTOP_HOST_SCOPE";
163​
164const MOUNT_FIELD_ESCAPE = /\\([0-7]{3})/g;
165const WINDOWS_ROOT = /^(?:[A-Za-z]:|\\\\[^\\]+\\[^\\]+)\\?$/;
166​
167const unescapeMountField = (field: string) =>
168 field.replace(MOUNT_FIELD_ESCAPE, (_, octal: string) =>
169 String.fromCharCode(Number.parseInt(octal, 8)),
170 );
171​
172const normalizeWindowsPath = (path: string) =>
173 (/^[a-z]:/.test(path) ? path[0]!.toUpperCase() + path.slice(1) : path).replace(/\\$/, "");
174​
175/**
176 * The Windows directory behind the deepest mount holding `dir`, read from
177 * `/proc/self/mountinfo` so a custom automount root resolves and an ext4
178 * mount under `/mnt` never passes for a drive.
179 */
180function windowsMountFor(
181 mountInfo: string,
182 dir: string,
183): { readonly mountPoint: string; readonly windowsRoot: string } | undefined {
184 let deepest: { mountPoint: string; windowsRoot: string | undefined } | undefined;
185 for (const line of mountInfo.split("\n")) {
186 const fields = line.split(" ");
187 const separator = fields.indexOf("-", 6);
188 if (separator === -1) continue;
189 const mountPoint = unescapeMountField(fields[4] ?? "");
190 const contains =
191 mountPoint === "/" ||
192 dir === mountPoint ||
193 dir.startsWith(mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`);
194 if (!contains || (deepest !== undefined && deepest.mountPoint.length > mountPoint.length)) {
195 continue;
196 }
197 // WSL2 mounts drives over 9p with `aname=drvfs;path=C:\`; WSL1 as `drvfs`.
198 const options = (fields[separator + 3] ?? "").split(/[,;]/);
199 const source = options.includes("aname=drvfs")
200 ? options.find((option) => option.startsWith("path="))?.slice("path=".length)
201 : fields[separator + 1] === "drvfs"
202 ? unescapeMountField(fields[separator + 2] ?? "")
203 : undefined;
204 const root = unescapeMountField(fields[3] ?? "/")
205 .split("/")
206 .filter(Boolean);
207 deepest = {
208 mountPoint,
209 windowsRoot:
210 source !== undefined && WINDOWS_ROOT.test(source)
211 ? [normalizeWindowsPath(source), ...root].join("\\")
212 : undefined,
213 };
214 }
215 return deepest?.windowsRoot === undefined
216 ? undefined
217 : { mountPoint: deepest.mountPoint, windowsRoot: deepest.windowsRoot };
219​
220/**
221 * drvfs keeps the casing a path was typed with, while Windows reports the
222 * on-disk names. Read those names rather than folding case, which would join
223 * distinct entries of a case-sensitive directory.
224 */
225async function onDiskNames(
226 mountPoint: string,
227 parts: readonly string[],
228): Promise<string[] | undefined> {
229 const names: string[] = [];
230 let current = mountPoint;
231 for (const part of parts) {
232 let entries: string[];
233 try {
234 entries = await NodeFSP.readdir(current);
235 } catch {
236 return undefined;
237 }
238 const folded = part.toUpperCase();
239 const [name, ...others] = entries.includes(part)
240 ? [part]
241 : entries.filter((entry) => entry.toUpperCase() === folded);
242 if (name === undefined || others.length > 0) return undefined;
243 names.push(name);
244 current = NodePath.posix.join(current, name);
245 }
246 return names;
248​
249export function physicalSourceIdOf(scope: string, windowsPath: string): string {
250 return NodeCrypto.createHash("sha256")
251 .update(`${scope}\0${windowsPath}`)
252 .digest("hex")
253 .slice(0, 32);
255​
256/**
257 * Identifies a Windows directory the same way from the Windows server and from
258 * a WSL server reading it through drvfs. Directories that are not Windows
259 * backed, and servers the desktop app did not start, get none.
260 */
261export async function readPhysicalSourceId(
262 dir: string,
263 scope: string | undefined,
264 platform: NodeJS.Platform,
265 mountInfoPath = "/proc/self/mountinfo",
266): Promise<string | undefined> {
267 if (scope === undefined || scope.length === 0) return undefined;
268 try {
269 if (platform === "win32") {
270 // The native realpath reports on-disk casing; the JS one keeps the input's.
271 return physicalSourceIdOf(scope, normalizeWindowsPath(await NodeFSP.realpath(dir)));
272 }
273 if (platform !== "linux") return undefined;
274 const mount = windowsMountFor(await NodeFSP.readFile(mountInfoPath, "utf8"), dir);
275 if (mount === undefined) return undefined;
276 const names = await onDiskNames(
277 mount.mountPoint,
278 dir.slice(mount.mountPoint.length).split("/").filter(Boolean),
279 );
280 return names === undefined
281 ? undefined
282 : physicalSourceIdOf(scope, [mount.windowsRoot, ...names].join("\\"));
283 } catch {
284 return undefined;
285 }
287​
288async function guardMatches(
289 handle: NodeFSP.FileHandle,
290 position: TranscriptParsePosition,
291): Promise<boolean> {
292 if (position.guardLength <= 0 || position.guardLength > GUARD_LENGTH) return false;
293 try {
294 const window = Buffer.alloc(position.guardLength);
295 const { bytesRead } = await handle.read(
296 window,
297 0,
298 position.guardLength,
299 position.resumeOffset - position.guardLength,
300 );
301 return bytesRead === position.guardLength && fnv1a(window) === position.guardHash;
302 } catch {
303 return false;
304 }
306​
307/** Plain files reuse one buffer, so a chunk is only valid until the next one is requested. */
308async function* readChunks(
309 handle: NodeFSP.FileHandle,
310 start: number,
311 compressed: boolean,
312): AsyncGenerator<Buffer> {
313 if (compressed) {
314 // Compressed snapshots cache a full parse; decoded byte offsets cannot
315 // resume the compressed input.
316 yield* handle
317 .createReadStream({ start, autoClose: true, highWaterMark: READ_CHUNK_BYTES })
318 .compose(NodeZlib.createZstdDecompress());
319 return;
320 }
321 const buffer = Buffer.allocUnsafe(READ_CHUNK_BYTES);
322 for (let position = start; ;) {
323 const { bytesRead } = await handle.read(buffer, 0, buffer.length, position);
324 if (bytesRead === 0) return;
325 position += bytesRead;
326 yield buffer.subarray(0, bytesRead);
327 }
329​
330// Match ASCII markers as raw bytes: UTF-8 cannot false-match them mid-sequence, and no line string is allocated.
331export function transcriptLineGate(markers: readonly [string, ...string[]]) {
332 const needles = markers.map((marker) => Buffer.from(marker));
333 return (line: Buffer) => needles.some((needle) => line.includes(needle));
335​
336/** Returns null on read failure; caching it as empty would hide usage until size/mtime changes. */
337export async function readTranscriptRecords<State>(
338 filePath: string,
339 format: TranscriptUsageFormat<State>,
340 resumeFrom?: TranscriptParsePosition,
341 options?: { readonly streamingThresholdBytes?: number },
342): Promise<TranscriptParseResult | null> {
343 const streamingThresholdBytes = options?.streamingThresholdBytes ?? STREAMING_THRESHOLD_BYTES;
344 const compressed = filePath.endsWith(".jsonl.zst");
345 let handle: NodeFSP.FileHandle;
346 try {
347 handle = await NodeFSP.open(filePath, "r");
348 } catch {
349 return null;
350 }
351​
352 try {
353 const codec = format.state;
354 const decodeState = codec === undefined ? undefined : Schema.decodeUnknownOption(codec.schema);
355 const encodeState = codec === undefined ? undefined : Schema.encodeSync(codec.schema);
356 let state = codec === undefined ? (undefined as State) : codec.initial();
357 const stats = await handle.stat({ bigint: true });
358 const fileId = `${stats.dev}:${stats.ino}`;
359 let resumed = false;
360 let start = 0;
361 const savedState =
362 resumeFrom === undefined || decodeState === undefined || resumeFrom.state === null
363 ? Option.none()
364 : decodeState(resumeFrom.state);
365 if (
366 !compressed &&
367 resumeFrom !== undefined &&
368 resumeFrom.fileId === fileId &&
369 resumeFrom.resumeOffset > 0 &&
370 (codec === undefined || Option.isSome(savedState)) &&
371 (await guardMatches(handle, resumeFrom))
372 ) {
373 if (Option.isSome(savedState)) state = savedState.value;
374 start = resumeFrom.resumeOffset;
375 resumed = true;
376 }
377​
378 const toLineString = (lineBuffer: Buffer): string => {
379 const content =
380 lineBuffer.length > 0 && lineBuffer[lineBuffer.length - 1] === CARRIAGE_RETURN
381 ? lineBuffer.subarray(0, -1)
382 : lineBuffer;
383 return content.toString("utf8");
384 };
385​
386 const mightCarryUsage = transcriptLineGate(format.usageMarkers);
387 const parseLine = (lineBuffer: Buffer, lineState: State, out: UsageRecord[]): void => {
388 if (!mightCarryUsage(lineBuffer)) return;
389 for (const record of format.parseLine(toLineString(lineBuffer), lineState)) out.push(record);
390 };
391​
392 const records: UsageRecord[] = [];
393 let resumeOffset = start;
394 let scanOffset = start;
395 let pendingChunks: Buffer[] = [];
396 let pendingBytes = 0;
397 let streaming: ReturnType<typeof createTranscriptJsonReader> | undefined;
398 let decoder: NodeStringDecoder.StringDecoder | undefined;
399 const selectPath = selectUsageFields(format.selectFields);
400​
401 const append = (segment: Buffer) => {
402 if (!streaming && pendingBytes + segment.length <= streamingThresholdBytes) {
403 // Copy: the next read overwrites the chunk this segment points into.
404 if (segment.length > 0) pendingChunks.push(Buffer.from(segment));
405 pendingBytes += segment.length;
406 return;
407 }
408 if (!streaming) {
409 // Usage has no import-history budget; retain selected fields regardless of surrounding tool payload size.
410 streaming = createTranscriptJsonReader(() => {}, selectPath, { maxDepth: Infinity });
411 decoder = new NodeStringDecoder.StringDecoder("utf8");
412 for (const pending of pendingChunks) streaming.write(decoder.write(pending));
413 pendingChunks = [];
414 pendingBytes = 0;
415 }
416 streaming.write(decoder!.write(segment));
417 };
418 const finish = (lineState: State, out: UsageRecord[]) => {
419 if (streaming) {
420 streaming.write(decoder!.end());
421 const projected = streaming.finish();
422 for (const record of format.parseProjected(projected, lineState)) out.push(record);
423 } else if (pendingBytes > 0) {
424 const line =
425 pendingChunks.length === 1
426 ? pendingChunks[0]!
427 : Buffer.concat(pendingChunks, pendingBytes);
428 parseLine(line, lineState, out);
429 }
430 pendingChunks = [];
431 pendingBytes = 0;
432 streaming = undefined;
433 decoder = undefined;
434 };
435 for await (const chunk of readChunks(handle, start, compressed)) {
436 let lineStart = 0;
437 while (lineStart < chunk.length) {
438 const newlineIndex = chunk.indexOf(NEWLINE, lineStart);
439 if (newlineIndex === -1) {
440 append(chunk.subarray(lineStart));
441 break;
442 }
443 if (!streaming && pendingBytes === 0) {
444 parseLine(chunk.subarray(lineStart, newlineIndex), state, records);
445 } else {
446 append(chunk.subarray(lineStart, newlineIndex));
447 finish(state, records);
448 }
449 lineStart = newlineIndex + 1;
450 resumeOffset = scanOffset + lineStart;
451 }
452 scanOffset += chunk.length;
453 }
454​
455 // Parse unfinished tails against copied state so the next scan can replay from resumeOffset.
456 const encodedState = encodeState === undefined ? null : encodeState(state);
457 const tailRecords: UsageRecord[] = [];
458 const tailState =
459 decodeState === undefined ? state : Option.getOrThrow(decodeState(encodedState));
460 finish(tailState, tailRecords);
461​
462 const guardLength = compressed ? 0 : Math.min(GUARD_LENGTH, resumeOffset);
463 let guardHash = 0;
464 if (guardLength > 0) {
465 const window = Buffer.alloc(guardLength);
466 await handle.read(window, 0, guardLength, resumeOffset - guardLength);
467 guardHash = fnv1a(window);
468 }
469​
470 return {
471 records,
472 tailRecords,
473 malformedRecords: format.readMalformedRecords?.(tailState) ?? [],
474 position: {
475 fileId,
476 resumeOffset: compressed ? 0 : resumeOffset,
477 guardLength,
478 guardHash,
479 state: encodedState,
480 },
481 resumed,
482 };
483 } catch {
484 return null;
485 } finally {
486 await handle.close().catch(() => undefined);
487 }