From f60c68ddee2f52c3279a12b8137cb479c5b26327 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 1 Nov 2026 07:36:57 +0100 Subject: [PATCH 1/6] fix(android): stop accepting screen-record rotations once a stop is claimed A rotation that was awaiting native work could publish its chunk and arm another 170s timer after finish or forceCleanup had already settled the recording, starting a recorder on the device for a recording that ended. The rotation lifecycle is now a phase the stop claims synchronously before it awaits the in-flight rotation, so scheduling and chunk publication both refuse after that point. --- .../src/recording/runtime.test.ts | 150 ++++++++++++++++++ .../platform-android/src/recording/runtime.ts | 51 +++++- 2 files changed, 196 insertions(+), 5 deletions(-) diff --git a/packages/platform-android/src/recording/runtime.test.ts b/packages/platform-android/src/recording/runtime.test.ts index 19ef2409bc..a7add21d32 100644 --- a/packages/platform-android/src/recording/runtime.test.ts +++ b/packages/platform-android/src/recording/runtime.test.ts @@ -190,6 +190,156 @@ test('serializes a failed rotation so finish cannot publish completion', async ( } }); +/** + * Pauses the rotation once, at the manifest write that would commit the chunk it has already + * launched, so a stop can be driven while that rotation is still in flight. + */ +function pauseChunkCommit() { + let paused = false; + let release!: () => void; + const released = new Promise((resolve) => { + release = resolve; + }); + return { + intercept: async (contents: string) => { + if (paused) return; + const written = JSON.parse(contents) as { chunks?: unknown[] }; + if (written.chunks?.length !== 2) return; + paused = true; + await released; + }, + isPaused: () => paused, + release: () => release(), + }; +} + +/** Pauses the launch of the next chunk, so a stop can be claimed before that child is reported. */ +function pauseNextLaunch() { + let waiting = false; + let release!: () => void; + const released = new Promise((resolve) => { + release = resolve; + }); + return { + intercept: async () => { + waiting = true; + await released; + }, + isWaiting: () => waiting, + release: () => release(), + }; +} + +test('does not start a chunk after finish when a successful rotation is still in flight', async () => { + vi.useFakeTimers(); + try { + let starts = 0; + let manifest = ''; + const commit = pauseChunkCommit(); + const runtime = await start({ + start: async () => { + starts += 1; + return recordingProcess(String(41 + starts)); + }, + writeManifest: async ({ contents }: { contents: string }) => { + manifest = contents; + await commit.intercept(contents); + }, + }); + const handle = (await runtime.screenRecordingStart(recordingInput())).pendingHandle.transfer(); + await vi.advanceTimersByTimeAsync(170_000); + expect(starts).toBe(2); + expect(commit.isPaused()).toBe(true); + const finishing = handle.finish(); + commit.release(); + await vi.advanceTimersByTimeAsync(5_000); + await expect(finishing).resolves.toMatchObject({ status: 'completed' }); + await vi.advanceTimersByTimeAsync(170_000); + expect(starts).toBe(2); + expect(JSON.parse(manifest)).toMatchObject({ + chunks: [{ remotePid: '42' }, { remotePid: '43' }], + }); + } finally { + vi.useRealTimers(); + } +}); + +test('does not start a chunk after force cleanup when a successful rotation is still in flight', async () => { + vi.useFakeTimers(); + try { + let starts = 0; + let manifest = ''; + const commit = pauseChunkCommit(); + const runtime = await start({ + start: async () => { + starts += 1; + return recordingProcess(String(41 + starts)); + }, + writeManifest: async ({ contents }: { contents: string }) => { + manifest = contents; + await commit.intercept(contents); + }, + readManifest: async () => + manifest ? { status: 'read' as const, contents: manifest } : { status: 'missing' as const }, + removeManifest: async () => { + manifest = ''; + return true; + }, + }); + const handle = (await runtime.screenRecordingStart(recordingInput())).pendingHandle.transfer(); + await vi.advanceTimersByTimeAsync(170_000); + expect(starts).toBe(2); + expect(commit.isPaused()).toBe(true); + const cleaning = handle.forceCleanup(); + commit.release(); + await vi.advanceTimersByTimeAsync(5_000); + await expect(cleaning).resolves.toEqual({ status: 'cleaned' }); + await vi.advanceTimersByTimeAsync(170_000); + expect(starts).toBe(2); + expect(manifest).toBe(''); + } finally { + vi.useRealTimers(); + } +}); + +test('rolls back the chunk a rotation launched after the stop was claimed', async () => { + vi.useFakeTimers(); + try { + let starts = 0; + let manifest = ''; + const launch = pauseNextLaunch(); + const startedPaths: string[] = []; + const removed: string[] = []; + const runtime = await start({ + start: async ({ remotePath }: { remotePath: string }) => { + starts += 1; + if (starts > 1) await launch.intercept(); + startedPaths.push(remotePath); + return recordingProcess(String(41 + starts)); + }, + writeManifest: async ({ contents }: { contents: string }) => { + manifest = contents; + }, + remove: async (remotePath: string) => { + removed.push(remotePath); + return true; + }, + }); + const handle = (await runtime.screenRecordingStart(recordingInput())).pendingHandle.transfer(); + await vi.advanceTimersByTimeAsync(170_000); + expect(launch.isWaiting()).toBe(true); + const finishing = handle.finish(); + launch.release(); + await vi.advanceTimersByTimeAsync(5_000); + await expect(finishing).resolves.toMatchObject({ status: 'completed' }); + expect(starts).toBe(2); + expect(removed).toContain(startedPaths[1]); + expect(JSON.parse(manifest).chunks).toHaveLength(1); + } finally { + vi.useRealTimers(); + } +}); + test('falls back to sequential rotation when concurrent start is unavailable', async () => { vi.useFakeTimers(); try { diff --git a/packages/platform-android/src/recording/runtime.ts b/packages/platform-android/src/recording/runtime.ts index cc0223858a..29f05ed313 100644 --- a/packages/platform-android/src/recording/runtime.ts +++ b/packages/platform-android/src/recording/runtime.ts @@ -28,6 +28,14 @@ import { cleanupAndroidRecording, reattachAndroidRecording, readLiveEvidence } f const ROTATE_AFTER_MS = 170_000; +/** + * The rotation lifecycle of one recording. `recording` may still start a chunk, `stopping` has been + * asked to stop and is settling the rotation it accepted, `finished` has committed its native + * evidence. Only `claimStop` and `confirmNativeCleanup` move it, so one owner decides whether a + * rotation may still start a chunk on the device. + */ +type RecordingPhase = 'recording' | 'stopping' | 'finished'; + export async function bindAndroidScreenRecordingRuntime(params: { host: PlatformRuntimeHost; device: DeviceInfo; @@ -70,8 +78,22 @@ async function startAndroidRecording(params: { let timer: ReturnType | undefined; let rotation: Promise | undefined; let rotationFailure: unknown; - let nativeCleanupConfirmed = false; + let phase: RecordingPhase = 'recording'; + /** + * Stops accepting rotations and arms nothing that could start one. The claim is synchronous, so the + * rotation already in flight cannot publish a chunk behind the stop that interrupted it. + */ + const claimStop = () => { + if (timer) clearTimeout(timer); + if (phase === 'recording') phase = 'stopping'; + }; + const acceptsRotations = () => phase === 'recording'; + /** Marks the native evidence settled, which is the only way out of `stopping`. */ + const confirmNativeCleanup = () => { + phase = 'finished'; + }; const schedule = () => { + if (!acceptsRotations()) return; timer = setTimeout(() => { rotation = rotate().catch((error: unknown) => { rotationFailure = error; @@ -79,6 +101,19 @@ async function startAndroidRecording(params: { }, ROTATE_AFTER_MS); timer.unref?.(); }; + /** + * Gives up a chunk the stop refused while it was launching, so its recorder cannot outlive the + * recording. An abandoned chunk that cannot be cleaned is a rotation failure: the marker still + * names it as pending, and only disposal may then settle it. + */ + const abandonUncommittedChunk = async (chunk: NativeChunk) => { + await rollbackChunks(transport, [chunk]); + await persistNativeManifest( + transport, + manifestPath, + createNativeManifest(device, input, startedAt, chunks, undefined, transport.mode), + ).catch(() => {}); + }; const rotate = async () => { const previous = chunks.at(-1); if (!previous) throw new Error('Android recording has no active chunk'); @@ -111,6 +146,10 @@ async function startAndroidRecording(params: { throw sequentialStartError instanceof Error ? sequentialStartError : concurrentStartError; } } + if (!acceptsRotations()) { + await abandonUncommittedChunk(next); + return; + } const nextChunks = [...chunks, { ...next, index: chunks.length + 1 }]; try { await persistNativeManifest( @@ -144,6 +183,8 @@ async function startAndroidRecording(params: { } throw error; } + // Committing is the last point a rotation can still be refused: the device holds this chunk from + // here, so it belongs to the recording even when a stop was claimed during the write. chunks = nextChunks; if (!previousStopped) await stopChunk(transport, previous); schedule(); @@ -151,7 +192,7 @@ async function startAndroidRecording(params: { schedule(); const handle = createScreenRecordingLiveHandle(snapshot(input, startedAt), { finish: async (current, progress) => { - if (timer) clearTimeout(timer); + claimStop(); await rotation; if (rotationFailure) throw rotationFailure; const outcome = await finalizeAndroidRecording({ @@ -163,12 +204,12 @@ async function startAndroidRecording(params: { startedAtMs: initial.startedAtMs, progress, }); - nativeCleanupConfirmed = true; + confirmNativeCleanup(); return outcome; }, forceCleanup: async () => { - if (timer) clearTimeout(timer); - if (nativeCleanupConfirmed) return { status: 'cleaned' } as const; + claimStop(); + if (phase === 'finished') return { status: 'cleaned' } as const; try { await rotation; } catch (error) { From 91c753b658b622650c230e43d4e90bcb5ed02c29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 1 Nov 2026 07:40:38 +0100 Subject: [PATCH 2/6] refactor(android): own repeated recording-request fields in one builder Extracts the requested-option fields the native marker and the durable descriptor both carry, and splits the rotation steps so the stop claim and each commit step read on their own. --- .../src/recording/manifest.ts | 26 +++- .../platform-android/src/recording/runtime.ts | 143 +++++++++--------- 2 files changed, 87 insertions(+), 82 deletions(-) diff --git a/packages/platform-android/src/recording/manifest.ts b/packages/platform-android/src/recording/manifest.ts index e93ff91e20..5f0f121161 100644 --- a/packages/platform-android/src/recording/manifest.ts +++ b/packages/platform-android/src/recording/manifest.ts @@ -90,6 +90,23 @@ export const androidScreenRecordingDescriptorCodec = Object.freeze({ : ({ status: 'invalid', message: 'Invalid Android screen-recording descriptor' } as const), }); +/** + * The requested recording options, carried unchanged by every durable record of the recording: an + * option recorded in one place and not another would make that record disagree about what was asked. + */ +export function recordingRequestFields(input: ScreenRecordingStartInput) { + return { + outputPath: input.outputPath, + ...(input.clientOutputPath === undefined ? {} : { clientOutputPath: input.clientOutputPath }), + scope: input.scope, + showTouches: input.showTouches, + recordOnlySession: input.recordOnlySession, + ...(input.activeSessionApp === undefined ? {} : { activeSessionApp: input.activeSessionApp }), + ...(input.exportQuality === undefined ? {} : { exportQuality: input.exportQuality }), + ...(input.fps === undefined ? {} : { fps: input.fps }), + }; +} + export function createNativeManifest( device: DeviceInfo, input: ScreenRecordingStartInput, @@ -106,14 +123,7 @@ export function createNativeManifest( sessionId: input.sessionId, deviceId: device.id, startedAt, - outputPath: input.outputPath, - ...(input.clientOutputPath === undefined ? {} : { clientOutputPath: input.clientOutputPath }), - scope: input.scope, - showTouches: input.showTouches, - recordOnlySession: input.recordOnlySession, - ...(input.activeSessionApp === undefined ? {} : { activeSessionApp: input.activeSessionApp }), - ...(input.exportQuality === undefined ? {} : { exportQuality: input.exportQuality }), - ...(input.fps === undefined ? {} : { fps: input.fps }), + ...recordingRequestFields(input), chunks, ...(pendingRemotePath === undefined ? {} : { pendingRemotePath }), transportMode, diff --git a/packages/platform-android/src/recording/runtime.ts b/packages/platform-android/src/recording/runtime.ts index 29f05ed313..ac560b58da 100644 --- a/packages/platform-android/src/recording/runtime.ts +++ b/packages/platform-android/src/recording/runtime.ts @@ -16,6 +16,7 @@ import { import { androidScreenRecordingDescriptorCodec, createNativeManifest, + recordingRequestFields, type NativeChunk, } from './manifest.ts'; import { rollbackChunks, stopChunk } from './chunks.ts'; @@ -102,85 +103,90 @@ async function startAndroidRecording(params: { timer.unref?.(); }; /** - * Gives up a chunk the stop refused while it was launching, so its recorder cannot outlive the - * recording. An abandoned chunk that cannot be cleaned is a rotation failure: the marker still - * names it as pending, and only disposal may then settle it. + * The active marker for the chunk set the recording currently owns. `pendingRemotePath` names a + * recorder the device holds that the marker has not committed, which is what keeps a chunk started + * during a claimed stop, or one whose rollback is unconfirmed, recoverable. */ - const abandonUncommittedChunk = async (chunk: NativeChunk) => { - await rollbackChunks(transport, [chunk]); - await persistNativeManifest( + const activeEvidence = (chunkList: readonly NativeChunk[], pendingRemotePath?: string) => + createNativeManifest(device, input, startedAt, chunkList, pendingRemotePath, transport.mode); + const launchChunk = async (previous: NativeChunk) => + await startPendingChunk({ transport, + device, + input, + startedAt, + chunks, manifestPath, - createNativeManifest(device, input, startedAt, chunks, undefined, transport.mode), - ).catch(() => {}); - }; - const rotate = async () => { - const previous = chunks.at(-1); - if (!previous) throw new Error('Android recording has no active chunk'); - let previousStopped = false; - let next: NativeChunk; + preferredDir: path.posix.dirname(previous.remotePath), + }); + /** + * Launches the next chunk, falling back to a sequential launch when the device refuses a second + * concurrent recorder. Reports whether that fallback had to retire the chunk being replaced. + */ + const launchRotationChunk = async ( + previous: NativeChunk, + ): Promise> => { try { - next = await startPendingChunk({ - transport, - device, - input, - startedAt, - chunks, - manifestPath, - preferredDir: path.posix.dirname(previous.remotePath), - }); + return { chunk: await launchChunk(previous), previousStopped: false }; } catch (concurrentStartError) { await stopChunk(transport, previous); - previousStopped = true; try { - next = await startPendingChunk({ - transport, - device, - input, - startedAt, - chunks, - manifestPath, - preferredDir: path.posix.dirname(previous.remotePath), - }); + return { chunk: await launchChunk(previous), previousStopped: true }; } catch (sequentialStartError) { throw sequentialStartError instanceof Error ? sequentialStartError : concurrentStartError; } } - if (!acceptsRotations()) { - await abandonUncommittedChunk(next); + }; + /** + * Gives up a chunk the stop refused while it was launching, so its recorder cannot outlive the + * recording. An abandoned chunk that cannot be cleaned is a rotation failure: the marker still + * names it as pending, and only disposal may then settle it. + */ + const abandonUncommittedChunk = async (chunk: NativeChunk) => { + await rollbackChunks(transport, [chunk]); + await persistNativeManifest(transport, manifestPath, activeEvidence(chunks)).catch(() => {}); + }; + /** Rewinds the marker to what the recording was before this rotation, once its commit failed. */ + const undoRotationCommit = async ( + next: NativeChunk, + previous: NativeChunk, + previousStopped: boolean, + ) => { + await rollbackChunks(transport, [next]).catch(() => {}); + if (previousStopped) { + await persistNativeManifest( + transport, + manifestPath, + activeEvidence(chunks, next.remotePath), + ).catch(() => {}); return; } - const nextChunks = [...chunks, { ...next, index: chunks.length + 1 }]; try { + await persistNativeManifest(transport, manifestPath, activeEvidence(chunks)); + } catch { + // The recorder this rotation was replacing is the only writer left, so the marker names the + // abandoned chunk as pending rather than claiming a chunk set the device no longer holds. + await stopChunk(transport, previous).catch(() => {}); await persistNativeManifest( transport, manifestPath, - createNativeManifest(device, input, startedAt, nextChunks, undefined, transport.mode), - ); + activeEvidence(chunks, next.remotePath), + ).catch(() => {}); + } + }; + const rotate = async () => { + const previous = chunks.at(-1); + if (!previous) throw new Error('Android recording has no active chunk'); + const { chunk: next, previousStopped } = await launchRotationChunk(previous); + if (!acceptsRotations()) { + await abandonUncommittedChunk(next); + return; + } + const nextChunks = [...chunks, { ...next, index: chunks.length + 1 }]; + try { + await persistNativeManifest(transport, manifestPath, activeEvidence(nextChunks)); } catch (error) { - await rollbackChunks(transport, [next]).catch(() => {}); - if (!previousStopped) { - try { - await persistNativeManifest( - transport, - manifestPath, - createNativeManifest(device, input, startedAt, chunks, undefined, transport.mode), - ); - } catch { - await stopChunk(transport, previous).catch(() => {}); - await persistNativeManifest( - transport, - manifestPath, - createNativeManifest(device, input, startedAt, chunks, next.remotePath, transport.mode), - ).catch(() => {}); - } - } else { - await persistNativeManifest( - transport, - manifestPath, - createNativeManifest(device, input, startedAt, chunks, next.remotePath, transport.mode), - ).catch(() => {}); - } + await undoRotationCommit(next, previous, previousStopped); throw error; } // Committing is the last point a rotation can still be refused: the device holds this chunk from @@ -198,7 +204,7 @@ async function startAndroidRecording(params: { const outcome = await finalizeAndroidRecording({ host, transport, - evidence: createNativeManifest(device, input, startedAt, chunks, undefined, transport.mode), + evidence: activeEvidence(chunks), manifestPath, recording: current, startedAtMs: initial.startedAtMs, @@ -238,18 +244,7 @@ async function startAndroidRecording(params: { descriptor: encodeDurableDescriptor(androidScreenRecordingDescriptorCodec, { backend: 'adb-screenrecord', manifestPath, - outputPath: input.outputPath, - ...(input.clientOutputPath === undefined - ? {} - : { clientOutputPath: input.clientOutputPath }), - scope: input.scope, - showTouches: input.showTouches, - recordOnlySession: input.recordOnlySession, - ...(input.activeSessionApp === undefined - ? {} - : { activeSessionApp: input.activeSessionApp }), - ...(input.exportQuality === undefined ? {} : { exportQuality: input.exportQuality }), - ...(input.fps === undefined ? {} : { fps: input.fps }), + ...recordingRequestFields(input), transportMode: transport.mode, }), }), From fa0effc59c5117d468e1733816f241ca0fab22e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 1 Nov 2026 09:22:27 +0100 Subject: [PATCH 3/6] fix(android): refuse rotation launches and commits once a stop is claimed --- .../platform-android/src/recording/chunks.ts | 11 + .../src/recording/fixtures.ts | 7 +- .../platform-android/src/recording/launch.ts | 20 +- .../src/recording/runtime.test.ts | 227 +++++++++++++++++- .../platform-android/src/recording/runtime.ts | 43 +++- 5 files changed, 294 insertions(+), 14 deletions(-) diff --git a/packages/platform-android/src/recording/chunks.ts b/packages/platform-android/src/recording/chunks.ts index 43f51fb58b..730a43fac1 100644 --- a/packages/platform-android/src/recording/chunks.ts +++ b/packages/platform-android/src/recording/chunks.ts @@ -18,6 +18,17 @@ export class AndroidScreenRecordingStartRollbackUnconfirmed extends Error { } } +/** + * Refusal raised when the recording's stop was claimed before a launch was dispatched, or before a + * rotation's commit reached the device. It is how the launch and commit owners report that the stop + * outran them, so the rotation can withdraw without starting or publishing anything. + */ +export class AndroidScreenRecordingStopClaimed extends Error { + constructor() { + super('Android screenrecord rotation refused: the recording stop was already claimed'); + } +} + export function candidateRemotePaths( preferredDir: string | undefined, now = Date.now(), diff --git a/packages/platform-android/src/recording/fixtures.ts b/packages/platform-android/src/recording/fixtures.ts index 57662a9f63..9d22012bd7 100644 --- a/packages/platform-android/src/recording/fixtures.ts +++ b/packages/platform-android/src/recording/fixtures.ts @@ -88,8 +88,11 @@ export function recordingHost(overrides: Record): PlatformRunti legacy.readManifest ? await legacy.readManifest(manifestPath) : { status: 'missing' as const }, - writeManifest: async (request: { manifestPath: string; contents: string }) => { - await legacy.writeManifest?.(request); + writeManifest: async ( + request: { manifestPath: string; contents: string }, + signal?: AbortSignal, + ) => { + await legacy.writeManifest?.(request, signal); }, removeManifest: async (manifestPath: string) => legacy.removeManifest ? await legacy.removeManifest(manifestPath) : true, diff --git a/packages/platform-android/src/recording/launch.ts b/packages/platform-android/src/recording/launch.ts index d0e6001f75..9a5dc45238 100644 --- a/packages/platform-android/src/recording/launch.ts +++ b/packages/platform-android/src/recording/launch.ts @@ -3,6 +3,7 @@ import type { PlatformRuntimeHost } from '@agent-device/contracts/platform-runti import type { ScreenRecordingStartInput } from '@agent-device/contracts/screen-recording-runtime'; import { AndroidScreenRecordingStartRollbackUnconfirmed, + AndroidScreenRecordingStopClaimed, candidateRemotePaths, rollbackChunks, startChunkAt, @@ -99,20 +100,37 @@ export async function startPendingChunk(params: { chunks: readonly NativeChunk[]; manifestPath: string; preferredDir: string; + // Refuses a device start once the recording's stop has been claimed. + launchAdmission: AbortSignal; }): Promise { - const { transport, device, input, startedAt, chunks, manifestPath, preferredDir } = params; + const { + transport, + device, + input, + startedAt, + chunks, + manifestPath, + preferredDir, + launchAdmission, + } = params; let last: unknown; for (const remotePath of candidateRemotePaths(preferredDir)) { + if (launchAdmission.aborted) throw new AndroidScreenRecordingStopClaimed(); await persistNativeManifest( transport, manifestPath, createNativeManifest(device, input, startedAt, chunks, remotePath, transport.mode), ); try { + // The pending evidence is on the device, but the stop may have been claimed while it was being + // written. Refuse here rather than dispatch a recorder the recording has already given up. + if (launchAdmission.aborted) throw new AndroidScreenRecordingStopClaimed(); return await startChunkAt(transport, remotePath, input); } catch (error) { if (error instanceof AndroidScreenRecordingStartRollbackUnconfirmed) throw error; try { + // Clears the pending marker, which names a recorder nothing launched when the refusal raised + // this error. await persistNativeManifest( transport, manifestPath, diff --git a/packages/platform-android/src/recording/runtime.test.ts b/packages/platform-android/src/recording/runtime.test.ts index a7add21d32..618c8fac97 100644 --- a/packages/platform-android/src/recording/runtime.test.ts +++ b/packages/platform-android/src/recording/runtime.test.ts @@ -191,8 +191,8 @@ test('serializes a failed rotation so finish cannot publish completion', async ( }); /** - * Pauses the rotation once, at the manifest write that would commit the chunk it has already - * launched, so a stop can be driven while that rotation is still in flight. + * Holds the manifest write that would commit the second chunk, before its contents reach the + * device, so a stop can be claimed while that publication is still in flight. */ function pauseChunkCommit() { let paused = false; @@ -213,19 +213,83 @@ function pauseChunkCommit() { }; } +/** + * Holds the manifest write that names the next chunk as pending, before any recorder for it is + * launched, so a stop can be claimed between the marker reaching the device and the launch. + */ +function pausePendingEvidence() { + let paused = false; + let release!: () => void; + const released = new Promise((resolve) => { + release = resolve; + }); + return { + intercept: async (contents: string) => { + if (paused) return; + const written = JSON.parse(contents) as { chunks?: unknown[]; pendingRemotePath?: string }; + if (written.chunks?.length !== 1 || written.pendingRemotePath === undefined) return; + paused = true; + await released; + }, + isPaused: () => paused, + release: () => release(), + }; +} + +/** + * Holds the manifest write that would commit the second chunk, standing in for the transport's + * `printf %s … > tmp && mv -f tmp manifest`, which publishes nothing until its command finishes. + */ +function pauseChunkCommitPublication() { + let paused = false; + let release!: () => void; + const released = new Promise((resolve) => { + release = resolve; + }); + return { + intercept: async (contents: string) => { + if (paused) return; + const written = JSON.parse(contents) as { chunks?: unknown[] }; + if (written.chunks?.length !== 2) return; + paused = true; + await released; + }, + isPaused: () => paused, + release: () => release(), + }; +} + +/** Holds the graceful stop of the recorder a sequential rotation is retiring. */ +function pauseChunkRetirement(pid: string) { + let paused = false; + let release!: () => void; + const released = new Promise((resolve) => { + release = resolve; + }); + return { + intercept: async (stoppedPid: string) => { + if (stoppedPid !== pid || paused) return; + paused = true; + await released; + }, + isPaused: () => paused, + release: () => release(), + }; +} + /** Pauses the launch of the next chunk, so a stop can be claimed before that child is reported. */ function pauseNextLaunch() { - let waiting = false; + let paused = false; let release!: () => void; const released = new Promise((resolve) => { release = resolve; }); return { intercept: async () => { - waiting = true; + paused = true; await released; }, - isWaiting: () => waiting, + isWaiting: () => paused, release: () => release(), }; } @@ -270,6 +334,7 @@ test('does not start a chunk after force cleanup when a successful rotation is s let starts = 0; let manifest = ''; const commit = pauseChunkCommit(); + const stopped = new Set(); const runtime = await start({ start: async () => { starts += 1; @@ -279,6 +344,13 @@ test('does not start a chunk after force cleanup when a successful rotation is s manifest = contents; await commit.intercept(contents); }, + stop: async ({ pid }: { pid: string }) => { + if (stopped.has(pid)) return 'already-missing' as const; + stopped.add(pid); + return 'stopped' as const; + }, + inspect: async ({ pid }: { pid: string }) => + stopped.has(pid) ? ('missing' as const) : ('owned-alive' as const), readManifest: async () => manifest ? { status: 'read' as const, contents: manifest } : { status: 'missing' as const }, removeManifest: async () => { @@ -296,6 +368,9 @@ test('does not start a chunk after force cleanup when a successful rotation is s await expect(cleaning).resolves.toEqual({ status: 'cleaned' }); await vi.advanceTimersByTimeAsync(170_000); expect(starts).toBe(2); + // The rotation's recorder was signaled whichever way its commit settled: adopted then cleaned, or + // refused then rolled back. Either way no recorder outlives the cleanup. + expect(stopped).toEqual(new Set(['42', '43'])); expect(manifest).toBe(''); } finally { vi.useRealTimers(); @@ -310,6 +385,7 @@ test('rolls back the chunk a rotation launched after the stop was claimed', asyn const launch = pauseNextLaunch(); const startedPaths: string[] = []; const removed: string[] = []; + const stopped = new Set(); const runtime = await start({ start: async ({ remotePath }: { remotePath: string }) => { starts += 1; @@ -320,6 +396,13 @@ test('rolls back the chunk a rotation launched after the stop was claimed', asyn writeManifest: async ({ contents }: { contents: string }) => { manifest = contents; }, + stop: async ({ pid }: { pid: string }) => { + if (stopped.has(pid)) return 'already-missing' as const; + stopped.add(pid); + return 'stopped' as const; + }, + inspect: async ({ pid }: { pid: string }) => + stopped.has(pid) ? ('missing' as const) : ('owned-alive' as const), remove: async (remotePath: string) => { removed.push(remotePath); return true; @@ -333,6 +416,7 @@ test('rolls back the chunk a rotation launched after the stop was claimed', asyn await vi.advanceTimersByTimeAsync(5_000); await expect(finishing).resolves.toMatchObject({ status: 'completed' }); expect(starts).toBe(2); + expect(stopped).toEqual(new Set(['42', '43'])); expect(removed).toContain(startedPaths[1]); expect(JSON.parse(manifest).chunks).toHaveLength(1); } finally { @@ -340,6 +424,139 @@ test('rolls back the chunk a rotation launched after the stop was claimed', asyn } }); +test('does not launch the sequential fallback after the stop was claimed', async () => { + vi.useFakeTimers(); + try { + let starts = 0; + let manifest = ''; + const retirement = pauseChunkRetirement('42'); + const stopped = new Set(); + const runtime = await start({ + start: async () => { + starts += 1; + if (starts > 1) throw new Error('concurrent start unavailable'); + return recordingProcess('42'); + }, + stop: async ({ pid }: { pid: string }) => { + await retirement.intercept(pid); + if (stopped.has(pid)) return 'already-missing' as const; + stopped.add(pid); + return 'stopped' as const; + }, + inspect: async ({ pid }: { pid: string }) => + stopped.has(pid) ? ('missing' as const) : ('owned-alive' as const), + writeManifest: async ({ contents }: { contents: string }) => { + manifest = contents; + }, + }); + const handle = (await runtime.screenRecordingStart(recordingInput())).pendingHandle.transfer(); + await vi.advanceTimersByTimeAsync(170_000); + expect(starts).toBe(3); + expect(retirement.isPaused()).toBe(true); + const finishing = handle.finish(); + retirement.release(); + await vi.advanceTimersByTimeAsync(5_000); + await expect(finishing).resolves.toMatchObject({ status: 'completed' }); + expect(starts).toBe(3); + expect(JSON.parse(manifest).chunks).toEqual([expect.objectContaining({ remotePid: '42' })]); + } finally { + vi.useRealTimers(); + } +}); + +test('does not dispatch a chunk launch whose pending evidence was written after the stop was claimed', async () => { + vi.useFakeTimers(); + try { + let starts = 0; + let manifest = ''; + const pending = pausePendingEvidence(); + const runtime = await start({ + start: async () => { + starts += 1; + return recordingProcess(String(41 + starts)); + }, + writeManifest: async ({ contents }: { contents: string }) => { + manifest = contents; + await pending.intercept(contents); + }, + }); + const handle = (await runtime.screenRecordingStart(recordingInput())).pendingHandle.transfer(); + await vi.advanceTimersByTimeAsync(170_000); + expect(pending.isPaused()).toBe(true); + const finishing = handle.finish(); + pending.release(); + await vi.advanceTimersByTimeAsync(5_000); + await expect(finishing).resolves.toMatchObject({ status: 'completed' }); + expect(starts).toBe(1); + // The refusal clears the pending marker through the normal rollback, so the device is never left + // naming a recorder nothing launched. + expect(JSON.parse(manifest)).toEqual( + expect.objectContaining({ chunks: [expect.objectContaining({ remotePid: '42' })] }), + ); + expect(JSON.parse(manifest)).not.toHaveProperty('pendingRemotePath'); + } finally { + vi.useRealTimers(); + } +}); + +test('does not adopt a chunk whose commit publication was refused by the stop', async () => { + vi.useFakeTimers(); + try { + let starts = 0; + // What the device's marker actually holds: a write publishes only once it resolves unaborted, the + // way the transport publishes through `printf %s … > tmp && mv -f tmp manifest`. + const deviceWrites: string[] = []; + const commit = pauseChunkCommitPublication(); + const startedPaths: string[] = []; + const stopped = new Set(); + const removed: string[] = []; + const runtime = await start({ + start: async ({ remotePath }: { remotePath: string }) => { + starts += 1; + startedPaths.push(remotePath); + return recordingProcess(String(41 + starts)); + }, + writeManifest: async ({ contents }: { contents: string }, signal?: AbortSignal) => { + await commit.intercept(contents); + if (signal?.aborted) throw new Error('manifest publication canceled'); + deviceWrites.push(contents); + }, + stop: async ({ pid }: { pid: string }) => { + if (stopped.has(pid)) return 'already-missing' as const; + stopped.add(pid); + return 'stopped' as const; + }, + inspect: async ({ pid }: { pid: string }) => + stopped.has(pid) ? ('missing' as const) : ('owned-alive' as const), + remove: async (remotePath: string) => { + removed.push(remotePath); + return true; + }, + }); + const handle = (await runtime.screenRecordingStart(recordingInput())).pendingHandle.transfer(); + await vi.advanceTimersByTimeAsync(170_000); + expect(starts).toBe(2); + expect(commit.isPaused()).toBe(true); + const finishing = handle.finish(); + commit.release(); + await vi.advanceTimersByTimeAsync(5_000); + await expect(finishing).resolves.toMatchObject({ status: 'completed' }); + // The refused publication never reached the device, and the marker the rollback re-published is + // the chunk set the recording held before this rotation. + expect(deviceWrites.map((contents) => JSON.parse(contents).chunks.length)).not.toContain(2); + const finalMarker = JSON.parse(deviceWrites.at(-1)!); + expect(finalMarker.chunks).toEqual([expect.objectContaining({ remotePid: '42' })]); + expect(finalMarker).not.toHaveProperty('pendingRemotePath'); + expect(finalMarker).toHaveProperty('completion'); + expect(stopped).toEqual(new Set(['42', '43'])); + // The refused chunk's artifact is removed by the rollback, and the recording's own chunk by the + // finish's disposal. + expect(removed).toEqual([startedPaths[1], startedPaths[0]]); + } finally { + vi.useRealTimers(); + } +}); + test('falls back to sequential rotation when concurrent start is unavailable', async () => { vi.useFakeTimers(); try { diff --git a/packages/platform-android/src/recording/runtime.ts b/packages/platform-android/src/recording/runtime.ts index ac560b58da..a1c12edced 100644 --- a/packages/platform-android/src/recording/runtime.ts +++ b/packages/platform-android/src/recording/runtime.ts @@ -19,7 +19,7 @@ import { recordingRequestFields, type NativeChunk, } from './manifest.ts'; -import { rollbackChunks, stopChunk } from './chunks.ts'; +import { AndroidScreenRecordingStopClaimed, rollbackChunks, stopChunk } from './chunks.ts'; import { startInitialTransaction, startPendingChunk } from './launch.ts'; import { persistNativeManifest } from './manifest-store.ts'; import { snapshot } from './live-snapshot.ts'; @@ -80,12 +80,19 @@ async function startAndroidRecording(params: { let rotation: Promise | undefined; let rotationFailure: unknown; let phase: RecordingPhase = 'recording'; + /** + * The recording's stop admission. It is aborted the moment either stop operation begins, so the + * launch owner and the commit boundary can each refuse at the device call they are about to make, + * rather than only being checked where the rotation happens to look. + */ + const stopAdmission = new AbortController(); /** * Stops accepting rotations and arms nothing that could start one. The claim is synchronous, so the - * rotation already in flight cannot publish a chunk behind the stop that interrupted it. + * rotation already in flight cannot start or publish a chunk behind the stop that interrupted it. */ const claimStop = () => { if (timer) clearTimeout(timer); + stopAdmission.abort(); if (phase === 'recording') phase = 'stopping'; }; const acceptsRotations = () => phase === 'recording'; @@ -118,6 +125,7 @@ async function startAndroidRecording(params: { chunks, manifestPath, preferredDir: path.posix.dirname(previous.remotePath), + launchAdmission: stopAdmission.signal, }); /** * Launches the next chunk, falling back to a sequential launch when the device refuses a second @@ -129,6 +137,10 @@ async function startAndroidRecording(params: { try { return { chunk: await launchChunk(previous), previousStopped: false }; } catch (concurrentStartError) { + // The stop refused this rotation before it dispatched anything. It must not retire the chunk + // being replaced either: the stop owns that recorder now. + if (concurrentStartError instanceof AndroidScreenRecordingStopClaimed) + throw concurrentStartError; await stopChunk(transport, previous); try { return { chunk: await launchChunk(previous), previousStopped: true }; @@ -177,20 +189,39 @@ async function startAndroidRecording(params: { const rotate = async () => { const previous = chunks.at(-1); if (!previous) throw new Error('Android recording has no active chunk'); - const { chunk: next, previousStopped } = await launchRotationChunk(previous); + let next: NativeChunk; + let previousStopped: boolean; + try { + ({ chunk: next, previousStopped } = await launchRotationChunk(previous)); + } catch (error) { + // The stop outran this rotation before it dispatched a device start. It launched nothing, so + // the stop owns the recording's evidence and this is not a rotation failure. + if (error instanceof AndroidScreenRecordingStopClaimed) return; + throw error; + } if (!acceptsRotations()) { await abandonUncommittedChunk(next); return; } const nextChunks = [...chunks, { ...next, index: chunks.length + 1 }]; try { - await persistNativeManifest(transport, manifestPath, activeEvidence(nextChunks)); + // The stop admission is carried to the device write itself: the publication is refused once a + // stop is claimed, so this cannot adopt a chunk the stop has already given up on. + await persistNativeManifest( + transport, + manifestPath, + activeEvidence(nextChunks), + stopAdmission.signal, + ); } catch (error) { await undoRotationCommit(next, previous, previousStopped); + // The stop refused this publication, and the rollback gave the chunk back. The recording's own + // chunks are intact, so the stop may finalize them rather than report a rotation it caused. + if (stopAdmission.signal.aborted) return; throw error; } - // Committing is the last point a rotation can still be refused: the device holds this chunk from - // here, so it belongs to the recording even when a stop was claimed during the write. + // The publication reached the device before any stop refused it, so the recording owns this + // chunk from here even when a stop was claimed while the write was in flight. chunks = nextChunks; if (!previousStopped) await stopChunk(transport, previous); schedule(); From a49c253de2b993c846097f110f1c25323086ec6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 1 Nov 2026 10:13:33 +0100 Subject: [PATCH 4/6] fix(android): let a rotation commit settle on its own outcome Cancelling the host command cannot undo the on-device rename or prove it never ran, so an abort signal cannot fence the commit boundary: it discarded a chunk the device had already committed, and it turned an unconfirmed rollback into a clean stop. Drop the signal from the commit write, run it to its real outcome, and keep the child in the recovery evidence whenever its rollback cannot be confirmed. Launch admission stays: no recorder starts after a stop. --- .../platform-android/src/recording/chunks.ts | 7 +- .../src/recording/runtime.test.ts | 178 +++++++++++++----- .../platform-android/src/recording/runtime.ts | 48 ++--- 3 files changed, 167 insertions(+), 66 deletions(-) diff --git a/packages/platform-android/src/recording/chunks.ts b/packages/platform-android/src/recording/chunks.ts index 730a43fac1..99080334d0 100644 --- a/packages/platform-android/src/recording/chunks.ts +++ b/packages/platform-android/src/recording/chunks.ts @@ -19,9 +19,10 @@ export class AndroidScreenRecordingStartRollbackUnconfirmed extends Error { } /** - * Refusal raised when the recording's stop was claimed before a launch was dispatched, or before a - * rotation's commit reached the device. It is how the launch and commit owners report that the stop - * outran them, so the rotation can withdraw without starting or publishing anything. + * Refusal raised when the recording's stop was claimed before a chunk launch was dispatched. It is + * how the launch owner reports that the stop outran it, so the rotation withdraws without starting a + * recorder. Only `startPendingChunk` raises it: a commit already in flight runs to its real outcome, + * because cancelling the host command cannot prove what the device's rename did. */ export class AndroidScreenRecordingStopClaimed extends Error { constructor() { diff --git a/packages/platform-android/src/recording/runtime.test.ts b/packages/platform-android/src/recording/runtime.test.ts index 618c8fac97..a888d11102 100644 --- a/packages/platform-android/src/recording/runtime.test.ts +++ b/packages/platform-android/src/recording/runtime.test.ts @@ -191,8 +191,9 @@ test('serializes a failed rotation so finish cannot publish completion', async ( }); /** - * Holds the manifest write that would commit the second chunk, before its contents reach the - * device, so a stop can be claimed while that publication is still in flight. + * Holds the manifest write that would commit the second chunk, standing in for the transport's + * `printf %s … > tmp && mv -f tmp manifest`, which publishes on the device only once its command + * finishes. Aborting the host command cannot undo that rename or prove it never ran. */ function pauseChunkCommit() { let paused = false; @@ -236,29 +237,6 @@ function pausePendingEvidence() { }; } -/** - * Holds the manifest write that would commit the second chunk, standing in for the transport's - * `printf %s … > tmp && mv -f tmp manifest`, which publishes nothing until its command finishes. - */ -function pauseChunkCommitPublication() { - let paused = false; - let release!: () => void; - const released = new Promise((resolve) => { - release = resolve; - }); - return { - intercept: async (contents: string) => { - if (paused) return; - const written = JSON.parse(contents) as { chunks?: unknown[] }; - if (written.chunks?.length !== 2) return; - paused = true; - await released; - }, - isPaused: () => paused, - release: () => release(), - }; -} - /** Holds the graceful stop of the recorder a sequential rotation is retiring. */ function pauseChunkRetirement(pid: string) { let paused = false; @@ -499,17 +477,19 @@ test('does not dispatch a chunk launch whose pending evidence was written after } }); -test('does not adopt a chunk whose commit publication was refused by the stop', async () => { +test('collects a chunk whose commit published while the stop was in flight', async () => { vi.useFakeTimers(); try { let starts = 0; - // What the device's marker actually holds: a write publishes only once it resolves unaborted, the - // way the transport publishes through `printf %s … > tmp && mv -f tmp manifest`. + // What the device's marker actually holds. A publication runs `printf %s … > tmp && mv -f tmp + // manifest`: the rename commits the marker on the device while the host command is still + // running, and aborting that command makes the host reject even though the rename already + // happened. This mock models that device outcome. const deviceWrites: string[] = []; - const commit = pauseChunkCommitPublication(); + const commit = pauseChunkCommit(); const startedPaths: string[] = []; + const pulled: string[] = []; const stopped = new Set(); - const removed: string[] = []; const runtime = await start({ start: async ({ remotePath }: { remotePath: string }) => { starts += 1; @@ -518,8 +498,8 @@ test('does not adopt a chunk whose commit publication was refused by the stop', }, writeManifest: async ({ contents }: { contents: string }, signal?: AbortSignal) => { await commit.intercept(contents); - if (signal?.aborted) throw new Error('manifest publication canceled'); deviceWrites.push(contents); + if (signal?.aborted) throw new Error('manifest publication canceled'); }, stop: async ({ pid }: { pid: string }) => { if (stopped.has(pid)) return 'already-missing' as const; @@ -528,9 +508,9 @@ test('does not adopt a chunk whose commit publication was refused by the stop', }, inspect: async ({ pid }: { pid: string }) => stopped.has(pid) ? ('missing' as const) : ('owned-alive' as const), - remove: async (remotePath: string) => { - removed.push(remotePath); - return true; + pullPlayable: async ({ remotePath }: { remotePath: string }) => { + pulled.push(remotePath); + return { stdout: '', stderr: '', exitCode: 0, playable: true }; }, }); const handle = (await runtime.screenRecordingStart(recordingInput())).pendingHandle.transfer(); @@ -541,17 +521,131 @@ test('does not adopt a chunk whose commit publication was refused by the stop', commit.release(); await vi.advanceTimersByTimeAsync(5_000); await expect(finishing).resolves.toMatchObject({ status: 'completed' }); - // The refused publication never reached the device, and the marker the rollback re-published is - // the chunk set the recording held before this rotation. - expect(deviceWrites.map((contents) => JSON.parse(contents).chunks.length)).not.toContain(2); + // The rename committed the chunk on the device while the stop was in flight, so the recording + // keeps it: finish collects both chunks and stops both recorders. + expect(pulled).toEqual([startedPaths[0], startedPaths[1]]); + expect(stopped).toEqual(new Set(['42', '43'])); const finalMarker = JSON.parse(deviceWrites.at(-1)!); - expect(finalMarker.chunks).toEqual([expect.objectContaining({ remotePid: '42' })]); + expect(finalMarker.chunks).toEqual([ + expect.objectContaining({ remotePid: '42' }), + expect.objectContaining({ remotePid: '43' }), + ]); expect(finalMarker).not.toHaveProperty('pendingRemotePath'); expect(finalMarker).toHaveProperty('completion'); - expect(stopped).toEqual(new Set(['42', '43'])); - // The refused chunk's artifact is removed by the rollback, and the recording's own chunk by the - // finish's disposal. - expect(removed).toEqual([startedPaths[1], startedPaths[0]]); + } finally { + vi.useRealTimers(); + } +}); + +test('retains the child when the rotation commit fails after the stop was claimed', async () => { + vi.useFakeTimers(); + try { + let starts = 0; + let manifest = ''; + const commit = pauseChunkCommit(); + const startedPaths: string[] = []; + const stopped = new Set(); + const runtime = await start({ + start: async ({ remotePath }: { remotePath: string }) => { + starts += 1; + startedPaths.push(remotePath); + return recordingProcess(String(41 + starts)); + }, + writeManifest: async ({ contents }: { contents: string }) => { + await commit.intercept(contents); + // The commit itself fails: a real write failure, not a stop refusing it. + if ((JSON.parse(contents) as { chunks: unknown[] }).chunks.length === 2) + throw new Error('rotation manifest failed'); + manifest = contents; + }, + stop: async ({ pid }: { pid: string }) => { + // The child's recorder cannot be confirmed gone, so its rollback stays unconfirmed. + if (pid === '43') return 'uncertain' as const; + if (stopped.has(pid)) return 'already-missing' as const; + stopped.add(pid); + return 'stopped' as const; + }, + inspect: async ({ pid }: { pid: string }) => + pid === '43' || !stopped.has(pid) ? ('owned-alive' as const) : ('missing' as const), + readManifest: async () => + manifest ? { status: 'read' as const, contents: manifest } : { status: 'missing' as const }, + }); + const handle = (await runtime.screenRecordingStart(recordingInput())).pendingHandle.transfer(); + await vi.advanceTimersByTimeAsync(170_000); + expect(starts).toBe(2); + expect(commit.isPaused()).toBe(true); + const finishing = handle.finish(); + const refused = expect(finishing).rejects.toThrow('rotation manifest failed'); + commit.release(); + await vi.advanceTimersByTimeAsync(20_000); + // A failed commit is a rotation failure even after a claimed stop: finish cannot report success + // while the child's recorder is unaccounted for. + await refused; + // The unconfirmed child stays in the recovery evidence as pending, so disposal can settle it. + const marker = JSON.parse(manifest); + expect(marker.chunks).toEqual([expect.objectContaining({ remotePid: '42' })]); + expect(marker).toMatchObject({ pendingRemotePath: startedPaths[1] }); + const cleaning = handle.forceCleanup(); + const pending = expect(cleaning).resolves.toMatchObject({ status: 'cleanup-pending' }); + await vi.advanceTimersByTimeAsync(30_000); + await pending; + expect(manifest).not.toBe(''); + } finally { + vi.useRealTimers(); + } +}); + +test('retains the child when its artifact removal fails after the stop was claimed', async () => { + vi.useFakeTimers(); + try { + let starts = 0; + let manifest = ''; + const commit = pauseChunkCommit(); + const startedPaths: string[] = []; + const stopped = new Set(); + const runtime = await start({ + start: async ({ remotePath }: { remotePath: string }) => { + starts += 1; + startedPaths.push(remotePath); + return recordingProcess(String(41 + starts)); + }, + writeManifest: async ({ contents }: { contents: string }) => { + await commit.intercept(contents); + if ((JSON.parse(contents) as { chunks: unknown[] }).chunks.length === 2) + throw new Error('rotation manifest failed'); + manifest = contents; + }, + stop: async ({ pid }: { pid: string }) => { + if (stopped.has(pid)) return 'already-missing' as const; + stopped.add(pid); + return 'stopped' as const; + }, + inspect: async ({ pid }: { pid: string }) => + stopped.has(pid) ? ('missing' as const) : ('owned-alive' as const), + // The recorder is gone but the device will not give the file back, so the rollback stays + // unconfirmed and the file keeps its name in the evidence. + remove: async (remotePath: string) => remotePath !== startedPaths[1], + readManifest: async () => + manifest ? { status: 'read' as const, contents: manifest } : { status: 'missing' as const }, + }); + const handle = (await runtime.screenRecordingStart(recordingInput())).pendingHandle.transfer(); + await vi.advanceTimersByTimeAsync(170_000); + expect(commit.isPaused()).toBe(true); + const finishing = handle.finish(); + const refused = expect(finishing).rejects.toThrow('rotation manifest failed'); + commit.release(); + await vi.advanceTimersByTimeAsync(20_000); + await refused; + const marker = JSON.parse(manifest); + expect(marker.chunks).toEqual([expect.objectContaining({ remotePid: '42' })]); + expect(marker).toMatchObject({ pendingRemotePath: startedPaths[1] }); + expect(stopped.has('43')).toBe(true); + // Disposal re-attempts the file the device still holds and stays pending while it cannot. + const cleaning = handle.forceCleanup(); + const pending = expect(cleaning).resolves.toMatchObject({ status: 'cleanup-pending' }); + await vi.advanceTimersByTimeAsync(30_000); + await pending; + expect(manifest).not.toBe(''); } finally { vi.useRealTimers(); } diff --git a/packages/platform-android/src/recording/runtime.ts b/packages/platform-android/src/recording/runtime.ts index a1c12edced..3a29f3c553 100644 --- a/packages/platform-android/src/recording/runtime.ts +++ b/packages/platform-android/src/recording/runtime.ts @@ -81,14 +81,17 @@ async function startAndroidRecording(params: { let rotationFailure: unknown; let phase: RecordingPhase = 'recording'; /** - * The recording's stop admission. It is aborted the moment either stop operation begins, so the - * launch owner and the commit boundary can each refuse at the device call they are about to make, - * rather than only being checked where the rotation happens to look. + * The recording's launch admission. It is aborted the moment either stop operation begins, so the + * launch owner refuses at the device call it is about to make and a claimed stop never starts + * another recorder. The commit boundary deliberately does not use it: aborting the host command + * cannot prove the on-device rename did not happen, so only that write's real outcome decides what + * the marker holds. */ const stopAdmission = new AbortController(); /** * Stops accepting rotations and arms nothing that could start one. The claim is synchronous, so the - * rotation already in flight cannot start or publish a chunk behind the stop that interrupted it. + * rotation already in flight cannot launch a chunk behind the stop that interrupted it. A commit + * already in flight may still commit, and the stop collects that chunk like any other. */ const claimStop = () => { if (timer) clearTimeout(timer); @@ -158,14 +161,24 @@ async function startAndroidRecording(params: { await rollbackChunks(transport, [chunk]); await persistNativeManifest(transport, manifestPath, activeEvidence(chunks)).catch(() => {}); }; - /** Rewinds the marker to what the recording was before this rotation, once its commit failed. */ + /** + * Rewinds the marker to what the recording was before this rotation, once its commit failed. The + * child may never be dropped from the evidence: when its rollback cannot be confirmed, the marker + * names its path as pending, which is what keeps an unaccounted recorder recoverable and makes the + * rotation failure the stop reports rather than a clean finish. + */ const undoRotationCommit = async ( next: NativeChunk, previous: NativeChunk, previousStopped: boolean, - ) => { - await rollbackChunks(transport, [next]).catch(() => {}); - if (previousStopped) { + ): Promise => { + const rollbackUncertain = await rollbackChunks(transport, [next]).then( + () => false, + () => true, + ); + // An uncertain rollback leaves the child's recorder, its artifact, or both on the device, so the + // marker must keep naming them as pending. + if (rollbackUncertain || previousStopped) { await persistNativeManifest( transport, manifestPath, @@ -205,23 +218,16 @@ async function startAndroidRecording(params: { } const nextChunks = [...chunks, { ...next, index: chunks.length + 1 }]; try { - // The stop admission is carried to the device write itself: the publication is refused once a - // stop is claimed, so this cannot adopt a chunk the stop has already given up on. - await persistNativeManifest( - transport, - manifestPath, - activeEvidence(nextChunks), - stopAdmission.signal, - ); + // No stop signal reaches this write. Aborting the host command cannot undo the on-device rename + // or prove it never ran, so the write runs to its real outcome: success means the device + // committed the chunk, whatever the stop did while the write was in flight. + await persistNativeManifest(transport, manifestPath, activeEvidence(nextChunks)); } catch (error) { await undoRotationCommit(next, previous, previousStopped); - // The stop refused this publication, and the rollback gave the chunk back. The recording's own - // chunks are intact, so the stop may finalize them rather than report a rotation it caused. - if (stopAdmission.signal.aborted) return; throw error; } - // The publication reached the device before any stop refused it, so the recording owns this - // chunk from here even when a stop was claimed while the write was in flight. + // The write committed this chunk on the device, so the recording keeps it and the stop collects + // it like every other committed chunk. A committed chunk is never discarded. chunks = nextChunks; if (!previousStopped) await stopChunk(transport, previous); schedule(); From 5bfb20e7382d36f05fa0cb256264cfc494886c7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 1 Nov 2026 10:58:46 +0100 Subject: [PATCH 5/6] fix(android): read a rotation's own retirement as not the platform limit A sequential fallback that retired the active recorder and then withdrew left that recorder's absence to be read by finalization as a 180s platform-limit exit, so a normal stop disclosed truncation that never happened. Refuse to begin a retirement once a stop is claimed, record a retirement already dispatched as the recording's own doing, and have finalize suppress the limit disclosure for it. --- .../platform-android/src/recording/finalize.ts | 10 +++++++++- .../src/recording/runtime.test.ts | 7 ++++++- .../platform-android/src/recording/runtime.ts | 17 +++++++++++++++++ 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/packages/platform-android/src/recording/finalize.ts b/packages/platform-android/src/recording/finalize.ts index c598c9fce8..9454da7194 100644 --- a/packages/platform-android/src/recording/finalize.ts +++ b/packages/platform-android/src/recording/finalize.ts @@ -53,6 +53,12 @@ export async function finalizeAndroidRecording( startedAtMs: number; progress?: DurableCaptureProgress; reachedLimit?: boolean; + /** + * Whether a rotation retired the active chunk's recorder itself and withdrew before replacing + * it. That retirement explains an already-gone active recorder, so its absence is not the + * platform's 180 s limit truncating a recording that was still running. + */ + activeRecorderRetired?: boolean; }>, ): Promise> { const { host, transport, evidence, recording, startedAtMs, progress } = params; @@ -66,7 +72,9 @@ export async function finalizeAndroidRecording( // growing is the evidence the recorder stopped writing (ADR 0024 2.2). The platform limit is // disclosed here rather than at the export because it is a fact about the recorder, and the // journal is what keeps it attached to a stop that has to be driven again. - reachedLimit = (await stopOwnedChunks(transport, evidence.chunks)) || reachedLimit; + const activeRecorderAlreadyGone = await stopOwnedChunks(transport, evidence.chunks); + reachedLimit = + (activeRecorderAlreadyGone && params.activeRecorderRetired !== true) || reachedLimit; await waitForStableArtifacts(transport, evidence.chunks); return { observation: { recorder: 'confirmed' }, diff --git a/packages/platform-android/src/recording/runtime.test.ts b/packages/platform-android/src/recording/runtime.test.ts index a888d11102..b70893bb5b 100644 --- a/packages/platform-android/src/recording/runtime.test.ts +++ b/packages/platform-android/src/recording/runtime.test.ts @@ -434,7 +434,12 @@ test('does not launch the sequential fallback after the stop was claimed', async const finishing = handle.finish(); retirement.release(); await vi.advanceTimersByTimeAsync(5_000); - await expect(finishing).resolves.toMatchObject({ status: 'completed' }); + const outcome = await finishing; + expect(outcome).toMatchObject({ status: 'completed' }); + // The rotation retired this recorder itself, so its absence is not the 180 s platform limit. + expect((outcome as { result?: { warning?: string } }).result?.warning ?? '').not.toMatch( + /platform limit/, + ); expect(starts).toBe(3); expect(JSON.parse(manifest).chunks).toEqual([expect.objectContaining({ remotePid: '42' })]); } finally { diff --git a/packages/platform-android/src/recording/runtime.ts b/packages/platform-android/src/recording/runtime.ts index 3a29f3c553..2f70e9f309 100644 --- a/packages/platform-android/src/recording/runtime.ts +++ b/packages/platform-android/src/recording/runtime.ts @@ -80,6 +80,12 @@ async function startAndroidRecording(params: { let rotation: Promise | undefined; let rotationFailure: unknown; let phase: RecordingPhase = 'recording'; + /** + * Whether a rotation retired the active chunk's recorder itself and then withdrew without + * replacing it. Finalization must read that recorder's absence as this recording's own retirement, + * not as the platform's 180 s limit cutting a recorder short. + */ + let retiredActiveRecorder = false; /** * The recording's launch admission. It is aborted the moment either stop operation begins, so the * launch owner refuses at the device call it is about to make and a claimed stop never starts @@ -144,6 +150,13 @@ async function startAndroidRecording(params: { // being replaced either: the stop owns that recorder now. if (concurrentStartError instanceof AndroidScreenRecordingStopClaimed) throw concurrentStartError; + // The stop owns the current recorder now, so do not begin retiring it for a replacement this + // recording has already given up on. Finalization will stop it like any active chunk. + if (stopAdmission.signal.aborted) throw new AndroidScreenRecordingStopClaimed(); + // From here the retirement is this recording's own doing, so a later finalization must not + // read this recorder's absence as the platform's 180 s limit, whether or not the replacement + // this retirement was made for ever launches. + retiredActiveRecorder = true; await stopChunk(transport, previous); try { return { chunk: await launchChunk(previous), previousStopped: true }; @@ -229,6 +242,9 @@ async function startAndroidRecording(params: { // The write committed this chunk on the device, so the recording keeps it and the stop collects // it like every other committed chunk. A committed chunk is never discarded. chunks = nextChunks; + // The active chunk is this freshly launched one now, so a retirement recorded earlier can no + // longer explain its absence. + retiredActiveRecorder = false; if (!previousStopped) await stopChunk(transport, previous); schedule(); }; @@ -246,6 +262,7 @@ async function startAndroidRecording(params: { recording: current, startedAtMs: initial.startedAtMs, progress, + activeRecorderRetired: retiredActiveRecorder, }); confirmNativeCleanup(); return outcome; From c4760a56722479c6759305fcfac2956da59b2630 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 1 Nov 2026 12:12:09 +0100 Subject: [PATCH 6/6] fix(android): count only a confirmed retirement as the recording's own A sequential fallback marked the active recorder retired before its stop answered, so a recorder the platform's 180s cap had already ended was read by finalization as this recording's own retirement and its truncation disclosure went silent. Record the retirement only when the stop confirmed the recorder was live, and drop the dead aborted-commit branch from the publication test. --- .../src/recording/runtime.test.ts | 54 +++++++++++++++++-- .../platform-android/src/recording/runtime.ts | 17 +++--- 2 files changed, 58 insertions(+), 13 deletions(-) diff --git a/packages/platform-android/src/recording/runtime.test.ts b/packages/platform-android/src/recording/runtime.test.ts index b70893bb5b..93f43f74bb 100644 --- a/packages/platform-android/src/recording/runtime.test.ts +++ b/packages/platform-android/src/recording/runtime.test.ts @@ -447,6 +447,50 @@ test('does not launch the sequential fallback after the stop was claimed', async } }); +test('still discloses the platform limit when the recorder a fallback retired had already exited', async () => { + vi.useFakeTimers(); + try { + let starts = 0; + let manifest = ''; + const retirement = pauseChunkRetirement('42'); + const runtime = await start({ + start: async () => { + starts += 1; + if (starts > 1) throw new Error('concurrent start unavailable'); + return recordingProcess('42'); + }, + // The platform's 180 s cap ended this recorder just before the rotation reached it, so the + // retirement is told the recorder was already gone rather than confirming a stop of its own. + stop: async ({ pid }: { pid: string }) => { + await retirement.intercept(pid); + return 'already-missing' as const; + }, + inspect: async () => 'missing' as const, + writeManifest: async ({ contents }: { contents: string }) => { + manifest = contents; + }, + }); + const handle = (await runtime.screenRecordingStart(recordingInput())).pendingHandle.transfer(); + await vi.advanceTimersByTimeAsync(170_000); + expect(starts).toBe(3); + expect(retirement.isPaused()).toBe(true); + const finishing = handle.finish(); + retirement.release(); + await vi.advanceTimersByTimeAsync(5_000); + const outcome = await finishing; + expect(outcome).toMatchObject({ status: 'completed' }); + // The recorder died of the platform limit before the retirement ran, so that disclosure must + // survive the rotation that tried to retire it. + expect((outcome as { result?: { warning?: string } }).result?.warning ?? '').toMatch( + /platform limit/, + ); + expect(starts).toBe(3); + expect(JSON.parse(manifest).chunks).toEqual([expect.objectContaining({ remotePid: '42' })]); + } finally { + vi.useRealTimers(); + } +}); + test('does not dispatch a chunk launch whose pending evidence was written after the stop was claimed', async () => { vi.useFakeTimers(); try { @@ -487,9 +531,10 @@ test('collects a chunk whose commit published while the stop was in flight', asy try { let starts = 0; // What the device's marker actually holds. A publication runs `printf %s … > tmp && mv -f tmp - // manifest`: the rename commits the marker on the device while the host command is still - // running, and aborting that command makes the host reject even though the rename already - // happened. This mock models that device outcome. + // manifest`: the rename commits the marker on the device while the host command is still running, + // and aborting that command would make the host reject even though the rename already happened. + // The commit therefore takes no stop signal at all, and this mock holds that write in flight + // across the stop to show its real outcome decides what the recording keeps. const deviceWrites: string[] = []; const commit = pauseChunkCommit(); const startedPaths: string[] = []; @@ -501,10 +546,9 @@ test('collects a chunk whose commit published while the stop was in flight', asy startedPaths.push(remotePath); return recordingProcess(String(41 + starts)); }, - writeManifest: async ({ contents }: { contents: string }, signal?: AbortSignal) => { + writeManifest: async ({ contents }: { contents: string }) => { await commit.intercept(contents); deviceWrites.push(contents); - if (signal?.aborted) throw new Error('manifest publication canceled'); }, stop: async ({ pid }: { pid: string }) => { if (stopped.has(pid)) return 'already-missing' as const; diff --git a/packages/platform-android/src/recording/runtime.ts b/packages/platform-android/src/recording/runtime.ts index 2f70e9f309..4ea5facdc8 100644 --- a/packages/platform-android/src/recording/runtime.ts +++ b/packages/platform-android/src/recording/runtime.ts @@ -81,9 +81,10 @@ async function startAndroidRecording(params: { let rotationFailure: unknown; let phase: RecordingPhase = 'recording'; /** - * Whether a rotation retired the active chunk's recorder itself and then withdrew without - * replacing it. Finalization must read that recorder's absence as this recording's own retirement, - * not as the platform's 180 s limit cutting a recorder short. + * Whether a rotation retired the active chunk's recorder itself, confirmed by that stop, and then + * withdrew without replacing it. Finalization must read that recorder's absence as this recording's + * own retirement, not as the platform's 180 s limit cutting a recorder short. A retirement that + * found the recorder already gone is not this recording's doing and records nothing. */ let retiredActiveRecorder = false; /** @@ -153,11 +154,11 @@ async function startAndroidRecording(params: { // The stop owns the current recorder now, so do not begin retiring it for a replacement this // recording has already given up on. Finalization will stop it like any active chunk. if (stopAdmission.signal.aborted) throw new AndroidScreenRecordingStopClaimed(); - // From here the retirement is this recording's own doing, so a later finalization must not - // read this recorder's absence as the platform's 180 s limit, whether or not the replacement - // this retirement was made for ever launches. - retiredActiveRecorder = true; - await stopChunk(transport, previous); + // Retiring this recorder is this recording's own doing, so a later finalization must not read + // its absence as the platform's 180 s limit, whether or not the replacement this retirement was + // made for ever launches. Only a stop that confirmed the recorder was live counts: one already + // gone means the recorder ended on its own, and that disclosure must survive this rotation. + if (!(await stopChunk(transport, previous))) retiredActiveRecorder = true; try { return { chunk: await launchChunk(previous), previousStopped: true }; } catch (sequentialStartError) {