diff --git a/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts b/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts index 71ac7831ed..6c2bb1f1cd 100644 --- a/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts +++ b/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts @@ -5,13 +5,25 @@ import * as NodePath from "node:path"; import { ThreadId } from "@t3tools/contracts"; import { assert, describe, it } from "@effect/vitest"; +import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import * as Logger from "effect/Logger"; import * as Schema from "effect/Schema"; +import * as TestClock from "effect/testing/TestClock"; -import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts"; +import { makeEventNdjsonLogger, makeEventNdjsonLogStore } from "./EventNdjsonLogger.ts"; const encodeUnknownJson = Schema.encodeUnknownSync(Schema.UnknownFromJsonString); +const decodeOmittedRecord = Schema.decodeUnknownSync( + Schema.fromJsonString( + Schema.Struct({ + _tag: Schema.String, + reason: Schema.String, + originalBytes: Schema.Number, + eventType: Schema.NullOr(Schema.String), + }), + ), +); function parseLogLine(line: string) { const match = /^\[([^\]]+)\] ([A-Z]+): (.+)$/.exec(line); @@ -55,6 +67,7 @@ describe("EventNdjsonLogger", () => { assert.exists(logger); if (!logger) return; yield* logger.write(circular, ThreadId.make("thread-1")); + yield* logger.close(); const serialized = encodeUnknownJson(messages); assert.notInclude(serialized, secret); @@ -190,25 +203,99 @@ describe("EventNdjsonLogger", () => { }), ); + it.effect("shares one thread writer across native and canonical streams", () => + Effect.gen(function* () { + const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); + const basePath = NodePath.join(tempDir, "events.log"); + + try { + const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 }); + const native = store.logger("native"); + const canonical = store.logger("canonical"); + const threadId = ThreadId.make("thread-shared"); + + yield* native.write({ id: "native-event" }, threadId); + yield* canonical.write({ type: "item.completed", id: "canonical-event" }, threadId); + yield* store.close(); + + const lines = NodeFS.readFileSync(NodePath.join(tempDir, "thread-shared.log"), "utf8") + .trim() + .split("\n") + .map(parseLogLine); + + assert.deepEqual( + lines.map(({ stream, payload }) => ({ stream, payload })), + [ + { stream: "NTIVE", payload: '{"id":"native-event"}' }, + { + stream: "CANON", + payload: '{"type":"item.completed","id":"canonical-event"}', + }, + ], + ); + } finally { + NodeFS.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ); + + it.effect("drops transient canonical events before serialization", () => + Effect.gen(function* () { + const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); + const basePath = NodePath.join(tempDir, "events.log"); + + try { + const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 }); + const canonical = store.logger("canonical"); + const native = store.logger("native"); + const threadId = ThreadId.make("thread-filtered"); + const circularDelta: Record = { type: "content.delta" }; + circularDelta["self"] = circularDelta; + + yield* canonical.write(circularDelta, threadId); + yield* canonical.write({ type: "item.completed", id: "final" }, threadId); + yield* native.write({ type: "content.delta", id: "native-delta" }, threadId); + yield* store.close(); + + const lines = NodeFS.readFileSync(NodePath.join(tempDir, "thread-filtered.log"), "utf8") + .trim() + .split("\n") + .map(parseLogLine); + + assert.deepEqual( + lines.map(({ stream, payload }) => ({ stream, payload })), + [ + { stream: "CANON", payload: '{"type":"item.completed","id":"final"}' }, + { stream: "NTIVE", payload: '{"type":"content.delta","id":"native-delta"}' }, + ], + ); + } finally { + NodeFS.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ); + it.effect("rotates per-thread files when max size is exceeded", () => Effect.gen(function* () { const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); const basePath = NodePath.join(tempDir, "provider-native.ndjson"); try { - const logger = yield* makeEventNdjsonLogger(basePath, { - stream: "native", - maxBytes: 120, + const store = yield* makeEventNdjsonLogStore(basePath, { + maxBytes: 512, maxFiles: 2, + batchWindowMs: 0, + maxBufferedBytes: 256, + maxRecordBytes: 256, }); - assert.notEqual(logger, undefined); - if (!logger) { - return; - } + const native = store.logger("native"); + const canonical = store.logger("canonical"); for (let index = 0; index < 10; index += 1) { + const logger = index % 2 === 0 ? native : canonical; yield* logger.write( { + type: "session.started", threadId: "provider-thread-rotate", id: `evt-${index}`, payload: "x".repeat(40), @@ -216,7 +303,7 @@ describe("EventNdjsonLogger", () => { ThreadId.make("thread-rotate"), ); } - yield* logger.close(); + yield* store.close(); const fileStem = "thread-rotate.log"; const matchingFiles = NodeFS.readdirSync(tempDir) @@ -235,6 +322,129 @@ describe("EventNdjsonLogger", () => { matchingFiles.some((entry) => entry === `${fileStem}.3`), false, ); + for (const entry of matchingFiles) { + assert.isAtMost(NodeFS.statSync(NodePath.join(tempDir, entry)).size, 512); + } + } finally { + NodeFS.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ); + + it.effect("replaces oversized records with a bounded omission marker", () => + Effect.gen(function* () { + const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); + const basePath = NodePath.join(tempDir, "events.log"); + + try { + const store = yield* makeEventNdjsonLogStore(basePath, { + maxBytes: 512, + maxRecordBytes: 256, + maxBufferedBytes: 256, + batchWindowMs: 0, + }); + yield* store + .logger("canonical") + .write( + { type: "item.completed", payload: "x".repeat(2_000) }, + ThreadId.make("thread-oversized"), + ); + yield* store + .logger("canonical") + .write( + { type: "x".repeat(1_000), payload: "x".repeat(2_000) }, + ThreadId.make("thread-oversized-type"), + ); + yield* store.close(); + + const filePath = NodePath.join(tempDir, "thread-oversized.log"); + assert.isAtMost(NodeFS.statSync(filePath).size, 256); + const line = parseLogLine(NodeFS.readFileSync(filePath, "utf8").trim()); + const payload = decodeOmittedRecord(line.payload); + assert.equal(payload._tag, "ProviderEventLogRecordOmitted"); + assert.equal(payload.eventType, "item.completed"); + assert.isAbove(payload.originalBytes, 2_000); + + const longTypeFilePath = NodePath.join(tempDir, "thread-oversized-type.log"); + assert.isAtMost(NodeFS.statSync(longTypeFilePath).size, 256); + const longTypeLine = parseLogLine(NodeFS.readFileSync(longTypeFilePath, "utf8").trim()); + const longTypePayload = decodeOmittedRecord(longTypeLine.payload); + assert.equal(longTypePayload.eventType, null); + } finally { + NodeFS.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ); + + it.effect("enforces aggregate age and byte retention on startup", () => + Effect.gen(function* () { + const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); + const basePath = NodePath.join(tempDir, "events.log"); + const expiredPath = NodePath.join(tempDir, "expired.log"); + const oldPath = NodePath.join(tempDir, "old.log"); + const newPath = NodePath.join(tempDir, "new.log"); + const ignoredPath = NodePath.join(tempDir, "ignored.txt"); + + try { + yield* TestClock.setTime(1_800_000_000_000); + const now = yield* Clock.currentTimeMillis; + for (const filePath of [expiredPath, oldPath, newPath, ignoredPath]) { + NodeFS.writeFileSync(filePath, "x".repeat(400)); + } + NodeFS.utimesSync(expiredPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000); + NodeFS.utimesSync(oldPath, (now - 5_000) / 1_000, (now - 5_000) / 1_000); + NodeFS.utimesSync(newPath, now / 1_000, now / 1_000); + + const store = yield* makeEventNdjsonLogStore(basePath, { + maxAgeMs: 10_000, + maxTotalBytes: 600, + }); + yield* store.close(); + + assert.equal(NodeFS.existsSync(expiredPath), false); + assert.equal(NodeFS.existsSync(oldPath), false); + assert.equal(NodeFS.existsSync(newPath), true); + assert.equal(NodeFS.existsSync(ignoredPath), true); + } finally { + NodeFS.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ); + + it.effect("keeps aggregate provider logs within the byte budget while writing", () => + Effect.gen(function* () { + const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); + const basePath = NodePath.join(tempDir, "events.log"); + + try { + const store = yield* makeEventNdjsonLogStore(basePath, { + maxBytes: 512, + maxFiles: 2, + maxTotalBytes: 1_200, + maxBufferedBytes: 256, + maxRecordBytes: 256, + batchWindowMs: 0, + }); + + for (let index = 0; index < 30; index += 1) { + yield* store.logger(index % 2 === 0 ? "native" : "canonical").write( + { + type: "item.completed", + id: `evt-${index}`, + payload: "x".repeat(80), + }, + ThreadId.make(`thread-${index % 4}`), + ); + } + yield* store.close(); + + const totalBytes = NodeFS.readdirSync(tempDir, { withFileTypes: true }) + .filter((entry) => entry.isFile() && /\.log(?:\.\d+)?$/u.test(entry.name)) + .reduce( + (total, entry) => total + NodeFS.statSync(NodePath.join(tempDir, entry.name)).size, + 0, + ); + assert.isAtMost(totalBytes, 1_200); } finally { NodeFS.rmSync(tempDir, { recursive: true, force: true }); } diff --git a/apps/server/src/provider/Layers/EventNdjsonLogger.ts b/apps/server/src/provider/Layers/EventNdjsonLogger.ts index 8c20a4c193..ab950340eb 100644 --- a/apps/server/src/provider/Layers/EventNdjsonLogger.ts +++ b/apps/server/src/provider/Layers/EventNdjsonLogger.ts @@ -1,10 +1,9 @@ // @effect-diagnostics nodeBuiltinImport:off /** - * Provider event logger helper. + * Best-effort provider event logging with one shared writer store. * - * Best-effort writer for observability logs. Each record is formatted as a - * single effect-style text line in a thread-scoped file. Failures are - * downgraded to warnings so provider runtime behavior is unaffected. + * Native and canonical views share batching, rotation, and retention state so + * they cannot race while appending to the same thread-scoped file. */ import * as NodeFS from "node:fs"; import * as NodePath from "node:path"; @@ -12,84 +11,429 @@ import * as NodePath from "node:path"; import type { ThreadId } from "@t3tools/contracts"; import { RotatingFileSink } from "@t3tools/shared/logging"; import { errorTag } from "@t3tools/shared/observability"; +import * as Clock from "effect/Clock"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; -import * as Logger from "effect/Logger"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as SynchronizedRef from "effect/SynchronizedRef"; import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts"; -const DEFAULT_MAX_BYTES = 10 * 1024 * 1024; +const MEBIBYTE = 1024 * 1024; +const DAY_MS = 24 * 60 * 60 * 1_000; +const MIN_RECORD_BYTES = 256; +const DEFAULT_MAX_BYTES = 10 * MEBIBYTE; const DEFAULT_MAX_FILES = 10; -const DEFAULT_BATCH_WINDOW_MS = 200; +const DEFAULT_BATCH_WINDOW_MS = 1_000; +const DEFAULT_MAX_TOTAL_BYTES = 512 * MEBIBYTE; +const DEFAULT_MAX_AGE_MS = 14 * DAY_MS; +const DEFAULT_RETENTION_CHECK_INTERVAL_MS = 5 * 60 * 1_000; +const DEFAULT_MAX_BUFFERED_BYTES = MEBIBYTE; +const DEFAULT_MAX_BUFFERED_RECORDS = 512; +const DEFAULT_MAX_RECORD_BYTES = MEBIBYTE; +const DEFAULT_MAX_CACHED_SINKS = 64; const GLOBAL_THREAD_SEGMENT = "_global"; const LOG_SCOPE = "provider-observability"; +const PROVIDER_LOG_FILE_PATTERN = /\.log(?:\.\d+)?$/u; const encodeUnknownJsonString = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString); +const transientCanonicalEventTypes = new Set([ + "content.delta", + "hook.progress", + "item.updated", + "task.progress", + "thread.realtime.audio.delta", + "tool.progress", + "turn.proposed.delta", +]); + export type EventNdjsonStream = "native" | "canonical" | "orchestration"; export interface EventNdjsonLogger { readonly filePath: string; - write: (event: unknown, threadId: ThreadId | null) => Effect.Effect; - close: () => Effect.Effect; + readonly write: (event: unknown, threadId: ThreadId | null) => Effect.Effect; + readonly close: () => Effect.Effect; } -export interface EventNdjsonLoggerOptions { - readonly stream: EventNdjsonStream; +export interface EventNdjsonLogStore { + readonly filePath: string; + readonly logger: (stream: EventNdjsonStream) => EventNdjsonLogger; + readonly close: () => Effect.Effect; +} + +export interface EventNdjsonLogStoreOptions { readonly maxBytes?: number; readonly maxFiles?: number; readonly batchWindowMs?: number; + readonly maxTotalBytes?: number; + readonly maxAgeMs?: number; + readonly retentionCheckIntervalMs?: number; + readonly maxBufferedBytes?: number; + readonly maxBufferedRecords?: number; + readonly maxRecordBytes?: number; + readonly maxCachedSinks?: number; } -interface ThreadWriter { - writeMessage: (message: string) => Effect.Effect; - close: () => Effect.Effect; +export interface EventNdjsonLoggerOptions extends EventNdjsonLogStoreOptions { + readonly stream: EventNdjsonStream; } -interface LoggerState { - readonly threadWriters: Map; - readonly failedSegments: Set; +export class EventNdjsonLogConfigurationError extends Schema.TaggedErrorClass()( + "EventNdjsonLogConfigurationError", + { + filePath: Schema.String, + option: Schema.String, + value: Schema.Number, + minimum: Schema.Number, + }, +) { + override get message(): string { + return `Provider event log option '${this.option}' must be an integer >= ${this.minimum}; received ${this.value} for '${this.filePath}'`; + } } -function logWarning(message: string, context: Record): Effect.Effect { +export class EventNdjsonLogDirectoryError extends Schema.TaggedErrorClass()( + "EventNdjsonLogDirectoryError", + { + directory: Schema.String, + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Failed to create provider event log directory '${this.directory}'`; + } +} + +export type EventNdjsonLogStoreError = + | EventNdjsonLogConfigurationError + | EventNdjsonLogDirectoryError; + +interface ResolvedOptions { + readonly maxBytes: number; + readonly maxFiles: number; + readonly batchWindowMs: number; + readonly maxTotalBytes: number; + readonly maxAgeMs: number; + readonly retentionCheckIntervalMs: number; + readonly maxBufferedBytes: number; + readonly maxBufferedRecords: number; + readonly maxRecordBytes: number; + readonly maxCachedSinks: number; +} + +interface PendingRecord { + readonly threadSegment: string; + readonly line: string; + readonly bytes: number; +} + +interface StoreState { + readonly pending: ReadonlyArray; + readonly pendingBytes: number; + readonly sinks: ReadonlyMap; + readonly closed: boolean; + readonly lastRetentionAt: number; + readonly retainedBytesEstimate: number; +} + +interface FileOperationFailure { + readonly filePath: string; + readonly cause: unknown; +} + +interface RetentionResult { + readonly failures: ReadonlyArray; + readonly removedCount: number; + readonly totalBytes: number; +} + +interface DrainResult { + readonly failures: ReadonlyArray; +} + +function logWarning(message: string, context: Record) { return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE })); } -function resolveThreadSegment(raw: string | null | undefined): string { +function resolveThreadSegment(raw: string | null | undefined) { const normalized = typeof raw === "string" ? toSafeThreadAttachmentSegment(raw) : null; return normalized ?? GLOBAL_THREAD_SEGMENT; } -function formatLoggerMessage(message: unknown): string { - if (Array.isArray(message)) { - return message.map((part) => (typeof part === "string" ? part : String(part))).join(" "); +function resolveStreamLabel(stream: EventNdjsonStream) { + return stream === "native" ? "NTIVE" : "CANON"; +} + +function shouldPersist(stream: EventNdjsonStream, event: unknown) { + if (stream !== "canonical" || typeof event !== "object" || event === null) { + return true; } - return typeof message === "string" ? message : String(message); + const type = Reflect.get(event, "type"); + return typeof type !== "string" || !transientCanonicalEventTypes.has(type); } -function makeLineLogger(streamLabel: string): Logger.Logger { - return Logger.make( - ({ date, message }) => - `[${date.toISOString()}] ${streamLabel}: ${formatLoggerMessage(message)}\n`, - ); +function eventType(event: unknown) { + if (typeof event !== "object" || event === null) return null; + const type = Reflect.get(event, "type"); + return typeof type === "string" ? type.slice(0, 128) : null; } -function resolveStreamLabel(stream: EventNdjsonStream): string { - switch (stream) { - case "native": - return "NTIVE"; - case "canonical": - case "orchestration": - default: - return "CANON"; +function formatRecordLine(input: { + readonly stream: EventNdjsonStream; + readonly event: unknown; + readonly observedAt: string; + readonly payload: string; + readonly maxRecordBytes: number; +}) { + const prefix = `[${input.observedAt}] ${resolveStreamLabel(input.stream)}: `; + const line = `${prefix}${input.payload}\n`; + const bytes = Buffer.byteLength(line); + if (bytes <= input.maxRecordBytes) { + return { line, bytes }; } + + const omittedPayload = (type: string | null) => + JSON.stringify({ + _tag: "ProviderEventLogRecordOmitted", + reason: "record_too_large", + originalBytes: bytes, + eventType: type, + }); + let omittedLine = `${prefix}${omittedPayload(eventType(input.event))}\n`; + if (Buffer.byteLength(omittedLine) > input.maxRecordBytes) { + omittedLine = `${prefix}${omittedPayload(null)}\n`; + } + return { + line: omittedLine, + bytes: Buffer.byteLength(omittedLine), + }; } -const toLogMessage = Effect.fn("toLogMessage")(function* ( - event: unknown, -): Effect.fn.Return { +function writeBatchedRecords( + sink: RotatingFileSink, + records: ReadonlyArray, + maxChunkBytes: number, +) { + let pendingLines: Array = []; + let pendingBytes = 0; + + const flush = () => { + if (pendingLines.length === 0) return; + sink.write(pendingLines.join("")); + pendingLines = []; + pendingBytes = 0; + }; + + for (const record of records) { + if (pendingBytes > 0 && pendingBytes + record.bytes > maxChunkBytes) { + flush(); + } + pendingLines.push(record.line); + pendingBytes += record.bytes; + if (pendingBytes >= maxChunkBytes) { + flush(); + } + } + flush(); +} + +function enforceRetention(input: { + readonly directory: string; + readonly maxTotalBytes: number; + readonly maxAgeMs: number; + readonly now: number; +}): RetentionResult { + const failures: Array = []; + const files: Array<{ filePath: string; mtimeMs: number; size: number }> = []; + + let entries: ReadonlyArray; + try { + entries = NodeFS.readdirSync(input.directory, { withFileTypes: true }); + } catch (cause) { + return { + failures: [{ filePath: input.directory, cause }], + removedCount: 0, + totalBytes: input.maxTotalBytes + 1, + }; + } + + for (const entry of entries) { + if (!entry.isFile() || !PROVIDER_LOG_FILE_PATTERN.test(entry.name)) continue; + const filePath = NodePath.join(input.directory, entry.name); + try { + const stat = NodeFS.statSync(filePath); + files.push({ filePath, mtimeMs: stat.mtimeMs, size: stat.size }); + } catch (cause) { + failures.push({ filePath, cause }); + } + } + + let totalBytes = files.reduce((total, file) => total + file.size, 0); + let removedCount = 0; + const remove = (file: (typeof files)[number]) => { + try { + NodeFS.rmSync(file.filePath, { force: true }); + totalBytes -= file.size; + removedCount += 1; + return true; + } catch (cause) { + failures.push({ filePath: file.filePath, cause }); + return false; + } + }; + + const retained = files.filter((file) => { + if (input.now - file.mtimeMs <= input.maxAgeMs) return true; + return !remove(file); + }); + + for (const file of retained.toSorted( + (left, right) => left.mtimeMs - right.mtimeMs || left.filePath.localeCompare(right.filePath), + )) { + if (totalBytes <= input.maxTotalBytes) break; + remove(file); + } + + return { failures, removedCount, totalBytes }; +} + +function validateOption(input: { + readonly filePath: string; + readonly option: string; + readonly value: number; + readonly minimum: number; +}) { + if (Number.isInteger(input.value) && input.value >= input.minimum) return undefined; + return new EventNdjsonLogConfigurationError(input); +} + +function resolveOptions(filePath: string, options: EventNdjsonLogStoreOptions) { + const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES; + const maxBufferedBytes = options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES; + const requestedMaxRecordBytes = options.maxRecordBytes ?? DEFAULT_MAX_RECORD_BYTES; + const resolved = { + maxBytes, + maxFiles: options.maxFiles ?? DEFAULT_MAX_FILES, + batchWindowMs: options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS, + maxTotalBytes: options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES, + maxAgeMs: options.maxAgeMs ?? DEFAULT_MAX_AGE_MS, + retentionCheckIntervalMs: + options.retentionCheckIntervalMs ?? DEFAULT_RETENTION_CHECK_INTERVAL_MS, + maxBufferedBytes, + maxBufferedRecords: options.maxBufferedRecords ?? DEFAULT_MAX_BUFFERED_RECORDS, + maxRecordBytes: Math.min(requestedMaxRecordBytes, maxBytes, maxBufferedBytes), + maxCachedSinks: options.maxCachedSinks ?? DEFAULT_MAX_CACHED_SINKS, + } satisfies ResolvedOptions; + + const validations = [ + ["maxBytes", maxBytes, MIN_RECORD_BYTES], + ["maxFiles", resolved.maxFiles, 1], + ["batchWindowMs", resolved.batchWindowMs, 0], + ["maxTotalBytes", resolved.maxTotalBytes, 1], + ["maxAgeMs", resolved.maxAgeMs, 1], + ["retentionCheckIntervalMs", resolved.retentionCheckIntervalMs, 1], + ["maxBufferedBytes", maxBufferedBytes, MIN_RECORD_BYTES], + ["maxBufferedRecords", resolved.maxBufferedRecords, 1], + ["maxRecordBytes", requestedMaxRecordBytes, MIN_RECORD_BYTES], + ["maxCachedSinks", resolved.maxCachedSinks, 1], + ] as const; + + for (const [option, value, minimum] of validations) { + const error = validateOption({ filePath, option, value, minimum }); + if (error) return Effect.fail(error); + } + return Effect.succeed(resolved); +} + +function drainPending(input: { + readonly directory: string; + readonly options: ResolvedOptions; + readonly state: StoreState; + readonly now: number; + readonly close: boolean; +}): readonly [DrainResult, StoreState] { + if (input.state.closed) { + return [{ failures: [] }, input.state]; + } + + let sinks = new Map(input.state.sinks); + const failures: Array = []; + const recordsBySegment = new Map>(); + + for (const record of input.state.pending) { + const records = recordsBySegment.get(record.threadSegment) ?? []; + records.push(record); + recordsBySegment.set(record.threadSegment, records); + } + + let writtenBytes = 0; + for (const [threadSegment, records] of recordsBySegment) { + const filePath = NodePath.join(input.directory, `${threadSegment}.log`); + let sink = sinks.get(threadSegment); + try { + if (!sink) { + sink = new RotatingFileSink({ + filePath, + maxBytes: input.options.maxBytes, + maxFiles: input.options.maxFiles, + throwOnError: true, + }); + } + sinks.delete(threadSegment); + sinks.set(threadSegment, sink); + while (sinks.size > input.options.maxCachedSinks) { + const oldest = sinks.keys().next().value; + if (oldest === undefined) break; + sinks.delete(oldest); + } + writeBatchedRecords( + sink, + records, + Math.min(input.options.maxBytes, input.options.maxBufferedBytes), + ); + writtenBytes += records.reduce((total, record) => total + record.bytes, 0); + } catch (cause) { + sinks.delete(threadSegment); + failures.push({ filePath, cause }); + } + } + + const retainedBytesEstimate = input.state.retainedBytesEstimate + writtenBytes; + const retentionDue = + input.close || + failures.length > 0 || + retainedBytesEstimate > input.options.maxTotalBytes || + input.now - input.state.lastRetentionAt >= input.options.retentionCheckIntervalMs; + const retention = retentionDue + ? enforceRetention({ + directory: input.directory, + maxTotalBytes: input.options.maxTotalBytes, + maxAgeMs: input.options.maxAgeMs, + now: input.now, + }) + : null; + if (retention && retention.removedCount > 0) { + sinks = new Map(); + } + + return [ + { + failures: [...failures, ...(retention?.failures ?? [])], + }, + { + pending: [], + pendingBytes: 0, + sinks, + closed: input.close, + lastRetentionAt: retention ? input.now : input.state.lastRetentionAt, + retainedBytesEstimate: retention?.totalBytes ?? retainedBytesEstimate, + }, + ]; +} + +const serializeEvent = Effect.fnUntraced(function* (event: unknown) { return yield* encodeUnknownJsonString(event).pipe( Effect.catch((error) => logWarning("failed to serialize provider event log record", { @@ -99,188 +443,160 @@ const toLogMessage = Effect.fn("toLogMessage")(function* ( ); }); -const makeThreadWriter = Effect.fn("makeThreadWriter")(function* (input: { - readonly filePath: string; - readonly maxBytes: number; - readonly maxFiles: number; - readonly batchWindowMs: number; - readonly streamLabel: string; -}): Effect.fn.Return { - const sinkResult = yield* Effect.sync(() => { - try { - return { - ok: true as const, - sink: new RotatingFileSink({ - filePath: input.filePath, - maxBytes: input.maxBytes, - maxFiles: input.maxFiles, - throwOnError: true, - }), - }; - } catch (error) { - return { ok: false as const, error }; +export const makeEventNdjsonLogStore = Effect.fnUntraced(function* ( + filePath: string, + options: EventNdjsonLogStoreOptions = {}, +): Effect.fn.Return { + const resolved = yield* resolveOptions(filePath, options); + const directory = NodePath.dirname(filePath); + + yield* Effect.try({ + try: () => NodeFS.mkdirSync(directory, { recursive: true }), + catch: (cause) => new EventNdjsonLogDirectoryError({ directory, cause }), + }); + + const initializedAt = yield* Clock.currentTimeMillis; + const initialRetention = yield* Effect.sync(() => + enforceRetention({ + directory, + maxTotalBytes: resolved.maxTotalBytes, + maxAgeMs: resolved.maxAgeMs, + now: initializedAt, + }), + ); + for (const failure of initialRetention.failures) { + yield* logWarning("provider event log retention failed", { + filePath: failure.filePath, + errorTag: errorTag(failure.cause), + }); + } + + const stateRef = yield* SynchronizedRef.make({ + pending: [], + pendingBytes: 0, + sinks: new Map(), + closed: false, + lastRetentionAt: initializedAt, + retainedBytesEstimate: initialRetention.totalBytes, + }); + const timerScope = yield* Scope.make(); + + const reportDrainResult = Effect.fnUntraced(function* (result: DrainResult) { + for (const failure of result.failures) { + yield* logWarning("provider event log write or retention failed", { + filePath: failure.filePath, + errorTag: errorTag(failure.cause), + }); } }); - if (!sinkResult.ok) { - yield* logWarning("failed to initialize provider thread log file", { - filePath: input.filePath, - errorTag: errorTag(sinkResult.error), - }); - return undefined; + const flush = Effect.fnUntraced(function* (close: boolean) { + const now = yield* Clock.currentTimeMillis; + const result = yield* SynchronizedRef.modifyEffect(stateRef, (state) => + Effect.sync(() => + drainPending({ + directory, + options: resolved, + state, + now, + close, + }), + ), + ); + yield* reportDrainResult(result); + }); + + if (resolved.batchWindowMs > 0) { + yield* Effect.forkIn( + Effect.forever(Effect.sleep(resolved.batchWindowMs).pipe(Effect.andThen(flush(false)))), + timerScope, + { startImmediately: true }, + ); } - const sink = sinkResult.sink; - const scope = yield* Scope.make(); - const lineLogger = makeLineLogger(input.streamLabel); - const batchedLogger = yield* Logger.batched(lineLogger, { - window: input.batchWindowMs, - flush: Effect.fn("makeThreadWriter.flush")(function* (messages) { - const flushResult = yield* Effect.sync(() => { - try { - for (const message of messages) { - sink.write(message); - } - return { ok: true as const }; - } catch (error) { - return { ok: false as const, error }; - } + const close = Effect.fnUntraced(function* () { + yield* flush(true); + yield* Scope.close(timerScope, Exit.void); + }); + + const loggerViews = new Map(); + const logger = (stream: EventNdjsonStream): EventNdjsonLogger => { + const existing = loggerViews.get(stream); + if (existing) return existing; + + const write = Effect.fnUntraced(function* (event: unknown, threadId: ThreadId | null) { + if (!shouldPersist(stream, event)) return; + const payload = yield* serializeEvent(event); + if (payload === undefined) return; + + const observedAt = yield* DateTime.now.pipe(Effect.map(DateTime.formatIso)); + const record = formatRecordLine({ + stream, + event, + observedAt, + payload, + maxRecordBytes: resolved.maxRecordBytes, }); - - if (!flushResult.ok) { - yield* logWarning("provider event log batch flush failed", { - filePath: input.filePath, - errorTag: errorTag(flushResult.error), + const now = yield* Clock.currentTimeMillis; + const result = yield* SynchronizedRef.modifyEffect(stateRef, (state) => { + if (state.closed) { + return Effect.succeed([null, state] as const); + } + const pending = [ + ...state.pending, + { + threadSegment: resolveThreadSegment(threadId), + line: record.line, + bytes: record.bytes, + }, + ]; + const pendingBytes = state.pendingBytes + record.bytes; + const shouldFlush = + resolved.batchWindowMs === 0 || + pending.length >= resolved.maxBufferedRecords || + pendingBytes >= resolved.maxBufferedBytes; + const nextState = { + ...state, + pending, + pendingBytes, + }; + if (!shouldFlush) { + return Effect.succeed([null, nextState] as const); + } + return Effect.sync(() => { + const [drainResult, drainedState] = drainPending({ + directory, + options: resolved, + state: nextState, + now, + close: false, + }); + return [drainResult, drainedState] as const; }); + }); + if (result) { + yield* reportDrainResult(result); } - }), - }).pipe(Effect.provideService(Scope.Scope, scope)); + }); - const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false }); + const view = { filePath, write, close } satisfies EventNdjsonLogger; + loggerViews.set(stream, view); + return view; + }; - return { - writeMessage(message: string) { - return Effect.log(message).pipe(Effect.provide(loggerLayer)); - }, - close() { - return Scope.close(scope, Exit.void); - }, - } satisfies ThreadWriter; + return { filePath, logger, close } satisfies EventNdjsonLogStore; }); -export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function* ( +export const makeEventNdjsonLogger = Effect.fnUntraced(function* ( filePath: string, options: EventNdjsonLoggerOptions, ): Effect.fn.Return { - const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES; - const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES; - const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS; - const streamLabel = resolveStreamLabel(options.stream); - - const directoryReady = yield* Effect.sync(() => { - try { - NodeFS.mkdirSync(NodePath.dirname(filePath), { recursive: true }); - return true; - } catch (error) { - return { ok: false as const, error }; - } - }); - if (directoryReady !== true) { - yield* logWarning("failed to create provider event log directory", { - filePath, - errorTag: errorTag(directoryReady.error), - }); - return undefined; - } - - const stateRef = yield* SynchronizedRef.make({ - threadWriters: new Map(), - failedSegments: new Set(), - }); - - const resolveThreadWriter = Effect.fn("resolveThreadWriter")(function* ( - threadSegment: string, - ): Effect.fn.Return { - return yield* SynchronizedRef.modifyEffect(stateRef, (state) => { - if (state.failedSegments.has(threadSegment)) { - return Effect.succeed([undefined, state] as const); - } - - const existing = state.threadWriters.get(threadSegment); - if (existing) { - return Effect.succeed([existing, state] as const); - } - - return makeThreadWriter({ - filePath: NodePath.join(NodePath.dirname(filePath), `${threadSegment}.log`), - maxBytes, - maxFiles, - batchWindowMs, - streamLabel, - }).pipe( - Effect.map((writer) => { - if (!writer) { - const nextFailedSegments = new Set(state.failedSegments); - nextFailedSegments.add(threadSegment); - return [ - undefined, - { - ...state, - failedSegments: nextFailedSegments, - }, - ] as const; - } - - const nextThreadWriters = new Map(state.threadWriters); - nextThreadWriters.set(threadSegment, writer); - return [ - writer, - { - ...state, - threadWriters: nextThreadWriters, - }, - ] as const; - }), - ); - }); - }); - - const write = Effect.fn("write")(function* (event: unknown, threadId: ThreadId | null) { - const threadSegment = resolveThreadSegment(threadId); - const message = yield* toLogMessage(event); - if (!message) { - return; - } - - const writer = yield* resolveThreadWriter(threadSegment); - if (!writer) { - return; - } - - yield* writer.writeMessage(message); - }); - - const close = Effect.fn("close")(function* () { - yield* SynchronizedRef.modifyEffect(stateRef, (state) => - Effect.gen(function* () { - for (const writer of state.threadWriters.values()) { - yield* writer.close(); - } - - return [ - undefined, - { - threadWriters: new Map(), - failedSegments: new Set(), - }, - ] as const; - }), - ); - }); - - return { - filePath, - write, - close, - } satisfies EventNdjsonLogger; + const store = yield* makeEventNdjsonLogStore(filePath, options).pipe( + Effect.catch((error) => + logWarning(error.message, { error }).pipe( + Effect.as(undefined), + ), + ), + ); + return store?.logger(options.stream); }); diff --git a/apps/server/src/provider/Layers/ProviderEventLoggers.ts b/apps/server/src/provider/Layers/ProviderEventLoggers.ts index 711aa6e76b..2ef9644e2a 100644 --- a/apps/server/src/provider/Layers/ProviderEventLoggers.ts +++ b/apps/server/src/provider/Layers/ProviderEventLoggers.ts @@ -1,6 +1,6 @@ /** - * ProviderEventLoggers — single observability service that owns the two - * shared NDJSON streams the provider runtime writes: + * ProviderEventLoggers — single observability service that owns the shared + * provider event log store and exposes its two runtime views: * * - `native` — provider-protocol events as the SDK emits them, written * from inside each `Adapter` factory. @@ -13,17 +13,14 @@ * not at the boot Layer. There is no longer a single `makeAdapterLive(options)` * call site where we can hand an `EventNdjsonLogger` in by hand. * - Multiple driver instances per kind (`codex_personal`, `codex_work`) - * should share one underlying log writer per stream — opening N writers - * against the same rotating file would race the rotation logic. Owning - * the loggers on a single tag keeps that invariant intact. + * should share one underlying log store — opening N writers against the + * same rotating file would race the rotation logic. Owning the loggers on + * a single tag keeps that invariant intact. * - Tests can swap one (or both) loggers with in-memory recorders by * `Layer.succeed(ProviderEventLoggers, { native, canonical })` instead of * juggling per-Layer option threading. * - * Both fields are optional. `makeEventNdjsonLogger` returns `undefined` when - * the target directory cannot be created; we forward that as `undefined` - * rather than failing the boot Layer, matching the previous best-effort - * behavior of `server.ts`. + * Both fields are optional because observability must not prevent startup. * * @module provider/Layers/ProviderEventLoggers */ @@ -32,7 +29,11 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import { ServerConfig } from "../../config.ts"; -import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts"; +import { + type EventNdjsonLogger, + type EventNdjsonLogStore, + makeEventNdjsonLogStore, +} from "./EventNdjsonLogger.ts"; export interface ProviderEventLoggersShape { readonly native: EventNdjsonLogger | undefined; @@ -63,23 +64,30 @@ export const NoOpProviderEventLoggers: ProviderEventLoggersShape = { }; /** - * Live Layer that builds both loggers from `ServerConfig.providerEventLogPath`. - * If the directory create fails for either stream, the corresponding field - * is `undefined` and writes from that stream become no-ops downstream. + * Live layer that builds both stream views over one shared store. Setup + * failures are logged and downgraded to the no-op service so diagnostics never + * block startup. The layer scope flushes and closes the store during shutdown. */ export const ProviderEventLoggersLive = Layer.effect( ProviderEventLoggers, Effect.gen(function* () { const { providerEventLogPath } = yield* ServerConfig; - const native = yield* makeEventNdjsonLogger(providerEventLogPath, { - stream: "native", - }); - const canonical = yield* makeEventNdjsonLogger(providerEventLogPath, { - stream: "canonical", - }); + const store = yield* makeEventNdjsonLogStore(providerEventLogPath).pipe( + Effect.catch((error) => + Effect.logWarning(error.message, { error }).pipe( + Effect.annotateLogs({ scope: "provider-observability" }), + Effect.as(undefined), + ), + ), + ); + if (!store) { + return NoOpProviderEventLoggers; + } + + yield* Effect.addFinalizer(() => store.close()); return { - native, - canonical, + native: store.logger("native"), + canonical: store.logger("canonical"), } satisfies ProviderEventLoggersShape; }), );