Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import assert from 'node:assert/strict';
import { afterEach, beforeEach, test } from 'vitest';
import { afterEach, beforeEach, test, vi } from 'vitest';
import { captureAndroidSnapshotWithHelperSession } from '../snapshot-helper-session.ts';
import {
resetAndroidSnapshotHelperSessions,
Expand All @@ -11,17 +11,23 @@ import { recoverAndroidSnapshotHelperRetirement } from '../snapshot-helper-retir
import {
createSessionProvider,
FakeAndroidProcess,
isAndroidHelperForwardRemoval,
isAndroidHelperRuntimeForceStop,
type SessionProviderOptions,
} from './snapshot-helper-session.fixtures.ts';
import type { AndroidAdbExecutor, AndroidAdbProvider } from '../adb-executor.ts';
import path from 'node:path';
import { promises as fs } from 'node:fs';
import { mkdtempForTest } from './test-utils/tmp-dir.ts';
import { withDiagnosticsScope } from '@agent-device/host-kit/diagnostics';

beforeEach(async () => {
delete process.env.AGENT_DEVICE_ANDROID_SNAPSHOT_HELPER_SESSION;
await resetAndroidSnapshotHelperSessions();
});

afterEach(async () => {
vi.restoreAllMocks();
delete process.env.AGENT_DEVICE_ANDROID_SNAPSHOT_HELPER_SESSION;
await resetAndroidSnapshotHelperSessions();
});
Expand Down Expand Up @@ -226,6 +232,119 @@ test('a session whose capture timed out is not restarted by the next command', a
);
});

test('a reused session whose capture times out keeps the helper build one-shot until reset', async () => {
const spawnArgs: (readonly string[])[] = [];
// The helper answers once and then goes silent: the idle freeze of #3929. Force-stop kills the
// frozen process cleanly, so the retirement proves release and only the timeout tells.
const provider = createSessionProvider({
calls: [],
spawnArgs,
answeredSnapshotsBeforeStall: 1,
stalledSnapshots: 1,
});
const capture = (deviceKey: string) =>
captureAndroidSnapshotWithHelperSession({
adb: provider.exec,
adbProvider: provider,
deviceKey,
commandTimeoutMs: 400,
});
const logPath = path.join(
await mkdtempForTest('agent-device-android-session-disable-diag-'),
'diag.ndjson',
);

await withDiagnosticsScope({ debug: true, logPath }, async () => {
assert.equal((await capture('android:coloros-16'))?.metadata.transport, 'persistent-session');
assert.equal(await capture('android:coloros-16'), undefined, 'the frozen session falls back');
skewClockPastSessionBackoff();
assert.equal(
await capture('android:coloros-16'),
undefined,
'the next command answers one-shot after any ordinary backoff has run out',
);
assert.equal(spawnArgs.length, 1, 'the frozen helper build is not spawned again');
const otherDevice = await capture('android:other-device');
assert.equal(otherDevice?.metadata.transport, 'persistent-session');
});

const log = await fs.readFile(logPath, 'utf8');
assert.match(log, /"phase":"android_snapshot_helper_session_stop"[^\n]*"release":"released"/);
assert.match(log, /android_snapshot_helper_persistent_session_disabled/);

await resetAndroidSnapshotHelperSessions();
const fresh = await capture('android:coloros-16');
assert.equal(spawnArgs.length, 3, 'reset allows a fresh persistent attempt');
assert.equal(fresh?.metadata.transport, 'persistent-session');
});

test('a first capture that times out on a fresh session only earns the ordinary backoff', async () => {
const spawnArgs: (readonly string[])[] = [];
const provider = createSessionProvider({ calls: [], spawnArgs, stalledSnapshots: 1 });
const capture = () =>
captureAndroidSnapshotWithHelperSession({
adb: provider.exec,
adbProvider: provider,
deviceKey: 'android:emulator-5554',
commandTimeoutMs: 400,
});
const logPath = path.join(
await mkdtempForTest('agent-device-android-session-first-timeout-diag-'),
'diag.ndjson',
);

await withDiagnosticsScope({ debug: true, logPath }, async () => {
assert.equal(await capture(), undefined);
skewClockPastSessionBackoff();
assert.equal((await capture())?.metadata.transport, 'persistent-session');
});

assert.equal(spawnArgs.length, 2, 'the backoff ran out and a new helper was started');
const log = await fs.readFile(logPath, 'utf8');
assert.doesNotMatch(log, /android_snapshot_helper_persistent_session_disabled/);
});

