Skip to content

Commit e41d66e

Browse files
committed
fix(recording): sniff the collected copy, keep it until its finalization is journaled, and never serve a refused export
ADR 0024 2.3 records the collected checkpoint only after the copy passes the container sniff. The simulator copy now gets that sniff (`finalize.sniff`: ftyp + moov, no validator spawn); the export still gets the full playability verdict once. The collected copy is removed by a `discard` step the sequence runs after the finalization is journaled, and again on a replay. Removing it inside `finalize` left a crash window in which the checkpoint named a copy that no longer existed, so every later stop failed. When the export copy or the finalizer fails, the caller's paths are removed before the error returns. A killed simctl used to leave an unplayable file at `--out` next to a failed stop.
1 parent b64efa7 commit e41d66e

18 files changed

Lines changed: 234 additions & 59 deletions

‎CHANGELOG.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,8 +72,10 @@
7272
stays `retirable` and the recording stays finishable until the device answers.
7373
- Changed (record): an iOS Simulator recording no longer has the recorder write the file the caller
7474
asked for. `simctl` records to a `<name>.native.<ext>` sibling; `record stop` copies that file to a
75-
`<name>.collected.<ext>` sibling, writes the caller's `--out` path once from the copy, checks that
76-
export is a playable video, and retires the recorder's own file (ADR 0024 2.3). The
75+
`<name>.collected.<ext>` sibling, checks that the copy has an MP4 container, writes the caller's
76+
`--out` path once from the copy, checks that export is a playable video, and retires the recorder's
77+
own file (ADR 0024 2.3). An export the finalizer refuses is removed, so `--out` only ever holds a
78+
video that passed that check. The
7779
caller's path is never a file a recorder is still writing, and a stop that fails before the export
7880
exists leaves it absent with the copy in place — so the next stop resumes from the copy instead of
7981
signalling a recorder that already stopped. Both siblings are deleted on success, and a stop that
@@ -84,8 +86,8 @@
8486
video, so nothing deletes them.
8587
- Changed (record): an Android recording is no longer pulled onto the path the caller asked for.
8688
`record stop` pulls the device's chunks to `<name>.collected.<ext>` siblings, retrying each pull
87-
until it plays, then writes the caller's paths from copies of them and drops the collected set
88-
(ADR 0024 2.3). A stop that dies before the export exists leaves it absent with the pulled set in
89+
until it plays, then writes the caller's paths from copies of them and drops the collected set once the
90+
finalization is journaled (ADR 0024 2.3). Chunk paths the finalizer refused are removed. A stop that dies before the export exists leaves it absent with the pulled set in
8991
place, and the next stop resumes from that set instead of signalling a `screenrecord` process that
9092
already stopped and pulling a file that may have moved since. The 180s platform-limit disclosure now
9193
travels with the recorder's own observation rather than with the export, so a stop that has to be

‎packages/capture-kit/src/recording/stop-sequence.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,31 @@ test('signals the recorder, collects a sibling copy, and finalizes that copy int
4141
});
4242
});
4343

