Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

TraceDiagnostics.test.ts

258 lines8.9 KB

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