diff --git a/.changeset/timings-history.md b/.changeset/timings-history.md new file mode 100644 index 0000000000..3b0f2f8605 --- /dev/null +++ b/.changeset/timings-history.md @@ -0,0 +1,5 @@ +--- +"e2e": patch +--- + +`e2e run` keeps a small `/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 ` moves it. A missing or invalid file is no history, and the previous `report.json` is still the fallback. diff --git a/.gitignore b/.gitignore index e70fb09325..2a59d4752d 100644 --- a/.gitignore +++ b/.gitignore @@ -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/ diff --git a/AGENTS.md b/AGENTS.md index 5c46298aab..fe1963398c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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. diff --git a/docs/ci.mdx b/docs/ci.mdx index a16f86197d..e4f8520b67 100644 --- a/docs/ci.mdx +++ b/docs/ci.mdx @@ -205,6 +205,26 @@ 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, after +any file it has no time for, ordered by `/timings.json` (`.e2e/timings.json` by default): a few KB that a +run updates when it ran at least one file whole. A fresh CI checkout 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 ` reads and writes another path. + ## Sharding `--shard ` runs one slice of the suite. Every job runs the diff --git a/docs/ci/github-actions.mdx b/docs/ci/github-actions.mdx index 758875e74b..39a5639225 100644 --- a/docs/ci/github-actions.mdx +++ b/docs/ci/github-actions.mdx @@ -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 }}-${{ github.run_attempt }} + restore-keys: | + e2e-timings-${{ github.ref_name }}- + e2e-timings-main- +``` + +Each run, and each rerun, 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 diff --git a/docs/reference/cli.mdx b/docs/reference/cli.mdx index f0b63a9987..7b641c4986 100644 --- a/docs/reference/cli.mdx +++ b/docs/reference/cli.mdx @@ -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/.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 | @@ -575,6 +575,7 @@ Test files, directories, or globs relative to the project root: | `--reporter ` | 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 ` | 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 ` | 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 ` | The [timings history](/ci#cache-the-timings-history) to update when the run ends, over `/timings.json`. With more than one worker, files with no recorded time start first, then the rest longest first. Resolved from the project root. A missing or invalid file is no history, never an error. | | `--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 `/ai-trace.json`; see [Output](#output). | | `--trace [mode]` | Which tests keep a trace page (`/results//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). | diff --git a/docs/reference/config.mdx b/docs/reference/config.mdx index c59313d819..2333388824 100644 --- a/docs/reference/config.mdx +++ b/docs/reference/config.mdx @@ -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-/` 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-/` | | `sessions/` | The run's encrypted `test.setup` sessions, deleted when it ends | | `videos//` | [`e2e mcp`](/reference/mcp#recording) session recordings | diff --git a/packages/e2e/schema/fixtures/timings-v1.invalid.json b/packages/e2e/schema/fixtures/timings-v1.invalid.json new file mode 100644 index 0000000000..1f420632a8 --- /dev/null +++ b/packages/e2e/schema/fixtures/timings-v1.invalid.json @@ -0,0 +1,7 @@ +{ + "schemaVersion": "timings-1", + "files": { + "web::tests/checkout.e2e.ts": 17042, + "web::tests/login.e2e.ts": -5 + } +} diff --git a/packages/e2e/schema/fixtures/timings-v1.valid.json b/packages/e2e/schema/fixtures/timings-v1.valid.json new file mode 100644 index 0000000000..1d4e8a458a --- /dev/null +++ b/packages/e2e/schema/fixtures/timings-v1.valid.json @@ -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 + } +} diff --git a/packages/e2e/schema/timings-v1.schema.json b/packages/e2e/schema/timings-v1.schema.json new file mode 100644 index 0000000000..7e83fd70d4 --- /dev/null +++ b/packages/e2e/schema/timings-v1.schema.json @@ -0,0 +1,29 @@ +{ + "$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 `/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 `::`: a target name, then a POSIX path with no `..` segment.", + "type": "object", + "maxProperties": 100000, + "propertyNames": { + "pattern": "^(?!\\.+::)[A-Za-z0-9_.-]+::(?!/)(?![A-Za-z]:)(?!.*\\\\)(?!\\.\\.?(?:/|$))(?!.*/\\.\\.?(?:/|$))(?!.*//)[^/]+(?:/[^/]+)*$" + }, + "additionalProperties": { + "type": "integer", + "minimum": 0 + } + } + } +} diff --git a/packages/e2e/src/cli/index.ts b/packages/e2e/src/cli/index.ts index 7915e31b44..8427572060 100644 --- a/packages/e2e/src/cli/index.ts +++ b/packages/e2e/src/cli/index.ts @@ -635,6 +635,7 @@ function createProgram(version: string, telemetry: Telemetry, updateCheck: Updat .option('--reporter ', `comma-separated reporters: ${BUILTIN_REPORTERS.join(', ')}`, parseReporters) .option('--output ', 'results directory: report, artifacts, sessions (default: output in the config, else .e2e)') .option('--cache-dir ', CACHE_DIR_DESCRIPTION) + .option('--timings ', 'the timings history file a run updates when it ends, and with more than one worker starts files longest first by (default: /timings.json)') .addOption(new Option('--artifacts ').hideHelp().argParser(removedArtifactsFlag)) .option('--debug', 'print phase timings and the agent step table to stderr') .option('--ai-trace', 'record every model call to /ai-trace.json (unbox-ai)') @@ -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; @@ -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, diff --git a/packages/e2e/src/cli/init.ts b/packages/e2e/src/cli/init.ts index 6d7c034a00..dcc1db8c72 100644 --- a/packages/e2e/src/cli/init.ts +++ b/packages/e2e/src/cli/init.ts @@ -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/', diff --git a/packages/e2e/src/run/last-run.ts b/packages/e2e/src/run/last-run.ts index f31e551af2..b3f9548a91 100644 --- a/packages/e2e/src/run/last-run.ts +++ b/packages/e2e/src/run/last-run.ts @@ -275,29 +275,53 @@ function isError(value: unknown): value is ReportError { } /** - * How long each file took for each target in the previous run, keyed by + * Whether a result stands for a test its run did not carry out whole: left + * out by a filter, never reached, or with an attempt cut short, which a retry + * after a failure leaves under the earlier verdict. A test its `platforms` + * list keeps off the target is not left out: no run of that target would ever + * carry it out, so it does not make its file partial. + */ +function leftUnmeasured(result: ReportResult): boolean { + const onlyPlatformExcluded = result.skip?.cause === 'platform-unavailable'; + if ((result.selected === false && !onlyPlatformExcluded) || result.status === 'interrupted' || result.attempts.some((attempt) => attempt.status === 'interrupted')) return true; + return result.skip !== undefined && UNDELIVERED_SKIPS.has(result.skip.cause); +} + +/** + * 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> { +export function fileDurationsOf(report: Report1Document): ReadonlyMap { + const cutShort = report.run.serialGroups.filter((group) => group.attempts.some((attempt) => attempt.status === 'interrupted')); + const partial = new Set([...report.run.results.filter(leftUnmeasured), ...cutShort].map((unit) => fileDurationKey(unit.targetId, unit.file))); const durations = new Map(); - 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> { + 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}`; } diff --git a/packages/e2e/src/run/output.ts b/packages/e2e/src/run/output.ts index 6444b96781..696944e804 100644 --- a/packages/e2e/src/run/output.ts +++ b/packages/e2e/src/run/output.ts @@ -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//`, holding its trace page * (`trace.md`) and its attempts' artifacts (`attempt-/`); the report's @@ -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), diff --git a/packages/e2e/src/run/runner.ts b/packages/e2e/src/run/runner.ts index 9d64c63663..e65e971966 100644 --- a/packages/e2e/src/run/runner.ts +++ b/packages/e2e/src/run/runner.ts @@ -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'; @@ -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 `/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 `/ai-trace.json` (`--ai-trace`). */ aiTrace?: boolean | undefined; /** @@ -643,6 +651,29 @@ export async function run(options: RunOptions = {}): Promise { }; + /** 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 => { + 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 @@ -708,6 +739,7 @@ export async function run(options: RunOptions = {}): Promise { // 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() : await writeTraces(written, document); const exitCode = currentExitCode(); @@ -915,7 +947,8 @@ export async function run(options: RunOptions = {}): Promise { 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 = diff --git a/packages/e2e/src/run/timings.ts b/packages/e2e/src/run/timings.ts new file mode 100644 index 0000000000..5fa826e0cf --- /dev/null +++ b/packages/e2e/src/run/timings.ts @@ -0,0 +1,115 @@ +/** + * The timings history (`/timings.json`, schema `timings-1`): how long + * each target's file took, kept between runs so the scheduler can start the + * longest files first even on a fresh CI checkout that restored only this + * small file from its cache. Advisory by contract: a missing, stale, + * corrupt, or schema-invalid file is no history, never an error, so a + * poisoned cache can reorder work and nothing else. + */ + +import { existsSync } from 'node:fs'; +import { readFile, stat } from 'node:fs/promises'; +import path from 'node:path'; +import type { Report1Document } from '../report/build.ts'; +import { writeJsonReport } from '../report/write.ts'; +import { fileDurationsOf, previousFileDurations } from './last-run.ts'; + +/** The `schemaVersion` of a timings file. */ +const TIMINGS_SCHEMA_VERSION = 'timings-1'; + +/** Past this a file is not ours to read: a real one holds a few KB per hundred files. */ +const MAX_TIMINGS_BYTES = 8 * 1024 * 1024; + +/** The weight a run's own time carries against the history before it, so one slow run moves an entry by a third. */ +const NEW_RUN_WEIGHT = 1 / 3; + +/** The separator `fileDurationKey` puts between a target name and a file; target names never hold a `:`. */ +const KEY_SEPARATOR = '::'; + +/** + * A key as `timings-1` allows it: a target name, then a project-relative POSIX + * file with no `..` segment. The same pattern as `schema/timings-v1.schema.json`. + */ +const KEY_PATTERN = /^(?!\.+::)[A-Za-z0-9_.-]+::(?!\/)(?![A-Za-z]:)(?!.*\\)(?!\.\.?(?:\/|$))(?!.*\/\.\.?(?:\/|$))(?!.*\/\/)[^/]+(?:\/[^/]+)*$/u; + +/** Reads `timings.json`; undefined for anything but a valid `timings-1` document. */ +async function readTimingsFile(file: string): Promise | undefined> { + try { + if ((await stat(file)).size > MAX_TIMINGS_BYTES) return undefined; + const document: unknown = JSON.parse(await readFile(file, 'utf8')); + if (typeof document !== 'object' || document === null || Array.isArray(document)) return undefined; + const { schemaVersion, files, ...rest } = document as Record; + if (schemaVersion !== TIMINGS_SCHEMA_VERSION || Object.keys(rest).length > 0) return undefined; + if (typeof files !== 'object' || files === null || Array.isArray(files)) return undefined; + const durations = new Map(); + for (const [key, ms] of Object.entries(files)) { + if (!KEY_PATTERN.test(key) || typeof ms !== 'number' || !Number.isSafeInteger(ms) || ms < 0) return undefined; + durations.set(key, ms); + } + return durations; + } catch { + return undefined; + } +} + +/** + * The history a run schedules by: the timings file when it is valid, else the + * previous run's `report.json`, as before the file existed. No history is an + * empty map. + */ +export async function loadTimings(timingsPath: string, reportPath: string): Promise> { + return (await readTimingsFile(timingsPath)) ?? (await previousFileDurations(reportPath)); +} + +/** + * Folds one run's file durations into the history: an entry the run measured + * moves toward it by an exponential moving average, a new one takes it, and + * an entry for a target the config no longer has or a file no longer on disk + * is dropped. A file the run did not reach keeps its old time. + */ +function mergeTimings( + history: ReadonlyMap, + measured: ReadonlyMap, + keep: (target: string, file: string) => boolean, +): Record { + const merged = new Map(history); + for (const [key, ms] of measured) { + const before = history.get(key); + merged.set(key, before === undefined ? ms : Math.round(before + (ms - before) * NEW_RUN_WEIGHT)); + } + const files: Record = {}; + for (const key of [...merged.keys()].toSorted()) { + const at = key.indexOf(KEY_SEPARATOR); + if (at < 0 || !keep(key.slice(0, at), key.slice(at + KEY_SEPARATOR.length))) continue; + files[key] = Math.round(merged.get(key)!); + } + return files; +} + +export interface WriteTimingsOptions { + /** The timings file to read and rewrite. */ + readonly timingsPath: string; + /** The `report.json` an absent timings file falls back to. */ + readonly reportPath: string; + /** The project root the report's files are relative to. */ + readonly projectRoot: string; + /** The names of the config's targets. */ + readonly targets: ReadonlySet; +} + +/** + * Rewrites the timings file from a finished run's report. A run that timed no + * file leaves the file as it was. The caller treats a failure as a line on + * stderr: the history is advisory and never changes a run's outcome. + */ +export async function writeTimings(document: Report1Document, options: WriteTimingsOptions): Promise { + const measured = fileDurationsOf(document); + if (measured.size === 0) return; + const history = await loadTimings(options.timingsPath, options.reportPath); + const files = mergeTimings( + history, + measured, + (target, file) => options.targets.has(target) && existsSync(path.resolve(options.projectRoot, file)), + ); + await writeJsonReport(options.timingsPath, { schemaVersion: TIMINGS_SCHEMA_VERSION, files }); +} diff --git a/packages/e2e/tests/integration/timings.test.ts b/packages/e2e/tests/integration/timings.test.ts new file mode 100644 index 0000000000..d00040064a --- /dev/null +++ b/packages/e2e/tests/integration/timings.test.ts @@ -0,0 +1,83 @@ +/** + * The timings history (`/timings.json`): a run that executes its tests + * writes it, `--timings` moves it, a seeded file is read and smoothed into the + * next one, a file a run only ran part of keeps its entry, and a run that stops + * before its tests writes nothing. + */ + +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { createProject, runExistingWithConfigFile, workerFakeConfigSource } from '../helpers/run-project.ts'; + +const TWO_TESTS = `import { test } from 'e2e'; + +test('first', async ({ app }) => { + await app.open(); +}); + +test('second', async ({ app }) => { + await app.open(); +}); +`; + +const files = { 'tests/a.e2e.ts': TWO_TESTS, 'tests/b.e2e.ts': TWO_TESTS }; +const A = 'fake::tests/a.e2e.ts'; +const B = 'fake::tests/b.e2e.ts'; + +function project() { + return createProject({ ...files, 'e2e.config.ts': workerFakeConfigSource(2) }); +} + +function seed(file: string, timings: Record): void { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify({ schemaVersion: 'timings-1', files: timings })); +} + +function read(file: string): { schemaVersion: string; files: Record } { + return JSON.parse(readFileSync(file, 'utf8')) as { schemaVersion: string; files: Record }; +} + +describe('timings history', () => { + it('writes how long each file took to /timings.json', async () => { + const dir = project(); + const outcome = await runExistingWithConfigFile(dir, {}); + expect(outcome.exitCode).toBe(0); + const history = read(path.join(dir.dir, '.e2e', 'timings.json')); + expect(history.schemaVersion).toBe('timings-1'); + expect(Object.keys(history.files).toSorted()).toEqual([A, B]); + dir.cleanup(); + }, 120_000); + + it('reads a seeded file and smooths the run into it, at the path --timings names', async () => { + const dir = project(); + const custom = path.join(dir.dir, 'ci', 'timings.json'); + seed(custom, { [A]: 60_000, 'gone::tests/a.e2e.ts': 5, 'fake::tests/deleted.e2e.ts': 5 }); + await runExistingWithConfigFile(dir, { runOptions: { timings: 'ci/timings.json' } }); + const history = read(custom); + // A third of the way from 60 s toward the few hundred ms the run took. + expect(history.files[A]).toBeGreaterThan(30_000); + expect(history.files[A]).toBeLessThan(45_000); + expect(Object.keys(history.files).toSorted()).toEqual([A, B]); + expect(existsSync(path.join(dir.dir, '.e2e', 'timings.json'))).toBe(false); + dir.cleanup(); + }, 120_000); + + it('keeps the entry of a file the run only ran part of', async () => { + const dir = project(); + const file = path.join(dir.dir, '.e2e', 'timings.json'); + seed(file, { [A]: 60_000, [B]: 60_000 }); + const outcome = await runExistingWithConfigFile(dir, { runOptions: { grep: [/first/] } }); + expect(outcome.report.run.summary).toMatchObject({ selected: 2, executed: 2, discovered: 4 }); + expect(read(file).files).toEqual({ [A]: 60_000, [B]: 60_000 }); + dir.cleanup(); + }, 120_000); + + it('writes nothing for a run that stops before its tests', async () => { + const dir = project(); + const outcome = await runExistingWithConfigFile(dir, { runOptions: { grep: [/matches nothing/] } }); + expect(outcome.exitCode).not.toBe(0); + expect(existsSync(path.join(dir.dir, '.e2e'))).toBe(false); + dir.cleanup(); + }, 120_000); +}); diff --git a/packages/e2e/tests/unit/cli-init.test.ts b/packages/e2e/tests/unit/cli-init.test.ts index 3022ecd914..ccdae802e3 100644 --- a/packages/e2e/tests/unit/cli-init.test.ts +++ b/packages/e2e/tests/unit/cli-init.test.ts @@ -725,7 +725,7 @@ describe('e2e init', () => { await init(dir, { yes: true }); expect(read('e2e.config.ts')).toBe('// custom config\n'); expect(read('tests/example.e2e.ts')).toBe('// custom test\n'); - expect(read('.gitignore')).toBe(`${older}.e2e/results/\n.e2e/ai-trace.json\n.e2e/junit.xml\n.e2e/summary.md\n.e2e/logs/\n.e2e/videos/\n`); + expect(read('.gitignore')).toBe(`${older}.e2e/results/\n.e2e/ai-trace.json\n.e2e/timings.json\n.e2e/junit.xml\n.e2e/summary.md\n.e2e/logs/\n.e2e/videos/\n`); expect(output()).not.toContain('commit-the-replay-cache'); }); diff --git a/packages/e2e/tests/unit/cli.test.ts b/packages/e2e/tests/unit/cli.test.ts index 7d288d6e65..1e25a211f3 100644 --- a/packages/e2e/tests/unit/cli.test.ts +++ b/packages/e2e/tests/unit/cli.test.ts @@ -847,6 +847,7 @@ describe('e2e --version and --help', () => { '--reporter', '--output', '--cache-dir', + '--timings', '--debug', '--ai-trace', '--trace', diff --git a/packages/e2e/tests/unit/last-run.test.ts b/packages/e2e/tests/unit/last-run.test.ts index c6af64fc73..190832d16d 100644 --- a/packages/e2e/tests/unit/last-run.test.ts +++ b/packages/e2e/tests/unit/last-run.test.ts @@ -343,6 +343,50 @@ describe('previousFileDurations', () => { expect(durations.has(fileDurationKey('web', 'tests/skipped.e2e.ts'))).toBe(false); }); + it('leaves a file untimed when the run did not carry out all of it, and counts only the first of its repeats', async () => { + const attempts = [{ durationMs: 100, artifacts: [] }]; + const durations = await previousFileDurations( + reportFile( + report([ + { id: 'whole', status: 'passed', file: 'tests/whole.e2e.ts', attempts }, + { id: 'failed', status: 'failed', file: 'tests/whole.e2e.ts', attempts }, + { id: 'ran', status: 'passed', file: 'tests/filtered.e2e.ts', attempts }, + leftOut('filtered', 'title does not match --grep'), + { id: 'cut', status: 'passed', file: 'tests/cut.e2e.ts', attempts }, + { id: 'never', status: 'skipped', file: 'tests/cut.e2e.ts', skip: { cause: 'failure-limit', reason: 'stopped' } }, + { id: 'stopped', status: 'interrupted', file: 'tests/interrupted.e2e.ts', attempts }, + { + id: 'retry-cut', + status: 'failed', + file: 'tests/retry-cut.e2e.ts', + attempts: [{ status: 'failed', durationMs: 100, artifacts: [] }, { status: 'interrupted', durationMs: 5, artifacts: [] }], + }, + { id: 'again-0', status: 'passed', file: 'tests/repeated.e2e.ts', repeat: 0, attempts }, + { id: 'again-1', status: 'passed', file: 'tests/repeated.e2e.ts', repeat: 1, attempts }, + ].map((row) => (row['id'] === 'filtered' ? { ...row, file: 'tests/filtered.e2e.ts' } : row))), + ), + ); + expect([...durations]).toEqual([ + [fileDurationKey('web', 'tests/whole.e2e.ts'), 200], + [fileDurationKey('web', 'tests/repeated.e2e.ts'), 100], + ]); + }); + + it('times a file whose other tests a platforms list keeps off the target, but not one a filter left out', async () => { + const attempts = [{ durationMs: 100, artifacts: [] }]; + const durations = await previousFileDurations( + reportFile( + report([ + { id: 'common', status: 'passed', file: 'tests/platforms.e2e.ts', attempts }, + { id: 'ios-only', status: 'skipped', selected: false, file: 'tests/platforms.e2e.ts', skip: { cause: 'platform-unavailable', reason: 'test declares platforms [ios]' } }, + { id: 'grep-ran', status: 'passed', file: 'tests/grep.e2e.ts', attempts }, + { id: 'grep-out', status: 'skipped', selected: false, file: 'tests/grep.e2e.ts', skip: { cause: 'filtered', reason: 'title does not match --grep' } }, + ]), + ), + ); + expect([...durations]).toEqual([[fileDurationKey('web', 'tests/platforms.e2e.ts'), 100]]); + }); + it('is no history, not an error, without a readable report', async () => { const dir = mkdtempSync(path.join(os.tmpdir(), 'e2e-last-run-')); tempRoots.push(dir); diff --git a/packages/e2e/tests/unit/timings.test.ts b/packages/e2e/tests/unit/timings.test.ts new file mode 100644 index 0000000000..67f263cb4b --- /dev/null +++ b/packages/e2e/tests/unit/timings.test.ts @@ -0,0 +1,159 @@ +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { Ajv2020 } from 'ajv/dist/2020.js'; +import { afterEach, describe, expect, it } from 'vitest'; +import type { Report1Document } from '../../src/report/build.ts'; +import { loadTimings, writeTimings } from '../../src/run/timings.ts'; + +const tempRoots: string[] = []; + +afterEach(() => { + for (const root of tempRoots.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +/** A project directory holding the given files, with `.e2e/` for the history beside them. */ +function project(files: readonly string[]): { root: string; timings: string; report: string } { + const root = mkdtempSync(path.join(os.tmpdir(), 'e2e-timings-')); + tempRoots.push(root); + mkdirSync(path.join(root, '.e2e')); + for (const file of files) { + mkdirSync(path.dirname(path.join(root, file)), { recursive: true }); + writeFileSync(path.join(root, file), ''); + } + return { root, timings: path.join(root, '.e2e', 'timings.json'), report: path.join(root, '.e2e', 'report.json') }; +} + +/** A report whose result per `[target, file, ms]` row has one attempt of that length. */ +function reportOf(rows: readonly (readonly [string, string, number])[]): Report1Document { + return { + schemaVersion: 'report-1', + run: { + results: rows.map(([targetId, file, ms], index) => ({ id: `r${index}`, status: 'passed', titlePath: ['t'], targetId, file, attempts: [{ durationMs: ms, artifacts: [] }] })), + serialGroups: [], + errors: [], + }, + } as unknown as Report1Document; +} + +function history(file: string): unknown { + return JSON.parse(readFileSync(file, 'utf8')); +} + +describe('loadTimings', () => { + it('reads a valid timings file', async () => { + const { timings, report } = project([]); + writeFileSync(timings, JSON.stringify({ schemaVersion: 'timings-1', files: { 'web::a.e2e.ts': 90 } })); + expect([...(await loadTimings(timings, report))]).toEqual([['web::a.e2e.ts', 90]]); + }); + + it.each([ + ['not JSON', 'not json'], + ['another schema version', JSON.stringify({ schemaVersion: 'timings-2', files: { 'web::a.e2e.ts': 90 } })], + ['no files', JSON.stringify({ schemaVersion: 'timings-1' })], + ['an array', '[]'], + ['an extra field', JSON.stringify({ schemaVersion: 'timings-1', files: {}, extra: 1 })], + ['a key with no target', JSON.stringify({ schemaVersion: 'timings-1', files: { 'a.e2e.ts': 90 } })], + ['a negative time', JSON.stringify({ schemaVersion: 'timings-1', files: { 'web::a.e2e.ts': -1 } })], + ['a time that is not an integer', JSON.stringify({ schemaVersion: 'timings-1', files: { 'web::a.e2e.ts': 1.5 } })], + ['a time that is a string', JSON.stringify({ schemaVersion: 'timings-1', files: { 'web::a.e2e.ts': '90' } })], + ])('is no history for %s', async (_name, content) => { + const { timings, report } = project([]); + writeFileSync(timings, content); + expect((await loadTimings(timings, report)).size).toBe(0); + }); + + it.each([ + ['web::tests/a.e2e.ts', true], + ['mobile-ios.1::a/b/c.e2e.ts', true], + ['web::a.e2e.ts::b', true], + ['web::../outside.e2e.ts', false], + ['web::tests/../../outside', false], + ['web::..', false], + ['web::tests/..', false], + ['web::/abs/a.e2e.ts', false], + ['web::C:/a.e2e.ts', false], + ['web::tests\\a.e2e.ts', false], + ['web::tests//a.e2e.ts', false], + ['..::a.e2e.ts', false], + ['.::a.e2e.ts', false], + ['::a.e2e.ts', false], + ['web::', false], + ['a.e2e.ts', false], + ])('reads the key %j as the schema does (%s)', async (key, accepted) => { + const { timings, report } = project([]); + writeFileSync(timings, JSON.stringify({ schemaVersion: 'timings-1', files: { [key]: 90 } })); + expect((await loadTimings(timings, report)).size).toBe(accepted ? 1 : 0); + const schema = JSON.parse(readFileSync(path.join(import.meta.dirname, '..', '..', 'schema', 'timings-v1.schema.json'), 'utf8')) as Record; + const validate = new Ajv2020({ strict: false }).compile(schema); + expect(validate({ schemaVersion: 'timings-1', files: { [key]: 90 } })).toBe(accepted); + }); + + it('is no history when nothing is there', async () => { + const { timings, report } = project([]); + expect((await loadTimings(timings, report)).size).toBe(0); + }); + + it('falls back to the previous report when the timings file is absent or invalid', async () => { + const { timings, report } = project([]); + writeFileSync(report, JSON.stringify(reportOf([['web', 'a.e2e.ts', 120]]))); + expect([...(await loadTimings(timings, report))]).toEqual([['web::a.e2e.ts', 120]]); + writeFileSync(timings, 'garbage'); + expect([...(await loadTimings(timings, report))]).toEqual([['web::a.e2e.ts', 120]]); + }); +}); + +describe('writeTimings', () => { + it('writes a first run as measured, sorted by key', async () => { + const { root, timings, report } = project(['b.e2e.ts', 'a.e2e.ts']); + await writeTimings(reportOf([['web', 'b.e2e.ts', 200], ['web', 'a.e2e.ts', 100]]), { timingsPath: timings, reportPath: report, projectRoot: root, targets: new Set(['web']) }); + expect(history(timings)).toEqual({ schemaVersion: 'timings-1', files: { 'web::a.e2e.ts': 100, 'web::b.e2e.ts': 200 } }); + expect(Object.keys((history(timings) as { files: object }).files)).toEqual(['web::a.e2e.ts', 'web::b.e2e.ts']); + }); + + it('writes a document the timings-1 schema accepts', async () => { + const { root, timings, report } = project(['a.e2e.ts']); + await writeTimings(reportOf([['web', 'a.e2e.ts', 100]]), { timingsPath: timings, reportPath: report, projectRoot: root, targets: new Set(['web']) }); + const schema = JSON.parse(readFileSync(path.join(import.meta.dirname, '..', '..', 'schema', 'timings-v1.schema.json'), 'utf8')) as Record; + const validate = new Ajv2020({ strict: false }).compile(schema); + expect(validate(history(timings)), JSON.stringify(validate.errors)).toBe(true); + }); + + it('smooths a measured file toward the new run and keeps one the run did not reach', async () => { + const { root, timings, report } = project(['a.e2e.ts', 'b.e2e.ts']); + writeFileSync(timings, JSON.stringify({ schemaVersion: 'timings-1', files: { 'web::a.e2e.ts': 300, 'web::b.e2e.ts': 50 } })); + await writeTimings(reportOf([['web', 'a.e2e.ts', 900]]), { timingsPath: timings, reportPath: report, projectRoot: root, targets: new Set(['web']) }); + expect(history(timings)).toEqual({ schemaVersion: 'timings-1', files: { 'web::a.e2e.ts': 500, 'web::b.e2e.ts': 50 } }); + }); + + it('drops a file that is gone and a target the config no longer has', async () => { + const { root, timings, report } = project(['a.e2e.ts']); + writeFileSync( + timings, + JSON.stringify({ schemaVersion: 'timings-1', files: { 'web::a.e2e.ts': 10, 'web::deleted.e2e.ts': 10, 'old-target::a.e2e.ts': 10 } }), + ); + await writeTimings(reportOf([['web', 'a.e2e.ts', 10]]), { timingsPath: timings, reportPath: report, projectRoot: root, targets: new Set(['web']) }); + expect(history(timings)).toEqual({ schemaVersion: 'timings-1', files: { 'web::a.e2e.ts': 10 } }); + }); + + it('seeds from the previous report when the file is absent', async () => { + const { root, timings, report } = project(['a.e2e.ts']); + writeFileSync(report, JSON.stringify(reportOf([['web', 'a.e2e.ts', 300]]))); + await writeTimings(reportOf([['web', 'a.e2e.ts', 900]]), { timingsPath: timings, reportPath: report, projectRoot: root, targets: new Set(['web']) }); + expect(history(timings)).toEqual({ schemaVersion: 'timings-1', files: { 'web::a.e2e.ts': 500 } }); + }); + + it('leaves the file as it was when the run timed nothing', async () => { + const { root, timings, report } = project(['a.e2e.ts']); + const seeded = JSON.stringify({ schemaVersion: 'timings-1', files: { 'web::a.e2e.ts': 70, 'web::deleted.e2e.ts': 9 } }); + writeFileSync(timings, seeded); + await writeTimings(reportOf([]), { timingsPath: timings, reportPath: report, projectRoot: root, targets: new Set(['web']) }); + expect(readFileSync(timings, 'utf8')).toBe(seeded); + }); + + it('writes no file when there is no history and the run timed nothing', async () => { + const { root, timings, report } = project(['a.e2e.ts']); + await writeTimings(reportOf([]), { timingsPath: timings, reportPath: report, projectRoot: root, targets: new Set(['web']) }); + expect(existsSync(timings)).toBe(false); + }); +}); diff --git a/plugins/e2e/skills/e2e/references/running.md b/plugins/e2e/skills/e2e/references/running.md index 0f7094675d..e42a77bd21 100644 --- a/plugins/e2e/skills/e2e/references/running.md +++ b/plugins/e2e/skills/e2e/references/running.md @@ -60,6 +60,7 @@ npx e2e telemetry [disable|enable] # anonymous usage telemetry: status or switch | `--pass-with-no-tests` | Exit 0, not `NO_TESTS`, when nothing matches; a run with nothing to run starts no engine or app. | | `--debug` | Phase timings and an agent step table on stderr; transcripts as artifacts. | | `--ai-trace` | Every model call except a test filter's, to `/ai-trace.json`. | +| `--timings ` | The timings history to update, over `/timings.json`. With more than one worker, files with no recorded time start first, then the rest longest first. | | `--trace [mode]`, `--video [mode]` | Which tests keep a trace page (`/results//trace.md`), or which attempts record a video (WebM on browsers, MP4 on devices), over the config and every target: bare is `on` (`--trace` then pages every test, passing ones too); `--trace off` writes none; `retain-on-failure` keeps only failures; `on-first-retry` keeps first retries, `on-all-retries` every retry. A test's own `trace` or `video` still wins; targets whose engine cannot record video are skipped with a notice. Both are greedy: write `--video=` or put test files first. The failure recap names the trace page and the video. | ```bash @@ -133,7 +134,7 @@ its own tools. ## Output `` (`.e2e` by default) holds `report.json`, `junit.xml`, -`summary.md`, `ai-trace.json`, `sessions/`, and `results/`, one directory +`summary.md`, `ai-trace.json`, `timings.json` (how long each file took; with more than one worker the next run starts the longest known files first, after any with no time), `sessions/`, and `results/`, one directory per test with its `trace.md` and an `attempt-/` per attempt (screenshots, videos, `--debug` transcripts, downloads). `results/` is cleared once a run's tests start; a run stopping before diff --git a/skills/e2e/references/running.md b/skills/e2e/references/running.md index 0f7094675d..e42a77bd21 100644 --- a/skills/e2e/references/running.md +++ b/skills/e2e/references/running.md @@ -60,6 +60,7 @@ npx e2e telemetry [disable|enable] # anonymous usage telemetry: status or switch | `--pass-with-no-tests` | Exit 0, not `NO_TESTS`, when nothing matches; a run with nothing to run starts no engine or app. | | `--debug` | Phase timings and an agent step table on stderr; transcripts as artifacts. | | `--ai-trace` | Every model call except a test filter's, to `/ai-trace.json`. | +| `--timings ` | The timings history to update, over `/timings.json`. With more than one worker, files with no recorded time start first, then the rest longest first. | | `--trace [mode]`, `--video [mode]` | Which tests keep a trace page (`/results//trace.md`), or which attempts record a video (WebM on browsers, MP4 on devices), over the config and every target: bare is `on` (`--trace` then pages every test, passing ones too); `--trace off` writes none; `retain-on-failure` keeps only failures; `on-first-retry` keeps first retries, `on-all-retries` every retry. A test's own `trace` or `video` still wins; targets whose engine cannot record video are skipped with a notice. Both are greedy: write `--video=` or put test files first. The failure recap names the trace page and the video. | ```bash @@ -133,7 +134,7 @@ its own tools. ## Output `` (`.e2e` by default) holds `report.json`, `junit.xml`, -`summary.md`, `ai-trace.json`, `sessions/`, and `results/`, one directory +`summary.md`, `ai-trace.json`, `timings.json` (how long each file took; with more than one worker the next run starts the longest known files first, after any with no time), `sessions/`, and `results/`, one directory per test with its `trace.md` and an `attempt-/` per attempt (screenshots, videos, `--debug` transcripts, downloads). `results/` is cleared once a run's tests start; a run stopping before