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