diff --git a/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts b/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts index 7a317a3bd2..a44f78613d 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts @@ -186,9 +186,15 @@ export type SessionProviderOptions = { stalledCleanup?: boolean; /** How many `forward --remove` calls hang until their cleanup budget aborts them. */ stalledForwardRemovals?: number; + /** + * How many snapshot requests the first helper process leaves unanswered. A stall belongs to the + * helper that hung, so a helper started after it answers. + */ stalledSnapshots?: number; - /** How many snapshot requests each helper process answers before `stalledSnapshots` applies. */ + /** How many snapshot requests the first helper answers before `stalledSnapshots` applies. */ answeredSnapshotsBeforeStall?: number; + /** Called when the helper receives a request it leaves unanswered. */ + onStalledSnapshot?: () => void; /** Whether `adb features` advertises the shell protocol that forwards device exit status. */ shellProtocolV2?: boolean; /** Make the `adb features` probe fail the way an adb too old to know the command does. */ @@ -211,7 +217,7 @@ export type FakeAndroidHelperRuntimeRelease = export function createSessionProvider(options: SessionProviderOptions): AndroidAdbProvider { bindAndroidAdbTestHost(); - let stalledSnapshots = options.stalledSnapshots ?? 0; + let spawnedHelpers = 0; return { exec: createSessionExec(options), spawn: (args) => { @@ -219,6 +225,8 @@ export function createSessionProvider(options: SessionProviderOptions): AndroidA const port = readSessionPort(args); const process = new FakeAndroidProcess(); options.processes?.push(process); + spawnedHelpers += 1; + let stalledSnapshots = spawnedHelpers === 1 ? (options.stalledSnapshots ?? 0) : 0; let snapshotCount = 0; const sockets = new Set(); const server = net.createServer((socket) => { @@ -263,6 +271,7 @@ export function createSessionProvider(options: SessionProviderOptions): AndroidA snapshotCount += 1; if (snapshotCount > (options.answeredSnapshotsBeforeStall ?? 0) && stalledSnapshots > 0) { stalledSnapshots -= 1; + options.onStalledSnapshot?.(); return; } const body = ``; diff --git a/packages/platform-android/src/__tests__/snapshot-helper-session.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-session.test.ts index 38cfa9a472..e835a98e9b 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session.test.ts @@ -99,53 +99,69 @@ test('retires a persistent session that exceeds the helper command budget', asyn ); }); -test('cancels a stalled snapshot, retires its helper, and starts the next capture cleanly', async () => { - const calls: (readonly string[])[] = []; - const processes: FakeAndroidProcess[] = []; - const provider = createSessionProvider({ calls, processes, stalledSnapshots: 1 }); - const controller = new AbortController(); - const capture = captureAndroidSnapshotWithHelperSession({ - adb: provider.exec, - adbProvider: provider, - deviceKey: 'android:emulator-5554', - signal: controller.signal, - }); - setTimeout(() => controller.abort(new Error('wait deadline exceeded')), 10); +// A cancellation lands wherever the caller's deadline falls (#4030): before the helper reports +// ready, or while the helper holds the snapshot request it never answers. +for (const cancelPoint of ['before the helper is ready', 'while the helper stalls'] as const) { + test(`cancels a capture ${cancelPoint}, retires its helper, and starts the next capture cleanly`, async () => { + const calls: (readonly string[])[] = []; + const processes: FakeAndroidProcess[] = []; + const controller = new AbortController(); + const cancel = () => controller.abort(new Error('wait deadline exceeded')); + const provider = createSessionProvider({ + calls, + processes, + stalledSnapshots: 1, + ...(cancelPoint === 'while the helper stalls' ? { onStalledSnapshot: cancel } : {}), + }); + const capture = captureAndroidSnapshotWithHelperSession({ + adb: provider.exec, + adbProvider: { + ...provider, + spawn: (args, options) => { + const process = provider.spawn!(args, options); + if (cancelPoint === 'before the helper is ready') cancel(); + return process; + }, + }, + deviceKey: 'android:emulator-5554', + signal: controller.signal, + }); - await assert.rejects(capture, /wait deadline exceeded/); - assert.equal(processes[0]?.killed, true); - assert.equal( - calls.some((args) => args[0] === 'forward' && args[1] === '--remove'), - true, - ); + await assert.rejects(capture, /wait deadline exceeded/); + assert.equal(processes[0]?.killed, true); + assert.equal( + calls.some((args) => args[0] === 'forward' && args[1] === '--remove'), + true, + ); - const next = await captureAndroidSnapshotWithHelperSession({ - adb: provider.exec, - adbProvider: provider, - deviceKey: 'android:emulator-5554', + const next = await captureAndroidSnapshotWithHelperSession({ + adb: provider.exec, + adbProvider: provider, + deviceKey: 'android:emulator-5554', + }); + assert.match(next?.xml ?? '', /snapshot 1/); + assert.equal(next?.metadata.sessionReused, false); + assert.equal(processes.length, 2); }); - assert.match(next?.xml ?? '', /snapshot 1/); - assert.equal(next?.metadata.sessionReused, false); - assert.equal(processes.length, 2); -}); +} test('canceled capture joins canceled external cleanup before returning', async () => { const calls: (readonly string[])[] = []; const cleanupAborts: (readonly string[])[] = []; + const controller = new AbortController(); const provider = createSessionProvider({ calls, cleanupAborts, stalledSnapshots: 1, stalledCleanup: true, + onStalledSnapshot: () => controller.abort(new Error('wait deadline exceeded')), }); - const controller = new AbortController(); const capture = captureAndroidSnapshotWithHelperSession({ adb: provider.exec, adbProvider: provider, deviceKey: 'android:emulator-5554', signal: controller.signal, }); - setTimeout(() => controller.abort(new Error('wait deadline exceeded')), 10); const outcome = await Promise.race([ capture.then( diff --git a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts new file mode 100644 index 0000000000..a1643e25d8 --- /dev/null +++ b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts @@ -0,0 +1,311 @@ +import assert from 'node:assert/strict'; +import { afterEach, beforeEach, test, vi } from 'vitest'; + +// Time does not pass on its own: a wait without a signal ends at once, and a cancellable wait ends +// only when its signal aborts, so a wait that ignores the caller's cancellation is observable. +vi.mock('../adb.ts', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + sleep: vi.fn( + async (_ms: number, signal?: AbortSignal) => + await new Promise((resolve) => { + if (!signal || signal.aborted) return resolve(); + signal.addEventListener('abort', () => resolve(), { once: true }); + }), + ), + }; +}); + +import type { DeviceInfo } from '@agent-device/kernel/device'; +import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import type { AndroidAdbExecutorResult, AndroidAdbProvider } from '../adb-executor.ts'; +import { isRefusedInstrumentationStart } from '../instrumentation-helper.ts'; +import { snapshotAndroid } from '../snapshot.ts'; +import { resetAndroidSnapshotHelperInstallCache } from '../snapshot-helper-install.ts'; +import { resetAndroidSnapshotHelperSessions } from '../snapshot-helper-session-lifecycle.ts'; +import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './test-utils/android-snapshot-helper.ts'; +import { + ANDROID_HELPER_INSTALLED_VERSION_PROBE, + createSessionProvider, + androidHelperInstrumentationOutput, + androidHelperRuntimeProbeResult, + FakeAndroidProcess, + isAndroidHelperRuntimeForceStop, + isAndroidHelperRuntimeProbe, +} from './snapshot-helper-session.fixtures.ts'; +import { bindAndroidAdbTestHost } from './test-utils/android-host-test-setup.ts'; + +const device: DeviceInfo = { + platform: 'android', + id: 'emulator-5556', + name: 'Pixel', + kind: 'emulator', + booted: true, +}; + +const HELPER_PACKAGE = ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.packageName; +// The component as `am` names it in its refusal: fully qualified, not the `/.Class` short form. +const HELPER_RUNNER = `${HELPER_PACKAGE}/${HELPER_PACKAGE}.SnapshotInstrumentation`; + +// What `am instrument -w` printed, verbatim, when the system refused to start the uninstalled helper +// on an Android 15 (API 35) emulator: ActivityManagerService reports the refusal as status -1, and +// then `am` throws INSTRUMENTATION_FAILED. The live retry run on the same device printed the same. +const REFUSED_STDOUT = [ + `INSTRUMENTATION_STATUS: Error=Unable to find instrumentation info for: ComponentInfo{${HELPER_RUNNER}}`, + 'INSTRUMENTATION_STATUS: id=ActivityManagerService', + 'INSTRUMENTATION_STATUS_CODE: -1', + '', +].join('\n'); +const REFUSED_STDERR = [ + `android.util.AndroidException: INSTRUMENTATION_FAILED: ${HELPER_RUNNER}`, + '\tat com.android.commands.am.Instrument.run(Instrument.java:543)', + '\tat com.android.commands.am.Am.runInstrument(Am.java:213)', + '', +].join('\n'); +const INSTRUMENTATION_FAILED_RUN: AndroidAdbExecutorResult = { + exitCode: 1, + stdout: REFUSED_STDOUT, + stderr: REFUSED_STDERR, +}; + +const CAPTURED_RUN: AndroidAdbExecutorResult = { + exitCode: 0, + stdout: androidHelperInstrumentationOutput( + '', + ), + stderr: '', +}; + +beforeEach(async () => { + await resetAndroidSnapshotHelperSessions(); + resetAndroidSnapshotHelperInstallCache(); +}); + +afterEach(async () => { + await resetAndroidSnapshotHelperSessions(); +}); + +type OneShotRun = AndroidAdbExecutorResult | AppError; + +/** + * A device whose helper is installed and current. Its persistent session either exits before it is + * ready, refused like the one-shot run (#4109), or becomes ready and then fails its capture. Each + * one-shot run answers with the next of `oneShotRuns`; an `AppError` is thrown as the executor does. + */ +function freshlyBootedHelper( + oneShotRuns: OneShotRun[], + session: 'exits-before-ready' | 'ready-then-fails' = 'exits-before-ready', +): { provider: AndroidAdbProvider; calls: (readonly string[])[] } { + bindAndroidAdbTestHost(); + const calls: (readonly string[])[] = []; + const runs = [...oneShotRuns]; + const failingSession = createSessionProvider({ calls: [], responseMode: 'malformed' }); + return { + calls, + provider: { + exec: async (args) => { + calls.push(args); + if (args.includes('--show-versioncode')) return ANDROID_HELPER_INSTALLED_VERSION_PROBE; + if (isAndroidHelperRuntimeProbe(args)) return androidHelperRuntimeProbeResult(); + if (!isOneShotRun(args)) return { exitCode: 0, stdout: '', stderr: '' }; + const run = runs.shift() ?? CAPTURED_RUN; + if (run instanceof AppError) throw run; + return run; + }, + spawn: (args, options) => { + if (session === 'ready-then-fails') return failingSession.spawn!(args, options); + const process = new FakeAndroidProcess(); + setImmediate(() => { + process.stdout.write(REFUSED_STDOUT); + process.stderr.write(REFUSED_STDERR); + process.emitExit(1, null); + }); + return process; + }, + }, + }; +} + +const isOneShotRun = (args: readonly string[]) => args.includes('instrument'); + +async function snapshotRejection(provider: AndroidAdbProvider) { + try { + await snapshotAndroid(device, { + helperAdb: provider, + helperArtifact: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + }); + } catch (error) { + return normalizeError(error); + } + assert.fail('expected the snapshot to fail'); +} + +// One row per condition of a refused start: each row is the captured refusal with exactly that +// condition broken, so dropping the condition from the predicate flips its rows and no others. +const refusal = { exitCode: 1, stdout: REFUSED_STDOUT, stderr: REFUSED_STDERR }; +const refusalRows: { + breaks: string; + run: { exitCode: number | null; stdout: string; stderr: string; signal?: string }; +}[] = [ + { breaks: 'nothing', run: refusal }, + { + breaks: 'the INSTRUMENTATION_FAILED envelope', + run: { ...refusal, stderr: REFUSED_STDERR.split('\n').slice(1).join('\n') }, + }, + { breaks: 'an exit status', run: { ...refusal, exitCode: null } }, + { breaks: 'a non-zero exit', run: { ...refusal, exitCode: 0 } }, + { breaks: 'no signal', run: { ...refusal, signal: 'SIGKILL' } }, + { + breaks: 'the system reporter', + run: { ...refusal, stdout: REFUSED_STDOUT.replace('id=ActivityManagerService', 'id=Other') }, + }, + { + breaks: 'the refusal status code', + run: { + ...refusal, + stdout: REFUSED_STDOUT.replace('STATUS_CODE: -1', 'STATUS_CODE: -2'), + }, + }, + ...[ + [ + 'a trailing helper status', + 'INSTRUMENTATION_STATUS: agentDeviceProtocol=1\nINSTRUMENTATION_STATUS: payloadBase64=PHg+\n', + ], + ['a malformed trailing result', 'INSTRUMENTATION_RESULT: invalid\n'], + ['a trailing result message', 'INSTRUMENTATION_RESULT: shortMsg=Process crashed.\n'], + ['a trailing abort', 'INSTRUMENTATION_ABORTED: System has crashed.\n'], + ['a trailing withheld abort', 'INSTRUMENTATION_ABORTED: \n'], + ['a trailing plain line', 'plain output\n'], + ].map(([what, trailer]) => ({ + breaks: `the refusal-only stdout (${what})`, + run: { ...refusal, stdout: `${REFUSED_STDOUT}${trailer}` }, + })), + { + breaks: 'the refusal-only stdout (an earlier helper status)', + run: { + ...refusal, + stdout: `INSTRUMENTATION_STATUS: numtests=1\nINSTRUMENTATION_STATUS_CODE: 1\n${REFUSED_STDOUT}`, + }, + }, + { + breaks: 'the refusal-only stdout (no Error record)', + run: { ...refusal, stdout: REFUSED_STDOUT.split('\n').slice(1).join('\n') }, + }, +]; + +test('a refused start is told apart from every run that breaks one of its conditions', () => { + const misclassified = refusalRows + .filter((row) => isRefusedInstrumentationStart(row.run) !== (row.breaks === 'nothing')) + .map((row) => row.breaks); + assert.deepEqual(misclassified, []); +}); + +// The two conditions that live outside the run's parsed result: the run came back from adb on its +// own, and no session was ready for the capture. +const captureRows: { + name: string; + run: OneShotRun; + session?: 'ready-then-fails'; + retried: boolean; +}[] = [ + { name: 'a start the system refused', run: INSTRUMENTATION_FAILED_RUN, retried: true }, + { + name: 'a refused start after a session was ready', + run: INSTRUMENTATION_FAILED_RUN, + session: 'ready-then-fails', + retried: false, + }, + { + name: 'a run the command budget ended', + run: new AppError('COMMAND_FAILED', 'adb command timed out', { + timeoutMs: 30_000, + exitCode: 1, + stdout: REFUSED_STDOUT, + stderr: REFUSED_STDERR, + }), + retried: false, + }, +]; + +for (const row of captureRows) { + test(`${row.name} ${row.retried ? 'gets one more start after a runtime reset' : 'is not started again'}`, async () => { + const { provider, calls } = freshlyBootedHelper([row.run], row.session); + + if (!row.retried) { + const error = await snapshotRejection(provider); + assert.equal(error.code, 'COMMAND_FAILED'); + assert.equal(calls.filter(isOneShotRun).length, 1); + return; + } + const snapshot = await snapshotAndroid(device, { + helperAdb: provider, + helperArtifact: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + }); + assert.ok(snapshot.nodes.some((node) => node.label === 'after retry')); + const oneShotRuns = calls.flatMap((args, index) => (isOneShotRun(args) ? [index] : [])); + assert.equal(oneShotRuns.length, 2); + assert.ok( + calls.slice(oneShotRuns[0], oneShotRuns[1]).some(isAndroidHelperRuntimeForceStop), + 'the helper runtime is reset before the second start', + ); + }); +} + +test('a helper the system refuses to start twice reports the refusal', async () => { + const { provider, calls } = freshlyBootedHelper([ + INSTRUMENTATION_FAILED_RUN, + INSTRUMENTATION_FAILED_RUN, + ]); + + const error = await snapshotRejection(provider); + + assert.equal(calls.filter(isOneShotRun).length, 2); + assert.equal(error.code, 'COMMAND_FAILED'); + assert.equal(error.details?.androidSnapshotHelperStartRefused, true); + assert.deepEqual(error.details?.instrumentation, { + exitCode: 1, + statusCode: -1, + failed: HELPER_RUNNER, + error: `Unable to find instrumentation info for: ComponentInfo{${HELPER_RUNNER}}`, + }); +}); + +// The reset before the second start is a force-stop and then a settle delay; a cancellation in either +// ends the capture there. +for (const cancelPoint of ['force-stop', 'settle delay'] as const) { + test(`a capture cancelled during the reset's ${cancelPoint} rejects without starting the helper again`, async () => { + const { provider, calls } = freshlyBootedHelper([INSTRUMENTATION_FAILED_RUN]); + const controller = new AbortController(); + const cancel = () => controller.abort(new Error('wait deadline exceeded')); + const exec = provider.exec; + provider.exec = async (args, options) => { + // The reset that follows the refused one-shot start, not the session's own cleanup. + if (!isAndroidHelperRuntimeForceStop(args) || !calls.some(isOneShotRun)) { + return await exec(args, options); + } + calls.push(args); + if (cancelPoint === 'settle delay') { + setImmediate(cancel); + return { exitCode: 0, stdout: '', stderr: '' }; + } + // A force-stop that hangs ends only through the signal it was given; the cancellation lands + // once it is in flight and listening. + return await new Promise((_resolve, reject) => { + const signal = options?.signal; + signal?.addEventListener('abort', () => reject(signal.reason), { once: true }); + setImmediate(cancel); + }); + }; + + await assert.rejects( + snapshotAndroid(device, { + helperAdb: provider, + helperArtifact: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + signal: controller.signal, + }), + /wait deadline exceeded/, + ); + assert.equal(calls.filter(isOneShotRun).length, 1); + }); +} diff --git a/packages/platform-android/src/instrumentation-helper.ts b/packages/platform-android/src/instrumentation-helper.ts index 33c59867f2..c197dc4ed6 100644 --- a/packages/platform-android/src/instrumentation-helper.ts +++ b/packages/platform-android/src/instrumentation-helper.ts @@ -174,6 +174,15 @@ const ABORTED_RE = /^INSTRUMENTATION_ABORTED:[ \t]?(.*)$/; const PROTOCOL_RECORD_RE = /^INSTRUMENTATION_(?:STATUS|STATUS_CODE|RESULT|CODE|ABORTED|FAILED):/; const VALUE_RECORD_RE = /^INSTRUMENTATION_(?:STATUS|RESULT): ([^=]*)=(.*)$/; const CODE_RE = /^INSTRUMENTATION_(STATUS_CODE|CODE): (-?\d+)\s*$/; +// How `ActivityManagerService` reports an instrumentation it refused to start, before `am` prints +// INSTRUMENTATION_FAILED. The snapshot helper itself only reports status 1 (a chunk) and 2 (ready). +const SYSTEM_REFUSAL_REPORTER = 'ActivityManagerService'; +const SYSTEM_REFUSAL_STATUS_CODE = -1; +// The refusal's stdout lines by record kind and key; Bundle order decides which key comes first. +const SYSTEM_REFUSAL_SHAPES = new Set([ + 'STATUS Error,STATUS id,STATUS_CODE', + 'STATUS id,STATUS Error,STATUS_CODE', +]); // The protocol keys whose values are text, by the field they fill. const MESSAGE_FIELDS = { shortMsg: 'shortMsg', longMsg: 'longMsg', Error: 'error', stack: 'stack' }; type MessageField = 'shortMsg' | 'longMsg' | 'error' | 'stack'; @@ -219,6 +228,9 @@ function createInstrumentationOutput() { > = {}; let open: MessageField | undefined; const withheld = new Set(); + // Every non-blank stdout line by kind and key, never by value, for `isSystemRefusal`. + const stdoutShape: string[] = []; + let reportedBySystem = false; /** A line the limit cut cannot be proven clean, so its field is withheld like a marked one. */ const checked = (field: MessageField | 'aborted', text: string, cut: boolean) => { if (cut || holdsSnapshotMarker(text)) withheld.add(field); @@ -236,6 +248,7 @@ function createInstrumentationOutput() { return false; }; const readStdoutLine = (line: string, cut: boolean) => { + if (line.trim() !== '') stdoutShape.push(stdoutLineShape(line, cut)); if (readFailed(line, cut)) { open = undefined; } else if (PROTOCOL_RECORD_RE.test(line)) { @@ -244,28 +257,41 @@ function createInstrumentationOutput() { fields[open] = appendLine(fields[open], checked(open, line, cut)); } }; + const readCodeRecord = (kind: string, value: number) => { + if (kind === 'CODE') fields.resultCode ??= value; + else fields.statusCode = value; + }; + const readAbortedRecord = (message: string, cut: boolean) => { + if (fields.aborted !== undefined) return; + // The abort message is one line; whatever follows it is not part of it. + fields.aborted = checked('aborted', message, cut).slice(0, MESSAGE_FIELD_MAX_CHARS); + }; + /** Answers the message field a value record opens, if any. */ + const readMessageRecord = (key: string, value: string, cut: boolean) => { + const field = messageFieldOf(key); + if (!field || fields[field] !== undefined) return undefined; + fields[field] = checked(field, value, cut).slice(0, MESSAGE_FIELD_MAX_CHARS); + return field; + }; /** Reads one protocol record; answers the message field whose value it opens, if any. */ const readProtocolRecord = (line: string, cut: boolean): MessageField | undefined => { const code = CODE_RE.exec(line); if (code) { const value = Number(code[2]); - if (!Number.isSafeInteger(value)) return undefined; - if (code[1] === 'CODE') fields.resultCode ??= value; - else fields.statusCode = value; + if (Number.isSafeInteger(value)) readCodeRecord(code[1]!, value); return undefined; } const aborted = ABORTED_RE.exec(line); if (aborted) { - if (fields.aborted !== undefined) return undefined; - // The abort message is one line; whatever follows it is not part of it. - fields.aborted = checked('aborted', aborted[1] ?? '', cut).slice(0, MESSAGE_FIELD_MAX_CHARS); + readAbortedRecord(aborted[1] ?? '', cut); return undefined; } const record = VALUE_RECORD_RE.exec(line); - const field = record ? messageFieldOf(record[1]!) : undefined; - if (!field || fields[field] !== undefined) return undefined; - fields[field] = checked(field, record![2] ?? '', cut).slice(0, MESSAGE_FIELD_MAX_CHARS); - return field; + if (!record) return undefined; + if (record[1] === 'id' && line.startsWith('INSTRUMENTATION_STATUS:')) { + reportedBySystem = record[2] === SYSTEM_REFUSAL_REPORTER; + } + return readMessageRecord(record[1]!, record[2] ?? '', cut); }; const stdout = createLineAssembler(readStdoutLine); const stderr = createLineAssembler(readFailed); @@ -299,9 +325,29 @@ function createInstrumentationOutput() { ...(withheld.size > 0 ? { withheldFields: [...withheld].sort() } : {}), }; }, + /** + * Stdout held the system's refusal to start the run and nothing else: a status holding just an + * `Error` and `id=ActivityManagerService`, then status code -1, and no other line. + */ + isSystemRefusal: () => + SYSTEM_REFUSAL_SHAPES.has(stdoutShape.join(',')) && + reportedBySystem && + fields.statusCode === SYSTEM_REFUSAL_STATUS_CODE, }; } +/** A stdout line by record kind and key only; anything else is told apart only as protocol or text. */ +function stdoutLineShape(line: string, cut: boolean): string { + if (cut) return 'cut'; + const code = CODE_RE.exec(line); + if (code) return code[1]!; + const record = VALUE_RECORD_RE.exec(line); + if (record) { + return `${line.startsWith('INSTRUMENTATION_STATUS:') ? 'STATUS' : 'RESULT'} ${record[1]}`; + } + return PROTOCOL_RECORD_RE.test(line) ? 'protocol' : 'text'; +} + function messageFieldOf(key: string): MessageField | undefined { return Object.hasOwn(MESSAGE_FIELDS, key) ? (MESSAGE_FIELDS[key as keyof typeof MESSAGE_FIELDS] as MessageField) @@ -313,16 +359,43 @@ function appendLine(value: string | undefined, line: string): string | undefined return next.length > MESSAGE_FIELD_MAX_CHARS ? value : next; } -export function readInstrumentationExitResult(run: { +/** + * Whether a finished run is a start the system refused, and nothing else. All of these hold: + * - `am instrument` reported `INSTRUMENTATION_FAILED`; + * - the process exited with a non-zero code; + * - no signal ended it; + * - its stdout is the system's refusal report and nothing else. + */ +export function isRefusedInstrumentationStart(run: InstrumentationRun): boolean { + const output = readInstrumentationOutput(run); + const result = output.result(run.exitCode, run.signal, true); + return ( + result.failed !== undefined && + result.exitCode !== null && + result.exitCode !== 0 && + result.signal === undefined && + output.isSystemRefusal() + ); +} + +type InstrumentationRun = { stdout: string; stderr: string; exitCode: number | null | undefined; signal?: string | null; -}): AndroidInstrumentationExitResult { +}; + +function readInstrumentationOutput(run: InstrumentationRun) { const output = createInstrumentationOutput(); output.writeStdout(run.stdout); output.writeStderr(run.stderr); - return output.result(run.exitCode, run.signal, true); + return output; +} + +export function readInstrumentationExitResult( + run: InstrumentationRun, +): AndroidInstrumentationExitResult { + return readInstrumentationOutput(run).result(run.exitCode, run.signal, true); } /** The exit of a spawned helper process and what it printed. */ diff --git a/packages/platform-android/src/snapshot-helper-capture.ts b/packages/platform-android/src/snapshot-helper-capture.ts index c1402b0186..e089068187 100644 --- a/packages/platform-android/src/snapshot-helper-capture.ts +++ b/packages/platform-android/src/snapshot-helper-capture.ts @@ -12,6 +12,7 @@ import { readInstrumentationResultIntegerList, readInstrumentationResultNumber, readInstrumentationExitResult, + isRefusedInstrumentationStart, } from './instrumentation-helper.ts'; import { ANDROID_SNAPSHOT_HELPER_CAPTURE_TIMEOUT_MS, @@ -121,6 +122,14 @@ export async function captureAndroidSnapshotWithHelper( return output; } +/** + * The one-shot run exited on its own after the system refused to start the helper (see + * `isRefusedInstrumentationStart`), so no helper code ran on the device. + */ +export function isAndroidSnapshotHelperStartFailure(error: unknown): boolean { + return error instanceof AppError && error.details?.androidSnapshotHelperStartRefused === true; +} + /** * An executor failure (a deadline, a spawn error) carries the helper's raw stdout, which can hold the * snapshot it was printing. It is replaced by the parsed instrumentation result; `stderr` and the @@ -268,6 +277,11 @@ function readAndroidSnapshotHelperOutput( stderr: result.stderr, exitCode: result.exitCode, instrumentation, + // Read only here, where adb returned the run's own exit: a deadline or a host failure throws + // before this point, so it can never read as a refused start. + ...(isRefusedInstrumentationStart(result) + ? { androidSnapshotHelperStartRefused: true } + : {}), ...androidCaptureFailureReasonDetail( androidCaptureFailureReasonFromExitCode(result.exitCode), ), diff --git a/packages/platform-android/src/snapshot-helper-runtime.ts b/packages/platform-android/src/snapshot-helper-runtime.ts index f8615a5821..1ff826a334 100644 --- a/packages/platform-android/src/snapshot-helper-runtime.ts +++ b/packages/platform-android/src/snapshot-helper-runtime.ts @@ -1,7 +1,10 @@ import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; +import { normalizeError } from '@agent-device/kernel/errors'; import { sleep } from './adb.ts'; import type { AndroidAdbExecutor } from './adb-executor.ts'; +import type { AndroidSnapshotHelperOutput } from './snapshot-helper-types.ts'; import { stopAndroidSnapshotHelperRuntime } from './snapshot-helper-retirement.ts'; +import { isAndroidSnapshotHelperStartFailure } from './snapshot-helper-capture.ts'; import { stopAndroidSnapshotHelperSession } from './snapshot-helper-session-lifecycle.ts'; const HELPER_RUNTIME_RESET_DELAY_MS = 150; @@ -24,19 +27,52 @@ export async function retireAndroidSnapshotHelperAfterContentFailure(params: { params.signal?.throwIfAborted(); if (!retiredPersistentSession) { // The suspect helper ran one-shot, so no session stop reset the runtime for us. - await resetAndroidSnapshotHelperRuntime(params.adb, params.packageName); + await resetAndroidSnapshotHelperRuntime({ adb: params.adb, packageName: params.packageName }); } } -export async function resetAndroidSnapshotHelperRuntime( - adb: AndroidAdbExecutor, - packageName: string, -): Promise { - await stopAndroidSnapshotHelperRuntime({ adb, packageName }); - await sleep(HELPER_RUNTIME_RESET_DELAY_MS); +/** A cancelled `signal` ends the reset early; the caller decides what a cancellation answers. */ +export async function resetAndroidSnapshotHelperRuntime(params: { + adb: AndroidAdbExecutor; + packageName: string; + signal?: AbortSignal; +}): Promise { + await stopAndroidSnapshotHelperRuntime(params); + await sleep(HELPER_RUNTIME_RESET_DELAY_MS, params.signal); + // A cancelled reset may have cut the force-stop or the settle short, so it does not report one. + if (params.signal?.aborted) return; emitDiagnostic({ level: 'debug', phase: 'android_snapshot_helper_runtime_reset', - data: { packageName }, + data: { packageName: params.packageName }, }); } + +/** + * Runs a one-shot helper capture. Right after a boot or a `/data` restore, the system can refuse to + * start a current helper once and start it on the next run (#4109). When no session was ready for + * this capture and the system refused the start, nothing ran on the device, so the helper gets + * exactly one more start after a runtime reset. Any other failure is the answer. + */ +export async function captureRetryingRefusedAndroidSnapshotHelperStart(params: { + capture: () => Promise; + sessionReady: boolean; + adb: AndroidAdbExecutor; + packageName: string; + signal?: AbortSignal; +}): Promise { + try { + return await params.capture(); + } catch (error) { + params.signal?.throwIfAborted(); + if (params.sessionReady || !isAndroidSnapshotHelperStartFailure(error)) throw error; + emitDiagnostic({ + level: 'warn', + phase: 'android_snapshot_helper_start_retry', + data: { instrumentation: normalizeError(error).details?.instrumentation }, + }); + await resetAndroidSnapshotHelperRuntime(params); + params.signal?.throwIfAborted(); + return await params.capture(); + } +} diff --git a/packages/platform-android/src/snapshot-helper-session.ts b/packages/platform-android/src/snapshot-helper-session.ts index 59f9b64ae7..5da974adbd 100644 --- a/packages/platform-android/src/snapshot-helper-session.ts +++ b/packages/platform-android/src/snapshot-helper-session.ts @@ -10,10 +10,7 @@ import type { AndroidSnapshotHelperCaptureOptions, AndroidSnapshotHelperOutput, } from './snapshot-helper-types.ts'; -import { - resolveAndroidSnapshotHelperCaptureOptions, - type AndroidSnapshotHelperResolvedCaptureOptions, -} from './snapshot-helper-capture.ts'; +import { resolveAndroidSnapshotHelperCaptureOptions } from './snapshot-helper-capture.ts'; import { isAndroidSnapshotHelperSessionRequestTimeout, parseAndroidSnapshotHelperSessionTouchResponse, @@ -25,7 +22,7 @@ import { getLiveAndroidSnapshotHelperSession, retireFailedAndroidSnapshotHelperSession, stopAndroidSnapshotHelperSession, - type AndroidSnapshotHelperSession, + type AndroidSnapshotHelperSessionAcquisition, type AndroidSnapshotHelperSessionHelperIdentity, } from './snapshot-helper-session-lifecycle.ts'; @@ -33,22 +30,15 @@ export async function captureAndroidSnapshotWithHelperSession( options: AndroidSnapshotHelperCaptureOptions, ): Promise { const acquired = await acquireAndroidSnapshotHelperSession(options); - if (!acquired) return undefined; - return await captureFromAndroidSnapshotHelperSession({ - session: acquired.session, - deviceKey: acquired.deviceKey, - options, - resolved: acquired.resolved, - }); + return acquired ? await captureFromAndroidSnapshotHelperSession(acquired, options) : undefined; } -async function captureFromAndroidSnapshotHelperSession(params: { - session: AndroidSnapshotHelperSession; - deviceKey: string; - options: AndroidSnapshotHelperCaptureOptions; - resolved: AndroidSnapshotHelperResolvedCaptureOptions; -}): Promise { - const { session, deviceKey, options, resolved } = params; +/** Captures over a session that is ready; `undefined` means the session failed and was retired. */ +export async function captureFromAndroidSnapshotHelperSession( + acquired: AndroidSnapshotHelperSessionAcquisition, + options: AndroidSnapshotHelperCaptureOptions, +): Promise { + const { session, deviceKey, resolved } = acquired; const requestedAtMs = Date.now(); const reused = session.capturedCount > 0; try { diff --git a/packages/platform-android/src/snapshot.ts b/packages/platform-android/src/snapshot.ts index baa411529e..f71b0237af 100644 --- a/packages/platform-android/src/snapshot.ts +++ b/packages/platform-android/src/snapshot.ts @@ -40,7 +40,6 @@ import { } from './snapshot-helper-types.ts'; import { captureAndroidSnapshotWithHelper, - captureAndroidSnapshotWithHelperSession, ensureAndroidSnapshotHelper, forgetAndroidSnapshotHelperInstall, stopAndroidSnapshotHelperSession, @@ -50,7 +49,11 @@ import { type AndroidSnapshotHelperInstallResult, type AndroidSnapshotHelperOutput, } from './snapshot-helper.ts'; -import { getLiveAndroidSnapshotHelperSession } from './snapshot-helper-session-lifecycle.ts'; +import { + acquireAndroidSnapshotHelperSession, + getLiveAndroidSnapshotHelperSession, +} from './snapshot-helper-session-lifecycle.ts'; +import { captureFromAndroidSnapshotHelperSession } from './snapshot-helper-session.ts'; import { isAndroidSnapshotHelperNotCurrentError } from './snapshot-helper-install.ts'; import { getAndroidSnapshotHelperSessionDeviceKey, @@ -72,6 +75,7 @@ import { readAndroidCaptureFailureReason, } from '@agent-device/contracts/android-snapshot-quality'; import { + captureRetryingRefusedAndroidSnapshotHelperStart, resetAndroidSnapshotHelperRuntime, retireAndroidSnapshotHelperAfterContentFailure, } from './snapshot-helper-runtime.ts'; @@ -478,10 +482,18 @@ async function captureAndroidUiHierarchyFromHelper(params: { }); captureOptions.idleWait = params.idleWait; let sessionCapture: AndroidSnapshotHelperOutput | undefined; + // A helper that reached a ready session was started, so a refused start after it is not #4109. + let sessionReady = false; try { await withDiagnosticTimer( ANDROID_SNAPSHOT_HELPER_SESSION_CAPTURE_PHASE, - async () => (sessionCapture = await captureAndroidSnapshotWithHelperSession(captureOptions)), + async () => { + const acquired = await acquireAndroidSnapshotHelperSession(captureOptions); + sessionReady = acquired !== undefined; + if (acquired) { + sessionCapture = await captureFromAndroidSnapshotHelperSession(acquired, captureOptions); + } + }, () => ({ packageName: artifact.manifest.packageName, version: artifact.manifest.version, @@ -501,19 +513,27 @@ async function captureAndroidUiHierarchyFromHelper(params: { phase: 'android_snapshot_helper_session_fallback', data: { reason: normalizeError(error).message }, }); - await resetAndroidSnapshotHelperRuntime(adb, artifact.manifest.packageName); + await resetAndroidSnapshotHelperRuntime({ adb, packageName: artifact.manifest.packageName }); } - return await withDiagnosticTimer( - ANDROID_SNAPSHOT_HELPER_CAPTURE_PHASE, - async () => await captureAndroidSnapshotWithHelper(captureOptions), - { - packageName: artifact.manifest.packageName, - version: artifact.manifest.version, - timeoutMs: ANDROID_SNAPSHOT_HELPER_CAPTURE_TIMEOUT_MS, - commandTimeoutMs: ANDROID_SNAPSHOT_HELPER_COMMAND_TIMEOUT_MS, - transport: 'instrumentation' satisfies AndroidSnapshotHelperTransport, - }, - ); + const captureOneShot = async () => + await withDiagnosticTimer( + ANDROID_SNAPSHOT_HELPER_CAPTURE_PHASE, + async () => await captureAndroidSnapshotWithHelper(captureOptions), + { + packageName: artifact.manifest.packageName, + version: artifact.manifest.version, + timeoutMs: ANDROID_SNAPSHOT_HELPER_CAPTURE_TIMEOUT_MS, + commandTimeoutMs: ANDROID_SNAPSHOT_HELPER_COMMAND_TIMEOUT_MS, + transport: 'instrumentation' satisfies AndroidSnapshotHelperTransport, + }, + ); + return await captureRetryingRefusedAndroidSnapshotHelperStart({ + capture: captureOneShot, + sessionReady, + adb, + packageName: artifact.manifest.packageName, + signal, + }); } function formatAndroidHelperCaptureResult( @@ -694,7 +714,10 @@ async function rejectAndroidHelperCaptureFailure(params: { }, }); await stopAndroidSnapshotHelperSession(params.helperDeviceKey); - await resetAndroidSnapshotHelperRuntime(params.adb, params.artifact.manifest.packageName); + await resetAndroidSnapshotHelperRuntime({ + adb: params.adb, + packageName: params.artifact.manifest.packageName, + }); forgetAndroidSnapshotHelperInstall({ deviceKey: params.helperDeviceKey, packageName: params.artifact.manifest.packageName,