Skip to content

Commit 811c3e3

Browse files
feat(daemon): report the host CPU architecture in /health (#3048)
* feat(daemon): report the host CPU architecture in /health (#3047) * fix(apple): pick the Mac runner and simulator build arch from the host CPU (#3047) * chore(gates): acknowledge the additive hostArch health field in the wire ledger * fix(host-kit): resolve the host CPU arch in host-process so process imports load no new modules The eager-closure gate refused the separate host-cpu-arch module: it added it and kernel/ttl-memo to every closure that imports @agent-device/host-kit/process. host-process.ts already loads the exec helpers the sysctl probe needs, so the arch helpers live there with plain module state, and their tests reset the module between cases. --------- Co-authored-by: Michał Pierzchała <[email protected]>
1 parent e0474a0 commit 811c3e3

26 files changed

Lines changed: 419 additions & 59 deletions

‎packages/contracts/src/daemon-http.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,20 +56,22 @@ export type DaemonHealthPayload = {
5656
version: string;
5757
rpcProtocolVersion: number;
5858
instanceId?: string;
59+
hostArch?: string;
5960
upstream?: unknown;
6061
};
6162

6263
export function buildDaemonHealthPayload(
6364
service: DaemonHealthPayload['service'],
6465
version: string,
65-
options: { upstream?: unknown; instanceId?: string } = {},
66+
options: { upstream?: unknown; instanceId?: string; hostArch?: string } = {},
6667
): DaemonHealthPayload {
6768
return {
6869
ok: true,
6970
service,
7071
version,
7172
rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION,
7273
...(options.instanceId !== undefined ? { instanceId: options.instanceId } : {}),
74+
...(options.hostArch !== undefined ? { hostArch: options.hostArch } : {}),
7375
...(options.upstream !== undefined ? { upstream: options.upstream } : {}),
7476
};
7577
}
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
import assert from 'node:assert/strict';
2+
import { beforeEach, test, vi } from 'vitest';
3+
import type { CommandExecutorOverride } from './exec.ts';
4+
5+
const { mockRunCmdSync } = vi.hoisted(() => ({ mockRunCmdSync: vi.fn() }));
6+
7+
vi.mock('./exec.ts', async (importOriginal) => ({
8+
...(await importOriginal<typeof import('./exec.ts')>()),
9+
runCmdSync: mockRunCmdSync,
10+
}));
11+
12+
let withCommandExecutorOverride: typeof import('./exec.ts').withCommandExecutorOverride;
13+
let readHostCpuArch: typeof import('./host-process.ts').readHostCpuArch;
14+
let readHostCpuArchSync: typeof import('./host-process.ts').readHostCpuArchSync;
15+
let resolveHostCpuArch: typeof import('./host-process.ts').resolveHostCpuArch;
16+
17+
// The host CPU arch is resolved once per module instance, so each test gets a fresh one.
18+
beforeEach(async () => {
19+
mockRunCmdSync.mockReset();
20+
vi.resetModules();
21+
({ withCommandExecutorOverride } = await import('./exec.ts'));
22+
({ readHostCpuArch, readHostCpuArchSync, resolveHostCpuArch } =
23+
await import('./host-process.ts'));
24+
});
25+
26+
function sysctlAnswering(result: { stdout?: string; exitCode?: number } | Error) {
27+
const calls: string[][] = [];
28+
const override: CommandExecutorOverride = async (command, args) => {
29+
calls.push([command, ...args]);
30+
if (result instanceof Error) throw result;
31+
return { stdout: result.stdout ?? '', stderr: '', exitCode: result.exitCode ?? 0 };
32+
};
33+
return { calls, override };
34+
}
35+
36+
test('an Apple silicon Mac reports arm64 even when Node runs as x64 under Rosetta', async () => {
37+
const sysctl = sysctlAnswering({ stdout: '1\n' });
38+
const arch = await withCommandExecutorOverride(sysctl.override, () =>
39+
resolveHostCpuArch('darwin', 'x64'),
40+
);
41+
assert.equal(arch, 'arm64');
42+
assert.deepEqual(sysctl.calls, [['/usr/sbin/sysctl', '-n', 'hw.optional.arm64']]);
43+
});
44+
45+
test('a Mac without the arm64 sysctl key falls back to the Node arch in Apple naming', async () => {
46+
for (const answer of [
47+
{ stdout: '', exitCode: 1 },
48+
{ stdout: '0\n' },
49+
new Error('spawn /usr/sbin/sysctl ENOENT'),
50+
]) {
51+
const sysctl = sysctlAnswering(answer);
52+
const arch = await withCommandExecutorOverride(sysctl.override, () =>
53+
resolveHostCpuArch('darwin', 'x64'),
54+
);
55+
assert.equal(arch, 'x86_64');
56+
}
57+
});
58+
59+
test('other platforms report the Node arch without running sysctl', async () => {
60+
const sysctl = sysctlAnswering({ stdout: '1\n' });
61+
await withCommandExecutorOverride(sysctl.override, async () => {
62+
assert.equal(await resolveHostCpuArch('linux', 'x64'), 'x86_64');
63+
assert.equal(await resolveHostCpuArch('linux', 'arm64'), 'arm64');
64+
assert.equal(await resolveHostCpuArch('linux', 'ppc64'), 'ppc64');
65+
});
66+
assert.deepEqual(sysctl.calls, []);
67+
});
68+
69+
async function asDarwinX64Process(run: () => Promise<void>): Promise<void> {
70+
const platform = Object.getOwnPropertyDescriptor(process, 'platform')!;
71+
const arch = Object.getOwnPropertyDescriptor(process, 'arch')!;
72+
Object.defineProperty(process, 'platform', { ...platform, value: 'darwin' });
73+
Object.defineProperty(process, 'arch', { ...arch, value: 'x64' });
74+
try {
75+
await run();
76+
} finally {
77+
Object.defineProperty(process, 'platform', platform);
78+
Object.defineProperty(process, 'arch', arch);
79+
}
80+
}
81+
82+
test('the per-process value a Rosetta-translated process resolves is the one sync callers read', async () => {
83+
await asDarwinX64Process(async () => {
84+
const sysctl = sysctlAnswering({ stdout: '1\n' });
85+
const resolved = await withCommandExecutorOverride(sysctl.override, () => readHostCpuArch());
86+
assert.equal(resolved, 'arm64');
87+
assert.equal(readHostCpuArchSync(), 'arm64');
88+
assert.equal(sysctl.calls.length, 1);
89+
assert.equal(mockRunCmdSync.mock.calls.length, 0);
90+
});
91+
});
92+
93+
test('a Rosetta-translated process resolves arm64 through the sync path first, and async callers share it', async () => {
94+
await asDarwinX64Process(async () => {
95+
mockRunCmdSync.mockReturnValue({ stdout: '1\n', stderr: '', exitCode: 0 });
96+
assert.equal(readHostCpuArchSync(), 'arm64');
97+
assert.deepEqual(
98+
mockRunCmdSync.mock.calls.map(([command, args]) => [command, ...args]),
99+
[['/usr/sbin/sysctl', '-n', 'hw.optional.arm64']],
100+
);
101+
102+
const sysctl = sysctlAnswering({ stdout: '0\n' });
103+
const resolved = await withCommandExecutorOverride(sysctl.override, () => readHostCpuArch());
104+
assert.equal(resolved, 'arm64');
105+
assert.deepEqual(sysctl.calls, []);
106+
});
107+
});
108+
109+
test('a sync read on an Intel Mac reports x86_64', async () => {
110+
await asDarwinX64Process(async () => {
111+
mockRunCmdSync.mockReturnValue({ stdout: '', stderr: '', exitCode: 1 });
112+
assert.equal(readHostCpuArchSync(), 'x86_64');
113+
});
114+
});

‎packages/host-kit/src/internal/host-process.ts‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,3 +288,76 @@ export async function stopPidsWithEscalation(
288288
signalPidsBestEffort(livePids, 'SIGKILL');
289289
await Promise.all(pids.map(async (pid) => await waitForProcessExit(pid, options.killTimeoutMs)));
290290
}
291+
292+
const SYSCTL_TIMEOUT_MS = 1_000;
293+
const APPLE_SILICON_SYSCTL = ['-n', 'hw.optional.arm64'] as const;
294+
295+
let pendingHostCpuArch: Promise<string> | undefined;
296+
let settledHostCpuArch: string | undefined;
297+
298+
/**
299+
* The machine's native CPU architecture in Apple naming (`arm64`, `x86_64`), which is what
300+
* simulators on a Mac run by default. Other CPUs keep Node's `process.arch` name. Resolved once
301+
* per process.
302+
*/
303+
export function readHostCpuArch(): Promise<string> {
304+
if (settledHostCpuArch !== undefined) return Promise.resolve(settledHostCpuArch);
305+
pendingHostCpuArch ??= resolveHostCpuArch(process.platform, process.arch).then(settleHostCpuArch);
306+
return pendingHostCpuArch;
307+
}
308+
309+
/**
310+
* {@link readHostCpuArch} for a caller that cannot await. It shares the same per-process value,
311+
* resolving it with a blocking `sysctl` only when nothing has resolved it yet.
312+
*/
313+
export function readHostCpuArchSync(): string {
314+
return (
315+
settledHostCpuArch ??
316+
settleHostCpuArch(
317+
hostCpuArchName(process.platform === 'darwin' && isAppleSiliconMacSync(), process.arch),
318+
)
319+
);
320+
}
321+
322+
function settleHostCpuArch(arch: string): string {
323+
settledHostCpuArch ??= arch;
324+
return settledHostCpuArch;
325+
}
326+
327+
export async function resolveHostCpuArch(
328+
platform: NodeJS.Platform,
329+
nodeArch: string,
330+
): Promise<string> {
331+
return hostCpuArchName(platform === 'darwin' && (await isAppleSiliconMac()), nodeArch);
332+
}
333+
334+
function hostCpuArchName(appleSilicon: boolean, nodeArch: string): string {
335+
if (appleSilicon) return 'arm64';
336+
return nodeArch === 'x64' ? 'x86_64' : nodeArch;
337+
}
338+
339+
// macOS: `hw.optional.arm64` is 1 on Apple silicon even inside a Rosetta-translated process,
340+
// where `process.arch` reports x64; Intel Macs do not define the key.
341+
async function isAppleSiliconMac(): Promise<boolean> {
342+
try {
343+
const result = await runCmd('/usr/sbin/sysctl', APPLE_SILICON_SYSCTL, {
344+
allowFailure: true,
345+
timeoutMs: SYSCTL_TIMEOUT_MS,
346+
});
347+
return result.exitCode === 0 && result.stdout.trim() === '1';
348+
} catch {
349+
return false;
350+
}
351+
}
352+
353+
function isAppleSiliconMacSync(): boolean {
354+
try {
355+
const result = runCmdSync('/usr/sbin/sysctl', APPLE_SILICON_SYSCTL, {
356+
allowFailure: true,
357+
timeoutMs: SYSCTL_TIMEOUT_MS,
358+
});
359+
return result.exitCode === 0 && result.stdout.trim() === '1';
360+
} catch {
361+
return false;
362+
}
363+
}

‎packages/host-kit/src/process.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ export {
1313
isProcessGroupAlive,
1414
isProcessZombie,
1515
listHostProcesses,
16+
readHostCpuArch,
17+
readHostCpuArchSync,
1618
readHostEnvironmentVariable,
1719
readHostProcessIdentityObservations,
1820
readProcessCommand,
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import assert from 'node:assert/strict';
2+
import { test } from 'vitest';
3+
import { withCommandExecutorOverride } from '@agent-device/host-kit/command';
4+
import { readHostCpuArch } from '@agent-device/host-kit/process';
5+
import '../runner-client.ts';
6+
import {
7+
resolveRunnerBuildDestination,
8+
resolveRunnerBuildDestinationFamily,
9+
resolveRunnerDestination,
10+
} from '../../runner/apple-runner-platform.ts';
11+
import { MACOS_DEVICE } from '../../runner/__tests__/device-fixtures.ts';
12+
13+
test('the macOS runner destinations name arm64 when Node runs as x64 under Rosetta', async () => {
14+
const platform = Object.getOwnPropertyDescriptor(process, 'platform')!;
15+
const arch = Object.getOwnPropertyDescriptor(process, 'arch')!;
16+
Object.defineProperty(process, 'platform', { ...platform, value: 'darwin' });
17+
Object.defineProperty(process, 'arch', { ...arch, value: 'x64' });
18+
try {
19+
await withCommandExecutorOverride(
20+
async (command, args) => {
21+
assert.deepEqual([command, ...args], ['/usr/sbin/sysctl', '-n', 'hw.optional.arm64']);
22+
return { stdout: '1\n', stderr: '', exitCode: 0 };
23+
},
24+
() => readHostCpuArch(),
25+
);
26+
for (const destination of [
27+
resolveRunnerDestination(MACOS_DEVICE),
28+
resolveRunnerBuildDestination(MACOS_DEVICE),
29+
resolveRunnerBuildDestinationFamily(MACOS_DEVICE),
30+
]) {
31+
assert.equal(destination, 'platform=macOS,arch=arm64');
32+
}
33+
} finally {
34+
Object.defineProperty(process, 'platform', platform);
35+
Object.defineProperty(process, 'arch', arch);
36+
}
37+
});

‎packages/platform-apple/src/core/runner-host.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
signalPidsBestEffort,
1919
signalProcessGroupBestEffort,
2020
classifyOwnerLiveness,
21+
readHostCpuArchSync,
2122
} from '@agent-device/host-kit/process';
2223
import { Deadline, isEnvTruthy, retryWithPolicy } from '@agent-device/host-kit/retry';
2324

@@ -82,6 +83,7 @@ export const appleRunnerHost: AppleRunnerHost = {
8283
withKeyedLock,
8384
publishFileSync,
8485
classifyOwnerLiveness,
86+
readHostCpuArchSync,
8587
createTtlMemo,
8688
parseBooleanLiteral,
8789
isRecord,

‎packages/platform-apple/src/foldable/fold-helper-cache.test.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ function fakeFoldHelperHost(
2121
const real = createSnapshotSourceHost();
2222
return {
2323
...real,
24+
cpuArch: async () => 'arm64',
2425
run: async (command, args) => {
2526
if (command === 'xcrun' && args.includes('clang')) {
2627
const outputPath = args.at(-1)!;
@@ -34,9 +35,7 @@ function fakeFoldHelperHost(
3435
? args.includes('-buildVersion')
3536
? '24G90'
3637
: '15.6'
37-
: command === 'uname'
38-
? 'arm64'
39-
: '';
38+
: '';
4039
return { stdout, stderr: '', exitCode: 0 };
4140
},
4241
};

‎packages/platform-apple/src/native-build/host.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,11 @@ import {
1010
renameHostPath,
1111
writeHostTextFile,
1212
} from '@agent-device/host-kit/host-file';
13-
import { hostProcessId, readProcessStartTime } from '@agent-device/host-kit/process';
13+
import {
14+
hostProcessId,
15+
readHostCpuArch,
16+
readProcessStartTime,
17+
} from '@agent-device/host-kit/process';
1418
import { NativeBuildError, nativeBuildError } from './errors.ts';
1519
import { remainingNativeBuildMs, type NativeBuildDeadline } from './deadline.ts';
1620

@@ -35,6 +39,7 @@ export type NativeBuildHost = Readonly<{
3539
options: { deadline: NativeBuildDeadline; description: string },
3640
): Promise<() => Promise<void>>;
3741
processId(): number;
42+
cpuArch(): Promise<string>;
3843
}>;
3944

4045
export function createNativeBuildHost(run: NativeBuildHost['run']): NativeBuildHost {
@@ -50,6 +55,7 @@ export function createNativeBuildHost(run: NativeBuildHost['run']): NativeBuildH
5055
remove: removeHostPath,
5156
acquireLock: acquireNativeBuildLock,
5257
processId: hostProcessId,
58+
cpuArch: readHostCpuArch,
5359
};
5460
}
5561

0 commit comments

Comments
 (0)