From de04880107d1744754edf9864da51cb078b9a451 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Mon, 9 Nov 2026 13:54:22 +0900 Subject: [PATCH 1/5] feat(run): keep a timings history that CI can cache `e2e run` already starts the longest files first, but it read the previous run's durations out of report.json, which a fresh CI checkout never has. Write a small versioned `/timings.json` (timings-1) at the end of every run instead: per target::file milliseconds, smoothed with an exponential moving average, with files that are gone and targets the config dropped pruned. The file is advisory. A missing, corrupt, or schema-invalid file is no history, and an absent one falls back to report.json as before, so a restored cache can reorder files and never change a result. `--timings ` moves it. `--last-failed` still reads report.json. Documents the actions/cache recipe for GitHub Actions and the generic restore/save rule in the CI guide. Duration-balanced --shard is left for a separate decision. Refs ENG-1111 Co-Authored-By: Claude Sonnet 5.5 --- .changeset/timings-history.md | 5 + .gitignore | 1 + AGENTS.md | 2 +- docs/ci.mdx | 28 ++++ docs/ci/github-actions.mdx | 26 ++++ docs/reference/cli.mdx | 3 +- docs/reference/config.mdx | 1 + .../schema/fixtures/timings-v1.invalid.json | 7 + .../e2e/schema/fixtures/timings-v1.valid.json | 8 ++ packages/e2e/schema/timings-v1.schema.json | 19 +++ packages/e2e/src/cli/index.ts | 3 + packages/e2e/src/cli/init.ts | 1 + packages/e2e/src/run/last-run.ts | 28 ++-- packages/e2e/src/run/output.ts | 3 + packages/e2e/src/run/runner.ts | 37 +++++- packages/e2e/src/run/timings.ts | 109 +++++++++++++++ packages/e2e/tests/unit/cli-init.test.ts | 2 +- packages/e2e/tests/unit/cli.test.ts | 1 + packages/e2e/tests/unit/timings.test.ts | 125 ++++++++++++++++++ plugins/e2e/skills/e2e/references/running.md | 3 +- skills/e2e/references/running.md | 3 +- 21 files changed, 397 insertions(+), 18 deletions(-) create mode 100644 .changeset/timings-history.md create mode 100644 packages/e2e/schema/fixtures/timings-v1.invalid.json create mode 100644 packages/e2e/schema/fixtures/timings-v1.valid.json create mode 100644 packages/e2e/schema/timings-v1.schema.json create mode 100644 packages/e2e/src/run/timings.ts create mode 100644 packages/e2e/tests/unit/timings.test.ts 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..a8a740cf0c 100644 --- a/docs/ci.mdx +++ b/docs/ci.mdx @@ -205,6 +205,34 @@ 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, so the +last file does not run alone at the end. It orders them by +`.e2e/timings.json`, which every run updates with how long each file took. +A fresh CI checkout has no such file, so restore it from your CI cache and +save it after the run. Nothing else in `.e2e/` is needed. + +- The file is a few KB, `{ "schemaVersion": "timings-1", "files": { "::": } }`. + Each run moves a file's time a third of the way toward what it just took, so + one slow run does not reorder everything. Files that are gone and targets + the config no longer has are dropped. +- It is advisory. A missing, stale, corrupt, or invalid file is no history, and + a run without one falls back to the previous `report.json`. A restored + file can change the order of files, never a result. +- `--last-failed` does not read it. It reads `report.json`. +- CI defaults to one worker, so set [`workers`](/reference/config#workers) or + pass `--workers` to benefit. +- `--timings ` reads and writes another path. +- Key the cache by branch with the default branch as the fallback, so a new + pull request starts from the history of `main`. With [sharding](#sharding), + add the shard index to the key; each shard then restores and saves its own + history. + +[GitHub Actions](/ci/github-actions#cache-the-timings-history) has the +workflow step. Any other cache works the same way: restore `.e2e/timings.json` +before `e2e run`, save it after. + ## 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..ff014089d4 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 }} + 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 cannot write to the base branch's cache, but it can read 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 web workflow above runs one worker, the CI default. The history only +helps with [`workers`](/reference/config#workers) of 2 or more. + ## 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..71440bf3ff 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 order files by and update when the run ends, over `/timings.json`. 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..320bbfd745 --- /dev/null +++ b/packages/e2e/schema/fixtures/timings-v1.invalid.json @@ -0,0 +1,7 @@ +{ + "schemaVersion": "timings-1", + "files": { + "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..6539511dd3 --- /dev/null +++ b/packages/e2e/schema/timings-v1.schema.json @@ -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 `/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 `::`.", + "type": "object", + "maxProperties": 100000, + "propertyNames": { "pattern": "^[A-Za-z0-9_.-]+::.+$" }, + "additionalProperties": { "type": "integer", "minimum": 0 } + } + } +} diff --git a/packages/e2e/src/cli/index.ts b/packages/e2e/src/cli/index.ts index 7915e31b44..de7161455b 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 orders its files by and updates when it ends (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..8ab53bcc89 100644 --- a/packages/e2e/src/run/last-run.ts +++ b/packages/e2e/src/run/last-run.ts @@ -275,19 +275,12 @@ function isError(value: unknown): value is ReportError { } /** - * 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 with no attempt (skipped, or never reached) has no entry. */ -export async function previousFileDurations(reportPath: string): Promise> { +export function fileDurationsOf(report: Report1Document): ReadonlyMap { 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); @@ -297,7 +290,20 @@ 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..53d31b6829 --- /dev/null +++ b/packages/e2e/src/run/timings.ts @@ -0,0 +1,109 @@ +/** + * 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 = '::'; + +/** 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.includes(KEY_SEPARATOR) || 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/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/timings.test.ts b/packages/e2e/tests/unit/timings.test.ts new file mode 100644 index 0000000000..d304ec3adb --- /dev/null +++ b/packages/e2e/tests/unit/timings.test.ts @@ -0,0 +1,125 @@ +import { 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('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']); + await writeTimings(reportOf([]), { timingsPath: timings, reportPath: report, projectRoot: root, targets: new Set(['web']) }); + expect(() => readFileSync(timings)).toThrow(); + }); +}); diff --git a/plugins/e2e/skills/e2e/references/running.md b/plugins/e2e/skills/e2e/references/running.md index 0f7094675d..9c0754f12c 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 order files by and update, over `/timings.json`. | | `--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, to start the longest first on the next run), `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..9c0754f12c 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 order files by and update, over `/timings.json`. | | `--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, to start the longest first on the next run), `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 From b3c6d55c1b26f4267d7d1c90f24ac85ceb0f532f Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Mon, 9 Nov 2026 14:13:40 +0900 Subject: [PATCH 2/5] fix(run): time a file only when the run carried out all of it A `--grep`, `--last-failed`, interrupted, or `--repeat-each` run summed only part of a file's tests, or several repeats of them, into the timings history, so a 60 s file could drop to about 40 s after a rerun of one failing test. A file now has a timing only when none of its tests was left out, cut short, or never reached, and repeats past the first do not count. Adds the integration test for the runner wiring. Refs ENG-1111 Co-Authored-By: Claude Sonnet 5.5 --- docs/ci.mdx | 37 ++++----- docs/ci/github-actions.mdx | 16 ++-- packages/e2e/src/run/last-run.ts | 14 +++- .../e2e/tests/integration/timings.test.ts | 83 +++++++++++++++++++ packages/e2e/tests/unit/last-run.test.ts | 23 +++++ 5 files changed, 140 insertions(+), 33 deletions(-) create mode 100644 packages/e2e/tests/integration/timings.test.ts diff --git a/docs/ci.mdx b/docs/ci.mdx index a8a740cf0c..4315b5a3f6 100644 --- a/docs/ci.mdx +++ b/docs/ci.mdx @@ -207,31 +207,22 @@ on `main`, the whole suite runs. See ## Cache the timings history -With more than one worker, `e2e run` starts the longest files first, so the -last file does not run alone at the end. It orders them by -`.e2e/timings.json`, which every run updates with how long each file took. -A fresh CI checkout has no such file, so restore it from your CI cache and -save it after the run. Nothing else in `.e2e/` is needed. - -- The file is a few KB, `{ "schemaVersion": "timings-1", "files": { "::": } }`. - Each run moves a file's time a third of the way toward what it just took, so - one slow run does not reorder everything. Files that are gone and targets - the config no longer has are dropped. -- It is advisory. A missing, stale, corrupt, or invalid file is no history, and - a run without one falls back to the previous `report.json`. A restored - file can change the order of files, never a result. -- `--last-failed` does not read it. It reads `report.json`. -- CI defaults to one worker, so set [`workers`](/reference/config#workers) or +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 +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. -- Key the cache by branch with the default branch as the fallback, so a new - pull request starts from the history of `main`. With [sharding](#sharding), - add the shard index to the key; each shard then restores and saves its own - history. - -[GitHub Actions](/ci/github-actions#cache-the-timings-history) has the -workflow step. Any other cache works the same way: restore `.e2e/timings.json` -before `e2e run`, save it after. ## Sharding diff --git a/docs/ci/github-actions.mdx b/docs/ci/github-actions.mdx index ff014089d4..8c7bab5563 100644 --- a/docs/ci/github-actions.mdx +++ b/docs/ci/github-actions.mdx @@ -115,15 +115,15 @@ step before the run: e2e-timings-main- ``` -Each run saves a new entry and restores the newest one for its branch. A -pull request cannot write to the base branch's cache, but it can read 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() }}`. +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 web workflow above runs one worker, the CI default. The history only -helps with [`workers`](/reference/config#workers) of 2 or more. +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 diff --git a/packages/e2e/src/run/last-run.ts b/packages/e2e/src/run/last-run.ts index 8ab53bcc89..f42eb6b815 100644 --- a/packages/e2e/src/run/last-run.ts +++ b/packages/e2e/src/run/last-run.ts @@ -274,16 +274,26 @@ 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; + 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. + * 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 function fileDurationsOf(report: Report1Document): ReadonlyMap { + const partial = new Set(report.run.results.filter(leftUnmeasured).map((result) => fileDurationKey(result.targetId, result.file))); const durations = new Map(); 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); } 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/last-run.test.ts b/packages/e2e/tests/unit/last-run.test.ts index c6af64fc73..87a6fa8758 100644 --- a/packages/e2e/tests/unit/last-run.test.ts +++ b/packages/e2e/tests/unit/last-run.test.ts @@ -343,6 +343,29 @@ 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, or ran it more than once', 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: '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('is no history, not an error, without a readable report', async () => { const dir = mkdtempSync(path.join(os.tmpdir(), 'e2e-last-run-')); tempRoots.push(dir); From 2e3f70f6ad8d3872fb3cff436a7d3f7fa95cb519 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Mon, 9 Nov 2026 14:21:20 +0900 Subject: [PATCH 3/5] fix(run): tighten the timings keys, count an interrupted retry as partial, and say when ordering applies - A retry cut short after a failure leaves the result under the earlier verdict; read the attempts, and a serial group's, for an interrupt. - timings-1 keys: a target name, then a project-relative POSIX file with no `..` segment, in the schema and the reader alike. - Rerun cache key adds github.run_attempt, since a rerun shares run_id and actions/cache never saves over an existing key. - Docs and help say the history orders files only with more than one worker, and that the file is `/timings.json`. Refs ENG-1111 Co-Authored-By: Claude Sonnet 5.5 --- docs/ci.mdx | 5 ++- docs/ci/github-actions.mdx | 4 +- docs/reference/cli.mdx | 2 +- .../schema/fixtures/timings-v1.invalid.json | 2 +- packages/e2e/schema/timings-v1.schema.json | 20 +++++++--- packages/e2e/src/cli/index.ts | 2 +- packages/e2e/src/run/last-run.ts | 11 ++++-- packages/e2e/src/run/timings.ts | 8 +++- packages/e2e/tests/unit/last-run.test.ts | 8 +++- packages/e2e/tests/unit/timings.test.ts | 38 ++++++++++++++++++- plugins/e2e/skills/e2e/references/running.md | 4 +- skills/e2e/references/running.md | 4 +- 12 files changed, 85 insertions(+), 23 deletions(-) diff --git a/docs/ci.mdx b/docs/ci.mdx index 4315b5a3f6..6bb42200e0 100644 --- a/docs/ci.mdx +++ b/docs/ci.mdx @@ -208,8 +208,9 @@ on `main`, the whole suite runs. See ## 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 -has none, so restore it from your CI cache before the run and save it after. +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, diff --git a/docs/ci/github-actions.mdx b/docs/ci/github-actions.mdx index 8c7bab5563..39a5639225 100644 --- a/docs/ci/github-actions.mdx +++ b/docs/ci/github-actions.mdx @@ -109,13 +109,13 @@ step before the run: - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: .e2e/timings.json - key: e2e-timings-${{ github.ref_name }}-${{ github.run_id }} + key: e2e-timings-${{ github.ref_name }}-${{ github.run_id }}-${{ github.run_attempt }} 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 +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`. diff --git a/docs/reference/cli.mdx b/docs/reference/cli.mdx index 71440bf3ff..fb982bdcb3 100644 --- a/docs/reference/cli.mdx +++ b/docs/reference/cli.mdx @@ -575,7 +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 order files by and update when the run ends, over `/timings.json`. Resolved from the project root. A missing or invalid file is no history, never an error. | +| `--timings ` | The [timings history](/ci#cache-the-timings-history) to update when the run ends, over `/timings.json`. With more than one worker, files start longest first by it. 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/packages/e2e/schema/fixtures/timings-v1.invalid.json b/packages/e2e/schema/fixtures/timings-v1.invalid.json index 320bbfd745..1f420632a8 100644 --- a/packages/e2e/schema/fixtures/timings-v1.invalid.json +++ b/packages/e2e/schema/fixtures/timings-v1.invalid.json @@ -1,7 +1,7 @@ { "schemaVersion": "timings-1", "files": { - "tests/checkout.e2e.ts": 17042, + "web::tests/checkout.e2e.ts": 17042, "web::tests/login.e2e.ts": -5 } } diff --git a/packages/e2e/schema/timings-v1.schema.json b/packages/e2e/schema/timings-v1.schema.json index 6539511dd3..7e83fd70d4 100644 --- a/packages/e2e/schema/timings-v1.schema.json +++ b/packages/e2e/schema/timings-v1.schema.json @@ -5,15 +5,25 @@ "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"], + "required": [ + "schemaVersion", + "files" + ], "properties": { - "schemaVersion": { "const": "timings-1" }, + "schemaVersion": { + "const": "timings-1" + }, "files": { - "description": "Milliseconds a target's file took, smoothed over recent runs, keyed `::`.", + "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_.-]+::.+$" }, - "additionalProperties": { "type": "integer", "minimum": 0 } + "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 de7161455b..5d09c72856 100644 --- a/packages/e2e/src/cli/index.ts +++ b/packages/e2e/src/cli/index.ts @@ -635,7 +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 orders its files by and updates when it ends (default: /timings.json)') + .option('--timings ', 'the timings history file a run updates when it ends, and with more than one worker starts the longest files 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)') diff --git a/packages/e2e/src/run/last-run.ts b/packages/e2e/src/run/last-run.ts index f42eb6b815..0d71176a1d 100644 --- a/packages/e2e/src/run/last-run.ts +++ b/packages/e2e/src/run/last-run.ts @@ -274,9 +274,13 @@ 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. */ +/** + * Whether a result stands for a test its run did not carry out whole: left + * out, never reached, or with an attempt cut short, which a retry after a + * failure leaves under the earlier verdict. + */ function leftUnmeasured(result: ReportResult): boolean { - if (result.selected === false || result.status === 'interrupted') return true; + if (result.selected === false || result.status === 'interrupted' || result.attempts.some((attempt) => attempt.status === 'interrupted')) return true; return result.skip !== undefined && UNDELIVERED_SKIPS.has(result.skip.cause); } @@ -289,7 +293,8 @@ function leftUnmeasured(result: ReportResult): boolean { * would read as slower. A file with no attempt has none either. */ export function fileDurationsOf(report: Report1Document): ReadonlyMap { - const partial = new Set(report.run.results.filter(leftUnmeasured).map((result) => fileDurationKey(result.targetId, result.file))); + 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(); for (const unit of [...report.run.results, ...report.run.serialGroups]) { const key = fileDurationKey(unit.targetId, unit.file); diff --git a/packages/e2e/src/run/timings.ts b/packages/e2e/src/run/timings.ts index 53d31b6829..5fa826e0cf 100644 --- a/packages/e2e/src/run/timings.ts +++ b/packages/e2e/src/run/timings.ts @@ -26,6 +26,12 @@ 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 { @@ -37,7 +43,7 @@ async function readTimingsFile(file: string): Promise(); for (const [key, ms] of Object.entries(files)) { - if (!key.includes(KEY_SEPARATOR) || typeof ms !== 'number' || !Number.isSafeInteger(ms) || ms < 0) return undefined; + if (!KEY_PATTERN.test(key) || typeof ms !== 'number' || !Number.isSafeInteger(ms) || ms < 0) return undefined; durations.set(key, ms); } return durations; diff --git a/packages/e2e/tests/unit/last-run.test.ts b/packages/e2e/tests/unit/last-run.test.ts index 87a6fa8758..8d138fd9a3 100644 --- a/packages/e2e/tests/unit/last-run.test.ts +++ b/packages/e2e/tests/unit/last-run.test.ts @@ -343,7 +343,7 @@ 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, or ran it more than once', async () => { + 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( @@ -355,6 +355,12 @@ describe('previousFileDurations', () => { { 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))), diff --git a/packages/e2e/tests/unit/timings.test.ts b/packages/e2e/tests/unit/timings.test.ts index d304ec3adb..67f263cb4b 100644 --- a/packages/e2e/tests/unit/timings.test.ts +++ b/packages/e2e/tests/unit/timings.test.ts @@ -1,4 +1,4 @@ -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +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'; @@ -63,6 +63,32 @@ describe('loadTimings', () => { 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); @@ -118,8 +144,16 @@ describe('writeTimings', () => { }); 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(() => readFileSync(timings)).toThrow(); + expect(existsSync(timings)).toBe(false); }); }); diff --git a/plugins/e2e/skills/e2e/references/running.md b/plugins/e2e/skills/e2e/references/running.md index 9c0754f12c..bfe8c41d0e 100644 --- a/plugins/e2e/skills/e2e/references/running.md +++ b/plugins/e2e/skills/e2e/references/running.md @@ -60,7 +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 order files by and update, over `/timings.json`. | +| `--timings ` | The timings history to update, over `/timings.json`. With more than one worker, files start longest first by it. | | `--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 @@ -134,7 +134,7 @@ its own tools. ## Output `` (`.e2e` by default) holds `report.json`, `junit.xml`, -`summary.md`, `ai-trace.json`, `timings.json` (how long each file took, to start the longest first on the next run), `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 first), `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 9c0754f12c..bfe8c41d0e 100644 --- a/skills/e2e/references/running.md +++ b/skills/e2e/references/running.md @@ -60,7 +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 order files by and update, over `/timings.json`. | +| `--timings ` | The timings history to update, over `/timings.json`. With more than one worker, files start longest first by it. | | `--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 @@ -134,7 +134,7 @@ its own tools. ## Output `` (`.e2e` by default) holds `report.json`, `junit.xml`, -`summary.md`, `ai-trace.json`, `timings.json` (how long each file took, to start the longest first on the next run), `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 first), `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 From f4f945e4767f86c71eb8073e7a64b38b80a65a7d Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Mon, 9 Nov 2026 14:27:36 +0900 Subject: [PATCH 4/5] docs(run): say files with no recorded time start before the timed ones Refs ENG-1111 Co-Authored-By: Claude Sonnet 5.5 --- docs/ci.mdx | 4 ++-- docs/reference/cli.mdx | 2 +- packages/e2e/src/cli/index.ts | 2 +- plugins/e2e/skills/e2e/references/running.md | 4 ++-- skills/e2e/references/running.md | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/ci.mdx b/docs/ci.mdx index 6bb42200e0..e4f8520b67 100644 --- a/docs/ci.mdx +++ b/docs/ci.mdx @@ -207,8 +207,8 @@ on `main`, the whole suite runs. See ## Cache the timings history -With more than one worker, `e2e run` starts the longest files first, ordered -by `/timings.json` (`.e2e/timings.json` by default): a few KB that a +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. diff --git a/docs/reference/cli.mdx b/docs/reference/cli.mdx index fb982bdcb3..7b641c4986 100644 --- a/docs/reference/cli.mdx +++ b/docs/reference/cli.mdx @@ -575,7 +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 start longest first by it. Resolved from the project root. A missing or invalid file is no history, never an error. | +| `--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/packages/e2e/src/cli/index.ts b/packages/e2e/src/cli/index.ts index 5d09c72856..8427572060 100644 --- a/packages/e2e/src/cli/index.ts +++ b/packages/e2e/src/cli/index.ts @@ -635,7 +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 the longest files first by (default: /timings.json)') + .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)') diff --git a/plugins/e2e/skills/e2e/references/running.md b/plugins/e2e/skills/e2e/references/running.md index bfe8c41d0e..e42a77bd21 100644 --- a/plugins/e2e/skills/e2e/references/running.md +++ b/plugins/e2e/skills/e2e/references/running.md @@ -60,7 +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 start longest first by it. | +| `--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 @@ -134,7 +134,7 @@ its own tools. ## Output `` (`.e2e` by default) holds `report.json`, `junit.xml`, -`summary.md`, `ai-trace.json`, `timings.json` (how long each file took; with more than one worker the next run starts the longest first), `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 bfe8c41d0e..e42a77bd21 100644 --- a/skills/e2e/references/running.md +++ b/skills/e2e/references/running.md @@ -60,7 +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 start longest first by it. | +| `--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 @@ -134,7 +134,7 @@ its own tools. ## Output `` (`.e2e` by default) holds `report.json`, `junit.xml`, -`summary.md`, `ai-trace.json`, `timings.json` (how long each file took; with more than one worker the next run starts the longest first), `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 From 183d6a18b2a4510dca0ca8d99204e8fc653448d6 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Tue, 10 Nov 2026 11:54:29 +0900 Subject: [PATCH 5/5] fix(run): time a file whose other tests a platforms list keeps off the target A test a `platforms` list excludes is `selected: false` with cause `platform-unavailable`, the same flag a `--grep` or `--last-failed` sets, so a file holding both an iOS-only and an Android-only test never got a time on either target. Only a filter makes a file partial; a permanent platform exclusion does not. Refs ENG-1111 Co-Authored-By: Claude Sonnet 5.5 --- packages/e2e/src/run/last-run.ts | 9 ++++++--- packages/e2e/tests/unit/last-run.test.ts | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/packages/e2e/src/run/last-run.ts b/packages/e2e/src/run/last-run.ts index 0d71176a1d..b3f9548a91 100644 --- a/packages/e2e/src/run/last-run.ts +++ b/packages/e2e/src/run/last-run.ts @@ -276,11 +276,14 @@ function isError(value: unknown): value is ReportError { /** * Whether a result stands for a test its run did not carry out whole: left - * out, never reached, or with an attempt cut short, which a retry after a - * failure leaves under the earlier verdict. + * 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 { - if (result.selected === false || result.status === 'interrupted' || result.attempts.some((attempt) => attempt.status === 'interrupted')) return true; + 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); } diff --git a/packages/e2e/tests/unit/last-run.test.ts b/packages/e2e/tests/unit/last-run.test.ts index 8d138fd9a3..190832d16d 100644 --- a/packages/e2e/tests/unit/last-run.test.ts +++ b/packages/e2e/tests/unit/last-run.test.ts @@ -372,6 +372,21 @@ describe('previousFileDurations', () => { ]); }); + 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);