Skip to content

Commit 99a379f

Browse files
committed
refactor(ios): scope this change to the daemon-startup recorder reap grace
The exit-16 classifier and graceful start rollback are owned by #2447 with the DEVICE_IN_USE contract; drop the overlapping COMMAND_FAILED classifier here to keep one start-path error contract. Keep only the non-overlapping daemon-startup fix: an orphaned simctl recorder is reaped with the same finalize grace the live stop path allows, plus a startup-wiring test. Refs #2170.
1 parent 1fb63cb commit 99a379f

4 files changed

Lines changed: 84 additions & 67 deletions
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import fs from 'node:fs';
2+
import { afterEach, expect, test, vi } from 'vitest';
3+
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';
4+
5+
const reapCalls = vi.hoisted(() => [] as Array<Record<string, unknown>>);
6+
7+
vi.mock('@agent-device/host-kit/process', async (importOriginal) => {
8+
const actual = await importOriginal<Record<string, unknown>>();
9+
return {
10+
...actual,
11+
reapOwnedProcessRecordsAtStartup: (_store: unknown, options?: Record<string, unknown>) => {
12+
reapCalls.push(options ?? {});
13+
return Promise.resolve({ terminated: [], failed: [] });
14+
},
15+
};
16+
});
17+
18+
vi.mock('../../platform-runtime.ts', () => ({
19+
androidObservation: {},
20+
createRequestPlatformProviders: () => ({
21+
run: async (_context: unknown, task: () => Promise<unknown>) => await task(),
22+
}),
23+
createPlatformRuntimeGateway: () => ({
24+
applicationLifecycle: {
25+
recoverStartupResources: async () => {},
26+
detachForDaemonShutdown: async () => {},
27+
finalizeDaemonShutdown: async () => {},
28+
},
29+
inspectFacts: async () => {
30+
throw new Error('unused');
31+
},
32+
bind: async () => {
33+
throw new Error('unused');
34+
},
35+
shutdown: async () => {},
36+
}),
37+
createPlatformDeviceInventoryGateways: () => ({}),
38+
}));
39+
40+
vi.mock('../../provider-device-runtimes.ts', () => ({
41+
DEFAULT_PROVIDER_RUNTIME_REQUIRED_IDS: [],
42+
createDefaultProviderRuntimeComposition: async () => ({ runtimes: [], platformModules: [] }),
43+
}));
44+
45+
import { startDaemonRuntime } from './daemon-runtime.ts';
46+
47+
afterEach(() => {
48+
reapCalls.length = 0;
49+
});
50+
51+
test('daemon startup reaps orphaned simctl recorders with a graceful finalize window', async () => {
52+
const stateDir = mkdtempForTestSync('agent-device-daemon-recording-reaper-');
53+
try {
54+
const runtime = await startDaemonRuntime({
55+
env: {
56+
...process.env,
57+
AGENT_DEVICE_STATE_DIR: stateDir,
58+
AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: '0',
59+
AGENT_DEVICE_DAEMON_SERVER_MODE: 'http',
60+
},
61+
exit: () => {},
62+
registerProcessHandlers: false,
63+
stderr: { write: () => {} },
64+
stdout: { write: () => {} },
65+
});
66+
expect(runtime).not.toBeNull();
67+
68+
const recordingReap = reapCalls.find(
69+
(call) => JSON.stringify(call.purposes) === JSON.stringify(['simctl-screen-recording']),
70+
);
71+
expect(recordingReap, 'startup should reap the simctl recorder purpose').toBeDefined();
72+
// An orphaned recorder must get the same graceful finalize window the live stop path allows,
73+
// so it releases the host recording lock instead of leaving it dangling for the next session.
74+
expect(Number(recordingReap!.termTimeoutMs)).toBeGreaterThanOrEqual(5_000);
75+
76+
await runtime?.shutdown();
77+
} finally {
78+
fs.rmSync(stateDir, { recursive: true, force: true });
79+
}
80+
});

‎src/daemon/server/daemon-runtime.ts‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -83,11 +83,9 @@ import { createScreenRecordingAdmissionLedger } from '../screen-recording-admiss
8383
const DAEMON_SESSION_LEASE_RELEASE_TIMEOUT_MS = 1_000;
8484
const DAEMON_PNG_WORKER_TERMINATE_TIMEOUT_MS = 1_000;
8585
const DAEMON_PROVIDER_RELEASE_DRAIN_TIMEOUT_MS = 2_000;
86-
// `simctl recordVideo` releases the host-wide recording lock only once it finishes finalizing on
87-
// SIGINT, so an orphaned recorder is given the same grace the live stop path allows before the
88-
// reaper escalates. An ungraceful SIGKILL fixes one device but leaves every later recording on the
89-
// host failing with EBUSY (#2170). The reaper only selects the recorder purpose, so this bounds one
90-
// tree — the daemon-startup budget stays well under the 15s client startup timeout.
86+
// An orphaned `simctl recordVideo` releases the host-wide recording lock only after it finishes
87+
// finalizing on SIGINT; force-killing it sooner leaves every later recording failing with EBUSY
88+
// (#2170). Bound the grace to the recorder purpose, so daemon startup stays under the client budget.
9189
const DAEMON_RECORDING_REAP_TERM_TIMEOUT_MS = 5_000;
9290

