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]>
This commit is contained in:
Theo BrowneandClaude Fable 5 committed 2026-08-09 14:46:08 -07:00
1 parent 3cc7cf3c83
commit 04ae0412ef
6 files changed
+138 -45

No files matched your search

+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,
@@ -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<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(
@@ -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);
}
}
+66 -35
View File
@@ -90,15 +90,28 @@ class TerminalSubprocessCheckError extends Schema.TaggedErrorClass<TerminalSubpr
"TerminalSubprocessCheckError",
{
cause: Schema.optional(Schema.Defect()),
// 0 when a whole-table snapshot failed rather than a single terminal.
terminalPid: Schema.Number,
command: Schema.Literals(["powershell", "ps"]),
command: Schema.String,
},
) {
override get message(): string {
return this.terminalPid > 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>()(
"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<readonly [number, number, string]> = [];
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<readonly [number, number, string]> = [];
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<ProcessTableSnapshot, TerminalSubprocessCheckError, ProcessRunner.ProcessRunner> {
): 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<TerminalSessionState & { pid: number }>,
entries: ReadonlyArray<RunningSessionPoll>,
) {
const results = new Map<number, TerminalSubprocessInspectResult>();
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<TerminalSubprocessInspectResult>())),
),
);
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<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;
@@ -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);
}
});
+38
View File
@@ -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");
+22 -9
View File
@@ -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,
);
+3
View File
@@ -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 =