test('a retirement whose forward removal stalls still falls back to one-shot', async () => {
const calls: (readonly string[])[] = [];
const spawnArgs: (readonly string[])[] = [];
const cleanupAborts: (readonly string[])[] = [];
// The forward removal hangs until the retirement budget aborts it.
const provider = createSessionProvider({
calls,
spawnArgs,
cleanupAborts,
stalledSnapshots: 1,
stalledForwardRemovals: 1,
});
const logPath = path.join(
await mkdtempForTest('agent-device-android-session-cleanup-timeout-diag-'),
'diag.ndjson',
);

await withDiagnosticsScope({ debug: true, logPath }, async () => {
assert.equal(
await captureAndroidSnapshotWithHelperSession({
adb: provider.exec,
adbProvider: provider,
deviceKey: 'android:emulator-5554',
commandTimeoutMs: 400,
}),
undefined,
'the stalled cleanup still falls back to one-shot',
);
});

assert.equal(cleanupAborts.filter(isAndroidHelperForwardRemoval).length, 1);
const log = await fs.readFile(logPath, 'utf8');
assert.match(log, /"externalCleanupTimedOut":true/);
});

/** Moves the module clock past the longest backoff a failed capture can earn on its own. */
function skewClockPastSessionBackoff(): void {
const realNow = Date.now.bind(Date);
vi.spyOn(Date, 'now').mockImplementation(() => realNow() + 10 * 60_000);
}

