Compare commits

...
Author SHA1 Message Date
Theo BrowneandClaude Fable 5 ffd43b41ec fix(server): second round of review findings
- Restore the powershell/ps literal union on
  TerminalSubprocessCheckError.command; the widening to Schema.String
  was unnecessary once the capture path got its own error class.
- Decide session liveness before registerTerminalProcesses, so a
  terminal that exited or restarted mid-tick cannot get its old process
  tree re-registered with port discovery.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-09 14:51:48 -07:00
Theo BrowneandClaude Fable 5 04ae0412ef fix(server): address review findings on trace churn PR
- Dedicated TerminalProcessTableCaptureError for whole-table snapshot
  failures instead of a terminalPid: 0 sentinel on the per-terminal
  error (Macroscope conventions).
- Fail the snapshot when ps/powershell output is truncated instead of
  silently treating cut-off sessions as subprocess-free; cap raised to
  4 MiB (Macroscope).
- Poll entries carry the pid they were inspected under, so a terminal
  restart mid-tick can no longer register a stale inspection against
  the new process (Macroscope).
- makeLocalFileTracer forwards compressBackups to its default sink
  (Macroscope).
- Crash-safe gzip rotation: rename first, publish gz via tmp+rename,
  drop plain crash leftovers next to their gz copy in both the rotation
  chain and the diagnostics reader, prune orphaned .gz.tmp files
  (Cursor Bugbot).
- cli/config.test.ts expectations updated for traceMaxFiles=30 and
  traceKeepAllSpans (CI failure).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-09 14:46:08 -07:00
Theo BrowneandClaude Fable 5 3cc7cf3c83 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]>
2026-08-08 21:12:57 -07:00
17 changed files with 807 additions and 395 deletions

No files matched your search

