Files
rea/src/process/LinuxCgroupMemory.ts
T
morluto 428e006f66 fix(filesystem): close file handles only through the owned-handle owners (#10578)
* fix(filesystem): close file handles only through the owned-handle owners

Three sites still closed a fs/promises FileHandle in a finally block, where a
failed close replaced the operation's own failure or result: the agentenv
runner head read, the Linux cgroup kernel-file read and the JavaScript
analysis transfer writer. They now use withOwnedFileHandle, which retains the
operation outcome alongside a failed close.

A lint rule, rea/no-raw-file-handle-close, refuses close() on a handle opened
from fs/promises or declared as FileHandle, and fs close/closeSync on a
descriptor, in src outside src/filesystem/Owned*.

* fix(lint): distinguish owned handle class fields

* fix(filesystem): retain diagnostic file cleanup owners

* test(hopper): retry after confirmed application exit

* fix(filesystem): settle doctor peers, sample cgroup outside admission, and bind lint this

Desktop doctor waits for every client inspection before reporting a retained close failure. Ghidra memory cgroup sampling no longer passes the resource scope's admission gate, so a pending owner cannot mask the provider failure; failed closes are still retained for session cleanup. The raw FileHandle close rule resolves this through arrow functions only, treats static blocks as static, and keeps #name distinct from constructor parameter properties.

* fix(ghidra): join in-flight cgroup samples before session cleanup

ArtifactResourceScope.track runs optional work outside the admission gate while cleanup drains still join it, so a cancelled request's final retry cannot finish before a sample retains a failed close.

* fix(filesystem): join work tracked during a cleanup drain and report doctor file cleanup as typed errors

A cleanup retry now repeats until no tracked work is active and every retained owner has had one attempt, so diagnostic work admitted while an earlier owner is releasing is joined. Doctor reports a retained runner or configuration file close as a ProviderCleanupError bound to its lease instead of rethrowing a raw file failure, so the error document keeps the retained file.

* fix(desktop): read the agentenv runner head through the artifact file owner

The runner read retained a failed close under one lease while the reported failure carried another, so a successful cleanup retry left the doctor error reporting an already-closed file. withArtifactFileHandle binds one lease to both.
2026-11-15 18:08:56 +08:00

224 lines
7.3 KiB
TypeScript

import { open } from "node:fs/promises";
import { posix } from "node:path";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import {
RegularFileCleanupFailure,
withOwnedFileHandle,
} from "../filesystem/OwnedRegularFile.js";
/** Memory facts for the cgroup v2 group that holds this process. */
export interface LinuxCgroupMemoryState {
/** Group path from `/proc/self/cgroup`, relative to the cgroup2 hierarchy root. */
readonly path: string;
/**
* Hierarchical `oom_kill` count from `memory.events`. The kernel charges an
* OOM kill to the victim's group and every ancestor, so a kill of any
* process in this group or a child group raises it, whichever limit was
* reached. Other processes can share this group.
*/
readonly oomKills: number;
/**
* This group's `memory.max`: bytes, `max` when the group sets no limit, or
* null when it could not be read. A limit on a parent group is not read.
*/
readonly memoryMax: number | "max" | null;
}
/** One cgroup2 mount from `/proc/self/mountinfo`. */
interface LinuxCgroup2Mount {
/** Hierarchy path that the mount exposes at its mount point. */
readonly root: string;
readonly mountPoint: string;
}
const KERNEL_FILE_BYTES = 16 * 1024;
/** Hosts with many container layers publish long mount tables. */
const MOUNT_INFO_BYTES = 4 * 1024 * 1024;
/** Read the single cgroup v2 (`0::`) row of one `/proc/<pid>/cgroup` record. */
const parseLinuxCgroupV2Path = (value: string): string | undefined => {
let path: string | undefined;
for (const line of value.split("\n")) {
if (!line.startsWith("0::")) continue;
if (path !== undefined) return undefined;
path = line.slice(3);
}
if (path === undefined || !path.startsWith("/")) return undefined;
return path.split("/").includes("..") ? undefined : path;
};
/** Read the single `oom_kill` counter of one cgroup v2 `memory.events` file. */
const parseLinuxCgroupOomKills = (value: string): number | undefined => {
let count: number | undefined;
for (const line of value.split("\n")) {
const match = /^oom_kill ([0-9]+)$/u.exec(line);
if (match === null) continue;
if (count !== undefined) return undefined;
count = Number(match[1]);
}
return count !== undefined && Number.isSafeInteger(count) ? count : undefined;
};
/** Read one cgroup v2 `memory.max` file; `max` means no limit. */
const parseLinuxCgroupMemoryMax = (
value: string,
): number | "max" | undefined => {
const token = value.trim();
if (token === "max") return "max";
if (!/^[0-9]+$/u.test(token)) return undefined;
const bytes = Number(token);
return Number.isSafeInteger(bytes) ? bytes : undefined;
};
/** Decode the octal escapes the kernel writes for space, tab, newline and backslash. */
const mountInfoField = (value: string): string =>
value.replace(/\\([0-7]{3})/gu, (_match, code: string) =>
String.fromCharCode(Number.parseInt(code, 8)),
);
/** List the cgroup2 mounts of one `/proc/<pid>/mountinfo` record. */
const parseLinuxCgroup2Mounts = (value: string): readonly LinuxCgroup2Mount[] =>
value.split("\n").flatMap((line) => {
const fields = line.split(" ");
const separator = fields.indexOf("-");
const root = fields[3];
const mountPoint = fields[4];
if (
separator < 6 ||
fields[separator + 1] !== "cgroup2" ||
root === undefined ||
mountPoint === undefined
)
return [];
return [
{ root: mountInfoField(root), mountPoint: mountInfoField(mountPoint) },
];
});
/**
* Locate a cgroup path below the mount whose root covers it most closely; a
* mount that exposes only part of the hierarchy is joined from its own root.
*/
const linuxCgroupDirectory = (
mounts: readonly LinuxCgroup2Mount[],
path: string,
): string | undefined => {
let selected:
| { readonly mount: LinuxCgroup2Mount; readonly rest: string }
| undefined;
for (const mount of mounts) {
const rest =
mount.root === "/"
? path
: path === mount.root
? "/"
: path.startsWith(`${mount.root}/`)
? path.slice(mount.root.length)
: undefined;
if (rest === undefined) continue;
if (
selected === undefined ||
mount.root.length > selected.mount.root.length
)
selected = { mount, rest };
}
return selected === undefined
? undefined
: posix.resolve(selected.mount.mountPoint, `.${selected.rest}`);
};
/**
* Observe this process's cgroup v2 memory group. Unavailable on other
* platforms, under cgroup v1, or when the files are unreadable.
*/
export const readLinuxCgroupMemoryState = async (
options: {
readonly platform?: NodeJS.Platform;
readonly procCgroupPath?: string;
readonly procMountInfoPath?: string;
readonly retainFailedClose?: (path: string, owner: OwnedFileHandle) => void;
} = {},
): Promise<LinuxCgroupMemoryState | undefined> => {
if ((options.platform ?? process.platform) !== "linux") return undefined;
const membership = await readKernelFile(
options.procCgroupPath ?? "/proc/self/cgroup",
undefined,
options.retainFailedClose,
);
const path =
membership === undefined ? undefined : parseLinuxCgroupV2Path(membership);
if (path === undefined) return undefined;
const mountInfo = await readKernelFile(
options.procMountInfoPath ?? "/proc/self/mountinfo",
MOUNT_INFO_BYTES,
options.retainFailedClose,
);
const group =
mountInfo === undefined
? undefined
: linuxCgroupDirectory(parseLinuxCgroup2Mounts(mountInfo), path);
if (group === undefined) return undefined;
const events = await readKernelFile(
posix.join(group, "memory.events"),
undefined,
options.retainFailedClose,
);
const oomKills =
events === undefined ? undefined : parseLinuxCgroupOomKills(events);
if (oomKills === undefined) return undefined;
const limit = await readKernelFile(
posix.join(group, "memory.max"),
undefined,
options.retainFailedClose,
);
return {
path,
oomKills,
memoryMax:
limit === undefined ? null : (parseLinuxCgroupMemoryMax(limit) ?? null),
};
};
/**
* Read a kernel report to EOF within a fixed budget; procfs may return it in
* several short reads. Absent on any failure or when the budget is exceeded.
*/
const readKernelFile = async (
path: string,
maxBytes = KERNEL_FILE_BYTES,
retainFailedClose?: (path: string, owner: OwnedFileHandle) => void,
): Promise<string | undefined> => {
try {
return await withOwnedFileHandle(
path,
new OwnedFileHandle(await open(path, "r")),
retainFailedClose === undefined
? {}
: { retainFailedClose: (owner) => retainFailedClose(path, owner) },
async (handle) => {
const buffer = Buffer.alloc(maxBytes + 1);
let length = 0;
for (;;) {
const { bytesRead } = await handle.read(
buffer,
length,
buffer.length - length,
null,
);
if (bytesRead === 0) break;
length += bytesRead;
if (length > maxBytes) return undefined;
}
return buffer.subarray(0, length).toString("utf8");
},
);
} catch (cause: unknown) {
if (
cause instanceof RegularFileCleanupFailure &&
cause.retention.kind !== "callback_returned"
)
throw cause;
return undefined;
}
};