From fe3cb343844616b4dae3e46173aae4e7ab4e9cab Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:18:19 -0500 Subject: [PATCH] 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 --- ...ssOwnership.descriptorCancellation.test.ts | 111 ++++++++++++++++-- src/process/ProcessOwnership.ts | 24 +++- src/process/ProcessOwnershipObservation.ts | 35 +++++- 3 files changed, 154 insertions(+), 16 deletions(-) diff --git a/src/process/ProcessOwnership.descriptorCancellation.test.ts b/src/process/ProcessOwnership.descriptorCancellation.test.ts index 296b083b17a..b9c5a69d6f6 100644 --- a/src/process/ProcessOwnership.descriptorCancellation.test.ts +++ b/src/process/ProcessOwnership.descriptorCancellation.test.ts @@ -8,6 +8,7 @@ import { awaitAcknowledgement } from "../../tests/fixtures/lifecycleAcknowledgem const fixture = vi.hoisted(() => ({ files: new Map(), handles: new Map(), + startedOpens: new Set(), denied: new Map(), onRead: undefined as undefined | ((path: string) => Promise), 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(), release: createDeferred() }, + ]), + ); + 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"); diff --git a/src/process/ProcessOwnership.ts b/src/process/ProcessOwnership.ts index 8b1f1394bd4..92b47400671 100644 --- a/src/process/ProcessOwnership.ts +++ b/src/process/ProcessOwnership.ts @@ -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, ): Promise => { 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, ): Promise => { 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; + 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; diff --git a/src/process/ProcessOwnershipObservation.ts b/src/process/ProcessOwnershipObservation.ts index d8371c2d60b..bbc7f23e109 100644 --- a/src/process/ProcessOwnershipObservation.ts +++ b/src/process/ProcessOwnershipObservation.ts @@ -1293,13 +1293,42 @@ export const createSystemProcessOwnershipHost = ( return undefined; } }; + const LINUX_PROC_INSPECTION_CONCURRENCY = 48; + + const allSettledBounded = async ( + items: readonly T[], + concurrency: number, + fn: (item: T, index: number) => Promise, + ): Promise[]> => { + const results = new Array>(items.length); + if (items.length === 0) return results; + let next = 0; + const worker = async (): Promise => { + 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(); const failures: { pid: number; requestIndex: number; cause: unknown }[] =