+1
View File
@@ -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,
+2 -1
View File
@@ -45,7 +45,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
traceTimingEnabled: true,
traceBatchWindowMs: 1_000,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
traceMaxFiles: 30,
traceKeepAllSpans: false,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
+7 -1
View File
@@ -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 ??
+1
View File
@@ -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,
+2
View File
@@ -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,
@@ -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({
+155 -103
View File
@@ -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<string> {
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<string, number> = {};
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<string>;
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<TraceFileReadResult, TraceFileReadError> {
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,46 @@ 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;
const loadedPaths = new Set<string>();
for (const path of paths) {
// A plain backup next to its own .gz copy is a crash leftover with
// identical content — counting both would double every span in it.
if (!path.endsWith(".gz") && loadedPaths.has(`${path}.gz`)) {
continue;
}
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;
loadedPaths.add(path);
aggregator.addFileText(result.success.text);
}
}
if (files.length === 0) {
if (loadedFileCount === 0) {
return makeEmptyDiagnostics({
traceFilePath: options.traceFilePath,
scannedFilePaths: paths,
@@ -466,12 +520,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 } : {}),
});
},
@@ -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,
@@ -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(
+3 -10
View File
@@ -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(
+1
View File
@@ -434,6 +434,7 @@ const buildAppUnderTest = (options?: {
traceBatchWindowMs: 200,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
traceKeepAllSpans: false,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
+23
View File
@@ -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);
});
+270 -268
View File
@@ -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";
@@ -90,7 +91,7 @@ class TerminalSubprocessCheckError extends Schema.TaggedErrorClass<TerminalSubpr
{
cause: Schema.optional(Schema.Defect()),
terminalPid: Schema.Number,
command: Schema.Literals(["powershell", "pgrep", "ps"]),
command: Schema.Literals(["powershell", "ps"]),
},
) {
override get message(): string {
@@ -98,6 +99,22 @@ class TerminalSubprocessCheckError extends Schema.TaggedErrorClass<TerminalSubpr
}
}
// The whole-table snapshot has no per-terminal identity, so its failure is a
// separate error rather than a TerminalSubprocessCheckError with a sentinel
// pid.
class TerminalProcessTableCaptureError extends Schema.TaggedErrorClass<TerminalProcessTableCaptureError>()(
"TerminalProcessTableCaptureError",
{
cause: Schema.optional(Schema.Defect()),
command: Schema.Literals(["powershell", "ps"]),
truncated: Schema.optional(Schema.Boolean),
},
) {
override get message(): string {
return `Failed to capture the process table with ${this.command}`;
}
}
class TerminalProcessSignalError extends Schema.TaggedErrorClass<TerminalProcessSignalError>()(
"TerminalProcessSignalError",
{
@@ -188,7 +205,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<number>;
@@ -610,246 +627,156 @@ 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<number, string>;
readonly childrenByParent: ReadonlyMap<number, ReadonlyArray<number>>;
}
function windowsInspectSubprocess(
terminalPid: number,
platform: NodeJS.Platform,
): Effect.Effect<
TerminalSubprocessInspectResult,
TerminalSubprocessCheckError,
export function processTableFromRows(
rows: Iterable<readonly [pid: number, parentPid: number, command: string]>,
): ProcessTableSnapshot {
const commandByPid = new Map<number, string>();
const childrenByParent = new Map<number, number[]>();
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 = 4 * 1_048_576;
function captureWindowsProcessTable(): Effect.Effect<
ProcessTableSnapshot,
TerminalProcessTableCaptureError,
ProcessRunner.ProcessRunner
> {
const command =
'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<number, string>();
const childrenByParent = new Map<number, number[]>();
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<number>([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 TerminalProcessTableCaptureError({ cause, command: "powershell" }),
),
);
if (result.code !== 0) {
return yield* new TerminalProcessTableCaptureError({ command: "powershell" });
}
// A truncated table silently loses the sessions past the cutoff — they
// would read as "no subprocesses" and drop out of resource registration.
if (result.stdoutTruncated) {
return yield* new TerminalProcessTableCaptureError({
command: "powershell",
truncated: true,
});
}
const rows: Array<readonly [number, number, string]> = [];
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,
TerminalSubprocessCheckError,
function capturePosixProcessTable(): Effect.Effect<
ProcessTableSnapshot,
TerminalProcessTableCaptureError,
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 TerminalProcessTableCaptureError({ cause, command: "ps" })),
);
if (result.code !== 0) {
return yield* new TerminalProcessTableCaptureError({ 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: [] };
if (result.stdoutTruncated) {
return yield* new TerminalProcessTableCaptureError({ command: "ps", truncated: true });
}
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;
}
const rows: Array<readonly [number, number, string]> = [];
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] ?? ""]);
}
}
return processTableFromRows(rows);
});
}
if (childPid === null) {
function captureProcessTableSnapshot(
platform: NodeJS.Platform,
): Effect.Effect<
ProcessTableSnapshot,
TerminalProcessTableCaptureError,
ProcessRunner.ProcessRunner
> {
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<number>([terminalPid]);
const psResult = yield* Effect.exit(runPs);
if (psResult._tag === "Success" && psResult.value.code === 0) {
const childrenByParent = new Map<number, number[]>();
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 +1154,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,56 +1977,100 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
}
});
// The session objects are mutable and a restart can swap pid mid-tick, so
// every poll entry carries the pid it was inspected under; downstream guards
// compare against this captured pid, never a re-read of session.pid.
interface RunningSessionPoll {
readonly session: TerminalSessionState;
readonly pid: number;
}
const inspectRunningSubprocesses = Effect.fn("terminal.inspectRunningSubprocesses")(function* (
entries: ReadonlyArray<RunningSessionPoll>,
) {
const results = new Map<number, TerminalSubprocessInspectResult>();
if (subprocessInspector !== null) {
for (const { session, pid } of entries) {
const inspectResult = yield* subprocessInspector(pid).pipe(
Effect.map(Option.some),
Effect.catch((reason) =>
Effect.logWarning("failed to check terminal subprocess activity", {
threadId: session.threadId,
terminalId: session.terminalId,
terminalPid: pid,
reason,
}).pipe(Effect.as(Option.none<TerminalSubprocessInspectResult>())),
),
);
if (Option.isSome(inspectResult)) {
results.set(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<ProcessTableSnapshot>())),
),
);
if (Option.isNone(snapshot)) {
return results;
}
for (const { pid } of entries) {
results.set(pid, inspectSubprocessFromSnapshot(pid, snapshot.value, platform));
}
return results;
});
const pollSubprocessActivity = Effect.fn("terminal.pollSubprocessActivity")(function* () {
const state = yield* readManagerState;
const runningSessions = [...state.sessions.values()].filter(
(session): session is TerminalSessionState & { pid: number } =>
session.status === "running" && Number.isInteger(session.pid),
);
const runningSessions: Array<RunningSessionPoll> = [];
for (const session of state.sessions.values()) {
if (session.status === "running" && session.pid !== null && Number.isInteger(session.pid)) {
runningSessions.push({ session, pid: session.pid });
}
}
if (runningSessions.length === 0) {
return;
}
const checkSubprocessActivity = Effect.fn("terminal.checkSubprocessActivity")(function* (
session: TerminalSessionState & { pid: number },
const inspections = yield* inspectRunningSubprocesses(runningSessions);
const applySubprocessActivity = Effect.fn("terminal.applySubprocessActivity")(function* (
{ session, pid: terminalPid }: RunningSessionPoll,
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<TerminalSubprocessInspectResult>())),
),
);
if (Option.isNone(inspectResult)) {
return;
}
const next = inspectResult.value;
yield* registerTerminalProcesses({
threadId: session.threadId,
terminalId: session.terminalId,
processIds: next.processIds,
});
const nextChildLabel = next.hasRunningSubprocess ? next.childCommand : null;
const event = yield* modifyManagerState((state) => {
const outcome = yield* modifyManagerState<{
readonly live: boolean;
readonly event: Option.Option<TerminalEvent>;
}>((state) => {
const liveSession: Option.Option<TerminalSessionState> = Option.fromNullishOr(
state.sessions.get(toSessionKey(session.threadId, session.terminalId)),
);
// Liveness is decided here, before process registration, so a
// terminal that exited or restarted mid-tick cannot get its old
// process tree re-registered with port discovery.
if (
Option.isNone(liveSession) ||
liveSession.value.status !== "running" ||
liveSession.value.pid !== terminalPid ||
(liveSession.value.hasRunningSubprocess === next.hasRunningSubprocess &&
liveSession.value.childCommandLabel === nextChildLabel)
liveSession.value.pid !== terminalPid
) {
return [Option.none(), state] as const;
return [{ live: false, event: Option.none<TerminalEvent>() }, state] as const;
}
if (
liveSession.value.hasRunningSubprocess === next.hasRunningSubprocess &&
liveSession.value.childCommandLabel === nextChildLabel
) {
return [{ live: true, event: Option.none<TerminalEvent>() }, state] as const;
}
liveSession.value.hasRunningSubprocess = next.hasRunningSubprocess;
@@ -2110,27 +2078,56 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
const eventStamp = advanceEventSequence(liveSession.value);
return [
Option.some({
type: "activity" as const,
threadId: liveSession.value.threadId,
terminalId: liveSession.value.terminalId,
sequence: eventStamp.sequence,
hasRunningSubprocess: next.hasRunningSubprocess,
label: terminalWireLabel(liveSession.value),
}),
{
live: true,
event: Option.some({
type: "activity" as const,
threadId: liveSession.value.threadId,
terminalId: liveSession.value.terminalId,
sequence: eventStamp.sequence,
hasRunningSubprocess: next.hasRunningSubprocess,
label: terminalWireLabel(liveSession.value),
}),
},
state,
] as const;
});
if (!outcome.live) {
return;
}
yield* registerTerminalProcesses({
threadId: session.threadId,
terminalId: session.terminalId,
processIds: next.processIds,
});
const event = outcome.event;
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 entry of runningSessions) {
const next = inspections.get(entry.pid);
if (next === undefined) {
continue;
}
yield* applySubprocessActivity(entry, next);
}
});
const hasRunningSessions = readManagerState.pipe(
@@ -2144,6 +2141,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),
+98
View File
@@ -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,101 @@ 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("drops a plain crash leftover instead of aging it next to its gz copy", () => {
const directory = makeTempDirectory();
const filePath = NodePath.join(directory, "log.ndjson");
// Crash window: gz published but the plain source was never unlinked.
NodeFS.writeFileSync(`${filePath}.1`, "duplicated-entry");
NodeFS.writeFileSync(`${filePath}.1.gz`, NodeZlib.gzipSync("duplicated-entry"));
NodeFS.writeFileSync(filePath, "current-entry");
const sink = new RotatingFileSink({
filePath,
maxBytes: 8,
maxFiles: 2,
compressBackups: true,
throwOnError: true,
});
sink.write("next-entry");
expect(NodeZlib.gunzipSync(NodeFS.readFileSync(`${filePath}.2.gz`)).toString("utf8")).toBe(
"duplicated-entry",
);
expect(NodeFS.existsSync(`${filePath}.2`)).toBe(false);
expect(NodeZlib.gunzipSync(NodeFS.readFileSync(`${filePath}.1.gz`)).toString("utf8")).toBe(
"current-entry",
);
expect(NodeFS.existsSync(`${filePath}.1`)).toBe(false);
});
it("prunes orphaned gz tmp files from interrupted compressions", () => {
const directory = makeTempDirectory();
const filePath = NodePath.join(directory, "log.ndjson");
const orphan = `${filePath}.1.gz.tmp`;
NodeFS.writeFileSync(orphan, "partial");
void new RotatingFileSink({ filePath, maxBytes: 8, maxFiles: 2, compressBackups: true });
expect(NodeFS.existsSync(orphan)).toBe(false);
});
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);
});
});
+51 -9
View File
@@ -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,43 @@ 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. When both variants exist at
// one index, the plain file is a leftover from a crash between the gz
// publish and the plain unlink below — the gz copy holds the same
// content, so the duplicate is dropped instead of aged.
for (let index = this.maxFiles - 1; index >= 1; index -= 1) {
const compressedSource = this.withSuffix(index, "gz");
const source = this.withSuffix(index);
const target = this.withSuffix(index + 1);
if (NodeFS.existsSync(source)) {
NodeFS.renameSync(source, target);
if (NodeFS.existsSync(compressedSource)) {
NodeFS.renameSync(compressedSource, this.withSuffix(index + 1, "gz"));
NodeFS.rmSync(source, { force: true });
} else if (NodeFS.existsSync(source)) {
NodeFS.renameSync(source, this.withSuffix(index + 1));
}
}
if (NodeFS.existsSync(this.filePath)) {
// Rename first so the live file is moved atomically and never coexists
// with a compressed copy of itself; the gz lands via a tmp file +
// rename so a partial write can't publish a corrupt backup.
NodeFS.renameSync(this.filePath, this.withSuffix(1));
if (this.compressBackups) {
const compressed = this.withSuffix(1, "gz");
const temporary = `${compressed}.tmp`;
NodeFS.writeFileSync(
temporary,
NodeZlib.gzipSync(NodeFS.readFileSync(this.withSuffix(1))),
);
NodeFS.renameSync(temporary, compressed);
NodeFS.rmSync(this.withSuffix(1), { force: true });
}
}
this.currentSize = 0;
@@ -146,7 +178,15 @@ 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);
// An orphaned .gz.tmp is a compression interrupted mid-write.
if (rawSuffix.endsWith(".gz.tmp")) {
NodeFS.rmSync(NodePath.join(dir, entry), { force: true });
continue;
}
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 +216,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}`;
}
}
+44
View File
@@ -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)),
),
);
});
+79 -2
View File
@@ -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));
}
}
@@ -512,6 +584,9 @@ export const makeLocalFileTracer = Effect.fn("makeLocalFileTracer")(function* (
maxFiles: options.maxFiles,
batchWindowMs: options.batchWindowMs,
...(options.onFlush ? { onFlush: options.onFlush } : {}),
...(options.compressBackups !== undefined
? { compressBackups: options.compressBackups }
: {}),
}));
const delegate =
@@ -520,9 +595,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 } : {}),
});