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("returns a not-found diagnostic when no files are available", () =>
147 Effect.gen(function* () {
148 const diagnostics = yield* readTraces({});
149
150 assert.equal(diagnostics.recordCount, 0);
151 assert.equal(Option.getOrUndefined(diagnostics.error)?.kind, "trace-file-not-found");
152 }),
153 );
154
155 it.effect("streams rotated files into the same result as reading them whole", () =>
156 Effect.gen(function* () {
157 const files = new Map([
158 [
159 `${traceFilePath}.1`,
160 [
161 record({
162 name: "server.getConfig",
163 traceId: "trace-a",
164 spanId: "span-a",
165 startMs: 1_000,
166 durationMs: 50,
167 }),
168 "not-json",
169 record({
170 name: "orchestration.dispatch",
171 traceId: "trace-b",
172 spanId: "span-b",
173 startMs: 2_000,
174 durationMs: 1_500,
175 exit: { _tag: "Failure", cause: "Provider crashed: café 🔥" },
176 }),
177 "",
178 ].join("\r\n"),
179 ],
180 [
181 traceFilePath,
182 [
183 record({
184 name: "git.status",
185 traceId: "trace-c",
186 spanId: "span-c",
187 startMs: 3_000,
188 durationMs: 25,
189 exit: { _tag: "Interrupted", cause: "Interrupted" },
190 events: [
191 {
192 name: "status delayed ⏳",
193 timeUnixNano: ns(3_010),
194 attributes: { "effect.logLevel": "Warning" },
195 },
196 ],
197 }),
198 "",
199 record({
200 name: "orchestration.dispatch",
201 traceId: "trace-d",
202 spanId: "span-d",
203 startMs: 4_000,
204 durationMs: 250,
205 exit: { _tag: "Failure", cause: "Provider crashed: café 🔥" },
206 }),
207 ].join("\n"),
208 ],
209 ]);
210 const encoder = new TextEncoder();
211
212 const diagnostics = yield* readTraces({
213 stream: (path) =>
214 Stream.fromIterable(
215 Array.from(encoder.encode(files.get(path)), (byte) => Uint8Array.of(byte)),
216 ),
217 });
218
219 assert.equal(diagnostics.recordCount, 4);
220 assert.deepStrictEqual(
221 diagnostics,
222 aggregateLines([...files.values()].flatMap((text) => text.split(/\r?\n/))),
223 );
224 }),
225 );
226
227 it.effect("preserves full failure causes and log messages", () =>
228 Effect.sync(() => {
229 const longCause = `VcsProcessSpawnError: ${"missing executable ".repeat(80)}`.trim();
230 const longMessage = `provider warning: ${"retrying command ".repeat(80)}`.trim();
231 const diagnostics = aggregateLines([
232 record({
233 name: "VcsProcess.run",
234 traceId: "trace-long",
235 spanId: "span-long",
236 startMs: 1_000,
237 durationMs: 25,
238 exit: { _tag: "Failure", cause: longCause },
239 events: [
240 {
241 name: longMessage,
242 timeUnixNano: ns(1_010),
243 attributes: { "effect.logLevel": "Warning" },
244 },
245 ],
246 }),
247 ]);
248
249 assert.equal(diagnostics.latestFailures[0]?.cause, longCause);
250 assert.equal(diagnostics.commonFailures[0]?.cause, longCause);
251 assert.equal(diagnostics.latestWarningAndErrorLogs[0]?.message, longMessage);
252 }),
253 );
254
255 it.effect("keeps loaded trace data when one rotated trace file fails to read", () =>
256 Effect.gen(function* () {
257 const readFailure = PlatformError.systemError({
258 _tag: "PermissionDenied",
259 module: "FileSystem",
260 method: "open",
261 description: "permission denied",
262 pathOrDescriptor: `${traceFilePath}.1`,
263 });
264 const logAnnotations: Array<Record<string, unknown>> = [];
265 const logger = Logger.make<unknown, void>((options) => {
266 logAnnotations.push({ ...options.fiber.getRef(References.CurrentLogAnnotations) });
267 });
268
269 const diagnostics = yield* readTraces({
270 stream: (path) =>
271 path === `${traceFilePath}.1`
272 ? Stream.fail(readFailure)
273 : Stream.make(
274 new TextEncoder().encode(
275 record({
276 name: "server.getConfig",
277 traceId: "trace-a",
278 spanId: "span-a",
279 startMs: 1_000,
280 durationMs: 50,
281 }),
282 ),
283 ),
284 }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
285
286 assert.equal(diagnostics.recordCount, 1);
287 assert.equal(
288 Option.getOrElse(diagnostics.partialFailure, () => false),
289 true,
290 );
291 assert.deepStrictEqual(Option.getOrUndefined(diagnostics.error), {
292 kind: "trace-file-read-failed",
293 message: `Failed to read local trace file '${traceFilePath}.1'.`,
294 });
295 assert.deepStrictEqual(diagnostics.scannedFilePaths, [`${traceFilePath}.1`, traceFilePath]);
296
297 const failureLog = logAnnotations.find(
298 (annotations) => annotations.traceFilePath === `${traceFilePath}.1`,
299 );
300 assert.exists(failureLog);
301 assert.deepStrictEqual(failureLog, {
302 traceFilePath: `${traceFilePath}.1`,
303 errorTag: "TraceFileReadError",
304 causeTag: "PermissionDenied",
305 });
306 }),
307 );
308
309 it.effect("keeps only the top spans, failures, and warning logs from large inputs", () =>
310 Effect.sync(() => {
311 const indexes = Array.from({ length: 30 }, (_, step) => (step * 7) % 30);
312 const diagnostics = aggregateLines(
313 indexes.map((index) =>
314 record({
315 name: `span-${index}`,
316 traceId: `trace-${index}`,
317 spanId: `span-${index}`,
318 startMs: index * 1_000,
319 durationMs: index,
320 exit: { _tag: "Failure", cause: "Provider crashed" },
321 events: [
322 {
323 name: `warning ${index}`,
324 timeUnixNano: ns(index * 1_000),
325 attributes: { "effect.logLevel": "Warning" },
326 },
327 ],
328 }),
329 ),
330 );
331 const newestTwenty = Array.from({ length: 20 }, (_, rank) => `trace-${29 - rank}`);
332
333 assert.equal(diagnostics.recordCount, 30);
334 assert.deepStrictEqual(
335 diagnostics.slowestSpans.map((span) => span.durationMs),
336 [29, 28, 27, 26, 25, 24, 23, 22, 21, 20],
337 );
338 assert.deepStrictEqual(
339 diagnostics.latestFailures.map((failure) => failure.traceId),
340 newestTwenty,
341 );
342 assert.deepStrictEqual(
343 diagnostics.latestWarningAndErrorLogs.map((log) => log.traceId),
344 newestTwenty,
345 );
346 }),
347 );
348});