Skip to content

Commit 26db9d0

Browse files
authored
refactor(ios): name the runner session xctestrun as a process-identity contract (#2987)
* refactor(ios-runner): name the runner session xctestrun as a process-identity contract A runner launch is killed by matching `xcodebuild`'s argv with `pkill -f`, and that argv carries the per-session xctestrun's filename. The filename is therefore a process-identity contract, but it was spelled three times: inline in the session, inline in disposal, and again in the daemon-client timeout sweep. Disposal escaped the device id for regex without flattening it the way the writer's filesystem sanitization does, so a device id needing flattening built a cleanup pattern that could not match the file the writer had already written. Name it once. `runner-artifact-env.ts` now owns the stem, the suffix field order, the sanitization, and the `pkill -f` pattern derived from those same parts, and the writer, the session, and disposal all go through it. The name lives in the writer rather than a shared contracts module because the timeout sweep must not follow a rename: it ships separately, cannot know which version named a timed-out launch, and has to keep matching the names older writers used. So the sweep keeps a pinned literal, and its test proves those bytes still select both the owner-token and the pre-owner-token spelling. Placing the name in the module the Apple façades already evaluate also holds the eager-closure budget (#1960) at zero new edges. Verified byte-for-byte against the previous patterns for concrete, host-style, and flattened device ids. The only divergence is the flattened case, where the old pattern failed to match its own file. Also record three tooling constraints read from `xcodebuild(1)` and `simctl help`, and checked on Xcode 27.1: only `TEST_RUNNER_`-prefixed names cross into the test runner; `simctl launch --stdout/--stderr` resolve their paths inside the device's data container, so `--console-pty` is the console mode this host path can use; and xcodebuild re-synthesizes the attachment-lifetime keys from its own defaults, since a plan setting `keepNever` still builds an xctestrun carrying `SystemAttachmentLifetime=deleteOnSuccess`. * refactor(ios-runner): reclaim a leased launch by the artifact the lease recorded A detached lease rewrites its owner token to `detached-<token>` while the xcodebuild it handed over keeps running under the name the writer gave it, so the token-derived pkill pattern named a file that never existed and the launch survived the reclaim. Lease-backed cleanup now follows the recorded xctestrun basename, which is exactly the argv the launch carries; the device sweep stays for the no-lease case, and the token branch of the old builder is removed. * test(ios-runner): put the reclaim pattern claim in the module that builds it Driving `runnerLeaseCleanupAdapter` directly proves the pkill bytes disposal issues select the launch a lease names, without session-startup choreography. Moves the detached-lease coverage out of the aggregated session suite, which the test-file size ratchet forbids growing.
1 parent 1354fa0 commit 26db9d0

13 files changed

Lines changed: 403 additions & 31 deletions

‎packages/platform-apple/src/core/app-launch.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,10 @@ function buildIosSimulatorLaunchArgs(
291291
options?: { launchConsole?: string; launchArgs?: string[]; terminateRunningApp?: boolean },
292292
): string[] {
293293
const args = ['launch'];
294+
// `--console-pty` is the console mode this path needs: simctl writes the app's bytes to its own
295+
// stdout through a PTY, which is what the caller redirects. `--stdout=<path>`/`--stderr=<path>`
296+
// cannot substitute, because they resolve the given path inside the device's data container
297+
// rather than on the host. Verified on Xcode 27.1.
294298
if (options?.launchConsole) args.push('--console-pty');
295299
if (options?.terminateRunningApp) args.push('--terminate-running-process');
296300
args.push(deviceId, bundleId);
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
import assert from 'node:assert/strict';
2+
import path from 'node:path';
3+
import { test } from 'vitest';
4+
import {
5+
buildRunnerSessionXctestrunDeviceCleanupPattern,
6+
buildRunnerSessionXctestrunPathCleanupPattern,
7+
buildRunnerSessionXctestrunSuffix,
8+
} from '../runner-artifact-env.ts';
9+
10+
// Released daemons and clients pkill runner launches by these exact bytes, and the timeout client
11+
// pins its own copy rather than deriving it, so it survives a rename here. Each expectation below
12+
// is a literal on purpose: deriving it from this same module would survive any rename, which is
13+
// precisely the change these lines exist to catch.
14+
15+
const OWNED_ARTIFACT_PATH =
16+
'/derived/Build/Products/AgentDeviceRunner.env.session-SIM-001-owner-4242-ab12cd34-8123.xctestrun';
17+
18+
test('the session suffix keeps the bytes and field order the matchers rely on', () => {
19+
assert.equal(
20+
buildRunnerSessionXctestrunSuffix({
21+
deviceId: 'SIM-001',
22+
ownerToken: 'owner-4242-ab12cd34',
23+
port: 8123,
24+
}),
25+
'session-SIM-001-owner-4242-ab12cd34-8123',
26+
);
27+
});
28+
29+
test('the lease cleanup pattern keeps the bytes released daemons pkilled', () => {
30+
const owned = buildRunnerSessionXctestrunPathCleanupPattern(OWNED_ARTIFACT_PATH);
31+
32+
assert.equal(
33+
owned,
34+
String.raw`AgentDeviceRunner\.env\.session-SIM-001-owner-4242-ab12cd34-8123\.xctestrun`,
35+
);
36+
assert.equal(new RegExp(owned ?? '').test(argvFor(path.basename(OWNED_ARTIFACT_PATH))), true);
37+
assert.equal(
38+
new RegExp(owned ?? '').test(argvFor(sessionFileName('SIM-002', 'owner-4242-ab12cd34'))),
39+
false,
40+
'another device must not match',
41+
);
42+
assert.equal(
43+
new RegExp(owned ?? '').test(argvFor(sessionFileName('SIM-001', 'owner-9999-ffee00'))),
44+
false,
45+
'another owner must not match',
46+
);
47+
assert.equal(
48+
new RegExp(owned ?? '').test(
49+
argvFor('AgentDeviceRunner.env.session-SIM-001-owner-4242-ab12cd34-8124.xctestrun'),
50+
),
51+
false,
52+
'the same session on another port must not match',
53+
);
54+
});
55+
56+
test('the device sweep pattern keeps selecting the pre-owner-token name and only that', () => {
57+
// A reclaiming daemon with no lease to read knows the device but not the artifact, so it sweeps by
58+
// device. The released bytes require a digit right after the device, which is the pre-owner-token
59+
// spelling; an owner-token name needs its own path to be selected.
60+
const sweep = buildRunnerSessionXctestrunDeviceCleanupPattern('SIM-002');
61+
62+
assert.equal(sweep, String.raw`AgentDeviceRunner\.env\.session-SIM-002-[0-9]`);
63+
assert.equal(
64+
new RegExp(sweep).test(argvFor('AgentDeviceRunner.env.session-SIM-002-8123.xctestrun')),
65+
true,
66+
);
67+
assert.equal(
68+
new RegExp(sweep).test(argvFor(sessionFileName('SIM-002', 'owner-1-ff'))),
69+
false,
70+
'a launch a lease still names must not fall to the device sweep',
71+
);
72+
});
73+
74+
test('a flattened name field stays selectable', () => {
75+
// A device id is caller-supplied and the writer flattens it onto disk, so both matchers have to
76+
// survive that flattening: the recorded path already holds the bytes the launch carries, and the
77+
// device sweep has to flatten the id it spells.
78+
const suffix = buildRunnerSessionXctestrunSuffix({
79+
deviceId: 'SIM 01/x',
80+
ownerToken: 'owner 7',
81+
port: 80,
82+
});
83+
84+
assert.equal(suffix, 'session-SIM_01_x-owner_7-80');
85+
const flattenedPath = `/derived/Build/Products/AgentDeviceRunner.env.${suffix}.xctestrun`;
86+
assert.equal(
87+
new RegExp(buildRunnerSessionXctestrunPathCleanupPattern(flattenedPath) ?? '').test(
88+
argvFor(`AgentDeviceRunner.env.${suffix}.xctestrun`),
89+
),
90+
true,
91+
);
92+
// The pre-owner-token spelling of the same flattened device, which is the only name a sweep selects.
93+
assert.equal(
94+
new RegExp(buildRunnerSessionXctestrunDeviceCleanupPattern('SIM 01/x')).test(
95+
argvFor('AgentDeviceRunner.env.session-SIM_01_x-8123.xctestrun'),
96+
),
97+
true,
98+
);
99+
});
100+
101+
test('a detached lease still selects the launch it started', () => {
102+
// Detaching rewrites `ownerToken` to `detached-<token>` while the launch keeps running under the
103+
// name the writer gave it. The bytes a token-derived pattern would have carried are spelled here
104+
// literally: they select a file that never existed, which is the gap following the recorded path
105+
// closes.
106+
const detachedTokenPattern = String.raw`AgentDeviceRunner\.env\.session-SIM-001-detached-owner-4242-ab12cd34-`;
107+
const argv = argvFor(path.basename(OWNED_ARTIFACT_PATH));
108+
109+
assert.equal(new RegExp(detachedTokenPattern).test(argv), false);
110+
assert.equal(
111+
new RegExp(buildRunnerSessionXctestrunPathCleanupPattern(OWNED_ARTIFACT_PATH) ?? '').test(argv),
112+
true,
113+
);
114+
});
115+
116+
test('a lease artifact path outside the runner session name declines to a pattern', () => {
117+
// A basename like `runner.xctestrun` would escape into a pattern loose enough to signal unrelated
118+
// xcodebuilds, so the caller has to fall back to the device sweep.
119+
assert.equal(buildRunnerSessionXctestrunPathCleanupPattern('/tmp/runner.xctestrun'), undefined);
120+
assert.equal(buildRunnerSessionXctestrunPathCleanupPattern(''), undefined);
121+
assert.equal(buildRunnerSessionXctestrunPathCleanupPattern(undefined), undefined);
122+
});
123+
124+
function sessionFileName(deviceId: string, ownerToken: string): string {
125+
return `AgentDeviceRunner.env.${buildRunnerSessionXctestrunSuffix({ deviceId, ownerToken, port: 8123 })}.xctestrun`;
126+
}
127+
128+
function argvFor(fileName: string): string {
129+
return `xcodebuild test-without-building -xctestrun /derived/Build/Products/${fileName}`;
130+
}

‎packages/platform-apple/src/runner/__tests__/runner-disposal.test.ts‎

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,13 @@ vi.mock('../runner-io.ts', async (importOriginal) => {
1515
return { ...actual, cleanupTempFile: mockCleanupTempFile };
1616
});
1717

18-
import { abortRunnerSessionsAndPrepProcesses, disposeRunnerSession } from '../runner-disposal.ts';
1918
import {
19+
abortRunnerSessionsAndPrepProcesses,
20+
disposeRunnerSession,
21+
runnerLeaseCleanupAdapter,
22+
} from '../runner-disposal.ts';
23+
import {
24+
buildDetachedRunnerLease,
2025
currentRunnerLeaseOwnerToken,
2126
releaseRunnerLease,
2227
withRunnerLeaseLock,
@@ -182,6 +187,57 @@ test('disposal serializes behind a successor reclaim window and never terminates
182187
expect(currentRunnerLeaseOwnerToken(IOS_SIMULATOR.id)).toBe('owner-toctou-successor');
183188
});
184189

190+
test('a leased cleanup selects the launch named by the artifact the lease recorded', async () => {
191+
// The launch is found by matching its argv, and a lease knows the artifact that launch was
192+
// started with. Detaching is why following the path rather than the token matters: it rewrites
193+
// `ownerToken` to `detached-<token>` while the handed-over xcodebuild keeps the name the writer
194+
// gave it, so a pattern rebuilt from the token names a file that never existed.
195+
const detached = buildDetachedRunnerLease(
196+
makeRunnerLease({ deviceId: IOS_SIMULATOR.id, ownerToken: 'owner-4242-ab12cd34' }),
197+
);
198+
expect(detached.ownerToken).toBe('detached-owner-4242-ab12cd34');
199+
200+
await runnerLeaseCleanupAdapter.cleanupRunnerXcodebuildProcesses({
201+
deviceId: detached.deviceId,
202+
xctestrunPath: detached.xctestrunPath,
203+
});
204+
205+
const pattern = runnerXcodebuildPkillPatterns()[0];
206+
expect(pattern).toBeDefined();
207+
const selects = (xctestrunPath: string): boolean =>
208+
new RegExp(pattern ?? '').test(runnerLaunchArgv(xctestrunPath));
209+
expect(selects(detached.xctestrunPath)).toBe(true);
210+
// A launch this lease does not name is somebody else's, and must stay untouched.
211+
expect(selects('/tmp/other/AgentDeviceRunner.xctestrun')).toBe(false);
212+
});
213+
214+
test('a cleanup with no recorded artifact sweeps that device launches only', async () => {
215+
// A reclaim with no lease to read knows the device and nothing else, so it keeps the released
216+
// pre-owner-token bytes and stays scoped to that device instead of every xcodebuild on the host.
217+
await runnerLeaseCleanupAdapter.cleanupRunnerXcodebuildProcesses({ deviceId: 'SIM-OTHER' });
218+
219+
const pattern = runnerXcodebuildPkillPatterns()[0];
220+
expect(pattern).toBeDefined();
221+
const selects = (fileName: string): boolean =>
222+
new RegExp(pattern ?? '').test(runnerLaunchArgv(`/tmp/${fileName}`));
223+
expect(selects('AgentDeviceRunner.env.session-SIM-OTHER-8123.xctestrun')).toBe(true);
224+
expect(selects('AgentDeviceRunner.env.session-SIM-VICTIM-8123.xctestrun')).toBe(false);
225+
// A launch a lease still names is not this sweep's to take: it is reached by its own lease.
226+
expect(
227+
selects('AgentDeviceRunner.env.session-SIM-OTHER-owner-4242-ab12cd34-8123.xctestrun'),
228+
).toBe(false);
229+
});
230+
231+
function runnerXcodebuildPkillPatterns(): string[] {
232+
return mockRunAppleToolCommand.mock.calls
233+
.filter(([tool, args]) => tool === 'pkill' && (args as string[]).includes('-f'))
234+
.map(([, args]) => String((args as string[])[2]));
235+
}
236+
237+
function runnerLaunchArgv(xctestrunPath: string): string {
238+
return `xcodebuild test-without-building -xctestrun ${xctestrunPath}`;
239+
}
240+
185241
function simulatorTerminateCalls(): unknown[] {
186242
return mockRunXcrun.mock.calls.filter(([args]) => (args as string[]).includes('terminate'));
187243
}

‎packages/platform-apple/src/runner/__tests__/runner-lease-claim-takeover.test.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import assert from 'node:assert/strict';
22
import fs from 'node:fs';
3+
import path from 'node:path';
34
import { afterEach, beforeEach, test } from 'vitest';
45
import type { DeviceInfo } from '@agent-device/kernel/device';
56
import { appleRunnerTestHost } from '../test-host.ts';
@@ -55,8 +56,11 @@ function recordingCleanupAdapter(): RunnerLeaseCleanupAdapter & { calls: string[
5556
cleanupRunnerProcessTree: async (_pid, signal) => {
5657
calls.push(`process-tree:${signal}`);
5758
},
58-
cleanupRunnerXcodebuildProcesses: async (_deviceId, ownerToken) => {
59-
calls.push(`xcodebuild:${ownerToken ?? 'any'}`);
59+
cleanupRunnerXcodebuildProcesses: async (target) => {
60+
const basename = target.xctestrunPath
61+
? `:${path.basename(target.xctestrunPath)}`
62+
: ':device-sweep';
63+
calls.push(`xcodebuild:${target.deviceId}${basename}`);
6064
},
6165
cleanupTempFile: (filePath) => {
6266
calls.push(`temp:${filePath}`);
@@ -78,7 +82,13 @@ test('device-claim authority reclaims a live foreign claim-aware lease', async (
7882

7983
await prepareRunnerLeaseForStartup(device, cleanup);
8084

81-
assert.ok(cleanup.calls.includes('xcodebuild:owner-foreign-live'));
85+
// The takeover kills the launch the lease named, so it must carry the recorded artifact path
86+
// rather than anything derived from the owner token it is preempting.
87+
assert.ok(
88+
cleanup.calls.includes(
89+
'xcodebuild:claim-takeover-sim:AgentDeviceRunner.env.session-claim-takeover-sim-owner-foreign-live-8123.xctestrun',
90+
),
91+
);
8292
// The probe must receive the full device identity, never a bare id: claim
8393
// ownership is canonical family/OS/id, and a same-id claim from another
8494
// platform family grants nothing.
@@ -89,7 +99,7 @@ test('device-claim authority reclaims a live foreign claim-aware lease', async (
8999
// sees an empty store instead of the foreign owner.
90100
const emptyCleanup = recordingCleanupAdapter();
91101
await prepareRunnerLeaseForStartup(device, emptyCleanup);
92-
assert.ok(emptyCleanup.calls.includes('xcodebuild:any'));
102+
assert.ok(emptyCleanup.calls.includes(`xcodebuild:${device.id}:device-sweep`));
93103
});
94104

95105
test('a claim-aware lease still refuses without device-claim authority', async () => {

‎packages/platform-apple/src/runner/__tests__/runner-session.test.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ import {
132132
writeRunnerLease,
133133
type RunnerLease,
134134
type RunnerLeaseCleanupAdapter,
135+
type RunnerXcodebuildCleanupTarget,
135136
} from '../runner-lease.ts';
136137

137138
// Test-only stand-in for the daemon's own runtime lease-owner-state-dir
@@ -741,13 +742,13 @@ test('runner session startup reclaims dead foreign runner lease before launching
741742
// separate adapter call and must keep running either way.
742743
function makeRecordingCleanupAdapter() {
743744
const treeKills: Array<{ pid: number | undefined; signal: string }> = [];
744-
const xcodebuildCleanups: Array<{ deviceId: string; ownerToken: string | undefined }> = [];
745+
const xcodebuildCleanups: RunnerXcodebuildCleanupTarget[] = [];
745746
const adapter: RunnerLeaseCleanupAdapter = {
746747
async cleanupRunnerProcessTree(pid, signal) {
747748
treeKills.push({ pid, signal });
748749
},
749-
async cleanupRunnerXcodebuildProcesses(deviceId, ownerToken) {
750-
xcodebuildCleanups.push({ deviceId, ownerToken });
750+
async cleanupRunnerXcodebuildProcesses(target) {
751+
xcodebuildCleanups.push(target);
751752
},
752753
cleanupTempFile() {},
753754
};
@@ -783,9 +784,8 @@ test('stale-lease cleanup does not signal a recycled runner pid (start time mism
783784
{ pid: undefined, signal: 'SIGTERM' },
784785
{ pid: undefined, signal: 'SIGKILL' },
785786
]);
786-
assert.deepEqual(xcodebuildCleanups, [
787-
{ deviceId: device.id, ownerToken: 'owner-dead-recycled' },
788-
]);
787+
const sweptDeviceIds = xcodebuildCleanups.map((target) => target.deviceId);
788+
assert.deepEqual(sweptDeviceIds, [device.id]);
789789
});
790790

791791
test('stale-lease cleanup signals the runner pid when its start time still matches', async () => {

‎packages/platform-apple/src/runner/__tests__/runner-xctestrun.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ import os from 'node:os';
66
import path from 'node:path';
77
import { pathToFileURL } from 'node:url';
88
import { mkdtempForTestSync } from './tmp-dir.ts';
9+
import {
10+
buildRunnerSessionXctestrunPathCleanupPattern,
11+
buildRunnerSessionXctestrunSuffix,
12+
} from '../runner-artifact-env.ts';
913
import { appleRunnerTestHost } from '../test-host.ts';
1014
import type { ExecOptions, ExecResult } from '@agent-device/host-kit/command';
1115

@@ -358,6 +362,46 @@ test('prepareXctestrunWithEnv writes env overlays into configured env dir', asyn
358362
});
359363
});
360364

365+
test('the session xctestrun the writer builds is found by the cleanup matcher', async () => {
366+
// The launch is killed by `pkill -f` on a pattern the writer module itself builds, and the
367+
// daemon-client sweep pins its own looser copy of these bytes. Binding writer to pattern and to
368+
// those pinned bytes here is what makes a rename that keeps each side self-consistent fail.
369+
await withTempDir('runner-xctestrun-identity-', async (root) => {
370+
const xctestrunPath = path.join(root, 'AgentDeviceRunner.xctestrun');
371+
fs.writeFileSync(
372+
xctestrunPath,
373+
JSON.stringify({
374+
TestConfigurations: [{ TestTargets: [{ TestBundlePath: 'AgentDeviceRunnerUITests' }] }],
375+
}),
376+
);
377+
appleRunnerTestHost.update({ runAppleToolCommand: fakeXctestrunPlutilToolCommand() });
378+
const suffix = buildRunnerSessionXctestrunSuffix({
379+
deviceId: 'SIM-001',
380+
ownerToken: 'owner-4242-ab12cd34',
381+
port: 8123,
382+
});
383+
384+
const prepared = await prepareXctestrunWithEnv(xctestrunPath, runnerPortEnv, suffix);
385+
const argv = `xcodebuild test-without-building -xctestrun ${prepared.xctestrunPath}`;
386+
387+
// The bytes the timeout sweep pins literally, so the sweep cannot drift off the writer's name.
388+
assert.match(argv, new RegExp(String.raw`xcodebuild .*AgentDeviceRunner\.env\.session-`));
389+
// The lease-backed pattern is spelled from the path the writer returned, so pin those bytes
390+
// literally rather than comparing the pattern to the path it was built from: a rename that keeps
391+
// both sides self-consistent must still fail here.
392+
assert.equal(
393+
buildRunnerSessionXctestrunPathCleanupPattern(prepared.xctestrunPath),
394+
String.raw`AgentDeviceRunner\.env\.session-SIM-001-owner-4242-ab12cd34-8123\.xctestrun`,
395+
);
396+
assert.match(
397+
argv,
398+
new RegExp(
399+
String.raw`xcodebuild.*test-without-building.*AgentDeviceRunner\.env\.session-SIM-001-owner-4242-ab12cd34-8123\.xctestrun`,
400+
),
401+
);
402+
});
403+
});
404+
361405
test('prepareXctestrunWithEnv leaves unrelated targets without capture policy', async () => {
362406
await withTempDir('runner-xctestrun-policy-', async (root) => {
363407
const xctestrunPath = path.join(root, 'AgentDeviceRunner.xctestrun');

0 commit comments

Comments
 (0)