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

EventNdjsonLogger.ts

663 lines21.5 KB

1// @effect-diagnostics nodeBuiltinImport:off
2/**
3 * Best-effort provider event logging with one shared writer per thread.
4 *
5 * Native and canonical views share batching, rotation, and retention state so
6 * they cannot race while appending to the same thread-scoped file.
7 */
8import * as NodeFS from "node:fs";
9import * as NodePath from "node:path";
10​
11import type { ThreadId } from "@t3tools/contracts";
12import { RotatingFileSink } from "@t3tools/shared/logging";
13import { errorTag } from "@t3tools/shared/observability";
14import * as Clock from "effect/Clock";
15import * as DateTime from "effect/DateTime";
16import * as Effect from "effect/Effect";
17import * as Exit from "effect/Exit";
18import * as Schema from "effect/Schema";
19import * as Scope from "effect/Scope";
20import * as SynchronizedRef from "effect/SynchronizedRef";
21​
22import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts";
23import type { ResourceAttribution } from "../../resourceTelemetry/ResourceAttribution.ts";
24​
25const MEBIBYTE = 1024 * 1024;
26const DAY_MS = 24 * 60 * 60 * 1_000;
27const DEFAULT_MAX_BYTES = 10 * MEBIBYTE;
28const DEFAULT_MAX_FILES = 10;
29const DEFAULT_BATCH_WINDOW_MS = 1_000;
30const DEFAULT_MAX_TOTAL_BYTES = 512 * MEBIBYTE;
31const DEFAULT_MAX_AGE_MS = 14 * DAY_MS;
32const DEFAULT_RETENTION_CHECK_INTERVAL_MS = 5 * 60 * 1_000;
33const DEFAULT_MAX_BUFFERED_BYTES = MEBIBYTE;
34const DEFAULT_MAX_BUFFERED_RECORDS = 512;
35const GLOBAL_THREAD_SEGMENT = "_global";
36const LOG_SCOPE = "provider-observability";
37const encodeUnknownJsonString = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
38​
39const transientCanonicalEventTypes = new Set([
40 "content.delta",
41 "hook.progress",
42 "item.updated",
43 "task.progress",
44 "thread.realtime.audio.delta",
45 "tool.progress",
46 "turn.proposed.delta",
47]);
48const transientNativeMethods = new Set([
49 "item/agentMessage/delta",
50 "item/commandExecution/outputDelta",
51 "item/fileChange/outputDelta",
52 "item/plan/delta",
53 "item/reasoning/summaryTextDelta",
54 "item/reasoning/textDelta",
55 "thread/realtime/outputAudio/delta",
56 "thread/realtime/transcript/delta",
57]);
58const transientAcpUpdates = new Set(["agent_message_chunk", "agent_thought_chunk"]);
59​
60export type EventNdjsonStream = "native" | "canonical" | "orchestration";
61​
62export interface EventNdjsonLogger {
63 readonly filePath: string;
64 readonly write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void>;
65 readonly close: () => Effect.Effect<void>;
67​
68export interface EventNdjsonLogStore {
69 readonly filePath: string;
70 readonly logger: (stream: EventNdjsonStream) => EventNdjsonLogger;
71 readonly close: () => Effect.Effect<void>;
73​
74export interface EventNdjsonLogStoreOptions {
75 readonly maxBytes?: number;
76 readonly maxFiles?: number;
77 readonly batchWindowMs?: number;
78 readonly maxTotalBytes?: number;
79 readonly maxAgeMs?: number;
80 readonly retentionCheckIntervalMs?: number;
81 readonly maxBufferedBytes?: number;
82 readonly maxBufferedRecords?: number;
83 readonly attribution?: ResourceAttribution["Service"];
85​
86export interface EventNdjsonLoggerOptions extends EventNdjsonLogStoreOptions {
87 readonly stream: EventNdjsonStream;
89​
90export class EventNdjsonLogConfigurationError extends Schema.TaggedErrorClass<EventNdjsonLogConfigurationError>()(
91 "EventNdjsonLogConfigurationError",
92 {
93 filePath: Schema.String,
94 option: Schema.String,
95 value: Schema.Number,
96 minimum: Schema.Number,
97 },
98) {
99 override get message(): string {
100 return `Provider event log option '${this.option}' must be an integer >= ${this.minimum}; received ${this.value} for '${this.filePath}'`;
101 }
103​
104export class EventNdjsonLogDirectoryError extends Schema.TaggedErrorClass<EventNdjsonLogDirectoryError>()(
105 "EventNdjsonLogDirectoryError",
106 {
107 directory: Schema.String,
108 cause: Schema.Defect(),
109 },
110) {
111 override get message(): string {
112 return `Failed to create provider event log directory '${this.directory}'`;
113 }
115​
116export type EventNdjsonLogStoreError =
117 | EventNdjsonLogConfigurationError
118 | EventNdjsonLogDirectoryError;
119​
120interface ResolvedOptions {
121 readonly maxBytes: number;
122 readonly maxFiles: number;
123 readonly batchWindowMs: number;
124 readonly maxTotalBytes: number;
125 readonly maxAgeMs: number;
126 readonly retentionCheckIntervalMs: number;
127 readonly maxBufferedBytes: number;
128 readonly maxBufferedRecords: number;
129 readonly attribution: ResourceAttribution["Service"] | undefined;
131​
132export interface PendingRecord {
133 readonly stream: EventNdjsonStream;
134 readonly threadSegment: string;
135 readonly line: string;
136 readonly bytes: number;
138​
139interface StoreState {
140 readonly pending: Array<PendingRecord>;
141 readonly pendingBytes: number;
142 readonly sinks: ReadonlyMap<string, RotatingFileSink>;
143 readonly flushScheduled: boolean;
144 readonly closed: boolean;
145 readonly lastRetentionAt: number;
147​
148interface AttributionSummary {
149 readonly stream: EventNdjsonStream;
150 readonly count: number;
151 readonly logicalWriteBytes: number;
153​
154interface FileOperationFailure {
155 readonly filePath: string;
156 readonly cause: unknown;
158​
159interface RetentionResult {
160 readonly failures: ReadonlyArray<FileOperationFailure>;
162​
163interface DrainResult {
164 readonly attributions: ReadonlyArray<AttributionSummary>;
165 readonly failures: ReadonlyArray<FileOperationFailure>;
167​
168function logWarning(message: string, context: Record<string, unknown>): Effect.Effect<void> {
169 return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE }));
171​
172function resolveThreadSegment(raw: string | null | undefined): string {
173 const normalized = typeof raw === "string" ? toSafeThreadAttachmentSegment(raw) : null;
174 return normalized ?? GLOBAL_THREAD_SEGMENT;
176​
177function resolveStreamLabel(stream: EventNdjsonStream): string {
178 return stream === "native" ? "NTIVE" : stream === "orchestration" ? "ORCH" : "CANON";
180​
181function providerLogPrefix(filePath: string): string {
182 const basename = NodePath.basename(filePath);
183 const extension = NodePath.extname(basename);
184 return `${extension.length > 0 ? basename.slice(0, -extension.length) : basename}.`;
186​
187function providerLogPath(directory: string, prefix: string, threadSegment: string): string {
188 return NodePath.join(directory, `${prefix}${threadSegment}.log`);
190​
191function shouldPersist(stream: EventNdjsonStream, event: unknown): boolean {
192 if (stream === "orchestration" || typeof event !== "object" || event === null) {
193 return true;
194 }
195 try {
196 const type = Reflect.get(event, "type");
197 if (typeof type === "string" && transientCanonicalEventTypes.has(type)) {
198 return false;
199 }
200 if (stream !== "native") return true;
201​
202 const nested = Reflect.get(event, "event");
203 const nativeEvent = typeof nested === "object" && nested !== null ? nested : event;
204 const method = Reflect.get(nativeEvent, "method");
205 if (
206 typeof method === "string" &&
207 (transientNativeMethods.has(method) ||
208 method.startsWith("claude/stream_event/content_block_delta/"))
209 ) {
210 return false;
211 }
212​
213 const nativeType = Reflect.get(nativeEvent, "type");
214 if (nativeType === "message.part.delta") return false;
215​
216 const payload = Reflect.get(nativeEvent, "payload");
217 if (typeof payload !== "object" || payload === null) return true;
218​
219 if (method === "session/update") {
220 const update = Reflect.get(payload, "update");
221 if (typeof update !== "object" || update === null) return true;
222 const updateType = Reflect.get(update, "sessionUpdate");
223 return typeof updateType !== "string" || !transientAcpUpdates.has(updateType);
224 }
225​
226 if (nativeType === "message.part.updated") {
227 const properties = Reflect.get(payload, "properties");
228 if (typeof properties !== "object" || properties === null) return true;
229 const part = Reflect.get(properties, "part");
230 if (typeof part !== "object" || part === null) return true;
231 const partType = Reflect.get(part, "type");
232 return partType !== "text" && partType !== "reasoning";
233 }
234​
235 return true;
236 } catch {
237 return true;
238 }
240​
241export function writeBatchedMessages(
242 sink: Pick<RotatingFileSink, "write">,
243 records: ReadonlyArray<PendingRecord>,
244 maxBytes: number,
245 onWritten: (records: ReadonlyArray<PendingRecord>) => void,
246): void {
247 let pendingRecords: Array<PendingRecord> = [];
248 let pendingBytes = 0;
249​
250 const flush = () => {
251 if (pendingRecords.length === 0) return;
252 const writtenRecords = pendingRecords;
253 sink.write(writtenRecords.map((record) => record.line).join(""));
254 onWritten(writtenRecords);
255 pendingRecords = [];
256 pendingBytes = 0;
257 };
258​
259 for (const record of records) {
260 if (pendingBytes > 0 && pendingBytes + record.bytes > maxBytes) {
261 flush();
262 }
263 pendingRecords.push(record);
264 pendingBytes += record.bytes;
265 if (pendingBytes >= maxBytes) {
266 flush();
267 }
268 }
269 flush();
271​
272function isProviderLogFile(filePath: string, fileName: string, filePrefix: string): boolean {
273 if (!/\.log(?:\.\d+)?$/u.test(fileName)) return false;
274 if (fileName.startsWith(filePrefix)) return true;
275​
276 const descriptor = NodeFS.openSync(filePath, "r");
277 try {
278 const header = Buffer.alloc(256);
279 const bytesRead = NodeFS.readSync(descriptor, header, 0, header.byteLength, 0);
280 return /^\[[^\]\r\n]+\] (?:NTIVE|CANON|ORCH): /u.test(header.toString("utf8", 0, bytesRead));
281 } finally {
282 NodeFS.closeSync(descriptor);
283 }
285​
286function enforceRetention(input: {
287 readonly directory: string;
288 readonly maxTotalBytes: number;
289 readonly maxAgeMs: number;
290 readonly activeFilePaths: ReadonlySet<string>;
291 readonly filePrefix: string;
292 readonly now: number;
293}): RetentionResult {
294 const failures: Array<FileOperationFailure> = [];
295 const files: Array<{ filePath: string; mtimeMs: number; size: number }> = [];
296​
297 let entries: ReadonlyArray<NodeFS.Dirent>;
298 try {
299 entries = NodeFS.readdirSync(input.directory, { withFileTypes: true });
300 } catch (cause) {
301 return { failures: [{ filePath: input.directory, cause }] };
302 }
303​
304 for (const entry of entries) {
305 if (!entry.isFile()) continue;
306 const filePath = NodePath.join(input.directory, entry.name);
307 try {
308 if (!isProviderLogFile(filePath, entry.name, input.filePrefix)) continue;
309 const stat = NodeFS.statSync(filePath);
310 files.push({ filePath, mtimeMs: stat.mtimeMs, size: stat.size });
311 } catch (cause) {
312 failures.push({ filePath, cause });
313 }
314 }
315​
316 let totalBytes = files.reduce((total, file) => total + file.size, 0);
317 const remove = (file: (typeof files)[number]) => {
318 if (input.activeFilePaths.has(file.filePath)) return false;
319 try {
320 NodeFS.rmSync(file.filePath, { force: true });
321 totalBytes -= file.size;
322 return true;
323 } catch (cause) {
324 failures.push({ filePath: file.filePath, cause });
325 return false;
326 }
327 };
328​
329 const retained = files.filter((file) => {
330 if (input.now - file.mtimeMs <= input.maxAgeMs) return true;
331 return !remove(file);
332 });
333​
334 for (const file of retained.toSorted(
335 (left, right) => left.mtimeMs - right.mtimeMs || left.filePath.localeCompare(right.filePath),
336 )) {
337 if (totalBytes <= input.maxTotalBytes) break;
338 remove(file);
339 }
340​
341 return { failures };
343​
344function validateOption(input: {
345 readonly filePath: string;
346 readonly option: string;
347 readonly value: number;
348 readonly minimum: number;
349}): EventNdjsonLogConfigurationError | undefined {
350 if (Number.isInteger(input.value) && input.value >= input.minimum) return undefined;
351 return new EventNdjsonLogConfigurationError(input);
353​
354function resolveOptions(
355 filePath: string,
356 options: EventNdjsonLogStoreOptions,
357): Effect.Effect<ResolvedOptions, EventNdjsonLogConfigurationError> {
358 const resolved = {
359 maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,
360 maxFiles: options.maxFiles ?? DEFAULT_MAX_FILES,
361 batchWindowMs: options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS,
362 maxTotalBytes: options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,
363 maxAgeMs: options.maxAgeMs ?? DEFAULT_MAX_AGE_MS,
364 retentionCheckIntervalMs:
365 options.retentionCheckIntervalMs ?? DEFAULT_RETENTION_CHECK_INTERVAL_MS,
366 maxBufferedBytes: options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES,
367 maxBufferedRecords: options.maxBufferedRecords ?? DEFAULT_MAX_BUFFERED_RECORDS,
368 attribution: options.attribution,
369 } satisfies ResolvedOptions;
370​
371 const validations = [
372 ["maxBytes", resolved.maxBytes, 1],
373 ["maxFiles", resolved.maxFiles, 1],
374 ["batchWindowMs", resolved.batchWindowMs, 0],
375 ["maxTotalBytes", resolved.maxTotalBytes, 1],
376 ["maxAgeMs", resolved.maxAgeMs, 1],
377 ["retentionCheckIntervalMs", resolved.retentionCheckIntervalMs, 1],
378 ["maxBufferedBytes", resolved.maxBufferedBytes, 1],
379 ["maxBufferedRecords", resolved.maxBufferedRecords, 1],
380 ] as const;
381​
382 for (const [option, value, minimum] of validations) {
383 const error = validateOption({ filePath, option, value, minimum });
384 if (error) return Effect.fail(error);
385 }
386 return Effect.succeed(resolved);
388​
389function drainPending(input: {
390 readonly directory: string;
391 readonly options: ResolvedOptions;
392 readonly state: StoreState;
393 readonly filePrefix: string;
394 readonly now: number;
395 readonly timerFired: boolean;
396 readonly close: boolean;
397}): readonly [DrainResult, StoreState] {
398 if (input.state.closed) {
399 return [{ attributions: [], failures: [] }, input.state];
400 }
401​
402 const sinks = new Map(input.state.sinks);
403 const failures: Array<FileOperationFailure> = [];
404 const attributionByStream = new Map<
405 EventNdjsonStream,
406 { count: number; logicalWriteBytes: number }
407 >();
408 const recordsBySegment = new Map<string, Array<PendingRecord>>();
409​
410 for (const record of input.state.pending) {
411 const records = recordsBySegment.get(record.threadSegment) ?? [];
412 records.push(record);
413 recordsBySegment.set(record.threadSegment, records);
414 }
415​
416 for (const [threadSegment, records] of recordsBySegment) {
417 const filePath = providerLogPath(input.directory, input.filePrefix, threadSegment);
418 let sink = sinks.get(threadSegment);
419 if (!sink) {
420 try {
421 sink = new RotatingFileSink({
422 filePath,
423 maxBytes: input.options.maxBytes,
424 maxFiles: input.options.maxFiles,
425 throwOnError: true,
426 });
427 sinks.set(threadSegment, sink);
428 } catch (cause) {
429 failures.push({ filePath, cause });
430 continue;
431 }
432 }
433​
434 try {
435 writeBatchedMessages(sink, records, input.options.maxBytes, (writtenRecords) => {
436 for (const record of writtenRecords) {
437 const current = attributionByStream.get(record.stream) ?? {
438 count: 0,
439 logicalWriteBytes: 0,
440 };
441 attributionByStream.set(record.stream, {
442 count: current.count + 1,
443 logicalWriteBytes: current.logicalWriteBytes + record.bytes,
444 });
445 }
446 });
447 } catch (cause) {
448 sinks.delete(threadSegment);
449 failures.push({ filePath, cause });
450 }
451 }
452​
453 const retentionDue =
454 input.now - input.state.lastRetentionAt >= input.options.retentionCheckIntervalMs;
455 const retention = retentionDue
456 ? enforceRetention({
457 directory: input.directory,
458 maxTotalBytes: input.options.maxTotalBytes,
459 maxAgeMs: input.options.maxAgeMs,
460 activeFilePaths: new Set(
461 Array.from(sinks.keys(), (threadSegment) =>
462 providerLogPath(input.directory, input.filePrefix, threadSegment),
463 ),
464 ),
465 filePrefix: input.filePrefix,
466 now: input.now,
467 })
468 : { failures: [] };
469​
470 return [
471 {
472 attributions: Array.from(attributionByStream, ([stream, value]) => ({
473 stream,
474 ...value,
475 })),
476 failures: [...failures, ...retention.failures],
477 },
478 {
479 pending: [],
480 pendingBytes: 0,
481 sinks,
482 flushScheduled: input.timerFired ? false : input.state.flushScheduled,
483 closed: input.close,
484 lastRetentionAt: retentionDue ? input.now : input.state.lastRetentionAt,
485 },
486 ];
488​
489const serializeEvent = Effect.fnUntraced(function* (event: unknown) {
490 return yield* encodeUnknownJsonString(event).pipe(
491 Effect.catch((error) =>
492 logWarning("failed to serialize provider event log record", {
493 errorTag: errorTag(error),
494 }).pipe(Effect.as(undefined)),
495 ),
496 );
497});
498​
499export const makeEventNdjsonLogStore = Effect.fnUntraced(function* (
500 filePath: string,
501 options: EventNdjsonLogStoreOptions = {},
502): Effect.fn.Return<EventNdjsonLogStore, EventNdjsonLogStoreError> {
503 const resolved = yield* resolveOptions(filePath, options);
504 const directory = NodePath.dirname(filePath);
505 const filePrefix = providerLogPrefix(filePath);
506​
507 yield* Effect.try({
508 try: () => NodeFS.mkdirSync(directory, { recursive: true }),
509 catch: (cause) => new EventNdjsonLogDirectoryError({ directory, cause }),
510 });
511​
512 const initializedAt = yield* Clock.currentTimeMillis;
513 const initialRetention = yield* Effect.sync(() =>
514 enforceRetention({
515 directory,
516 maxTotalBytes: resolved.maxTotalBytes,
517 maxAgeMs: resolved.maxAgeMs,
518 activeFilePaths: new Set(),
519 filePrefix,
520 now: initializedAt,
521 }),
522 );
523 for (const failure of initialRetention.failures) {
524 yield* logWarning("provider event log retention failed", {
525 filePath: failure.filePath,
526 errorTag: errorTag(failure.cause),
527 });
528 }
529​
530 const stateRef = yield* SynchronizedRef.make<StoreState>({
531 pending: [],
532 pendingBytes: 0,
533 sinks: new Map(),
534 flushScheduled: false,
535 closed: false,
536 lastRetentionAt: initializedAt,
537 });
538 const timerScope = yield* Scope.make();
539​
540 const flush = Effect.fnUntraced(function* (timerFired: boolean, close: boolean) {
541 const startedAt = yield* Clock.currentTimeMillis;
542 const result = yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
543 Effect.sync(() =>
544 drainPending({
545 directory,
546 options: resolved,
547 state,
548 filePrefix,
549 now: startedAt,
550 timerFired,
551 close,
552 }),
553 ),
554 );
555​
556 for (const failure of result.failures) {
557 yield* logWarning("provider event log write or retention failed", {
558 filePath: failure.filePath,
559 errorTag: errorTag(failure.cause),
560 });
561 }
562​
563 if (resolved.attribution && result.attributions.length > 0) {
564 const completedAt = yield* Clock.currentTimeMillis;
565 const durationMs = Math.max(0, completedAt - startedAt);
566 const totalBytes = result.attributions.reduce(
567 (total, entry) => total + entry.logicalWriteBytes,
568 0,
569 );
570 yield* Effect.forEach(
571 result.attributions,
572 (entry) =>
573 resolved.attribution?.record({
574 component: "provider-event-log",
575 operation: `${entry.stream}.append`,
576 logicalWriteBytes: entry.logicalWriteBytes,
577 count: entry.count,
578 durationMs:
579 totalBytes === 0
580 ? 0
581 : Math.round(durationMs * (entry.logicalWriteBytes / totalBytes)),
582 }) ?? Effect.void,
583 { discard: true },
584 );
585 }
586 });
587​
588 const scheduleFlush = Effect.fnUntraced(function* () {
589 yield* Effect.forkIn(
590 Effect.sleep(resolved.batchWindowMs).pipe(Effect.andThen(flush(true, false))),
591 timerScope,
592 { startImmediately: true },
593 );
594 });
595​
596 const close = Effect.fnUntraced(function* () {
597 yield* flush(false, true);
598 yield* Scope.close(timerScope, Exit.void);
599 });
600​
601 const loggerViews = new Map<EventNdjsonStream, EventNdjsonLogger>();
602 const logger = (stream: EventNdjsonStream): EventNdjsonLogger => {
603 const existing = loggerViews.get(stream);
604 if (existing) return existing;
605​
606 const write = Effect.fnUntraced(function* (event: unknown, threadId: ThreadId | null) {
607 if (!shouldPersist(stream, event)) return;
608 const payload = yield* serializeEvent(event);
609 if (payload === undefined) return;
610​
611 const observedAt = yield* DateTime.now.pipe(Effect.map(DateTime.formatIso));
612 const line = `[${observedAt}] ${resolveStreamLabel(stream)}: ${payload}\n`;
613 const bytes = Buffer.byteLength(line);
614 const action = yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
615 if (state.closed) {
616 return Effect.succeed([{ flush: false }, state] as const);
617 }
618 const pending = state.pending;
619 pending.push({ stream, threadSegment: resolveThreadSegment(threadId), line, bytes });
620 const pendingBytes = state.pendingBytes + bytes;
621 const flush =
622 resolved.batchWindowMs === 0 ||
623 pending.length >= resolved.maxBufferedRecords ||
624 pendingBytes >= resolved.maxBufferedBytes;
625 const schedule = !flush && !state.flushScheduled;
626 const nextState = {
627 ...state,
628 pending,
629 pendingBytes,
630 flushScheduled: state.flushScheduled || schedule,
631 };
632 return (schedule ? scheduleFlush() : Effect.void).pipe(
633 Effect.as([{ flush }, nextState] as const),
634 );
635 }).pipe(Effect.uninterruptible);
636​
637 if (action.flush) {
638 yield* flush(false, false);
639 }
640 });
641​
642 const view = { filePath, write, close: () => Effect.void } satisfies EventNdjsonLogger;
643 loggerViews.set(stream, view);
644 return view;
645 };
646​
647 return { filePath, logger, close } satisfies EventNdjsonLogStore;
648});
649​
650export const makeEventNdjsonLogger = Effect.fnUntraced(function* (
651 filePath: string,
652 options: EventNdjsonLoggerOptions,
653): Effect.fn.Return<EventNdjsonLogger | undefined> {
654 const store = yield* makeEventNdjsonLogStore(filePath, options).pipe(
655 Effect.catch((error) =>
656 logWarning(error.message, { error }).pipe(
657 Effect.as<EventNdjsonLogStore | undefined>(undefined),
658 ),
659 ),
660 );
661 if (!store) return undefined;
662 return { ...store.logger(options.stream), close: store.close };
663});