9391
type WritableOutput = {

‎src/platform-runtime-screen-recording-apple-simulator-host.test.ts‎

Lines changed: 0 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import fs from 'node:fs';
22
import path from 'node:path';
33
import { beforeEach, expect, test, vi } from 'vitest';
4-
import { AppError, normalizeError } from '@agent-device/kernel/errors';
54
import { mkdtempForTestSync } from './__tests__/test-utils/tmp-dir.ts';
65
import { createAppleScreenRecordingHost } from './platform-runtime-screen-recording-apple-host.ts';
76
import { startAppleSimulatorRecording } from './platform-runtime-screen-recording-apple-simulator-host.ts';
@@ -69,45 +68,6 @@ test('waits for delayed output and rejects an early nonzero exit', async () => {
6968
running.resolveWait({ stdout: '', stderr: '', exitCode: 0 });
7069
});
7170

72-
const BUSY_STDERR =
73-
'Error starting video recorder: Error Domain=NSPOSIXErrorDomain Code=16 "Resource busy"';
74-
75-
test('surfaces a typed hint for the EBUSY host-recording exit that survives normalization', async () => {
76-
const root = mkdtempForTestSync('agent-device-recording-busy-');
77-
const busy = background(50);
78-
busy.resolveWait({ stdout: '', stderr: BUSY_STDERR, exitCode: 16 });
79-
80-
const thrown = await withTransport(
81-
busy.process,
82-
async () => await startAppleSimulatorRecording(simulator, path.join(root, 'busy.mp4')),
83-
).catch((error: unknown) => error);
84-
85-
expect(thrown).toBeInstanceOf(AppError);
86-
const normalized = normalizeError(thrown);
87-
expect(normalized.code).toBe('COMMAND_FAILED');
88-
expect(normalized.hint).toContain('SimStreamProcessorService');
89-
expect(normalized.details).toMatchObject({
90-
reason: 'apple-simulator-host-recording-busy',
91-
exitCode: 16,
92-
processExitError: true,
93-
});
94-
expect(normalized.message).toContain('recording slot is busy');
95-
expect(normalized.message).toContain('Resource busy');
96-
});
97-
98-
test('keys the busy classification on the exit code, not the stderr text', async () => {
99-
const root = mkdtempForTestSync('agent-device-recording-not-busy-');
100-
const failed = background(51);
101-
failed.resolveWait({ stdout: '', stderr: BUSY_STDERR, exitCode: 1 });
102-
103-
await expect(
104-
withTransport(
105-
failed.process,
106-
async () => await startAppleSimulatorRecording(simulator, path.join(root, 'other.mp4')),
107-
),
108-
).rejects.toThrow('simctl recordVideo exited with code 1');
109-
});
110-
11171
test('cancellation during readiness kills and settles with the exact reason', async () => {
11272
const root = mkdtempForTestSync('agent-device-recording-cancel-');
11373
const controller = new AbortController();

‎src/platform-runtime-screen-recording-apple-simulator-host.ts‎

Lines changed: 1 addition & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,7 @@ import type {
44
ManagedProcessIdentity,
55
} from '@agent-device/contracts/platform-runtime-host';
66
import type { ScreenRecordingBackgroundProcess } from '@agent-device/contracts/screen-recording-runtime-host';
7-
import { execFailureDetails } from '@agent-device/host-kit/command';
87
import type { DeviceInfo } from '@agent-device/kernel/device';
9-
import { AppError } from '@agent-device/kernel/errors';
108
import type { AppleSimulatorScreenRecordingProcess } from './platform-runtime-screen-recording-apple-transport.ts';
119
import {
1210
inspectManagedProcess,
@@ -22,14 +20,6 @@ const READY_TIMEOUT_MS = 15_000;
2220
const IDENTITY_POLL_MS = 25;
2321
const IDENTITY_TIMEOUT_MS = 2_000;
2422

25-
// POSIX EBUSY. `simctl recordVideo` exits with this when CoreSimulator's shared
26-
// `SimStreamProcessorService` still holds the one host-wide recording slot — a live recording
27-
// elsewhere, or a prior recorder that died without detaching. A signal death reports `exitCode: 1`,
28-
// never 16, so this is safe to key on the exit code rather than the stderr text (#2170).
29-
const HOST_RECORDING_BUSY_EXIT_CODE = 16;
30-
const HOST_RECORDING_BUSY_HINT =
31-
'Another screen recording is active on this host, or a previous recorder died without detaching. Stop the other recording, or run `killall -9 SimStreamProcessorService` to clear the dangling stream service (it relaunches on demand), then retry.';
32-
3323
const appleSimulatorRecordingCommandMatches: ManagedProcessCommandMatcher = (
3424
persisted,
3525
observed,
@@ -249,18 +239,7 @@ function startError(outcome: AppleSimulatorExit): Error {
249239
if (outcome.kind === 'failed') {
250240
return outcome.error instanceof Error ? outcome.error : new Error(String(outcome.error));
251241
}
252-
const { stdout, stderr, exitCode } = outcome.result;
253-
if (exitCode === HOST_RECORDING_BUSY_EXIT_CODE) {
254-
return new AppError(
255-
'COMMAND_FAILED',
256-
'simctl recordVideo could not start because the CoreSimulator host recording slot is busy (EBUSY)',
257-
execFailureDetails(
258-
{ stdout, stderr, exitCode },
259-
{ reason: 'apple-simulator-host-recording-busy', hint: HOST_RECORDING_BUSY_HINT },
260-
),
261-
);
262-
}
263-
return new Error(`simctl recordVideo exited with code ${exitCode}`);
242+
return new Error(`simctl recordVideo exited with code ${outcome.result.exitCode}`);
264243
}
265244

266245
function delay(milliseconds: number, signal?: AbortSignal): Promise<void> {

0 commit comments

Comments
 (0)