Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
5 changes: 5 additions & 0 deletions .changeset/timings-history.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"e2e": patch
---

`e2e run` keeps a small `<output>/timings.json` (schema `timings-1`) of how long each file took, smoothed over recent runs, and starts the longest files first from it when it runs with more than one worker. A CI cache can restore and save just that file, so a fresh checkout gets the ordering; `--timings <file>` moves it. A missing or invalid file is no history, and the previous `report.json` is still the fallback.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ dist/
**/.e2e/sessions/
**/.e2e/report.json
**/.e2e/ai-trace.json
**/.e2e/timings.json
**/.e2e/junit.xml
**/.e2e/summary.md
**/.e2e/logs/
Expand Down
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ There is no separate spec. The code is the contract, pinned in three places:
by accident; it runs under the package `typecheck`, never under vitest.
- Wire formats live in `packages/e2e/schema/*.schema.json` (report-1,
session-1, agent-judgment-2, the engine protocol's engine-manifest-1,
`e2e doctor`'s doctor-1, and the deprecated agent-judgment-1) with a valid and an invalid fixture
`e2e doctor`'s doctor-1, the scheduler's advisory timings-1, and the deprecated agent-judgment-1) with a valid and an invalid fixture
each. Integration tests validate every generated report and session envelope
against them; `tests/unit/schema-fixtures.test.ts` checks the fixtures. A
wire change edits the schema, both fixtures, and the producer in one review.
Expand Down
19 changes: 19 additions & 0 deletions docs/ci.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,25 @@ leave out the tests the change is unlikely to affect. Without the flag, as
on `main`, the whole suite runs. See
[Add the decision filter](/filters#add-the-decision-filter).

## Cache the timings history

With more than one worker, `e2e run` starts the longest files first, ordered
by `.e2e/timings.json`: a few KB that every run updates. A fresh CI checkout
Comment thread
kdy1 marked this conversation as resolved.
Resolved
has none, so restore it from your CI cache before the run and save it after.
[GitHub Actions](/ci/github-actions#cache-the-timings-history) has the step.

- The file is advisory. One that is missing, corrupt, or invalid is no history,
and the run falls back to the previous `report.json`. A restored file can
change the order of files, never a result.
- A run times a file only when it ran all of it. A `--grep` or
`--last-failed` run leaves the entry of a file it ran in part as it was.
- CI defaults to one worker. Set [`workers`](/reference/config#workers) or
pass `--workers` to benefit.
- Key the cache by branch, with `main` as the fallback, so a new pull
request starts from the history of `main`. With [sharding](#sharding), add
the shard index to the key.
- `--timings <file>` reads and writes another path.

## Sharding

`--shard <index/total>` runs one slice of the suite. Every job runs the
Expand Down
26 changes: 26 additions & 0 deletions docs/ci/github-actions.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,32 @@ for the engine's pinned Playwright version, with their system libraries; the
cache step skips the download until the lockfile changes. A
test that passed on retry keeps its failed attempt's evidence in the upload.

## Cache the timings history

Restore and save [`.e2e/timings.json`](/ci#cache-the-timings-history) with
`actions/cache`, so a fresh runner starts the longest files first. Add the
step before the run:

```yaml
- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: .e2e/timings.json
key: e2e-timings-${{ github.ref_name }}-${{ github.run_id }}
Comment thread
kdy1 marked this conversation as resolved.
Resolved
restore-keys: |
e2e-timings-${{ github.ref_name }}-
e2e-timings-main-
```

Each run saves a new entry and restores the newest one for its branch. A pull
request can read the base branch's cache but not write to it, so a first run
on a new branch starts from the history of `main`.

The step saves after the job passes. To save after a failed run too, use
`actions/cache/restore` before the run and `actions/cache/save` after it with
`if: ${{ !cancelled() }}`. The history only helps with
[`workers`](/reference/config#workers) of 2 or more, and the workflow above
runs one.

## iOS and Android

This workflow runs one job for each platform and follows the rules in
Expand Down
3 changes: 2 additions & 1 deletion docs/reference/cli.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ field or lockfile, then the invoking package manager, then npm.
| `package.json` | Created as a private ESM package when missing; otherwise gets only the missing dependencies and scripts. Sibling packages (`@e2e-dev/web`, `@e2e-dev/mobile`) get the caret range of the version released with the CLI, or that exact version when the CLI is a prerelease. Adds a `test:e2e` script that runs `e2e run`, unless one exists |
| `e2e.config.ts` | One target per selected engine, with the app in its `app`. Playwright reads `APP_URL` (default `http://localhost:3000`) into `app.url` and shows `app.command` in a comment. Mobile sets `app: { bundleId: 'Settings' }` on iOS and `com.android.settings` on Android, and `workers: 1`. With a gateway, `agents.default` is `{ model, system }` |
| `tests/example.e2e.ts` | An app-open test that passes against any page, plus a commented agent test. Device setup gets a Settings check instead. With both engines, `tests/web.e2e.ts` and `tests/mobile.e2e.ts` instead, each test with `requires: ['browser']` or `requires: ['device']` so the other target skips it |
| `.gitignore` | Appends `node_modules/`, `.e2e/results/`, `.e2e/cache/`, `.e2e/sessions/`, `.e2e/report.json`, `.e2e/ai-trace.json`, `.e2e/junit.xml`, `.e2e/summary.md`, `.e2e/logs/`, and `.e2e/videos/`. Committing the cache is opt-in; see [commit the replay cache](/cache#commit-the-replay-cache) |
| `.gitignore` | Appends `node_modules/`, `.e2e/results/`, `.e2e/cache/`, `.e2e/sessions/`, `.e2e/report.json`, `.e2e/ai-trace.json`, `.e2e/timings.json`, `.e2e/junit.xml`, `.e2e/summary.md`, `.e2e/logs/`, and `.e2e/videos/`. Committing the cache is opt-in; see [commit the replay cache](/cache#commit-the-replay-cache) |
| `.agents/skills/e2e/`, `.claude/skills/e2e/` | `SKILL.md` and one `references/<topic>.md` per `e2e guide` topic. With both chosen, the Claude Code directory is a relative symlink (`../../.agents/skills/e2e`) to the copy, the layout `npx skills add` produces |
| `.mcp.json`, `.cursor/mcp.json`, `.codex/config.toml` | Registers `e2e mcp` without changing other servers |

Expand Down Expand Up @@ -575,6 +575,7 @@ Test files, directories, or globs relative to the project root:
| `--reporter <ids>` | Replaces the built-in IDs in `config.reporters`, comma-separated: `list`, `json`, `junit`, `markdown`. Default: the config. `json` with `list` is `INVALID_CONFIG`. [Reporter objects](/reference/reporters) in the config keep running. |
| `--output <dir>` | The results directory for this run, over the config's [`output`](/reference/config#output): the report, the reporter files, the AI trace, `results/`, and `sessions/`. Default: the config, else `.e2e`. Resolved from the project root; a directory the run cannot own is `INVALID_CONFIG`. `results/` is cleared once the tests start; a `--last-failed` rerun keeps what the previous report names. |
| `--cache-dir <dir>` | The replay cache directory for this run, over [`E2E_CACHE_DIR`](/reference/environment#replay-cache) and [`cache.dir`](/reference/config#cache). Default: `E2E_CACHE_DIR`, else `cache.dir`, else `.e2e/cache`. Resolved from the project root; `~` or a leading `~/` is the home directory. The cache mode stays as configured. With a custom `cache.store` it is `INVALID_CONFIG`. |
| `--timings <file>` | The [timings history](/ci#cache-the-timings-history) to order files by and update when the run ends, over `<output>/timings.json`. Resolved from the project root. A missing or invalid file is no history, never an error. |
Comment thread
kdy1 marked this conversation as resolved.
Resolved
| `--debug` | Phase timings and an agent step table on stderr after the run; see [Debug output](#debug-output). |
| `--ai-trace` | Records every model call to `<output>/ai-trace.json`; see [Output](#output). |
| `--trace [mode]` | Which tests keep a trace page (`<output>/results/<test>/trace.md`): `off`, `on`, `retain-on-failure`, `on-first-retry`, or `on-all-retries`. Default: the config. `--trace off` writes none for a test without its own `trace`. See [trace](/reference/config#trace). |
Expand Down
1 change: 1 addition & 0 deletions docs/reference/config.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -617,6 +617,7 @@ overrides it for one run.
| `report.json` | The canonical report; `--last-failed` reads the one here |
| `junit.xml`, `summary.md` | The `junit` and `markdown` reporters' files |
| `ai-trace.json` | `--ai-trace` |
| `timings.json` | How long each file took, smoothed over recent runs. A run with more than one worker starts the longest files first by it; see [Cache the timings history](/ci#cache-the-timings-history) |
| `results/` | One directory per test: its [trace page](/debugging#traces), `trace.md`, when the [`trace`](#trace) mode keeps one, and its screenshots, videos, downloads, and logs, one `attempt-<n>/` per attempt. Cleared once a run's tests start, so it holds the latest run's evidence and nothing its report no longer names. A `--last-failed` rerun keeps the files the report it reruns names and writes its own attempts under each test's `rerun-<n>/` |
| `sessions/` | The run's encrypted `test.setup` sessions, deleted when it ends |
| `videos/<session>/` | [`e2e mcp`](/reference/mcp#recording) session recordings |
Expand Down
7 changes: 7 additions & 0 deletions packages/e2e/schema/fixtures/timings-v1.invalid.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"schemaVersion": "timings-1",
"files": {
"tests/checkout.e2e.ts": 17042,
Comment thread
kdy1 marked this conversation as resolved.
Resolved
"web::tests/login.e2e.ts": -5
}
}
8 changes: 8 additions & 0 deletions packages/e2e/schema/fixtures/timings-v1.valid.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"schemaVersion": "timings-1",
"files": {
"web::tests/checkout.e2e.ts": 17042,
"web::tests/login.e2e.ts": 2310,
"mobile::tests/checkout.e2e.ts": 41877
}
}
19 changes: 19 additions & 0 deletions packages/e2e/schema/timings-v1.schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://e2e.dev/schema/timings-v1.schema.json",
"title": "e2e timings-1",
"description": "The history `e2e run` keeps in `<output>/timings.json` to start the longest files first. Advisory: a runner that finds any other document reads no history, and a restored file can reorder work, never change a result.",
"type": "object",
"additionalProperties": false,
"required": ["schemaVersion", "files"],
"properties": {
"schemaVersion": { "const": "timings-1" },
"files": {
"description": "Milliseconds a target's file took, smoothed over recent runs, keyed `<target>::<project-relative file>`.",
"type": "object",
"maxProperties": 100000,
"propertyNames": { "pattern": "^[A-Za-z0-9_.-]+::.+$" },
Comment thread
kdy1 marked this conversation as resolved.
Resolved
"additionalProperties": { "type": "integer", "minimum": 0 }
}
}
}
3 changes: 3 additions & 0 deletions packages/e2e/src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,7 @@ function createProgram(version: string, telemetry: Telemetry, updateCheck: Updat
.option('--reporter <ids>', `comma-separated reporters: ${BUILTIN_REPORTERS.join(', ')}`, parseReporters)
.option('--output <dir>', 'results directory: report, artifacts, sessions (default: output in the config, else .e2e)')
.option('--cache-dir <dir>', CACHE_DIR_DESCRIPTION)
.option('--timings <file>', 'the timings history file a run orders its files by and updates when it ends (default: <output>/timings.json)')
.addOption(new Option('--artifacts <dir>').hideHelp().argParser(removedArtifactsFlag))
.option('--debug', 'print phase timings and the agent step table to stderr')
.option('--ai-trace', 'record every model call to <output>/ai-trace.json (unbox-ai)')
Expand Down Expand Up @@ -692,6 +693,7 @@ function createProgram(version: string, telemetry: Telemetry, updateCheck: Updat
reporter?: Reporter[];
output?: string;
cacheDir?: string;
timings?: string;
/** Commander negation: `--no-cache` parses as `cache: false`. */
cache?: boolean;
strictCache?: boolean;
Expand Down Expand Up @@ -722,6 +724,7 @@ function createProgram(version: string, telemetry: Telemetry, updateCheck: Updat
reporters: options.reporter,
output: options.output,
cacheDir: options.cacheDir,
timings: options.timings,
noCache: options.cache === false,
strictCache: options.strictCache,
updateSnapshots: options.updateSnapshots,
Expand Down
1 change: 1 addition & 0 deletions packages/e2e/src/cli/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ const GITIGNORE_ENTRIES = [
'.e2e/sessions/',
'.e2e/report.json',
'.e2e/ai-trace.json',
'.e2e/timings.json',
'.e2e/junit.xml',
'.e2e/summary.md',
'.e2e/logs/',
Expand Down
40 changes: 28 additions & 12 deletions packages/e2e/src/run/last-run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,30 +274,46 @@ function isError(value: unknown): value is ReportError {
);
}

/** Whether a result stands for a test its run did not carry out whole: left out, cut short, or never reached. */
function leftUnmeasured(result: ReportResult): boolean {
if (result.selected === false || result.status === 'interrupted') return true;
Comment thread
kdy1 marked this conversation as resolved.
Resolved
return result.skip !== undefined && UNDELIVERED_SKIPS.has(result.skip.cause);
}

/**
* How long each file took for each target in the previous run, keyed by
* How long each file took for each target in a report, keyed by
* `target::file`: every attempt of every result and serial group summed. A
* file with no attempt (skipped, or never reached) has no entry. No readable
* report is no history, never an error.
* file has an entry only when the run carried out all of it, once: a file with
* a test a filter or `--last-failed` left out, or one an interrupt or a limit
* cut short, would read as faster than it is, and a repeat past the first
* would read as slower. A file with no attempt has none either.
*/
export async function previousFileDurations(reportPath: string): Promise<ReadonlyMap<string, number>> {
export function fileDurationsOf(report: Report1Document): ReadonlyMap<string, number> {
const partial = new Set(report.run.results.filter(leftUnmeasured).map((result) => fileDurationKey(result.targetId, result.file)));
const durations = new Map<string, number>();
let report: Report1Document;
try {
report = await readLastRun(reportPath);
} catch {
return durations;
}
for (const unit of [...report.run.results, ...report.run.serialGroups]) {
if (unit.attempts.length === 0) continue;
const key = fileDurationKey(unit.targetId, unit.file);
if (unit.attempts.length === 0 || unit.repeat > 0 || partial.has(key)) continue;
const ms = unit.attempts.reduce((sum, attempt) => sum + attempt.durationMs, 0);
durations.set(key, (durations.get(key) ?? 0) + ms);
}
return durations;
}

/** The key `previousFileDurations` files one target's file under. */
/**
* How long each file took for each target in the previous run, read from its
* report (see `fileDurationsOf`). No readable report is no history, never an
* error.
*/
export async function previousFileDurations(reportPath: string): Promise<ReadonlyMap<string, number>> {
try {
return fileDurationsOf(await readLastRun(reportPath));
} catch {
return new Map();
}
}

/** The key `fileDurationsOf` files one target's file under. */
export function fileDurationKey(targetName: string, file: string): string {
return `${targetName}::${file}`;
}
3 changes: 3 additions & 0 deletions packages/e2e/src/run/output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ export interface OutputLayout {
readonly report: string;
/** The `--ai-trace` recording, `ai-trace.json`. */
readonly aiTrace: string;
/** The timings history, `timings.json`: what a CI cache restores to order the next run's files. */
readonly timings: string;
/**
* One directory per test, `results/<test>/`, holding its trace page
* (`trace.md`) and its attempts' artifacts (`attempt-<n>/`); the report's
Expand All @@ -31,6 +33,7 @@ export function outputLayout(output: string): OutputLayout {
return {
report: path.join(output, 'report.json'),
aiTrace: path.join(output, 'ai-trace.json'),
timings: path.join(output, 'timings.json'),
results: path.join(output, 'results'),
sessions: path.join(output, 'sessions'),
videos: (sessionId) => path.join(output, 'videos', sessionId),
Expand Down
37 changes: 35 additions & 2 deletions packages/e2e/src/run/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ import { outputLayout } from './output.ts';
import type { RunnerOutput } from './process-output.ts';
import { registerStaticSecrets } from './secrecy.ts';
import { nextRerunDir, pruneArtifacts } from './artifacts.ts';
import { carryForward, fileDurationKey, lastFailedIds, previousFileDurations, readLastRun, reportArtifactPaths, type RerunCollection } from './last-run.ts';
import { carryForward, fileDurationKey, lastFailedIds, readLastRun, reportArtifactPaths, type RerunCollection } from './last-run.ts';
import { loadTimings, writeTimings } from './timings.ts';
import { childProcessSpawner } from './worker/handle.ts';
import { setSecretRegistry } from '../secrets.ts';
import { budgetText, withAbort } from '../internal/time.ts';
Expand Down Expand Up @@ -170,6 +171,13 @@ export interface RunOptions {
agent?: string | readonly string[] | undefined;
/** Prints aggregated phase timings to stderr after the run. */
debug?: boolean | undefined;
/**
* The timings history file for this run (`--timings`), relative to the
* project root, over `<output>/timings.json`: read to start the longest
* files first and rewritten when the run ends. A missing or invalid file
* is no history, never an error.
*/
timings?: string | undefined;
/** Records every model call to `<output>/ai-trace.json` (`--ai-trace`). */
aiTrace?: boolean | undefined;
/**
Expand Down Expand Up @@ -643,6 +651,29 @@ export async function run(options: RunOptions = {}): Promise<RunOutcome> {
};


/** The timings file: `--timings` against the project root, else the one in the output directory. */
const timingsPath = (config: ResolvedConfig): string =>
options.timings === undefined ? outputLayout(config.output).timings : path.resolve(config.projectRoot, options.timings);

/**
* Folds the run's file durations into the timings history. Advisory like
* the history itself: a write that fails is a line on stderr, never a run
* error. Runs before the report is written, because an absent timings file
* falls back to the previous report as the history to merge into.
*/
const writeTimingsHistory = async (config: ResolvedConfig, document: Report1Document): Promise<void> => {
try {
await writeTimings(document, {
timingsPath: timingsPath(config),
reportPath: outputLayout(config.output).report,
projectRoot: config.projectRoot,
targets: new Set(config.targets.map((target) => target.name)),
});
} catch (cause) {
process.stderr.write(`e2e: the timings history could not be written: ${errorMessage(cause)}\n`);
}
};

/**
* Writes the AI trace next to the report, on the same terms: the path is
* returned only once the file exists, and a lost trace is a recorded run
Expand Down Expand Up @@ -708,6 +739,7 @@ export async function run(options: RunOptions = {}): Promise<RunOutcome> {
// Only a failed write, itself a run error, forces a rebuild that records it.
const document = buildRunReport(currentExitCode());
const recorded = runErrors.length;
if (written !== undefined) await writeTimingsHistory(written, document);
const reportPath = written === undefined ? undefined : await writeCanonicalReport(written, document);
const traces = written === undefined ? new Map<string, string>() : await writeTraces(written, document);
const exitCode = currentExitCode();
Expand Down Expand Up @@ -915,7 +947,8 @@ export async function run(options: RunOptions = {}): Promise<RunOutcome> {
const inProcess = workerConfigPath === undefined;
const runWorkers = inProcess ? 1 : config.workers;
if (runWorkers > 1) {
const previous = await previousFileDurations(outputLayout(config.output).report);
const layout = outputLayout(config.output);
const previous = await loadTimings(timingsPath(config), layout.report);
plans = longestFirst(plans, (targetName, file) => previous.get(fileDurationKey(targetName, file)));
}
const timeLimit: TimeLimit | undefined =
Expand Down
Loading
Loading