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