Skip to content

Commit 23fcf9d

Browse files
committed
fix(android): clean recording evidence after its pid is reassigned
Exact-evidence cleanup refused to remove a recording whose recorder had already exited when Android reused the recorder's pid for an unrelated process, so the artifact and marker were retained indefinitely. Cleanup now treats a confirmed reassignment as proof the original recorder is gone and deletes the artifact only after a conclusive writer scan finds no writer for its path. It never signals the replacement process, and it retains the evidence when identity inspection or writer enumeration is inconclusive or a writer remains.
1 parent 22bd671 commit 23fcf9d

3 files changed

Lines changed: 203 additions & 17 deletions

File tree

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

Lines changed: 63 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -90,20 +90,31 @@ function validProcessIdentity(
9090
);
9191
}
9292

93+
/**
94+
* What a stop does with proof that the recorded recorder terminated while Android kept its numeric
95+
* pid. `refuse` is the export rule: an export cannot name the video a recorder it cannot identify
96+
* wrote. `require-unclaimed-artifact` is the exact-evidence cleanup rule: the recorder is proven gone,
97+
* so its artifact may be deleted once a conclusive scan finds no writer for its path. Both refuse to
98+
* signal the replacement process; the transport only ever kills a pid whose identity is the recorded
99+
* recorder, so a reassigned pid is never a stop target.
100+
*/
101+
export type AndroidRecordingReassignment = 'refuse' | 'require-unclaimed-artifact';
102+
93103
/**
94104
* Resolves whether the active (last) chunk's recorder had already exited, i.e. the video ends before
95105
* record stop. Earlier chunks always end before stop because rotation replaced them.
96106
*/
97107
export async function stopOwnedChunks(
98108
transport: Transport,
99109
chunks: readonly NativeChunk[],
110+
onReassignment: AndroidRecordingReassignment = 'refuse',
100111
): Promise<boolean> {
101112
const active = chunks.at(-1);
102113
let activeAlreadyExited = false;
103114
let failure: unknown;
104115
for (const chunk of [...chunks].reverse()) {
105116
try {
106-
const alreadyExited = await stopChunk(transport, chunk);
117+
const alreadyExited = await stopChunk(transport, chunk, onReassignment);
107118
if (chunk === active) activeAlreadyExited = alreadyExited;
108119
} catch (error) {
109120
failure ??= error;
@@ -218,6 +229,7 @@ async function rollbackStartedProcess(
218229
export async function stopChunk(
219230
transport: Transport,
220231
chunk: NativeChunk | undefined,
232+
onReassignment: AndroidRecordingReassignment = 'refuse',
221233
): Promise<boolean> {
222234
if (!chunk) return false;
223235
const processIdentity = {
@@ -227,16 +239,47 @@ export async function stopChunk(
227239
};
228240
const graceful = await transport.stop(processIdentity);
229241
if (graceful === 'already-missing') return true;
230-
if (graceful === 'ownership-lost')
231-
throw new Error(
232-
`Android screenrecord ownership could not be confirmed for pid ${chunk.remotePid}`,
233-
);
234-
if (await waitForStopped(transport, processIdentity)) return false;
242+
if (graceful === 'ownership-lost') {
243+
await acceptPidReassignment(transport, chunk, onReassignment);
244+
return true;
245+
}
246+
const poll = await waitForStopped(transport, processIdentity, onReassignment);
247+
if (poll === 'reassigned') {
248+
await acceptPidReassignment(transport, chunk, onReassignment);
249+
return false;
250+
}
251+
if (poll === 'gone') return false;
235252
const forced = await transport.stop(processIdentity, { force: true });
236253
if (forced === 'stopped' || forced === 'already-missing') return false;
254+
if (forced === 'ownership-lost' && onReassignment === 'require-unclaimed-artifact') {
255+
await acceptPidReassignment(transport, chunk, onReassignment);
256+
return false;
257+
}
237258
throw new Error(`failed to stop Android screenrecord pid ${chunk.remotePid}`);
238259
}
239260

261+
/**
262+
* Applies what a caller decided once the device proved the recorded recorder terminated while Android
263+
* kept its numeric pid. The replacement process is never signalled: a stop only kills a pid whose
264+
* readable identity is the recorded recorder, so a reassigned pid never receives a signal here.
265+
*/
266+
async function acceptPidReassignment(
267+
transport: Transport,
268+
chunk: NativeChunk,
269+
onReassignment: AndroidRecordingReassignment,
270+
): Promise<void> {
271+
if (onReassignment === 'refuse')
272+
throw new Error(
273+
`Android screenrecord ownership could not be confirmed for pid ${chunk.remotePid}`,
274+
);
275+
const writers = await transport.probeRunningWriters(chunk.remotePath);
276+
if (!writers.conclusive)
277+
throw new Error(`cannot list every recorder writing Android artifact: ${chunk.remotePath}`);
278+
const writer = writers.writers.at(0);
279+
if (writer)
280+
throw new Error(`Android artifact is still written by pid ${writer.pid}: ${chunk.remotePath}`);
281+
}
282+
240283
async function pullPlayableChunk(
241284
transport: Transport,
242285
remotePath: string,
@@ -250,21 +293,29 @@ async function pullPlayableChunk(
250293
throw new Error('failed to retrieve playable Android recording');
251294
}
252295

296+
/**
297+
* Polls until the process named by `processIdentity` is gone. A pid whose readable identity proves the
298+
* recorded recorder terminated is refused under `refuse` and reported under `require-unclaimed-artifact`,
299+
* which decides from a path-writer scan.
300+
*/
253301
async function waitForStopped(
254302
transport: Transport,
255303
processIdentity: Awaited<ReturnType<Transport['start']>>['process'],
256-
): Promise<boolean> {
304+
onReassignment: AndroidRecordingReassignment,
305+
): Promise<'gone' | 'reassigned' | 'timeout'> {
257306
for (let elapsed = 0; elapsed <= GRACEFUL_STOP_TIMEOUT_MS; elapsed += STOP_POLL_INTERVAL_MS) {
258307
const state = await transport.inspect(processIdentity);
259-
if (state === 'missing') return true;
308+
if (state === 'missing') return 'gone';
260309
if (provesAndroidScreenRecordTermination(state)) {
261-
throw new Error(
262-
`Android screenrecord ownership could not be confirmed for pid ${processIdentity.pid}`,
263-
);
310+
if (onReassignment === 'refuse')
311+
throw new Error(
312+
`Android screenrecord ownership could not be confirmed for pid ${processIdentity.pid}`,
313+
);
314+
return 'reassigned';
264315
}
265316
if (elapsed < GRACEFUL_STOP_TIMEOUT_MS) await delay(STOP_POLL_INTERVAL_MS);
266317
}
267-
return false;
318+
return 'timeout';
268319
}
269320

270321
function delay(ms: number): Promise<void> {

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

Lines changed: 135 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,25 @@
11
import { expect, test } from 'vitest';
22
import { cleanupVerifiedAndroidEvidence } from './cleanup.ts';
33
import { androidRecordingDevice, recordingHost, recordingInput } from './fixtures.ts';
4-
import { createNativeManifest } from './manifest.ts';
4+
import { createNativeManifest, type NativeManifest } from './manifest.ts';
5+
6+
const recordedChunk = {
7+
index: 1,
8+
remotePath: '/sdcard/agent-device-recording-1.mp4',
9+
remotePid: '42',
10+
remoteStartTime: '7',
11+
};
12+
13+
function reusedPidEvidence(): NativeManifest {
14+
return createNativeManifest(
15+
androidRecordingDevice,
16+
recordingInput(),
17+
1,
18+
[recordedChunk],
19+
undefined,
20+
'local',
21+
);
22+
}
523

624
test('attempts every fenced native chunk before retaining cleanup evidence', async () => {
725
const attempts: string[] = [];
@@ -49,3 +67,119 @@ test('attempts every fenced native chunk before retaining cleanup evidence', asy
4967
expect(attempts).toContain('stop:42');
5068
expect(attempts).toContain('stop:41');
5169
});
70+
71+
test('cleans evidence whose pid was reassigned once a conclusive scan finds no writer', async () => {
72+
const stops: Array<{ pid: string; force?: boolean }> = [];
73+
const removed: string[] = [];
74+
const markers: string[] = [];
75+
const host = recordingHost({
76+
stop: async ({ pid, force }: { pid: string; force?: boolean }) => {
77+
stops.push({ pid, force });
78+
return 'ownership-lost' as const;
79+
},
80+
findRunning: async () => ({ writers: [], conclusive: true }),
81+
remove: async (remotePath: string) => {
82+
removed.push(remotePath);
83+
return true;
84+
},
85+
removeManifest: async (manifestPath: string) => {
86+
markers.push(manifestPath);
87+
return true;
88+
},
89+
});
90+
const transport = await host.screenRecording.android.resolve(androidRecordingDevice);
91+
await expect(
92+
cleanupVerifiedAndroidEvidence(
93+
transport,
94+
reusedPidEvidence(),
95+
'/sdcard/agent-device-recording-active.json',
96+
),
97+
).resolves.toEqual({ status: 'cleaned' });
98+
expect(stops).toEqual([{ pid: '42', force: undefined }]);
99+
expect(removed).toEqual([recordedChunk.remotePath]);
100+
expect(markers).toEqual(['/sdcard/agent-device-recording-active.json']);
101+
});
102+
103+
test('cleans evidence whose pid is reassigned while its graceful stop is polled', async () => {
104+
const stops: Array<{ pid: string; force?: boolean }> = [];
105+
const host = recordingHost({
106+
stop: async ({ pid, force }: { pid: string; force?: boolean }) => {
107+
stops.push({ pid, force });
108+
return 'stopped' as const;
109+
},
110+
inspect: async () => 'ownership-lost' as const,
111+
findRunning: async () => ({ writers: [], conclusive: true }),
112+
removeManifest: async () => true,
113+
});
114+
const transport = await host.screenRecording.android.resolve(androidRecordingDevice);
115+
await expect(
116+
cleanupVerifiedAndroidEvidence(
117+
transport,
118+
reusedPidEvidence(),
119+
'/sdcard/agent-device-recording-active.json',
120+
),
121+
).resolves.toEqual({ status: 'cleaned' });
122+
expect(stops).toEqual([{ pid: '42', force: undefined }]);
123+
});
124+
125+
test.each([
126+
['an inconclusive scan', { writers: [], conclusive: false }],
127+
[
128+
'a foreign writer on the recorded path',
129+
{
130+
writers: [{ pid: '77', remotePath: recordedChunk.remotePath, startTime: '99' }],
131+
conclusive: true,
132+
},
133+
],
134+
] as const)('retains evidence whose reassigned pid path reports %s', async (_name, scan) => {
135+
const removed: string[] = [];
136+
let manifest = JSON.stringify(reusedPidEvidence());
137+
const host = recordingHost({
138+
stop: async () => 'ownership-lost' as const,
139+
findRunning: async () => scan,
140+
remove: async (remotePath: string) => {
141+
removed.push(remotePath);
142+
return true;
143+
},
144+
removeManifest: async () => {
145+
manifest = '';
146+
return true;
147+
},
148+
});
149+
const transport = await host.screenRecording.android.resolve(androidRecordingDevice);
150+
await expect(
151+
cleanupVerifiedAndroidEvidence(
152+
transport,
153+
reusedPidEvidence(),
154+
'/sdcard/agent-device-recording-active.json',
155+
),
156+
).resolves.toMatchObject({ status: 'cleanup-pending', reason: 'transport-failed' });
157+
expect(removed).toEqual([]);
158+
expect(manifest).not.toBe('');
159+
});
160+
161+
test('stops a recorder that still owns its pid without scanning the artifact path', async () => {
162+
const stops: Array<{ pid: string; force?: boolean }> = [];
163+
let scans = 0;
164+
const host = recordingHost({
165+
stop: async ({ pid, force }: { pid: string; force?: boolean }) => {
166+
stops.push({ pid, force });
167+
return 'stopped' as const;
168+
},
169+
inspect: async () => 'missing' as const,
170+
findRunning: async () => {
171+
scans += 1;
172+
return { writers: [], conclusive: true };
173+
},
174+
});
175+
const transport = await host.screenRecording.android.resolve(androidRecordingDevice);
176+
await expect(
177+
cleanupVerifiedAndroidEvidence(
178+
transport,
179+
reusedPidEvidence(),
180+
'/sdcard/agent-device-recording-active.json',
181+
),
182+
).resolves.toEqual({ status: 'cleaned' });
183+
expect(stops).toEqual([{ pid: '42', force: undefined }]);
184+
expect(scans).toBe(0);
185+
});

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

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,11 @@ export async function cleanupVerifiedAndroidEvidence(
1414
): Promise<CleanupOutcome> {
1515
try {
1616
const pendingPath = evidence.pendingRemotePath;
17-
await stopOwnedChunks(transport, [
18-
...evidence.chunks,
19-
...(await pendingWriterChunks(transport, evidence)),
20-
]);
17+
await stopOwnedChunks(
18+
transport,
19+
[...evidence.chunks, ...(await pendingWriterChunks(transport, evidence))],
20+
'require-unclaimed-artifact',
21+
);
2122
await cleanupChunks(transport, evidence.chunks);
2223
if (pendingPath !== undefined && !(await transport.remove(pendingPath)))
2324
throw new Error(`failed to remove Android recording artifact: ${pendingPath}`);

0 commit comments

Comments
 (0)