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("includes browser failures and interruptions in diagnostics", () => {
65 const diagnostics = aggregateLines(
66 [
67 { status: { code: "2", message: "Interrupted" }, attributes: {} },
68 { status: { code: "0" }, attributes: { "effect.fiber.interrupted": true } },
69 { status: { code: "1", message: "Interrupted" }, attributes: {} },
70 { status: { code: "1" }, attributes: {} },
71 ].map((outcome, index) =>
72 JSON.stringify({
73 type: "otlp-span",
74 name: "browser.request",
75 traceId: `trace-${index}`,
76 spanId: `span-${index}`,
77 startTimeUnixNano: ns(index * 100),
78 endTimeUnixNano: ns(index * 100 + 10),
79 durationMs: 10,
80 ...outcome,
81 }),
82 ),
83 );
84
85 assert.equal(diagnostics.recordCount, 4);
86 assert.equal(diagnostics.failureCount, 1);
87 assert.equal(diagnostics.interruptionCount, 2);
88 assert.equal(diagnostics.topSpansByCount[0]?.failureCount, 1);
89 assert.equal(diagnostics.commonFailures[0]?.cause, "Interrupted");
90 assert.equal(diagnostics.latestFailures[0]?.cause, "Interrupted");
91 });
92
93 it("does not count an open subscription's lifetime as a slow span", () => {
94 // Shapes recorded from a real server trace: a subscription span lasts as long as the client watches.
95 const subscriptionLifetimeMs = 90_000;
96 const diagnostics = aggregateLines([
97 record({
98 name: "git.status",
99 traceId: "trace-git",
100 spanId: "span-git",
101 startMs: 0,
102 durationMs: 1_500,
103 }),
104 JSON.stringify({
105 type: "effect-span",
106 name: "ws.rpc.subscribeVcsStatus",
107 traceId: "trace-sub",
108 spanId: "span-ws",
109 kind: "internal",
110 startTimeUnixNano: ns(0),
111 endTimeUnixNano: ns(subscriptionLifetimeMs),
112 durationMs: subscriptionLifetimeMs,
113 attributes: { "rpc.system": "effect-rpc", "rpc.method": "subscribeVcsStatus" },
114 exit: {
115 _tag: "Interrupted",
116 cause: "InterruptError: All fibers interrupted without error",
117 },
118 }),
119 JSON.stringify({
120 type: "otlp-span",
121 name: "subscribeVcsStatus",
122 traceId: "trace-sub",
123 spanId: "span-client",
124 kind: "client",
125 startTimeUnixNano: ns(0),
126 endTimeUnixNano: ns(subscriptionLifetimeMs),
127 durationMs: subscriptionLifetimeMs,
128 attributes: { "rpc.method": "subscribeVcsStatus", "effect.fiber.interrupted": true },
129 status: { code: "0" },
130 }),
131 JSON.stringify({
132 type: "otlp-span",
133 name: "EnvironmentRpc.subscribe",
134 traceId: "trace-sub",
135 spanId: "span-env",
136 kind: "internal",
137 startTimeUnixNano: ns(0),
138 endTimeUnixNano: ns(subscriptionLifetimeMs),
139 durationMs: subscriptionLifetimeMs,
140 attributes: { "rpc.method": "subscribeVcsStatus", "effect.fiber.interrupted": true },
141 status: { code: "0" },
142 }),
143 ]);
144
145 assert.equal(diagnostics.slowSpanCount, 1);
146 });
147
148 it.effect("aggregates failures, slow spans, log levels, and parse errors", () =>
149 Effect.sync(() => {
150 const diagnostics = aggregateLines([
151 record({
152 name: "server.getConfig",
153 traceId: "trace-a",
154 spanId: "span-a",
155 startMs: 1_000,
156 durationMs: 50,
157 }),
158 "not-json",
159 record({
160 name: "orchestration.dispatch",
161 traceId: "trace-b",
162 spanId: "span-b",
163 startMs: 2_000,
164 durationMs: 1_500,
165 exit: { _tag: "Failure", cause: "Provider crashed" },
166 events: [
167 {
168 name: "provider failed",
169 timeUnixNano: ns(3_400),
170 attributes: { "effect.logLevel": "Error" },
171 },
172 ],
173 }),
174 record({
175 name: "orchestration.dispatch",
176 traceId: "trace-c",
177 spanId: "span-c",
178 startMs: 4_000,
179 durationMs: 250,
180 exit: { _tag: "Failure", cause: "Provider crashed" },
181 }),
182 record({
183 name: "git.status",
184 traceId: "trace-d",
185 spanId: "span-d",
186 startMs: 5_000,
187 durationMs: 25,
188 exit: { _tag: "Interrupted", cause: "Interrupted" },
189 events: [
190 {
191 name: "status delayed",
192 timeUnixNano: ns(5_010),
193 attributes: { "effect.logLevel": "Warning" },
194 },
195 ],
196 }),
197 ]);
198
199 assert.equal(diagnostics.recordCount, 4);
200 assert.equal(DateTime.formatIso(diagnostics.readAt), "2026-05-05T10:00:00.000Z");
201 assert.equal(
202 Option.match(diagnostics.firstSpanAt, {
203 onNone: () => null,
204 onSome: DateTime.formatIso,
205 }),
206 "1970-01-01T00:00:01.000Z",
207 );
208 assert.equal(
209 Option.match(diagnostics.lastSpanAt, {
210 onNone: () => null,
211 onSome: DateTime.formatIso,
212 }),
213 "1970-01-01T00:00:05.025Z",
214 );
215 assert.equal(diagnostics.parseErrorCount, 1);
216 assert.equal(diagnostics.failureCount, 2);
217 assert.equal(diagnostics.interruptionCount, 1);
218 assert.equal(diagnostics.slowSpanCount, 1);
219 assert.equal(diagnostics.logLevelCounts.Error, 1);
220 assert.equal(diagnostics.logLevelCounts.Warning, 1);
221 assert.equal(diagnostics.commonFailures[0]?.name, "orchestration.dispatch");
222 assert.equal(diagnostics.commonFailures[0]?.count, 2);
223 assert.equal(diagnostics.latestFailures[0]?.traceId, "trace-c");
224 assert.equal(diagnostics.slowestSpans[0]?.traceId, "trace-b");
225 assert.equal(diagnostics.latestWarningAndErrorLogs[0]?.message, "status delayed");
226 assert.equal(diagnostics.topSpansByCount[0]?.name, "orchestration.dispatch");
227 }),
228 );
229
230 it.effect("streams rotated files into the same result as reading them whole", () =>
231 Effect.gen(function* () {
232 const files = new Map([
233 [
234 `${traceFilePath}.1`,
235 [
236 record({
237 name: "server.getConfig",
238 traceId: "trace-a",
239 spanId: "span-a",
240 startMs: 1_000,
241 durationMs: 50,
242 }),
243 "not-json",
244 record({
245 name: "orchestration.dispatch",
246 traceId: "trace-b",
247 spanId: "span-b",
248 startMs: 2_000,
249 durationMs: 1_500,
250 exit: { _tag: "Failure", cause: "Provider crashed: café 🔥" },
251 }),
252 "",
253 ].join("\r\n"),
254 ],
255 [
256 traceFilePath,
257 [
258 record({
259 name: "git.status",
260 traceId: "trace-c",
261 spanId: "span-c",
262 startMs: 3_000,
263 durationMs: 25,
264 exit: { _tag: "Interrupted", cause: "Interrupted" },
265 events: [
266 {
267 name: "status delayed ⏳",
268 timeUnixNano: ns(3_010),
269 attributes: { "effect.logLevel": "Warning" },
270 },
271 ],
272 }),
273 "",
274 record({
275 name: "orchestration.dispatch",
276 traceId: "trace-d",
277 spanId: "span-d",
278 startMs: 4_000,
279 durationMs: 250,
280 exit: { _tag: "Failure", cause: "Provider crashed: café 🔥" },
281 }),
282 ].join("\n"),
283 ],
284 ]);
285 const encoder = new TextEncoder();
286
287 const diagnostics = yield* readTraces({
288 stream: (path) =>
289 Stream.fromIterable(
290 Array.from(encoder.encode(files.get(path)), (byte) => Uint8Array.of(byte)),
291 ),
292 });
293
294 assert.equal(diagnostics.recordCount, 4);
295 assert.deepStrictEqual(
296 diagnostics,
297 aggregateLines([...files.values()].flatMap((text) => text.split(/\r?\n/))),
298 );
299 }),
300 );
301
302 it.effect("keeps loaded trace data when one rotated trace file fails to read", () =>
303 Effect.gen(function* () {
304 const readFailure = PlatformError.systemError({
305 _tag: "PermissionDenied",
306 module: "FileSystem",
307 method: "open",
308 description: "permission denied",
309 pathOrDescriptor: `${traceFilePath}.1`,
310 });
311 const logAnnotations: Array<Record<string, unknown>> = [];
312 const logger = Logger.make<unknown, void>((options) => {
313 logAnnotations.push({ ...options.fiber.getRef(References.CurrentLogAnnotations) });
314 });
315
316 const diagnostics = yield* readTraces({
317 stream: (path) =>
318 path === `${traceFilePath}.1`
319 ? Stream.fail(readFailure)
320 : Stream.make(
321 new TextEncoder().encode(
322 record({
323 name: "server.getConfig",
324 traceId: "trace-a",
325 spanId: "span-a",
326 startMs: 1_000,
327 durationMs: 50,
328 }),
329 ),
330 ),
331 }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
332
333 assert.equal(diagnostics.recordCount, 1);
334 assert.equal(
335 Option.getOrElse(diagnostics.partialFailure, () => false),
336 true,
337 );
338 assert.deepStrictEqual(Option.getOrUndefined(diagnostics.error), {
339 kind: "trace-file-read-failed",
340 message: `Failed to read local trace file '${traceFilePath}.1'.`,
341 });
342 assert.deepStrictEqual(diagnostics.scannedFilePaths, [`${traceFilePath}.1`, traceFilePath]);
343
344 const failureLog = logAnnotations.find(
345 (annotations) => annotations.traceFilePath === `${traceFilePath}.1`,
346 );
347 assert.exists(failureLog);
348 assert.deepStrictEqual(failureLog, {
349 traceFilePath: `${traceFilePath}.1`,
350 errorTag: "TraceFileReadError",
351 causeTag: "PermissionDenied",
352 });
353 }),
354 );
355});