Skip to content
TypeScript

feat(server): export server and process-group resource metrics (#22122)

Julius Marminge86d130af6c02
diff --git a/apps/server/src/observability/EventLoopMonitor.test.ts b/apps/server/src/observability/EventLoopMonitor.test.ts
index 963279d1382..0941c8428b1 100644
--- a/apps/server/src/observability/EventLoopMonitor.test.ts
+++ b/apps/server/src/observability/EventLoopMonitor.test.ts
@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
+import * as Metric from "effect/Metric";
import * as Tracer from "effect/Tracer";
import * as TestClock from "effect/testing/TestClock";
@@ -24,6 +25,8 @@ const stalled: EventLoopMonitor.EventLoopReadings = {
involuntaryContextSwitches: 57,
},
rssBytes: 1536 * 1024 * 1024,
+ heapUsedBytes: 512 * 1024 * 1024,
+ elapsedMs: 30_000,
};
const quiet: EventLoopMonitor.EventLoopReadings = { ...stalled, delayMaxNs: ms(2_950) };
@@ -78,6 +81,29 @@ describe("EventLoopMonitor", () => {
}),
);
+ it.effect("exports the server's memory, CPU and event loop from each sample", () =>
+ Effect.gen(function* () {
+ yield* monitor([quiet, stalled]);
+ yield* TestClock.adjust("60 seconds");
+
+ const gauges = Object.fromEntries(
+ (yield* Metric.snapshot).flatMap((snapshot) =>
+ snapshot.id.startsWith("t3_server_") && snapshot.type === "Gauge"
+ ? [[snapshot.id, snapshot.state.value]]
+ : [],
+ ),
+ );
+ assert.deepStrictEqual(gauges, {
+ t3_server_resident_bytes: 1536 * 1024 * 1024,
+ t3_server_heap_used_bytes: 512 * 1024 * 1024,
+ t3_server_event_loop_utilization: 0.176,
+ t3_server_event_loop_delay_max: 4_950,
+ // 406 ms of CPU over 30 s of wall time.
+ t3_server_cpu_utilization: 406 / 30_000,
+ });
+ }).pipe(Effect.scoped),
+ );
+
it.effect("keeps each stall as one line in a capped stall log", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
diff --git a/apps/server/src/observability/EventLoopMonitor.ts b/apps/server/src/observability/EventLoopMonitor.ts
index d713e71940d..a2944b87b74 100644
--- a/apps/server/src/observability/EventLoopMonitor.ts
+++ b/apps/server/src/observability/EventLoopMonitor.ts
@@ -5,11 +5,13 @@ import { RotatingFileSink } from "@t3tools/shared/logging";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
+import * as Metric from "effect/Metric";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import type * as Scope from "effect/Scope";
import * as ServerConfig from "../config.ts";
+import * as Metrics from "./Metrics.ts";
// Node's delay histogram wakes a native timer every RESOLUTION_MS and records the
// gap between wakeups, so an idle loop reads about RESOLUTION_MS and a stall of S
@@ -34,6 +36,9 @@ export interface EventLoopReadings {
| "involuntaryContextSwitches"
>;
readonly rssBytes: number;
+ readonly heapUsedBytes: number;
+ /** Wall time the readings cover. */
+ readonly elapsedMs: number;
}
// Node skips the first gap after a reset, so a stall right at a sample boundary can be missed.
@@ -48,11 +53,14 @@ const makeNodeSampler = Effect.gen(function* () {
);
let elu = NodePerfHooks.performance.eventLoopUtilization();
let usage = process.resourceUsage();
+ let sampledAt = NodePerfHooks.performance.now();
// @effect-diagnostics-next-line returnEffectInGen:off - the read effect is the result.
return Effect.sync(() => {
const nextElu = NodePerfHooks.performance.eventLoopUtilization();
const nextUsage = process.resourceUsage();
+ const nextSampledAt = NodePerfHooks.performance.now();
+ const memory = process.memoryUsage();
const loop = NodePerfHooks.performance.eventLoopUtilization(nextElu, elu);
const readings: EventLoopReadings = {
delayMaxNs: histogram.max,
@@ -66,11 +74,14 @@ const makeNodeSampler = Effect.gen(function* () {
involuntaryContextSwitches:
nextUsage.involuntaryContextSwitches - usage.involuntaryContextSwitches,
},
- rssBytes: process.memoryUsage.rss(),
+ rssBytes: memory.rss,
+ heapUsedBytes: memory.heapUsed,
+ elapsedMs: nextSampledAt - sampledAt,
};
histogram.reset();
elu = nextElu;
usage = nextUsage;
+ sampledAt = nextSampledAt;
return readings;
});
});
@@ -83,6 +94,21 @@ export const stallMs = ({ delayMaxNs, activeMs }: EventLoopReadings) => {
return delayMs;
};
+// Untraced: it runs inside every 30-second tick, which already has the monitor's own span.
+const recordGauges = Effect.fnUntraced(function* (readings: EventLoopReadings) {
+ const cpuMs = (readings.usage.userCPUTime + readings.usage.systemCPUTime) / 1000;
+ yield* Metric.update(Metrics.serverResidentBytes, readings.rssBytes);
+ yield* Metric.update(Metrics.serverHeapUsedBytes, readings.heapUsedBytes);
+ yield* Metric.update(Metrics.serverEventLoopUtilization, readings.utilization);
+ yield* Metric.update(
+ Metrics.serverEventLoopDelayMax,
+ Math.max(0, Math.round(readings.delayMaxNs / 1e6) - RESOLUTION_MS),
+ );
+ if (readings.elapsedMs > 0) {
+ yield* Metric.update(Metrics.serverCpuUtilization, cpuMs / readings.elapsedMs);
+ }
+});
+
const encodeStallLine = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
export interface StallLogOptions {
@@ -114,6 +140,7 @@ export const layerWith = (
);
const tick = Effect.gen(function* () {
const readings = yield* sample;
+ yield* recordGauges(readings);
const delayMaxMs = stallMs(readings);
if (delayMaxMs === undefined) return;
const { utilization, usage, rssBytes } = readings;
diff --git a/apps/server/src/observability/Metrics.ts b/apps/server/src/observability/Metrics.ts
index 033157554d3..6ba17819cea 100644
--- a/apps/server/src/observability/Metrics.ts
+++ b/apps/server/src/observability/Metrics.ts
@@ -39,6 +39,30 @@ export const providerTurnDuration = Metric.timer("t3_provider_turn_duration", {
description: "Time for the provider adapter to start a turn, not how long the turn runs.",
});
+// OTLP carries the unit, and Prometheus names the series by it: a unitless gauge gains `_ratio`.
+export const serverResidentBytes = Metric.gauge("t3_server_resident_bytes", {
+ description: "Resident memory of the server process.",
+ attributes: { unit: "By" },
+});
+
+export const serverHeapUsedBytes = Metric.gauge("t3_server_heap_used_bytes", {
+ description: "JavaScript heap in use by the server process.",
+ attributes: { unit: "By" },
+});
+
+export const serverCpuUtilization = Metric.gauge("t3_server_cpu_utilization", {
+ description: "CPU time the server used per second over the last sample; 1 is one full core.",
+});
+
+export const serverEventLoopUtilization = Metric.gauge("t3_server_event_loop_utilization", {
+ description: "Share of the last sample the server's event loop spent busy.",
+});
+
+export const serverEventLoopDelayMax = Metric.gauge("t3_server_event_loop_delay_max", {
+ description: "Longest event loop delay over the last sample.",
+ attributes: { unit: "ms" },
+});
+
export const gitCommandsTotal = Metric.counter("t3_git_commands_total", {
description: "Total git commands executed by the server runtime.",
});
diff --git a/apps/server/src/resourceTelemetry/ProcessGroupMetrics.test.ts b/apps/server/src/resourceTelemetry/ProcessGroupMetrics.test.ts
new file mode 100644
index 00000000000..694803b6484
--- /dev/null
+++ b/apps/server/src/resourceTelemetry/ProcessGroupMetrics.test.ts
@@ -0,0 +1,59 @@
+import { assert, describe, it } from "@effect/vitest";
+import type { ResourceTelemetryProcess } from "@t3tools/contracts";
+
+import { groupProcesses } from "./ProcessGroupMetrics.ts";
+
+const process = (
+ pid: number,
+ ppid: number,
+ name: string,
+ category: ResourceTelemetryProcess["category"] = "server-child",
+ command = name,
+) =>
+ ({
+ identity: { pid, startTimeMs: 1 },
+ ppid,
+ name,
+ command,
+ category,
+ residentBytes: pid * 1_000,
+ cpuPercent: pid,
+ }) as ResourceTelemetryProcess;
+
+describe("groupProcesses", () => {
+ it("sums each direct child of the server with its whole subtree", () => {
+ const totals = groupProcesses([
+ process(10, 1, "node", "server"),
+ process(11, 10, "t3-resource-mon", "resource-monitor"),
+ process(20, 10, "claude"),
+ process(21, 20, "bash"),
+ process(22, 21, "cargo"),
+ process(30, 10, "codex"),
+ process(40, 10, "zsh"),
+ process(50, 10, "chrome-headless"),
+ process(60, 10, "git", "server-child", "git checkout claude/fix"),
+ process(70, 99, "orphan"),
+ // An older Claude package runs as a script under node.
+ process(
+ 80,
+ 10,
+ "node",
+ "server-child",
+ "node /opt/node_modules/@anthropic-ai/claude-code/cli.js",
+ ),
+ process(90, 10, "node", "server-child", "node /srv/tools/report.js"),
+ ]);
+
+ assert.deepStrictEqual(Object.fromEntries(totals), {
+ server: { residentBytes: 10_000, cpuPercent: 10, count: 1 },
+ "resource-monitor": { residentBytes: 11_000, cpuPercent: 11, count: 1 },
+ // The agent's shell and the build it ran belong to the agent, not the terminal group.
+ claude: { residentBytes: 143_000, cpuPercent: 143, count: 4 },
+ codex: { residentBytes: 30_000, cpuPercent: 30, count: 1 },
+ terminal: { residentBytes: 40_000, cpuPercent: 40, count: 1 },
+ browser: { residentBytes: 50_000, cpuPercent: 50, count: 1 },
+ // `git` whose arguments mention claude, a parentless process, and a node script.
+ other: { residentBytes: 220_000, cpuPercent: 220, count: 3 },
+ });
+ });
+});
diff --git a/apps/server/src/resourceTelemetry/ProcessGroupMetrics.ts b/apps/server/src/resourceTelemetry/ProcessGroupMetrics.ts
new file mode 100644
index 00000000000..6f8f29c3716
--- /dev/null
+++ b/apps/server/src/resourceTelemetry/ProcessGroupMetrics.ts
@@ -0,0 +1,125 @@
+import type { ResourceTelemetryProcess } from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Metric from "effect/Metric";
+
+import * as ServerConfig from "../config.ts";
+import { metricAttributes } from "../observability/Metrics.ts";
+import * as ResourceTelemetry from "./ResourceTelemetry.ts";
+
+const SAMPLE_INTERVAL = "1 minute";
+
+const residentBytes = Metric.gauge("t3_process_group_resident_bytes", {
+ description: "Resident memory of the server's processes, summed by group.",
+ attributes: { unit: "By" },
+});
+const cpuPercent = Metric.gauge("t3_process_group_cpu_percent", {
+ description: "CPU use of the server's processes, summed by group; 100 is one full core.",
+ attributes: { unit: "%" },
+});
+const processCount = Metric.gauge("t3_process_group_count", {
+ description: "Processes in each group.",
+ attributes: { unit: "{process}" },
+});
+
+// Each direct child of the server names the group of its whole subtree. A fixed set keeps one
+// series per group per server, however many agents and processes come and go.
+const PROVIDER_GROUPS: ReadonlyArray<readonly [RegExp, string]> = [
+ [/codex/, "codex"],
+ [/claude/, "claude"],
+ [/cursor/, "cursor"],
+ [/opencode/, "opencode"],
+ [/grok/, "grok"],
+ [/antigravity|gemini/, "antigravity"],
+];
+const OTHER_GROUPS: ReadonlyArray<readonly [RegExp, string]> = [
+ [/chrom/, "browser"],
+ [/^(?:ba|z|fi|da|c)?sh(?:\.exe)?$|^pwsh|^powershell|^cmd\.exe$/, "terminal"],
+];
+// A CLI shipped as a script runs under a JavaScript runtime, so its process name is the
+// runtime's (older Claude packages run `node .../@anthropic-ai/claude-code/cli.js`). Only those
+// are matched by command line; any other name is matched by name alone, so a shell or `git`
+// whose arguments mention a provider stays in its own group.
+const SCRIPT_RUNTIME = /^(?:node|bun|deno)(?:\.exe)?$/;
+
+const match = (groups: ReadonlyArray<readonly [RegExp, string]>, text: string) =>
+ groups.find(([pattern]) => pattern.test(text))?.[1];
+
+const childGroup = (name: string, command: string) => {
+ const lowerName = name.toLowerCase();
+ if (SCRIPT_RUNTIME.test(lowerName))
+ return match(PROVIDER_GROUPS, command.toLowerCase()) ?? "other";
+ return match(PROVIDER_GROUPS, lowerName) ?? match(OTHER_GROUPS, lowerName) ?? "other";
+};
+
+export interface ProcessGroupTotals {
+ readonly residentBytes: number;
+ readonly cpuPercent: number;
+ readonly count: number;
+}
+
+export function groupProcesses(
+ processes: ReadonlyArray<ResourceTelemetryProcess>,
+): ReadonlyMap<string, ProcessGroupTotals> {
+ const byPid = new Map(processes.map((process) => [process.identity.pid, process]));
+ const serverPid = processes.find((process) => process.category === "server")?.identity.pid;
+ const groupOf = (process: ResourceTelemetryProcess): string => {
+ if (process.category === "server") return "server";
+ if (process.category === "resource-monitor") return "resource-monitor";
+ if (process.category.startsWith("electron-")) return "electron";
+ let current = process;
+ // Bounded by the table size, in case a reused PID makes the parent chain loop.
+ for (let step = 0; step < processes.length; step++) {
+ if (current.ppid === serverPid) return childGroup(current.name, current.command);
+ const parent = byPid.get(current.ppid);
+ if (parent === undefined) break;
+ current = parent;
+ }
+ return "other";
+ };
+ const totals = new Map<string, ProcessGroupTotals>();
+ for (const process of processes) {
+ const group = groupOf(process);
+ const total = totals.get(group) ?? { residentBytes: 0, cpuPercent: 0, count: 0 };
+ totals.set(group, {
+ residentBytes: total.residentBytes + process.residentBytes,
+ cpuPercent: total.cpuPercent + process.cpuPercent,
+ count: total.count + 1,
+ });
+ }
+ return totals;
+}
+
+/**
+ * Exports process totals by group while OTLP metrics export is on. Sampling walks the process
+ * table, which an idle server otherwise never does, so only a server exporting metrics pays for
+ * it, once a minute.
+ */
+export const layer = Layer.effectDiscard(
+ Effect.gen(function* () {
+ const config = yield* ServerConfig.ServerConfig;
+ if (config.otlpMetricsUrl === undefined) return;
+ const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
+ // A group that empties reads zero rather than holding its last value.
+ const seen = new Set<string>();
+ const sample = Effect.fn("ProcessGroupMetrics.sample")(function* () {
+ const totals = groupProcesses((yield* telemetry.refresh).processes);
+ for (const group of totals.keys()) seen.add(group);
+ for (const group of seen) {
+ const total = totals.get(group) ?? { residentBytes: 0, cpuPercent: 0, count: 0 };
+ const attributes = metricAttributes({ group });
+ yield* Metric.update(Metric.withAttributes(residentBytes, attributes), total.residentBytes);
+ yield* Metric.update(Metric.withAttributes(cpuPercent, attributes), total.cpuPercent);
+ yield* Metric.update(Metric.withAttributes(processCount, attributes), total.count);
+ }
+ });
+ yield* sample().pipe(
+ Effect.catch((error) =>
+ Effect.logDebug("process group metrics sample failed", { error: error.message }),
+ ),
+ Effect.andThen(Effect.sleep(SAMPLE_INTERVAL)),
+ Effect.forever,
+ Effect.forkScoped,
+ );
+ }),
+);
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 94485a4aa09..fd8e0824649 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -163,6 +163,7 @@ import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryR
import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts";
import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts";
import * as ResourceMonitorBinary from "./resourceTelemetry/ResourceMonitorBinary.ts";
+import * as ProcessGroupMetrics from "./resourceTelemetry/ProcessGroupMetrics.ts";
import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
import * as AntigravityUsage from "./provider/Drivers/AntigravityUsage.ts";
import * as CursorAccountReader from "@t3tools/provider-cursor/server/CursorAccountReader";
@@ -276,6 +277,7 @@ const layerResourceDiagnostics = Layer.mergeAll(
layerResourceTelemetry,
ProcessDiagnostics.layer.pipe(Layer.provide(layerResourceTelemetry)),
ProcessResourceMonitor.layer.pipe(Layer.provide(layerResourceTelemetry)),
+ ProcessGroupMetrics.layer.pipe(Layer.provide(layerResourceTelemetry)),
);
const layerRelayClient = Layer.unwrap(
diff --git a/docs/internals/resource-telemetry.md b/docs/internals/resource-telemetry.md
index 736769f59b8..1b7dea3d6aa 100644
--- a/docs/internals/resource-telemetry.md
+++ b/docs/internals/resource-telemetry.md
@@ -11,8 +11,13 @@ protocol. A missing or failed collector leaves the server running.
The native child owns sampling and bounded in-memory history. It samples on a timer
only while diagnostics has live subscribers. With none, the server sends a sample
interval of 0 and the child samples only on request, so an idle server never walks
-the process table. History therefore covers only time with a live subscriber, plus
-on-demand samples. Consuming host power for background scheduling must not retain
+the process table. The exception is OTLP metrics export: a server exporting metrics
+requests one sample a minute and exports process totals by group
+([`ProcessGroupMetrics`](../../apps/server/src/resourceTelemetry/ProcessGroupMetrics.ts)),
+because the user asked for continuous telemetry. Groups are a fixed set named after
+the server's direct children, never process IDs or threads, so the series count
+stays bounded as agents come and go. History therefore covers only time with a live
+subscriber, plus on-demand and export samples. Consuming host power for background scheduling must not retain
live diagnostics. There is no telemetry database or recurring shell-probe fallback.
History has independent bounds for age, snapshot count, process rows, and retained