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));
24const decodeUnknownJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
25
26function ownedLogPath(basePath: string, segment: string): string {
27 const basename = NodePath.basename(basePath);
28 const extension = NodePath.extname(basename);
29 const stem = extension.length > 0 ? basename.slice(0, -extension.length) : basename;
30 return NodePath.join(NodePath.dirname(basePath), `${stem}.${segment}.log`);
31}
32
33function parseLogLine(line: string) {
34 const match = /^\[([^\]]+)\] ([A-Z]+): (.+)$/.exec(line);
35 assert.notEqual(match, null);
36 if (!match) {
37 throw new Error(`invalid log line: ${line}`);
38 }
39 const observedAt = match[1];
40 const stream = match[2];
41 const payload = match[3];
42 if (!observedAt || !stream || payload === undefined) {
43 throw new Error(`invalid log line: ${line}`);
44 }
45 return {
46 observedAt,
47 stream,
48 payload,
49 };
50}
51
52describe("EventNdjsonLogger", () => {
53 it.effect("summarizes circular events without exposing their contents in diagnostics", () => {
54 const messages: Array<unknown> = [];
55 const logCapture = Logger.make<unknown, void>(({ message }) => {
56 if (Array.isArray(message)) {
57 messages.push(...message);
58 } else {
59 messages.push(message);
60 }
61 });
62 const secret = "secret-circular-event-value";
63
64 return Effect.gen(function* () {
65 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
66 const basePath = NodePath.join(tempDir, "provider-native.ndjson");
67 const circular: Record<string, unknown> = { secret };
68 circular.self = circular;
69
70 try {
71 const logger = yield* makeEventNdjsonLogger(basePath, { stream: "native" });
72 assert.exists(logger);
73 if (!logger) return;
74 yield* logger.write(circular, ThreadId.make("thread-1"));
75 yield* logger.close();
76
77 const serialized = encodeUnknownJson(messages);
78 assert.notInclude(serialized, secret);
79 const line = parseLogLine(
80 NodeFS.readFileSync(ownedLogPath(basePath, "thread-1"), "utf8").trim(),
81 );
82 assert.equal(line.payload, '{"truncated":true}');
83 } finally {
84 NodeFS.rmSync(tempDir, { recursive: true, force: true });
85 }
86 }).pipe(Effect.provide(Logger.layer([logCapture], { mergeWithExisting: false })));
87 });
88
89 it.effect("writes effect-style lines to thread-scoped files", () =>
90 Effect.gen(function* () {
91 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
92 const basePath = NodePath.join(tempDir, "provider-native.ndjson");
93
94 try {
95 const logger = yield* makeEventNdjsonLogger(basePath, { stream: "native" });
96 assert.notEqual(logger, undefined);
97 if (!logger) {
98 return;
99 }
100
101 yield* logger.write(
102 { threadId: "provider-thread-1", id: "evt-1" },
103 ThreadId.make("thread-1"),
104 );
105 yield* logger.write(
106 { type: "turn.completed", threadId: "provider-thread-2", id: "evt-2" },
107 ThreadId.make("thread-2"),
108 );
109 yield* logger.close();
110
111 const threadOnePath = ownedLogPath(basePath, "thread-1");
112 const threadTwoPath = ownedLogPath(basePath, "thread-2");
113 assert.equal(NodeFS.existsSync(threadOnePath), true);
114 assert.equal(NodeFS.existsSync(threadTwoPath), true);
115
116 const first = parseLogLine(NodeFS.readFileSync(threadOnePath, "utf8").trim());
117 const second = parseLogLine(NodeFS.readFileSync(threadTwoPath, "utf8").trim());
118
119 assert.equal(Number.isNaN(Date.parse(first.observedAt)), false);
120 assert.equal(first.stream, "NTIVE");
121 assert.equal(first.payload, '{"threadId":"provider-thread-1","id":"evt-1"}');
122
123 assert.equal(Number.isNaN(Date.parse(second.observedAt)), false);
124 assert.equal(second.stream, "NTIVE");
125 assert.equal(
126 second.payload,
127 '{"type":"turn.completed","threadId":"provider-thread-2","id":"evt-2"}',
128 );
129 } finally {
130 NodeFS.rmSync(tempDir, { recursive: true, force: true });
131 }
132 }),
133 );
134
135 it.effect(
136 "falls back to a global segment when orchestration thread id is missing or invalid",
137 () =>
138 Effect.gen(function* () {
139 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
140 const basePath = NodePath.join(tempDir, "provider-canonical.ndjson");
141
142 try {
143 const logger = yield* makeEventNdjsonLogger(basePath, { stream: "orchestration" });
144 assert.notEqual(logger, undefined);
145 if (!logger) {
146 return;
147 }
148
149 yield* logger.write({ id: "evt-no-thread" }, null);
150 yield* logger.write({ id: "evt-invalid-thread" }, "!!!" as unknown as ThreadId);
151 yield* logger.close();
152
153 const globalPath = ownedLogPath(basePath, "_global");
154 assert.equal(NodeFS.existsSync(globalPath), true);
155 const lines = NodeFS.readFileSync(globalPath, "utf8")
156 .trim()
157 .split("\n")
158 .map((line) => parseLogLine(line));
159 assert.equal(lines.length, 2);
160 assert.equal(Number.isNaN(Date.parse(lines[0]?.observedAt ?? "")), false);
161 assert.equal(Number.isNaN(Date.parse(lines[1]?.observedAt ?? "")), false);
162 assert.equal(lines[0]?.stream, "ORCH");
163 assert.equal(lines[0]?.payload, '{"id":"evt-no-thread"}');
164 assert.equal(lines[1]?.stream, "ORCH");
165 assert.equal(lines[1]?.payload, '{"id":"evt-invalid-thread"}');
166 } finally {
167 NodeFS.rmSync(tempDir, { recursive: true, force: true });
168 }
169 }),
170 );
171
172 it.effect("shares one thread writer across native and canonical streams", () =>
173 Effect.gen(function* () {
174 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
175 const basePath = NodePath.join(tempDir, "events.log");
176
177 try {
178 const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 });
179 const native = store.logger("native");
180 const canonical = store.logger("canonical");
181 const threadId = ThreadId.make("thread-shared");
182
183 yield* native.write({ id: "native-event" }, threadId);
184 yield* canonical.write({ type: "item.completed", id: "canonical-event" }, threadId);
185 yield* store.close();
186
187 const lines = NodeFS.readFileSync(ownedLogPath(basePath, "thread-shared"), "utf8")
188 .trim()
189 .split("\n")
190 .map(parseLogLine);
191
192 assert.deepEqual(
193 lines.map(({ stream, payload }) => ({ stream, payload })),
194 [
195 { stream: "NTIVE", payload: '{"id":"native-event"}' },
196 {
197 stream: "CANON",
198 payload: '{"type":"item.completed","id":"canonical-event"}',
199 },
200 ],
201 );
202 } finally {
203 NodeFS.rmSync(tempDir, { recursive: true, force: true });
204 }
205 }),
206 );
207
208 it.effect("keeps shared store views non-owning when one adapter closes", () =>
209 Effect.gen(function* () {
210 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
211 const basePath = NodePath.join(tempDir, "events.log");
212
213 try {
214 const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 });
215 const native = store.logger("native");
216 const canonical = store.logger("canonical");
217 const threadId = ThreadId.make("thread-shared-close");
218
219 yield* native.write({ id: "before-close" }, threadId);
220 yield* native.close();
221 yield* canonical.write({ type: "item.completed", id: "after-close" }, threadId);
222 yield* store.close();
223
224 const lines = NodeFS.readFileSync(ownedLogPath(basePath, "thread-shared-close"), "utf8")
225 .trim()
226 .split("\n")
227 .map(parseLogLine);
228
229 assert.deepEqual(
230 lines.map(({ stream, payload }) => ({ stream, payload })),
231 [
232 { stream: "NTIVE", payload: '{"id":"before-close"}' },
233 {
234 stream: "CANON",
235 payload: '{"type":"item.completed","id":"after-close"}',
236 },
237 ],
238 );
239 } finally {
240 NodeFS.rmSync(tempDir, { recursive: true, force: true });
241 }
242 }),
243 );
244
245 it.effect("flushes an active batch without a permanent polling loop", () =>
246 Effect.gen(function* () {
247 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
248 const basePath = NodePath.join(tempDir, "events.log");
249 const threadPath = ownedLogPath(basePath, "thread-batched");
250
251 try {
252 const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 1_000 });
253 yield* store
254 .logger("native")
255 .write({ id: "batched-event" }, ThreadId.make("thread-batched"));
256
257 assert.equal(NodeFS.existsSync(threadPath), false);
258 yield* TestClock.adjust(1_000);
259 assert.equal(NodeFS.existsSync(threadPath), true);
260 yield* store.close();
261 } finally {
262 NodeFS.rmSync(tempDir, { recursive: true, force: true });
263 }
264 }),
265 );
266
267 it.effect("does not strand a later batch after an interrupted write", () =>
268 Effect.gen(function* () {
269 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
270 const basePath = NodePath.join(tempDir, "events.log");
271 const threadPath = ownedLogPath(basePath, "thread-interrupted");
272
273 try {
274 const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 1_000 });
275 const logger = store.logger("native");
276 const interruptedWrite = yield* logger
277 .write({ id: "possibly-interrupted" }, ThreadId.make("thread-interrupted"))
278 .pipe(Effect.forkChild);
279 yield* Effect.yieldNow;
280 yield* Fiber.interrupt(interruptedWrite);
281 yield* logger.write({ id: "accepted" }, ThreadId.make("thread-interrupted"));
282
283 yield* TestClock.adjust(1_000);
284
285 assert.equal(NodeFS.existsSync(threadPath), true);
286 assert.include(NodeFS.readFileSync(threadPath, "utf8"), '{"id":"accepted"}');
287 yield* store.close();
288 } finally {
289 NodeFS.rmSync(tempDir, { recursive: true, force: true });
290 }
291 }),
292 );
293
294 it.effect("drops transient provider events before serialization", () =>
295 Effect.gen(function* () {
296 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
297 const basePath = NodePath.join(tempDir, "events.log");
298
299 try {
300 const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 });
301 const canonical = store.logger("canonical");
302 const native = store.logger("native");
303 const threadId = ThreadId.make("thread-filtered");
304 const circularDelta: Record<string, unknown> = { type: "content.delta" };
305 circularDelta["self"] = circularDelta;
306
307 yield* canonical.write(circularDelta, threadId);
308 yield* canonical.write({ type: "item.completed", id: "final" }, threadId);
309 yield* native.write({ type: "content.delta", id: "native-delta" }, threadId);
310 yield* native.write(
311 { method: "item/agentMessage/delta", payload: circularDelta },
312 threadId,
313 );
314 yield* native.write(
315 { method: "thread/realtime/outputAudio/delta", payload: circularDelta },
316 threadId,
317 );
318 yield* native.write(
319 { method: "thread/realtime/transcript/delta", payload: circularDelta },
320 threadId,
321 );
322 yield* native.write({ method: "turn/diff/updated", payload: circularDelta }, threadId);
323 yield* native.write(
324 {
325 event: {
326 direction: "incoming",
327 stage: "decoded",
328 payload: {
329 method: "turn/diff/updated",
330 get params() {
331 throw new Error("unused diff snapshots must not be traversed");
332 },
333 },
334 },
335 },
336 threadId,
337 );
338 yield* native.write(
339 {
340 event: {
341 method: "claude/stream_event/content_block_delta/text_delta",
342 payload: circularDelta,
343 },
344 },
345 threadId,
346 );
347 yield* native.write(
348 {
349 event: {
350 method: "session/update",
351 payload: { update: { sessionUpdate: "agent_message_chunk" } },
352 },
353 },
354 threadId,
355 );
356 yield* native.write(
357 {
358 event: {
359 direction: "incoming",
360 stage: "decoded",
361 payload: { method: "item/commandExecution/outputDelta", params: circularDelta },
362 },
363 },
364 threadId,
365 );
366 yield* native.write(
367 {
368 event: {
369 direction: "incoming",
370 stage: "decoded",
371 payload: {
372 type: "stream_event",
373 event: { type: "content_block_delta", delta: circularDelta },
374 },
375 },
376 },
377 threadId,
378 );
379 yield* native.write(
380 {
381 event: {
382 direction: "incoming",
383 stage: "raw",
384 get payload() {
385 throw new Error("raw frames must not be inspected");
386 },
387 },
388 },
389 threadId,
390 );
391 yield* native.write(
392 {
393 event: {
394 type: "message.part.updated",
395 payload: { properties: { part: { type: "text" } } },
396 },
397 },
398 threadId,
399 );
400 yield* native.write(
401 {
402 event: {
403 type: "message.part.updated",
404 payload: {
405 properties: {
406 part: { type: "tool", state: { status: "running", output: "progress" } },
407 },
408 },
409 },
410 },
411 threadId,
412 );
413 yield* native.write({ type: "turn.completed", id: "native-final" }, threadId);
414 yield* store.close();
415
416 const lines = NodeFS.readFileSync(ownedLogPath(basePath, "thread-filtered"), "utf8")
417 .trim()
418 .split("\n")
419 .map(parseLogLine);
420
421 assert.deepEqual(
422 lines.map(({ stream, payload }) => ({ stream, payload })),
423 [
424 { stream: "CANON", payload: '{"type":"item.completed","id":"final"}' },
425 { stream: "NTIVE", payload: '{"type":"turn.completed","id":"native-final"}' },
426 ],
427 );
428 } finally {
429 NodeFS.rmSync(tempDir, { recursive: true, force: true });
430 }
431 }),
432 );
433
434 it.effect("summarizes large histories without reading their items", () =>
435 Effect.gen(function* () {
436 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
437 const basePath = NodePath.join(tempDir, "events.log");
438 const turns = Array.from({ length: 10_000 });
439 Object.defineProperty(turns, 0, {
440 get: () => {
441 throw new Error("history must not be serialized");
442 },
443 });
444
445 try {
446 const store = yield* makeEventNdjsonLogStore(basePath);
447 yield* store.logger("native").write(
448 {
449 provider: "codex",
450 event: {
451 direction: "incoming",
452 stage: "decoded",
453 payload: { id: 42, result: { thread: { id: "native-thread", turns } } },
454 },
455 },
456 ThreadId.make("large-history"),
457 );
458 yield* store.close();
459
460 const contents = NodeFS.readFileSync(ownedLogPath(basePath, "large-history"), "utf8");
461 assert.isBelow(Buffer.byteLength(contents), 2_048);
462 const record = decodeUnknownJson(parseLogLine(contents.trim()).payload);
463 assert.nestedPropertyVal(record, "event.payload.id", 42);
464 assert.nestedPropertyVal(record, "event.payload.result.thread.id", "native-thread");
465 assert.nestedPropertyVal(record, "event.payload.result.thread.turns.itemCount", 10_000);
466 } finally {
467 NodeFS.rmSync(tempDir, { recursive: true, force: true });
468 }
469 }),
470 );
471
472 it.effect("bounds oversized records while retaining failure details", () =>
473 Effect.gen(function* () {
474 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
475 const basePath = NodePath.join(tempDir, "events.log");
476
477 try {
478 const store = yield* makeEventNdjsonLogStore(basePath);
479 const logger = store.logger("native");
480 const threadId = ThreadId.make("large-error");
481 const failure = {
482 method: "error",
483 params: {
484 threadId: "native-thread",
485 turnId: "native-turn",
486 error: { message: "The provider is unavailable.", code: "overloaded" },
487 output: "x".repeat(128 * 1_024),
488 },
489 };
490 yield* logger.write(failure, threadId);
491 yield* logger.write({ id: "escaped", output: "\u0000".repeat(20_000) }, threadId);
492 yield* store.close();
493
494 const contents = NodeFS.readFileSync(ownedLogPath(basePath, "large-error"), "utf8");
495 const records = contents
496 .trim()
497 .split("\n")
498 .map((line) => decodeUnknownJson(parseLogLine(line).payload));
499 assert.isBelow(Buffer.byteLength(contents), 64 * 1_024);
500 assert.equal(records.length, 2);
501 assert.nestedPropertyVal(records[0], "params.threadId", "native-thread");
502 assert.nestedPropertyVal(records[0], "params.turnId", "native-turn");
503 assert.nestedPropertyVal(
504 records[0],
505 "params.error.message",
506 "The provider is unavailable.",
507 );
508 assert.nestedPropertyVal(records[0], "params.error.code", "overloaded");
509 assert.propertyVal(records[1], "id", "escaped");
510 } finally {
511 NodeFS.rmSync(tempDir, { recursive: true, force: true });
512 }
513 }),
514 );
515
516 it.effect("bounds canonical diff snapshots before serializing their duplicate payloads", () =>
517 Effect.gen(function* () {
518 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
519 const basePath = NodePath.join(tempDir, "events.log");
520 const threadId = ThreadId.make("large-diff");
521 const diff = "diff-payload".repeat(128 * 1_024);
522 try {
523 const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 });
524 yield* store.logger("canonical").write(
525 {
526 type: "turn.diff.updated",
527 threadId,
528 turnId: "native-turn",
529 raw: { method: "turn/diff/updated", payload: { diff } },
530 payload: { unifiedDiff: diff },
531 },
532 threadId,
533 );
534 yield* store.close();
535 const contents = NodeFS.readFileSync(ownedLogPath(basePath, "large-diff"), "utf8");
536 assert.isBelow(Buffer.byteLength(contents), 2_048);
537 const record = decodeUnknownJson(parseLogLine(contents.trim()).payload);
538 assert.propertyVal(record, "type", "turn.diff.updated");
539 assert.propertyVal(record, "threadId", threadId);
540 assert.propertyVal(record, "turnId", "native-turn");
541 } finally {
542 NodeFS.rmSync(tempDir, { recursive: true, force: true });
543 }
544 }),
545 );
546
547 it.effect("keeps OpenCode tool input, final output, and errors in native logs", () =>
548 Effect.gen(function* () {
549 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
550 const basePath = NodePath.join(tempDir, "events.log");
551 const threadId = ThreadId.make("thread-tool-lifecycle");
552
553 try {
554 const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 });
555 const native = store.logger("native");
556 const input = { command: "run-build" };
557 const states = [
558 { status: "pending", input },
559 { status: "completed", input, output: "Build complete", time: { start: 1, end: 2 } },
560 { status: "error", input, error: "Build failed", time: { start: 3, end: 4 } },
561 { status: "unknown", input },
562 null,
563 ];
564 const events = states.map((state) => ({
565 event: {
566 type: "message.part.updated",
567 payload: { properties: { part: { type: "tool", state } } },
568 },
569 }));
570 for (const event of events) {
571 yield* native.write(event, threadId);
572 }
573 yield* store.close();
574
575 const payloads = NodeFS.readFileSync(
576 ownedLogPath(basePath, "thread-tool-lifecycle"),
577 "utf8",
578 )
579 .trim()
580 .split("\n")
581 .map((line) => parseLogLine(line).payload);
582 assert.deepEqual(
583 payloads,
584 events.map((event) => encodeUnknownJson(event)),
585 );
586 } finally {
587 NodeFS.rmSync(tempDir, { recursive: true, force: true });
588 }
589 }),
590 );
591
592 it.effect("contains hostile event accessors inside guarded serialization", () =>
593 Effect.gen(function* () {
594 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
595 const basePath = NodePath.join(tempDir, "events.log");
596
597 try {
598 const logger = yield* makeEventNdjsonLogger(basePath, {
599 stream: "canonical",
600 batchWindowMs: 0,
601 });
602 assert.exists(logger);
603 if (!logger) return;
604 const hostile = new Proxy(
605 { id: "hostile" },
606 {
607 get(_target, property) {
608 if (property === "type") throw new Error("blocked");
609 return undefined;
610 },
611 },
612 );
613
614 yield* logger.write(hostile, ThreadId.make("thread-hostile"));
615 yield* logger.close();
616
617 const contents = NodeFS.readFileSync(ownedLogPath(basePath, "thread-hostile"), "utf8");
618 assert.notInclude(contents, "blocked");
619 } finally {
620 NodeFS.rmSync(tempDir, { recursive: true, force: true });
621 }
622 }),
623 );
624
625 it.effect("serializes concurrent first writes for the same segment", () =>
626 Effect.gen(function* () {
627 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
628 const basePath = NodePath.join(tempDir, "provider-canonical.ndjson");
629
630 try {
631 const logger = yield* makeEventNdjsonLogger(basePath, {
632 stream: "canonical",
633 batchWindowMs: 0,
634 });
635 assert.notEqual(logger, undefined);
636 if (!logger) {
637 return;
638 }
639
640 yield* Effect.all(
641 [
642 logger.write({ id: "evt-concurrent-1" }, null),
643 logger.write({ id: "evt-concurrent-2" }, null),
644 ],
645 { concurrency: "unbounded" },
646 );
647 yield* logger.close();
648
649 const globalPath = ownedLogPath(basePath, "_global");
650 assert.equal(NodeFS.existsSync(globalPath), true);
651 const lines = NodeFS.readFileSync(globalPath, "utf8")
652 .trim()
653 .split("\n")
654 .map((line) => parseLogLine(line));
655
656 assert.equal(lines.length, 2);
657 assert.deepEqual(lines.map((line) => line.payload).toSorted(), [
658 '{"id":"evt-concurrent-1"}',
659 '{"id":"evt-concurrent-2"}',
660 ]);
661 } finally {
662 NodeFS.rmSync(tempDir, { recursive: true, force: true });
663 }
664 }),
665 );
666
667 it.effect("rotates per-thread files when max size is exceeded", () =>
668 Effect.gen(function* () {
669 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
670 const basePath = NodePath.join(tempDir, "provider-native.ndjson");
671
672 try {
673 const store = yield* makeEventNdjsonLogStore(basePath, {
674 maxBytes: 120,
675 maxFiles: 2,
676 batchWindowMs: 0,
677 });
678 const native = store.logger("native");
679 const canonical = store.logger("canonical");
680
681 for (let index = 0; index < 10; index += 1) {
682 const logger = index % 2 === 0 ? native : canonical;
683 yield* logger.write(
684 {
685 type: "session.started",
686 threadId: "provider-thread-rotate",
687 id: `evt-${index}`,
688 payload: "x".repeat(40),
689 },
690 ThreadId.make("thread-rotate"),
691 );
692 }
693 yield* store.close();
694
695 const fileStem = NodePath.basename(ownedLogPath(basePath, "thread-rotate"));
696 const matchingFiles = NodeFS.readdirSync(tempDir)
697 .filter((entry) => entry === fileStem || entry.startsWith(`${fileStem}.`))
698 .toSorted();
699
700 assert.equal(
701 matchingFiles.some((entry) => entry === `${fileStem}.1`),
702 true,
703 );
704 assert.equal(
705 matchingFiles.some((entry) => entry === fileStem || entry === `${fileStem}.2`),
706 true,
707 );
708 assert.equal(
709 matchingFiles.some((entry) => entry === `${fileStem}.3`),
710 false,
711 );
712 } finally {
713 NodeFS.rmSync(tempDir, { recursive: true, force: true });
714 }
715 }),
716 );
717
718 it.effect("enforces aggregate age and byte retention on startup", () =>
719 Effect.gen(function* () {
720 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
721 const basePath = NodePath.join(tempDir, "events.log");
722 const expiredPath = ownedLogPath(basePath, "expired");
723 const oldPath = ownedLogPath(basePath, "old");
724 const newPath = ownedLogPath(basePath, "new");
725 const unrelatedLogPath = NodePath.join(tempDir, "unrelated.log");
726 const legacyLogPath = NodePath.join(tempDir, "legacy-thread.log");
727 const ignoredPath = NodePath.join(tempDir, "ignored.txt");
728
729 try {
730 yield* TestClock.setTime(1_800_000_000_000);
731 const now = yield* Clock.currentTimeMillis;
732 for (const filePath of [expiredPath, oldPath, newPath, unrelatedLogPath, ignoredPath]) {
733 NodeFS.writeFileSync(filePath, "x".repeat(40));
734 }
735 NodeFS.writeFileSync(
736 legacyLogPath,
737 "[2026-01-01T00:00:00.000Z] CANON: legacy provider event\n",
738 );
739 NodeFS.utimesSync(expiredPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000);
740 NodeFS.utimesSync(legacyLogPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000);
741 NodeFS.utimesSync(oldPath, (now - 5_000) / 1_000, (now - 5_000) / 1_000);
742 NodeFS.utimesSync(newPath, now / 1_000, now / 1_000);
743
744 const store = yield* makeEventNdjsonLogStore(basePath, {
745 maxAgeMs: 10_000,
746 maxTotalBytes: 60,
747 });
748 yield* store.close();
749
750 assert.equal(NodeFS.existsSync(expiredPath), false);
751 assert.equal(NodeFS.existsSync(legacyLogPath), false);
752 assert.equal(NodeFS.existsSync(oldPath), false);
753 assert.equal(NodeFS.existsSync(newPath), true);
754 assert.equal(NodeFS.existsSync(unrelatedLogPath), true);
755 assert.equal(NodeFS.existsSync(ignoredPath), true);
756 } finally {
757 NodeFS.rmSync(tempDir, { recursive: true, force: true });
758 }
759 }),
760 );
761
762 it.effect("does not prune an active thread sink during an unrelated flush", () =>
763 Effect.gen(function* () {
764 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
765 const basePath = NodePath.join(tempDir, "events.log");
766 const activePath = ownedLogPath(basePath, "active");
767
768 try {
769 yield* TestClock.setTime(1_800_000_000_000);
770 const store = yield* makeEventNdjsonLogStore(basePath, {
771 batchWindowMs: 0,
772 maxAgeMs: 1,
773 retentionCheckIntervalMs: 1,
774 });
775 const logger = store.logger("native");
776
777 yield* logger.write({ id: "active-before-retention" }, ThreadId.make("active"));
778 assert.equal(NodeFS.existsSync(activePath), true);
779
780 yield* TestClock.adjust("2 millis");
781 yield* logger.write({ id: "retention-trigger" }, ThreadId.make("other"));
782
783 assert.equal(NodeFS.existsSync(activePath), true);
784 yield* store.close();
785 } finally {
786 NodeFS.rmSync(tempDir, { recursive: true, force: true });
787 }
788 }),
789 );
790
791 it("attributes batches that were written before a later chunk fails", () => {
792 const records: ReadonlyArray<PendingRecord> = [
793 {
794 stream: "native",
795 threadSegment: "thread",
796 line: "first",
797 bytes: 5,
798 },
799 {
800 stream: "canonical",
801 threadSegment: "thread",
802 line: "second",
803 bytes: 6,
804 },
805 ];
806 const attributed: Array<PendingRecord> = [];
807 let writes = 0;
808
809 assert.throws(() =>
810 writeBatchedMessages(
811 {
812 write: () => {
813 writes += 1;
814 if (writes === 2) throw new Error("simulated disk exhaustion");
815 },
816 },
817 records,
818 5,
819 (written) => attributed.push(...written),
820 ),
821 );
822 assert.deepEqual(attributed, [records[0]]);
823 });
824
825 it.effect("reports logical provider log writes to resource attribution", () =>
826 Effect.gen(function* () {
827 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
828 const basePath = NodePath.join(tempDir, "provider-native.ndjson");
829
830 try {
831 const attribution = yield* ResourceAttribution.make();
832 const logger = yield* makeEventNdjsonLogger(basePath, {
833 stream: "native",
834 batchWindowMs: 0,
835 attribution,
836 });
837 assert.notEqual(logger, undefined);
838 if (!logger) {
839 return;
840 }
841
842 yield* logger.write({ id: "attributed-event" }, ThreadId.make("thread-attribution"));
843 yield* logger.close();
844
845 const snapshot = yield* attribution.snapshot;
846 assert.equal(snapshot.entries.length, 1);
847 assert.equal(snapshot.entries[0]?.component, "provider-event-log");
848 assert.equal(snapshot.entries[0]?.operation, "native.append");
849 assert.equal(snapshot.entries[0]?.count, 1);
850 assert.isAbove(snapshot.entries[0]?.logicalWriteBytes ?? 0, 0);
851 } finally {
852 NodeFS.rmSync(tempDir, { recursive: true, force: true });
853 }
854 }),
855 );
856});