From 3cc7cf3c837ae41d6abfb1995b603902cb65f726 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sat, 8 Aug 2026 21:12:57 -0700 Subject: [PATCH] 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 --- apps/server/src/bin.test.ts | 1 + apps/server/src/cli/config.ts | 8 +- apps/server/src/cli/pair.ts | 1 + apps/server/src/config.ts | 2 + .../src/diagnostics/TraceDiagnostics.test.ts | 66 ++- .../src/diagnostics/TraceDiagnostics.ts | 251 ++++++---- .../src/environment/ServerEnvironment.test.ts | 1 + .../src/observability/Layers/Observability.ts | 4 + apps/server/src/persistence/Layers/Sqlite.ts | 13 +- apps/server/src/server.test.ts | 1 + apps/server/src/terminal/Manager.test.ts | 23 + apps/server/src/terminal/Manager.ts | 440 ++++++++---------- packages/shared/src/logging.test.ts | 60 +++ packages/shared/src/logging.ts | 47 +- packages/shared/src/observability.test.ts | 44 ++ packages/shared/src/observability.ts | 78 +++- 16 files changed, 670 insertions(+), 370 deletions(-) diff --git a/apps/server/src/bin.test.ts b/apps/server/src/bin.test.ts index fcb662b9b7..525b337dc6 100644 --- a/apps/server/src/bin.test.ts +++ b/apps/server/src/bin.test.ts @@ -72,6 +72,7 @@ const makeCliTestServerConfig = (baseDir: string) => traceBatchWindowMs: 200, traceMaxBytes: 10 * 1024 * 1024, traceMaxFiles: 10, + traceKeepAllSpans: false, otlpTracesUrl: undefined, otlpMetricsUrl: undefined, otlpExportIntervalMs: 10_000, diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts index 5b05b773b3..df22ea6cfd 100644 --- a/apps/server/src/cli/config.ts +++ b/apps/server/src/cli/config.ts @@ -84,8 +84,13 @@ const EnvServerConfig = Config.all({ Config.map(Option.getOrUndefined), ), traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)), - traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)), + // Rotated backups are gzip-compressed (~12x on span NDJSON), so a larger + // file count buys hours of incident history for tens of megabytes. + traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(30)), traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(1_000)), + // Escape hatch: persist every sampled span (no tail filtering) when full + // fidelity matters more than the retention window. + traceKeepAllSpans: Config.boolean("T3CODE_TRACE_KEEP_ALL_SPANS").pipe(Config.withDefault(false)), otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe( Config.option, Config.map(Option.getOrUndefined), @@ -356,6 +361,7 @@ export const resolveServerConfig = ( traceBatchWindowMs: env.traceBatchWindowMs, traceMaxBytes: env.traceMaxBytes, traceMaxFiles: env.traceMaxFiles, + traceKeepAllSpans: env.traceKeepAllSpans, otlpTracesUrl: env.otlpTracesUrl ?? bootstrap?.otlpTracesUrl ?? diff --git a/apps/server/src/cli/pair.ts b/apps/server/src/cli/pair.ts index 38fa3be8bb..d9c5773910 100644 --- a/apps/server/src/cli/pair.ts +++ b/apps/server/src/cli/pair.ts @@ -328,6 +328,7 @@ const makePairServerConfig = Effect.fn(function* (input: { traceBatchWindowMs: 1_000, traceMaxBytes: 10 * 1024 * 1024, traceMaxFiles: 10, + traceKeepAllSpans: false, otlpTracesUrl: undefined, otlpMetricsUrl: undefined, otlpExportIntervalMs: 10_000, diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index e678264dde..ca0ae1c949 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -61,6 +61,7 @@ export class ServerConfig extends Context.Service< readonly traceBatchWindowMs: number; readonly traceMaxBytes: number; readonly traceMaxFiles: number; + readonly traceKeepAllSpans: boolean; readonly otlpTracesUrl: string | undefined; readonly otlpMetricsUrl: string | undefined; readonly otlpExportIntervalMs: number; @@ -174,6 +175,7 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* ( traceBatchWindowMs: 200, traceMaxBytes: 10 * 1024 * 1024, traceMaxFiles: 10, + traceKeepAllSpans: false, otlpTracesUrl: undefined, otlpMetricsUrl: undefined, otlpExportIntervalMs: 10_000, diff --git a/apps/server/src/diagnostics/TraceDiagnostics.test.ts b/apps/server/src/diagnostics/TraceDiagnostics.test.ts index 70bb4dc815..8ddefa3a1e 100644 --- a/apps/server/src/diagnostics/TraceDiagnostics.test.ts +++ b/apps/server/src/diagnostics/TraceDiagnostics.test.ts @@ -1,4 +1,5 @@ import { assert, describe, it } from "@effect/vitest"; +import * as NodeZlib from "node:zlib"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -237,7 +238,11 @@ describe("TraceDiagnostics", () => { kind: "trace-file-read-failed", message: `Failed to read local trace file '${traceFilePath}.1'.`, }); - assert.deepStrictEqual(diagnostics.scannedFilePaths, [`${traceFilePath}.1`, traceFilePath]); + assert.deepStrictEqual(diagnostics.scannedFilePaths, [ + `${traceFilePath}.1.gz`, + `${traceFilePath}.1`, + traceFilePath, + ]); const failureLog = logAnnotations.find( (annotations) => annotations.traceFilePath === `${traceFilePath}.1`, @@ -251,6 +256,65 @@ describe("TraceDiagnostics", () => { }), ); + it.effect("reads gzip-compressed rotated backups", () => + Effect.gen(function* () { + const traceFilePath = "/tmp/server.trace.ndjson"; + const notFound = (method: string, path: string) => + Effect.fail( + PlatformError.systemError({ + _tag: "NotFound", + module: "FileSystem", + method, + description: "missing", + pathOrDescriptor: path, + }), + ); + const fileSystemLayer = FileSystem.layerNoop({ + readFile: (path) => + path === `${traceFilePath}.1.gz` + ? Effect.succeed( + new Uint8Array( + NodeZlib.gzipSync( + record({ + name: "backup.span", + traceId: "trace-gz", + spanId: "span-gz", + startMs: 1_000, + durationMs: 10, + }), + ), + ), + ) + : notFound("readFile", path), + readFileString: (path) => + path === traceFilePath + ? Effect.succeed( + record({ + name: "current.span", + traceId: "trace-live", + spanId: "span-live", + startMs: 2_000, + durationMs: 10, + }), + ) + : notFound("readFileString", path), + }); + + const diagnostics = yield* TraceDiagnostics.readTraceDiagnostics({ + traceFilePath, + maxFiles: 1, + readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"), + }).pipe(Effect.provide(TraceDiagnostics.layer.pipe(Layer.provide(fileSystemLayer)))); + + assert.equal(diagnostics.recordCount, 2); + assert.equal(Option.isNone(diagnostics.error), true); + assert.deepStrictEqual(diagnostics.topSpansByCount.map((span) => span.name).toSorted(), [ + "backup.span", + "current.span", + ]); + }), + ); + it.effect("keeps only the slowest span occurrences while aggregating large inputs", () => Effect.sync(() => { const diagnostics = TraceDiagnostics.aggregateTraceDiagnostics({ diff --git a/apps/server/src/diagnostics/TraceDiagnostics.ts b/apps/server/src/diagnostics/TraceDiagnostics.ts index d54e033380..022794a7bf 100644 --- a/apps/server/src/diagnostics/TraceDiagnostics.ts +++ b/apps/server/src/diagnostics/TraceDiagnostics.ts @@ -7,6 +7,7 @@ import type { ServerTraceDiagnosticsSpanOccurrence, ServerTraceDiagnosticsSpanSummary, } from "@t3tools/contracts"; +import * as NodeZlib from "node:zlib"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -81,11 +82,12 @@ interface TraceDiagnosticsErrorSummary { const DEFAULT_SLOW_SPAN_THRESHOLD_MS = 1_000; const TOP_LIMIT = 10; const RECENT_LIMIT = 20; +// Backups rotate as `.N.gz` since compressBackups, but plain `.N` files from +// before the change age along the chain untouched, so both are candidates. function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyArray { const backupCount = Math.max(0, Math.floor(maxFiles)); - const backups = Array.from( - { length: backupCount }, - (_, index) => `${traceFilePath}.${backupCount - index}`, + const backups = Array.from({ length: backupCount }, (_, index) => backupCount - index).flatMap( + (suffix) => [`${traceFilePath}.${suffix}.gz`, `${traceFilePath}.${suffix}`], ); return [...backups, traceFilePath]; } @@ -186,26 +188,10 @@ function insertBoundedSlowestSpan( } } -export function aggregateTraceDiagnostics( - input: TraceDiagnosticsInput, -): ServerTraceDiagnosticsResult { - const readAt = input.readAt; - const slowSpanThresholdMs = input.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS; - const scannedFilePaths = input.scannedFilePaths ?? input.files.map((file) => file.path); - if (input.files.length === 0) { - return makeEmptyDiagnostics({ - traceFilePath: input.traceFilePath, - scannedFilePaths, - readAt, - slowSpanThresholdMs, - error: input.error ?? { - kind: "trace-file-not-found", - message: "No local trace files were found.", - }, - ...(input.partialFailure ? { partialFailure: true } : {}), - }); - } - +// Incremental aggregation lets the reader feed one decoded file at a time and +// drop its text before touching the next, so peak memory stays one file wide +// no matter how many rotated backups exist. +export function createTraceDiagnosticsAggregator(slowSpanThresholdMs: number) { let parseErrorCount = 0; let recordCount = 0; let failureCount = 0; @@ -224,8 +210,8 @@ export function aggregateTraceDiagnostics( const latestWarningAndErrorLogs: ServerTraceDiagnosticsLogEvent[] = []; const logLevelCounts: Record = {}; - for (const file of input.files) { - const lines = file.text.split(/\r?\n/); + const addFileText = (text: string) => { + const lines = text.split(/\r?\n/); for (const line of lines) { if (line.trim().length === 0) continue; @@ -334,56 +320,102 @@ export function aggregateTraceDiagnostics( } } } + }; + + const finish = (input: { + readonly traceFilePath: string; + readonly scannedFilePaths: ReadonlyArray; + readonly readAt: DateTime.Utc; + readonly error?: TraceDiagnosticsErrorSummary; + readonly partialFailure?: boolean; + }): ServerTraceDiagnosticsResult => { + const topSpansByCount: ServerTraceDiagnosticsSpanSummary[] = [...spansByName.entries()] + .map(([name, span]) => ({ + name, + count: span.count, + failureCount: span.failureCount, + totalDurationMs: span.totalDurationMs, + averageDurationMs: span.count > 0 ? span.totalDurationMs / span.count : 0, + maxDurationMs: span.maxDurationMs, + })) + .toSorted( + (left, right) => right.count - left.count || right.maxDurationMs - left.maxDurationMs, + ) + .slice(0, TOP_LIMIT); + + return { + traceFilePath: input.traceFilePath, + scannedFilePaths: [...input.scannedFilePaths], + readAt: input.readAt, + recordCount, + parseErrorCount, + firstSpanAt: Option.fromNullishOr(firstSpanAt), + lastSpanAt: Option.fromNullishOr(lastSpanAt), + failureCount, + interruptionCount, + slowSpanThresholdMs, + slowSpanCount, + logLevelCounts, + topSpansByCount, + slowestSpans, + commonFailures: [...failuresByKey.values()] + .toSorted( + (left, right) => + right.count - left.count || + DateTime.toEpochMillis(right.lastSeenAt) - DateTime.toEpochMillis(left.lastSeenAt), + ) + .slice(0, TOP_LIMIT), + latestFailures: latestFailures + .toSorted( + (left, right) => + DateTime.toEpochMillis(right.endedAt) - DateTime.toEpochMillis(left.endedAt), + ) + .slice(0, RECENT_LIMIT), + latestWarningAndErrorLogs: latestWarningAndErrorLogs + .toSorted( + (left, right) => + DateTime.toEpochMillis(right.seenAt) - DateTime.toEpochMillis(left.seenAt), + ) + .slice(0, RECENT_LIMIT), + partialFailure: input.partialFailure ? Option.some(true) : Option.none(), + error: Option.fromNullishOr(input.error), + }; + }; + + return { addFileText, finish }; +} + +export function aggregateTraceDiagnostics( + input: TraceDiagnosticsInput, +): ServerTraceDiagnosticsResult { + const readAt = input.readAt; + const slowSpanThresholdMs = input.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS; + const scannedFilePaths = input.scannedFilePaths ?? input.files.map((file) => file.path); + if (input.files.length === 0) { + return makeEmptyDiagnostics({ + traceFilePath: input.traceFilePath, + scannedFilePaths, + readAt, + slowSpanThresholdMs, + error: input.error ?? { + kind: "trace-file-not-found", + message: "No local trace files were found.", + }, + ...(input.partialFailure ? { partialFailure: true } : {}), + }); } - const topSpansByCount: ServerTraceDiagnosticsSpanSummary[] = [...spansByName.entries()] - .map(([name, span]) => ({ - name, - count: span.count, - failureCount: span.failureCount, - totalDurationMs: span.totalDurationMs, - averageDurationMs: span.count > 0 ? span.totalDurationMs / span.count : 0, - maxDurationMs: span.maxDurationMs, - })) - .toSorted((left, right) => right.count - left.count || right.maxDurationMs - left.maxDurationMs) - .slice(0, TOP_LIMIT); - - return { + const aggregator = createTraceDiagnosticsAggregator(slowSpanThresholdMs); + for (const file of input.files) { + aggregator.addFileText(file.text); + } + return aggregator.finish({ traceFilePath: input.traceFilePath, scannedFilePaths, readAt, - recordCount, - parseErrorCount, - firstSpanAt: Option.fromNullishOr(firstSpanAt), - lastSpanAt: Option.fromNullishOr(lastSpanAt), - failureCount, - interruptionCount, - slowSpanThresholdMs, - slowSpanCount, - logLevelCounts, - topSpansByCount, - slowestSpans, - commonFailures: [...failuresByKey.values()] - .toSorted( - (left, right) => - right.count - left.count || - DateTime.toEpochMillis(right.lastSeenAt) - DateTime.toEpochMillis(left.lastSeenAt), - ) - .slice(0, TOP_LIMIT), - latestFailures: latestFailures - .toSorted( - (left, right) => - DateTime.toEpochMillis(right.endedAt) - DateTime.toEpochMillis(left.endedAt), - ) - .slice(0, RECENT_LIMIT), - latestWarningAndErrorLogs: latestWarningAndErrorLogs - .toSorted( - (left, right) => DateTime.toEpochMillis(right.seenAt) - DateTime.toEpochMillis(left.seenAt), - ) - .slice(0, RECENT_LIMIT), - partialFailure: input.partialFailure ? Option.some(true) : Option.none(), - error: Option.fromNullishOr(input.error), - }; + ...(input.error ? { error: input.error } : {}), + ...(input.partialFailure ? { partialFailure: true } : {}), + }); } type TraceFileReadResult = @@ -394,7 +426,22 @@ function readTraceFile( fileSystem: FileSystem.FileSystem, path: string, ): Effect.Effect { - return fileSystem.readFileString(path).pipe( + const decoded = path.endsWith(".gz") + ? fileSystem.readFile(path).pipe( + Effect.flatMap((bytes) => + Effect.try({ + try: () => NodeZlib.gunzipSync(bytes).toString("utf8"), + catch: (cause) => + new TraceFileReadError({ + traceFilePath: path, + causeTag: "GzipDecode", + cause, + }), + }), + ), + ) + : fileSystem.readFileString(path); + return decoded.pipe( Effect.map((text): TraceFileReadResult => ({ _tag: "Loaded", path, text })), Effect.catchTags({ PlatformError: (cause) => @@ -419,39 +466,39 @@ export const make = Effect.gen(function* () { const readAt = options.readAt ?? (yield* DateTime.now); const slowSpanThresholdMs = options.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS; const paths = toRotatedTracePaths(options.traceFilePath, options.maxFiles); - const results = yield* Effect.all( - paths.map((path) => - readTraceFile(fileSystem, path).pipe( - Effect.tapError((cause) => - Effect.logWarning("Failed to read local trace file.").pipe( - Effect.annotateLogs({ - traceFilePath: cause.traceFilePath, - errorTag: cause._tag, - causeTag: cause.causeTag, - }), - ), + // One file at a time: each decoded text is aggregated and released + // before the next read, so a large maxFiles never loads the whole + // rotation window into memory at once. + const aggregator = createTraceDiagnosticsAggregator(slowSpanThresholdMs); + let loadedFileCount = 0; + let readFailureError: TraceDiagnosticsErrorSummary | undefined; + for (const path of paths) { + const result = yield* readTraceFile(fileSystem, path).pipe( + Effect.tapError((cause) => + Effect.logWarning("Failed to read local trace file.").pipe( + Effect.annotateLogs({ + traceFilePath: cause.traceFilePath, + errorTag: cause._tag, + causeTag: cause.causeTag, + }), ), - Effect.result, ), - ), - { - concurrency: 1, - }, - ); - const files = results.flatMap((result) => - Result.isSuccess(result) && result.success._tag === "Loaded" - ? [{ path: result.success.path, text: result.success.text }] - : [], - ); - const readFailure = results.find(Result.isFailure); - const readFailureError = readFailure - ? ({ + Effect.result, + ); + if (Result.isFailure(result)) { + readFailureError ??= { kind: "trace-file-read-failed", - message: readFailure.failure.message, - } satisfies TraceDiagnosticsErrorSummary) - : undefined; + message: result.failure.message, + } satisfies TraceDiagnosticsErrorSummary; + continue; + } + if (result.success._tag === "Loaded") { + loadedFileCount += 1; + aggregator.addFileText(result.success.text); + } + } - if (files.length === 0) { + if (loadedFileCount === 0) { return makeEmptyDiagnostics({ traceFilePath: options.traceFilePath, scannedFilePaths: paths, @@ -466,12 +513,10 @@ export const make = Effect.gen(function* () { }); } - return aggregateTraceDiagnostics({ + return aggregator.finish({ traceFilePath: options.traceFilePath, - files, scannedFilePaths: paths, readAt, - slowSpanThresholdMs, ...(readFailureError ? { partialFailure: true, error: readFailureError } : {}), }); }, diff --git a/apps/server/src/environment/ServerEnvironment.test.ts b/apps/server/src/environment/ServerEnvironment.test.ts index a7aea90f82..0003374f60 100644 --- a/apps/server/src/environment/ServerEnvironment.test.ts +++ b/apps/server/src/environment/ServerEnvironment.test.ts @@ -27,6 +27,7 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) { traceBatchWindowMs: 200, traceMaxBytes: 10 * 1024 * 1024, traceMaxFiles: 10, + traceKeepAllSpans: false, otlpTracesUrl: undefined, otlpMetricsUrl: undefined, otlpExportIntervalMs: 10_000, diff --git a/apps/server/src/observability/Layers/Observability.ts b/apps/server/src/observability/Layers/Observability.ts index 8aac092753..ce95071df2 100644 --- a/apps/server/src/observability/Layers/Observability.ts +++ b/apps/server/src/observability/Layers/Observability.ts @@ -34,6 +34,7 @@ export const ObservabilityLive = Layer.unwrap( maxBytes: config.traceMaxBytes, maxFiles: config.traceMaxFiles, batchWindowMs: config.traceBatchWindowMs, + compressBackups: true, onFlush: (stats) => attribution.record({ component: "server-trace", @@ -65,6 +66,9 @@ export const ObservabilityLive = Layer.unwrap( batchWindowMs: config.traceBatchWindowMs, sink, ...(delegate ? { delegate } : {}), + // Tail policy applies to the local file only; the OTLP delegate + // still receives every sampled span. + ...(config.traceKeepAllSpans ? {} : { tailPolicy: {} }), }); return Layer.mergeAll( diff --git a/apps/server/src/persistence/Layers/Sqlite.ts b/apps/server/src/persistence/Layers/Sqlite.ts index d1e0025012..e9f5ac54b7 100644 --- a/apps/server/src/persistence/Layers/Sqlite.ts +++ b/apps/server/src/persistence/Layers/Sqlite.ts @@ -46,16 +46,9 @@ export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")( const path = yield* Path.Path; yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true }); - return Layer.provideMerge( - setup, - makeRuntimeSqliteLayer({ - filename: dbPath, - spanAttributes: { - "db.name": path.basename(dbPath), - "service.name": "t3-server", - }, - }), - ); + // No per-span attributes: sql.execute fires ~76/s under load and constant + // attributes on every span were a measurable share of local trace volume. + return Layer.provideMerge(setup, makeRuntimeSqliteLayer({ filename: dbPath })); }, Layer.unwrap); export const SqlitePersistenceMemory = Layer.provideMerge( diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index cb64c6a480..fc2b75f2f2 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -434,6 +434,7 @@ const buildAppUnderTest = (options?: { traceBatchWindowMs: 200, traceMaxBytes: 10 * 1024 * 1024, traceMaxFiles: 10, + traceKeepAllSpans: false, otlpTracesUrl: undefined, otlpMetricsUrl: undefined, otlpExportIntervalMs: 10_000, diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index ed25a0880b..e445eb2d44 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -1764,3 +1764,26 @@ it.layer( }).pipe(Effect.provide(TestClock.layer())), ); }); + +it("inspectSubprocessFromSnapshot resolves child command and descendants from one table", () => { + const snapshot = TerminalManager.processTableFromRows([ + [100, 1, "zsh"], + [200, 100, "node"], + [201, 200, "esbuild"], + [202, 200, "tmux: server"], + [900, 1, "unrelated"], + ]); + + const inspected = TerminalManager.inspectSubprocessFromSnapshot(100, snapshot, "linux"); + assert.equal(inspected.hasRunningSubprocess, true); + assert.equal(inspected.childCommand, "node"); + assert.deepStrictEqual([...inspected.processIds].toSorted(), [100, 200, 201, 202]); + + const idle = TerminalManager.inspectSubprocessFromSnapshot(900, snapshot, "linux"); + assert.equal(idle.hasRunningSubprocess, false); + assert.equal(idle.childCommand, null); + assert.deepStrictEqual(idle.processIds, []); + + const missing = TerminalManager.inspectSubprocessFromSnapshot(555, snapshot, "linux"); + assert.equal(missing.hasRunningSubprocess, false); +}); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 6dc9e1892b..d9d79cde15 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -46,6 +46,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as References from "effect/References"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; @@ -89,12 +90,15 @@ class TerminalSubprocessCheckError extends Schema.TaggedErrorClass 0 + ? `Failed to inspect terminal subprocesses for PID ${this.terminalPid} with ${this.command}` + : `Failed to capture the process table with ${this.command}`; } } @@ -188,7 +192,7 @@ export class TerminalManager extends Context.Service< } >()("t3/terminal/Manager/TerminalManager") {} -interface TerminalSubprocessInspectResult { +export interface TerminalSubprocessInspectResult { readonly hasRunningSubprocess: boolean; readonly childCommand: string | null; readonly processIds: ReadonlyArray; @@ -610,21 +614,33 @@ function isRetryableShellSpawnError(error: PtyAdapter.PtySpawnError): boolean { ); } -function parseFirstChildPidFromPgrep(stdout: string): number | null { - for (const line of stdout.split(/\r?\n/g)) { - const n = Number.parseInt(line.trim(), 10); - if (Number.isInteger(n) && n > 0) { - return n; - } - } - return null; +// One pid/ppid/name table read per poll tick serves every running terminal. +// The previous per-terminal inspection spawned pgrep plus up to three ps +// invocations per session per second (a full `ps -e` table each time), which +// dominated both process churn and trace volume on hosts with many terminals. +export interface ProcessTableSnapshot { + readonly commandByPid: ReadonlyMap; + readonly childrenByParent: ReadonlyMap>; } -function windowsInspectSubprocess( - terminalPid: number, - platform: NodeJS.Platform, -): Effect.Effect< - TerminalSubprocessInspectResult, +export function processTableFromRows( + rows: Iterable, +): ProcessTableSnapshot { + const commandByPid = new Map(); + const childrenByParent = new Map(); + for (const [pid, parentPid, command] of rows) { + commandByPid.set(pid, command); + const children = childrenByParent.get(parentPid) ?? []; + children.push(pid); + childrenByParent.set(parentPid, children); + } + return { commandByPid, childrenByParent }; +} + +const PROCESS_TABLE_MAX_OUTPUT_BYTES = 1_048_576; + +function captureWindowsProcessTable(): Effect.Effect< + ProcessTableSnapshot, TerminalSubprocessCheckError, ProcessRunner.ProcessRunner > { @@ -632,224 +648,110 @@ function windowsInspectSubprocess( 'Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { Write-Output "$($_.ProcessId)|$($_.ParentProcessId)|$($_.Name)" }'; return Effect.gen(function* () { const processRunner = yield* ProcessRunner.ProcessRunner; - return yield* processRunner.run({ - // powershell.exe is a real executable — never spawn it through cmd.exe - // shell mode, which would re-tokenize the `-Command` payload (pipes, - // semicolons) before PowerShell ever sees it. - command: "powershell.exe", - args: ["-NoProfile", "-NonInteractive", "-Command", command], - timeout: "1500 millis", - maxOutputBytes: 32_768, - outputMode: "truncate", - timeoutBehavior: "timedOutResult", - }); - }).pipe( - Effect.map((result) => { - if (result.code !== 0) { - return { hasRunningSubprocess: false, childCommand: null, processIds: [] } as const; - } - const processNameById = new Map(); - const childrenByParent = new Map(); - for (const line of result.stdout.split(/\r?\n/g)) { - const [pidRaw, parentPidRaw, nameRaw] = line.trim().split("|", 3); - const pid = Number(pidRaw); - const parentPid = Number(parentPidRaw); - if (!Number.isInteger(pid) || !Number.isInteger(parentPid)) continue; - processNameById.set(pid, nameRaw?.trim() ?? ""); - const children = childrenByParent.get(parentPid) ?? []; - children.push(pid); - childrenByParent.set(parentPid, children); - } - const directChildren = childrenByParent.get(terminalPid) ?? []; - const childPid = directChildren[0]; - if (childPid === undefined) { - return { hasRunningSubprocess: false, childCommand: null, processIds: [] } as const; - } - const processIds = new Set([terminalPid]); - const pending = [terminalPid]; - while (pending.length > 0) { - const parentPid = pending.pop(); - if (parentPid === undefined) continue; - for (const pid of childrenByParent.get(parentPid) ?? []) { - if (processIds.has(pid)) continue; - processIds.add(pid); - pending.push(pid); - } - } - const normalized = normalizeChildCommandName(processNameById.get(childPid) ?? "", platform); - return { - hasRunningSubprocess: true, - childCommand: normalized ? truncateTerminalWireLabel(normalized) : null, - processIds: [...processIds], - } as const; - }), - Effect.mapError( - (cause) => - new TerminalSubprocessCheckError({ - cause, - terminalPid, - command: "powershell", - }), - ), - ); + const result = yield* processRunner + .run({ + // powershell.exe is a real executable — never spawn it through cmd.exe + // shell mode, which would re-tokenize the `-Command` payload (pipes, + // semicolons) before PowerShell ever sees it. + command: "powershell.exe", + args: ["-NoProfile", "-NonInteractive", "-Command", command], + timeout: "1500 millis", + maxOutputBytes: PROCESS_TABLE_MAX_OUTPUT_BYTES, + outputMode: "truncate", + timeoutBehavior: "timedOutResult", + }) + .pipe( + Effect.mapError( + (cause) => + new TerminalSubprocessCheckError({ cause, terminalPid: 0, command: "powershell" }), + ), + ); + if (result.code !== 0) { + return yield* new TerminalSubprocessCheckError({ terminalPid: 0, command: "powershell" }); + } + const rows: Array = []; + for (const line of result.stdout.split(/\r?\n/g)) { + const [pidRaw, parentPidRaw, nameRaw] = line.trim().split("|", 3); + const pid = Number(pidRaw); + const parentPid = Number(parentPidRaw); + if (!Number.isInteger(pid) || !Number.isInteger(parentPid)) continue; + rows.push([pid, parentPid, nameRaw?.trim() ?? ""]); + } + return processTableFromRows(rows); + }); } -const posixInspectSubprocess = Effect.fn("terminal.posixInspectSubprocess")(function* ( - terminalPid: number, - platform: NodeJS.Platform, -): Effect.fn.Return< - TerminalSubprocessInspectResult, +function capturePosixProcessTable(): Effect.Effect< + ProcessTableSnapshot, TerminalSubprocessCheckError, ProcessRunner.ProcessRunner > { - const processRunner = yield* ProcessRunner.ProcessRunner; - const runPgrep = processRunner - .run({ - command: "pgrep", - args: ["-P", String(terminalPid)], - timeout: "1 second", - maxOutputBytes: 32_768, - outputMode: "truncate", - timeoutBehavior: "timedOutResult", - }) - .pipe( - Effect.mapError( - (cause) => - new TerminalSubprocessCheckError({ - cause, - terminalPid, - command: "pgrep", - }), - ), - ); - - const runPs = processRunner - .run({ - command: "ps", - args: ["-eo", "pid=,ppid="], - timeout: "1 second", - maxOutputBytes: 262_144, - outputMode: "truncate", - timeoutBehavior: "timedOutResult", - }) - .pipe( - Effect.mapError( - (cause) => - new TerminalSubprocessCheckError({ - cause, - terminalPid, - command: "ps", - }), - ), - ); - - let childPid: number | null = null; - - const pgrepResult = yield* Effect.exit(runPgrep); - if (pgrepResult._tag === "Success") { - if (pgrepResult.value.code === 0) { - childPid = parseFirstChildPidFromPgrep(pgrepResult.value.stdout); - } else if (pgrepResult.value.code === 1) { - return { hasRunningSubprocess: false, childCommand: null, processIds: [] }; + return Effect.gen(function* () { + const processRunner = yield* ProcessRunner.ProcessRunner; + const result = yield* processRunner + .run({ + command: "ps", + args: ["-eo", "pid=,ppid=,comm="], + timeout: "1 second", + maxOutputBytes: PROCESS_TABLE_MAX_OUTPUT_BYTES, + outputMode: "truncate", + timeoutBehavior: "timedOutResult", + }) + .pipe( + Effect.mapError( + (cause) => new TerminalSubprocessCheckError({ cause, terminalPid: 0, command: "ps" }), + ), + ); + if (result.code !== 0) { + return yield* new TerminalSubprocessCheckError({ terminalPid: 0, command: "ps" }); } - } - - if (childPid === null) { - const psResult = yield* Effect.exit(runPs); - if (psResult._tag === "Failure" || psResult.value.code !== 0) { - return { hasRunningSubprocess: false, childCommand: null, processIds: [] }; + const rows: Array = []; + for (const line of result.stdout.split(/\r?\n/g)) { + // comm may contain spaces ("tmux: server"), so only the two leading + // numeric columns are positional. + const match = /^(\d+)\s+(\d+)\s*(.*)$/.exec(line.trim()); + if (!match) continue; + rows.push([Number(match[1]), Number(match[2]), match[3] ?? ""]); } - for (const line of psResult.value.stdout.split(/\r?\n/g)) { - const [pidRaw, ppidRaw] = line.trim().split(/\s+/g); - const pid = Number(pidRaw); - const ppid = Number(ppidRaw); - if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue; - if (ppid === terminalPid) { - childPid = pid; - break; - } - } - } + return processTableFromRows(rows); + }); +} - if (childPid === null) { +function captureProcessTableSnapshot( + platform: NodeJS.Platform, +): Effect.Effect { + return platform === "win32" ? captureWindowsProcessTable() : capturePosixProcessTable(); +} + +export function inspectSubprocessFromSnapshot( + terminalPid: number, + snapshot: ProcessTableSnapshot, + platform: NodeJS.Platform, +): TerminalSubprocessInspectResult { + if (!Number.isInteger(terminalPid) || terminalPid <= 0) { return { hasRunningSubprocess: false, childCommand: null, processIds: [] }; } - - const runComm = processRunner.run({ - command: "ps", - args: ["-p", String(childPid), "-o", "comm="], - timeout: "1 second", - maxOutputBytes: 8_192, - outputMode: "truncate", - timeoutBehavior: "timedOutResult", - }); - - const commResult = yield* Effect.exit(runComm); - let rawComm: string | null = null; - if (commResult._tag === "Success" && commResult.value && commResult.value.code === 0) { - rawComm = commResult.value.stdout.trim(); + const childPid = (snapshot.childrenByParent.get(terminalPid) ?? [])[0]; + if (childPid === undefined) { + return { hasRunningSubprocess: false, childCommand: null, processIds: [] }; } - - if (!rawComm || rawComm.length === 0) { - const runArgs = processRunner.run({ - command: "ps", - args: ["-p", String(childPid), "-o", "args="], - timeout: "1 second", - maxOutputBytes: 16_384, - outputMode: "truncate", - timeoutBehavior: "timedOutResult", - }); - const argsResult = yield* Effect.exit(runArgs); - if (argsResult._tag === "Success" && argsResult.value && argsResult.value.code === 0) { - const first = argsResult.value.stdout.trim().split(/\s+/)[0] ?? ""; - rawComm = first.length > 0 ? first : null; - } - } - - const normalized = rawComm ? normalizeChildCommandName(rawComm, platform) : null; const processIds = new Set([terminalPid]); - const psResult = yield* Effect.exit(runPs); - if (psResult._tag === "Success" && psResult.value.code === 0) { - const childrenByParent = new Map(); - for (const line of psResult.value.stdout.split(/\r?\n/g)) { - const [pidRaw, ppidRaw] = line.trim().split(/\s+/g); - const pid = Number(pidRaw); - const ppid = Number(ppidRaw); - if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue; - const children = childrenByParent.get(ppid) ?? []; - children.push(pid); - childrenByParent.set(ppid, children); + const pending = [terminalPid]; + while (pending.length > 0) { + const parentPid = pending.pop(); + if (parentPid === undefined) continue; + for (const pid of snapshot.childrenByParent.get(parentPid) ?? []) { + if (processIds.has(pid)) continue; + processIds.add(pid); + pending.push(pid); } - const pending = [terminalPid]; - while (pending.length > 0) { - const parentPid = pending.pop(); - if (parentPid === undefined) continue; - for (const child of childrenByParent.get(parentPid) ?? []) { - if (processIds.has(child)) continue; - processIds.add(child); - pending.push(child); - } - } - } else { - processIds.add(childPid); } + const normalized = normalizeChildCommandName(snapshot.commandByPid.get(childPid) ?? "", platform); return { hasRunningSubprocess: true, childCommand: normalized ? truncateTerminalWireLabel(normalized) : null, processIds: [...processIds], }; -}); - -function defaultSubprocessInspectorForPlatform(platform: NodeJS.Platform) { - return Effect.fn("terminal.defaultSubprocessInspector")(function* (terminalPid: number) { - if (!Number.isInteger(terminalPid) || terminalPid <= 0) { - return { hasRunningSubprocess: false, childCommand: null, processIds: [] }; - } - if (platform === "win32") { - return yield* windowsInspectSubprocess(terminalPid, platform); - } - return yield* posixInspectSubprocess(terminalPid, platform); - }); } function capHistory(history: string, maxLines: number): string { @@ -1227,12 +1129,9 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const baseEnv = options.env ?? process.env; const shellResolver = options.shellResolver ?? (() => defaultShellResolver(platform, baseEnv)); const processRunner = yield* ProcessRunner.ProcessRunner; - const subprocessInspector = - options.subprocessInspector ?? - ((terminalPid) => - defaultSubprocessInspectorForPlatform(platform)(terminalPid).pipe( - Effect.provideService(ProcessRunner.ProcessRunner, processRunner), - )); + // Injected per-terminal inspector is the test seam; the default path takes + // one process-table snapshot per tick instead (see pollSubprocessActivity). + const subprocessInspector = options.subprocessInspector ?? null; const subprocessPollIntervalMs = options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS; const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS; @@ -2053,6 +1952,53 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func } }); + const inspectRunningSubprocesses = Effect.fn("terminal.inspectRunningSubprocesses")(function* ( + sessions: ReadonlyArray, + ) { + const results = new Map(); + if (subprocessInspector !== null) { + for (const session of sessions) { + const inspectResult = yield* subprocessInspector(session.pid).pipe( + Effect.map(Option.some), + Effect.catch((reason) => + Effect.logWarning("failed to check terminal subprocess activity", { + threadId: session.threadId, + terminalId: session.terminalId, + terminalPid: session.pid, + reason, + }).pipe(Effect.as(Option.none())), + ), + ); + if (Option.isSome(inspectResult)) { + results.set(session.pid, inspectResult.value); + } + } + return results; + } + + const snapshot = yield* captureProcessTableSnapshot(platform).pipe( + Effect.provideService(ProcessRunner.ProcessRunner, processRunner), + Effect.map(Option.some), + // A failed snapshot skips the tick: sessions keep their previous state + // and the next tick retries. + Effect.catch((reason) => + Effect.logWarning("failed to capture process table for subprocess activity", { + reason, + }).pipe(Effect.as(Option.none())), + ), + ); + if (Option.isNone(snapshot)) { + return results; + } + for (const session of sessions) { + results.set( + session.pid, + inspectSubprocessFromSnapshot(session.pid, snapshot.value, platform), + ); + } + return results; + }); + const pollSubprocessActivity = Effect.fn("terminal.pollSubprocessActivity")(function* () { const state = yield* readManagerState; const runningSessions = [...state.sessions.values()].filter( @@ -2064,27 +2010,13 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func return; } - const checkSubprocessActivity = Effect.fn("terminal.checkSubprocessActivity")(function* ( + const inspections = yield* inspectRunningSubprocesses(runningSessions); + + const applySubprocessActivity = Effect.fn("terminal.applySubprocessActivity")(function* ( session: TerminalSessionState & { pid: number }, + next: TerminalSubprocessInspectResult, ) { const terminalPid = session.pid; - const inspectResult = yield* subprocessInspector(terminalPid).pipe( - Effect.map(Option.some), - Effect.catch((reason) => - Effect.logWarning("failed to check terminal subprocess activity", { - threadId: session.threadId, - terminalId: session.terminalId, - terminalPid, - reason, - }).pipe(Effect.as(Option.none())), - ), - ); - - if (Option.isNone(inspectResult)) { - return; - } - - const next = inspectResult.value; yield* registerTerminalProcesses({ threadId: session.threadId, terminalId: session.terminalId, @@ -2123,14 +2055,29 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func }); if (Option.isSome(event)) { - yield* publishEvent(event.value); + // The poll tick runs with tracing suppressed; an actual state flip is + // the only part worth a span, so tracing is re-enabled just for it. + yield* publishEvent(event.value).pipe( + Effect.withSpan("terminal.subprocessActivityChanged", { + attributes: { + threadId: session.threadId, + terminalId: session.terminalId, + hasRunningSubprocess: next.hasRunningSubprocess, + ...(nextChildLabel !== null ? { childCommand: nextChildLabel } : {}), + }, + }), + Effect.provideService(References.TracerEnabled, true), + ); } }); - yield* Effect.forEach(runningSessions, checkSubprocessActivity, { - concurrency: "unbounded", - discard: true, - }); + for (const session of runningSessions) { + const next = inspections.get(session.pid); + if (next === undefined) { + continue; + } + yield* applySubprocessActivity(session, next); + } }); const hasRunningSessions = readManagerState.pipe( @@ -2144,6 +2091,11 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func Effect.flatMap((active) => active ? pollSubprocessActivity().pipe( + // Steady-state polling emitted several empty always-success + // spans per terminal per second. Suppress the whole tick; the + // explicit subprocessActivityChanged span above is the only + // trace output. + Effect.provideService(References.TracerEnabled, false), Effect.flatMap(() => Effect.sleep(subprocessPollIntervalMs)), ) : Effect.sleep(subprocessPollIntervalMs), diff --git a/packages/shared/src/logging.test.ts b/packages/shared/src/logging.test.ts index 4b19bd291d..2d81af85be 100644 --- a/packages/shared/src/logging.test.ts +++ b/packages/shared/src/logging.test.ts @@ -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); + }); }); diff --git a/packages/shared/src/logging.ts b/packages/shared/src/logging.ts index ac3d56e28e..58f02fdcdb 100644 --- a/packages/shared/src/logging.ts +++ b/packages/shared/src/logging.ts @@ -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()( @@ -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}`; } } diff --git a/packages/shared/src/observability.test.ts b/packages/shared/src/observability.test.ts index c58395393d..debb10a552 100644 --- a/packages/shared/src/observability.test.ts +++ b/packages/shared/src/observability.test.ts @@ -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)), + ), + ); }); diff --git a/packages/shared/src/observability.ts b/packages/shared/src/observability.ts index 67057c5488..93754ca33f 100644 --- a/packages/shared/src/observability.ts +++ b/packages/shared/src/observability.ts @@ -111,6 +111,8 @@ export interface TraceSinkOptions { readonly maxFiles: number; readonly batchWindowMs: number; readonly onFlush?: (stats: TraceSinkFlushStats) => Effect.Effect; + /** 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(); + + 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 = []; @@ -446,14 +515,17 @@ class LocalFileSpan implements Tracer.Span { events: Array<[name: string, startTime: bigint, attributes: Record]>; private readonly delegate: Tracer.Span; private readonly push: (record: EffectTraceRecord) => void; + private readonly shouldPersist: (span: LocalFileSpan, endTime: bigint) => boolean; constructor( options: Parameters[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 } : {}), });