fix(process): add an opt-in Swift module cache (#2252)

* fix(process): add an opt-in Swift module cache

Signed-off-by: Charan Rathore <180254320+charan-rathore@users.noreply.github.com>

* fix(process): preserve caller-owned Swift module caches

Fold the complementary implementation from #2260 into the earlier #2252 proposal, retaining the original contribution history.

Co-authored-by: NIU-123370 <191000457+NIU-123370@users.noreply.github.com>

* fix(process): bypass xcrun lookup for explicit Swift toolchains

---------

Signed-off-by: Charan Rathore <180254320+charan-rathore@users.noreply.github.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
Co-authored-by: NIU-123370 <191000457+NIU-123370@users.noreply.github.com>
This commit is contained in:
Charan Rathore
2026-10-13 02:26:16 +08:00
committed by GitHub
co-authored by morluto NIU-123370
parent f941968eb1
commit 47a51b08f4
4 changed files with 392 additions and 38 deletions
@@ -5,6 +5,7 @@ import {
mkdir,
mkdtemp,
readFile,
readdir,
rm,
symlink,
writeFile,
@@ -156,7 +157,10 @@ type ElectronCaptureOutcome =
it("reports an actionable missing Swift compiler without installing it", async () => {
const reader = createDarwinProcessRunTokenReader({
xcrun: join(tmpdir(), "rea-no-such-xcrun"),
compiler: {
kind: "xcrun",
executable: join(tmpdir(), "rea-no-such-xcrun"),
},
});
try {
await expect(
@@ -198,7 +202,9 @@ it.skipIf(process.platform === "win32")(
'#!/usr/bin/env node\nprocess.stderr.write("module cache is not writable\\n" + "x".repeat(12000)); process.exitCode = 1;\n',
);
await chmod(executable, 0o755);
const reader = createDarwinProcessRunTokenReader({ xcrun: executable });
const reader = createDarwinProcessRunTokenReader({
compiler: { kind: "xcrun", executable: executable },
});
try {
const failure = await preparationFailure(reader);
expect(failure.compilerOutcome).toMatchObject({
@@ -248,7 +254,7 @@ it.skipIf(process.platform === "win32")(
);
await chmod(executable, 0o755);
const reader = createDarwinProcessRunTokenReader({
xcrun: executable,
compiler: { kind: "xcrun", executable: executable },
// Headroom for the child interpreter's cold start under suite load.
compileTimeoutMs: 3_000,
});
@@ -280,7 +286,9 @@ it.skipIf(process.platform === "win32")(
'#!/usr/bin/env node\nprocess.stderr.write("fatal: segmentation fault during type checking\\n");\nprocess.kill(process.pid, "SIGSEGV");\n',
);
await chmod(executable, 0o755);
const reader = createDarwinProcessRunTokenReader({ xcrun: executable });
const reader = createDarwinProcessRunTokenReader({
compiler: { kind: "xcrun", executable: executable },
});
try {
await expect(preparationFailure(reader)).resolves.toMatchObject({
message:
@@ -310,7 +318,9 @@ it.skipIf(process.platform === "win32")(
`#!/usr/bin/env node\nprocess.stderr.write(${JSON.stringify(`${diagnostic}\n`)}); process.exitCode = 1;\n`,
);
await chmod(executable, 0o755);
const reader = createDarwinProcessRunTokenReader({ xcrun: executable });
const reader = createDarwinProcessRunTokenReader({
compiler: { kind: "xcrun", executable: executable },
});
try {
const failure = await preparationFailure(reader);
const outcome = failure.compilerOutcome;
@@ -376,7 +386,7 @@ it.skipIf(process.platform === "win32")(
);
const fakeCompiler = await writeBlockingCompiler(directory);
const reader = createDarwinProcessRunTokenReader({
xcrun: fakeCompiler.executable,
compiler: { kind: "xcrun", executable: fakeCompiler.executable },
});
const preparation = reader.prepare();
try {
@@ -390,6 +400,242 @@ it.skipIf(process.platform === "win32")(
},
);
const writeCacheRecordingCompiler = async (directory: string) => {
const executable = join(directory, "fake-cache-xcrun");
const statePath = join(directory, "cache-compile-state.json");
const source = `#!/usr/bin/env node
const fs = process.getBuiltinModule("node:fs");
const path = process.getBuiltinModule("node:path");
const flagIndex = process.argv.indexOf("-module-cache-path");
const cache = flagIndex === -1 ? undefined : process.argv[flagIndex + 1];
fs.writeFileSync(${JSON.stringify(statePath)}, JSON.stringify({
arguments: process.argv.slice(2),
moduleCacheEnvironment: process.env.CLANG_MODULE_CACHE_PATH ?? null,
}));
if (cache !== undefined) {
fs.mkdirSync(cache, { recursive: true });
fs.writeFileSync(path.join(cache, "written-into-cache"), "kept");
}
const output = process.argv[process.argv.indexOf("-o") + 1];
fs.writeFileSync(output, "#!/bin/sh\\nexit 0\\n");
fs.chmodSync(output, 0o755);
`;
await writeFile(executable, source);
await chmod(executable, 0o755);
return { executable, statePath };
};
const readCacheCompileState = async (statePath: string) =>
JSON.parse(await readFile(statePath, "utf8")) as {
arguments: string[];
moduleCacheEnvironment: string | null;
};
const existsPath = async (target: string) =>
access(target).then(
() => true,
() => false,
);
it.skipIf(process.platform === "win32")(
"forwards a caller-owned module cache and keeps it after the helper root is removed",
async () => {
const directory = await createTestTempDirectory(
"rea-process-token-caller-cache-test-",
);
const cachePath = join(directory, "caller", " modules ");
const fakeCompiler = await writeCacheRecordingCompiler(directory);
const reader = createDarwinProcessRunTokenReader({
compiler: { kind: "xcrun", executable: fakeCompiler.executable },
moduleCachePath: cachePath,
});
let executable: string;
try {
executable = await reader.prepare();
} finally {
await reader.close();
}
const state = await readCacheCompileState(fakeCompiler.statePath);
const flagIndex = state.arguments.indexOf("-module-cache-path");
expect(state.arguments[0]).toBe("swiftc");
expect(flagIndex).toBe(1);
expect(state.arguments[flagIndex + 1]).toBe(cachePath);
expect(state.moduleCacheEnvironment).toBe(cachePath);
expect(await existsPath(join(cachePath, "written-into-cache"))).toBe(true);
expect(await existsPath(executable)).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"selects the caller module cache through REA_DARWIN_MODULE_CACHE_PATH",
async () => {
const directory = await createTestTempDirectory(
"rea-process-token-host-cache-test-",
);
const cachePath = join(directory, "from-environment", "modules");
const fakeCompiler = await writeCacheRecordingCompiler(directory);
const host = createSystemProcessOwnershipHost(
"darwin",
{ ...process.env, REA_DARWIN_MODULE_CACHE_PATH: cachePath },
{
darwinCompiler: { kind: "xcrun", executable: fakeCompiler.executable },
},
);
try {
await host.prepare?.(AbortSignal.timeout(15_000));
const state = await readCacheCompileState(fakeCompiler.statePath);
const flagIndex = state.arguments.indexOf("-module-cache-path");
expect(state.arguments[flagIndex + 1]).toBe(cachePath);
} finally {
await host.close?.();
}
},
);
it.skipIf(process.platform === "win32")(
"keeps the shared module cache for the system host without the setting",
async () => {
const directory = await createTestTempDirectory(
"rea-process-token-host-default-test-",
);
vi.stubEnv("CLANG_MODULE_CACHE_PATH", join(directory, "ambient-cache"));
const hostEnvironment = { ...process.env };
delete hostEnvironment.REA_DARWIN_MODULE_CACHE_PATH;
const fakeCompiler = await writeCacheRecordingCompiler(directory);
const host = createSystemProcessOwnershipHost("darwin", hostEnvironment, {
darwinCompiler: { kind: "xcrun", executable: fakeCompiler.executable },
});
try {
await host.prepare?.(AbortSignal.timeout(15_000));
const state = await readCacheCompileState(fakeCompiler.statePath);
expect(state.arguments).not.toContain("-module-cache-path");
expect(state.moduleCacheEnvironment).toBeNull();
} finally {
await host.close?.();
}
},
);
it.skipIf(process.platform === "win32")(
"bypasses xcrun for an explicitly selected Swift compiler and SDK",
async () => {
const directory = await createTestTempDirectory(
"rea-process-token-direct-compiler-",
);
const fakeCompiler = await writeCacheRecordingCompiler(directory);
const sdkRoot = join(directory, "MacOSX.sdk");
const cachePath = join(directory, "modules");
const host = createSystemProcessOwnershipHost("darwin", {
...process.env,
REA_DARWIN_SWIFTC_PATH: fakeCompiler.executable,
SDKROOT: sdkRoot,
REA_DARWIN_MODULE_CACHE_PATH: cachePath,
});
try {
await host.prepare?.(AbortSignal.timeout(15_000));
const state = await readCacheCompileState(fakeCompiler.statePath);
expect(state.arguments.slice(0, 2)).toEqual(["-sdk", sdkRoot]);
expect(state.arguments).not.toContain("swiftc");
expect(state.arguments).toContain(cachePath);
} finally {
await host.close?.();
}
},
);
it.skipIf(process.platform === "win32")(
"reports the missing SDK prerequisite before starting a direct compiler",
async () => {
const directory = await createTestTempDirectory(
"rea-process-token-direct-no-sdk-",
);
const fakeCompiler = await writeCacheRecordingCompiler(directory);
const host = createSystemProcessOwnershipHost("darwin", {
...process.env,
REA_DARWIN_SWIFTC_PATH: fakeCompiler.executable,
SDKROOT: "",
});
try {
await expect(
host.prepare?.(AbortSignal.timeout(15_000)),
).rejects.toMatchObject({
name: "DarwinProcessOwnershipInspectionError",
message: expect.stringContaining("REA_DARWIN_SWIFTC_PATH and SDKROOT"),
});
expect(await existsPath(fakeCompiler.statePath)).toBe(false);
} finally {
await host.close?.();
}
},
);
it.skipIf(process.platform === "win32")(
"identifies a missing selected Swift compiler rather than xcrun",
async () => {
const directory = await createTestTempDirectory(
"rea-process-token-direct-missing-",
);
const host = createSystemProcessOwnershipHost("darwin", {
...process.env,
REA_DARWIN_SWIFTC_PATH: join(directory, "missing-swiftc"),
SDKROOT: join(directory, "MacOSX.sdk"),
});
try {
await expect(
host.prepare?.(AbortSignal.timeout(15_000)),
).rejects.toMatchObject({
message: expect.stringContaining(
"selected Swift compiler (REA_DARWIN_SWIFTC_PATH)",
),
compilerOutcome: expect.objectContaining({
outcome: "spawn_failed",
code: "ENOENT",
}),
});
} finally {
await host.close?.();
}
},
);
it.skipIf(!onDarwin)(
"compiles the helper against the caller cache with the host compiler",
async () => {
const directory = await createTestTempDirectory(
"rea-process-token-real-cache-test-",
);
const cachePath = join(directory, "caller", "modules");
const { stdout: compilerPath } = await execFileAsync("/usr/bin/xcrun", [
"--find",
"swiftc",
]);
const { stdout: sdkRoot } = await execFileAsync("/usr/bin/xcrun", [
"--show-sdk-path",
]);
const host = createSystemProcessOwnershipHost("darwin", {
...process.env,
REA_DARWIN_MODULE_CACHE_PATH: cachePath,
REA_DARWIN_SWIFTC_PATH: compilerPath.trim(),
SDKROOT: sdkRoot.trim(),
});
try {
await host.prepare?.(AbortSignal.timeout(180_000));
const entries = await readdir(cachePath);
expect(
entries.some(
(name) =>
name.endsWith(".swiftmodule") ||
name.endsWith(".pcm") ||
name === "Modules",
),
).toBe(true);
} finally {
await host.close?.();
}
expect(await existsPath(join(directory, "caller"))).toBe(true);
},
);
it.skipIf(process.platform === "win32")(
"rethrows compile cancellation, removes its temporary root, and permits retry",
async () => {
@@ -398,7 +644,7 @@ it.skipIf(process.platform === "win32")(
);
const fakeCompiler = await writeBlockingCompiler(directory);
const reader = createDarwinProcessRunTokenReader({
xcrun: fakeCompiler.executable,
compiler: { kind: "xcrun", executable: fakeCompiler.executable },
});
const controller = new AbortController();
const compilation = reader.prepare(controller.signal).then(
@@ -483,7 +729,7 @@ it.skipIf(process.platform === "win32")(
);
const compiler = await writeTemporaryObjectCompiler(directory);
const reader = createDarwinProcessRunTokenReader({
xcrun: compiler.executable,
compiler: { kind: "xcrun", executable: compiler.executable },
});
const controller = new AbortController();
const preparation = reader.prepare(controller.signal).then(
@@ -532,7 +778,7 @@ it.skipIf(process.platform === "win32").each(["first", "second"] as const)(
);
const fakeCompiler = await writeBlockingCompiler(directory);
const reader = createDarwinProcessRunTokenReader({
xcrun: fakeCompiler.executable,
compiler: { kind: "xcrun", executable: fakeCompiler.executable },
});
const firstController = new AbortController();
const secondController = new AbortController();
@@ -590,7 +836,7 @@ it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
);
const fakeCompiler = await writeBlockingCompiler(directory);
const reader = createDarwinProcessRunTokenReader({
xcrun: fakeCompiler.executable,
compiler: { kind: "xcrun", executable: fakeCompiler.executable },
});
const controller = new AbortController();
const preparation = reader.prepare(controller.signal).then(
@@ -631,7 +877,7 @@ it.skipIf(process.platform === "win32")(
);
const fakeCompiler = await writeBlockingCompiler(directory);
const reader = createDarwinProcessRunTokenReader({
xcrun: fakeCompiler.executable,
compiler: { kind: "xcrun", executable: fakeCompiler.executable },
});
const preparation = reader.prepare().then(
() => ({ state: "fulfilled" as const }),
@@ -664,7 +910,7 @@ it.skipIf(process.platform === "win32")(
);
const fakeCompiler = await writeBlockingCompiler(directory);
const reader = createDarwinProcessRunTokenReader({
xcrun: fakeCompiler.executable,
compiler: { kind: "xcrun", executable: fakeCompiler.executable },
});
const prepareSpy = vi
.spyOn(systemProcessOwnershipHost, "prepare")
@@ -716,7 +962,7 @@ it.skipIf(process.platform === "win32").each(["baseline", "tokens"] as const)(
);
const fakeCompiler = await writeBlockingIdentityCompiler(directory);
const host = createSystemProcessOwnershipHost("darwin", process.env, {
darwinXcrun: fakeCompiler.executable,
darwinCompiler: { kind: "xcrun", executable: fakeCompiler.executable },
});
const controller = new AbortController();
let helperRoot: string | undefined;
@@ -775,7 +1021,7 @@ it.skipIf(process.platform === "win32")(
);
const fakeCompiler = await writeBlockingIdentityCompiler(directory);
const reader = createDarwinProcessRunTokenReader({
xcrun: fakeCompiler.executable,
compiler: { kind: "xcrun", executable: fakeCompiler.executable },
});
const prepareSpy = vi
.spyOn(systemProcessOwnershipHost, "prepare")