feat: add native resource telemetry

Replace scheduled process shell probes with a persistent native collector, Electron power/process telemetry, Effect services, diagnostics UI, attribution, and release packaging.

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-17 13:34:50 -07:00
1 parent 79ad071184
commit dbd8a8e09c
62 files changed
+7749 -1965

No files matched your search

@@ -1,243 +1,132 @@
import { describe, expect, it } from "@effect/vitest";
import type {
DesktopHostTelemetrySnapshot,
ResourceMonitorSnapshotEvent,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
import * as NativeTelemetryClient from "../resourceTelemetry/NativeTelemetryClient.ts";
import * as ResourceAttribution from "../resourceTelemetry/ResourceAttribution.ts";
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
const encoder = new TextEncoder();
function makeNativeSnapshot(
processes: ResourceMonitorSnapshotEvent["processes"],
): ResourceMonitorSnapshotEvent {
return {
version: 1,
type: "snapshot",
sequence: 1,
sampledAtUnixMs: DateTime.toEpochMillis(DateTime.makeUnsafe("2026-05-05T10:00:00.000Z")),
collectionDurationMicros: 250,
scannedProcessCount: processes.length,
retainedProcessCount: processes.length,
inaccessibleProcessCount: 0,
processes,
};
}
function mockHandle(result: {
readonly stdout?: string;
readonly stderr?: string;
readonly code?: number;
}) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.make(encoder.encode(result.stdout ?? "")),
stderr: Stream.make(encoder.encode(result.stderr ?? "")),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
function makeTelemetryLayer(
snapshot: ResourceMonitorSnapshotEvent,
desktopSnapshot?: DesktopHostTelemetrySnapshot,
) {
const nativeLayer = NativeTelemetryClient.layerTest({
sampleNow: Effect.succeed(snapshot),
health: Effect.succeed({
status: "healthy",
hello: Option.none(),
lastSampleAt: Option.some(DateTime.makeUnsafe(snapshot.sampledAtUnixMs)),
lastError: Option.none(),
restartCount: 0,
}),
});
const desktopLayer = desktopSnapshot
? DesktopTelemetryReceiver.layerTest({
latest: Effect.succeedSome(desktopSnapshot),
health: Effect.succeed({
status: "healthy",
lastSampleAt: Option.some(DateTime.makeUnsafe(desktopSnapshot.sampledAtUnixMs)),
lastError: Option.none(),
}),
})
: DesktopTelemetryReceiver.layerTest();
return ResourceTelemetry.layer.pipe(
Layer.provide(Layer.mergeAll(nativeLayer, desktopLayer, ResourceAttribution.layer)),
);
}
describe("ProcessDiagnostics", () => {
it.effect("parses POSIX ps rows with full commands", () =>
Effect.sync(() => {
const rows = ProcessDiagnostics.parsePosixProcessRows(
[
" 10 1 10 Ss 0.0 1024 01:02.03 /usr/bin/node server.js",
" 11 10 10 S+ 12.5 20480 00:04 codex app-server --config /tmp/one two",
].join("\n"),
);
expect(rows).toEqual([
it.effect("projects live process data from resource telemetry", () =>
Effect.gen(function* () {
const snapshot = makeNativeSnapshot([
{
pid: 10,
pid: process.pid,
ppid: 1,
pgid: 10,
status: "Ss",
startTimeMs: 1_000,
runTimeMs: 60_000,
name: "node",
command: "t3 server",
status: "Running",
cpuPercent: 0,
rssBytes: 1024 * 1024,
elapsed: "01:02.03",
command: "/usr/bin/node server.js",
cpuTimeMs: 100,
residentBytes: 1_024,
virtualBytes: 2_048,
ioReadBytes: 100,
ioWriteBytes: 200,
ioSemantics: "storage",
},
{
pid: 11,
ppid: 10,
pgid: 10,
status: "S+",
cpuPercent: 12.5,
rssBytes: 20480 * 1024,
elapsed: "00:04",
command: "codex app-server --config /tmp/one two",
pid: 4_242,
ppid: process.pid,
startTimeMs: 2_000,
runTimeMs: 4_000,
name: "agent",
command: "codex app-server",
status: "Running",
cpuPercent: 1.5,
cpuTimeMs: 60,
residentBytes: 2_048,
virtualBytes: 4_096,
ioReadBytes: 300,
ioWriteBytes: 400,
ioSemantics: "storage",
},
]);
}),
);
const telemetryLayer = makeTelemetryLayer(snapshot);
const layer = ProcessDiagnostics.layer.pipe(Layer.provideMerge(telemetryLayer));
it.effect("aggregates only descendants of the server process", () =>
Effect.sync(() => {
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
serverPid: 100,
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 0,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
{
pid: 101,
ppid: 100,
pgid: 100,
status: "S",
cpuPercent: 1.5,
rssBytes: 2_000,
elapsed: "00:20",
command: "codex app-server",
},
{
pid: 102,
ppid: 101,
pgid: 100,
status: "R",
cpuPercent: 3.25,
rssBytes: 4_000,
elapsed: "00:05",
command: "git status",
},
{
pid: 200,
ppid: 1,
pgid: 200,
status: "S",
cpuPercent: 99,
rssBytes: 8_000,
elapsed: "00:01",
command: "unrelated",
},
{
pid: 201,
ppid: 100,
pgid: 100,
status: "R",
cpuPercent: 9,
rssBytes: 9_000,
elapsed: "00:00",
command: "ps -axo pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=",
},
],
});
expect(diagnostics.serverPid).toBe(100);
expect(DateTime.formatIso(diagnostics.readAt)).toBe("2026-05-05T10:00:00.000Z");
expect(diagnostics.processCount).toBe(2);
expect(diagnostics.totalRssBytes).toBe(6_000);
expect(diagnostics.totalCpuPercent).toBe(4.75);
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102]);
expect(diagnostics.processes.map((process) => process.depth)).toEqual([0, 1]);
expect(Option.getOrNull(diagnostics.processes[0]!.pgid)).toBe(100);
expect(diagnostics.processes[0]?.childPids).toEqual([102]);
}),
);
it.effect("preserves ascending sibling order for nested descendants", () =>
Effect.sync(() => {
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
serverPid: 100,
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
rows: [
{
pid: 101,
ppid: 100,
pgid: 100,
status: "S",
cpuPercent: 0,
rssBytes: 100,
elapsed: "00:10",
command: "agent",
},
{
pid: 103,
ppid: 101,
pgid: 100,
status: "S",
cpuPercent: 0,
rssBytes: 100,
elapsed: "00:10",
command: "child-b",
},
{
pid: 102,
ppid: 101,
pgid: 100,
status: "S",
cpuPercent: 0,
rssBytes: 100,
elapsed: "00:10",
command: "child-a",
},
],
});
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102, 103]);
}),
);
it.effect("queries processes through the ChildProcessSpawner service", () =>
Effect.gen(function* () {
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
[];
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const childProcess = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
};
commands.push({ command: childProcess.command, args: childProcess.args });
return Effect.succeed(
mockHandle({
stdout: [
` ${process.pid} 1 ${process.pid} Ss 0.0 1024 01:02.03 t3 server`,
` 4242 ${process.pid} ${process.pid} S 1.5 2048 00:04 agent`,
].join("\n"),
}),
);
}),
);
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
const diagnostics = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
Effect.flatMap((pd) => pd.read),
Effect.provide(layer),
);
const diagnostics = yield* Effect.gen(function* () {
const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics;
yield* telemetry.refresh;
return yield* processDiagnostics.read;
}).pipe(Effect.provide(layer));
expect(diagnostics.processes.map((process) => process.pid)).toEqual([4242]);
expect(commands).toEqual([
{
command: "ps",
args: ["-axo", "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command="],
},
]);
expect(diagnostics.processes[0]?.startTimeMs).toBe(2_000);
expect(diagnostics.processes[0]?.cpuPercent).toBe(1.5);
expect(diagnostics.processes[0]?.rssBytes).toBe(2_048);
}),
);
it.effect("does not allow signaling the diagnostics query process", () =>
it.effect("rejects stale process identities before signaling", () =>
Effect.gen(function* () {
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
mockHandle({
stdout: [
` ${process.pid} 1 ${process.pid} Ss 0.0 1024 01:02.03 t3 server`,
` 4242 ${process.pid} ${process.pid} R 1.5 2048 00:00 ps -axo pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=`,
].join("\n"),
}),
),
),
);
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
const snapshot = makeNativeSnapshot([]);
const telemetryLayer = makeTelemetryLayer(snapshot);
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(telemetryLayer));
const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
Effect.flatMap((pd) => pd.signal({ pid: 4242, signal: "SIGINT" })),
Effect.flatMap((processDiagnostics) =>
processDiagnostics.signal({
pid: 4_242,
startTimeMs: 2_000,
signal: "SIGINT",
}),
),
Effect.provide(layer),
);
@@ -245,7 +134,84 @@ describe("ProcessDiagnostics", () => {
pid: 4242,
signal: "SIGINT",
signaled: false,
message: Option.some("Process 4242 is not a live descendant of the T3 server."),
message: Option.some("Process 4242 no longer matches the selected process identity."),
});
}),
);
it.effect("rejects Electron processes as signal targets", () =>
Effect.gen(function* () {
const sampledAtUnixMs = DateTime.toEpochMillis(
DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
);
const snapshot = makeNativeSnapshot([
{
pid: 4_242,
ppid: 1,
startTimeMs: 2_000,
runTimeMs: 4_000,
name: "electron",
command: "electron",
status: "Running",
cpuPercent: 1.5,
cpuTimeMs: 60,
residentBytes: 2_048,
virtualBytes: 4_096,
ioReadBytes: 300,
ioWriteBytes: 400,
ioSemantics: "storage",
},
]);
const sampledAt = DateTime.makeUnsafe(sampledAtUnixMs);
const telemetryLayer = makeTelemetryLayer(snapshot, {
version: 1,
type: "desktopTelemetry",
sequence: 1,
sampledAtUnixMs,
power: {
source: "electron-main",
idle: "false",
idleSeconds: 0,
locked: "false",
suspended: false,
onBattery: "false",
lowPowerMode: "unknown",
thermalState: "nominal",
stale: false,
updatedAt: sampledAt,
},
speedLimitPercent: Option.none(),
electronProcesses: [
{
pid: 4_242,
creationTimeMs: 2_000,
type: "Browser",
name: "electron",
cpuPercent: 1.5,
idleWakeupsPerSecond: 0,
workingSetBytes: 2_048,
peakWorkingSetBytes: 2_048,
},
],
});
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(telemetryLayer));
const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
Effect.flatMap((processDiagnostics) =>
processDiagnostics.signal({
pid: 4_242,
startTimeMs: 2_000,
signal: "SIGKILL",
}),
),
Effect.provide(layer),
);
expect(result).toEqual({
pid: 4_242,
signal: "SIGKILL",
signaled: false,
message: Option.some("Process 4242 is not a signalable T3 backend descendant."),
});
}),
);
+139 -415
View File
@@ -1,40 +1,23 @@
import type {
ResourceTelemetryProcessCategory,
ServerProcessDiagnosticsEntry,
ServerProcessDiagnosticsResult,
ServerProcessSignal,
ServerSignalProcessResult,
} from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
export interface ProcessRow {
readonly pid: number;
readonly ppid: number;
readonly pgid: number | null;
readonly status: string;
readonly cpuPercent: number;
readonly rssBytes: number;
readonly elapsed: string;
readonly command: string;
}
const PROCESS_QUERY_TIMEOUT_MS = 1_000;
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
export interface ProcessDiagnosticsShape {
readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
readonly signal: (input: {
readonly pid: number;
readonly startTimeMs: number;
readonly signal: ServerProcessSignal;
}) => Effect.Effect<ServerSignalProcessResult>;
}
@@ -44,420 +27,161 @@ export class ProcessDiagnostics extends Context.Service<
ProcessDiagnosticsShape
>()("t3/diagnostics/ProcessDiagnostics") {}
class ProcessDiagnosticsError extends Schema.TaggedErrorClass<ProcessDiagnosticsError>()(
"ProcessDiagnosticsError",
export class ProcessIdentityChanged extends Schema.TaggedErrorClass<ProcessIdentityChanged>()(
"ProcessIdentityChanged",
{
message: Schema.String,
cause: Schema.optional(Schema.Defect()),
pid: Schema.Number,
startTimeMs: Schema.Number,
},
) {}
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
function toProcessDiagnosticsError(message: string, cause?: unknown): ProcessDiagnosticsError {
return new ProcessDiagnosticsError({
message,
...(cause === undefined ? {} : { cause }),
});
}
function parsePositiveInt(value: string): number | null {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
}
function parseNonNegativeInt(value: string): number | null {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
}
function parseNumber(value: string): number | null {
const parsed = Number.parseFloat(value);
return Number.isFinite(parsed) ? parsed : null;
}
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
const rows: ProcessRow[] = [];
const rowPattern =
/^\s*(\d+)\s+(\d+)\s+(-?\d+)\s+(\S+)\s+([+-]?(?:\d+\.?\d*|\.\d+))\s+(\d+)\s+(\S+)\s+(.+)$/;
for (const line of output.split(/\r?\n/)) {
if (line.trim().length === 0) continue;
const match = rowPattern.exec(line);
if (!match) continue;
const pidText = match[1];
const ppidText = match[2];
const pgidText = match[3];
const status = match[4];
const cpuText = match[5];
const rssText = match[6];
const elapsed = match[7];
const command = match[8];
if (
pidText === undefined ||
ppidText === undefined ||
pgidText === undefined ||
status === undefined ||
cpuText === undefined ||
rssText === undefined ||
elapsed === undefined ||
command === undefined
) {
continue;
}
const pid = parsePositiveInt(pidText);
const ppid = parseNonNegativeInt(ppidText);
const pgid = Number.parseInt(pgidText, 10);
const cpuPercent = parseNumber(cpuText);
const rssKiB = parseNonNegativeInt(rssText);
if (
pid === null ||
ppid === null ||
!Number.isInteger(pgid) ||
cpuPercent === null ||
rssKiB === null ||
!status ||
!elapsed ||
!command
) {
continue;
}
rows.push({
pid,
ppid,
pgid,
status,
cpuPercent,
rssBytes: rssKiB * 1024,
elapsed,
command,
});
}
return rows;
}
function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
if (typeof value !== "object" || value === null) return null;
const record = value as Record<string, unknown>;
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
const commandLine =
typeof record.CommandLine === "string" && record.CommandLine.trim().length > 0
? record.CommandLine
: typeof record.Name === "string"
? record.Name
: null;
const workingSet =
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
? Math.max(0, Math.round(record.WorkingSetSize))
: 0;
const cpuPercent =
typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
? Math.max(0, record.PercentProcessorTime)
: 0;
if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
return {
pid,
ppid,
pgid: null,
status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
cpuPercent,
rssBytes: workingSet,
elapsed: "",
command: commandLine,
};
}
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
if (output.trim().length === 0) return [];
try {
const parsed = JSON.parse(output) as unknown;
const records = Array.isArray(parsed) ? parsed : [parsed];
return records.flatMap((record) => {
const row = normalizeWindowsProcessRow(record);
return row ? [row] : [];
});
} catch {
return [];
) {
override get message(): string {
return `Process ${this.pid} no longer matches start time ${this.startTimeMs}.`;
}
}
export function buildDescendantEntries(
rows: ReadonlyArray<ProcessRow>,
serverPid: number,
): ReadonlyArray<ServerProcessDiagnosticsEntry> {
const childrenByParent = new Map<number, ProcessRow[]>();
for (const row of rows) {
const children = childrenByParent.get(row.ppid) ?? [];
children.push(row);
childrenByParent.set(row.ppid, children);
export class ProcessSignalFailed extends Schema.TaggedErrorClass<ProcessSignalFailed>()(
"ProcessSignalFailed",
{
pid: Schema.Number,
signal: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to signal process ${this.pid} with ${this.signal}.`;
}
const entries: ServerProcessDiagnosticsEntry[] = [];
const visited = new Set<number>();
const stack = [...(childrenByParent.get(serverPid) ?? [])]
.toSorted((left, right) => left.pid - right.pid)
.map((row) => ({ row, depth: 0 }));
while (stack.length > 0) {
const item = stack.shift();
if (!item || visited.has(item.row.pid)) continue;
visited.add(item.row.pid);
const children = [...(childrenByParent.get(item.row.pid) ?? [])].toSorted(
(left, right) => left.pid - right.pid,
);
entries.push({
pid: item.row.pid,
ppid: item.row.ppid,
pgid: Option.fromNullishOr(item.row.pgid),
status: item.row.status,
cpuPercent: item.row.cpuPercent,
rssBytes: item.row.rssBytes,
elapsed: item.row.elapsed || "n/a",
command: item.row.command,
depth: item.depth,
childPids: children.map((child) => child.pid),
});
stack.unshift(...children.map((row) => ({ row, depth: item.depth + 1 })));
}
return entries;
}
export function isDiagnosticsQueryProcess(row: ProcessRow, serverPid: number): boolean {
if (row.ppid !== serverPid) return false;
export type ProcessDiagnosticsError = ProcessIdentityChanged | ProcessSignalFailed;
const command = row.command.trim();
function formatElapsed(runTimeMs: number): string {
const totalSeconds = Math.max(0, Math.floor(runTimeMs / 1_000));
const hours = Math.floor(totalSeconds / 3_600);
const minutes = Math.floor((totalSeconds % 3_600) / 60);
const seconds = totalSeconds % 60;
return hours > 0
? `${hours}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`
: `${minutes}:${String(seconds).padStart(2, "0")}`;
}
function canSignalCategory(category: ResourceTelemetryProcessCategory): boolean {
return (
/(?:^|[/\\])ps\s+-axo\s+pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=/.test(command) ||
(/\bpowershell(?:\.exe)?\b/i.test(command) &&
/\bGet-CimInstance\s+Win32_Process\b/i.test(command))
);
}
function makeResult(input: {
readonly serverPid: number;
readonly rows: ReadonlyArray<ProcessRow>;
readonly readAt: DateTime.Utc;
readonly error?: string;
}): ServerProcessDiagnosticsResult {
const readAt = input.readAt;
const rows = input.rows.filter((row) => !isDiagnosticsQueryProcess(row, input.serverPid));
const processes = buildDescendantEntries(rows, input.serverPid);
const totalRssBytes = processes.reduce((total, process) => total + process.rssBytes, 0);
const totalCpuPercent = processes.reduce((total, process) => total + process.cpuPercent, 0);
return {
serverPid: input.serverPid,
readAt,
processCount: processes.length,
totalRssBytes,
totalCpuPercent,
processes,
error: input.error ? Option.some({ message: input.error }) : Option.none(),
};
}
interface ProcessOutput {
readonly exitCode: number;
readonly stdout: string;
readonly stderr: string;
}
const runProcess = Effect.fn("runProcess")(
function* (input: {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly errorMessage: string;
}) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
// `ps` and `powershell.exe` are real executables; spawning through cmd.exe
// shell mode would re-tokenize the PowerShell `-Command` payload (which
// contains pipes) before PowerShell ever sees it.
const child = yield* spawner.spawn(
ChildProcess.make(input.command, input.args, {
cwd: process.cwd(),
}),
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectUint8StreamText({
stream: child.stdout,
maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
truncatedMarker: "\n\n[truncated]",
}),
collectUint8StreamText({
stream: child.stderr,
maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
truncatedMarker: "\n\n[truncated]",
}),
child.exitCode,
],
{ concurrency: "unbounded" },
);
return {
exitCode,
stdout: stdout.text,
stderr: stderr.text,
} satisfies ProcessOutput;
},
(effect, input) =>
effect.pipe(
Effect.scoped,
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () => Effect.fail(toProcessDiagnosticsError(`${input.errorMessage} timed out.`)),
onSome: Effect.succeed,
}),
),
Effect.mapError((cause) =>
isProcessDiagnosticsError(cause)
? cause
: toProcessDiagnosticsError(input.errorMessage, cause),
),
),
);
function readPosixProcessRows(): Effect.Effect<
ReadonlyArray<ProcessRow>,
ProcessDiagnosticsError,
ChildProcessSpawner.ChildProcessSpawner
> {
return runProcess({
command: "ps",
args: ["-axo", POSIX_PROCESS_QUERY_COMMAND],
errorMessage: "Failed to query process diagnostics.",
}).pipe(
Effect.flatMap((result) =>
result.exitCode !== 0
? Effect.fail(toProcessDiagnosticsError(result.stderr.trim() || "ps failed."))
: Effect.succeed(parsePosixProcessRows(result.stdout)),
),
);
}
function readWindowsProcessRows(): Effect.Effect<
ReadonlyArray<ProcessRow>,
ProcessDiagnosticsError,
ChildProcessSpawner.ChildProcessSpawner
> {
const command = [
"$processes = Get-CimInstance Win32_Process | ForEach-Object {",
'$perf = Get-CimInstance Win32_PerfFormattedData_PerfProc_Process -Filter "IDProcess = $($_.ProcessId)" -ErrorAction SilentlyContinue;',
"[pscustomobject]@{ ProcessId = $_.ProcessId; ParentProcessId = $_.ParentProcessId; Name = $_.Name; CommandLine = $_.CommandLine; Status = $_.Status; WorkingSetSize = $_.WorkingSetSize; PercentProcessorTime = if ($perf) { $perf.PercentProcessorTime } else { 0 } }",
"};",
"$processes | ConvertTo-Json -Compress -Depth 3",
].join(" ");
return runProcess({
command: "powershell.exe",
args: ["-NoProfile", "-NonInteractive", "-Command", command],
errorMessage: "Failed to query process diagnostics.",
}).pipe(
Effect.flatMap((result) =>
result.exitCode !== 0
? Effect.fail(
toProcessDiagnosticsError(result.stderr.trim() || "PowerShell process query failed."),
)
: Effect.succeed(parseWindowsProcessRows(result.stdout)),
),
);
}
export const readProcessRows = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
return yield* platform === "win32" ? readWindowsProcessRows() : readPosixProcessRows();
});
export function aggregateProcessDiagnostics(input: {
readonly serverPid: number;
readonly rows: ReadonlyArray<ProcessRow>;
readonly readAt: DateTime.Utc;
}): ServerProcessDiagnosticsResult {
return makeResult(input);
}
function assertDescendantPid(
pid: number,
): Effect.Effect<void, ProcessDiagnosticsError, ChildProcessSpawner.ChildProcessSpawner> {
if (pid === process.pid) {
return Effect.fail(toProcessDiagnosticsError("Refusing to signal the T3 server process."));
}
return readProcessRows.pipe(
Effect.flatMap((rows) => {
const filteredRows = rows.filter((row) => !isDiagnosticsQueryProcess(row, process.pid));
const descendant = buildDescendantEntries(filteredRows, process.pid).some(
(entry) => entry.pid === pid,
);
return descendant
? Effect.void
: Effect.fail(
toProcessDiagnosticsError(`Process ${pid} is not a live descendant of the T3 server.`),
);
}),
category === "server-child" || category === "provider-root" || category === "terminal-root"
);
}
export const make = Effect.fn("makeProcessDiagnostics")(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const read: ProcessDiagnosticsShape["read"] = Effect.gen(function* () {
const readAt = yield* DateTime.now;
const rows = yield* readProcessRows.pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
return makeResult({ serverPid: process.pid, rows, readAt });
}).pipe(
Effect.catch((error: ProcessDiagnosticsError) =>
DateTime.now.pipe(
Effect.map((readAt) =>
makeResult({ serverPid: process.pid, rows: [], readAt, error: error.message }),
),
),
),
const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
const read: ProcessDiagnosticsShape["read"] = telemetry.latest.pipe(
Effect.map((snapshot) => {
const processes = snapshot.processes
.filter((entry) => entry.identity.pid !== process.pid)
.map(
(entry): ServerProcessDiagnosticsEntry => ({
pid: entry.identity.pid,
startTimeMs: entry.identity.startTimeMs,
ppid: entry.ppid,
pgid: Option.none(),
status: entry.status || "Unknown",
cpuPercent: entry.cpuPercent,
rssBytes: entry.residentBytes,
elapsed: formatElapsed(entry.runTimeMs),
command: entry.command || entry.name || "unknown",
depth: Math.max(0, entry.depth - 1),
childPids: entry.childPids,
}),
);
return {
serverPid: process.pid,
readAt: snapshot.readAt,
processCount: processes.length,
totalRssBytes: processes.reduce((total, entry) => total + entry.rssBytes, 0),
totalCpuPercent: processes.reduce((total, entry) => total + entry.cpuPercent, 0),
processes,
error: Option.map(snapshot.health.native.lastError, (message) => ({ message })),
};
}),
);
const signal: ProcessDiagnosticsShape["signal"] = Effect.fn("ProcessDiagnostics.signal")(
function* (input) {
return yield* assertDescendantPid(input.pid).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.flatMap(() =>
Effect.try({
try: () => {
process.kill(input.pid, input.signal);
return {
pid: input.pid,
signal: input.signal,
signaled: true,
message: Option.none(),
};
},
catch: (cause) =>
toProcessDiagnosticsError(
`Failed to signal process ${input.pid} with ${input.signal}.`,
cause,
),
}),
),
Effect.catch((error: ProcessDiagnosticsError) =>
Effect.succeed({
pid: input.pid,
signal: input.signal,
signaled: false,
message: Option.some(error.message),
}),
),
if (input.pid === process.pid) {
return {
pid: input.pid,
signal: input.signal,
signaled: false,
message: Option.some("Refusing to signal the T3 server process."),
};
}
const current = yield* telemetry.latest;
const selected = current.processes.find(
(entry) =>
entry.identity.pid === input.pid && entry.identity.startTimeMs === input.startTimeMs,
);
if (!selected) {
return {
pid: input.pid,
signal: input.signal,
signaled: false,
message: Option.some(
`Process ${input.pid} no longer matches the selected process identity.`,
),
};
}
if (!canSignalCategory(selected.category)) {
return {
pid: input.pid,
signal: input.signal,
signaled: false,
message: Option.some(`Process ${input.pid} is not a signalable T3 backend descendant.`),
};
}
return yield* telemetry
.validateProcessIdentity({
pid: input.pid,
startTimeMs: input.startTimeMs,
})
.pipe(
Effect.flatMap((valid) =>
valid
? Effect.void
: Effect.fail(
new ProcessIdentityChanged({
pid: input.pid,
startTimeMs: input.startTimeMs,
}),
),
),
Effect.flatMap(() =>
Effect.try({
try: () => {
process.kill(input.pid, input.signal);
return {
pid: input.pid,
signal: input.signal,
signaled: true,
message: Option.none(),
};
},
catch: (cause) =>
new ProcessSignalFailed({
pid: input.pid,
signal: input.signal,
cause,
}),
}),
),
Effect.catch((error) =>
Effect.succeed({
pid: input.pid,
signal: input.signal,
signaled: false,
message: Option.some(
error instanceof Error ? error.message : "Failed to signal process.",
),
}),
),
);
},
);
@@ -1,231 +1,132 @@
import { describe, expect, it } from "@effect/vitest";
import type { ResourceTelemetryHistory } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Stream from "effect/Stream";
import {
aggregateProcessResourceHistory,
collectMonitoredSamples,
} from "./ProcessResourceMonitor.ts";
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
import * as ProcessResourceMonitor from "./ProcessResourceMonitor.ts";
describe("ProcessResourceMonitor", () => {
it.effect("samples the server root process and descendants", () =>
Effect.sync(() => {
const sampledAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
const samples = collectMonitoredSamples({
serverPid: 100,
sampledAt,
sampledAtMs: DateTime.toEpochMillis(sampledAt),
rows: [
it.effect("projects resource telemetry history into the legacy diagnostics contract", () =>
Effect.gen(function* () {
const readAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
const history: ResourceTelemetryHistory = {
readAt,
windowMs: 60_000,
bucketMs: 10_000,
sampleIntervalMs: 1_000,
retainedSampleCount: 2,
buckets: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 2,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
{
pid: 101,
ppid: 100,
pgid: 100,
status: "S",
cpuPercent: 10,
rssBytes: 2_000,
elapsed: "00:20",
command: "codex app-server",
},
{
pid: 102,
ppid: 101,
pgid: 100,
status: "R",
cpuPercent: 50,
rssBytes: 3_000,
elapsed: "00:05",
command: "rg needle",
},
{
pid: 200,
ppid: 1,
pgid: 200,
status: "R",
cpuPercent: 99,
rssBytes: 9_000,
elapsed: "00:05",
command: "unrelated",
startedAt: DateTime.makeUnsafe("2026-05-05T09:59:50.000Z"),
endedAt: readAt,
avgCpuPercent: 15,
maxCpuPercent: 25,
maxRssBytes: 4_096,
ioReadBytes: 1_024,
ioWriteBytes: 2_048,
maxProcessCount: 2,
},
],
});
expect(samples.map((sample) => sample.pid)).toEqual([100, 101, 102]);
expect(samples.map((sample) => sample.depth)).toEqual([0, 1, 2]);
expect(samples[0]?.isServerRoot).toBe(true);
expect(samples[1]?.isServerRoot).toBe(false);
}),
);
it.effect("rolls samples up by process and CPU time", () =>
Effect.sync(() => {
const firstAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
const secondAt = DateTime.makeUnsafe("2026-05-05T10:00:05.000Z");
const samples = [
...collectMonitoredSamples({
serverPid: 100,
sampledAt: firstAt,
sampledAtMs: DateTime.toEpochMillis(firstAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 10,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
],
}),
...collectMonitoredSamples({
serverPid: 100,
sampledAt: secondAt,
sampledAtMs: DateTime.toEpochMillis(secondAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 30,
rssBytes: 2_000,
elapsed: "01:05",
command: "t3 server",
},
],
}),
];
const result = aggregateProcessResourceHistory({
samples,
readAt: secondAt,
readAtMs: DateTime.toEpochMillis(secondAt),
windowMs: 60_000,
bucketMs: 10_000,
lastError: null,
});
expect(Option.isNone(result.error)).toBe(true);
expect(result.topProcesses).toHaveLength(1);
expect(result.topProcesses[0]?.avgCpuPercent).toBe(20);
expect(result.topProcesses[0]?.maxCpuPercent).toBe(30);
expect(result.topProcesses[0]?.cpuSecondsApprox).toBe(2);
expect(result.totalCpuSecondsApprox).toBe(2);
expect(result.buckets.some((bucket) => bucket.maxCpuPercent === 30)).toBe(true);
}),
);
it.effect("keeps a process grouped when elapsed time drifts between samples", () =>
Effect.sync(() => {
const firstAt = DateTime.makeUnsafe("2026-05-05T10:00:00.400Z");
const secondAt = DateTime.makeUnsafe("2026-05-05T10:00:05.900Z");
const samples = [
...collectMonitoredSamples({
serverPid: 100,
sampledAt: firstAt,
sampledAtMs: DateTime.toEpochMillis(firstAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 1,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
],
}),
...collectMonitoredSamples({
serverPid: 100,
sampledAt: secondAt,
sampledAtMs: DateTime.toEpochMillis(secondAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 2,
rssBytes: 2_000,
elapsed: "01:06",
command: "t3 server",
},
],
}),
];
const result = aggregateProcessResourceHistory({
samples,
readAt: secondAt,
readAtMs: DateTime.toEpochMillis(secondAt),
windowMs: 60_000,
bucketMs: 10_000,
lastError: null,
});
expect(result.topProcesses).toHaveLength(1);
expect(result.topProcesses[0]?.isServerRoot).toBe(true);
expect(result.topProcesses[0]?.sampleCount).toBe(2);
expect(result.topProcesses[0]?.maxRssBytes).toBe(2_000);
}),
);
it.effect("returns all process summaries in the selected window", () =>
Effect.sync(() => {
const sampledAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
const samples = collectMonitoredSamples({
serverPid: 100,
sampledAt,
sampledAtMs: DateTime.toEpochMillis(sampledAt),
rows: [
topProcesses: [
{
pid: 100,
identity: { pid: process.pid, startTimeMs: 100 },
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 1,
rssBytes: 1_000,
elapsed: "01:00",
depth: 0,
name: "node",
command: "t3 server",
category: "server",
firstSeenAt: DateTime.makeUnsafe("2026-05-05T09:59:55.000Z"),
lastSeenAt: readAt,
currentCpuPercent: 5,
avgCpuPercent: 4,
maxCpuPercent: 8,
cpuTimeMs: 1_500,
currentRssBytes: 2_048,
peakRssBytes: 4_096,
ioReadBytes: 1_024,
ioWriteBytes: 2_048,
ioSemantics: "storage",
sampleCount: 2,
},
...Array.from({ length: 35 }, (_, index) => ({
pid: 200 + index,
ppid: index === 0 ? 100 : 199 + index,
pgid: 100,
status: "S",
cpuPercent: 35 - index,
rssBytes: 2_000 + index,
elapsed: "00:10",
command: `worker ${index}`,
})),
],
});
health: {
native: {
status: "degraded",
lastSampleAt: Option.some(readAt),
lastError: Option.some("collector stalled"),
},
desktop: {
status: "healthy",
lastSampleAt: Option.some(readAt),
lastError: Option.none(),
},
sidecarVersion: Option.some("0.1.0"),
sidecarPid: Option.some(9_000),
restartCount: 1,
collectionDurationMicros: 250,
scannedProcessCount: 80,
retainedProcessCount: 2,
inaccessibleProcessCount: 0,
},
};
const telemetry: ResourceTelemetry.ResourceTelemetryShape = {
latest: Effect.die("unused"),
changes: Stream.empty,
readHistory: () => Effect.succeed(history),
refresh: Effect.die("unused"),
validateProcessIdentity: () => Effect.die("unused"),
retry: Effect.die("unused"),
};
const layer = ProcessResourceMonitor.layer.pipe(
Layer.provide(
Layer.succeed(
ResourceTelemetry.ResourceTelemetry,
ResourceTelemetry.ResourceTelemetry.of(telemetry),
),
),
);
const result = aggregateProcessResourceHistory({
samples,
readAt: sampledAt,
readAtMs: DateTime.toEpochMillis(sampledAt),
windowMs: 60_000,
bucketMs: 10_000,
lastError: null,
});
const result = yield* Effect.service(ProcessResourceMonitor.ProcessResourceMonitor).pipe(
Effect.flatMap((monitor) =>
monitor.readHistory({
windowMs: 60_000,
bucketMs: 10_000,
}),
),
Effect.provide(layer),
);
expect(result.topProcesses).toHaveLength(36);
expect(result.topProcesses.some((process) => process.command === "worker 34")).toBe(true);
expect(result.totalCpuSecondsApprox).toBe(1.5);
expect(result.topProcesses).toEqual([
{
processKey: `${process.pid}:100`,
pid: process.pid,
ppid: 1,
command: "t3 server",
depth: 0,
isServerRoot: true,
firstSeenAt: DateTime.makeUnsafe("2026-05-05T09:59:55.000Z"),
lastSeenAt: readAt,
currentCpuPercent: 5,
avgCpuPercent: 4,
maxCpuPercent: 8,
cpuSecondsApprox: 1.5,
currentRssBytes: 2_048,
maxRssBytes: 4_096,
sampleCount: 2,
},
]);
expect(result.buckets[0]).toMatchObject({
avgCpuPercent: 15,
maxCpuPercent: 25,
maxRssBytes: 4_096,
maxProcessCount: 2,
});
expect(result.error).toEqual(Option.some({ message: "collector stalled" }));
}),
);
});
@@ -1,45 +1,13 @@
import type {
ServerProcessResourceHistoryBucket,
ServerProcessResourceHistoryInput,
ServerProcessResourceHistoryResult,
ServerProcessResourceHistorySummary,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
buildDescendantEntries,
isDiagnosticsQueryProcess,
type ProcessRow,
readProcessRows,
} from "./ProcessDiagnostics.ts";
const SAMPLE_INTERVAL_MS = 5_000;
const RETENTION_MS = 60 * 60_000;
const MAX_RETAINED_SAMPLES = 20_000;
export interface ProcessResourceSample {
readonly sampledAt: DateTime.Utc;
readonly sampledAtMs: number;
readonly processKey: string;
readonly pid: number;
readonly ppid: number;
readonly command: string;
readonly cpuPercent: number;
readonly rssBytes: number;
readonly depth: number;
readonly isServerRoot: boolean;
}
interface MonitorState {
readonly samples: ReadonlyArray<ProcessResourceSample>;
readonly lastError: string | null;
}
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
export interface ProcessResourceMonitorShape {
readonly readHistory: (
@@ -52,246 +20,51 @@ export class ProcessResourceMonitor extends Context.Service<
ProcessResourceMonitorShape
>()("t3/diagnostics/ProcessResourceMonitor") {}
function dateTimeFromMillis(ms: number): DateTime.Utc {
return DateTime.makeUnsafe(ms);
}
function sampleKey(row: Pick<ProcessRow, "pid" | "command">): string {
return `${row.pid}:${row.command}`;
}
function findServerRootRow(rows: ReadonlyArray<ProcessRow>, serverPid: number): ProcessRow | null {
return rows.find((row) => row.pid === serverPid) ?? null;
}
export function collectMonitoredSamples(input: {
readonly rows: ReadonlyArray<ProcessRow>;
readonly serverPid: number;
readonly sampledAt: DateTime.Utc;
readonly sampledAtMs: number;
}): ReadonlyArray<ProcessResourceSample> {
const rows = input.rows.filter((row) => !isDiagnosticsQueryProcess(row, input.serverPid));
const root = findServerRootRow(rows, input.serverPid);
const descendants = buildDescendantEntries(rows, input.serverPid);
const samples: ProcessResourceSample[] = [];
if (root) {
samples.push({
sampledAt: input.sampledAt,
sampledAtMs: input.sampledAtMs,
processKey: sampleKey(root),
pid: root.pid,
ppid: root.ppid,
command: root.command,
cpuPercent: root.cpuPercent,
rssBytes: root.rssBytes,
depth: 0,
isServerRoot: true,
});
}
for (const process of descendants) {
samples.push({
sampledAt: input.sampledAt,
sampledAtMs: input.sampledAtMs,
processKey: sampleKey(process),
pid: process.pid,
ppid: process.ppid,
command: process.command,
cpuPercent: process.cpuPercent,
rssBytes: process.rssBytes,
depth: process.depth + 1,
isServerRoot: false,
});
}
return samples;
}
function trimSamples(
samples: ReadonlyArray<ProcessResourceSample>,
nowMs: number,
): ReadonlyArray<ProcessResourceSample> {
const minSampledAtMs = nowMs - RETENTION_MS;
const retained = samples.filter((sample) => sample.sampledAtMs >= minSampledAtMs);
return retained.length <= MAX_RETAINED_SAMPLES
? retained
: retained.slice(retained.length - MAX_RETAINED_SAMPLES);
}
function summarizeProcesses(
samples: ReadonlyArray<ProcessResourceSample>,
): ReadonlyArray<ServerProcessResourceHistorySummary> {
const groups = new Map<string, ProcessResourceSample[]>();
for (const sample of samples) {
const processSamples = groups.get(sample.processKey) ?? [];
processSamples.push(sample);
groups.set(sample.processKey, processSamples);
}
return [...groups.entries()]
.map(([processKey, processSamples]) => {
const sorted = processSamples.toSorted((left, right) => left.sampledAtMs - right.sampledAtMs);
const first = sorted[0]!;
const latest = sorted[sorted.length - 1]!;
const cpuPercentTotal = sorted.reduce((total, sample) => total + sample.cpuPercent, 0);
const maxCpuPercent = Math.max(...sorted.map((sample) => sample.cpuPercent));
const maxRssBytes = Math.max(...sorted.map((sample) => sample.rssBytes));
const cpuSecondsApprox = sorted.reduce(
(total, sample) => total + (sample.cpuPercent / 100) * (SAMPLE_INTERVAL_MS / 1_000),
0,
);
return {
processKey,
pid: latest.pid,
ppid: latest.ppid,
command: latest.command,
depth: latest.depth,
isServerRoot: latest.isServerRoot,
firstSeenAt: first.sampledAt,
lastSeenAt: latest.sampledAt,
currentCpuPercent: latest.cpuPercent,
avgCpuPercent: cpuPercentTotal / sorted.length,
maxCpuPercent,
cpuSecondsApprox,
currentRssBytes: latest.rssBytes,
maxRssBytes,
sampleCount: sorted.length,
} satisfies ServerProcessResourceHistorySummary;
})
.toSorted((left, right) => right.cpuSecondsApprox - left.cpuSecondsApprox);
}
function buildBuckets(input: {
readonly samples: ReadonlyArray<ProcessResourceSample>;
readonly nowMs: number;
readonly windowMs: number;
readonly bucketMs: number;
}): ReadonlyArray<ServerProcessResourceHistoryBucket> {
const bucketMs = Math.max(1_000, input.bucketMs);
const windowStartMs = input.nowMs - input.windowMs;
const buckets: ServerProcessResourceHistoryBucket[] = [];
for (let startedAtMs = windowStartMs; startedAtMs < input.nowMs; startedAtMs += bucketMs) {
const endedAtMs = Math.min(input.nowMs, startedAtMs + bucketMs);
const bucketSamples = input.samples.filter(
(sample) =>
sample.sampledAtMs >= startedAtMs &&
(endedAtMs === input.nowMs
? sample.sampledAtMs <= endedAtMs
: sample.sampledAtMs < endedAtMs),
);
const samplesByRead = new Map<number, ProcessResourceSample[]>();
for (const sample of bucketSamples) {
const samplesAtTime = samplesByRead.get(sample.sampledAtMs) ?? [];
samplesAtTime.push(sample);
samplesByRead.set(sample.sampledAtMs, samplesAtTime);
}
const readTotals = [...samplesByRead.values()].map((samplesAtTime) => ({
cpuPercent: samplesAtTime.reduce((total, sample) => total + sample.cpuPercent, 0),
rssBytes: samplesAtTime.reduce((total, sample) => total + sample.rssBytes, 0),
processCount: samplesAtTime.length,
}));
const avgCpuPercent =
readTotals.length === 0
? 0
: readTotals.reduce((total, read) => total + read.cpuPercent, 0) / readTotals.length;
buckets.push({
startedAt: dateTimeFromMillis(startedAtMs),
endedAt: dateTimeFromMillis(endedAtMs),
avgCpuPercent,
maxCpuPercent: readTotals.length ? Math.max(...readTotals.map((read) => read.cpuPercent)) : 0,
maxRssBytes: readTotals.length ? Math.max(...readTotals.map((read) => read.rssBytes)) : 0,
maxProcessCount: readTotals.length
? Math.max(...readTotals.map((read) => read.processCount))
: 0,
});
}
return buckets;
}
export function aggregateProcessResourceHistory(input: {
readonly samples: ReadonlyArray<ProcessResourceSample>;
readonly readAt: DateTime.Utc;
readonly readAtMs: number;
readonly windowMs: number;
readonly bucketMs: number;
readonly lastError: string | null;
}): ServerProcessResourceHistoryResult {
const windowMs = Math.max(1_000, input.windowMs);
const bucketMs = Math.max(1_000, input.bucketMs);
const minSampledAtMs = input.readAtMs - windowMs;
const samples = input.samples.filter((sample) => sample.sampledAtMs >= minSampledAtMs);
const topProcesses = summarizeProcesses(samples);
const totalCpuSecondsApprox = samples.reduce(
(total, sample) => total + (sample.cpuPercent / 100) * (SAMPLE_INTERVAL_MS / 1_000),
0,
);
return {
readAt: input.readAt,
windowMs,
bucketMs,
sampleIntervalMs: SAMPLE_INTERVAL_MS,
retainedSampleCount: input.samples.length,
totalCpuSecondsApprox,
buckets: buildBuckets({ samples, nowMs: input.readAtMs, windowMs, bucketMs }),
topProcesses,
error: input.lastError ? Option.some({ message: input.lastError }) : Option.none(),
};
}
export const make = Effect.fn("makeProcessResourceMonitor")(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const state = yield* Ref.make<MonitorState>({ samples: [], lastError: null });
const sampleOnce = Effect.gen(function* () {
const sampledAt = yield* DateTime.now;
const sampledAtMs = DateTime.toEpochMillis(sampledAt);
const rows = yield* readProcessRows.pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
const samples = collectMonitoredSamples({
rows,
serverPid: process.pid,
sampledAt,
sampledAtMs,
});
yield* Ref.update(state, (current) => ({
samples: trimSamples([...current.samples, ...samples], sampledAtMs),
lastError: null,
}));
}).pipe(
Effect.catch((error: unknown) =>
Ref.update(state, (current) => ({
...current,
lastError: error instanceof Error ? error.message : "Failed to sample process resources.",
})),
),
);
yield* Effect.forever(sampleOnce.pipe(Effect.andThen(Effect.sleep(SAMPLE_INTERVAL_MS)))).pipe(
Effect.forkScoped,
);
const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
const readHistory: ProcessResourceMonitorShape["readHistory"] = (input) =>
Effect.gen(function* () {
const readAt = yield* DateTime.now;
const readAtMs = DateTime.toEpochMillis(readAt);
const current = yield* Ref.get(state);
return aggregateProcessResourceHistory({
samples: current.samples,
readAt,
readAtMs,
windowMs: input.windowMs,
bucketMs: input.bucketMs,
lastError: current.lastError,
});
});
telemetry.readHistory(input).pipe(
Effect.map((history) => {
const topProcesses = history.topProcesses.map((entry) => ({
processKey: `${entry.identity.pid}:${entry.identity.startTimeMs}`,
pid: entry.identity.pid,
ppid: entry.ppid,
command: entry.command || entry.name || "unknown",
depth: entry.depth,
isServerRoot: entry.category === "server",
firstSeenAt: entry.firstSeenAt,
lastSeenAt: entry.lastSeenAt,
currentCpuPercent: entry.currentCpuPercent,
avgCpuPercent: entry.avgCpuPercent,
maxCpuPercent: entry.maxCpuPercent,
cpuSecondsApprox: entry.cpuTimeMs / 1_000,
currentRssBytes: entry.currentRssBytes,
maxRssBytes: entry.peakRssBytes,
sampleCount: entry.sampleCount,
}));
return {
readAt: history.readAt,
windowMs: history.windowMs,
bucketMs: history.bucketMs,
sampleIntervalMs: history.sampleIntervalMs,
retainedSampleCount: history.retainedSampleCount,
totalCpuSecondsApprox: topProcesses.reduce(
(total, entry) => total + entry.cpuSecondsApprox,
0,
),
buckets: history.buckets.map((bucket) => ({
startedAt: bucket.startedAt,
endedAt: bucket.endedAt,
avgCpuPercent: bucket.avgCpuPercent,
maxCpuPercent: bucket.maxCpuPercent,
maxRssBytes: bucket.maxRssBytes,
maxProcessCount: bucket.maxProcessCount,
})),
topProcesses,
error: history.health.native.lastError.pipe(Option.map((message) => ({ message }))),
};
}),
);
return ProcessResourceMonitor.of({ readHistory });
});