perf(server): trace logs keep hours of history instead of minutes
The local trace file burned through its whole 100 MB rotation window in 10-36 minutes, which made incident audits impossible: by the time a slow-PR-badge report came in, the relevant spans were already rotated away. Two sources dominated: the terminal subprocess poller (~40% of bytes: pgrep + up to three ps spawns per session per second, each a full process-table enumeration) and sql.execute spans (~28%). Write less: - One shared ps/powershell process-table snapshot per poll tick serves every running terminal; per-session inspection is now pure lookup. This also removes 50-75 process spawns/sec on busy hosts. - The poll tick runs untraced; an explicit terminal.subprocessActivityChanged span fires only on a real state flip. - Tail policy in the local file tracer: failures, interruptions, spans with events, and slow spans always persist; fast successes are rate-limited per span name (50 per 30s). OTLP delegate still sees every span. T3CODE_TRACE_KEEP_ALL_SPANS=true restores full fidelity. - Dropped constant db.name/service.name attributes from every sql.execute span. Keep more: - Rotated trace backups are gzipped (measured 10.6x on real span data) and T3CODE_TRACE_MAX_FILES now defaults to 30, so the same disk budget covers hours. - TraceDiagnostics reads backups one file at a time (instead of slurping every rotation into memory) and transparently gunzips .gz backups; plain legacy backups still age along the chain. Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
05eb051184
commit
3cc7cf3c83
16 files changed
+670
-370
No files matched your search
@@ -2,6 +2,7 @@
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeZlib from "node:zlib";
|
||||
import { afterEach, describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
@@ -167,4 +168,63 @@ describe("RotatingFileSink", () => {
|
||||
expect(thrown).toMatchObject({ operation: "prune", filePath });
|
||||
expect((thrown as RotatingFileSinkError).cause).toBeInstanceOf(Error);
|
||||
});
|
||||
|
||||
it("gzips backups on rotation when compressBackups is enabled", () => {
|
||||
const directory = makeTempDirectory();
|
||||
const filePath = NodePath.join(directory, "log.ndjson");
|
||||
const sink = new RotatingFileSink({
|
||||
filePath,
|
||||
maxBytes: 8,
|
||||
maxFiles: 2,
|
||||
compressBackups: true,
|
||||
throwOnError: true,
|
||||
});
|
||||
|
||||
sink.write("first-entry");
|
||||
sink.write("second-entry");
|
||||
sink.write("third-entry");
|
||||
|
||||
expect(NodeFS.readFileSync(filePath, "utf8")).toBe("third-entry");
|
||||
expect(NodeZlib.gunzipSync(NodeFS.readFileSync(`${filePath}.1.gz`)).toString("utf8")).toBe(
|
||||
"second-entry",
|
||||
);
|
||||
expect(NodeZlib.gunzipSync(NodeFS.readFileSync(`${filePath}.2.gz`)).toString("utf8")).toBe(
|
||||
"first-entry",
|
||||
);
|
||||
expect(NodeFS.existsSync(`${filePath}.1`)).toBe(false);
|
||||
expect(NodeFS.existsSync(`${filePath}.2`)).toBe(false);
|
||||
});
|
||||
|
||||
it("ages plain backups from before compressBackups along the rotation chain", () => {
|
||||
const directory = makeTempDirectory();
|
||||
const filePath = NodePath.join(directory, "log.ndjson");
|
||||
NodeFS.writeFileSync(`${filePath}.1`, "legacy-entry");
|
||||
NodeFS.writeFileSync(filePath, "current-entry");
|
||||
const sink = new RotatingFileSink({
|
||||
filePath,
|
||||
maxBytes: 8,
|
||||
maxFiles: 2,
|
||||
compressBackups: true,
|
||||
throwOnError: true,
|
||||
});
|
||||
|
||||
sink.write("next-entry");
|
||||
|
||||
expect(NodeFS.readFileSync(filePath, "utf8")).toBe("next-entry");
|
||||
expect(NodeZlib.gunzipSync(NodeFS.readFileSync(`${filePath}.1.gz`)).toString("utf8")).toBe(
|
||||
"current-entry",
|
||||
);
|
||||
expect(NodeFS.readFileSync(`${filePath}.2`, "utf8")).toBe("legacy-entry");
|
||||
});
|
||||
|
||||
it("prunes overflowing compressed backups", () => {
|
||||
const directory = makeTempDirectory();
|
||||
const filePath = NodePath.join(directory, "log.ndjson");
|
||||
const overflowBackup = `${filePath}.3.gz`;
|
||||
NodeFS.writeFileSync(overflowBackup, "stale");
|
||||
|
||||
void new RotatingFileSink({ filePath, maxBytes: 8, maxFiles: 2, compressBackups: true });
|
||||
|
||||
expect(NodeFS.existsSync(overflowBackup)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeZlib from "node:zlib";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export interface RotatingFileSinkOptions {
|
||||
@@ -8,6 +9,13 @@ export interface RotatingFileSinkOptions {
|
||||
readonly maxBytes: number;
|
||||
readonly maxFiles: number;
|
||||
readonly throwOnError?: boolean;
|
||||
/**
|
||||
* Gzip backups as they rotate out (`file.1.gz`, `file.2.gz`, ...). Span
|
||||
* NDJSON compresses ~10x, so the same maxFiles budget covers an order of
|
||||
* magnitude more history. Compression is synchronous but rare (once per
|
||||
* maxBytes of writes) and costs ~60ms per 10 MB.
|
||||
*/
|
||||
readonly compressBackups?: boolean;
|
||||
}
|
||||
|
||||
export class RotatingFileSinkConfigurationError extends Schema.TaggedErrorClass<RotatingFileSinkConfigurationError>()(
|
||||
@@ -46,6 +54,7 @@ export class RotatingFileSink {
|
||||
private readonly maxBytes: number;
|
||||
private readonly maxFiles: number;
|
||||
private readonly throwOnError: boolean;
|
||||
private readonly compressBackups: boolean;
|
||||
private currentSize = 0;
|
||||
|
||||
constructor(options: RotatingFileSinkOptions) {
|
||||
@@ -68,6 +77,7 @@ export class RotatingFileSink {
|
||||
this.maxBytes = options.maxBytes;
|
||||
this.maxFiles = options.maxFiles;
|
||||
this.throwOnError = options.throwOnError ?? false;
|
||||
this.compressBackups = options.compressBackups ?? false;
|
||||
|
||||
try {
|
||||
NodeFS.mkdirSync(NodePath.dirname(this.filePath), { recursive: true });
|
||||
@@ -110,21 +120,35 @@ export class RotatingFileSink {
|
||||
|
||||
private rotate(): void {
|
||||
try {
|
||||
const oldest = this.withSuffix(this.maxFiles);
|
||||
if (NodeFS.existsSync(oldest)) {
|
||||
NodeFS.rmSync(oldest, { force: true });
|
||||
for (const oldest of [this.withSuffix(this.maxFiles), this.withSuffix(this.maxFiles, "gz")]) {
|
||||
if (NodeFS.existsSync(oldest)) {
|
||||
NodeFS.rmSync(oldest, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
// Backups written before compressBackups was enabled keep their plain
|
||||
// suffix and age along the chain unchanged.
|
||||
for (let index = this.maxFiles - 1; index >= 1; index -= 1) {
|
||||
const compressedSource = this.withSuffix(index, "gz");
|
||||
if (NodeFS.existsSync(compressedSource)) {
|
||||
NodeFS.renameSync(compressedSource, this.withSuffix(index + 1, "gz"));
|
||||
}
|
||||
const source = this.withSuffix(index);
|
||||
const target = this.withSuffix(index + 1);
|
||||
if (NodeFS.existsSync(source)) {
|
||||
NodeFS.renameSync(source, target);
|
||||
NodeFS.renameSync(source, this.withSuffix(index + 1));
|
||||
}
|
||||
}
|
||||
|
||||
if (NodeFS.existsSync(this.filePath)) {
|
||||
NodeFS.renameSync(this.filePath, this.withSuffix(1));
|
||||
if (this.compressBackups) {
|
||||
NodeFS.writeFileSync(
|
||||
this.withSuffix(1, "gz"),
|
||||
NodeZlib.gzipSync(NodeFS.readFileSync(this.filePath)),
|
||||
);
|
||||
NodeFS.rmSync(this.filePath, { force: true });
|
||||
} else {
|
||||
NodeFS.renameSync(this.filePath, this.withSuffix(1));
|
||||
}
|
||||
}
|
||||
|
||||
this.currentSize = 0;
|
||||
@@ -146,7 +170,10 @@ export class RotatingFileSink {
|
||||
const baseName = NodePath.basename(this.filePath);
|
||||
for (const entry of NodeFS.readdirSync(dir)) {
|
||||
if (!entry.startsWith(`${baseName}.`)) continue;
|
||||
const suffix = Number(entry.slice(baseName.length + 1));
|
||||
const rawSuffix = entry.slice(baseName.length + 1);
|
||||
const suffix = Number(
|
||||
rawSuffix.endsWith(".gz") ? rawSuffix.slice(0, -".gz".length) : rawSuffix,
|
||||
);
|
||||
if (!Number.isInteger(suffix) || suffix <= this.maxFiles) continue;
|
||||
NodeFS.rmSync(NodePath.join(dir, entry), { force: true });
|
||||
}
|
||||
@@ -176,7 +203,9 @@ export class RotatingFileSink {
|
||||
}
|
||||
}
|
||||
|
||||
private withSuffix(index: number): string {
|
||||
return `${this.filePath}.${index}`;
|
||||
private withSuffix(index: number, extension?: "gz"): string {
|
||||
return extension === undefined
|
||||
? `${this.filePath}.${index}`
|
||||
: `${this.filePath}.${index}.${extension}`;
|
||||
}
|
||||
}
|
||||
@@ -458,4 +458,48 @@ describe("observability", () => {
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
// it.live: the slow span needs real Clock time to cross the tail-policy
|
||||
// duration threshold.
|
||||
it.live("tail policy keeps failures and slow spans while rate-limiting fast successes", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
|
||||
const tracePath = path.join(tempDir, "shared.trace.ndjson");
|
||||
const tracerLayer = Layer.effect(
|
||||
Tracer.Tracer,
|
||||
makeLocalFileTracer({
|
||||
filePath: tracePath,
|
||||
maxBytes: 1024 * 1024,
|
||||
maxFiles: 2,
|
||||
batchWindowMs: 10_000,
|
||||
tailPolicy: {
|
||||
slowSpanThresholdMs: 40,
|
||||
fastSuccessLimitPerWindow: 2,
|
||||
fastSuccessWindowMs: 60_000,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
for (let index = 0; index < 5; index += 1) {
|
||||
yield* Effect.void.pipe(Effect.withSpan("hot-success"));
|
||||
}
|
||||
yield* Effect.exit(Effect.fail("boom" as const).pipe(Effect.withSpan("failing-span")));
|
||||
yield* Effect.sleep("80 millis").pipe(Effect.withSpan("slow-span"));
|
||||
}).pipe(Effect.provide(tracerLayer)),
|
||||
);
|
||||
|
||||
const records = yield* readTraceRecords(tracePath);
|
||||
const names = records.map((record) => record.name);
|
||||
|
||||
assert.equal(names.filter((name) => name === "hot-success").length, 2);
|
||||
assert.equal(names.filter((name) => name === "failing-span").length, 1);
|
||||
assert.equal(names.filter((name) => name === "slow-span").length, 1);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -111,6 +111,8 @@ export interface TraceSinkOptions {
|
||||
readonly maxFiles: number;
|
||||
readonly batchWindowMs: number;
|
||||
readonly onFlush?: (stats: TraceSinkFlushStats) => Effect.Effect<void>;
|
||||
/** Gzip rotated backups (see RotatingFileSinkOptions.compressBackups). */
|
||||
readonly compressBackups?: boolean;
|
||||
}
|
||||
|
||||
export interface TraceSinkFlushStats {
|
||||
@@ -129,6 +131,72 @@ export interface TraceSink {
|
||||
export interface LocalFileTracerOptions extends TraceSinkOptions {
|
||||
readonly delegate?: Tracer.Tracer;
|
||||
readonly sink?: TraceSink;
|
||||
/**
|
||||
* Tail policy for what reaches the local file. Failures, interruptions,
|
||||
* spans carrying events, and slow spans always persist; fast successes are
|
||||
* rate-limited per span name. Omit to persist every sampled span.
|
||||
*/
|
||||
readonly tailPolicy?: TraceTailPolicyOptions;
|
||||
}
|
||||
|
||||
export interface TraceTailPolicyOptions {
|
||||
/** Spans at least this slow always persist. */
|
||||
readonly slowSpanThresholdMs?: number;
|
||||
/** Fast successful spans persisted per name inside each sampling window. */
|
||||
readonly fastSuccessLimitPerWindow?: number;
|
||||
readonly fastSuccessWindowMs?: number;
|
||||
}
|
||||
|
||||
const DEFAULT_TAIL_POLICY = {
|
||||
slowSpanThresholdMs: 25,
|
||||
fastSuccessLimitPerWindow: 50,
|
||||
fastSuccessWindowMs: 30_000,
|
||||
} as const;
|
||||
|
||||
// Local trace files exist for incident audits, and steady-state span volume
|
||||
// decides how far back they reach. Hot always-success spans (sql.execute, the
|
||||
// projection pipeline) used to fill the whole rotation window in minutes; a
|
||||
// bounded per-name sample keeps their rate observable without the flood.
|
||||
function makeTraceTailFilter(
|
||||
options: TraceTailPolicyOptions,
|
||||
): (span: LocalFileSpan, endTime: bigint) => boolean {
|
||||
const slowSpanThresholdNanos = BigInt(
|
||||
Math.round(
|
||||
(options.slowSpanThresholdMs ?? DEFAULT_TAIL_POLICY.slowSpanThresholdMs) * 1_000_000,
|
||||
),
|
||||
);
|
||||
const fastSuccessLimitPerWindow =
|
||||
options.fastSuccessLimitPerWindow ?? DEFAULT_TAIL_POLICY.fastSuccessLimitPerWindow;
|
||||
const fastSuccessWindowMs =
|
||||
options.fastSuccessWindowMs ?? DEFAULT_TAIL_POLICY.fastSuccessWindowMs;
|
||||
let windowStartedAt = -fastSuccessWindowMs;
|
||||
let fastSuccessCountsByName = new Map<string, number>();
|
||||
|
||||
return (span, endTime) => {
|
||||
if (span.status._tag !== "Ended") {
|
||||
return true;
|
||||
}
|
||||
if (!ExitRuntime.isSuccess(span.status.exit)) {
|
||||
return true;
|
||||
}
|
||||
if (span.events.length > 0) {
|
||||
return true;
|
||||
}
|
||||
if (endTime - span.status.startTime >= slowSpanThresholdNanos) {
|
||||
return true;
|
||||
}
|
||||
const now = performance.now();
|
||||
if (now - windowStartedAt >= fastSuccessWindowMs) {
|
||||
windowStartedAt = now;
|
||||
fastSuccessCountsByName = new Map();
|
||||
}
|
||||
const count = fastSuccessCountsByName.get(span.name) ?? 0;
|
||||
if (count >= fastSuccessLimitPerWindow) {
|
||||
return false;
|
||||
}
|
||||
fastSuccessCountsByName.set(span.name, count + 1);
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
type OtlpSpan = OtlpTracer.ScopeSpan["spans"][number];
|
||||
@@ -341,6 +409,7 @@ export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: Trac
|
||||
maxBytes: options.maxBytes,
|
||||
maxFiles: options.maxFiles,
|
||||
throwOnError: true,
|
||||
...(options.compressBackups !== undefined ? { compressBackups: options.compressBackups } : {}),
|
||||
});
|
||||
|
||||
let buffer: Array<string> = [];
|
||||
@@ -446,14 +515,17 @@ class LocalFileSpan implements Tracer.Span {
|
||||
events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]>;
|
||||
private readonly delegate: Tracer.Span;
|
||||
private readonly push: (record: EffectTraceRecord) => void;
|
||||
private readonly shouldPersist: (span: LocalFileSpan, endTime: bigint) => boolean;
|
||||
|
||||
constructor(
|
||||
options: Parameters<Tracer.Tracer["span"]>[0],
|
||||
delegate: Tracer.Span,
|
||||
push: (record: EffectTraceRecord) => void,
|
||||
shouldPersist: (span: LocalFileSpan, endTime: bigint) => boolean = () => true,
|
||||
) {
|
||||
this.delegate = delegate;
|
||||
this.push = push;
|
||||
this.shouldPersist = shouldPersist;
|
||||
this.name = delegate.name;
|
||||
this.spanId = delegate.spanId;
|
||||
this.traceId = delegate.traceId;
|
||||
@@ -479,7 +551,7 @@ class LocalFileSpan implements Tracer.Span {
|
||||
};
|
||||
this.delegate.end(endTime, exit);
|
||||
|
||||
if (this.sampled) {
|
||||
if (this.sampled && this.shouldPersist(this, endTime)) {
|
||||
this.push(spanToTraceRecord(this));
|
||||
}
|
||||
}
|
||||
@@ -520,9 +592,11 @@ export const makeLocalFileTracer = Effect.fn("makeLocalFileTracer")(function* (
|
||||
span: (spanOptions) => new Tracer.NativeSpan(spanOptions),
|
||||
});
|
||||
|
||||
const shouldPersist = options.tailPolicy ? makeTraceTailFilter(options.tailPolicy) : undefined;
|
||||
|
||||
return Tracer.make({
|
||||
span(spanOptions) {
|
||||
return new LocalFileSpan(spanOptions, delegate.span(spanOptions), sink.push);
|
||||
return new LocalFileSpan(spanOptions, delegate.span(spanOptions), sink.push, shouldPersist);
|
||||
},
|
||||
...(delegate.context ? { context: delegate.context } : {}),
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user