Files
callstack__agent-device/scripts/perf/cli.ts
Michał Pierzchała 45cfad5cc5 feat: e2e command perf benchmark harness + nightly CI (#630)
* feat: add e2e command perf benchmark harness + nightly CI

Adds scripts/perf, a cheap end-to-end perf benchmark that drives the built
CLI through an ordered Settings tour of ~24 commands for N rounds, on a fully
isolated daemon/state-dir and self-cleaning device, and emits JSON + Markdown
reports. Per-command timing comes from wrapping each batchable command in its
own single-step batch (daemon durationMs) plus wall-clock around the process.

Wires a scheduled + workflow_dispatch CI job (perf-nightly.yml) that reuses the
cached iOS XCUITest runner (setup-apple-replay) and the Android replay host, and
runs the CLI from source via --experimental-strip-types (no dist build).

* refactor(perf): drive the harness CLI via runCmdSync, not spawnSync

Review (P2): repo rule is to spawn processes through src/utils/exec.ts, not
node:child_process directly. Switch the perf harness's invokeCli to runCmdSync
(allowFailure so non-zero exits are recorded as samples) and add a maxBuffer
option to ExecOptions/runCmdSync (snapshot payloads exceed Node's ~1MB default).

* perf(harness): warm the runner after open so the first measured command is clean

The first interaction after open/relaunch pays the one-time iOS XCUITest runner
startup (~10s+ cold) and a per-relaunch first-AX-query settle cost (~4s). That was
landing on the first measured command each round (snapshot -i), inflating it ~10x
vs the next snapshot. Run an untimed warmup snapshot -i after establishSession, after
each round's reset-open, and after every freshRoot relaunch, so no measured command
absorbs runner startup. Noted in the report header.

* refactor(perf): address review + fix Fallow CI

- exec.ts: extract spawnRejectionError + commandCloseFailure helpers, deduping the
  error/close handler clones (Fallow duplication ✗ that surfaced once the maxBuffer
  change pulled exec.ts into the audit scope).
- .fallowrc: exclude scripts/perf/** (non-shipped benchmark tooling, like examples/
  test-app) so its naturally-moderate functions don't trip the complexity gate.
- config.ts: drop unused exports CLI_BIN/DEFAULT_OUT_DIR; add readIntValue so
  --n/--rounds/--warmup report the actual flag + reject non-integers clearly.
- harness.ts: extract toSample(); type sampleError param as CliResult.
- scenario.ts: ScenarioStep is now a discriminated union on execMode (removes step.step!/
  step.args ?? []).
- comment/legend rewords (platform defaults are local-convenience/CI-overridden;
  elements = node count). check:fallow now green; typecheck/lint/unit pass.

* perf(harness): downgrade sample ok when a batch step reports ok:false

Defensive belt-and-suspenders for the Codex review note: stop-only batch already
surfaces a failed step as a top-level failure (caught by invokeCli), but if an
on-error=continue mode ever keeps the batch ok while a step fails, don't silently
count that step as a successful sample — derive ok from the step's own result.ok.
2026-05-31 14:37:59 +02:00

100 lines
4.0 KiB
TypeScript

import { performance } from 'node:perf_hooks';
import { runCmdSync } from '../../src/utils/exec.ts';
import { resolveCliArgv, REPO_ROOT } from './config.ts';
import type { BatchStepSpec } from './scenario.ts';
import type { CliResult } from './types.ts';
const MAX_BUFFER = 64 * 1024 * 1024;
const CLI_ARGV = resolveCliArgv();
function tryParseJson(stdout: string): unknown {
const trimmed = stdout.trim();
if (!trimmed) return undefined;
try {
return JSON.parse(trimmed);
} catch {
// Some commands print a trailing line after JSON; try the last JSON-looking block.
const start = trimmed.indexOf('{');
const end = trimmed.lastIndexOf('}');
if (start >= 0 && end > start) {
try {
return JSON.parse(trimmed.slice(start, end + 1));
} catch {
return undefined;
}
}
return undefined;
}
}
function jsonOk(json: unknown): boolean {
return !(json !== null && typeof json === 'object' && (json as { ok?: unknown }).ok === false);
}
// Invoke the built CLI once. `args` includes the command + positionals + dash-flags;
// `baseFlags` carries the isolation + device flags shared by every call.
export function invokeCli(args: string[], baseFlags: string[]): CliResult {
const full = [...CLI_ARGV, ...args, ...baseFlags, '--json'];
const t0 = performance.now();
let stdout = '';
let stderr = '';
let exitCode = -1;
try {
// allowFailure so non-zero exits are recorded as samples instead of thrown; maxBuffer
// raised because snapshot payloads exceed Node's ~1MB default.
const r = runCmdSync(process.execPath, full, {
cwd: REPO_ROOT,
maxBuffer: MAX_BUFFER,
allowFailure: true,
});
stdout = r.stdout;
stderr = r.stderr;
exitCode = r.exitCode;
} catch (error) {
// Spawn-level failures (missing executable, timeout) — record as a failed sample.
stderr = error instanceof Error ? error.message : String(error);
}
const wallClockMs = performance.now() - t0;
const json = tryParseJson(stdout);
return { exitCode, wallClockMs, stdout, stderr, json, ok: exitCode === 0 && jsonOk(json) };
}
// Wrap a single command in its own `batch` invocation to read per-step durationMs.
export function invokeBatchStep(spec: BatchStepSpec, baseFlags: string[]): CliResult {
const result = invokeCli(['batch', '--steps', JSON.stringify([spec])], baseFlags);
// Defensive: today's stop-only batch surfaces a failed step as a top-level non-zero/ok:false
// (already caught by invokeCli). But if a future on-error mode keeps the batch ok while a step
// fails, don't silently count that step as a success — downgrade ok from the step's own ok.
const stepOk = firstBatchResult(result.json)?.ok;
if (result.ok && stepOk === false) {
return { ...result, ok: false };
}
return result;
}
function firstBatchResult(json: unknown): Record<string, unknown> | undefined {
const data = (json as { data?: { results?: unknown[] } } | undefined)?.data;
const first = data?.results?.[0];
return first && typeof first === 'object' ? (first as Record<string, unknown>) : undefined;
}
export function readBatchStepDurationMs(result: CliResult): number | undefined {
const v = firstBatchResult(result.json)?.durationMs;
return typeof v === 'number' ? v : undefined;
}
export function readBatchStepError(result: CliResult): { code?: string; message?: string } {
const err = (result.json as { error?: { code?: string; message?: string } } | undefined)?.error;
return { code: err?.code, message: err?.message };
}
// Proxy for a11y-tree size: snapshot node count (falls back to distinct @eN refs).
export function countElements(result: CliResult): number | undefined {
const stepData = firstBatchResult(result.json)?.data;
if (stepData === undefined || typeof stepData !== 'object') return undefined;
const nodes = (stepData as { nodes?: unknown }).nodes;
if (Array.isArray(nodes)) return nodes.length;
const matches = JSON.stringify(stepData).match(/@e\d+/g);
return matches ? new Set(matches).size : 0;
}