test('starts and reuses a persistent Android snapshot helper session', async () => {
const calls: (readonly string[])[] = [];
const spawnArgs: (readonly string[])[] = [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,11 @@ export type SessionProviderOptions = {
forceStopDelayMs?: number;
recoveryFailure?: boolean;
stalledCleanup?: boolean;
/** How many `forward --remove` calls hang until their cleanup budget aborts them. */
stalledForwardRemovals?: number;
stalledSnapshots?: number;
/** How many snapshot requests each helper process answers before `stalledSnapshots` applies. */
answeredSnapshotsBeforeStall?: number;
/** 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. */
Expand Down Expand Up @@ -257,7 +261,7 @@ export function createSessionProvider(options: SessionProviderOptions): AndroidA
return;
}
snapshotCount += 1;
if (stalledSnapshots > 0) {
if (snapshotCount > (options.answeredSnapshotsBeforeStall ?? 0) && stalledSnapshots > 0) {
stalledSnapshots -= 1;
return;
}
Expand Down Expand Up @@ -370,8 +374,14 @@ async function stallSessionCleanupIfConfigured(
signal: AbortSignal | undefined,
forceStopsRuntime: boolean,
): Promise<void> {
const removesForward = args[0] === 'forward' && args[1] === '--remove';
if (!options.stalledCleanup || !signal || (!removesForward && !forceStopsRuntime)) return;
const removesForward = isAndroidHelperForwardRemoval(args);
const stalledForwardRemovals = options.stalledForwardRemovals ?? 0;
const stallsForwardRemoval = removesForward && stalledForwardRemovals > 0;
// Only a call with a cleanup signal can actually hang, so only it consumes a stall.
if (stallsForwardRemoval && signal) options.stalledForwardRemovals = stalledForwardRemovals - 1;
const stalls =
stallsForwardRemoval || (options.stalledCleanup && (removesForward || forceStopsRuntime));
if (!stalls || !signal) return;
await new Promise<never>((_resolve, reject) => {
const onAbort = () => {
options.cleanupAborts?.push(args);
Expand Down
41 changes: 23 additions & 18 deletions packages/platform-android/src/snapshot-helper-retirement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,20 +227,18 @@ export async function settleAndroidSnapshotHelperSessionCleanup(params: {
forceStopRuntime: boolean;
}): Promise<{ timedOut: boolean }> {
const signal = AbortSignal.timeout(params.timeoutMs);
await Promise.all([
...(params.forceStopRuntime
? [
stopAndroidSnapshotHelperRuntime({
adb: params.adb,
packageName: params.packageName,
timeoutMs: params.timeoutMs,
signal,
}),
]
: []),
const [, forwardRemoved] = await Promise.all([
params.forceStopRuntime
? stopAndroidSnapshotHelperRuntime({
adb: params.adb,
packageName: params.packageName,
timeoutMs: params.timeoutMs,
signal,
})
: undefined,
removeAndroidSnapshotHelperSessionForward({ ...params, signal }),
]);
return { timedOut: signal.aborted };
return { timedOut: signal.aborted || !forwardRemoved };
}

/**
Expand Down Expand Up @@ -367,13 +365,20 @@ async function removeAndroidSnapshotHelperSessionForward(params: {
port: number;
timeoutMs: number;
signal: AbortSignal;
}): Promise<void> {
}): Promise<boolean> {
params.process.stdin?.end();
params.process.stdout?.destroy();
params.process.stderr?.destroy();
await params.adb(['forward', '--remove', `tcp:${params.port}`], {
allowFailure: true,
timeoutMs: params.timeoutMs,
signal: params.signal,
});
// `allowFailure` already absorbs an adb error, so a rejection is a removal that ran out of budget
// or was aborted: report it as a timed-out cleanup rather than failing the teardown.
return await params
.adb(['forward', '--remove', `tcp:${params.port}`], {
allowFailure: true,
timeoutMs: params.timeoutMs,
signal: params.signal,
})
.then(
() => true,
() => false,
);
}
14 changes: 14 additions & 0 deletions packages/platform-android/src/snapshot-helper-session-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,8 @@ export async function retireFailedAndroidSnapshotHelperSession(params: {
failedAfterMs: number;
/** Budget of the one-shot capture that answers in place of the failed session. */
fallbackBudgetMs: number;
/** The session had already answered a capture, and this one got no answer before its deadline. */
reusedSessionTimedOut: boolean;
signal?: AbortSignal;
cause: unknown;
}): Promise<void> {
Expand All @@ -261,6 +263,18 @@ export async function retireFailedAndroidSnapshotHelperSession(params: {
cause: params.cause,
});
if (params.signal?.aborted) return;
// A helper that answered and then went silent was frozen while idle (#3929: ColorOS freezes the
// idle helper, force-stop kills it cleanly, and every restarted helper is frozen again), so this
// build stays one-shot until reset.
if (params.reusedSessionTimedOut) {
Comment thread
mvanhorn marked this conversation as resolved.
Resolved
failedSessions().set(params.identity, Number.POSITIVE_INFINITY);
emitDiagnostic({
level: 'warn',
phase: 'android_snapshot_helper_persistent_session_disabled',
data: { deviceKey: params.deviceKey, failedAfterMs: params.failedAfterMs },
});
return;
}
failedSessions().set(
params.identity,
Date.now() +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ export function allocateAndroidSnapshotHelperSessionPort(): Promise<number> {
});
}

const SESSION_REQUEST_TIMEOUT_REASON = 'android_snapshot_helper_session_request_timeout';

/** The helper accepted the session request but sent no answer before the command deadline. */
export function isAndroidSnapshotHelperSessionRequestTimeout(error: unknown): boolean {
return error instanceof AppError && error.details?.reason === SESSION_REQUEST_TIMEOUT_REASON;
}

export function sendAndroidSnapshotHelperSessionCommand(
port: number,
command: string,
Expand All @@ -52,6 +59,7 @@ export function sendAndroidSnapshotHelperSessionCommand(
command: command.split(' ', 1)[0],
timeoutMs,
port,
reason: SESSION_REQUEST_TIMEOUT_REASON,
Comment thread
mvanhorn marked this conversation as resolved.
Resolved
}),
);
}, timeoutMs);
Expand Down
4 changes: 3 additions & 1 deletion packages/platform-android/src/snapshot-helper-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
type AndroidSnapshotHelperResolvedCaptureOptions,
} from './snapshot-helper-capture.ts';
import {
isAndroidSnapshotHelperSessionRequestTimeout,
parseAndroidSnapshotHelperSessionTouchResponse,
requestAndroidSnapshotHelperSessionSnapshot,
sendAndroidSnapshotHelperSessionCommand,
Expand Down Expand Up @@ -49,8 +50,8 @@ async function captureFromAndroidSnapshotHelperSession(params: {
}): Promise<AndroidSnapshotHelperOutput | undefined> {
const { session, deviceKey, options, resolved } = params;
const requestedAtMs = Date.now();
const reused = session.capturedCount > 0;
try {
const reused = session.capturedCount > 0;
const output = await requestAndroidSnapshotHelperSessionSnapshot({
port: session.port,
commandTimeoutMs: resolved.commandTimeoutMs,
Expand All @@ -73,6 +74,7 @@ async function captureFromAndroidSnapshotHelperSession(params: {
identity: session.identity,
failedAfterMs: Date.now() - requestedAtMs,
fallbackBudgetMs: resolveAndroidSnapshotHelperCaptureOptions(options).commandTimeoutMs,
reusedSessionTimedOut: reused && isAndroidSnapshotHelperSessionRequestTimeout(error),
signal: options.signal,
cause: error,
});
Expand Down
Loading