diff --git a/apps/server/src/cli/config.test.ts b/apps/server/src/cli/config.test.ts index def63b61fa..1683ea0a5a 100644 --- a/apps/server/src/cli/config.test.ts +++ b/apps/server/src/cli/config.test.ts @@ -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, diff --git a/apps/server/src/diagnostics/TraceDiagnostics.ts b/apps/server/src/diagnostics/TraceDiagnostics.ts index 022794a7bf..ba5a17169a 100644 --- a/apps/server/src/diagnostics/TraceDiagnostics.ts +++ b/apps/server/src/diagnostics/TraceDiagnostics.ts @@ -472,7 +472,13 @@ export const make = Effect.gen(function* () { const aggregator = createTraceDiagnosticsAggregator(slowSpanThresholdMs); let loadedFileCount = 0; let readFailureError: TraceDiagnosticsErrorSummary | undefined; + const loadedPaths = new Set(); 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( @@ -494,6 +500,7 @@ export const make = Effect.gen(function* () { } if (result.success._tag === "Loaded") { loadedFileCount += 1; + loadedPaths.add(path); aggregator.addFileText(result.success.text); } } diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index d9d79cde15..46773043a3 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -90,15 +90,28 @@ 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}`; + return `Failed to inspect terminal subprocesses for PID ${this.terminalPid} with ${this.command}`; + } +} + +// 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", + { + 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}`; } } @@ -637,11 +650,11 @@ export function processTableFromRows( return { commandByPid, childrenByParent }; } -const PROCESS_TABLE_MAX_OUTPUT_BYTES = 1_048_576; +const PROCESS_TABLE_MAX_OUTPUT_BYTES = 4 * 1_048_576; function captureWindowsProcessTable(): Effect.Effect< ProcessTableSnapshot, - TerminalSubprocessCheckError, + TerminalProcessTableCaptureError, ProcessRunner.ProcessRunner > { const command = @@ -662,12 +675,19 @@ function captureWindowsProcessTable(): Effect.Effect< }) .pipe( Effect.mapError( - (cause) => - new TerminalSubprocessCheckError({ cause, terminalPid: 0, command: "powershell" }), + (cause) => new TerminalProcessTableCaptureError({ cause, command: "powershell" }), ), ); if (result.code !== 0) { - return yield* new TerminalSubprocessCheckError({ terminalPid: 0, command: "powershell" }); + 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 = []; for (const line of result.stdout.split(/\r?\n/g)) { @@ -683,7 +703,7 @@ function captureWindowsProcessTable(): Effect.Effect< function capturePosixProcessTable(): Effect.Effect< ProcessTableSnapshot, - TerminalSubprocessCheckError, + TerminalProcessTableCaptureError, ProcessRunner.ProcessRunner > { return Effect.gen(function* () { @@ -698,12 +718,13 @@ function capturePosixProcessTable(): Effect.Effect< timeoutBehavior: "timedOutResult", }) .pipe( - Effect.mapError( - (cause) => new TerminalSubprocessCheckError({ cause, terminalPid: 0, command: "ps" }), - ), + Effect.mapError((cause) => new TerminalProcessTableCaptureError({ cause, command: "ps" })), ); if (result.code !== 0) { - return yield* new TerminalSubprocessCheckError({ terminalPid: 0, command: "ps" }); + return yield* new TerminalProcessTableCaptureError({ command: "ps" }); + } + if (result.stdoutTruncated) { + return yield* new TerminalProcessTableCaptureError({ command: "ps", truncated: true }); } const rows: Array = []; for (const line of result.stdout.split(/\r?\n/g)) { @@ -719,7 +740,11 @@ function capturePosixProcessTable(): Effect.Effect< function captureProcessTableSnapshot( platform: NodeJS.Platform, -): Effect.Effect { +): Effect.Effect< + ProcessTableSnapshot, + TerminalProcessTableCaptureError, + ProcessRunner.ProcessRunner +> { return platform === "win32" ? captureWindowsProcessTable() : capturePosixProcessTable(); } @@ -1952,25 +1977,33 @@ 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* ( - sessions: ReadonlyArray, + entries: ReadonlyArray, ) { const results = new Map(); if (subprocessInspector !== null) { - for (const session of sessions) { - const inspectResult = yield* subprocessInspector(session.pid).pipe( + 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: session.pid, + terminalPid: pid, reason, }).pipe(Effect.as(Option.none())), ), ); if (Option.isSome(inspectResult)) { - results.set(session.pid, inspectResult.value); + results.set(pid, inspectResult.value); } } return results; @@ -1990,21 +2023,20 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func if (Option.isNone(snapshot)) { return results; } - for (const session of sessions) { - results.set( - session.pid, - inspectSubprocessFromSnapshot(session.pid, snapshot.value, platform), - ); + 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 = []; + 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; @@ -2013,10 +2045,9 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const inspections = yield* inspectRunningSubprocesses(runningSessions); const applySubprocessActivity = Effect.fn("terminal.applySubprocessActivity")(function* ( - session: TerminalSessionState & { pid: number }, + { session, pid: terminalPid }: RunningSessionPoll, next: TerminalSubprocessInspectResult, ) { - const terminalPid = session.pid; yield* registerTerminalProcesses({ threadId: session.threadId, terminalId: session.terminalId, @@ -2071,12 +2102,12 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func } }); - for (const session of runningSessions) { - const next = inspections.get(session.pid); + for (const entry of runningSessions) { + const next = inspections.get(entry.pid); if (next === undefined) { continue; } - yield* applySubprocessActivity(session, next); + yield* applySubprocessActivity(entry, next); } }); diff --git a/packages/shared/src/logging.test.ts b/packages/shared/src/logging.test.ts index 2d81af85be..502c322a60 100644 --- a/packages/shared/src/logging.test.ts +++ b/packages/shared/src/logging.test.ts @@ -217,6 +217,44 @@ describe("RotatingFileSink", () => { 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"); diff --git a/packages/shared/src/logging.ts b/packages/shared/src/logging.ts index 58f02fdcdb..1b3699b286 100644 --- a/packages/shared/src/logging.ts +++ b/packages/shared/src/logging.ts @@ -127,27 +127,35 @@ export class RotatingFileSink { } // Backups written before compressBackups was enabled keep their plain - // suffix and age along the chain unchanged. + // 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); if (NodeFS.existsSync(compressedSource)) { NodeFS.renameSync(compressedSource, this.withSuffix(index + 1, "gz")); - } - const source = this.withSuffix(index); - if (NodeFS.existsSync(source)) { + 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( - this.withSuffix(1, "gz"), - NodeZlib.gzipSync(NodeFS.readFileSync(this.filePath)), + temporary, + NodeZlib.gzipSync(NodeFS.readFileSync(this.withSuffix(1))), ); - NodeFS.rmSync(this.filePath, { force: true }); - } else { - NodeFS.renameSync(this.filePath, this.withSuffix(1)); + NodeFS.renameSync(temporary, compressed); + NodeFS.rmSync(this.withSuffix(1), { force: true }); } } @@ -171,6 +179,11 @@ export class RotatingFileSink { for (const entry of NodeFS.readdirSync(dir)) { if (!entry.startsWith(`${baseName}.`)) continue; 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, ); diff --git a/packages/shared/src/observability.ts b/packages/shared/src/observability.ts index 93754ca33f..5c518876f3 100644 --- a/packages/shared/src/observability.ts +++ b/packages/shared/src/observability.ts @@ -584,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 =