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.UnknownFromJsonString);
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 canonical 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* store.close();
306
307 const lines = NodeFS.readFileSync(ownedLogPath(basePath, "thread-filtered"), "utf8")
308 .trim()
309 .split("\n")
310 .map(parseLogLine);
311
312 assert.deepEqual(
313 lines.map(({ stream, payload }) => ({ stream, payload })),
314 [
315 { stream: "CANON", payload: '{"type":"item.completed","id":"final"}' },
316 { stream: "NTIVE", payload: '{"type":"content.delta","id":"native-delta"}' },
317 ],
318 );
319 } finally {
320 NodeFS.rmSync(tempDir, { recursive: true, force: true });
321 }
322 }),
323 );
324
325 it.effect("contains hostile event accessors inside guarded serialization", () =>
326 Effect.gen(function* () {
327 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
328 const basePath = NodePath.join(tempDir, "events.log");
329
330 try {
331 const logger = yield* makeEventNdjsonLogger(basePath, {
332 stream: "canonical",
333 batchWindowMs: 0,
334 });
335 assert.exists(logger);
336 if (!logger) return;
337 const hostile = new Proxy(
338 { id: "hostile" },
339 {
340 get(_target, property) {
341 if (property === "type") throw new Error("blocked");
342 return undefined;
343 },
344 },
345 );
346
347 yield* logger.write(hostile, ThreadId.make("thread-hostile"));
348 yield* logger.close();
349
350 const contents = NodeFS.readFileSync(ownedLogPath(basePath, "thread-hostile"), "utf8");
351 assert.notInclude(contents, "blocked");
352 } finally {
353 NodeFS.rmSync(tempDir, { recursive: true, force: true });
354 }
355 }),
356 );
357
358 it.effect("serializes concurrent first writes for the same segment", () =>
359 Effect.gen(function* () {
360 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
361 const basePath = NodePath.join(tempDir, "provider-canonical.ndjson");
362
363 try {
364 const logger = yield* makeEventNdjsonLogger(basePath, {
365 stream: "canonical",
366 batchWindowMs: 0,
367 });
368 assert.notEqual(logger, undefined);
369 if (!logger) {
370 return;
371 }
372
373 yield* Effect.all(
374 [
375 logger.write({ id: "evt-concurrent-1" }, null),
376 logger.write({ id: "evt-concurrent-2" }, null),
377 ],
378 { concurrency: "unbounded" },
379 );
380 yield* logger.close();
381
382 const globalPath = ownedLogPath(basePath, "_global");
383 assert.equal(NodeFS.existsSync(globalPath), true);
384 const lines = NodeFS.readFileSync(globalPath, "utf8")
385 .trim()
386 .split("\n")
387 .map((line) => parseLogLine(line));
388
389 assert.equal(lines.length, 2);
390 assert.deepEqual(lines.map((line) => line.payload).toSorted(), [
391 '{"id":"evt-concurrent-1"}',
392 '{"id":"evt-concurrent-2"}',
393 ]);
394 } finally {
395 NodeFS.rmSync(tempDir, { recursive: true, force: true });
396 }
397 }),
398 );
399
400 it.effect("rotates per-thread files when max size is exceeded", () =>
401 Effect.gen(function* () {
402 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
403 const basePath = NodePath.join(tempDir, "provider-native.ndjson");
404
405 try {
406 const store = yield* makeEventNdjsonLogStore(basePath, {
407 maxBytes: 120,
408 maxFiles: 2,
409 batchWindowMs: 0,
410 });
411 const native = store.logger("native");
412 const canonical = store.logger("canonical");
413
414 for (let index = 0; index < 10; index += 1) {
415 const logger = index % 2 === 0 ? native : canonical;
416 yield* logger.write(
417 {
418 type: "session.started",
419 threadId: "provider-thread-rotate",
420 id: `evt-${index}`,
421 payload: "x".repeat(40),
422 },
423 ThreadId.make("thread-rotate"),
424 );
425 }
426 yield* store.close();
427
428 const fileStem = NodePath.basename(ownedLogPath(basePath, "thread-rotate"));
429 const matchingFiles = NodeFS.readdirSync(tempDir)
430 .filter((entry) => entry === fileStem || entry.startsWith(`${fileStem}.`))
431 .toSorted();
432
433 assert.equal(
434 matchingFiles.some((entry) => entry === `${fileStem}.1`),
435 true,
436 );
437 assert.equal(
438 matchingFiles.some((entry) => entry === fileStem || entry === `${fileStem}.2`),
439 true,
440 );
441 assert.equal(
442 matchingFiles.some((entry) => entry === `${fileStem}.3`),
443 false,
444 );
445 } finally {
446 NodeFS.rmSync(tempDir, { recursive: true, force: true });
447 }
448 }),
449 );
450
451 it.effect("enforces aggregate age and byte retention on startup", () =>
452 Effect.gen(function* () {
453 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
454 const basePath = NodePath.join(tempDir, "events.log");
455 const expiredPath = ownedLogPath(basePath, "expired");
456 const oldPath = ownedLogPath(basePath, "old");
457 const newPath = ownedLogPath(basePath, "new");
458 const unrelatedLogPath = NodePath.join(tempDir, "unrelated.log");
459 const legacyLogPath = NodePath.join(tempDir, "legacy-thread.log");
460 const ignoredPath = NodePath.join(tempDir, "ignored.txt");
461
462 try {
463 yield* TestClock.setTime(1_800_000_000_000);
464 const now = yield* Clock.currentTimeMillis;
465 for (const filePath of [expiredPath, oldPath, newPath, unrelatedLogPath, ignoredPath]) {
466 NodeFS.writeFileSync(filePath, "x".repeat(40));
467 }
468 NodeFS.writeFileSync(
469 legacyLogPath,
470 "[2026-01-01T00:00:00.000Z] CANON: legacy provider event\n",
471 );
472 NodeFS.utimesSync(expiredPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000);
473 NodeFS.utimesSync(legacyLogPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000);
474 NodeFS.utimesSync(oldPath, (now - 5_000) / 1_000, (now - 5_000) / 1_000);
475 NodeFS.utimesSync(newPath, now / 1_000, now / 1_000);
476
477 const store = yield* makeEventNdjsonLogStore(basePath, {
478 maxAgeMs: 10_000,
479 maxTotalBytes: 60,
480 });
481 yield* store.close();
482
483 assert.equal(NodeFS.existsSync(expiredPath), false);
484 assert.equal(NodeFS.existsSync(legacyLogPath), false);
485 assert.equal(NodeFS.existsSync(oldPath), false);
486 assert.equal(NodeFS.existsSync(newPath), true);
487 assert.equal(NodeFS.existsSync(unrelatedLogPath), true);
488 assert.equal(NodeFS.existsSync(ignoredPath), true);
489 } finally {
490 NodeFS.rmSync(tempDir, { recursive: true, force: true });
491 }
492 }),
493 );
494
495 it.effect("does not prune an active thread sink during an unrelated flush", () =>
496 Effect.gen(function* () {
497 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
498 const basePath = NodePath.join(tempDir, "events.log");
499 const activePath = ownedLogPath(basePath, "active");
500
501 try {
502 yield* TestClock.setTime(1_800_000_000_000);
503 const store = yield* makeEventNdjsonLogStore(basePath, {
504 batchWindowMs: 0,
505 maxAgeMs: 1,
506 retentionCheckIntervalMs: 1,
507 });
508 const logger = store.logger("native");
509
510 yield* logger.write({ id: "active-before-retention" }, ThreadId.make("active"));
511 assert.equal(NodeFS.existsSync(activePath), true);
512
513 yield* TestClock.adjust("2 millis");
514 yield* logger.write({ id: "retention-trigger" }, ThreadId.make("other"));
515
516 assert.equal(NodeFS.existsSync(activePath), true);
517 yield* store.close();
518 } finally {
519 NodeFS.rmSync(tempDir, { recursive: true, force: true });
520 }
521 }),
522 );
523
524 it("attributes batches that were written before a later chunk fails", () => {
525 const records: ReadonlyArray<PendingRecord> = [
526 {
527 stream: "native",
528 threadSegment: "thread",
529 line: "first",
530 bytes: 5,
531 },
532 {
533 stream: "canonical",
534 threadSegment: "thread",
535 line: "second",
536 bytes: 6,
537 },
538 ];
539 const attributed: Array<PendingRecord> = [];
540 let writes = 0;
541
542 assert.throws(() =>
543 writeBatchedMessages(
544 {
545 write: () => {
546 writes += 1;
547 if (writes === 2) throw new Error("simulated disk exhaustion");
548 },
549 },
550 records,
551 5,
552 (written) => attributed.push(...written),
553 ),
554 );
555 assert.deepEqual(attributed, [records[0]]);
556 });
557
558 it.effect("reports logical provider log writes to resource attribution", () =>
559 Effect.gen(function* () {
560 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
561 const basePath = NodePath.join(tempDir, "provider-native.ndjson");
562
563 try {
564 const attribution = yield* ResourceAttribution.make();
565 const logger = yield* makeEventNdjsonLogger(basePath, {
566 stream: "native",
567 batchWindowMs: 0,
568 attribution,
569 });
570 assert.notEqual(logger, undefined);
571 if (!logger) {
572 return;
573 }
574
575 yield* logger.write({ id: "attributed-event" }, ThreadId.make("thread-attribution"));
576 yield* logger.close();
577
578 const snapshot = yield* attribution.snapshot;
579 assert.equal(snapshot.entries.length, 1);
580 assert.equal(snapshot.entries[0]?.component, "provider-event-log");
581 assert.equal(snapshot.entries[0]?.operation, "native.append");
582 assert.equal(snapshot.entries[0]?.count, 1);
583 assert.isAbove(snapshot.entries[0]?.logicalWriteBytes ?? 0, 0);
584 } finally {
585 NodeFS.rmSync(tempDir, { recursive: true, force: true });
586 }
587 }),
588 );
589});