Files
reverse-engineering-anything/src/desktop/DesktopSessionObservations.test.ts
T
morluto 089fce8614 fix(process): share Linux limits and bind samples to process identity (#12160)
* refactor(process): share Linux resource limit admission with EVM

Refs #12128

* fix(desktop): bind process details to their Linux generation

Refs #12134.

* fix(desktop): bind open-file samples to their process generation

Refs #12134.
2026-11-19 03:48:12 +00:00

415 lines
13 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import { systemProcessOwnershipHost } from "../process/ProcessOwnershipObservation.js";
import type { ProcessLifecycle } from "../process/ProcessLifecycle.js";
import * as linuxSampling from "../process/capture/LinuxProcessSampling.js";
import { samplingObservation } from "../process/capture/ProcessSamplingObservation.js";
import {
SessionObservations,
observedSession,
recordWindows,
sampleOpenFiles,
sampleProcesses,
sampleTokenCarriers,
trackProcess,
type SessionProcfs,
} from "./DesktopSessionObservations.js";
import type { ObservedWindow } from "../ports/DesktopApplicationSession.js";
const descriptorTargets = vi.hoisted(() => new Map<string, () => string>());
vi.mock("node:fs/promises", async (original) => {
const native = await original<typeof import("node:fs/promises")>();
return {
...native,
readdir: async (...args: Parameters<typeof native.readdir>) =>
descriptorTargets.has(`${String(args[0])}/3`)
? ["3"]
: native.readdir(...args),
readlink: async (...args: Parameters<typeof native.readlink>) => {
const target = descriptorTargets.get(String(args[0]));
return target === undefined ? native.readlink(...args) : target();
},
};
});
interface FakeProcess {
readonly parentPid: number;
readonly startTime: string;
/** Undefined models a zombie or a process whose environment is unreadable. */
readonly runId?: string;
readonly lifecycle?: ProcessLifecycle;
}
const procfs = (
table: Map<number, FakeProcess>,
tableReadable = true,
): SessionProcfs => ({
stat: async (pid) => {
const entry = table.get(pid);
return samplingObservation(
entry === undefined
? undefined
: {
pid,
parent_pid: entry.parentPid,
process_group_id: pid,
session_id: pid,
startTime: entry.startTime,
lifecycle: entry.lifecycle ?? "non-zombie",
command: "",
},
);
},
children: async (pid) =>
[...table]
.filter(([, entry]) => entry.parentPid === pid)
.map(([child]) => child),
runId: async (pid) => table.get(pid)?.runId,
command: async (pid) => samplingObservation(`process ${String(pid)}`),
tokenCarriers: async (runId) =>
tableReadable
? [...table]
.filter(
([, entry]) =>
entry.runId === runId && entry.lifecycle !== "zombie",
)
.map(([pid]) => pid)
: undefined,
});
const window = (
id: string,
pid: number,
class_: string | null,
): ObservedWindow => ({
id,
pid,
class: class_,
instance: class_?.toLowerCase() ?? null,
title: null,
window_type: "normal",
});
const observe = (
table: Map<number, FakeProcess>,
byPid = true,
tableReadable = true,
) =>
new SessionObservations(
performance.now(),
{ runId: "run", launchPid: 100 },
{ names: new Set(["notes"]), byPid },
procfs(table, tableReadable),
);
const startedBy = (observations: SessionObservations) =>
Object.fromEntries(
observedSession(observations).processes.map((entry) => [
entry.pid,
entry.started_by_capture,
]),
);
const signal = new AbortController().signal;
it.each([100, 101])(
"discards metadata from a new PID generation during discovery of %i",
async (pid) => {
const table = new Map<number, FakeProcess>([
[pid, { parentPid: 1, startTime: "11", runId: "run" }],
]);
const observations = new SessionObservations(
performance.now(),
{ runId: "run", launchPid: 100 },
{ names: new Set(), byPid: true },
{
...procfs(table),
command: async () => {
table.set(pid, { parentPid: 1, startTime: "22" });
return samplingObservation("replacement process");
},
},
);
await trackProcess(observations, pid, signal);
expect(observedSession(observations).processes).toEqual(
pid === 100
? [
expect.objectContaining({
pid,
parent_pid: process.pid,
command: "",
started_by_capture: true,
}),
]
: [],
);
expect(observations.liveProcessIds()).toEqual([]);
await trackProcess(observations, pid, signal);
expect(observedSession(observations).processes.at(-1)).toMatchObject({
pid,
command: "replacement process",
started_by_capture: false,
});
},
);
describe("SessionObservations", () => {
it("counts a process as started when its parent chain reaches the launch, even without a readable token", async () => {
const table = new Map<number, FakeProcess>([
[100, { parentPid: 1, startTime: "10", runId: "run" }],
[101, { parentPid: 100, startTime: "11" }],
[150, { parentPid: 100, startTime: "15" }],
[201, { parentPid: 150, startTime: "20" }],
[300, { parentPid: 1, startTime: "30" }],
]);
const observations = observe(table);
await trackProcess(observations, 100, signal);
await recordWindows(
observations,
[window("0x1", 201, "Notes"), window("0x2", 300, "Notes")],
signal,
);
await sampleProcesses(observations, signal);
expect(startedBy(observations)).toEqual({
100: true,
101: true,
150: true,
201: true,
300: false,
});
});
it("records the launched process as started after it has already exited", async () => {
const observations = observe(new Map());
await trackProcess(observations, 100, signal);
expect(observedSession(observations).processes).toEqual([
expect.objectContaining({
pid: 100,
parent_pid: process.pid,
started_by_capture: true,
}),
]);
expect(observations.liveProcessIds()).toEqual([]);
});
it("treats a reused pid as a different process", async () => {
const table = new Map<number, FakeProcess>([
[100, { parentPid: 1, startTime: "10", runId: "run" }],
[101, { parentPid: 100, startTime: "11", runId: "run" }],
]);
const observations = observe(table);
await trackProcess(observations, 100, signal);
await sampleProcesses(observations, signal);
expect(observations.belongs(window("0x3", 101, "Other"))).toBe(true);
table.set(101, { parentPid: 1, startTime: "99" });
await sampleProcesses(observations, signal);
expect(observations.liveProcessIds()).toEqual([100]);
expect(observations.belongs(window("0x3", 101, "Other"))).toBe(false);
await recordWindows(observations, [window("0x4", 101, "Notes")], signal);
expect(
observedSession(observations).processes.map((entry) => [
entry.pid,
entry.started_by_capture,
]),
).toEqual([
[100, true],
[101, true],
[101, false],
]);
});
it("does not attribute a reused pid discovered while recording windows", async () => {
const table = new Map<number, FakeProcess>([
[100, { parentPid: 1, startTime: "10", runId: "run" }],
[101, { parentPid: 100, startTime: "11", runId: "run" }],
]);
const observations = observe(table);
await trackProcess(observations, 100, signal);
await sampleProcesses(observations, signal);
table.set(101, { parentPid: 1, startTime: "99" });
expect(
await recordWindows(observations, [window("0x8", 101, "Other")], signal),
).toBe(0);
expect(
await recordWindows(observations, [window("0x8", 101, "Other")], signal),
).toBe(0);
expect(observedSession(observations).windows[0]?.application).toBe(false);
expect(observations.firstWindowMs).toBeNull();
expect(
await recordWindows(observations, [window("0x9", 101, "Notes")], signal),
).toBe(1);
});
it("does not keep a zombie child alive, whether first seen as one or exiting later", async () => {
const table = new Map<number, FakeProcess>([
[100, { parentPid: 1, startTime: "10", runId: "run" }],
[101, { parentPid: 100, startTime: "11", lifecycle: "zombie" }],
[102, { parentPid: 100, startTime: "12" }],
]);
const observations = observe(table);
await trackProcess(observations, 100, signal);
await sampleProcesses(observations, signal);
await sampleProcesses(observations, signal);
expect(observations.liveProcessIds(true)).toEqual([100, 102]);
table.delete(100);
table.set(102, { parentPid: 1, startTime: "12", lifecycle: "zombie" });
await sampleProcesses(observations, signal);
await recordWindows(observations, [window("0x7", 102, "Other")], signal);
expect(observations.liveProcessIds(true)).toEqual([]);
expect(startedBy(observations)).toEqual({
100: true,
101: true,
102: true,
});
expect(observedSession(observations).processes).toHaveLength(3);
});
it("matches windows by name only when their pids are sandbox pids", async () => {
const table = new Map<number, FakeProcess>([
[100, { parentPid: 1, startTime: "10", runId: "run" }],
[2, { parentPid: 1, startTime: "2" }],
]);
const observations = observe(table, false);
await trackProcess(observations, 100, signal);
expect(observations.belongs(window("0x5", 100, "Other"))).toBe(false);
expect(
await recordWindows(observations, [window("0x6", 2, "Notes")], signal),
).toBe(1);
expect(
observedSession(observations).processes.map(({ pid }) => pid),
).toEqual([100]);
});
});
describe("sampleTokenCarriers", () => {
it("finds a worker whose launcher exited before any sample reached it", async () => {
const table = new Map<number, FakeProcess>([
[200, { parentPid: 1, startTime: "20", runId: "run" }],
[201, { parentPid: 200, startTime: "21" }],
[300, { parentPid: 1, startTime: "30", runId: "other" }],
]);
const observations = observe(table);
await trackProcess(observations, 100, signal);
await sampleProcesses(observations, signal);
expect(observations.liveProcessIds(true)).toEqual([]);
expect(await sampleTokenCarriers(observations, signal)).toBe(true);
await sampleProcesses(observations, signal);
expect(observations.liveProcessIds(true)).toEqual([200, 201]);
expect(startedBy(observations)).toEqual({
100: true,
200: true,
201: true,
});
});
it("reports an unreadable process table as unknown", async () => {
const observations = observe(
new Map([[200, { parentPid: 1, startTime: "20", runId: "run" }]]),
true,
false,
);
expect(await sampleTokenCarriers(observations, signal)).toBe(false);
expect(observations.liveProcessIds()).toEqual([]);
});
});
it("records open files only from the observed process generation", async () => {
const table = new Map<number, FakeProcess>([
[100, { parentPid: 1, startTime: "10", runId: "run" }],
[101, { parentPid: 100, startTime: "11", runId: "run" }],
]);
const observations = observe(table);
await trackProcess(observations, 100, signal);
await trackProcess(observations, 101, signal);
descriptorTargets.set("/proc/100/fd/3", () => "/scope/stable (deleted)");
descriptorTargets.set("/proc/101/fd/3", () => {
table.set(101, { parentPid: 100, startTime: "22" });
return "/scope/replacement";
});
try {
await sampleOpenFiles(observations, ["/scope"], signal);
expect(
observedSession(observations).opened_files.map(({ path }) => path),
).toEqual(["/scope/stable"]);
} finally {
descriptorTargets.clear();
}
});
it("keeps a failed optional token-table probe unknown", async () => {
const observations = new SessionObservations(
performance.now(),
{ runId: "inert-observation", launchPid: process.pid },
{ names: new Set(), byPid: true },
);
const table = vi
.spyOn(systemProcessOwnershipHost, "listProcesses")
.mockRejectedValue(
Object.assign(new Error("table read failed"), { code: "EIO" }),
);
const environment = vi
.spyOn(systemProcessOwnershipHost, "environment")
.mockRejectedValue(
new Error("no token read is authorized after an unreadable table"),
);
try {
expect(
await sampleTokenCarriers(observations, new AbortController().signal),
).toBe(false);
expect(table).toHaveBeenCalledTimes(1);
expect(environment).not.toHaveBeenCalled();
} finally {
table.mockRestore();
environment.mockRestore();
}
});
it("keeps a failed optional process-token read unknown", async () => {
const observations = new SessionObservations(
performance.now(),
{ runId: "inert-observation", launchPid: process.pid },
{ names: new Set(), byPid: false },
);
const environment = vi
.spyOn(systemProcessOwnershipHost, "environment")
.mockRejectedValue(
Object.assign(new Error("token read failed"), { code: "EIO" }),
);
const stat = vi
.spyOn(linuxSampling, "readLinuxProcessStat")
.mockImplementation(
procfs(
new Map([[process.pid, { parentPid: process.ppid, startTime: "10" }]]),
).stat,
);
try {
await trackProcess(observations, process.pid, new AbortController().signal);
expect(environment).toHaveBeenCalledTimes(1);
expect(observedSession(observations).processes).toEqual([
expect.objectContaining({ pid: process.pid, started_by_capture: true }),
]);
} finally {
stat.mockRestore();
environment.mockRestore();
}
});