mirror of
https://github.com/morluto/rea.git
synced 2026-12-02 03:25:20 +00:00
perf(process): bound Linux /proc FD concurrency and reuse relation identities in token sweep (#13780)
* perf(process): bound Linux /proc FD concurrency and reuse relation identities in token sweep * test(process): cover queued Linux identity reads
This commit is contained in:
1 parent
61e8f73f4b
commit
fe3cb34384
3 files changed
+154
-16
No files matched your search
@@ -8,6 +8,7 @@ import { awaitAcknowledgement } from "../../tests/fixtures/lifecycleAcknowledgem
|
||||
const fixture = vi.hoisted(() => ({
|
||||
files: new Map<string, string>(),
|
||||
handles: new Map<string, FileHandle>(),
|
||||
startedOpens: new Set<string>(),
|
||||
denied: new Map<string, Error>(),
|
||||
onRead: undefined as undefined | ((path: string) => Promise<void>),
|
||||
onReadFailure: undefined as undefined | ((cause: unknown) => void),
|
||||
@@ -24,6 +25,7 @@ vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
return filesystem.readFile(...args);
|
||||
},
|
||||
open: async (path: string) => {
|
||||
fixture.startedOpens.add(path);
|
||||
const selected = fixture.files.get(path);
|
||||
if (selected === undefined) throw new Error(`Unexpected open: ${path}`);
|
||||
const handle = await filesystem.open(selected, "r");
|
||||
@@ -65,34 +67,125 @@ import {
|
||||
readNativeProcessIdentityMap,
|
||||
} from "./ProcessOwnershipObservation.js";
|
||||
|
||||
const prepare = async () => {
|
||||
const prepare = async (count = 3, startTime = (_pid: number) => 100) => {
|
||||
fixture.files.clear();
|
||||
fixture.handles.clear();
|
||||
fixture.startedOpens.clear();
|
||||
fixture.denied.clear();
|
||||
fixture.onRead = undefined;
|
||||
fixture.onReadFailure = undefined;
|
||||
fixture.onClosed = undefined;
|
||||
fixture.onDeniedClose = undefined;
|
||||
const root = await createTestTempDirectory("rea-inspection-descriptor-");
|
||||
const rows = [42, 43, 44].map((pid) => ({
|
||||
pid,
|
||||
parentPid: 1,
|
||||
processGroupId: pid,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
}));
|
||||
const rows = Array.from({ length: count }, (_, index) => 42 + index).map(
|
||||
(pid) => ({
|
||||
pid,
|
||||
parentPid: 1,
|
||||
processGroupId: pid,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
}),
|
||||
);
|
||||
for (const { pid } of rows) {
|
||||
const path = join(root, String(pid));
|
||||
// Linux stat fields 3..22, including PF flags and the native start tick.
|
||||
await writeFile(
|
||||
path,
|
||||
`${pid} (fixture) S 1 ${pid} ${pid} 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 100`,
|
||||
`${pid} (fixture) S 1 ${pid} ${pid} 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ${startTime(pid)}`,
|
||||
);
|
||||
fixture.files.set(`/proc/${pid}/stat`, path);
|
||||
}
|
||||
return { root, rows, host: createSystemProcessOwnershipHost("linux", {}) };
|
||||
};
|
||||
|
||||
it.each(["complete", "cancel"] as const)(
|
||||
"bounds Linux identity reads and preserves PID attribution when queued reads %s",
|
||||
async (outcome) => {
|
||||
const concurrency = 48;
|
||||
const startTime = (pid: number) => 1_000 + pid;
|
||||
const { rows, host } = await prepare(concurrency + 4, startTime);
|
||||
const paths = rows.map(({ pid }) => `/proc/${pid}/stat`);
|
||||
const gates = new Map(
|
||||
paths.map((path) => [
|
||||
path,
|
||||
{ entered: createDeferred<void>(), release: createDeferred<void>() },
|
||||
]),
|
||||
);
|
||||
fixture.onRead = (path) => {
|
||||
const gate = gates.get(path)!;
|
||||
gate.entered.resolve();
|
||||
return gate.release.promise;
|
||||
};
|
||||
const closed: string[] = [];
|
||||
fixture.onClosed = (path) => closed.push(path);
|
||||
const controller = new AbortController();
|
||||
const reason = { caller: "while identity reads remain queued" };
|
||||
const pending = host.processIdentities!(rows, controller.signal).catch(
|
||||
(cause: unknown) => cause,
|
||||
);
|
||||
const firstWave = paths.slice(0, concurrency);
|
||||
const firstQueued = paths[concurrency]!;
|
||||
const secondQueued = paths[concurrency + 1]!;
|
||||
const lastOfFirstWave = firstWave.at(-1)!;
|
||||
let result: unknown;
|
||||
try {
|
||||
await awaitAcknowledgement(
|
||||
Promise.all(firstWave.map((path) => gates.get(path)!.entered.promise)),
|
||||
pending,
|
||||
"first identity read wave",
|
||||
);
|
||||
expect(fixture.startedOpens).toEqual(new Set(firstWave));
|
||||
|
||||
gates.get(lastOfFirstWave)!.release.resolve();
|
||||
await awaitAcknowledgement(
|
||||
gates.get(firstQueued)!.entered.promise,
|
||||
pending,
|
||||
"first queued identity read",
|
||||
);
|
||||
gates.get(firstQueued)!.release.resolve();
|
||||
await awaitAcknowledgement(
|
||||
gates.get(secondQueued)!.entered.promise,
|
||||
pending,
|
||||
"second queued identity read",
|
||||
);
|
||||
expect(closed).toEqual([lastOfFirstWave, firstQueued]);
|
||||
expect(fixture.startedOpens).toEqual(
|
||||
new Set([...firstWave, firstQueued, secondQueued]),
|
||||
);
|
||||
if (outcome === "cancel") controller.abort(reason);
|
||||
} finally {
|
||||
for (const gate of gates.values()) gate.release.resolve();
|
||||
result = await pending;
|
||||
}
|
||||
for (const handle of fixture.handles.values()) expect(handle.fd).toBe(-1);
|
||||
if (outcome === "complete") {
|
||||
if (!(result instanceof Map)) throw result;
|
||||
expect([...result.keys()]).toEqual(rows.map(({ pid }) => pid));
|
||||
for (const { pid } of rows)
|
||||
expect(result.get(pid)).toMatchObject({
|
||||
state: "readable",
|
||||
identity: `linux-starttime:${startTime(pid)}`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!(result instanceof ProcessOwnershipIdentityBatchFailure)) throw result;
|
||||
expect(result).toMatchObject({ origin: "cancelled", reason });
|
||||
const completed = rows.slice(concurrency - 1, concurrency + 1);
|
||||
expect([...result.observations.keys()]).toEqual(
|
||||
completed.map(({ pid }) => pid),
|
||||
);
|
||||
for (const { pid } of completed)
|
||||
expect(result.observations.get(pid)).toMatchObject({
|
||||
state: "readable",
|
||||
identity: `linux-starttime:${startTime(pid)}`,
|
||||
});
|
||||
expect(result.cancellations.at(-1)?.pid).toBe(rows.at(-1)!.pid);
|
||||
expect(fixture.startedOpens).toEqual(
|
||||
new Set(paths.slice(0, concurrency + 2)),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("retains an actual descriptor read fault as unavailable when the identical fault aborts the caller", async () => {
|
||||
const { root, rows, host } = await prepare();
|
||||
const directory = join(root, "directory");
|
||||
|
||||
@@ -1072,6 +1072,7 @@ const createOwnedCleanupPlan = async (
|
||||
: { sampledProcessGroupIds: [...sampledProcessGroupIds] }),
|
||||
},
|
||||
exitSettlement,
|
||||
relationSnapshot.identities,
|
||||
)
|
||||
: { owned: [], failures: [], unverified: [], identities: new Map() };
|
||||
const listedPids = new Set(processes.map(({ pid }) => pid));
|
||||
@@ -1738,6 +1739,7 @@ const scanTokenOwnedProcesses = async (
|
||||
captureBaseline: ProcessOwnershipBaseline | undefined,
|
||||
relation: OwnershipSweepRelation | undefined,
|
||||
exitSettlement: ProcessExitSettlementBudget,
|
||||
initialIdentities?: ReadonlyMap<number, ProcessIdentityObservation>,
|
||||
): Promise<TokenOwnedProcessScan> => {
|
||||
if (host.processIdentities !== undefined)
|
||||
return scanWithOwnershipEvidence(
|
||||
@@ -1747,6 +1749,7 @@ const scanTokenOwnedProcesses = async (
|
||||
captureBaseline,
|
||||
relation,
|
||||
exitSettlement,
|
||||
initialIdentities,
|
||||
);
|
||||
|
||||
const candidates = processes;
|
||||
@@ -1840,6 +1843,7 @@ const scanWithOwnershipEvidence = async (
|
||||
captureBaseline: ProcessOwnershipBaseline | undefined,
|
||||
relation: OwnershipSweepRelation | undefined,
|
||||
exitSettlement: ProcessExitSettlementBudget,
|
||||
initialIdentities?: ReadonlyMap<number, ProcessIdentityObservation>,
|
||||
): Promise<TokenOwnedProcessScan> => {
|
||||
const evidenceOwner =
|
||||
relation === undefined
|
||||
@@ -1865,10 +1869,22 @@ const scanWithOwnershipEvidence = async (
|
||||
(captureBaseline ?? []).map(({ pid, identity }) => [pid, identity]),
|
||||
);
|
||||
const retainedPids = new Set(evidenceOwner.candidates.map(({ pid }) => pid));
|
||||
const firstIdentities = await readNativeProcessIdentityMap(
|
||||
observationRows,
|
||||
host,
|
||||
);
|
||||
let firstIdentities: ReadonlyMap<number, ProcessIdentityObservation>;
|
||||
if (initialIdentities !== undefined && initialIdentities.size > 0) {
|
||||
const missingRows = observationRows.filter(
|
||||
({ pid }) => !initialIdentities.has(pid),
|
||||
);
|
||||
if (missingRows.length === 0) {
|
||||
firstIdentities = initialIdentities;
|
||||
} else {
|
||||
const fetched = await readNativeProcessIdentityMap(missingRows, host);
|
||||
const merged = new Map(initialIdentities);
|
||||
for (const [pid, observation] of fetched) merged.set(pid, observation);
|
||||
firstIdentities = merged;
|
||||
}
|
||||
} else {
|
||||
firstIdentities = await readNativeProcessIdentityMap(observationRows, host);
|
||||
}
|
||||
const candidates = observationRows.filter((process) => {
|
||||
if (retainedPids.has(process.pid)) return true;
|
||||
if (!baseline.has(process.pid)) return true;
|
||||
|
||||
@@ -1293,13 +1293,42 @@ export const createSystemProcessOwnershipHost = (
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
const LINUX_PROC_INSPECTION_CONCURRENCY = 48;
|
||||
|
||||
const allSettledBounded = async <T, U>(
|
||||
items: readonly T[],
|
||||
concurrency: number,
|
||||
fn: (item: T, index: number) => Promise<U>,
|
||||
): Promise<PromiseSettledResult<U>[]> => {
|
||||
const results = new Array<PromiseSettledResult<U>>(items.length);
|
||||
if (items.length === 0) return results;
|
||||
let next = 0;
|
||||
const worker = async (): Promise<void> => {
|
||||
while (next < items.length) {
|
||||
const index = next++;
|
||||
try {
|
||||
const value = await fn(items[index]!, index);
|
||||
results[index] = { status: "fulfilled", value };
|
||||
} catch (reason: unknown) {
|
||||
results[index] = { status: "rejected", reason };
|
||||
}
|
||||
}
|
||||
};
|
||||
await Promise.all(
|
||||
Array.from({ length: Math.min(concurrency, items.length) }, worker),
|
||||
);
|
||||
return results;
|
||||
};
|
||||
|
||||
const physicalReadFailures: {
|
||||
pid: number;
|
||||
requestIndex: number;
|
||||
cause: unknown;
|
||||
}[] = [];
|
||||
const results = await Promise.allSettled(
|
||||
processes.map(async ({ pid }, requestIndex) => {
|
||||
const results = await allSettledBounded(
|
||||
processes,
|
||||
LINUX_PROC_INSPECTION_CONCURRENCY,
|
||||
async ({ pid }, requestIndex) => {
|
||||
if (!Number.isSafeInteger(pid) || pid <= 0)
|
||||
return [
|
||||
pid,
|
||||
@@ -1508,7 +1537,7 @@ export const createSystemProcessOwnershipHost = (
|
||||
{ state: "unavailable", reason: errorMessage(cause) } as const,
|
||||
] as const;
|
||||
}
|
||||
}),
|
||||
},
|
||||
);
|
||||
const observations = new Map<number, ProcessIdentityObservation>();
|
||||
const failures: { pid: number; requestIndex: number; cause: unknown }[] =
|
||||
|
||||
Reference in new issue
Block a user