44+
test('discards the collected copy only once its finalization is journaled, on a replay too', async () => {
45+
const manifest = stopManifest();
46+
const journaledBeforeDiscard: (JsonObject | undefined)[] = [];
47+
const steps = recordingSteps();
48+
steps.discard.mockImplementation(async () => {
49+
journaledBeforeDiscard.push(manifest.read());
50+
});
51+
52+
await stopAndExportScreenRecording({ steps, snapshot: snapshot(), progress: manifest.progress });
53+
const replay = recordingSteps();
54+
await stopAndExportScreenRecording({
55+
steps: replay,
56+
snapshot: snapshot(),
57+
progress: stopManifest(manifest.read()).progress,
58+
});
59+
60+
assert.deepEqual(steps.discard.mock.calls, [['/tmp/recording.collected.mp4']]);
61+
assert.ok(
62+
journaledBeforeDiscard[0]?.stopFinalization,
63+
'discard ran before the finalization was journaled',
64+
);
65+
// A crash between the journal and the removal leaves the copy behind; the replay removes it.
66+
assert.deepEqual(replay.discard.mock.calls, [['/tmp/recording.collected.mp4']]);
67+
});
68+
4469
test('discloses what the recorder did beside the export it produced', async () => {
4570
const steps = recordingSteps({
4671
stop: async () => ({
@@ -218,6 +243,7 @@ function recordingSteps(
218243
overrides.stop ?? (async () => ({ observation: { recorder: 'confirmed' } as const })),
219244
),
220245
collect: vi.fn(async (_collectedPath: string) => {}),
246+
discard: vi.fn(async (_collectedPath: string) => {}),
221247
finalize: vi.fn(async () => ({
222248
telemetryPath: '/tmp/recording.telemetry.json',
223249
warning: '2 chunks were merged',

‎packages/capture-kit/src/recording/stop-sequence.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,15 +22,15 @@ export type RecorderStop = Readonly<{
2222
}>;
2323

2424
/**
25-
* The three things a backend can do to a recording, named separately so a stop can commit between
25+
* The four things a backend can do to a recording, named separately so a stop can commit between
2626
* them (ADR 0024 2.3). A backend implements these and owns nothing about ordering: the sequence below
2727
* decides when a recorder is asked again, when a collected copy may be reused, and which facts are
2828
* durable before the export is written.
2929
*/
3030
export type ScreenRecordingStopSteps = Readonly<{
3131
/** Signal this recording's recorder safely and report what was observed. Writes no artifacts. */
3232
stop(): Promise<RecorderStop>;
33-
/** Copy or pull the recorder's own artifact into `collectedPath`. */
33+
/** Copy or pull the recorder's own artifact into `collectedPath`, past the container sniff. */
3434
collect(collectedPath: string): Promise<void>;
3535
/**
3636
* Turn the collected copy into the export. Never finalizes the recorder's own path in place, and
@@ -40,6 +40,8 @@ export type ScreenRecordingStopSteps = Readonly<{
4040
finalize(
4141
input: Readonly<{ collectedPath: string; exportPath: string; stoppedAtMs: number }>,
4242
): Promise<ScreenRecordingFinalization>;
43+
/** Remove the collected copy. It runs only once the finalization is journaled, and never throws. */
44+
discard(collectedPath: string): Promise<void>;
4345
}>;
4446

4547
/**
@@ -91,6 +93,9 @@ export async function stopAndExportScreenRecording(
9193
stoppedAtMs: stoppedAtMs ?? now(),
9294
}));
9395
progress?.record(writeStopCheckpoint({ exportPath: snapshot.outPath, finalization }));
96+
// The copy is what a retry re-finalizes from, so it goes only after the finalization it produced is
97+
// journaled: from here a retry replays that finalization and never reads the copy again.
98+
await steps.discard(collectedPath);
9499
const { nativePathDisposition, warning, ...exportFacts } = finalization;
95100
const warnings = [warning, recorderWarning].filter(
96101
(entry): entry is string => entry !== undefined && entry.length > 0,

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,14 @@ function isSwiftVideoValidatorUnavailable(stderr: string, stdout: string): boole
141141
);
142142
}
143143

144+
/**
145+
* The container sniff alone: `ftyp` and `moov` for MP4, the EBML segment for WebM. It reads the file and
146+
* spawns nothing, which is what lets a stop check a copy before it trusts it (ADR 0024 2.3).
147+
*/
148+
export async function hasVideoContainer(filePath: string): Promise<boolean> {
149+
return (await likelyPlayableVideoContainer(filePath)) !== undefined;
150+
}
151+
144152
async function likelyPlayableVideoContainer(filePath: string): Promise<'mp4' | 'webm' | undefined> {
145153
try {
146154
const stats = fs.statSync(filePath);

‎packages/contracts/src/screen-recording-runtime-host.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,13 @@ export type WebScreenRecordingHost = Readonly<{
240240

241241
/** Closed post-processing authority for stable/playable validation, telemetry, and overlays. */
242242
export type ScreenRecordingFinalizer = Readonly<{
243+
/**
244+
* The container sniff a stop runs on its collected copy before it checkpoints that copy (ADR 0024
245+
* 2.3): `ftyp` and `moov` for MP4, the EBML segment for WebM. It spawns no validator; `complete`
246+
* still gives the export the full playability verdict. A file that fails is refused with the same
247+
* retriable unplayable error `complete` uses.
248+
*/
249+
sniff(input: Readonly<{ outputPath: string }>): Promise<void>;
243250
complete(
244251
input: Readonly<{
245252
outputPath: string;

‎packages/platform-android/src/recording/finalize.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,35 @@ test('a stop that already collected serves the export without signalling again',
128128
expect(files.exists('/tmp/capture.mp4')).toBe(true);
129129
});
130130

131+
test('a chunked export the finalizer refuses leaves the caller paths empty and the pulled set for the retry', async () => {
132+
const files = recordingFileStore();
133+
const host = recordingHost({
134+
files,
135+
finalize: {
136+
complete: async () => {
137+
throw new Error('recording was not finalized into a playable video');
138+
},
139+
},
140+
});
141+
const transport = await host.screenRecording.android.resolve(androidRecordingDevice);
142+
143+
await expect(
144+
finalizeAndroidRecording({
145+
host,
146+
transport,
147+
evidence: evidenceFor([REMOTE_CHUNK, '/sdcard/agent-device-recording-2.mp4']),
148+
manifestPath: '/sdcard/agent-device-recording-active.json',
149+
recording: snapshot(recordingInput(), 1),
150+
startedAtMs: 1,
151+
}),
152+
).rejects.toThrow('playable video');
153+
154+
expect(files.exists('/tmp/capture.mp4')).toBe(false);
155+
expect(files.exists('/tmp/capture.part-002.mp4')).toBe(false);
156+
expect(files.exists('/tmp/capture.collected.mp4')).toBe(true);
157+
expect(files.exists('/tmp/capture.collected.part-002.mp4')).toBe(true);
158+
});
159+
131160
test('answers with the disposition the device shows after disposal', async () => {
132161
const host = recordingHost({
133162
// The device agrees to every removal and then keeps listing the file, which is the case the

‎packages/platform-android/src/recording/finalize.ts‎

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,8 @@ export async function finalizeAndroidRecording(
8686
collectedPath,
8787
exportPath,
8888
}),
89+
discard: (collectedPath) =>
90+
discardCollectedChunks(host, collectedPath, evidence.chunks.length),
8991
},
9092
});
9193
return await recordCompletionAndDisposeChunks(params, outcome);
@@ -110,23 +112,31 @@ async function exportCollectedChunks(
110112
exportClientPath: recording.clientOutPath,
111113
count: evidence.chunks.length,
112114
});
113-
await copyCollectedChunksToExport(host, files);
114115
const chunked = files.length > 1;
115-
const finalization = await host.screenRecording.finalize.complete({
116-
outputPath: exportPath,
117-
showTouches: chunked ? false : recording.showTouches,
118-
gestureEvents: recording.gestureEvents,
119-
exportQuality: recording.exportQuality ?? 'medium',
120-
targetLabel: TARGET_LABEL,
121-
});
116+
let finalization: Awaited<
117+
ReturnType<PlatformRuntimeHost['screenRecording']['finalize']['complete']>
118+
>;
119+
try {
120+
await copyCollectedChunksToExport(host, files);
121+
finalization = await host.screenRecording.finalize.complete({
122+
outputPath: exportPath,
123+
showTouches: chunked ? false : recording.showTouches,
124+
gestureEvents: recording.gestureEvents,
125+
exportQuality: recording.exportQuality ?? 'medium',
126+
targetLabel: TARGET_LABEL,
127+
});
128+
} catch (error) {
129+
// The caller's paths only ever hold bytes the finalizer accepted. The collected set stays for the retry.
130+
for (const { served } of files) await host.screenRecording.outputs.remove(served.path);
131+
throw error;
132+
}
122133
// The length is measured on the pulled set because those are the bytes the recorder wrote; the
123134
// export is a copy of them, and a copy cannot tell the caller anything the original did not.
124135
const captured = measureCapturedWindow({
125136
chunkPaths: files.map(({ collected }) => collected.path),
126137
startedAtMs: params.startedAtMs,
127138
stoppedAtMs: params.stoppedAtMs,
128139
});
129-
await discardCollectedChunks(host, files);
130140
return finalizationFromExport({ finalization, captured, recording, chunked, files });
131141
}
132142

@@ -140,16 +150,17 @@ async function copyCollectedChunksToExport(
140150
}
141151

142152
/**
143-
* The collected set has served its purpose once the export is durable; keeping it would leave a second
144-
* copy of the video behind with nothing left to read it. Refusing to delete it is not a failure the
153+
* The collected set has served its purpose once its finalization is journaled; keeping it would leave a
154+
* second copy of the video behind with nothing left to read it. A refused removal is not a failure the
145155
* caller can act on, because their video already exists.
146156
*/
147157
async function discardCollectedChunks(
148158
host: PlatformRuntimeHost,
149-
files: readonly Readonly<{ collected: ScreenRecordingChunk; served: ScreenRecordingChunk }>[],
159+
collectedPath: string,
160+
count: number,
150161
): Promise<void> {
151-
for (const { collected } of files) {
152-
await host.screenRecording.outputs.remove(collected.path);
162+
for (let index = 1; index <= count; index += 1) {
163+
await host.screenRecording.outputs.remove(chunkPathAt(collectedPath, index));
153164
}
154165
}
155166

‎packages/platform-android/src/recording/fixtures.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,10 @@ export function recordingHost(overrides: Record<string, unknown>): PlatformRunti
109109
screenRecording: {
110110
android: { resolve: async () => transport },
111111
outputs: Object.assign({}, store.outputs, legacy.outputs),
112-
finalize: Object.assign({ complete: async () => ({}) }, legacy.finalize),
112+
finalize: Object.assign(
113+
{ sniff: async () => {}, complete: async () => ({}) },
114+
legacy.finalize,
115+
),
113116
},
114117
} as unknown as PlatformRuntimeHost;
115118
}

‎packages/platform-apple/src/recording/completion.ts‎

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -80,19 +80,23 @@ export async function finalizeAppleRecordingFromCollected(
8080
if (snapshot.invalidatedReason && !snapshot.showTouches) {
8181
throw new Error(`recording invalidated: ${snapshot.invalidatedReason}`);
8282
}
83-
await host.screenRecording.outputs.copy({ from: collectedPath, to: exportPath });
84-
const finalization = await asAppErrorAsync(() =>
85-
host.screenRecording.finalize.complete({
86-
outputPath: exportPath,
87-
showTouches: snapshot.invalidatedReason ? false : snapshot.showTouches,
88-
gestureEvents: snapshot.gestureEvents,
89-
exportQuality: snapshot.exportQuality ?? 'medium',
90-
targetLabel,
91-
}),
92-
);
93-
// The export is durable from this line on, so the copy the stop made is disposable. A refusal to
94-
// delete it is never an error: the caller's video already exists.
95-
await host.screenRecording.outputs.remove(collectedPath);
83+
let finalization: Awaited<ReturnType<typeof host.screenRecording.finalize.complete>>;
84+
try {
85+
await host.screenRecording.outputs.copy({ from: collectedPath, to: exportPath });
86+
finalization = await asAppErrorAsync(() =>
87+
host.screenRecording.finalize.complete({
88+
outputPath: exportPath,
89+
showTouches: snapshot.invalidatedReason ? false : snapshot.showTouches,
90+
gestureEvents: snapshot.gestureEvents,
91+
exportQuality: snapshot.exportQuality ?? 'medium',
92+
targetLabel,
93+
}),
94+
);
95+
} catch (error) {
96+
// `--out` only ever holds bytes the finalizer accepted. The collected copy stays for the retry.
97+
await host.screenRecording.outputs.remove(exportPath);
98+
throw error;
99+
}
96100
return {
97101
...finalization,
98102
...(snapshot.invalidatedReason

‎packages/platform-apple/src/recording/runtime.fixtures.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ export function appleRecordingHost(
6969
options: {
7070
apple?: Partial<ScreenRecordingRuntimeHost['apple']>;
7171
complete?: ScreenRecordingFinalizer['complete'];
72+
sniff?: ScreenRecordingFinalizer['sniff'];
7273
files?: ReturnType<typeof recordingFileStore>;
7374
outputs?: Partial<ScreenRecordingRuntimeHost['outputs']>;
7475
ownedProcesses?: ScreenRecordingRuntimeHost['ownedProcesses'];
@@ -112,7 +113,10 @@ export function appleRecordingHost(
112113
screenRecording: {
113114
apple,
114115
outputs: Object.assign({}, store.outputs, options.outputs),
115-
finalize: { complete: options.complete ?? (async () => ({})) },
116+
finalize: {
117+
sniff: options.sniff ?? (async () => {}),
118+
complete: options.complete ?? (async () => ({})),
119+
},
116120
ownedProcesses: options.ownedProcesses ?? { replace: () => {}, clear: () => {} },
117121
},
118122
};

0 commit comments

Comments
 (0)