Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5
6import { ThreadId } from "@t3tools/contracts";
7import { assert, describe, it } from "@effect/vitest";
8import * as Clock from "effect/Clock";
9import * as Effect from "effect/Effect";
10import * as Fiber from "effect/Fiber";
11import * as Logger from "effect/Logger";
12import * as Schema from "effect/Schema";
13import * as TestClock from "effect/testing/TestClock";
14
15import * as ResourceAttribution from "../../resourceTelemetry/ResourceAttribution.ts";
16import {
17 makeEventNdjsonLogger,
18 makeEventNdjsonLogStore,
19 type PendingRecord,
20 writeBatchedMessages,
21} from "./EventNdjsonLogger.ts";
22
23const encodeUnknownJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
24
25function ownedLogPath(basePath: string, segment: string): string {
26 const basename = NodePath.basename(basePath);
27 const extension = NodePath.extname(basename);
28 const stem = extension.length > 0 ? basename.slice(0, -extension.length) : basename;
29 return NodePath.join(NodePath.dirname(basePath), `${stem}.${segment}.log`);
30}
31
32function parseLogLine(line: string) {
33 const match = /^\[([^\]]+)\] ([A-Z]+): (.+)$/.exec(line);
34 assert.notEqual(match, null);
35 if (!match) {
36 throw new Error(`invalid log line: ${line}`);
37 }
38 const observedAt = match[1];
39 const stream = match[2];
40 const payload = match[3];
41 if (!observedAt || !stream || payload === undefined) {
42 throw new Error(`invalid log line: ${line}`);
43 }
44 return {
45 observedAt,
46 stream,
47 payload,
48 };
49}
50
51describe("EventNdjsonLogger", () => {
52 it.effect("logs bounded diagnostics when an event cannot be serialized", () => {
53 const messages: Array<unknown> = [];
54 const logCapture = Logger.make<unknown, void>(({ message }) => {
55 if (Array.isArray(message)) {
56 messages.push(...message);
57 } else {
58 messages.push(message);
59 }
60 });
61 const secret = "secret-circular-event-value";
62
63 return Effect.gen(function* () {
64 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
65 const basePath = NodePath.join(tempDir, "provider-native.ndjson");
66 const circular: Record<string, unknown> = { secret };
67 circular.self = circular;
68
69 try {
70 const logger = yield* makeEventNdjsonLogger(basePath, { stream: "native" });
71 assert.exists(logger);
72 if (!logger) return;
73 yield* logger.write(circular, ThreadId.make("thread-1"));
74
75 const serialized = encodeUnknownJson(messages);
76 assert.notInclude(serialized, secret);
77 assert.include(serialized, '"errorTag":"SchemaError"');
78 } finally {
79 NodeFS.rmSync(tempDir, { recursive: true, force: true });
80 }
81 }).pipe(Effect.provide(Logger.layer([logCapture], { mergeWithExisting: false })));
82 });
83
84 it.effect("writes effect-style lines to thread-scoped files", () =>
85 Effect.gen(function* () {
86 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
87 const basePath = NodePath.join(tempDir, "provider-native.ndjson");
88
89 try {
90 const logger = yield* makeEventNdjsonLogger(basePath, { stream: "native" });
91 assert.notEqual(logger, undefined);
92 if (!logger) {
93 return;
94 }
95
96 yield* logger.write(
97 { threadId: "provider-thread-1", id: "evt-1" },
98 ThreadId.make("thread-1"),
99 );
100 yield* logger.write(
101 { type: "turn.completed", threadId: "provider-thread-2", id: "evt-2" },
102 ThreadId.make("thread-2"),
103 );
104 yield* logger.close();
105
106 const threadOnePath = ownedLogPath(basePath, "thread-1");
107 const threadTwoPath = ownedLogPath(basePath, "thread-2");
108 assert.equal(NodeFS.existsSync(threadOnePath), true);
109 assert.equal(NodeFS.existsSync(threadTwoPath), true);
110
111 const first = parseLogLine(NodeFS.readFileSync(threadOnePath, "utf8").trim());
112 const second = parseLogLine(NodeFS.readFileSync(threadTwoPath, "utf8").trim());
113
114 assert.equal(Number.isNaN(Date.parse(first.observedAt)), false);
115 assert.equal(first.stream, "NTIVE");
116 assert.equal(first.payload, '{"threadId":"provider-thread-1","id":"evt-1"}');
117
118 assert.equal(Number.isNaN(Date.parse(second.observedAt)), false);
119 assert.equal(second.stream, "NTIVE");
120 assert.equal(
121 second.payload,
122 '{"type":"turn.completed","threadId":"provider-thread-2","id":"evt-2"}',
123 );
124 } finally {
125 NodeFS.rmSync(tempDir, { recursive: true, force: true });
126 }
127 }),
128 );
129
130 it.effect(
131 "falls back to a global segment when orchestration thread id is missing or invalid",
132 () =>
133 Effect.gen(function* () {
134 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
135 const basePath = NodePath.join(tempDir, "provider-canonical.ndjson");
136
137 try {
138 const logger = yield* makeEventNdjsonLogger(basePath, { stream: "orchestration" });
139 assert.notEqual(logger, undefined);
140 if (!logger) {
141 return;
142 }
143
144 yield* logger.write({ id: "evt-no-thread" }, null);
145 yield* logger.write({ id: "evt-invalid-thread" }, "!!!" as unknown as ThreadId);
146 yield* logger.close();
147
148 const globalPath = ownedLogPath(basePath, "_global");
149 assert.equal(NodeFS.existsSync(globalPath), true);
150 const lines = NodeFS.readFileSync(globalPath, "utf8")
151 .trim()
152 .split("\n")
153 .map((line) => parseLogLine(line));
154 assert.equal(lines.length, 2);
155 assert.equal(Number.isNaN(Date.parse(lines[0]?.observedAt ?? "")), false);
156 assert.equal(Number.isNaN(Date.parse(lines[1]?.observedAt ?? "")), false);
157 assert.equal(lines[0]?.stream, "ORCH");
158 assert.equal(lines[0]?.payload, '{"id":"evt-no-thread"}');
159 assert.equal(lines[1]?.stream, "ORCH");
160 assert.equal(lines[1]?.payload, '{"id":"evt-invalid-thread"}');
161 } finally {
162 NodeFS.rmSync(tempDir, { recursive: true, force: true });
163 }
164 }),
165 );
166
167 it.effect("shares one thread writer across native and canonical streams", () =>
168 Effect.gen(function* () {
169 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
170 const basePath = NodePath.join(tempDir, "events.log");
171
172 try {
173 const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 });
174 const native = store.logger("native");
175 const canonical = store.logger("canonical");
176 const threadId = ThreadId.make("thread-shared");
177
178 yield* native.write({ id: "native-event" }, threadId);
179 yield* canonical.write({ type: "item.completed", id: "canonical-event" }, threadId);
180 yield* store.close();
181
182 const lines = NodeFS.readFileSync(ownedLogPath(basePath, "thread-shared"), "utf8")
183 .trim()
184 .split("\n")
185 .map(parseLogLine);
186
187 assert.deepEqual(
188 lines.map(({ stream, payload }) => ({ stream, payload })),
189 [
190 { stream: "NTIVE", payload: '{"id":"native-event"}' },
191 {
192 stream: "CANON",
193 payload: '{"type":"item.completed","id":"canonical-event"}',
194 },
195 ],
196 );
197 } finally {
198 NodeFS.rmSync(tempDir, { recursive: true, force: true });
199 }
200 }),
201 );
202
203 it.effect("keeps shared store views non-owning when one adapter closes", () =>
204 Effect.gen(function* () {
205 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
206 const basePath = NodePath.join(tempDir, "events.log");
207
208 try {
209 const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 });
210 const native = store.logger("native");
211 const canonical = store.logger("canonical");
212 const threadId = ThreadId.make("thread-shared-close");
213
214 yield* native.write({ id: "before-close" }, threadId);
215 yield* native.close();
216 yield* canonical.write({ type: "item.completed", id: "after-close" }, threadId);
217 yield* store.close();
218
219 const lines = NodeFS.readFileSync(ownedLogPath(basePath, "thread-shared-close"), "utf8")
220 .trim()
221 .split("\n")
222 .map(parseLogLine);
223
224 assert.deepEqual(
225 lines.map(({ stream, payload }) => ({ stream, payload })),
226 [
227 { stream: "NTIVE", payload: '{"id":"before-close"}' },
228 {
229 stream: "CANON",
230 payload: '{"type":"item.completed","id":"after-close"}',
231 },
232 ],
233 );
234 } finally {
235 NodeFS.rmSync(tempDir, { recursive: true, force: true });
236 }
237 }),
238 );
239
240 it.effect("flushes an active batch without a permanent polling loop", () =>
241 Effect.gen(function* () {
242 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
243 const basePath = NodePath.join(tempDir, "events.log");
244 const threadPath = ownedLogPath(basePath, "thread-batched");
245
246 try {
247 const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 1_000 });
248 yield* store
249 .logger("native")
250 .write({ id: "batched-event" }, ThreadId.make("thread-batched"));
251
252 assert.equal(NodeFS.existsSync(threadPath), false);
253 yield* TestClock.adjust(1_000);
254 assert.equal(NodeFS.existsSync(threadPath), true);
255 yield* store.close();
256 } finally {
257 NodeFS.rmSync(tempDir, { recursive: true, force: true });
258 }
259 }),
260 );
261
262 it.effect("does not strand a later batch after an interrupted write", () =>
263 Effect.gen(function* () {
264 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
265 const basePath = NodePath.join(tempDir, "events.log");
266 const threadPath = ownedLogPath(basePath, "thread-interrupted");
267
268 try {
269 const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 1_000 });
270 const logger = store.logger("native");
271 const interruptedWrite = yield* logger
272 .write({ id: "possibly-interrupted" }, ThreadId.make("thread-interrupted"))
273 .pipe(Effect.forkChild);
274 yield* Effect.yieldNow;
275 yield* Fiber.interrupt(interruptedWrite);
276 yield* logger.write({ id: "accepted" }, ThreadId.make("thread-interrupted"));
277
278 yield* TestClock.adjust(1_000);
279
280 assert.equal(NodeFS.existsSync(threadPath), true);
281 assert.include(NodeFS.readFileSync(threadPath, "utf8"), '{"id":"accepted"}');
282 yield* store.close();
283 } finally {
284 NodeFS.rmSync(tempDir, { recursive: true, force: true });
285 }
286 }),
287 );
288
289 it.effect("drops transient provider events before serialization", () =>
290 Effect.gen(function* () {
291 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
292 const basePath = NodePath.join(tempDir, "events.log");
293
294 try {
295 const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 });
296 const canonical = store.logger("canonical");
297 const native = store.logger("native");
298 const threadId = ThreadId.make("thread-filtered");
299 const circularDelta: Record<string, unknown> = { type: "content.delta" };
300 circularDelta["self"] = circularDelta;
301
302 yield* canonical.write(circularDelta, threadId);
303 yield* canonical.write({ type: "item.completed", id: "final" }, threadId);
304 yield* native.write({ type: "content.delta", id: "native-delta" }, threadId);
305 yield* native.write(
306 { method: "item/agentMessage/delta", payload: circularDelta },
307 threadId,
308 );
309 yield* native.write(
310 { method: "thread/realtime/outputAudio/delta", payload: circularDelta },
311 threadId,
312 );
313 yield* native.write(
314 { method: "thread/realtime/transcript/delta", payload: circularDelta },
315 threadId,
316 );
317 yield* native.write(
318 {
319 event: {
320 method: "claude/stream_event/content_block_delta/text_delta",
321 payload: circularDelta,
322 },
323 },
324 threadId,
325 );
326 yield* native.write(
327 {
328 event: {
329 method: "session/update",
330 payload: { update: { sessionUpdate: "agent_message_chunk" } },
331 },
332 },
333 threadId,
334 );
335 yield* native.write(
336 {
337 event: {
338 type: "message.part.updated",
339 payload: { properties: { part: { type: "text" } } },
340 },
341 },
342 threadId,
343 );
344 yield* native.write({ type: "turn.completed", id: "native-final" }, threadId);
345 yield* store.close();
346
347 const lines = NodeFS.readFileSync(ownedLogPath(basePath, "thread-filtered"), "utf8")
348 .trim()
349 .split("\n")
350 .map(parseLogLine);
351
352 assert.deepEqual(
353 lines.map(({ stream, payload }) => ({ stream, payload })),
354 [
355 { stream: "CANON", payload: '{"type":"item.completed","id":"final"}' },
356 { stream: "NTIVE", payload: '{"type":"turn.completed","id":"native-final"}' },
357 ],
358 );
359 } finally {
360 NodeFS.rmSync(tempDir, { recursive: true, force: true });
361 }
362 }),
363 );
364
365 it.effect("contains hostile event accessors inside guarded serialization", () =>
366 Effect.gen(function* () {
367 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
368 const basePath = NodePath.join(tempDir, "events.log");
369
370 try {
371 const logger = yield* makeEventNdjsonLogger(basePath, {
372 stream: "canonical",
373 batchWindowMs: 0,
374 });
375 assert.exists(logger);
376 if (!logger) return;
377 const hostile = new Proxy(
378 { id: "hostile" },
379 {
380 get(_target, property) {
381 if (property === "type") throw new Error("blocked");
382 return undefined;
383 },
384 },
385 );
386
387 yield* logger.write(hostile, ThreadId.make("thread-hostile"));
388 yield* logger.close();
389
390 const contents = NodeFS.readFileSync(ownedLogPath(basePath, "thread-hostile"), "utf8");
391 assert.notInclude(contents, "blocked");
392 } finally {
393 NodeFS.rmSync(tempDir, { recursive: true, force: true });
394 }
395 }),
396 );
397
398 it.effect("serializes concurrent first writes for the same segment", () =>
399 Effect.gen(function* () {
400 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
401 const basePath = NodePath.join(tempDir, "provider-canonical.ndjson");
402
403 try {
404 const logger = yield* makeEventNdjsonLogger(basePath, {
405 stream: "canonical",
406 batchWindowMs: 0,
407 });
408 assert.notEqual(logger, undefined);
409 if (!logger) {
410 return;
411 }
412
413 yield* Effect.all(
414 [
415 logger.write({ id: "evt-concurrent-1" }, null),
416 logger.write({ id: "evt-concurrent-2" }, null),
417 ],
418 { concurrency: "unbounded" },
419 );
420 yield* logger.close();
421
422 const globalPath = ownedLogPath(basePath, "_global");
423 assert.equal(NodeFS.existsSync(globalPath), true);
424 const lines = NodeFS.readFileSync(globalPath, "utf8")
425 .trim()
426 .split("\n")
427 .map((line) => parseLogLine(line));
428
429 assert.equal(lines.length, 2);
430 assert.deepEqual(lines.map((line) => line.payload).toSorted(), [
431 '{"id":"evt-concurrent-1"}',
432 '{"id":"evt-concurrent-2"}',
433 ]);
434 } finally {
435 NodeFS.rmSync(tempDir, { recursive: true, force: true });
436 }
437 }),
438 );
439
440 it.effect("rotates per-thread files when max size is exceeded", () =>
441 Effect.gen(function* () {
442 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
443 const basePath = NodePath.join(tempDir, "provider-native.ndjson");
444
445 try {
446 const store = yield* makeEventNdjsonLogStore(basePath, {
447 maxBytes: 120,
448 maxFiles: 2,
449 batchWindowMs: 0,
450 });
451 const native = store.logger("native");
452 const canonical = store.logger("canonical");
453
454 for (let index = 0; index < 10; index += 1) {
455 const logger = index % 2 === 0 ? native : canonical;
456 yield* logger.write(
457 {
458 type: "session.started",
459 threadId: "provider-thread-rotate",
460 id: `evt-${index}`,
461 payload: "x".repeat(40),
462 },
463 ThreadId.make("thread-rotate"),
464 );
465 }
466 yield* store.close();
467
468 const fileStem = NodePath.basename(ownedLogPath(basePath, "thread-rotate"));
469 const matchingFiles = NodeFS.readdirSync(tempDir)
470 .filter((entry) => entry === fileStem || entry.startsWith(`${fileStem}.`))
471 .toSorted();
472
473 assert.equal(
474 matchingFiles.some((entry) => entry === `${fileStem}.1`),
475 true,
476 );
477 assert.equal(
478 matchingFiles.some((entry) => entry === fileStem || entry === `${fileStem}.2`),
479 true,
480 );
481 assert.equal(
482 matchingFiles.some((entry) => entry === `${fileStem}.3`),
483 false,
484 );
485 } finally {
486 NodeFS.rmSync(tempDir, { recursive: true, force: true });
487 }
488 }),
489 );
490
491 it.effect("enforces aggregate age and byte retention on startup", () =>
492 Effect.gen(function* () {
493 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
494 const basePath = NodePath.join(tempDir, "events.log");
495 const expiredPath = ownedLogPath(basePath, "expired");
496 const oldPath = ownedLogPath(basePath, "old");
497 const newPath = ownedLogPath(basePath, "new");
498 const unrelatedLogPath = NodePath.join(tempDir, "unrelated.log");
499 const legacyLogPath = NodePath.join(tempDir, "legacy-thread.log");
500 const ignoredPath = NodePath.join(tempDir, "ignored.txt");
501
502 try {
503 yield* TestClock.setTime(1_800_000_000_000);
504 const now = yield* Clock.currentTimeMillis;
505 for (const filePath of [expiredPath, oldPath, newPath, unrelatedLogPath, ignoredPath]) {
506 NodeFS.writeFileSync(filePath, "x".repeat(40));
507 }
508 NodeFS.writeFileSync(
509 legacyLogPath,
510 "[2026-01-01T00:00:00.000Z] CANON: legacy provider event\n",
511 );
512 NodeFS.utimesSync(expiredPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000);
513 NodeFS.utimesSync(legacyLogPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000);
514 NodeFS.utimesSync(oldPath, (now - 5_000) / 1_000, (now - 5_000) / 1_000);
515 NodeFS.utimesSync(newPath, now / 1_000, now / 1_000);
516
517 const store = yield* makeEventNdjsonLogStore(basePath, {
518 maxAgeMs: 10_000,
519 maxTotalBytes: 60,
520 });
521 yield* store.close();
522
523 assert.equal(NodeFS.existsSync(expiredPath), false);
524 assert.equal(NodeFS.existsSync(legacyLogPath), false);
525 assert.equal(NodeFS.existsSync(oldPath), false);
526 assert.equal(NodeFS.existsSync(newPath), true);
527 assert.equal(NodeFS.existsSync(unrelatedLogPath), true);
528 assert.equal(NodeFS.existsSync(ignoredPath), true);
529 } finally {
530 NodeFS.rmSync(tempDir, { recursive: true, force: true });
531 }
532 }),
533 );
534
535 it.effect("does not prune an active thread sink during an unrelated flush", () =>
536 Effect.gen(function* () {
537 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
538 const basePath = NodePath.join(tempDir, "events.log");
539 const activePath = ownedLogPath(basePath, "active");
540
541 try {
542 yield* TestClock.setTime(1_800_000_000_000);
543 const store = yield* makeEventNdjsonLogStore(basePath, {
544 batchWindowMs: 0,
545 maxAgeMs: 1,
546 retentionCheckIntervalMs: 1,
547 });
548 const logger = store.logger("native");
549
550 yield* logger.write({ id: "active-before-retention" }, ThreadId.make("active"));
551 assert.equal(NodeFS.existsSync(activePath), true);
552
553 yield* TestClock.adjust("2 millis");
554 yield* logger.write({ id: "retention-trigger" }, ThreadId.make("other"));
555
556 assert.equal(NodeFS.existsSync(activePath), true);
557 yield* store.close();
558 } finally {
559 NodeFS.rmSync(tempDir, { recursive: true, force: true });
560 }
561 }),
562 );
563
564 it("attributes batches that were written before a later chunk fails", () => {
565 const records: ReadonlyArray<PendingRecord> = [
566 {
567 stream: "native",
568 threadSegment: "thread",
569 line: "first",
570 bytes: 5,
571 },
572 {
573 stream: "canonical",
574 threadSegment: "thread",
575 line: "second",
576 bytes: 6,
577 },
578 ];
579 const attributed: Array<PendingRecord> = [];
580 let writes = 0;
581
582 assert.throws(() =>
583 writeBatchedMessages(
584 {
585 write: () => {
586 writes += 1;
587 if (writes === 2) throw new Error("simulated disk exhaustion");
588 },
589 },
590 records,
591 5,
592 (written) => attributed.push(...written),
593 ),
594 );
595 assert.deepEqual(attributed, [records[0]]);
596 });
597
598 it.effect("reports logical provider log writes to resource attribution", () =>
599 Effect.gen(function* () {
600 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
601 const basePath = NodePath.join(tempDir, "provider-native.ndjson");
602
603 try {
604 const attribution = yield* ResourceAttribution.make();
605 const logger = yield* makeEventNdjsonLogger(basePath, {
606 stream: "native",
607 batchWindowMs: 0,
608 attribution,
609 });
610 assert.notEqual(logger, undefined);
611 if (!logger) {
612 return;
613 }
614
615 yield* logger.write({ id: "attributed-event" }, ThreadId.make("thread-attribution"));
616 yield* logger.close();
617
618 const snapshot = yield* attribution.snapshot;
619 assert.equal(snapshot.entries.length, 1);
620 assert.equal(snapshot.entries[0]?.component, "provider-event-log");
621 assert.equal(snapshot.entries[0]?.operation, "native.append");
622 assert.equal(snapshot.entries[0]?.count, 1);
623 assert.isAbove(snapshot.entries[0]?.logicalWriteBytes ?? 0, 0);
624 } finally {
625 NodeFS.rmSync(tempDir, { recursive: true, force: true });
626 }
627 }),
628 );
629});