Skip to content

Write HTML. Render video. Built for agents.

feat(engine): zero-dependency per-pid RSS sampler (ps / tasklist)

Vance Ingallsbc70156f0073
diff --git a/packages/engine/src/utils/processRss.test.ts b/packages/engine/src/utils/processRss.test.ts
new file mode 100644
index 0000000000..85204688d2
--- /dev/null
+++ b/packages/engine/src/utils/processRss.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from "vitest";
+import { parsePsRss, parseTasklistCsv, sampleProcessRss } from "./processRss.js";
+
+describe("parsePsRss", () => {
+ it("parses pid and rss kilobytes into megabytes", () => {
+ const out = " 4242 1048576\n 4243 2048\n";
+ expect(parsePsRss(out)).toEqual([
+ { pid: 4242, rssMb: 1024 },
+ { pid: 4243, rssMb: 2 },
+ ]);
+ });
+
+ it("skips blank and malformed lines", () => {
+ expect(parsePsRss("\n PID RSS\nabc def\n 7 10240\n")).toEqual([{ pid: 7, rssMb: 10 }]);
+ });
+});
+
+describe("parseTasklistCsv", () => {
+ it("parses the memory column with thousands separators", () => {
+ const out = '"chrome.exe","4242","Console","1","1,048,576 K"\r\n';
+ expect(parseTasklistCsv(4242, out)).toEqual([{ pid: 4242, rssMb: 1024 }]);
+ });
+
+ it("returns [] for the 'no tasks' message", () => {
+ expect(
+ parseTasklistCsv(4242, "INFO: No tasks are running which match the specified criteria."),
+ ).toEqual([]);
+ });
+});
+
+describe("sampleProcessRss", () => {
+ it("uses one ps call for all pids on posix", async () => {
+ const calls: Array<{ file: string; args: readonly string[] }> = [];
+ const exec = async (file: string, args: readonly string[]) => {
+ calls.push({ file, args });
+ return { stdout: " 1 1024\n 2 2048\n" };
+ };
+ const result = await sampleProcessRss([1, 2], exec, "darwin");
+ expect(calls).toEqual([{ file: "ps", args: ["-o", "pid=,rss=", "-p", "1,2"] }]);
+ expect(result).toEqual([
+ { pid: 1, rssMb: 1 },
+ { pid: 2, rssMb: 2 },
+ ]);
+ });
+
+ it("uses one tasklist call per pid on win32", async () => {
+ const calls: string[][] = [];
+ const exec = async (_file: string, args: readonly string[]) => {
+ calls.push([...args]);
+ return { stdout: '"chrome.exe","9","Console","1","2,048 K"\r\n' };
+ };
+ const result = await sampleProcessRss([9], exec, "win32");
+ expect(calls).toEqual([["/FO", "CSV", "/NH", "/FI", "PID eq 9"]]);
+ expect(result).toEqual([{ pid: 9, rssMb: 2 }]);
+ });
+
+ it("returns [] on empty input without calling exec", async () => {
+ let called = false;
+ const exec = async () => {
+ called = true;
+ return { stdout: "" };
+ };
+ expect(await sampleProcessRss([], exec, "linux")).toEqual([]);
+ expect(called).toBe(false);
+ });
+
+ it("never rejects when exec fails", async () => {
+ const exec = async () => {
+ throw new Error("ENOENT");
+ };
+ expect(await sampleProcessRss([1], exec, "linux")).toEqual([]);
+ });
+});
diff --git a/packages/engine/src/utils/processRss.ts b/packages/engine/src/utils/processRss.ts
new file mode 100644
index 0000000000..48af97caf2
--- /dev/null
+++ b/packages/engine/src/utils/processRss.ts
@@ -0,0 +1,75 @@
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+
+export interface ProcessRssSample {
+ pid: number;
+ rssMb: number;
+}
+
+export type ExecFileLike = (file: string, args: readonly string[]) => Promise<{ stdout: string }>;
+
+const KB_PER_MB = 1024;
+
+function defaultExec(): ExecFileLike {
+ // promisify lazily so vitest module mocks of child_process still take effect
+ // (same reason psnr.ts does this).
+ const execFileP = promisify(execFile);
+ return async (file, args) => {
+ const { stdout } = await execFileP(file, [...args], { windowsHide: true, timeout: 5_000 });
+ return { stdout: String(stdout) };
+ };
+}
+
+/** `ps -o pid=,rss=` output: one "<pid> <rss-kb>" pair per line. */
+export function parsePsRss(stdout: string): ProcessRssSample[] {
+ const samples: ProcessRssSample[] = [];
+ for (const line of stdout.split("\n")) {
+ const match = /^\s*(\d+)\s+(\d+)\s*$/.exec(line);
+ if (!match) continue;
+ const pid = Number(match[1]);
+ const rssKb = Number(match[2]);
+ if (!Number.isFinite(pid) || !Number.isFinite(rssKb)) continue;
+ samples.push({ pid, rssMb: Math.round(rssKb / KB_PER_MB) });
+ }
+ return samples;
+}
+
+/** `tasklist /FO CSV /NH /FI "PID eq N"`: `"image","pid","session","sess#","12,345 K"`. */
+export function parseTasklistCsv(pid: number, stdout: string): ProcessRssSample[] {
+ const line = stdout.split(/\r?\n/).find((l) => l.startsWith('"'));
+ if (!line) return [];
+ const cells = line.split('","').map((c) => c.replace(/^"|"$/g, ""));
+ const memCell = cells[4];
+ if (typeof memCell !== "string") return [];
+ const kb = Number(memCell.replace(/[^0-9]/g, ""));
+ if (!Number.isFinite(kb) || kb <= 0) return [];
+ return [{ pid, rssMb: Math.round(kb / KB_PER_MB) }];
+}
+
+/**
+ * Resident set size per pid, in MiB. Zero dependencies: `ps` on POSIX (one
+ * call for all pids), `tasklist` on Windows (one call per pid). Never
+ * rejects; a pid that exited between discovery and sampling is simply absent.
+ */
+export async function sampleProcessRss(
+ pids: readonly number[],
+ exec: ExecFileLike = defaultExec(),
+ platform: NodeJS.Platform = process.platform,
+): Promise<ProcessRssSample[]> {
+ const unique = [...new Set(pids.filter((p) => Number.isInteger(p) && p > 0))];
+ if (unique.length === 0) return [];
+ try {
+ if (platform === "win32") {
+ const results: ProcessRssSample[] = [];
+ for (const pid of unique) {
+ const { stdout } = await exec("tasklist", ["/FO", "CSV", "/NH", "/FI", `PID eq ${pid}`]);
+ results.push(...parseTasklistCsv(pid, stdout));
+ }
+ return results;
+ }
+ const { stdout } = await exec("ps", ["-o", "pid=,rss=", "-p", unique.join(",")]);
+ return parsePsRss(stdout);
+ } catch {
+ return [];
+ }
+}