feat(cli): summarize the server trace file from the command line (#13698)

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Theo BrowneandClaude Opus 5.5 authored and GitHub committed 2026-09-25 19:28:54 -07:00
1 parent 8aa5be2f02
commit 75bf92e652
6 files changed
+361 -6

No files matched your search

+2
View File
@@ -24,6 +24,7 @@ import { serviceLauncherCommand } from "./cli/serviceLauncher.ts";
import { servicePreflightCommand } from "./cli/servicePreflight.ts";
import { sshHelperCommand } from "./cli/sshHelper.ts";
import { themeCommand } from "./cli/theme.ts";
import { traceCommand } from "./cli/trace.ts";
import { triageCommand } from "./cli/triage.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
@@ -71,6 +72,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
servicePreflightCommand,
sshHelperCommand,
themeCommand,
traceCommand,
triageCommand,
cloudEnabled ? connectCommand : connectUnavailableCommand,
]),
+11 -5
View File
@@ -82,16 +82,22 @@ const tailscaleServePortFlag = Flag.Int("tailscale-serve-port").pipe(
Flag.optional,
);
// Trace file location, shared by the server and `t3 trace summary`.
export const traceFileConfig = Config.String("T3CODE_TRACE_FILE").pipe(
Config.option,
Config.map(Option.getOrUndefined),
);
export const traceMaxFilesConfig = Config.Int("T3CODE_TRACE_MAX_FILES").pipe(
Config.withDefault(10),
);
const EnvServerConfig = Config.all({
logLevel: Config.LogLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
traceMinLevel: Config.LogLevel("T3CODE_TRACE_MIN_LEVEL").pipe(Config.withDefault("Info")),
traceTimingEnabled: Config.Boolean("T3CODE_TRACE_TIMING_ENABLED").pipe(Config.withDefault(true)),
traceFile: Config.String("T3CODE_TRACE_FILE").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
traceFile: traceFileConfig,
traceMaxBytes: Config.Int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
traceMaxFiles: Config.Int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)),
traceMaxFiles: traceMaxFilesConfig,
traceBatchWindowMs: Config.Int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(1_000)),
otlpTracesUrl: Config.String("T3CODE_OTLP_TRACES_URL").pipe(
Config.option,
+100
View File
@@ -0,0 +1,100 @@
import { assert, it } from "@effect/vitest";
import { makeTraceSpanSummary } from "./trace.ts";
const MINUTE_MS = 60_000;
function span(name: string, durationMs: number, endMs: number, exitTag = "Success") {
return JSON.stringify({
type: "effect-span",
name,
traceId: "trace",
spanId: "span",
durationMs,
endTimeUnixNano: String(BigInt(endMs) * 1_000_000n),
exit: { _tag: exitTag, cause: "cause" },
});
}
function browserSpan(name: string, status: { code: string; message?: string }) {
return JSON.stringify({
type: "otlp-span",
name,
durationMs: 1,
endTimeUnixNano: "1000000",
status,
});
}
it("reports count, rate, percentiles, and exits per span name", () => {
// Ten `refresh` spans of 1..10 ms end over minutes 0..9, and one `probe`
// span ends at minute 10, so the recorded window is 10 minutes.
const refreshes = Array.from({ length: 10 }, (_, index) =>
span(
"refresh",
index + 1,
index * MINUTE_MS,
index === 0 ? "Interrupted" : index === 1 ? "Failure" : "Success",
),
);
const summarizer = makeTraceSpanSummary();
[...refreshes, span("probe", 2_500, 10 * MINUTE_MS)].forEach(summarizer.addLine);
const summary = summarizer.finish();
assert.strictEqual(summary.spanCount, 11);
assert.strictEqual(summary.minutes, 10);
assert.deepStrictEqual(summary.spans, [
{
name: "refresh",
count: 10,
perMinute: 1,
p50Ms: 5,
p90Ms: 9,
maxMs: 10,
interrupted: 1,
failures: 1,
},
{
name: "probe",
count: 1,
perMinute: 0.1,
p50Ms: 2_500,
p90Ms: 2_500,
maxMs: 2_500,
interrupted: 0,
failures: 0,
},
]);
});
it("drops spans that ended before the window and counts unreadable lines", () => {
const summarizer = makeTraceSpanSummary(MINUTE_MS);
[
span("old", 1, 0),
"",
"{not json",
JSON.stringify({ name: "no-duration" }),
// Ends past the largest Date, so the report could not print it.
JSON.stringify({ name: "far-future", durationMs: 1, endTimeUnixNano: "9".repeat(22) }),
span("recent", 4, 5 * MINUTE_MS),
].forEach(summarizer.addLine);
const summary = summarizer.finish();
assert.strictEqual(summary.skippedLineCount, 3);
assert.deepStrictEqual(
summary.spans.map((entry) => [entry.name, entry.count, entry.perMinute]),
[["recent", 1, undefined]],
);
});
it("reads failures and interrupts of browser spans from their OTLP status", () => {
const summarizer = makeTraceSpanSummary();
[
browserSpan("render", { code: "2", message: "boom" }),
browserSpan("render", { code: "1", message: "Interrupted" }),
browserSpan("render", { code: "1" }),
].forEach(summarizer.addLine);
const [render] = summarizer.finish().spans;
assert.deepStrictEqual([render?.count, render?.interrupted, render?.failures], [3, 1, 1]);
});
+227
View File
@@ -0,0 +1,227 @@
/**
* `t3 trace summary` - per-span counts, rates, and latency percentiles from
* the local server trace file and its rotated backups. It reads the files
* directly, so it works while the server is stalled or stopped.
*/
import { PositiveInt } from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Config from "effect/Config";
import * as Console from "effect/Console";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { Command, Flag } from "effect/unstable/cli";
import * as ServerConfig from "../config.ts";
import { toRotatedTracePaths, TraceFileReadError } from "../diagnostics/TraceDiagnostics.ts";
import { resolveBaseDir } from "../os-jank.ts";
import { baseDirFlag, DurationFromString, traceFileConfig, traceMaxFilesConfig } from "./config.ts";
// Only the fields the summary needs. Other record fields are ignored.
const decodeTraceSpanLine = Schema.decodeUnknownOption(
Schema.fromJsonString(
Schema.Struct({
name: Schema.String,
durationMs: Schema.Finite,
endTimeUnixNano: Schema.FiniteFromString,
// Server (`effect-span`) records.
exit: Schema.optional(Schema.Struct({ _tag: Schema.String })),
// Browser (`otlp-span`) records. Effect's OTLP tracer writes code "2" for
// errors and code "1" with message "Interrupted" for interrupts.
status: Schema.optional(
Schema.Struct({
code: Schema.optional(Schema.String),
message: Schema.optional(Schema.String),
}),
),
}),
),
);
/**
* Groups trace NDJSON by span name. Call `addLine` once per line as the files
* stream in, then `finish` for the summary. Spans that ended before `sinceMs`
* are left out. Rates are per minute between the first and last span end,
* since spans are written when they end.
*/
export function makeTraceSpanSummary(sinceMs = -Infinity) {
// Keep each span's duration (8 bytes, a few MB for the default 110 MB of
// rotated traces) for exact percentiles. A bounded sketch would save little
// and make p50 and p90 approximate.
const byName = new Map<string, { durations: number[]; interrupted: number; failures: number }>();
let spanCount = 0;
let skippedLineCount = 0;
let firstEndMs = Infinity;
let lastEndMs = -Infinity;
const addLine = (line: string) => {
if (line.trim().length === 0) return;
const span = Option.getOrUndefined(decodeTraceSpanLine(line));
if (span === undefined) {
skippedLineCount += 1;
return;
}
const endMs = span.endTimeUnixNano / 1_000_000;
// The report prints end times as dates, so skip ones outside the Date range.
if (Option.isNone(DateTime.make(endMs))) {
skippedLineCount += 1;
return;
}
if (endMs < sinceMs) return;
spanCount += 1;
firstEndMs = Math.min(firstEndMs, endMs);
lastEndMs = Math.max(lastEndMs, endMs);
const stats = byName.get(span.name) ?? { durations: [], interrupted: 0, failures: 0 };
stats.durations.push(span.durationMs);
if (span.exit?._tag === "Interrupted" || span.status?.message === "Interrupted") {
stats.interrupted += 1;
}
if (span.exit?._tag === "Failure" || span.status?.code === "2") stats.failures += 1;
byName.set(span.name, stats);
};
const finish = () => {
const minutes = (lastEndMs - firstEndMs) / 60_000;
const spans = [...byName]
.map(([name, { durations, interrupted, failures }]) => {
const sorted = durations.toSorted((left, right) => left - right);
// Nearest-rank percentile.
const percentile = (p: number) => sorted[Math.ceil(p * sorted.length) - 1]!;
return {
name,
count: sorted.length,
perMinute: minutes > 0 ? sorted.length / minutes : undefined,
p50Ms: percentile(0.5),
p90Ms: percentile(0.9),
maxMs: sorted[sorted.length - 1]!,
interrupted,
failures,
};
})
.toSorted((left, right) => right.count - left.count || left.name.localeCompare(right.name));
return { spanCount, skippedLineCount, firstEndMs, lastEndMs, minutes, spans };
};
return { addLine, finish };
}
const formatMs = (ms: number) =>
ms < 1_000 ? `${Math.round(ms)}ms` : `${(ms / 1_000).toFixed(1)}s`;
function formatTraceSummary(
summary: ReturnType<ReturnType<typeof makeTraceSpanSummary>["finish"]>,
limit: number,
) {
const header = ["span", "count", "/min", "p50", "p90", "max", "interrupted", "failed"];
const rows = summary.spans
.slice(0, limit)
.map((span) => [
span.name,
String(span.count),
span.perMinute === undefined
? "-"
: span.perMinute < 0.1
? "<0.1"
: span.perMinute.toFixed(1),
formatMs(span.p50Ms),
formatMs(span.p90Ms),
formatMs(span.maxMs),
String(span.interrupted),
String(span.failures),
]);
const table = [header, ...rows];
const widths = header.map((_, column) => Math.max(...table.map((row) => row[column]!.length)));
const formatIso = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms));
return [
`${summary.spanCount} spans ended from ${formatIso(summary.firstEndMs)} to ${formatIso(summary.lastEndMs)} (${summary.minutes.toFixed(1)} min).`,
...(summary.skippedLineCount > 0
? [`Skipped ${summary.skippedLineCount} lines that are not spans.`]
: []),
"",
...table.map((row) =>
row
.map((cell, column) =>
column === 0 ? cell.padEnd(widths[column]!) : cell.padStart(widths[column]!),
)
.join(" "),
),
...(summary.spans.length > limit
? ["", `${summary.spans.length - limit} more span names. Use --limit to show more.`]
: []),
].join("\n");
}
const traceSummaryCommand = Command.make("summary", {
baseDir: baseDirFlag,
since: Flag.String("since").pipe(
Flag.withSchema(DurationFromString),
Flag.withDescription("Only count spans that ended in this window, for example 30m or 2h."),
Flag.optional,
),
limit: Flag.Int("limit").pipe(
Flag.withSchema(PositiveInt),
Flag.withDescription("Number of span names to show, busiest first."),
Flag.withDefault(25),
),
}).pipe(
Command.withDescription("Summarize the local server trace file: counts, rates, and latency."),
Command.withHandler(
Effect.fn("cli.trace.summary")(function* (flags) {
const fs = yield* FileSystem.FileSystem;
// T3CODE_TRACE_FILE, else the userdata trace file for --base-dir or
// T3CODE_HOME. Implicit dev runs write elsewhere; set T3CODE_TRACE_FILE.
const envHome = yield* Config.String("T3CODE_HOME").pipe(Config.option);
const baseDir = yield* resolveBaseDir(
Option.getOrUndefined(Option.orElse(flags.baseDir, () => envHome)),
);
const traceFilePath =
(yield* traceFileConfig) ??
(yield* ServerConfig.deriveServerPaths(baseDir, undefined)).serverTracePath;
const sinceMs = Option.isSome(flags.since)
? (yield* Clock.currentTimeMillis) - Duration.toMillis(flags.since.value)
: undefined;
const summarizer = makeTraceSpanSummary(sinceMs);
// Stream each file so only one chunk of text is in memory at a time.
yield* Effect.forEach(
toRotatedTracePaths(traceFilePath, yield* traceMaxFilesConfig),
(path) =>
fs.stream(path).pipe(
Stream.decodeText,
Stream.splitLines,
Stream.runForEachArray((lines) => Effect.sync(() => lines.forEach(summarizer.addLine))),
Effect.catchTags({
PlatformError: (cause) =>
cause.reason._tag === "NotFound"
? Effect.void
: Effect.fail(
new TraceFileReadError({
traceFilePath: path,
causeTag: cause.reason._tag,
cause,
}),
),
}),
),
{ discard: true },
);
const summary = summarizer.finish();
yield* Console.log(
summary.spanCount === 0
? `No spans found in ${traceFilePath} or its rotated files${sinceMs === undefined ? "" : " in that window"}.${summary.skippedLineCount > 0 ? ` Skipped ${summary.skippedLineCount} lines that are not spans.` : ""}`
: formatTraceSummary(summary, flags.limit),
);
}),
),
);
export const traceCommand = Command.make("trace").pipe(
Command.withDescription("Inspect the local server trace file."),
Command.withSubcommands([traceSummaryCommand]),
);
@@ -81,7 +81,12 @@ interface TraceDiagnosticsErrorSummary {
const DEFAULT_SLOW_SPAN_THRESHOLD_MS = 1_000;
const TOP_LIMIT = 10;
const RECENT_LIMIT = 20;
function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyArray<string> {
/** The trace file and its rotated backups, oldest first. */
export function toRotatedTracePaths(
traceFilePath: string,
maxFiles: number,
): ReadonlyArray<string> {
const backupCount = Math.max(0, Math.floor(maxFiles));
const backups = Array.from(
{ length: backupCount },
+15
View File
@@ -62,6 +62,21 @@ far in the future for the environment server's allowed window. It can point to
a date or time problem on either device, but it can also result from a delayed
request.
#### Summarize the trace file
`t3 trace summary` reads the trace file and its rotated backups directly, so it works while the
server is stalled or stopped. It prints counts, rates, and latency percentiles per span name. Use
it to measure background work or to compare two builds.
```bash
t3 trace summary --since 30m --limit 40
```
It reads `T3CODE_TRACE_FILE` if set, else `<home>/userdata/logs/server.trace.ndjson` for
`--base-dir` or `T3CODE_HOME`, plus the `T3CODE_TRACE_MAX_FILES` rotated backups. For a dev run or
a copied file, set `T3CODE_TRACE_FILE`. `--since 30m` keeps spans that ended in the last 30
minutes. The rate is per minute between the first and last span end.
### Metrics
Metrics are not written to a local file.