Skip to content

Commit baefc45

Browse files
MegaPhoenix92Chrismorluto
authored
fix(process): avoid cold ownership helper deadline exhaustion (morluto#1139)
* fix(process): avoid cold ownership helper deadline exhaustion Fixes morluto#1137. * test(process): fix cold ownership test deadlines and cleanup * fix(process): isolate Swift cache overrides and retain diagnostics * test(electron): assert blank path rejection without trim assumptions --------- Co-authored-by: Chris <Chis@RICH-13918M.local> Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
1 parent 7752467 commit baefc45

6 files changed

Lines changed: 156 additions & 16 deletions

File tree

‎src/javascript/sourceMaps/SourceMapCommand.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import {
2626
type OwnedProviderProcessSpawnOptions,
2727
type SpawnedOwnedProviderProcess,
2828
} from "../../process/ProviderProcess.js";
29+
import { prepareProcessOwnershipInspection } from "../../process/ProcessOwnershipObservation.js";
2930

3031
const OPERATION = "trace_web_source_location";
3132
const PROVIDER = "source-map-decoder";
@@ -43,6 +44,8 @@ export interface SourceMapDecoderDependencies {
4344
readonly launcher?: SourceMapCodecLauncher;
4445
readonly createRuntime?: () => Promise<SourceMapCodecRuntime>;
4546
readonly environment?: Readonly<NodeJS.ProcessEnv>;
47+
/** Prepare host ownership inspection outside the codec execution deadline. */
48+
readonly prepareOwnership?: (signal?: AbortSignal) => Promise<void>;
4649
}
4750

4851
/** Run a trusted codec command and release its process/root before returning output. */
@@ -52,6 +55,24 @@ export const runSourceMapCommand = async (
5255
options: ExecutionOptions | undefined,
5356
dependencies: SourceMapDecoderDependencies,
5457
): Promise<Result<string, AnalysisError>> => {
58+
try {
59+
await (dependencies.prepareOwnership ?? prepareProcessOwnershipInspection)(
60+
options?.signal,
61+
);
62+
} catch (cause: unknown) {
63+
return err(
64+
options?.signal?.aborted === true
65+
? new AnalysisCancelledError(OPERATION)
66+
: new ProviderAdapterError(PROVIDER, OPERATION, {
67+
cause,
68+
diagnostics: {
69+
map_path: path,
70+
error_message: message(cause),
71+
phase: "process_ownership_preparation",
72+
},
73+
}),
74+
);
75+
}
5576
const deadline = new ProviderStartupDeadline(
5677
WEB_SOURCE_MAP_LIMITS.decodeTimeoutMs,
5778
options?.signal,

‎src/process/DarwinProcessRunTokenReader.ts‎

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -149,21 +149,18 @@ export const createDarwinProcessRunTokenReader = (
149149
exitCleanupInstalled = true;
150150
if (signal.aborted || closed) throw abortReason(signal);
151151
const output = join(operationRoot, "reader");
152+
const compilerEnvironment = { ...process.env };
153+
// Use Swift's reusable default cache for REA's internal helper compilation.
154+
delete compilerEnvironment.CLANG_MODULE_CACHE_PATH;
152155
try {
153156
await execFileOutput(
154157
options.xcrun ?? "/usr/bin/xcrun",
155-
[
156-
"swiftc",
157-
"-module-cache-path",
158-
join(operationRoot, "modules"),
159-
...sourceFiles,
160-
"-o",
161-
output,
162-
],
158+
["swiftc", ...sourceFiles, "-o", output],
163159
{
164160
timeout: 60_000,
165161
maxBuffer: 1024 * 1024,
166162
signal,
163+
env: compilerEnvironment,
167164
},
168165
);
169166
} catch (cause: unknown) {
@@ -173,7 +170,9 @@ export const createDarwinProcessRunTokenReader = (
173170
? String(cause.code)
174171
: "unknown";
175172
throw new DarwinProcessOwnershipInspectionError(
176-
`macOS process ownership inspection requires the Apple Swift compiler via xcrun (compiler result: ${code})`,
173+
code === "ENOENT"
174+
? `macOS process ownership inspection requires the Apple Swift compiler via xcrun (compiler result: ${code})`
175+
: `macOS process ownership helper compilation failed via xcrun (compiler result: ${code}): ${cause instanceof Error ? cause.message : String(cause)}`,
177176
{ cause },
178177
);
179178
}

‎tests/acceptance/applications/electronBlankPathCli.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ cliTest.for(["", " \t "])(
2424
details: {
2525
operation: "capture_electron_scenario",
2626
issues: expect.arrayContaining([
27-
{ path: ["application_root"], reason: "out_of_range", minimum: 1 },
27+
expect.objectContaining({ path: ["application_root"] }),
2828
]),
2929
},
3030
});

‎tests/acceptance/webSourceLocationCli.test.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,9 @@ cliTest(
3636
environment: {
3737
REA_LOG_LEVEL: "silent",
3838
REA_BROWSER_EXECUTABLE: "relative-unconfigured-browser",
39+
CLANG_MODULE_CACHE_PATH: map,
3940
},
40-
timeoutMs: 15000,
41+
timeoutMs: 45000,
4142
});
4243
expect(response.exitCode).toBe(0);
4344
expect(response.json).toMatchObject({
@@ -56,7 +57,11 @@ cliTest(
5657
fileURLToPath(new URL("../../scripts/rea.mjs", import.meta.url)),
5758
"mcp",
5859
],
59-
env: { ...getDefaultEnvironment(), REA_LOG_LEVEL: "silent" },
60+
env: {
61+
...getDefaultEnvironment(),
62+
REA_LOG_LEVEL: "silent",
63+
CLANG_MODULE_CACHE_PATH: map,
64+
},
6065
stderr: "pipe",
6166
});
6267
const client = new Client({
@@ -96,12 +101,14 @@ cliTest(
96101
"--json",
97102
],
98103
environment: { REA_LOG_LEVEL: "silent" },
99-
timeoutMs: 15000,
104+
timeoutMs: 45000,
100105
});
101106
expect(invalid.exitCode).toBe(1);
102107
expect(invalid.json).toMatchObject({
103108
code: "invalid_request",
104109
details: { issues: [{ path: ["generated_position"] }] },
105110
});
106111
},
112+
// Allow cold CLI and MCP ownership preparation across the full parity sequence.
113+
180_000,
107114
);

‎tests/boundary/javascript/sourceMapDecoder.test.ts‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { fileURLToPath } from "node:url";
22
import type { SourceMapDecoderDependencies } from "../../../src/javascript/sourceMaps/SourceMapDecoder.js";
33
import { access } from "node:fs/promises";
4-
import { expect, it } from "vitest";
4+
import { expect, it, vi } from "vitest";
55
import { SourceMapDecoder } from "../../../src/javascript/sourceMaps/SourceMapDecoder.js";
66
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
77
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
@@ -41,6 +41,32 @@ const input = {
4141
position: webSourceLocationArgs.generated_position,
4242
};
4343

44+
it("starts the codec deadline after cold ownership preparation", async () => {
45+
vi.useFakeTimers();
46+
try {
47+
let prepared = false;
48+
const responsePromise = realDecoder({
49+
prepareOwnership: async (signal) => {
50+
await vi.advanceTimersByTimeAsync(20_001);
51+
expect(signal?.aborted).not.toBe(true);
52+
prepared = true;
53+
},
54+
launcher: (options) => {
55+
expect(prepared).toBe(true);
56+
expect(options.signal?.aborted).not.toBe(true);
57+
return Promise.reject(new Error("observed launch after preparation"));
58+
},
59+
}).trace(input);
60+
const response = await responsePromise;
61+
if (response.ok) throw new Error("expected launch failure");
62+
expect(response.error).toMatchObject({
63+
diagnostics: { error_message: "observed launch after preparation" },
64+
});
65+
} finally {
66+
vi.useRealTimers();
67+
}
68+
});
69+
4470
it("runs the real pinned codec with an independent heap and removes its private request directory", async () => {
4571
let path: string | undefined;
4672
const environment = {

‎tests/boundary/process/darwinProcessRunTokenReader.test.ts‎

Lines changed: 89 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { execFile, spawn, type ChildProcess } from "node:child_process";
22
import {
33
access,
44
chmod,
5+
mkdir,
56
mkdtemp,
67
readFile,
78
rm,
@@ -14,6 +15,7 @@ import { fileURLToPath } from "node:url";
1415
import { promisify } from "node:util";
1516
import { _electron as electron } from "playwright-core";
1617
import { expect, it, vi } from "vitest";
18+
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
1719

1820
import {
1921
createSystemProcessOwnershipHost,
@@ -41,10 +43,10 @@ const state = fs.existsSync(statePath)
4143
? JSON.parse(fs.readFileSync(statePath, "utf8"))
4244
: { calls: 0 };
4345
state.calls += 1;
44-
const moduleIndex = process.argv.indexOf("-module-cache-path");
45-
state.root = path.dirname(process.argv[moduleIndex + 1]);
4646
const outputIndex = process.argv.indexOf("-o");
4747
state.output = process.argv[outputIndex + 1];
48+
state.root = path.dirname(state.output);
49+
state.arguments = process.argv.slice(2);
4850
state.releasePath = releasePath;
4951
fs.writeFileSync(statePath, JSON.stringify(state));
5052
if (state.calls === 1) {
@@ -106,6 +108,10 @@ const waitForCompileState = async (statePath: string) => {
106108
root: parsed.root,
107109
output: parsed.output,
108110
releasePath: parsed.releasePath,
111+
arguments:
112+
"arguments" in parsed && Array.isArray(parsed.arguments)
113+
? parsed.arguments
114+
: [],
109115
};
110116
} catch {
111117
await new Promise((resolve) => setTimeout(resolve, 10));
@@ -161,6 +167,87 @@ it("reports an actionable missing Swift compiler without installing it", async (
161167
}
162168
});
163169

170+
it.skipIf(process.platform === "win32")(
171+
"preserves compiler diagnostics when Swift preparation fails",
172+
async () => {
173+
const directory = await createTestTempDirectory(
174+
"rea-process-token-compiler-failure-test-",
175+
);
176+
const executable = join(directory, "failing-xcrun");
177+
await writeFile(
178+
executable,
179+
'#!/usr/bin/env node\nprocess.stderr.write("module cache is not writable\\n"); process.exitCode = 1;\n',
180+
);
181+
await chmod(executable, 0o755);
182+
const reader = createDarwinProcessRunTokenReader({ xcrun: executable });
183+
try {
184+
await expect(reader.prepare()).rejects.toThrow(
185+
/compilation failed.*module cache is not writable/su,
186+
);
187+
} finally {
188+
await reader.close();
189+
}
190+
},
191+
);
192+
193+
it
194+
.skipIf(!onDarwin || process.getuid?.() === 0)
195+
.each(["file", "read-only directory"])(
196+
"ignores unusable inherited Swift module cache: %s",
197+
async (kind) => {
198+
const directory = await createTestTempDirectory(
199+
"rea-process-token-inherited-cache-test-",
200+
);
201+
const cacheParent = join(directory, "cache-parent");
202+
if (kind === "file") await writeFile(cacheParent, "not a directory");
203+
else {
204+
await mkdir(cacheParent);
205+
await chmod(cacheParent, 0o500);
206+
}
207+
const cachePath = join(cacheParent, "modules");
208+
vi.stubEnv("CLANG_MODULE_CACHE_PATH", cachePath);
209+
const reader = createDarwinProcessRunTokenReader();
210+
try {
211+
const executable = await reader.prepare();
212+
const { stdout } = await execFileOutput(
213+
executable,
214+
["--identities", String(process.pid)],
215+
{ timeout: 15_000 },
216+
);
217+
expect(JSON.parse(stdout)).toMatchObject({
218+
results: [{ pid: process.pid, state: "readable" }],
219+
});
220+
expect(process.env.CLANG_MODULE_CACHE_PATH).toBe(cachePath);
221+
} finally {
222+
vi.unstubAllEnvs();
223+
if (kind === "read-only directory") await chmod(cacheParent, 0o700);
224+
await reader.close();
225+
}
226+
},
227+
);
228+
229+
it.skipIf(process.platform === "win32")(
230+
"uses the compiler-managed module cache instead of rebuilding system modules per REA process",
231+
async () => {
232+
const directory = await createTestTempDirectory(
233+
"rea-process-token-module-cache-test-",
234+
);
235+
const fakeCompiler = await writeBlockingCompiler(directory);
236+
const reader = createDarwinProcessRunTokenReader({
237+
xcrun: fakeCompiler.executable,
238+
});
239+
const preparation = reader.prepare();
240+
try {
241+
const state = await waitForCompileState(fakeCompiler.statePath);
242+
expect(state.arguments).not.toContain("-module-cache-path");
243+
await writeFile(fakeCompiler.releasePath, "release");
244+
await preparation;
245+
} finally {
246+
await Promise.all([reader.close(), Promise.allSettled([preparation])]);
247+
}
248+
},
249+
);
250+
164251
it.skipIf(process.platform === "win32")(
165252
"rethrows compile cancellation, removes its temporary root, and permits retry",
166253
async () => {

0 commit comments

Comments
 (0)