Skip to content

Commit c8fae0f

Browse files
committed
fix(android): read device ownership off the device, not off adb
The snapshot helper retirement treated the outcome of an `am force-stop` call as the fact it was supposed to measure. On a loaded host the adb round trip exceeds its budget while the helper process is already gone, so a completed interaction failed its own teardown, and the quarantine that followed refused the next command with "could not confirm release of device automation ownership" on a device that had nothing holding UiAutomation. Ownership is a device fact, so it is now read as one: `adb shell pidof` answers released, occupied, or unknown, and only a device that names a live helper process may refuse a command. Teardown records what it could not prove for the next acquire and never decides what the command it is finishing reports, which is what let a settled `press` turn into a stale-coordinate failure in #2553. A start that only ran out of time or lost its transport no longer excludes the helper identity for the rest of the daemon's life; it retries after a cooldown. Only a helper that ran and exited before announcing readiness proves the identity unusable.
1 parent 4a56565 commit c8fae0f

13 files changed

Lines changed: 541 additions & 259 deletions

‎packages/platform-android/src/__tests__/snapshot-helper-capture.test.ts‎

Lines changed: 31 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -31,14 +31,17 @@ test('one-shot capture that resolves during cancellation retires before rejectin
3131
if (options?.signal?.aborted) onAbort();
3232
});
3333
}
34+
if (args.join(' ').includes('pidof')) {
35+
return { exitCode: 1, stdout: '', stderr: '' };
36+
}
3437
assert.deepEqual(args, [
3538
'shell',
3639
'am',
3740
'force-stop',
3841
'com.callstack.agentdevice.snapshothelper',
3942
]);
40-
assert.notEqual(options?.signal, controller.signal);
41-
assert.equal(options?.signal?.aborted, false);
43+
// The retirement stop must not inherit the aborted command signal; it bounds itself.
44+
assert.ok(!options?.signal?.aborted);
4245
events.push('retirement-started');
4346
await retirementCanFinish;
4447
events.push('retirement-finished');
@@ -70,22 +73,26 @@ test('one-shot capture that resolves during cancellation retires before rejectin
7073
]);
7174
});
7275

