Reduce provider observability disk churn

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-23 10:46:02 -07:00
1 parent 7addf7c6d6
commit 2f8211fa85
7 files changed
+678 -299

No files matched your search

+3 -5
View File
@@ -472,9 +472,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
),
);
const tabIdForWebContents = Effect.fn("PreviewManager.tabIdForWebContents")(function* (
webContentsId: number,
) {
const tabIdForWebContents = Effect.fnUntraced(function* (webContentsId: number) {
const tabs = yield* SynchronizedRef.get(tabsRef);
return (
Array.from(tabs.entries()).find(([, tab]) => tab.webContentsId === webContentsId)?.[0] ?? null
@@ -484,7 +482,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const pushBounded = <A>(buffer: ReadonlyArray<A>, entry: A): ReadonlyArray<A> =>
[...buffer, entry].slice(-DIAGNOSTIC_BUFFER_LIMIT);
const captureDiagnosticMessage = Effect.fn("PreviewManager.captureDiagnosticMessage")(function* (
const captureDiagnosticMessage = Effect.fnUntraced(function* (
webContentsId: number,
method: string,
params: Record<string, unknown>,
@@ -663,7 +661,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const createControlSession = Effect.fn("PreviewManager.createControlSession")(function* () {
const semaphore = yield* Semaphore.make(1);
const scope = yield* Scope.fork(parentScope, "sequential");
const handleDebuggerMessage = Effect.fn("PreviewManager.handleDebuggerMessage")(function* (
const handleDebuggerMessage = Effect.fnUntraced(function* (
method: string,
params: Record<string, unknown>,
) {
@@ -1377,6 +1377,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
stream: "native",
})
: undefined);
const managedNativeEventLogger =
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
const createQuery =
options?.createQuery ??
@@ -1410,7 +1412,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid);
const logNativeSdkMessage = Effect.fn("logNativeSdkMessage")(function* (
const logNativeSdkMessage = Effect.fnUntraced(function* (
context: ClaudeSessionContext,
message: SDKMessage,
) {
@@ -3850,6 +3852,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
Effect.logError("Failed to emit Claude session shutdown event.", { cause }),
),
Effect.tap(() => Queue.shutdown(runtimeEventQueue)),
Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
),
);
@@ -1637,7 +1637,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
),
);
const writeNativeEvent = Effect.fn("writeNativeEvent")(function* (event: ProviderEvent) {
const writeNativeEvent = Effect.fnUntraced(function* (event: ProviderEvent) {
if (!nativeEventLogger) {
return;
}
@@ -5,10 +5,12 @@ import path 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 TestClock from "effect/testing/TestClock";
import * as ResourceAttribution from "../../resourceTelemetry/ResourceAttribution.ts";
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import { makeEventNdjsonLogger, makeEventNdjsonLogStore } from "./EventNdjsonLogger.ts";
function parseLogLine(line: string) {
const match = /^\[([^\]]+)\] ([A-Z]+): (.+)$/.exec(line);
@@ -114,6 +116,102 @@ describe("EventNdjsonLogger", () => {
}),
);
it.effect("shares one thread writer across native and canonical streams", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
const basePath = path.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 = fs
.readFileSync(path.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 {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
it.effect("flushes an active batch without a permanent polling loop", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
const basePath = path.join(tempDir, "events.log");
const threadPath = path.join(tempDir, "thread-batched.log");
try {
const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 1_000 });
yield* store
.logger("native")
.write({ id: "batched-event" }, ThreadId.make("thread-batched"));
assert.equal(fs.existsSync(threadPath), false);
yield* TestClock.adjust(1_000);
assert.equal(fs.existsSync(threadPath), true);
yield* store.close();
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
it.effect("drops transient canonical events before serialization", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
const basePath = path.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<string, unknown> = { 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 = fs
.readFileSync(path.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 {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
it.effect("serializes concurrent first writes for the same segment", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
@@ -163,19 +261,19 @@ describe("EventNdjsonLogger", () => {
const basePath = path.join(tempDir, "provider-native.ndjson");
try {
const logger = yield* makeEventNdjsonLogger(basePath, {
stream: "native",
const store = yield* makeEventNdjsonLogStore(basePath, {
maxBytes: 120,
maxFiles: 2,
batchWindowMs: 0,
});
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),
@@ -183,7 +281,7 @@ describe("EventNdjsonLogger", () => {
ThreadId.make("thread-rotate"),
);
}
yield* logger.close();
yield* store.close();
const fileStem = "thread-rotate.log";
const matchingFiles = fs
@@ -209,6 +307,41 @@ describe("EventNdjsonLogger", () => {
}),
);
it.effect("enforces aggregate age and byte retention on startup", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
const basePath = path.join(tempDir, "events.log");
const expiredPath = path.join(tempDir, "expired.log");
const oldPath = path.join(tempDir, "old.log");
const newPath = path.join(tempDir, "new.log");
const ignoredPath = path.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]) {
fs.writeFileSync(filePath, "x".repeat(40));
}
fs.utimesSync(expiredPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000);
fs.utimesSync(oldPath, (now - 5_000) / 1_000, (now - 5_000) / 1_000);
fs.utimesSync(newPath, now / 1_000, now / 1_000);
const store = yield* makeEventNdjsonLogStore(basePath, {
maxAgeMs: 10_000,
maxTotalBytes: 60,
});
yield* store.close();
assert.equal(fs.existsSync(expiredPath), false);
assert.equal(fs.existsSync(oldPath), false);
assert.equal(fs.existsSync(newPath), true);
assert.equal(fs.existsSync(ignoredPath), true);
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
it.effect("reports logical provider log writes to resource attribution", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
@@ -1,10 +1,9 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* Provider event logger helper.
* Best-effort provider event logging with one shared writer per thread.
*
* 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 fs from "node:fs";
import path from "node:path";
@@ -12,9 +11,9 @@ import path from "node:path";
import type { ThreadId } from "@t3tools/contracts";
import { RotatingFileSink } from "@t3tools/shared/logging";
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";
@@ -22,38 +21,138 @@ import * as SynchronizedRef from "effect/SynchronizedRef";
import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts";
import type { ResourceAttributionShape } from "../../resourceTelemetry/ResourceAttribution.ts";
const DEFAULT_MAX_BYTES = 10 * 1024 * 1024;
const MEBIBYTE = 1024 * 1024;
const DAY_MS = 24 * 60 * 60 * 1_000;
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 GLOBAL_THREAD_SEGMENT = "_global";
const LOG_SCOPE = "provider-observability";
const PROVIDER_LOG_FILE_PATTERN = /\.log(?:\.\d+)?$/u;
const encodeUnknownJsonString = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
const textEncoder = new TextEncoder();
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<void>;
close: () => Effect.Effect<void>;
readonly write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void>;
readonly close: () => Effect.Effect<void>;
}
export interface EventNdjsonLoggerOptions {
readonly stream: EventNdjsonStream;
export interface EventNdjsonLogStore {
readonly filePath: string;
readonly logger: (stream: EventNdjsonStream) => EventNdjsonLogger;
readonly close: () => Effect.Effect<void>;
}
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 attribution?: ResourceAttributionShape;
}
interface ThreadWriter {
writeMessage: (message: string) => Effect.Effect<void>;
close: () => Effect.Effect<void>;
export interface EventNdjsonLoggerOptions extends EventNdjsonLogStoreOptions {
readonly stream: EventNdjsonStream;
}
interface LoggerState {
readonly threadWriters: Map<string, ThreadWriter>;
readonly failedSegments: Set<string>;
export class EventNdjsonLogConfigurationError extends Schema.TaggedErrorClass<EventNdjsonLogConfigurationError>()(
"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}'`;
}
}
export class EventNdjsonLogDirectoryError extends Schema.TaggedErrorClass<EventNdjsonLogDirectoryError>()(
"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 attribution: ResourceAttributionShape | undefined;
}
interface PendingRecord {
readonly stream: EventNdjsonStream;
readonly threadSegment: string;
readonly line: string;
readonly bytes: number;
}
interface StoreState {
readonly pending: ReadonlyArray<PendingRecord>;
readonly pendingBytes: number;
readonly sinks: ReadonlyMap<string, RotatingFileSink>;
readonly failedSegments: ReadonlySet<string>;
readonly flushScheduled: boolean;
readonly closed: boolean;
readonly lastRetentionAt: number;
}
interface AttributionSummary {
readonly stream: EventNdjsonStream;
readonly count: number;
readonly logicalWriteBytes: number;
}
interface FileOperationFailure {
readonly filePath: string;
readonly cause: unknown;
}
interface RetentionResult {
readonly failures: ReadonlyArray<FileOperationFailure>;
}
interface DrainResult {
readonly attributions: ReadonlyArray<AttributionSummary>;
readonly failures: ReadonlyArray<FileOperationFailure>;
}
function logWarning(message: string, context: Record<string, unknown>): Effect.Effect<void> {
@@ -65,69 +164,249 @@ function resolveThreadSegment(raw: string | null | undefined): string {
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(" ");
}
return typeof message === "string" ? message : String(message);
}
function makeLineLogger(streamLabel: string): Logger.Logger<unknown, string> {
return Logger.make(
({ date, message }) =>
`[${date.toISOString()}] ${streamLabel}: ${formatLoggerMessage(message)}\n`,
);
}
function resolveStreamLabel(stream: EventNdjsonStream): string {
switch (stream) {
case "native":
return "NTIVE";
case "canonical":
case "orchestration":
default:
return "CANON";
return stream === "native" ? "NTIVE" : "CANON";
}
function shouldPersist(stream: EventNdjsonStream, event: unknown): boolean {
if (stream !== "canonical" || typeof event !== "object" || event === null) {
return true;
}
const type = Reflect.get(event, "type");
return typeof type !== "string" || !transientCanonicalEventTypes.has(type);
}
function writeBatchedMessages(
sink: RotatingFileSink,
messages: ReadonlyArray<string>,
records: ReadonlyArray<PendingRecord>,
maxBytes: number,
): number {
let pendingMessages: Array<string> = [];
): void {
let pendingLines: Array<string> = [];
let pendingBytes = 0;
let logicalWriteBytes = 0;
const flush = () => {
if (pendingMessages.length === 0) {
return;
}
sink.write(pendingMessages.join(""));
pendingMessages = [];
if (pendingLines.length === 0) return;
sink.write(pendingLines.join(""));
pendingLines = [];
pendingBytes = 0;
};
for (const message of messages) {
const messageBytes = textEncoder.encode(message).byteLength;
logicalWriteBytes += messageBytes;
if (pendingBytes > 0 && pendingBytes + messageBytes > maxBytes) {
for (const record of records) {
if (pendingBytes > 0 && pendingBytes + record.bytes > maxBytes) {
flush();
}
pendingMessages.push(message);
pendingBytes += messageBytes;
pendingLines.push(record.line);
pendingBytes += record.bytes;
if (pendingBytes >= maxBytes) {
flush();
}
}
flush();
return logicalWriteBytes;
}
const toLogMessage = Effect.fn("toLogMessage")(function* (
event: unknown,
): Effect.fn.Return<string | undefined> {
function enforceRetention(input: {
readonly directory: string;
readonly maxTotalBytes: number;
readonly maxAgeMs: number;
readonly activeFilePaths: ReadonlySet<string>;
readonly now: number;
}): RetentionResult {
const failures: Array<FileOperationFailure> = [];
const files: Array<{ filePath: string; mtimeMs: number; size: number }> = [];
let entries: ReadonlyArray<fs.Dirent>;
try {
entries = fs.readdirSync(input.directory, { withFileTypes: true });
} catch (cause) {
return { failures: [{ filePath: input.directory, cause }] };
}
for (const entry of entries) {
if (!entry.isFile() || !PROVIDER_LOG_FILE_PATTERN.test(entry.name)) continue;
const filePath = path.join(input.directory, entry.name);
try {
const stat = fs.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);
const remove = (file: (typeof files)[number]) => {
if (input.activeFilePaths.has(file.filePath)) return false;
try {
fs.rmSync(file.filePath, { force: true });
totalBytes -= file.size;
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 };
}
function validateOption(input: {
readonly filePath: string;
readonly option: string;
readonly value: number;
readonly minimum: number;
}): EventNdjsonLogConfigurationError | undefined {
if (Number.isInteger(input.value) && input.value >= input.minimum) return undefined;
return new EventNdjsonLogConfigurationError(input);
}
function resolveOptions(
filePath: string,
options: EventNdjsonLogStoreOptions,
): Effect.Effect<ResolvedOptions, EventNdjsonLogConfigurationError> {
const resolved = {
maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,
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: options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES,
maxBufferedRecords: options.maxBufferedRecords ?? DEFAULT_MAX_BUFFERED_RECORDS,
attribution: options.attribution,
} satisfies ResolvedOptions;
const validations = [
["maxBytes", resolved.maxBytes, 1],
["maxFiles", resolved.maxFiles, 1],
["batchWindowMs", resolved.batchWindowMs, 0],
["maxTotalBytes", resolved.maxTotalBytes, 1],
["maxAgeMs", resolved.maxAgeMs, 1],
["retentionCheckIntervalMs", resolved.retentionCheckIntervalMs, 1],
["maxBufferedBytes", resolved.maxBufferedBytes, 1],
["maxBufferedRecords", resolved.maxBufferedRecords, 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 timerFired: boolean;
readonly close: boolean;
}): readonly [DrainResult, StoreState] {
if (input.state.closed) {
return [{ attributions: [], failures: [] }, input.state];
}
const sinks = new Map(input.state.sinks);
const failedSegments = new Set(input.state.failedSegments);
const failures: Array<FileOperationFailure> = [];
const attributionByStream = new Map<
EventNdjsonStream,
{ count: number; logicalWriteBytes: number }
>();
const recordsBySegment = new Map<string, Array<PendingRecord>>();
for (const record of input.state.pending) {
const records = recordsBySegment.get(record.threadSegment) ?? [];
records.push(record);
recordsBySegment.set(record.threadSegment, records);
}
for (const [threadSegment, records] of recordsBySegment) {
if (failedSegments.has(threadSegment)) continue;
const filePath = path.join(input.directory, `${threadSegment}.log`);
let sink = sinks.get(threadSegment);
if (!sink) {
try {
sink = new RotatingFileSink({
filePath,
maxBytes: input.options.maxBytes,
maxFiles: input.options.maxFiles,
throwOnError: true,
});
sinks.set(threadSegment, sink);
} catch (cause) {
failedSegments.add(threadSegment);
failures.push({ filePath, cause });
continue;
}
}
try {
writeBatchedMessages(sink, records, input.options.maxBytes);
for (const record of records) {
const current = attributionByStream.get(record.stream) ?? {
count: 0,
logicalWriteBytes: 0,
};
attributionByStream.set(record.stream, {
count: current.count + 1,
logicalWriteBytes: current.logicalWriteBytes + record.bytes,
});
}
} catch (cause) {
failedSegments.add(threadSegment);
failures.push({ filePath, cause });
}
}
const retentionDue =
input.now - input.state.lastRetentionAt >= input.options.retentionCheckIntervalMs;
const retention = retentionDue
? enforceRetention({
directory: input.directory,
maxTotalBytes: input.options.maxTotalBytes,
maxAgeMs: input.options.maxAgeMs,
activeFilePaths: new Set(
Array.from(sinks.keys(), (threadSegment) =>
path.join(input.directory, `${threadSegment}.log`),
),
),
now: input.now,
})
: { failures: [] };
return [
{
attributions: Array.from(attributionByStream, ([stream, value]) => ({
stream,
...value,
})),
failures: [...failures, ...retention.failures],
},
{
pending: [],
pendingBytes: 0,
sinks,
failedSegments,
flushScheduled: input.timerFired ? false : input.state.flushScheduled,
closed: input.close,
lastRetentionAt: retentionDue ? input.now : input.state.lastRetentionAt,
},
];
}
const serializeEvent = Effect.fnUntraced(function* (event: unknown) {
return yield* encodeUnknownJsonString(event).pipe(
Effect.catch((error) =>
logWarning("failed to serialize provider event log record", { error }).pipe(
@@ -137,206 +416,169 @@ 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;
readonly stream: EventNdjsonStream;
readonly attribution?: ResourceAttributionShape;
}): Effect.fn.Return<ThreadWriter | undefined> {
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 };
}
});
if (!sinkResult.ok) {
yield* logWarning("failed to initialize provider thread log file", {
filePath: input.filePath,
error: sinkResult.error,
});
return undefined;
}
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 startedAt = yield* Clock.currentTimeMillis;
const flushResult = yield* Effect.sync(() => {
try {
return {
ok: true as const,
logicalWriteBytes: writeBatchedMessages(sink, messages, input.maxBytes),
count: messages.length,
};
} catch (error) {
return { ok: false as const, error };
}
});
if (!flushResult.ok) {
yield* logWarning("provider event log batch flush failed", {
filePath: input.filePath,
error: flushResult.error,
});
return;
}
if (input.attribution && flushResult.count > 0) {
const completedAt = yield* Clock.currentTimeMillis;
yield* input.attribution.record({
component: "provider-event-log",
operation: `${input.stream}.append`,
logicalWriteBytes: flushResult.logicalWriteBytes,
count: flushResult.count,
durationMs: Math.max(0, completedAt - startedAt),
});
}
}),
}).pipe(Effect.provideService(Scope.Scope, scope));
const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
return {
writeMessage(message: string) {
return Effect.log(message).pipe(Effect.provide(loggerLayer));
},
close() {
return Scope.close(scope, Exit.void);
},
} satisfies ThreadWriter;
});
export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function* (
export const makeEventNdjsonLogStore = Effect.fnUntraced(function* (
filePath: string,
options: EventNdjsonLoggerOptions,
): Effect.fn.Return<EventNdjsonLogger | undefined> {
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);
options: EventNdjsonLogStoreOptions = {},
): Effect.fn.Return<EventNdjsonLogStore, EventNdjsonLogStoreError> {
const resolved = yield* resolveOptions(filePath, options);
const directory = path.dirname(filePath);
const directoryReady = yield* Effect.sync(() => {
try {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
return true;
} catch (error) {
return { ok: false as const, error };
}
yield* Effect.try({
try: () => fs.mkdirSync(directory, { recursive: true }),
catch: (cause) => new EventNdjsonLogDirectoryError({ directory, cause }),
});
if (directoryReady !== true) {
yield* logWarning("failed to create provider event log directory", {
filePath,
error: directoryReady.error,
const initializedAt = yield* Clock.currentTimeMillis;
const initialRetention = yield* Effect.sync(() =>
enforceRetention({
directory,
maxTotalBytes: resolved.maxTotalBytes,
maxAgeMs: resolved.maxAgeMs,
activeFilePaths: new Set(),
now: initializedAt,
}),
);
for (const failure of initialRetention.failures) {
yield* logWarning("provider event log retention failed", {
filePath: failure.filePath,
cause: failure.cause,
});
return undefined;
}
const stateRef = yield* SynchronizedRef.make<LoggerState>({
threadWriters: new Map(),
const stateRef = yield* SynchronizedRef.make<StoreState>({
pending: [],
pendingBytes: 0,
sinks: new Map(),
failedSegments: new Set(),
flushScheduled: false,
closed: false,
lastRetentionAt: initializedAt,
});
const timerScope = yield* Scope.make();
const resolveThreadWriter = Effect.fn("resolveThreadWriter")(function* (
threadSegment: string,
): Effect.fn.Return<ThreadWriter | undefined> {
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: path.join(path.dirname(filePath), `${threadSegment}.log`),
maxBytes,
maxFiles,
batchWindowMs,
streamLabel,
stream: options.stream,
...(options.attribution ? { attribution: options.attribution } : {}),
}).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 flush = Effect.fnUntraced(function* (timerFired: boolean, close: boolean) {
const startedAt = yield* Clock.currentTimeMillis;
const result = yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
Effect.sync(() =>
drainPending({
directory,
options: resolved,
state,
now: startedAt,
timerFired,
close,
}),
),
);
for (const failure of result.failures) {
yield* logWarning("provider event log write or retention failed", {
filePath: failure.filePath,
cause: failure.cause,
});
}
if (resolved.attribution && result.attributions.length > 0) {
const completedAt = yield* Clock.currentTimeMillis;
const durationMs = Math.max(0, completedAt - startedAt);
const totalBytes = result.attributions.reduce(
(total, entry) => total + entry.logicalWriteBytes,
0,
);
});
yield* Effect.forEach(
result.attributions,
(entry) =>
resolved.attribution?.record({
component: "provider-event-log",
operation: `${entry.stream}.append`,
logicalWriteBytes: entry.logicalWriteBytes,
count: entry.count,
durationMs:
totalBytes === 0
? 0
: Math.round(durationMs * (entry.logicalWriteBytes / totalBytes)),
}) ?? Effect.void,
{ discard: true },
);
}
});
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<string, ThreadWriter>(),
failedSegments: new Set<string>(),
},
] as const;
}),
const scheduleFlush = Effect.fnUntraced(function* () {
yield* Effect.forkIn(
Effect.sleep(resolved.batchWindowMs).pipe(Effect.andThen(flush(true, false))),
timerScope,
{ startImmediately: true },
);
});
return {
filePath,
write,
close,
} satisfies EventNdjsonLogger;
const close = Effect.fnUntraced(function* () {
yield* flush(false, true);
yield* Scope.close(timerScope, Exit.void);
});
const loggerViews = new Map<EventNdjsonStream, EventNdjsonLogger>();
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 line = `[${observedAt}] ${resolveStreamLabel(stream)}: ${payload}\n`;
const bytes = Buffer.byteLength(line);
const action = yield* SynchronizedRef.modify(stateRef, (state) => {
if (state.closed) {
return [{ flush: false, schedule: false }, state] as const;
}
const pending = [
...state.pending,
{ stream, threadSegment: resolveThreadSegment(threadId), line, bytes },
];
const pendingBytes = state.pendingBytes + bytes;
const flush =
resolved.batchWindowMs === 0 ||
pending.length >= resolved.maxBufferedRecords ||
pendingBytes >= resolved.maxBufferedBytes;
const schedule = !flush && !state.flushScheduled;
return [
{ flush, schedule },
{
...state,
pending,
pendingBytes,
flushScheduled: state.flushScheduled || schedule,
},
] as const;
});
if (action.flush) {
yield* flush(false, false);
} else if (action.schedule) {
yield* scheduleFlush();
}
});
const view = { filePath, write, close } satisfies EventNdjsonLogger;
loggerViews.set(stream, view);
return view;
};
return { filePath, logger, close } satisfies EventNdjsonLogStore;
});
export const makeEventNdjsonLogger = Effect.fnUntraced(function* (
filePath: string,
options: EventNdjsonLoggerOptions,
): Effect.fn.Return<EventNdjsonLogger | undefined> {
const store = yield* makeEventNdjsonLogStore(filePath, options).pipe(
Effect.catch((error) =>
logWarning(error.message, { error }).pipe(
Effect.as<EventNdjsonLogStore | undefined>(undefined),
),
),
);
return store?.logger(options.stream);
});
@@ -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 `<X>Adapter` factory.
@@ -13,17 +13,14 @@
* not at the boot Layer. There is no longer a single `make<X>AdapterLive(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.
* must 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
*/
@@ -33,11 +30,11 @@ import * as Layer from "effect/Layer";
import { ServerConfig } from "../../config.ts";
import * as ResourceAttribution from "../../resourceTelemetry/ResourceAttribution.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import * as EventNdjsonLogger from "./EventNdjsonLogger.ts";
export interface ProviderEventLoggersShape {
readonly native: EventNdjsonLogger | undefined;
readonly canonical: EventNdjsonLogger | undefined;
readonly native: EventNdjsonLogger.EventNdjsonLogger | undefined;
readonly canonical: EventNdjsonLogger.EventNdjsonLogger | undefined;
}
/**
@@ -45,8 +42,8 @@ export interface ProviderEventLoggersShape {
*
* Service value is intentionally a struct of two optional loggers rather
* than two parallel tags. Construction site is one place
* (`ProviderEventLoggersLive`); consumers (drivers, `ProviderService`) read
* one tag and pluck the field they need.
* (`layer`); consumers (drivers, `ProviderService`) read one tag and pluck the
* field they need.
*/
export class ProviderEventLoggers extends Context.Service<
ProviderEventLoggers,
@@ -64,26 +61,32 @@ 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.
* Builds both stream views over one shared store. Setup failures are logged
* and downgraded to the no-op service so diagnostics never block startup.
*/
export const ProviderEventLoggersLive = Layer.effect(
ProviderEventLoggers,
Effect.gen(function* () {
const { providerEventLogPath } = yield* ServerConfig;
const attribution = yield* ResourceAttribution.ResourceAttribution;
const native = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "native",
attribution,
});
const canonical = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "canonical",
attribution,
});
return {
native,
canonical,
} satisfies ProviderEventLoggersShape;
}),
);
export const make = Effect.gen(function* () {
const { providerEventLogPath } = yield* ServerConfig;
const attribution = yield* ResourceAttribution.ResourceAttribution;
const store = yield* EventNdjsonLogger.makeEventNdjsonLogStore(providerEventLogPath, {
attribution,
}).pipe(
Effect.catch((error) =>
Effect.logWarning(error.message, { error }).pipe(
Effect.annotateLogs({ scope: "provider-observability" }),
Effect.as<EventNdjsonLogger.EventNdjsonLogStore | undefined>(undefined),
),
),
);
if (!store) {
return ProviderEventLoggers.of(NoOpProviderEventLoggers);
}
yield* Effect.addFinalizer(() => store.close());
return ProviderEventLoggers.of({
native: store.logger("native"),
canonical: store.logger("canonical"),
});
});
export const layer = Layer.effect(ProviderEventLoggers, make);
+3 -3
View File
@@ -23,7 +23,7 @@ import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService.t
import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory.ts";
import { ProviderSessionRuntimeRepositoryLive } from "./persistence/Layers/ProviderSessionRuntime.ts";
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry.ts";
import { ProviderEventLoggersLive } from "./provider/Layers/ProviderEventLoggers.ts";
import * as ProviderEventLoggers from "./provider/Layers/ProviderEventLoggers.ts";
import { ProviderServiceLive } from "./provider/Layers/ProviderService.ts";
import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReaper.ts";
import { OpenCodeRuntimeLive } from "./provider/opencodeRuntime.ts";
@@ -208,7 +208,7 @@ const ProviderSessionDirectoryLayerLive = ProviderSessionDirectoryLive.pipe(
// `ProviderAdapterRegistryLive` is now a facade that resolves kind → adapter
// by looking up the default `ProviderInstance` per driver in the instance
// registry. Adapter construction itself moved inside each driver's
// `create()`; `ProviderEventLoggersLive` owns the shared native/canonical
// `create()`; `ProviderEventLoggers.layer` owns the shared native/canonical
// NDJSON writers and is provided at the outer runtime layer so both
// `ProviderService` and the per-instance drivers read the same logger pair.
const ProviderLayerLive = ProviderServiceLive.pipe(
@@ -342,7 +342,7 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
// `ProviderService` (canonical stream, written after event normalization).
// Provided once at the runtime level so every consumer sees the same
// logger instances.
Layer.provideMerge(ProviderEventLoggersLive),
Layer.provideMerge(ProviderEventLoggers.layer),
// `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old
// `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but
// the rewritten registry reads snapshots off the instance registry and