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
15 changes: 15 additions & 0 deletions scripts/perf/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,18 @@ When failures are new or more, a faster median is `insufficient-samples`, not `i
The samples that still pass do not show that the step got faster.
Regressions and worse failures are workflow warnings. The job stays green.
The thresholds are in `compare.ts`.

### Executable origin

`metadata.origin` in `summary.json` records the origin of the CLI and of the SDK that the run measured.
The origin is `checkout`, `installed-package`, or `unknown`, with the version and the commit where known.
`metadata.commit` and `metadata.agentDeviceVersion` describe the harness checkout.
`AGENT_DEVICE_PERF_CLI` replaces the CLI. It does not replace the SDK.
The override is `unknown` unless it is one path to the `bin` entry of an installed `agent-device` package or of a git checkout.
Older harness versions did not record `metadata.origin`.
If such a summary has a `runId`, has the `ref` `main`, and is not `dirty`, the comparison reads it as `checkout`.
Each other summary without `metadata.origin` is `unknown`.

If an origin is `unknown`, or if the CLI or SDK origin differs between the compared runs, each step that both sides measured gets the timing verdict `incomparable-origin`.
The comparison names those runs. It still judges failures.
Versions and commits can differ.
135 changes: 134 additions & 1 deletion scripts/perf/compare.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import assert from 'node:assert/strict';
import { test } from 'vitest';
import { compareRuns, type ComparisonRow } from './compare.ts';
import { compareRuns, renderComparison, type ComparisonRow } from './compare.ts';
import { summaryFixture, type StepFixture } from './summary.fixtures.ts';
import { parsePerfSummary } from './summary.ts';
import type { MeasuredOrigin, PerfSummary } from './types.ts';

const STEP = 'heavy-feed/snapshot';

Expand Down Expand Up @@ -144,3 +146,134 @@ test('refuses a baseline run from another platform', () => {
]);
assert.equal(comparison.platform, 'android');
});

const installed = (version: string): MeasuredOrigin => ({
cli: { kind: 'installed-package', version },
sdk: { kind: 'checkout' },
});

const slower = () => summaryFixture(flat(1500));

function compareToQuietNights(target: PerfSummary, ...extra: PerfSummary[]) {
return compareRuns({ summary: target, label: 'tonight' }, [
...nights(flat(1000), flat(1000), flat(1000)),
...extra.map((summary) => ({ summary, label: 'odd night' })),
]);
}

test('judges timing across versions and commits of one origin kind', () => {
const comparison = compareRuns(
{ summary: summaryFixture(flat(1500), { origin: installed('2.0.0') }), label: 'tonight' },
['1.0.0', '1.1.0', '1.2.0'].map((version) => ({
summary: summaryFixture(flat(1000), { origin: installed(version) }),
label: version,
})),
);
assert.equal(comparison.rows[0]?.timing, 'regression');
assert.deepEqual(comparison.warnings, []);
});

test('refuses a timing verdict when one baseline run measured another origin', () => {
const comparison = compareToQuietNights(
slower(),
summaryFixture(flat(1000), { origin: installed('1.0.0') }),
);
const [step] = comparison.rows;
assert.equal(step?.timing, 'incomparable-origin');
assert.equal(step?.deltaMs, null);
assert.equal(step?.threshold, null);
assert.equal(comparison.warnings.length, 1);
assert.match(
comparison.warnings[0]!,
/^No timing verdict: .*odd night: CLI installed package 1\.0\.0, SDK checkout\./,
);
assert.doesNotMatch(comparison.warnings[0]!, /night 0/);
});

test('refuses a timing verdict when only the SDK origin differs', () => {
const sdkInstalled: MeasuredOrigin = {
cli: { kind: 'checkout' },
sdk: { kind: 'installed-package' },
};
const comparison = compareToQuietNights(summaryFixture(flat(1500), { origin: sdkInstalled }));
assert.equal(comparison.rows[0]?.timing, 'incomparable-origin');
});

test('refuses runs of unknown origin even when both sides are unknown, and keeps failures', () => {
const origin: MeasuredOrigin = { cli: { kind: 'unknown' }, sdk: { kind: 'checkout' } };
const comparison = compareRuns(
{ summary: summaryFixture(flat(1500, { failures: 1 }), { origin }), label: 'tonight' },
[1, 2, 3].map((n) => ({
summary: summaryFixture(flat(1000), { origin }),
label: `night ${n}`,
})),
);
assert.equal(comparison.rows[0]?.timing, 'incomparable-origin');
assert.equal(comparison.rows[0]?.failures, 'new-failures');
});

// The metadata of `perf-ios-summary` from scheduled run 46217057081, written before
// `metadata.origin` existed.
const NIGHTLY_METADATA: PerfSummary['metadata'] = {
commit: '89e65e9099d11f1f15fab96a17c6371a79006503',
ref: 'main',
dirty: false,
runId: '46217057081',
runAttempt: '1',
agentDeviceVersion: '0.21.45-dev',
host: {
os: 'darwin 25.3.0',
arch: 'arm64',
cpu: 'Apple M4 Pro (Virtual)',
cores: 6,
memoryGb: 24,
},
xcode: 'Xcode 26.6 Build version 17F113',
node: 'v24.13.1',
device: {
name: 'iPhone 17 Pro',
udid: '2B2616F6-DEDD-4A00-BF00-491F8130D75F',
runtime: 'iOS-26-2',
},
fixture: {
appId: 'com.callstack.agentdevicelab',
appPath: '/Users/runner/_work/agent-device/agent-device/.tmp/fixture-app/AgentDeviceTester.app',
},
};

function historical(steps: StepFixture[], metadata: Partial<PerfSummary['metadata']> = {}) {
const summary = { ...summaryFixture(steps), metadata: { ...NIGHTLY_METADATA, ...metadata } };
return parsePerfSummary(JSON.parse(JSON.stringify(summary)), 'old/summary.json');
}

test('judges a recorded checkout run against earlier nightly artifacts without an origin', () => {
const comparison = compareRuns(
{ summary: slower(), label: 'tonight' },
[1, 2, 3].map((n) => ({ summary: historical(flat(1000)), label: `night ${n}` })),
);
assert.equal(comparison.rows[0]?.timing, 'regression');
const inferred = {
kind: 'checkout',
version: '0.21.45-dev',
commit: '89e65e9099d11f1f15fab96a17c6371a79006503',
dirty: false,
};
assert.deepEqual(comparison.baseline[0]?.origin, { cli: inferred, sdk: inferred });
});

test.each([
['a manual run', { runId: undefined, runAttempt: undefined }],
['a CI run of another branch', { ref: 'perf/experiment' }],
['a run of a dirty tree', { dirty: true }],
])('reads %s without an origin record as unknown origin', (_, metadata) => {
const comparison = compareToQuietNights(slower(), historical(flat(1000), metadata));
assert.deepEqual(comparison.baseline.at(-1)?.origin, {
cli: { kind: 'unknown' },
sdk: { kind: 'unknown' },
});
assert.equal(comparison.rows[0]?.timing, 'incomparable-origin');
const markdown = renderComparison(comparison);
assert.match(markdown, /odd night: CLI unknown origin, SDK unknown origin/);
assert.match(markdown, /Timing was not judged/);
assert.doesNotMatch(markdown, /No step moved beyond its noise threshold/);
});
112 changes: 103 additions & 9 deletions scripts/perf/compare.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { MIN_MEASURED_ROUNDS } from './config.ts';
import { median, scaledMad } from './stats.ts';
import type { Measurement, PerfSummary, Platform, Stat } from './types.ts';
import type {
ExecutableOrigin,
MeasuredOrigin,
Measurement,
PerfSummary,
Platform,
RunMetadata,
Stat,
} from './types.ts';

export type ComparisonThresholds = {
// A change must exceed every one of these to be flagged.
Expand Down Expand Up @@ -28,7 +36,8 @@ export type TimingVerdict =
| 'insufficient-samples'
| 'insufficient-baseline'
| 'new'
| 'missing';
| 'missing'
| 'incomparable-origin';

export type FailureVerdict = 'new-failures' | 'more-failures' | 'fixed' | 'unchanged';

Expand Down Expand Up @@ -72,6 +81,7 @@ export type RunRef = {
device: string;
xcode?: string;
rounds: number;
origin: MeasuredOrigin;
};

const COMPARISON_SCHEMA = 'agent-device-perf-comparison/v1';
Expand All @@ -90,6 +100,77 @@ export type Comparison = {
rows: ComparisonRow[];
};

/**
* The origin of a summary from a harness that did not record `metadata.origin`. The nightly
* workflow on `main` never replaced the CLI or the SDK of the checkout in a run that uploaded this
* summary schema, so a clean CI run of `main` measured the checkout.
*/
function unrecordedOrigin(metadata: RunMetadata): ExecutableOrigin {
const { runId, ref, dirty, commit, agentDeviceVersion } = metadata;
if (!runId || ref !== 'main' || dirty !== false) return { kind: 'unknown' };
return { kind: 'checkout', version: agentDeviceVersion, commit, dirty };
}

/** The measured executables of a run. An unrecognized record reads as `unknown`. */
function measuredOrigin({ metadata }: PerfSummary): MeasuredOrigin {
const recorded = metadata.origin;
if (recorded === undefined) {
const origin = unrecordedOrigin(metadata);
return { cli: origin, sdk: origin };
}
const read = (origin: ExecutableOrigin | undefined): ExecutableOrigin =>
origin?.kind === 'checkout' || origin?.kind === 'installed-package'
? origin
: { kind: 'unknown' };
return { cli: read(recorded?.cli), sdk: read(recorded?.sdk) };
}

function describeExecutable(origin: ExecutableOrigin): string {
if (origin.kind === 'unknown') return 'unknown origin';
const version = origin.version ? ` ${origin.version}` : '';
if (origin.kind === 'installed-package') return `installed package${version}`;
const commit = origin.commit ? ` @ ${origin.commit.slice(0, 7)}` : '';
return `checkout${version}${commit}${origin.dirty ? ' (dirty)' : ''}`;
}

function describeOrigin({ cli, sdk }: MeasuredOrigin): string {
return `CLI ${describeExecutable(cli)}, SDK ${describeExecutable(sdk)}`;
}

/**
* Timings are comparable only when every run measured a known origin of the same kind as the
* target, for the CLI and for the SDK. Versions and commits may differ: they are what a comparison
* measures. Returns why the timings are not comparable.
*/
function originRefusal(
target: { summary: PerfSummary; label: string },
baseline: { summary: PerfSummary; label: string }[],
): string | undefined {
const mine = measuredOrigin(target.summary);
const comparable = (origin: MeasuredOrigin) =>
(['cli', 'sdk'] as const).every(
(key) => origin[key].kind !== 'unknown' && origin[key].kind === mine[key].kind,
);
const refused = baseline.filter((run) => !comparable(measuredOrigin(run.summary)));
if (comparable(mine) && refused.length === 0) return undefined;
const runs = [target, ...refused]
.map((run) => `${run.label}: ${describeOrigin(measuredOrigin(run.summary))}`)
.join('; ');
return `No timing verdict: every compared run must measure the same known executable origin (checkout or installed package). ${runs}.`;
}

/** Removes the timing judgement of a step that both sides measured. Failures stay judged. */
function withholdTiming(row: ComparisonRow): ComparisonRow {
if (!row.target || !row.baseline) return row;
return {
...row,
timing: 'incomparable-origin',
deltaMs: null,
deltaRelative: null,
threshold: null,
};
}

function describeRun(summary: PerfSummary, label: string): RunRef {
return {
label,
Expand All @@ -99,6 +180,7 @@ function describeRun(summary: PerfSummary, label: string): RunRef {
device: `${summary.metadata.device.name}${summary.metadata.device.runtime ? ` ${summary.metadata.device.runtime}` : ''}`,
xcode: summary.metadata.xcode,
rounds: summary.config.rounds,
origin: measuredOrigin(summary),
};
}

Expand Down Expand Up @@ -218,7 +300,8 @@ function environmentWarnings(target: PerfSummary, baseline: PerfSummary[]): stri
* only when its change exceeds the relative floor, the night-to-night spread, tonight's own
* sampling error, and an absolute floor together. Tonight and every night that counts need
* `minSamples` successful samples. Failures are judged apart from timing. Every baseline run must
* come from the platform of the target.
* come from the platform of the target. Runs of mixed or unknown executable origin get no timing
* verdict.
*/
export function compareRuns(
target: { summary: PerfSummary; label: string },
Expand All @@ -237,14 +320,16 @@ export function compareRuns(
...target.summary.measurements.map((m) => m.id),
...baseline.flatMap((b) => b.summary.measurements.map((m) => m.id)),
];
const rows = [...new Set(ids)].map((id) =>
const refusal = originRefusal(target, baseline);
const judged = [...new Set(ids)].map((id) =>
compareStep(
id,
targetById.get(id),
baseline.flatMap((b) => b.summary.measurements.filter((m) => m.id === id)),
thresholds,
),
);
const rows = refusal ? judged.map(withholdTiming) : judged;
const counts: Comparison['counts'] = { timing: {}, failures: {} };
for (const row of rows) {
counts.timing[row.timing] = (counts.timing[row.timing] ?? 0) + 1;
Expand All @@ -257,10 +342,13 @@ export function compareRuns(
baseline: baseline.map((b) => describeRun(b.summary, b.label)),
thresholds,
counts,
warnings: environmentWarnings(
target.summary,
baseline.map((b) => b.summary),
),
warnings: [
...(refusal ? [refusal] : []),
...environmentWarnings(
target.summary,
baseline.map((b) => b.summary),
),
],
Comment thread
thymikee marked this conversation as resolved.
Resolved
rows,
};
}
Expand Down Expand Up @@ -311,6 +399,7 @@ export function renderComparison(comparison: Comparison): string {
'',
`- **Tonight**: ${comparison.target.label} · ${comparison.target.commit.slice(0, 12)} · ${comparison.target.startedAt} · ${comparison.target.device}`,
`- **Baseline**: ${comparison.baseline.length === 0 ? 'none' : comparison.baseline.map((b) => `${b.label} (${b.commit.slice(0, 7)})`).join(', ')}`,
`- **Measured tonight**: ${describeOrigin(comparison.target.origin)}`,
`- **Rule**: flag a step when its median moves by more than max(${pct(t.minRelative)}, ${t.spreadFactor}× night-to-night spread, ${t.withinFactor}× tonight cv/√n) and more than ${t.minAbsoluteMs} ms against the median of the baseline nights; a timing verdict needs ${t.minBaselineNights} nights, and tonight and each of those nights need ${t.minSamples} successful samples. Failures are flagged when tonight has more failed samples than every baseline night, in count and in share.`,
`- **Timing**: ${describeCounts(comparison.counts.timing)}`,
`- **Failures**: ${describeCounts(comparison.counts.failures)}`,
Expand All @@ -320,7 +409,12 @@ export function renderComparison(comparison: Comparison): string {
if (flagged.length > 0) {
lines.push(...TABLE_HEAD, ...flagged.map(tableRow), '');
} else {
lines.push('No step moved beyond its noise threshold.', '');
lines.push(
comparison.counts.timing['incomparable-origin']
? 'Timing was not judged. No failure verdict changed.'
: 'No step moved beyond its noise threshold.',
'',
);
}
lines.push(
'<details><summary>All steps</summary>',
Expand Down
Loading
Loading