73-
test('uncertain one-shot retirement is quarantined until the next capture recovers it', async () => {
76+
test('canceled one-shot capture reports the cancellation and the next capture recovers the device', async () => {
7477
const controller = new AbortController();
78+
const cancellation = new Error('wait deadline exceeded');
7579
const events: string[] = [];
76-
let forceStopCount = 0;
80+
let stopCount = 0;
7781
const adb: AndroidAdbExecutor = async (args, options) => {
7882
if (args.join(' ').includes('am force-stop')) {
79-
forceStopCount += 1;
80-
events.push(`force-stop-${forceStopCount}`);
81-
return {
82-
exitCode: forceStopCount === 1 ? 1 : 0,
83-
stdout: '',
84-
stderr: forceStopCount === 1 ? 'runtime still busy' : '',
85-
};
83+
stopCount += 1;
84+
events.push(`force-stop-${stopCount}`);
85+
return { exitCode: 0, stdout: '', stderr: '' };
86+
}
87+
if (args.join(' ').includes('pidof')) {
88+
// The first read happens while Android still runs the helper; the next says it is gone.
89+
events.push('pidof');
90+
return stopCount === 1
91+
? { exitCode: 0, stdout: '4211\n', stderr: '' }
92+
: { exitCode: 1, stdout: '', stderr: '' };
8693
}
87-
events.push(`instrument-${forceStopCount}`);
88-
if (forceStopCount === 0) {
94+
events.push(`instrument-${stopCount}`);
95+
if (stopCount === 0) {
8996
return await new Promise((_resolve, reject) => {
9097
const onAbort = () => reject(options?.signal?.reason);
9198
options?.signal?.addEventListener('abort', onAbort, { once: true });
@@ -103,21 +110,24 @@ test('uncertain one-shot retirement is quarantined until the next capture recove
103110
deviceKey: 'android:emulator-5554',
104111
signal: controller.signal,
105112
});
106-
controller.abort(new Error('wait deadline exceeded'));
113+
controller.abort(cancellation);
107114

108-
await assert.rejects(
109-
canceledCapture,
110-
(error: unknown) =>
111-
(error as { details?: { reason?: string } }).details?.reason ===
112-
'android_snapshot_helper_retirement_unconfirmed',
113-
);
115+
// The ownership question never replaces the reason this command stopped.
116+
await assert.rejects(canceledCapture, cancellation);
114117
const recovered = await captureAndroidSnapshotWithHelper({
115118
adb,
116119
deviceKey: 'android:emulator-5554',
117120
});
118121

119122
assert.match(recovered.xml, /recovered/);
120-
assert.deepEqual(events, ['instrument-0', 'force-stop-1', 'force-stop-2', 'instrument-2']);
123+
assert.deepEqual(events, [
124+
'instrument-0',
125+
'force-stop-1',
126+
'pidof',
127+
'force-stop-2',
128+
'pidof',
129+
'instrument-2',
130+
]);
121131
});
122132

123133
function helperOutput(xml: string): string {

‎packages/platform-android/src/__tests__/snapshot-helper-retirement.test.ts‎

Lines changed: 80 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -3,77 +3,107 @@ import { beforeEach, test } from 'vitest';
33
import { EventEmitter } from 'node:events';
44
import { PassThrough } from 'node:stream';
55
import {
6+
isAndroidSnapshotHelperRuntimeOccupiedError,
67
recoverAndroidSnapshotHelperRetirement,
8+
recordAndroidSnapshotHelperRelease,
79
resetAndroidSnapshotHelperRetirements,
810
retireCanceledAndroidSnapshotHelperCapture,
911
settleAndroidSnapshotHelperSessionCleanup,
1012
} from '../snapshot-helper-retirement.ts';
1113
import type { AndroidAdbProcess } from '../adb-executor.ts';
1214
import type { AndroidAdbExecutor } from '../snapshot-helper-types.ts';
1315

16+
const PACKAGE_NAME = 'com.callstack.agentdevice.snapshothelper';
17+
const DEVICE_KEY = 'android:emulator-5554';
18+
1419
beforeEach(() => {
1520
resetAndroidSnapshotHelperRetirements();
1621
});
1722

18-
test('requires positive recovery evidence after uncertain runtime retirement', async () => {
23+
test('canceled capture answers for the device, not for the force-stop call that served it', async () => {
1924
const calls: string[][] = [];
20-
let forceStopCount = 0;
2125
const adb: AndroidAdbExecutor = async (args) => {
2226
calls.push(args);
23-
forceStopCount += 1;
24-
return {
25-
exitCode: forceStopCount === 1 ? 1 : 0,
26-
stdout: '',
27-
stderr: forceStopCount === 1 ? 'runtime still busy' : '',
28-
};
27+
if (args.includes('force-stop')) throw new Error('adb round trip exceeded its budget');
28+
return { exitCode: 1, stdout: '', stderr: '' };
2929
};
3030

31-
await assert.rejects(
32-
retireCanceledAndroidSnapshotHelperCapture({
33-
deviceKey: 'android:emulator-5554',
34-
packageName: 'com.callstack.agentdevice.snapshothelper',
35-
adb,
36-
cause: new Error('capture canceled'),
37-
}),
38-
(error: unknown) =>
39-
(error as { details?: { reason?: string } }).details?.reason ===
40-
'android_snapshot_helper_retirement_unconfirmed',
41-
);
42-
await recoverAndroidSnapshotHelperRetirement({
43-
deviceKey: 'android:emulator-5554',
31+
// A loaded host makes the stop call time out while the helper process is already gone. Ownership
32+
// is decided by the process Android reports, so this retirement resolves.
33+
await retireCanceledAndroidSnapshotHelperCapture({
34+
deviceKey: DEVICE_KEY,
35+
packageName: PACKAGE_NAME,
4436
adb,
37+
cause: new Error('capture canceled'),
4538
});
46-
await recoverAndroidSnapshotHelperRetirement({
47-
deviceKey: 'android:emulator-5554',
39+
40+
assert.deepEqual(calls, [
41+
['shell', 'am', 'force-stop', PACKAGE_NAME],
42+
['shell', 'pidof', PACKAGE_NAME],
43+
]);
44+
await recoverAndroidSnapshotHelperRetirement({ deviceKey: DEVICE_KEY, adb });
45+
assert.equal(calls.length, 2);
46+
});
47+
48+
test('unproven release stays pending until an acquire reads the device', async () => {
49+
let helperAlive = true;
50+
const adb: AndroidAdbExecutor = async (args) => {
51+
if (args.includes('pidof')) {
52+
return helperAlive
53+
? { exitCode: 0, stdout: '4211\n', stderr: '' }
54+
: { exitCode: 1, stdout: '', stderr: '' };
55+
}
56+
return { exitCode: 0, stdout: '', stderr: '' };
57+
};
58+
59+
await retireCanceledAndroidSnapshotHelperCapture({
60+
deviceKey: DEVICE_KEY,
61+
packageName: PACKAGE_NAME,
4862
adb,
63+
cause: new Error('capture canceled'),
4964
});
5065

51-
assert.equal(forceStopCount, 2);
52-
assert.deepEqual(
53-
calls,
54-
Array.from({ length: 2 }, () => [
55-
'shell',
56-
'am',
57-
'force-stop',
58-
'com.callstack.agentdevice.snapshothelper',
59-
]),
66+
await assert.rejects(
67+
recoverAndroidSnapshotHelperRetirement({ deviceKey: DEVICE_KEY, adb }),
68+
isAndroidSnapshotHelperRuntimeOccupiedError,
6069
);
70+
71+
helperAlive = false;
72+
await recoverAndroidSnapshotHelperRetirement({ deviceKey: DEVICE_KEY, adb });
73+
await recoverAndroidSnapshotHelperRetirement({ deviceKey: DEVICE_KEY, adb });
74+
});
75+
76+
test('a device that cannot be read leaves the retirement pending without failing the command', async () => {
77+
const adb: AndroidAdbExecutor = async (args) => {
78+
if (args.includes('pidof')) throw new Error('device offline');
79+
return { exitCode: 0, stdout: '', stderr: '' };
80+
};
81+
82+
const release = await recordAndroidSnapshotHelperRelease({
83+
deviceKey: DEVICE_KEY,
84+
packageName: PACKAGE_NAME,
85+
adb,
86+
cause: new Error('quit timed out'),
87+
});
88+
assert.equal(release, 'unknown');
89+
await recoverAndroidSnapshotHelperRetirement({ deviceKey: DEVICE_KEY, adb });
6190
});
6291

63-
test('session cleanup force-stops the runtime when release was not confirmed', async () => {
92+
test('session cleanup stops the runtime even when the transport refuses the stop', async () => {
6493
const calls: string[][] = [];
6594
const cleanup = await settleAndroidSnapshotHelperSessionCleanup({
66-
adb: recordingAdb(calls),
95+
adb: recordingAdb(calls, () => ({ exitCode: 1, stdout: '', stderr: 'device offline' })),
6796
process: new StubAndroidProcess(),
6897
port: 41234,
69-
packageName: 'com.callstack.agentdevice.snapshothelper',
98+
packageName: PACKAGE_NAME,
7099
timeoutMs: 2_000,
71100
forceStopRuntime: true,
72101
});
73102

74-
assert.equal(cleanup.runtimeForceStopped, true);
103+
// The stop is an action, never the release evidence; a refused call must not fail the teardown.
104+
assert.equal(cleanup.timedOut, false);
75105
assert.deepEqual(calls, [
76-
['shell', 'am', 'force-stop', 'com.callstack.agentdevice.snapshothelper'],
106+
['shell', 'am', 'force-stop', PACKAGE_NAME],
77107
['forward', '--remove', 'tcp:41234'],
78108
]);
79109
});
@@ -84,21 +114,28 @@ test('session cleanup skips the force-stop round trip once release is confirmed'
84114
adb: recordingAdb(calls),
85115
process: new StubAndroidProcess(),
86116
port: 41234,
87-
packageName: 'com.callstack.agentdevice.snapshothelper',
117+
packageName: PACKAGE_NAME,
88118
timeoutMs: 2_000,
89119
forceStopRuntime: false,
90120
});
91121

92-
// The helper already released UiAutomation, so nothing was force-stopped and nothing may claim
93-
// it was: the caller reads this flag to decide whether the retirement needs quarantining.
94-
assert.equal(cleanup.runtimeForceStopped, false);
122+
// The helper already released UiAutomation, so the only device call is the forward removal the
123+
// next session on this port would otherwise collide with.
124+
assert.equal(cleanup.timedOut, false);
95125
assert.deepEqual(calls, [['forward', '--remove', 'tcp:41234']]);
96126
});
97127

98-
function recordingAdb(calls: string[][]): AndroidAdbExecutor {
128+
function recordingAdb(
129+
calls: string[][],
130+
result: () => { exitCode: number; stdout: string; stderr: string } = () => ({
131+
exitCode: 0,
132+
stdout: '',
133+
stderr: '',
134+
}),
135+
): AndroidAdbExecutor {
99136
return async (args) => {
100137
calls.push(args);
101-
return { exitCode: 0, stdout: '', stderr: '' };
138+
return result();
102139
};
103140
}
104141

‎packages/platform-android/src/__tests__/snapshot-helper-session-lifecycle.test.ts‎

Lines changed: 42 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import assert from 'node:assert/strict';
2-
import { afterEach, beforeEach, test } from 'vitest';
2+
import { afterEach, beforeEach, test, vi } from 'vitest';
33
import { captureAndroidSnapshotWithHelperSession } from '../snapshot-helper-session.ts';
44
import {
55
resetAndroidSnapshotHelperSessions,
@@ -84,6 +84,37 @@ test('disables repeated persistent session attempts after startup failure', asyn
8484
assert.equal(calls.filter((args) => args[0] === 'forward').length, 2);
8585
});
8686

87+
test('a start that failed for a transient reason is retried instead of ending the persistent path', async () => {
88+
vi.useFakeTimers({ toFake: ['Date'] });
89+
try {
90+
const calls: string[][] = [];
91+
const spawnArgs: string[][] = [];
92+
const provider = createSessionProvider({ calls, spawnArgs });
93+
let transportHealthy = false;
94+
const adb: AndroidAdbExecutor = async (args, options) => {
95+
if (args[0] === 'forward' && !transportHealthy) throw new Error('adb server is restarting');
96+
return await provider.exec!(args, options);
97+
};
98+
const capture = () =>
99+
captureAndroidSnapshotWithHelperSession({
100+
adb,
101+
adbProvider: { ...provider, exec: adb },
102+
deviceKey: 'android:emulator-5554',
103+
});
104+
105+
assert.equal(await capture(), undefined);
106+
assert.equal(await capture(), undefined);
107+
assert.equal(spawnArgs.length, 0, 'the failed start is not retried inside its cooldown');
108+
109+
vi.advanceTimersByTime(61_000);
110+
transportHealthy = true;
111+
assert.match((await capture())?.xml ?? '', /snapshot 1/);
112+
assert.equal(spawnArgs.length, 1);
113+
} finally {
114+
vi.useRealTimers();
115+
}
116+
});
117+
87118
test('starts and reuses a persistent Android snapshot helper session', async () => {
88119
const calls: string[][] = [];
89120
const spawnArgs: string[][] = [];
@@ -273,11 +304,11 @@ test('probes the adb transport once per device instead of once per teardown', as
273304
assert.equal(calls.some(isHelperRuntimeForceStop), false);
274305
});
275306

276-
test('failed whole-module reset preserves quarantine until recovery is confirmed', async () => {
307+
test('whole-module reset clears a release the last teardown left pending', async () => {
277308
const options: SessionProviderOptions = {
278309
calls: [],
279310
quitResponseMode: 'malformed',
280-
recoveryFailure: true,
311+
runtimeRelease: 'occupied',
281312
};
282313
const provider = createSessionProvider(options);
283314
const deviceKey = 'android:emulator-5554';
@@ -287,26 +318,22 @@ test('failed whole-module reset preserves quarantine until recovery is confirmed
287318
adbProvider: provider,
288319
deviceKey,
289320
});
290-
await assert.rejects(
291-
resetAndroidSnapshotHelperSessions(),
292-
/Failed to retire every Android snapshot helper session/,
293-
);
294-
const forceStopsBeforeRecovery = options.calls.filter((args) =>
295-
args.join(' ').includes('am force-stop'),
296-
).length;
321+
await resetAndroidSnapshotHelperSessions();
322+
const forceStopsAfterReset = countForceStops(options);
297323

298-
options.recoveryFailure = false;
299324
await recoverAndroidSnapshotHelperRetirement({
300325
deviceKey,
301326
adb: provider.exec,
302327
});
303328

304-
assert.equal(
305-
options.calls.filter((args) => args.join(' ').includes('am force-stop')).length,
306-
forceStopsBeforeRecovery + 1,
307-
);
329+
assert.ok(forceStopsAfterReset > 0, 'the teardown stopped the runtime');
330+
assert.equal(countForceStops(options), forceStopsAfterReset);
308331
});
309332

333+
function countForceStops(options: SessionProviderOptions): number {
334+
return options.calls.filter((args) => isHelperRuntimeForceStop(args)).length;
335+
}
336+
310337
function isHelperRuntimeForceStop(args: string[]): boolean {
311338
return args.join(' ') === 'shell am force-stop com.callstack.agentdevice.snapshothelper';
312339
}

0 commit comments

Comments
 (0)