Skip to content

Commit 4176e54

Browse files
committed
fix(apple-runner): fence prep spawns behind a start-owned admission (#3220)
A non-retained close killed the in-flight `build-for-testing` before waiting for the session lock the start holds, and the same caller's health retry answered the kill with a second build while close waited — close timed out on the build it just asked to stop. One start-owned admission now answers who may prepare a device: it is captured when a start requests the device, shared by every start that queues behind that work, closed by a teardown BEFORE it stops prep children or takes the session lock, and closed by the LAST interested waiter's cancellation while any other waiter still preserves the work. The preparation-spawn seam and the session-publish points both read it immediately before they act, so a retired start's retry is refused before the replacement child exists, and a retired start can never publish into a fresh start. A start that merely QUEUED behind a close re-routes to a fresh admission once that close has settled — the fence refuses mid-close retries, never innocent waiters; the settle clears the fence inside the session lock. The starting request counts as an interested waiter even on surfaces that pass no caller signal, so a joiner's cancellation cannot outvote the live owner and stop its build. Removed the #3193 request-owner prep filter (`runnerPrepProcessChildrenWithoutActiveOwner` / `stopRunnerPrepProcessesWithoutActiveOwner`): the admission's waiter count supersedes the owner-liveness sniff. The shutdown-detach mechanism moved to runner-adoption.ts beside the adoption it hands off to (pure move). Closes #3220
1 parent 14e1bd7 commit 4176e54

16 files changed

Lines changed: 1516 additions & 364 deletions

‎apple/runner/AgentDeviceRunner/RecordingScripts/RecordingExportSupport.swift‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -88,23 +88,18 @@ func makeRecordingExporter(
8888
return exporter
8989
}
9090

91-
/// How long an export may run when the caller names no budget of its own.
92-
let defaultRecordingExportTimeoutSeconds: Double = 120
93-
94-
/// Bounded asynchronous export: signals completion through a semaphore and cancels after
95-
/// `timeoutSeconds` so a wedged or slow encoder cannot hang the recording pipeline past the
96-
/// caller's own timeout budget.
91+
/// Bounded asynchronous export: signals completion through a semaphore and cancels after 120s so a
92+
/// wedged encoder cannot hang the recording pipeline past the caller's own timeout budget.
9793
func runRecordingExport(
9894
_ exporter: AVAssetExportSession,
99-
timeoutSeconds: Double = defaultRecordingExportTimeoutSeconds,
10095
timeoutMessage: String,
10196
failureMessage: String
10297
) throws {
10398
let semaphore = DispatchSemaphore(value: 0)
10499
exporter.exportAsynchronously {
105100
semaphore.signal()
106101
}
107-
if semaphore.wait(timeout: .now() + timeoutSeconds) == .timedOut {
102+
if semaphore.wait(timeout: .now() + 120) == .timedOut {
108103
exporter.cancelExport()
109104
throw RecordingScriptError.exportFailed(timeoutMessage)
110105
}

‎apple/runner/AgentDeviceRunner/RecordingScripts/recording-overlay.swift‎

Lines changed: 11 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,6 @@ func run() throws {
145145
)
146146
try runRecordingExport(
147147
exporter,
148-
timeoutSeconds: parsedArgs.timeoutSeconds,
149148
timeoutMessage: "Touch overlay export timed out.",
150149
failureMessage: "Touch overlay export failed."
151150
)
@@ -158,11 +157,10 @@ func run() throws {
158157

159158
func parseArguments(
160159
_ arguments: [String]
161-
) throws -> (inputPath: String, outputPath: String, eventsPath: String, timeoutSeconds: Double) {
160+
) throws -> (inputPath: String, outputPath: String, eventsPath: String) {
162161
var inputPath: String?
163162
var outputPath: String?
164163
var eventsPath: String?
165-
var timeoutSeconds = defaultRecordingExportTimeoutSeconds
166164
var index = 0
167165

168166
while index < arguments.count {
@@ -187,24 +185,17 @@ func parseArguments(
187185
throw RecordingScriptError.invalidArgs("--quality must be one of: medium, high")
188186
}
189187
index += 2
190-
case "--timeout-ms":
191-
let rawValue = try recordingOptionValue(arguments, nextIndex, "--timeout-ms")
192-
guard let milliseconds = Double(rawValue), milliseconds > 0 else {
193-
throw RecordingScriptError.invalidArgs("--timeout-ms must be a positive number")
194-
}
195-
timeoutSeconds = milliseconds / 1000
196-
index += 2
197188
default:
198189
throw RecordingScriptError.invalidArgs("Unknown argument: \(argument)")
199190
}
200191
}
201192

202193
guard let inputPath, let outputPath, let eventsPath else {
203194
throw RecordingScriptError.invalidArgs(
204-
"Usage: recording-overlay.swift --input <video> --output <video> --events <json> [--quality <medium|high>] [--timeout-ms <ms>]"
195+
"Usage: recording-overlay.swift --input <video> --output <video> --events <json> [--quality <medium|high>]"
205196
)
206197
}
207-
return (inputPath, outputPath, eventsPath, timeoutSeconds)
198+
return (inputPath, outputPath, eventsPath)
208199
}
209200

210201
/// The composited overlay must keep the captured track's dimensions, so it can only use a preset
@@ -338,26 +329,19 @@ func frameMeanLuma(_ image: CGImage) -> Double? {
338329
return total / Double(count)
339330
}
340331

341-
/// The composited export renders at most this many frames a second, which is smooth for a touch
342-
/// that stays visible for 0.45s.
343-
let maximumCompositedFrameRate: Int32 = 30
344-
345-
/// A variable-frame-rate capture (simctl recordVideo, adb screenrecord) reports one tick of its
346-
/// timescale as `minFrameDuration` (1/600s from simctl). Rendering at that asked the compositor for
347-
/// every frame the encoder could make, 75 a second from an iOS simulator and 60 from an Android
348-
/// emulator, about three times the frames the capture holds; a 5-minute recording's export then
349-
/// outlasted the `record stop` request. So the frame duration is the capture's, but never shorter
350-
/// than one frame at `maximumCompositedFrameRate`. A capture that reports none renders at that
351-
/// rate: its average (`nominalFrameRate`) can be a couple of frames a second over a still screen,
352-
/// which would skip a touch.
353332
func resolvedFrameDuration(for track: AVAssetTrack) -> CMTime {
354-
let shortest = CMTime(value: 1, timescale: maximumCompositedFrameRate)
355333
let minFrameDuration = track.minFrameDuration
356334
if minFrameDuration.isValid && !minFrameDuration.isIndefinite && minFrameDuration.seconds > 0 {
357-
return CMTimeMaximum(minFrameDuration, shortest)
335+
return minFrameDuration
336+
}
337+
338+
let nominalFrameRate = track.nominalFrameRate
339+
if nominalFrameRate > 0 {
340+
let timescale = Int32(max(1, round(nominalFrameRate)))
341+
return CMTime(value: 1, timescale: timescale)
358342
}
359343

360-
return shortest
344+
return CMTime(value: 1, timescale: 60)
361345
}
362346

363347
func overlayPoint(event: GestureEvent, x: Double, y: Double, renderSize: CGSize) -> CGPoint {

‎packages/capture-kit/src/recording/__tests__/overlay.test.ts‎

Lines changed: 1 addition & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ vi.mock('../video.ts', () => ({
2828
waitForPlayableVideo: vi.fn(async () => {}),
2929
}));
3030

31-
import { OVERLAY_BUDGET_MS, overlayRecordingTouches } from '../overlay.ts';
31+
import { overlayRecordingTouches } from '../overlay.ts';
3232
import { AppError } from '@agent-device/kernel/errors';
3333
import { runCmd } from '@agent-device/host-kit/command';
3434

@@ -48,7 +48,6 @@ beforeEach(() => {
4848
});
4949

5050
afterEach(() => {
51-
vi.useRealTimers();
5251
fs.rmSync(tmpDir, { recursive: true, force: true });
5352
});
5453

@@ -130,46 +129,3 @@ test('overlay forwards the requested high export preset', async () => {
130129
expect.arrayContaining(['--events', telemetryPath, '--quality', 'high']),
131130
);
132131
});
133-
134-
test('overlay hands the helper what is left of its budget, inside the record request', async () => {
135-
const videoPath = path.join(tmpDir, 'recording.mp4');
136-
const telemetryPath = path.join(tmpDir, 'recording.gesture-telemetry.json');
137-
fs.writeFileSync(videoPath, 'original');
138-
fs.writeFileSync(telemetryPath, '{"events":[]}');
139-
140-
await overlayRecordingTouches({ videoPath, telemetryPath });
141-
142-
const compileCall = mockRunCmd.mock.calls.find(([cmd]) => cmd === 'xcrun');
143-
const helperCall = mockRunCmd.mock.calls.find(([cmd]) => cmd !== 'xcrun');
144-
const args = helperScriptArgs();
145-
const exportMs = Number(args[args.indexOf('--timeout-ms') + 1]);
146-
expect(exportMs).toBeGreaterThan(0);
147-
// The compile, the export and the helper's exit all fit in the budget. That the budget fits in
148-
// `record`'s request envelope is checked where the envelope is declared.
149-
expect(compileCall?.[2]?.timeoutMs).toBeLessThanOrEqual(OVERLAY_BUDGET_MS);
150-
expect(helperCall?.[2]?.timeoutMs).toBeLessThanOrEqual(OVERLAY_BUDGET_MS);
151-
expect(exportMs).toBeLessThan(helperCall?.[2]?.timeoutMs ?? 0);
152-
});
153-
154-
test('overlay leaves the video as recorded when compiling the helper spent its budget', async () => {
155-
vi.useFakeTimers({ toFake: ['Date'] });
156-
const videoPath = path.join(tmpDir, 'recording.mp4');
157-
const telemetryPath = path.join(tmpDir, 'recording.gesture-telemetry.json');
158-
fs.writeFileSync(videoPath, 'original');
159-
fs.writeFileSync(telemetryPath, '{"events":[]}');
160-
161-
mockRunCmd.mockImplementationOnce(async (_cmd, args) => {
162-
vi.setSystemTime(Date.now() + OVERLAY_BUDGET_MS);
163-
const outputPath = args[args.indexOf('-o') + 1]!;
164-
fs.writeFileSync(outputPath, 'compiled');
165-
fs.chmodSync(outputPath, 0o755);
166-
return { stdout: '', stderr: '', exitCode: 0 };
167-
});
168-
169-
await expect(overlayRecordingTouches({ videoPath, telemetryPath })).rejects.toMatchObject({
170-
code: 'COMMAND_FAILED',
171-
message: 'Failed to add touch overlays to the recording',
172-
});
173-
expect(mockRunCmd.mock.calls.filter(([cmd]) => cmd !== 'xcrun')).toHaveLength(0);
174-
expect(fs.readFileSync(videoPath, 'utf8')).toBe('original');
175-
});

‎packages/capture-kit/src/recording/overlay.ts‎

Lines changed: 4 additions & 41 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 { runCmd } from '@agent-device/host-kit/command';
4-
import { Deadline } from '@agent-device/host-kit/retry';
54
import { AppError } from '@agent-device/kernel/errors';
65
import { findProjectRoot } from '@agent-device/host-kit/version';
76
import {
@@ -24,20 +23,6 @@ export function getRecordingOverlaySupportWarning(
2423
return 'touch overlay burn-in is only available on macOS hosts; returning raw video plus gesture telemetry';
2524
}
2625

27-
/**
28-
* `record stop` is one daemon request, which the client abandons after `record`'s 90 s envelope:
29-
* the caller gets "Daemon request timed out" while the daemon finishes the stop. So the overlay must
30-
* end well inside it. Compiling the helper, its export and its exit all come out of this budget;
31-
* past it the stop keeps the raw video and its gesture telemetry, with a warning.
32-
*/
33-
export const OVERLAY_BUDGET_MS = 70_000;
34-
35-
/**
36-
* The helper's time outside its export: starting up, then verifying the composited output or
37-
* cancelling the export, and exiting.
38-
*/
39-
const HELPER_EXIT_GRACE_MS = 5_000;
40-
4126
let overlayScriptPath: string | undefined;
4227
let exportSupportScriptPath: string | undefined;
4328

@@ -59,10 +44,8 @@ async function exportProcessedVideo(params: {
5944
scriptPath: string;
6045
scriptArgs: string[];
6146
commandDescription: string;
62-
budgetMs: number;
6347
}): Promise<void> {
6448
const { videoPath, scriptPath, scriptArgs, commandDescription } = params;
65-
const deadline = Deadline.fromTimeoutMs(params.budgetMs);
6649
await waitForStableFile(videoPath);
6750
await waitForPlayableVideo(videoPath);
6851

@@ -71,30 +54,11 @@ async function exportProcessedVideo(params: {
7154
const executablePath = await compileSwiftSourceFile({
7255
sourcePath: scriptPath,
7356
extraSourcePaths: [getExportSupportScriptPath()],
74-
// `runCmd` reads a timeout of 0 as none.
75-
timeoutMs: Math.max(1, deadline.remainingMs()),
7657
});
77-
const helperMs = deadline.remainingMs();
78-
const exportMs = helperMs - HELPER_EXIT_GRACE_MS;
79-
if (exportMs <= 0) {
80-
throw new AppError(
81-
'COMMAND_FAILED',
82-
`No time was left for the export within the ${params.budgetMs}ms budget`,
83-
);
84-
}
85-
await runCmd(
86-
executablePath,
87-
[
88-
'--input',
89-
videoPath,
90-
'--output',
91-
outputPath,
92-
...scriptArgs,
93-
'--timeout-ms',
94-
String(Math.round(exportMs)),
95-
],
96-
{ timeoutMs: helperMs, env: buildSwiftToolEnv() },
97-
);
58+
await runCmd(executablePath, ['--input', videoPath, '--output', outputPath, ...scriptArgs], {
59+
timeoutMs: 120_000,
60+
env: buildSwiftToolEnv(),
61+
});
9862
await waitForPlayableVideo(outputPath);
9963
fs.renameSync(outputPath, videoPath);
10064
} catch (error) {
@@ -145,6 +109,5 @@ export async function overlayRecordingTouches(params: {
145109
scriptPath: getOverlayScriptPath(),
146110
scriptArgs: ['--events', telemetryPath, '--quality', exportQuality],
147111
commandDescription: `Failed to add touch overlays to the ${targetLabel}`,
148-
budgetMs: OVERLAY_BUDGET_MS,
149112
});
150113
}

0 commit comments

Comments
 (0)