Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import * as DateTime from "effect/DateTime";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Logger from "effect/Logger";
7import * as Option from "effect/Option";
8import * as PlatformError from "effect/PlatformError";
9import * as References from "effect/References";
10import * as Stream from "effect/Stream";
11
12import * as TraceDiagnostics from "./TraceDiagnostics.ts";
13
14function ns(ms: number): string {
15 return String(BigInt(ms) * 1_000_000n);
16}
17
18function record(input: {
19 readonly name: string;
20 readonly traceId: string;
21 readonly spanId: string;
22 readonly startMs: number;
23 readonly durationMs: number;
24 readonly exit?: { readonly _tag: "Success" | "Failure" | "Interrupted"; readonly cause?: string };
25 readonly events?: ReadonlyArray<unknown>;
26}) {
27 return JSON.stringify({
28 type: "effect-span",
29 name: input.name,
30 traceId: input.traceId,
31 spanId: input.spanId,
32 sampled: true,
33 kind: "internal",
34 startTimeUnixNano: ns(input.startMs),
35 endTimeUnixNano: ns(input.startMs + input.durationMs),
36 durationMs: input.durationMs,
37 attributes: {},
38 events: input.events ?? [],
39 links: [],
40 exit: input.exit ?? { _tag: "Success" },
41 });
42}
43
44const traceFilePath = "/tmp/server.trace.ndjson";
45const readAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
46
47function aggregateLines(lines: ReadonlyArray<string>) {
48 const aggregator = TraceDiagnostics.makeTraceDiagnosticsAggregator();
49 lines.forEach(aggregator.addLine);
50 return aggregator.finish({
51 traceFilePath,
52 scannedFilePaths: TraceDiagnostics.toRotatedTracePaths(traceFilePath, 1),
53 readAt,
54 });
55}
56
57function readTraces(fileSystem: Partial<FileSystem.FileSystem>) {
58 return TraceDiagnostics.readTraceDiagnostics({ traceFilePath, maxFiles: 1, readAt }).pipe(
59 Effect.provide(TraceDiagnostics.layer.pipe(Layer.provide(FileSystem.layerNoop(fileSystem)))),
60 );
61}
62
63describe("TraceDiagnostics", () => {
64 it.effect("aggregates failures, slow spans, log levels, and parse errors", () =>
65 Effect.sync(() => {
66 const diagnostics = aggregateLines([
67 record({
68 name: "server.getConfig",
69 traceId: "trace-a",
70 spanId: "span-a",
71 startMs: 1_000,
72 durationMs: 50,
73 }),
74 "not-json",
75 record({
76 name: "orchestration.dispatch",
77 traceId: "trace-b",
78 spanId: "span-b",
79 startMs: 2_000,
80 durationMs: 1_500,
81 exit: { _tag: "Failure", cause: "Provider crashed" },
82 events: [
83 {
84 name: "provider failed",
85 timeUnixNano: ns(3_400),
86 attributes: { "effect.logLevel": "Error" },
87 },
88 ],
89 }),
90 record({
91 name: "orchestration.dispatch",
92 traceId: "trace-c",
93 spanId: "span-c",
94 startMs: 4_000,
95 durationMs: 250,
96 exit: { _tag: "Failure", cause: "Provider crashed" },
97 }),
98 record({
99 name: "git.status",
100 traceId: "trace-d",
101 spanId: "span-d",
102 startMs: 5_000,
103 durationMs: 25,
104 exit: { _tag: "Interrupted", cause: "Interrupted" },
105 events: [
106 {
107 name: "status delayed",
108 timeUnixNano: ns(5_010),
109 attributes: { "effect.logLevel": "Warning" },
110 },
111 ],
112 }),
113 ]);
114
115 assert.equal(diagnostics.recordCount, 4);
116 assert.equal(DateTime.formatIso(diagnostics.readAt), "2026-05-05T10:00:00.000Z");
117 assert.equal(
118 Option.match(diagnostics.firstSpanAt, {
119 onNone: () => null,
120 onSome: DateTime.formatIso,
121 }),
122 "1970-01-01T00:00:01.000Z",
123 );
124 assert.equal(
125 Option.match(diagnostics.lastSpanAt, {
126 onNone: () => null,
127 onSome: DateTime.formatIso,
128 }),
129 "1970-01-01T00:00:05.025Z",
130 );
131 assert.equal(diagnostics.parseErrorCount, 1);
132 assert.equal(diagnostics.failureCount, 2);
133 assert.equal(diagnostics.interruptionCount, 1);
134 assert.equal(diagnostics.slowSpanCount, 1);
135 assert.equal(diagnostics.logLevelCounts.Error, 1);
136 assert.equal(diagnostics.logLevelCounts.Warning, 1);
137 assert.equal(diagnostics.commonFailures[0]?.name, "orchestration.dispatch");
138 assert.equal(diagnostics.commonFailures[0]?.count, 2);
139 assert.equal(diagnostics.latestFailures[0]?.traceId, "trace-c");
140 assert.equal(diagnostics.slowestSpans[0]?.traceId, "trace-b");
141 assert.equal(diagnostics.latestWarningAndErrorLogs[0]?.message, "status delayed");
142 assert.equal(diagnostics.topSpansByCount[0]?.name, "orchestration.dispatch");
143 }),
144 );
145
146 it.effect("streams rotated files into the same result as reading them whole", () =>
147 Effect.gen(function* () {
148 const files = new Map([
149 [
150 `${traceFilePath}.1`,
151 [
152 record({
153 name: "server.getConfig",
154 traceId: "trace-a",
155 spanId: "span-a",
156 startMs: 1_000,
157 durationMs: 50,
158 }),
159 "not-json",
160 record({
161 name: "orchestration.dispatch",
162 traceId: "trace-b",
163 spanId: "span-b",
164 startMs: 2_000,
165 durationMs: 1_500,
166 exit: { _tag: "Failure", cause: "Provider crashed: café 🔥" },
167 }),
168 "",
169 ].join("\r\n"),
170 ],
171 [
172 traceFilePath,
173 [
174 record({
175 name: "git.status",
176 traceId: "trace-c",
177 spanId: "span-c",
178 startMs: 3_000,
179 durationMs: 25,
180 exit: { _tag: "Interrupted", cause: "Interrupted" },
181 events: [
182 {
183 name: "status delayed ⏳",
184 timeUnixNano: ns(3_010),
185 attributes: { "effect.logLevel": "Warning" },
186 },
187 ],
188 }),
189 "",
190 record({
191 name: "orchestration.dispatch",
192 traceId: "trace-d",
193 spanId: "span-d",
194 startMs: 4_000,
195 durationMs: 250,
196 exit: { _tag: "Failure", cause: "Provider crashed: café 🔥" },
197 }),
198 ].join("\n"),
199 ],
200 ]);
201 const encoder = new TextEncoder();
202
203 const diagnostics = yield* readTraces({
204 stream: (path) =>
205 Stream.fromIterable(
206 Array.from(encoder.encode(files.get(path)), (byte) => Uint8Array.of(byte)),
207 ),
208 });
209
210 assert.equal(diagnostics.recordCount, 4);
211 assert.deepStrictEqual(
212 diagnostics,
213 aggregateLines([...files.values()].flatMap((text) => text.split(/\r?\n/))),
214 );
215 }),
216 );
217
218 it.effect("keeps loaded trace data when one rotated trace file fails to read", () =>
219 Effect.gen(function* () {
220 const readFailure = PlatformError.systemError({
221 _tag: "PermissionDenied",
222 module: "FileSystem",
223 method: "open",
224 description: "permission denied",
225 pathOrDescriptor: `${traceFilePath}.1`,
226 });
227 const logAnnotations: Array<Record<string, unknown>> = [];
228 const logger = Logger.make<unknown, void>((options) => {
229 logAnnotations.push({ ...options.fiber.getRef(References.CurrentLogAnnotations) });
230 });
231
232 const diagnostics = yield* readTraces({
233 stream: (path) =>
234 path === `${traceFilePath}.1`
235 ? Stream.fail(readFailure)
236 : Stream.make(
237 new TextEncoder().encode(
238 record({
239 name: "server.getConfig",
240 traceId: "trace-a",
241 spanId: "span-a",
242 startMs: 1_000,
243 durationMs: 50,
244 }),
245 ),
246 ),
247 }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
248
249 assert.equal(diagnostics.recordCount, 1);
250 assert.equal(
251 Option.getOrElse(diagnostics.partialFailure, () => false),
252 true,
253 );
254 assert.deepStrictEqual(Option.getOrUndefined(diagnostics.error), {
255 kind: "trace-file-read-failed",
256 message: `Failed to read local trace file '${traceFilePath}.1'.`,
257 });
258 assert.deepStrictEqual(diagnostics.scannedFilePaths, [`${traceFilePath}.1`, traceFilePath]);
259
260 const failureLog = logAnnotations.find(
261 (annotations) => annotations.traceFilePath === `${traceFilePath}.1`,
262 );
263 assert.exists(failureLog);
264 assert.deepStrictEqual(failureLog, {
265 traceFilePath: `${traceFilePath}.1`,
266 errorTag: "TraceFileReadError",
267 causeTag: "PermissionDenied",
268 });
269 }),
270 );
271});