Repository navigation
Expand file tree
/
Copy pathsuite-harness.ts
More file actions
372 lines (345 loc) · 13.5 KB
/
Copy pathsuite-harness.ts
File metadata and controls
372 lines (345 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import fs from 'node:fs';
import path from 'node:path';
import {
resolveSessionDir,
resolveSessionRequestLogPath,
} from '@agent-device/daemon-contracts/session-artifact-paths';
import { invokeCli } from './cli.ts';
import type { PerfConfig } from './config.ts';
import { captureWithForcedBackend } from './forced-backend.ts';
import { expectationViolation, type PlatformStep, type SuiteScenario } from './suite.ts';
import { buildMeasurement } from './measurement.ts';
import {
profileRequestLog,
readClientDiagnostics,
readSettleFacts,
readSnapshotFacts,
} from './profile.ts';
import type { CliResult, Measurement, Platform, Sample } from './types.ts';
const SESSION = 'perf';
export type SuiteContext = {
platform: Platform;
stateDir: string;
// The iOS simulator UDID or the Android emulator serial.
device: string;
appId: string;
artifactsDir: string;
rawDir: string;
// Set when a request outlived the client timeout. That request still holds the session, so
// the suite restarts the daemon before the next scenario.
daemonStuck?: boolean;
// Variables that the running daemon was started with, set by a step with `daemonEnv`.
daemonEnv?: Readonly<Record<string, string>>;
// Set when the daemon restart after a `daemonEnv` step could not reopen the session. The rest
// of the scenario is skipped, and the next scenario reopens the session.
restoreFailed?: string;
};
function log(msg: string): void {
process.stderr.write(`[perf] ${msg}\n`);
}
function baseFlags(ctx: SuiteContext): string[] {
return ['--state-dir', ctx.stateDir, '--session', SESSION, '--platform', ctx.platform];
}
function deviceFlags(ctx: SuiteContext): string[] {
return ctx.platform === 'ios' ? ['--udid', ctx.device] : ['--serial', ctx.device];
}
function cli(ctx: SuiteContext, args: string[]): CliResult {
return watch(ctx, invokeCli(args, baseFlags(ctx), { env: ctx.daemonEnv }));
}
function run(ctx: SuiteContext, args: readonly string[]): CliResult {
return cli(ctx, expandStatic(args, ctx));
}
function watch(ctx: SuiteContext, result: CliResult): CliResult {
if (daemonTimedOut(result)) ctx.daemonStuck = true;
return result;
}
function expandStatic(args: readonly string[], ctx: SuiteContext): string[] {
return args.map((arg) =>
arg === '{app}'
? ctx.appId
: arg.replace(/^\{out:(.+)\}$/, (_, file: string) => path.join(ctx.artifactsDir, file)),
);
}
type SnapshotNode = {
ref?: string;
identifier?: string;
rect?: { x: number; y: number; width: number; height: number };
};
const TARGET_TOKEN = /^\{(ref|point):(.+)\}$/;
/** Expands `{ref:id}` and `{point:id}` from one untimed interactive snapshot. */
function resolveTargets(args: string[], ctx: SuiteContext): string[] | { error: string } {
if (!args.some((arg) => TARGET_TOKEN.test(arg))) return args;
const snapshot = run(ctx, ['snapshot', '-i']);
const nodes = ((snapshot.json as { data?: { nodes?: SnapshotNode[] } })?.data?.nodes ??
[]) as SnapshotNode[];
const expanded: string[] = [];
for (const arg of args) {
const match = TARGET_TOKEN.exec(arg);
if (!match) {
expanded.push(arg);
continue;
}
const node = nodes.find((candidate) => candidate.identifier === match[2]);
if (!node?.ref || !node.rect) return { error: `target ${match[2]} is not in snapshot -i` };
if (match[1] === 'ref') {
expanded.push(`@${node.ref}`);
} else {
expanded.push(
String(Math.round(node.rect.x + node.rect.width / 2)),
String(Math.round(node.rect.y + node.rect.height / 2)),
);
}
}
return expanded;
}
/** Runs untimed calls in order and describes the first failure. */
function untimed(
ctx: SuiteContext,
calls: readonly (readonly string[])[] = [],
): string | undefined {
for (const args of calls) {
const result = run(ctx, args);
if (!result.ok) return `${args.join(' ')}: ${errorOf(result).errorMessage}`;
}
return undefined;
}
/** True when the client gave up on a daemon request that is still running. */
function daemonTimedOut(result: CliResult): boolean {
const details = (result.json as { error?: { details?: { reason?: unknown } } } | undefined)?.error
?.details;
return details?.reason === 'daemon_transport_timeout';
}
function errorOf(result: CliResult): Pick<Sample, 'errorCode' | 'errorMessage'> {
const error = (result.json as { error?: { code?: string; message?: string } } | undefined)?.error;
return {
errorCode: error?.code ?? `exit:${result.exitCode}`,
errorMessage: (error?.message ?? result.stderr.trim().split('\n').pop() ?? '').slice(0, 300),
};
}
function readProfile(ctx: SuiteContext, requestId: string | undefined) {
if (!requestId) return undefined;
const sessionDir = resolveSessionDir(path.join(ctx.stateDir, 'sessions'), SESSION);
const logPath = resolveSessionRequestLogPath(sessionDir, requestId);
return fs.existsSync(logPath) ? profileRequestLog(fs.readFileSync(logPath, 'utf8')) : undefined;
}
function recordFailure(ctx: SuiteContext, id: string, round: number, detail: unknown): void {
const dir = path.join(ctx.rawDir, 'failures');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(
path.join(dir, `${id.replace('/', '__')}.round-${round}.json`),
JSON.stringify(detail, null, 2),
);
}
/**
* Restarts the daemon with `env` and reopens the session on the current screen. A daemon reads
* its host environment once, at start.
*/
function restartDaemon(
ctx: SuiteContext,
env: Readonly<Record<string, string>> | undefined,
): string | undefined {
const stop = invokeCli(['daemon', 'stop'], ['--state-dir', ctx.stateDir]);
if (!stop.ok) return `daemon stop: ${errorOf(stop).errorMessage}`;
ctx.daemonEnv = env;
const failure = sessionError(openSession(ctx, { relaunch: false }));
// A fresh daemon holds no request from before the restart.
if (!failure) ctx.daemonStuck = false;
return failure;
}
async function runTimedStep(
scenario: SuiteScenario,
step: PlatformStep,
ctx: SuiteContext,
round: number,
): Promise<Sample> {
const id = `${scenario.id}/${step.id}`;
const restoreDaemon = (): void => {
if (step.daemonEnv) ctx.restoreFailed = restartDaemon(ctx, undefined);
};
const before =
(step.daemonEnv ? restartDaemon(ctx, step.daemonEnv) : undefined) ?? untimed(ctx, step.before);
if (before) {
restoreDaemon();
log(` ✗ ${id} (before_failed: ${before})`);
return { round, ok: false, wallClockMs: 0, errorCode: 'before_failed', errorMessage: before };
}
let sample: Sample;
if (step.via === 'sdk-forced-tree') {
const { result: forced, requestId } = await captureWithForcedBackend({
stateDir: ctx.stateDir,
session: SESSION,
udid: ctx.device,
backend: 'tree',
});
const result = watch(ctx, forced);
const profile = readProfile(ctx, requestId);
sample = {
round,
ok: result.ok,
wallClockMs: result.wallClockMs,
daemonMs: profile?.requestSpanMs,
requestId,
snapshot: readSnapshotFacts(result.json),
profile,
};
if (!result.ok) Object.assign(sample, errorOf(result));
} else {
const args = resolveTargets(expandStatic(step.args, ctx), ctx);
if ('error' in args) {
sample = {
round,
ok: false,
wallClockMs: 0,
errorCode: 'target_unresolved',
errorMessage: args.error,
};
} else {
const result = cli(ctx, [...args, '--debug']);
const diagnostics = readClientDiagnostics(result.stderr);
sample = {
round,
ok: result.ok,
wallClockMs: result.wallClockMs,
daemonMs: diagnostics.daemonMs,
requestId: diagnostics.requestId,
snapshot: step.command === 'snapshot' ? readSnapshotFacts(result.json) : undefined,
settle: readSettleFacts(result.json),
profile: readProfile(ctx, diagnostics.requestId),
};
if (!result.ok) {
Object.assign(sample, errorOf(result));
recordFailure(ctx, id, round, {
args,
json: result.json,
stderrTail: result.stderr.slice(-4000),
});
}
}
}
const violation = sample.ok ? expectationViolation(step.expect, sample.snapshot) : undefined;
if (violation)
Object.assign(sample, { ok: false, errorCode: 'expectation_failed', errorMessage: violation });
restoreDaemon();
const after = untimed(ctx, step.after);
if (after) log(` ! ${id} after: ${after}`);
if (!sample.ok) log(` ✗ ${id} (${sample.errorCode}: ${sample.errorMessage})`);
return sample;
}
function sessionError(result: CliResult): string | undefined {
if (result.ok) return undefined;
const message = `open: ${errorOf(result).errorMessage}`;
log(` ✗ session failed: ${message}`);
return message;
}
function stopStuckDaemon(ctx: SuiteContext): void {
log(' ! a request outlived its timeout; restarting the daemon');
invokeCli(['daemon', 'stop', '--clean'], ['--state-dir', ctx.stateDir]);
ctx.daemonStuck = false;
ctx.daemonEnv = undefined;
ctx.restoreFailed = undefined;
}
/** Opens the session with device selectors; later calls address it by session name alone. */
function openSession(ctx: SuiteContext, options: { relaunch: boolean }): CliResult {
const relaunch = options.relaunch ? ['--relaunch'] : [];
return cli(ctx, ['open', ctx.appId, ...relaunch, ...deviceFlags(ctx)]);
}
function establishSession(ctx: SuiteContext): CliResult {
if (ctx.daemonStuck || ctx.restoreFailed) stopStuckDaemon(ctx);
return openSession(ctx, { relaunch: true });
}
export async function runSuite(
ctx: SuiteContext,
cfg: PerfConfig,
scenarios: readonly SuiteScenario[],
): Promise<Measurement[]> {
const samples = new Map<string, Sample[]>();
const totalRounds = cfg.warmup + cfg.rounds;
for (let round = 0; round < totalRounds; round++) {
const measured = round >= cfg.warmup;
log(`round ${round + 1}/${totalRounds}${measured ? '' : ' (warmup, dropped)'}`);
let sessionFailure = sessionError(establishSession(ctx));
for (const scenario of scenarios) {
// A request that outlived its timeout still holds the session, and a failed daemon restore
// lost it; reopen before the next scenario.
if (ctx.daemonStuck || ctx.restoreFailed)
sessionFailure = sessionError(establishSession(ctx));
log(` scenario ${scenario.id}`);
const setupFailure = sessionFailure ?? untimed(ctx, scenario.setup);
if (setupFailure) log(` ✗ setup failed: ${setupFailure}`);
for (const step of scenario.steps) {
// CLI calls block the event loop; yield so an interrupt can stop the run between steps.
await new Promise((resolve) => setImmediate(resolve));
const id = `${scenario.id}/${step.id}`;
const skipped = setupFailure
? { errorCode: 'setup_failed', errorMessage: setupFailure }
: ctx.restoreFailed
? { errorCode: 'restore_failed', errorMessage: ctx.restoreFailed }
: ctx.daemonStuck
? {
errorCode: 'daemon_stuck',
errorMessage: 'an earlier request still holds the session',
}
: undefined;
const sample: Sample = skipped
? { round, ok: false, wallClockMs: 0, ...skipped }
: await runTimedStep(scenario, step, ctx, round);
if (measured) samples.set(id, [...(samples.get(id) ?? []), sample]);
}
}
}
return scenarios.flatMap((scenario) =>
scenario.steps.map((step) =>
buildMeasurement({
id: `${scenario.id}/${step.id}`,
scenario: scenario.id,
label: step.args.join(' '),
command: step.command,
args: [...step.args],
platform: ctx.platform,
execMode: step.via === 'sdk-forced-tree' ? 'sdk' : 'standalone',
samples: samples.get(`${scenario.id}/${step.id}`) ?? [],
warmupDropped: cfg.warmup,
}),
),
);
}
// A stalled close or daemon stop must not keep the run, and its logs, from finishing.
const TEARDOWN_TIMEOUT_MS = 60_000;
/**
* Returns the end of a run: save the logs, stop the session and the daemon within a deadline, save
* the logs again with the teardown, and remove the state directory unless it is kept. It runs once,
* so the interrupt handler and the normal finish can both call it.
*/
export function runFinalizer(ctx: SuiteContext, keepArtifacts: boolean): () => void {
let finalized = false;
const saveLogs = (): void => {
try {
copyRawState(ctx);
} catch (error) {
log(`finalize: saving logs failed: ${(error as Error).message}`);
}
};
const teardown = (args: string[], flags: string[]): void => {
const result = invokeCli(args, flags, { timeoutMs: TEARDOWN_TIMEOUT_MS });
if (!result.ok) log(`finalize: ${args.join(' ')} failed: ${result.stderr.trim().slice(-400)}`);
};
return () => {
if (finalized) return;
finalized = true;
saveLogs();
teardown(['close'], ['--state-dir', ctx.stateDir, '--session', SESSION]);
teardown(['daemon', 'stop', '--clean'], ['--state-dir', ctx.stateDir]);
saveLogs();
if (!keepArtifacts) fs.rmSync(ctx.stateDir, { recursive: true, force: true });
};
}
/** Copies daemon and session logs into the raw artifact; the daemon token file stays behind. */
function copyRawState(ctx: SuiteContext): void {
const target = path.join(ctx.rawDir, 'state');
fs.mkdirSync(target, { recursive: true });
const daemonLog = path.join(ctx.stateDir, 'daemon.log');
if (fs.existsSync(daemonLog)) fs.copyFileSync(daemonLog, path.join(target, 'daemon.log'));
const sessions = path.join(ctx.stateDir, 'sessions');
if (fs.existsSync(sessions))
fs.cpSync(sessions, path.join(target, 'sessions'), { recursive: true });
}