Skip to content

Commit 8a582e7

Browse files
airoweclaude
andcommitted
fix(android): share one dump budget across an observation's variants
A per-read bound still let one observation walk every dumpsys variant that answered without a focus line, each spending up to its own 10 s. All reads of one observation now draw on a single 10 s budget, so an observation costs at most one bound however many variants it reads; a spent budget or a timed-out read leaves the question unanswered. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent defd554 commit 8a582e7

2 files changed

Lines changed: 110 additions & 61 deletions

File tree

‎packages/platform-android/src/observation.test.ts‎

Lines changed: 85 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -100,55 +100,103 @@ test('a transient empty dump never demotes a variant that previously answered',
100100
expect(calls[thirdReadStart]).toBe('shell dumpsys window windows');
101101
});
102102

103-
function timedOutAdb(args: readonly string[]): AppError {
104-
return new AppError('COMMAND_FAILED', 'adb timed out', { cmd: 'adb', args, timeoutMs: 1 });
103+
function timedOutAdb(args: readonly string[], timeoutMs: number): AppError {
104+
return new AppError('COMMAND_FAILED', 'adb timed out', { cmd: 'adb', args, timeoutMs });
105105
}
106106

107-
test('bounds every dump read the foreground question makes', async () => {
108-
const host = hostFor(new Map());
109-
const observer = createAndroidObservationAdapter(host);
107+
type Observer = ReturnType<typeof createAndroidObservationAdapter>;
110108

111-
await observer.readAppState({ ...device, id: 'emulator-bounded' });
109+
const QUESTIONS = [
110+
{
111+
question: 'foreground',
112+
ask: (observer: Observer, target: DeviceInfo) => observer.readAppState(target),
113+
unanswered: {},
114+
},
115+
{
116+
question: 'blocking dialog',
117+
ask: (observer: Observer, target: DeviceInfo) => observer.readBlockingDialog(target),
118+
unanswered: { status: 'unknown' },
119+
},
120+
] as const;
121+
122+
/**
123+
* A host whose every dump answers without a focus line after `spendMs(timeoutMs)` of a virtual
124+
* clock, optionally timing out instead, so an observation walks every variant it is allowed to.
125+
*/
126+
function slowHost(params: { spendMs: (timeoutMs: number) => number; timeOut?: boolean }): {
127+
host: AndroidObservationHost;
128+
timeouts: number[];
129+
restore: () => void;
130+
} {
131+
const originMs = Date.now();
132+
let elapsedMs = 0;
133+
const now = vi.spyOn(Date, 'now').mockImplementation(() => originMs + elapsedMs);
134+
const timeouts: number[] = [];
135+
const host: AndroidObservationHost = {
136+
...hostFor(new Map()),
137+
runAdb: vi.fn(async (_device, args, options) => {
138+
const timeoutMs = options?.timeoutMs ?? Number.POSITIVE_INFINITY;
139+
timeouts.push(timeoutMs);
140+
elapsedMs += params.spendMs(timeoutMs);
141+
if (params.timeOut) throw timedOutAdb(args, timeoutMs);
142+
return { exitCode: 0, stdout: '', stderr: '' };
143+
}),
144+
};
145+
return { host, timeouts, restore: () => now.mockRestore() };
146+
}
112147

113-
const calls = vi.mocked(host.runAdb).mock.calls;
114-
expect(calls.map(([, args]) => args.join(' '))).toEqual([
148+
test('bounds every dump read the foreground question makes', async () => {
149+
const { host, timeouts, restore } = slowHost({ spendMs: () => 0 });
150+
try {
151+
await createAndroidObservationAdapter(host).readAppState({ ...device, id: 'emulator-bounded' });
152+
} finally {
153+
restore();
154+
}
155+
156+
expect(vi.mocked(host.runAdb).mock.calls.map(([, args]) => args.join(' '))).toEqual([
115157
'shell dumpsys window windows',
116158
'shell dumpsys window',
117159
'shell dumpsys activity activities',
118160
'shell dumpsys activity',
119161
]);
120-
for (const [, , options] of calls) {
121-
expect(options).toEqual({ allowFailure: true, timeoutMs: expect.any(Number) });
122-
expect(options?.timeoutMs).toBeGreaterThan(0);
162+
for (const timeoutMs of timeouts) expect(Number.isFinite(timeoutMs) && timeoutMs > 0).toBe(true);
163+
});
164+
165+
test('later variants receive only what the earlier reads left of one observation budget', async () => {
166+
const { host, timeouts, restore } = slowHost({
167+
spendMs: (timeoutMs) => Math.floor(timeoutMs / 2),
168+
});
169+
try {
170+
await createAndroidObservationAdapter(host).readAppState({ ...device, id: 'emulator-slow' });
171+
} finally {
172+
restore();
173+
}
174+
175+
const budgetMs = timeouts[0]!;
176+
expect(timeouts.length).toBeGreaterThan(1);
177+
for (let index = 1; index < timeouts.length; index += 1) {
178+
expect(timeouts[index]).toBe(timeouts[index - 1]! - Math.floor(timeouts[index - 1]! / 2));
123179
}
180+
const spentMs = timeouts.reduce((sum, timeoutMs) => sum + Math.floor(timeoutMs / 2), 0);
181+
expect(spentMs).toBeLessThanOrEqual(budgetMs);
124182
});
125183

126-
test.each([
127-
{
128-
question: 'foreground',
129-
ask: (observer: ReturnType<typeof createAndroidObservationAdapter>, target: DeviceInfo) =>
130-
observer.readAppState(target),
131-
unanswered: {},
132-
},
133-
{
134-
question: 'blocking dialog',
135-
ask: (observer: ReturnType<typeof createAndroidObservationAdapter>, target: DeviceInfo) =>
136-
observer.readBlockingDialog(target),
137-
unanswered: { status: 'unknown' },
138-
},
139-
])(
140-
'a timed-out dump leaves the $question question unanswered and reads no further variant',
141-
async ({ question, ask, unanswered }) => {
142-
const host: AndroidObservationHost = {
143-
...hostFor(new Map()),
144-
runAdb: vi.fn(async (_device, args) => {
145-
throw timedOutAdb(args);
146-
}),
147-
};
148-
149-
await expect(
150-
ask(createAndroidObservationAdapter(host), { ...device, id: `emulator-hung-${question}` }),
151-
).resolves.toEqual(unanswered);
184+
test.each(
185+
QUESTIONS.flatMap((entry) => [
186+
{ ...entry, ending: 'times out', timeOut: true },
187+
{ ...entry, ending: 'answers at its bound', timeOut: false },
188+
]),
189+
)(
190+
'a $question read that $ending spends the observation budget and leaves it unanswered',
191+
async ({ question, ask, unanswered, timeOut }) => {
192+
const { host, restore } = slowHost({ spendMs: (timeoutMs) => timeoutMs, timeOut });
193+
try {
194+
await expect(
195+
ask(createAndroidObservationAdapter(host), { ...device, id: `emulator-${question}` }),
196+
).resolves.toEqual(unanswered);
197+
} finally {
198+
restore();
199+
}
152200
expect(host.runAdb).toHaveBeenCalledTimes(1);
153201
},
154202
);

‎packages/platform-android/src/observation.ts‎

Lines changed: 25 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ const PERMISSION_PACKAGES = new Set([
3333
'com.google.android.packageinstaller',
3434
]);
3535

36-
const DUMP_READ_TIMEOUT_MS = 10_000;
36+
const DUMP_OBSERVATION_BUDGET_MS = 10_000;
3737

3838
type Question = 'foreground' | 'blockingDialog';
3939
type DumpReader = (words: readonly string[]) => Promise<string>;
@@ -83,34 +83,35 @@ export function createAndroidObservationAdapter(
8383
}
8484

8585
/**
86-
* A dump that times out is an unanswered read, like one that printed nothing: the observation
87-
* reports `unknown` and never refuses the command. After one timeout the device is not answering,
88-
* so the reader skips its remaining variants and an observation costs at most one bound.
86+
* Every variant one observation reads shares a single {@link DUMP_OBSERVATION_BUDGET_MS} budget,
87+
* so an observation costs at most one bound however many variants it walks. A read that times out
88+
* or finds the budget spent is an unanswered read, like one that printed nothing: the observation
89+
* reports `unknown` and never refuses the command.
8990
*/
9091
function createDumpReader(host: AndroidObservationHost, device: DeviceInfo): DumpReader {
9192
const dumps = new Map<string, Promise<string>>();
92-
let timedOut = false;
93+
const deadlineMs = Date.now() + DUMP_OBSERVATION_BUDGET_MS;
9394
return (words) => {
94-
if (timedOut) return Promise.resolve('');
9595
const key = words.join(' ');
96-
const pending =
97-
dumps.get(key) ??
98-
host
99-
.runAdb(device, deviceShellArgv('adb', 'shell', words), {
100-
allowFailure: true,
101-
timeoutMs: DUMP_READ_TIMEOUT_MS,
102-
})
103-
.then(
104-
(result) => {
105-
recordSections(device, key, result.stdout);
106-
return result.stdout;
107-
},
108-
(error: unknown) => {
109-
if (!isCommandTimeoutError(error)) throw error;
110-
timedOut = true;
111-
return '';
112-
},
113-
);
96+
const cached = dumps.get(key);
97+
if (cached) return cached;
98+
const remainingMs = deadlineMs - Date.now();
99+
if (remainingMs <= 0) return Promise.resolve('');
100+
const pending = host
101+
.runAdb(device, deviceShellArgv('adb', 'shell', words), {
102+
allowFailure: true,
103+
timeoutMs: remainingMs,
104+
})
105+
.then(
106+
(result) => {
107+
recordSections(device, key, result.stdout);
108+
return result.stdout;
109+
},
110+
(error: unknown) => {
111+
if (!isCommandTimeoutError(error)) throw error;
112+
return '';
113+
},
114+
);
114115
dumps.set(key, pending);
115116
return pending;
116117
};

0 commit comments

Comments
 (0)