diff --git a/.changeset/rerun-integrity.md b/.changeset/rerun-integrity.md new file mode 100644 index 0000000000..d876cd47f5 --- /dev/null +++ b/.changeset/rerun-integrity.md @@ -0,0 +1,6 @@ +--- +"e2e": patch +"@e2e-dev/github": patch +--- + +`--last-failed` no longer goes green on tests it never ran. It reruns tests `--max-failures` skipped, and a test or failed `beforeAll`/`afterAll` another filter leaves out stays owed in the report's new `run.carried` until a rerun runs it. A rerun also keeps the artifacts of the run it reruns and writes its own under `artifacts/rerun-/` in the output directory (`.e2e` by default), so the folded pull request comment keeps its evidence and stays red while anything is owed. diff --git a/docs/ci.mdx b/docs/ci.mdx index f6fc883d2b..39a8ca3ea5 100644 --- a/docs/ci.mdx +++ b/docs/ci.mdx @@ -139,10 +139,12 @@ implemented yet. `--last-failed` runs only the tests the previous run did not pass, read from `report.json` in the [`output`](/reference/config#output) directory (`.e2e` -by default). The rerun empties `artifacts/` there when it starts, so -upload the first run's artifacts before rerunning in the same job if you want -both. The [CLI reference](/reference/cli#flags) lists what counts as not -passed. Locally it is the loop after a red run: +by default). The rerun keeps the artifacts the first run's report names and +writes its own under `artifacts/rerun-1/`, so one upload after both steps +holds the evidence of each. A test another filter keeps out of the rerun +stays owed: the next `--last-failed` runs it. The +[CLI reference](/reference/cli#flags) lists what counts as not passed. +Locally it is the loop after a red run: ```bash npm diff --git a/docs/debugging.mdx b/docs/debugging.mdx index ec34b1d084..4bb4dd6d94 100644 --- a/docs/debugging.mdx +++ b/docs/debugging.mdx @@ -91,7 +91,9 @@ failed result: Artifacts land under `.e2e/artifacts/` (`/artifacts/` when the [`output`](/reference/config#output) is moved), one directory per attempt. -Each run empties it first, so it holds the latest run's evidence: +Each run empties it first, so it holds the latest run's evidence. A +`--last-failed` rerun instead empties it down to the files the report it +reruns names, and writes its own under `rerun-/`: - **Screenshots.** Failed attempts capture one whenever the engine can and pixels are allowed. The built-in `agent.assert` also captures one after diff --git a/docs/github.mdx b/docs/github.mdx index 242eac8878..1c35b9d1ad 100644 --- a/docs/github.mdx +++ b/docs/github.mdx @@ -63,7 +63,10 @@ Upload artifacts even when a retry passes. Each failure's evidence links open the run's Artifacts section; inside the download, every test has a directory named after it and the agent that ran it (`web/tests_billing.e2e.ts__upgrades/default/attempt-0/`), so keep -`path: .e2e/artifacts` and the download lines up with the report. A project +`path: .e2e/artifacts` and the download lines up with the report. A +`--last-failed` rerun keeps the first run's directories and puts its own +under `rerun-1/`, so a flaky test's failed attempt still links to its own +files. A project below the checkout root, such as `packages/e2e-tests`, gets source links under that path. The checkout root is the nearest directory holding `.git` inside `GITHUB_WORKSPACE`, so `actions/checkout` with a `path` input works too. @@ -144,10 +147,13 @@ passes: The comment covers the whole suite, not only the tests the rerun ran again. A test that failed and then passed shows as flaky, a test that failed twice stays failed, one that was interrupted and then passed shows as passed, and -the rest keep their first-pass results. The comment -matches the job's status: it stays red when another filter kept a failed -test out of the rerun, and shows ⏹️ when it kept out a test the first pass -never finished. +the rest keep their first-pass results. The comment stays red while the +rerun left out something it owed: a failed test, one `--max-failures` stopped +before it ran, or a failed `beforeAll` or `afterAll` whose tests another +filter kept out of the rerun. It shows ⏹️ when the rerun left out a test the +first pass never finished. The rerun's own exit code counts only what it ran. +A failed attempt's evidence links to the first run's files, which the rerun +keeps. ## Matrix jobs diff --git a/docs/reference/cli.mdx b/docs/reference/cli.mdx index 6e2c398f02..703f93f300 100644 --- a/docs/reference/cli.mdx +++ b/docs/reference/cli.mdx @@ -359,7 +359,7 @@ or every test was filtered out. | `--exclude-tag ` | comma-separated or repeated | none | Leaves out every test carrying any of the tags, whatever `--tag` or a positional selected. A serial group still runs whole when any member is selected; tag the serial `describe` to exclude the flow. | | `--grep ` | regular expression, repeatable | none | Only tests whose title matches one of the patterns. The text matched is the describe titles and the test title joined by one space (`checkout pays`); the file and the tags are not part of it. A bare pattern is case-sensitive; `'/pattern/i'` adds flags. A pattern that does not compile is a usage error, exit 2. | | `--grep-invert ` | regular expression, repeatable | none | Leaves out every test whose title matches one of the patterns. Same text and pattern forms as `--grep`; both together keep the tests `--grep` matches minus the ones `--grep-invert` matches. | -| `--last-failed` | boolean | `false` | Only the tests the previous run did not pass, read from the `report.json` this run overwrites, `/report.json` (`--output`, else the config's [`output`](/reference/config#output)): failed, timed out, interrupted, or skipped because a setup, a serial predecessor, a hook, or the worker failed, and every test it selected in the describe or file, on that target, of a `beforeAll` or `afterAll` that failed (for a setup, the tests that consume its session). A rerun that runs the hook again reports it again if it still fails; another filter that leaves its tests out leaves the failure out of the next report too. A test is named per target and agent. No report is `NO_LAST_RUN`; a previous run with nothing failed selects nothing, `NO_TESTS` unless `--pass-with-no-tests`. | +| `--last-failed` | boolean | `false` | Only the tests the previous run did not pass, read from the `report.json` this run overwrites, `/report.json` (`--output`, else the config's [`output`](/reference/config#output)): failed, timed out, interrupted, or skipped because a setup, a serial predecessor, a hook, or the worker failed or `--max-failures` stopped the run first, and every test it selected in the describe or file, on that target, of a `beforeAll` or `afterAll` that failed (for a setup, the tests that consume its session). A rerun that runs the hook again reports it again if it still fails, and a rerun that runs any test of its scope without it failing resolves it. A test another filter (`--grep`, `--tag`, `--target`, `--agent`, a positional) leaves out of the rerun stays owed: the rerun's report carries its last result, and the hook failure whose scope it is in, under `run.carried`, the next `--last-failed` selects it again, and the [`@e2e-dev/github`](/github) page stays red until it passes (⏹️ for a test the run before interrupted). The rerun's own exit code and summary count only what it ran. It keeps the artifacts the previous report names and writes its own under `artifacts/rerun-/`, so no attempt overwrites an earlier one's files. A test is named per target and agent. No report is `NO_LAST_RUN`; a previous run with nothing failed selects nothing, `NO_TESTS` unless `--pass-with-no-tests`. | | `--shard ` | `2/3` | none | Runs one contiguous slice of the selected tests, cut once every other filter applied. Slices differ in size by at most one test, a serial group counts as one and is never split, and each shard brings only the setup tests its own tests need. Every shard runs the same command with a different index; the order is the report order, so the same suite shards the same way on every machine. A shard that gets no test is `NO_TESTS` unless `--pass-with-no-tests`. See [Sharding](/ci#sharding). | | `--headed` | boolean | `false` | Visible UI when the engine supports it. | | `--agent ` | comma-separated or repeated | `default` | Runs unpinned tests once per selected agent. For a test with `{ agent }`, selects the shared names when there is overlap; otherwise keeps the test's selection. An unknown name is `INVALID_CONFIG`. | @@ -368,7 +368,7 @@ or every test was filtered out. | `--repeat-each ` | integer, at least 1 | `1` | Runs every selected test this many times. Each run is a result of its own, with `repeat` 0 through `n - 1` and its own `id`; the list reporter titles the later runs `(repeat #1)`, `(repeat #2)`, and their artifacts go under a `repeat-` directory. Setup tests run once. With the replay cache on, the first run records and the later ones replay, so pair it with `--no-cache` to exercise the model each time. The `list` summary adds a `Repeats` row (`1 of 2 tests passed all 5 runs`) and one line per test that did not pass every run, naming each run that failed; the `markdown` page carries the same tally. | | `--max-failures ` | integer, at least 1 | none | Stops the run once this many tests have failed or timed out. Nothing more is dispatched, the tests running on other workers end as `interrupted`, and the tests not started, the rest of the file whose test reached the limit included, are skipped with cause `failure-limit` and the reason `run stopped after 3 failures (--max-failures 3)`. The exit code is the failures' own, 1, not 130. | | `--reporter ` | comma-separated list | config | Replaces the built-in IDs in `config.reporters`: `list`, `json`, `junit`, `markdown`. `json` with `list` is `INVALID_CONFIG`. [Reporter objects](/reference/reporters) in the config keep running. | -| `--output ` | string | config, else `.e2e` | The results directory for this run, over the config's [`output`](/reference/config#output): the report, the reporter files, the AI trace, `artifacts/` (cleared once the run's tests start), and `sessions/`. Resolved from the project root; one the run cannot own is `INVALID_CONFIG`. The removed `--artifacts ` fails with the `--output` it maps to: `--artifacts out/artifacts` is `--output out`, and a directory whose parent is the project root or outside it maps to `--output .e2e`. | +| `--output ` | string | config, else `.e2e` | The results directory for this run, over the config's [`output`](/reference/config#output): the report, the reporter files, the AI trace, `artifacts/` (cleared once the run's tests start, down to what the previous report names on a `--last-failed` rerun), and `sessions/`. Resolved from the project root; one the run cannot own is `INVALID_CONFIG`. The removed `--artifacts ` fails with the `--output` it maps to: `--artifacts out/artifacts` is `--output out`, and a directory whose parent is the project root or outside it maps to `--output .e2e`. | | `--no-cache` | boolean | `false` | Replay cache off for this run, whatever `config.cache` says. | | `--strict-cache` | boolean | `false` | Turns on `cache.strict` for this run: a step whose recording exists but no longer replays fails with `REPLAY_STALE` instead of handing off to the agent. See [Fail on a stale recording](/cache#fail-on-a-stale-recording). | | `--pass-with-no-tests` | boolean | `false` | Exit 0 instead of `NO_TESTS` when nothing is selected. | diff --git a/docs/reference/config.mdx b/docs/reference/config.mdx index b9834354fb..351912bc55 100644 --- a/docs/reference/config.mdx +++ b/docs/reference/config.mdx @@ -383,7 +383,7 @@ run. | `report.json` | The canonical report; `--last-failed` reads the one here | | `junit.xml`, `summary.md`, `failures/` | The `junit` and `markdown` reporters' files | | `ai-trace.json` | `--ai-trace` | -| `artifacts/` | Screenshots, traces, videos, downloads, and logs, one directory per attempt. Cleared once a run's tests start, so it holds the latest run's evidence and nothing its report no longer names | +| `artifacts/` | Screenshots, traces, videos, downloads, and logs, one directory 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 `artifacts/rerun-/` | | `sessions/` | The run's encrypted `test.setup` sessions, deleted when it ends | | `videos//` | [`e2e mcp`](/reference/mcp#recording) session recordings | diff --git a/docs/reference/reporters.mdx b/docs/reference/reporters.mdx index b53f7ce128..8b35eada22 100644 --- a/docs/reference/reporters.mdx +++ b/docs/reference/reporters.mdx @@ -180,7 +180,13 @@ abandoned reporter keeps the CLI alive after the run has ended. With `--last-failed`, `lastRun` is the report the rerun selected from. The rerun's own report lists the tests it left out as unselected, so a reporter that keeps one place current, the way `@e2e-dev/github` keeps a pull request -comment, folds the rerun into `lastRun` to show both runs as one. +comment, folds the rerun into `lastRun` to show both runs as one. A test the +rerun owed but another filter left out is in the rerun's `run.carried`: its +last result, the serial group its attempts live on, and the `beforeAll` or +`afterAll` failure whose scope holds it, from whichever earlier run reported +them. A fold shows the carried result in place of the unselected one and +counts a carried failure or hook error against the outcome. The artifacts +both reports name are on disk under `artifactsRoot`. The rows a reporter resolves with print under the `list` summary in the same layout as `Report`; the `json` reporter does not carry them: diff --git a/packages/e2e/schema/fixtures/report-v1.valid.json b/packages/e2e/schema/fixtures/report-v1.valid.json index 2dab3aca85..b8c9c6b922 100644 --- a/packages/e2e/schema/fixtures/report-v1.valid.json +++ b/packages/e2e/schema/fixtures/report-v1.valid.json @@ -56,7 +56,9 @@ "id": "4bbfd0a6dbf44ac1018dd6ca1a6243d742b24607aa735b28d57541e1128507d3", "testId": "tests/example.e2e.ts::opens%20app", "kind": "test", - "tags": ["smoke"], + "tags": [ + "smoke" + ], "declarationIndex": 0, "titlePath": [ "opens app" @@ -392,6 +394,204 @@ "modelCachedTokens": 0, "maxModelCallsInStep": 0, "maxActionStepsInStep": 0 + }, + "carried": { + "results": [ + { + "id": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "testId": "tests/example.e2e.ts::carried", + "kind": "test", + "tags": [ + "smoke" + ], + "declarationIndex": 2, + "titlePath": [ + "carried from the first run" + ], + "file": "tests/example.e2e.ts", + "source": { + "file": "tests/example.e2e.ts", + "line": 3, + "column": 1 + }, + "targetId": "web", + "platform": "web", + "agent": "default", + "repeat": 0, + "selected": true, + "status": "passed", + "attempts": [ + { + "id": "018f0f5c-7b2a-7abc-8abc-2123456789ab", + "index": 0, + "status": "passed", + "startedAt": "2026-07-24T12:00:00.000Z", + "durationMs": 1000, + "steps": [ + { + "id": "018f0f5c-7b2a-7abc-8abc-3123456789ab:0", + "index": 0, + "kind": "agent", + "api": "agent.act", + "label": "adds shoes to the cart", + "source": { + "file": "tests/example.e2e.ts", + "line": 3, + "column": 1 + }, + "status": "passed", + "startedAt": "2026-07-24T12:00:00.000Z", + "durationMs": 4200, + "events": [ + { + "kind": "model", + "startedAt": "2026-07-24T12:00:00.100Z", + "durationMs": 2840, + "status": "passed", + "name": "executor", + "count": 120, + "inputTokens": 100, + "outputTokens": 20, + "reasoning": "A modal blocks the checkout button; closing it before continuing." + }, + { + "kind": "engine", + "startedAt": "2026-07-24T12:00:03.000Z", + "durationMs": 27, + "status": "passed", + "name": "tap", + "detail": "tap button \"Close\"" + } + ], + "metrics": { + "modelCalls": 1, + "actionSteps": 1, + "observationBytes": 512, + "contextBytes": 0, + "ledgerBytes": 0 + }, + "cache": { + "mode": "missed", + "reason": "gap", + "derived": "minted-token", + "replayedActions": 0, + "totalActions": 2 + }, + "artifacts": [], + "turns": [ + { + "index": 1, + "calls": [ + "tap({\"target\":\"n19\"})" + ], + "outcome": "Tapped #n19.\nScreen changes: 4 added." + } + ] + }, + { + "id": "018f0f5c-7b2a-7abc-8abc-3123456789ab:1", + "index": 1, + "kind": "agent", + "api": "agent.assert", + "label": "the result is visible", + "source": { + "file": "tests/example.e2e.ts", + "line": 3, + "column": 1 + }, + "status": "failed", + "startedAt": "2026-07-24T12:00:00.000Z", + "durationMs": 1000, + "events": [], + "metrics": { + "modelCalls": 0, + "actionSteps": 0, + "observationBytes": 0, + "contextBytes": 0, + "ledgerBytes": 0 + }, + "artifacts": [], + "error": { + "category": "test", + "code": "OPERATION_TIMEOUT", + "message": "semantic capture timed out", + "retryable": false + } + } + ], + "artifacts": [ + { + "id": "018f0f5c-7b2a-7abc-8abc-2123456789ab:artifact:0", + "kind": "video", + "mediaType": "video/webm", + "path": "web/tests_example.e2e.ts__carried/attempt-0/video/video.webm", + "size": 8, + "sha256": "1111111111111111111111111111111111111111111111111111111111111111", + "startedAt": "2026-07-24T12:00:00.000Z", + "redaction": "incomplete", + "producer": { + "kind": "attempt" + } + }, + { + "id": "018f0f5c-7b2a-7abc-8abc-2123456789ab:artifact:1", + "kind": "video", + "mediaType": "video/mp4", + "url": "https://recordings.example.com/sessions/abc/replay.mp4", + "startedAt": "2026-07-24T12:00:00.000Z", + "redaction": "incomplete", + "producer": { + "kind": "attempt" + } + } + ], + "secondaryErrors": [], + "cleanup": "complete", + "failure": { + "url": "http://127.0.0.1:3000/todos", + "screen": "018f0f5c-7b2a-7abc-8abc-2123456789ab:artifact:0", + "candidates": [ + "#n19 button \"Add\"" + ] + }, + "error": { + "category": "test", + "code": "ASSERTION_FAILED", + "message": "expect.toHaveText failed", + "retryable": false, + "phase": "body", + "details": { + "locator": "getByRole(\"status\")", + "expected": "text \"2 remaining\"", + "observed": "text \"1 remaining\"", + "matches": 1 + }, + "source": { + "file": "tests/example.e2e.ts", + "line": 9, + "column": 3 + } + } + } + ] + } + ], + "serialGroups": [], + "errors": [ + { + "category": "test", + "code": "HOOK_FAILED", + "message": "afterAll failed: teardown broke", + "retryable": false, + "phase": "afterAll", + "scopeId": "file", + "scope": { + "file": "tests/example.e2e.ts", + "targetId": "web", + "titlePath": [] + } + } + ] } } } diff --git a/packages/e2e/schema/report-v1.schema.json b/packages/e2e/schema/report-v1.schema.json index 527839bf47..0e9e4c1703 100644 --- a/packages/e2e/schema/report-v1.schema.json +++ b/packages/e2e/schema/report-v1.schema.json @@ -671,10 +671,22 @@ "summary": { "$ref": "#/$defs/summary" }, "limits": { "$ref": "#/$defs/limits" }, "usage": { "$ref": "#/$defs/usage" }, + "carried": { "$ref": "#/$defs/carried" }, "explore": { "$ref": "#/$defs/explore" }, "extensions": { "$ref": "#/$defs/extensions" } } }, + "carried": { + "description": "What earlier runs left unresolved that a --last-failed rerun did not run again: their results as they reported them, the serial groups those results' attempts live on, and the suite hook failures whose scope still holds one of them. The next --last-failed selects these tests too. Not part of the run's status, exit code, or summary.", + "type": "object", + "additionalProperties": false, + "required": ["results", "serialGroups", "errors"], + "properties": { + "results": { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/result" } }, + "serialGroups": { "type": "array", "items": { "$ref": "#/$defs/serialGroup" } }, + "errors": { "type": "array", "items": { "$ref": "#/$defs/error" } } + } + }, "exploreFinding": { "type": "object", "additionalProperties": false, diff --git a/packages/e2e/src/report/build.ts b/packages/e2e/src/report/build.ts index 26fdaf7a0a..6f21812e8a 100644 --- a/packages/e2e/src/report/build.ts +++ b/packages/e2e/src/report/build.ts @@ -338,6 +338,20 @@ export interface ReportSummary { skipped: number; } +/** + * What earlier runs left unresolved that a `--last-failed` rerun did not run + * again, because another filter left it out: the results as those runs + * reported them, the serial groups their members' attempts live on, and the + * suite hook failures whose scope still holds a carried test. The next + * `--last-failed` selects these tests too, so a test that never ran again + * stays owed until it does. + */ +export interface ReportCarried { + results: readonly ReportResult[]; + serialGroups: readonly ReportSerialGroup[]; + errors: readonly ReportError[]; +} + export interface Report1Document { schemaVersion: 'report-1'; run: { @@ -368,6 +382,11 @@ export interface Report1Document { summary: ReportSummary; limits: ReportLimits; usage: ReportUsage; + /** + * Present on a `--last-failed` rerun that left out a test an earlier run + * did not pass. Not part of this run's status, exit code, or summary. + */ + carried?: ReportCarried | undefined; /** Present on an `e2e explore` run only. */ explore?: ReportExplore | undefined; }; diff --git a/packages/e2e/src/run/artifacts.ts b/packages/e2e/src/run/artifacts.ts index 1a54bdd29c..284b3bcd99 100644 --- a/packages/e2e/src/run/artifacts.ts +++ b/packages/e2e/src/run/artifacts.ts @@ -2,7 +2,7 @@ import { createHash } from 'node:crypto'; import { createReadStream, mkdirSync } from 'node:fs'; -import { readFile, stat } from 'node:fs/promises'; +import { mkdir, readdir, readFile, rm, rmdir, stat } from 'node:fs/promises'; import path from 'node:path'; import { pipeline } from 'node:stream/promises'; import { writeFileAtomic } from '../internal/atomic-write.ts'; @@ -206,6 +206,69 @@ export function createAttemptArtifacts(options: { return { dir, records, sink, settle }; } +/** What a `--last-failed` rerun's attempt directory is called, `rerun-`, numbered from 1. */ +const RERUN_DIR = /^rerun-([1-9][0-9]*)$/; + +/** + * Empties an artifact tree down to the files `keep` names, by their report + * paths, and removes the directories left empty. A `--last-failed` rerun + * starts this way rather than from an empty tree: the evidence the report it + * reruns names stays, since that report's results fold into the rerun's and + * its carried tests are not run again. + */ +export async function pruneArtifacts(root: string, keep: ReadonlySet): Promise { + const prune = async (dir: string, relative: string): Promise => { + let entries; + try { + entries = await readdir(dir, { withFileTypes: true }); + } catch (cause) { + if ((cause as NodeJS.ErrnoException).code === 'ENOENT') return true; + throw cause; + } + let empty = true; + for (const entry of entries) { + const reportPath = relative === '' ? entry.name : `${relative}/${entry.name}`; + const absolute = path.join(dir, entry.name); + if (entry.isDirectory()) { + if (await prune(absolute, reportPath)) await rmdir(absolute); + else empty = false; + } else if (keep.has(reportPath)) { + empty = false; + } else { + await rm(absolute, { force: true }); + } + } + return empty; + }; + await prune(root, ''); +} + +/** + * Claims the directory a `--last-failed` rerun's attempts write under, beside + * the evidence it kept, and returns its name: `rerun-`, past every number + * already there, so the tree reads in run order. The directory is created + * exclusively, so no attempt of the rerun writes into a directory an earlier + * run's report still names. + */ +export async function claimRerunDir(root: string): Promise { + await mkdir(root, { recursive: true }); + const taken = (await readdir(root)).map((name) => Number(RERUN_DIR.exec(name)?.[1] ?? 0)); + for (let n = Math.max(0, ...taken) + 1; ; n += 1) { + const name = `rerun-${n}`; + try { + await mkdir(path.join(root, name)); + return name; + } catch (cause) { + if ((cause as NodeJS.ErrnoException).code !== 'EEXIST') throw cause; + } + } +} + +/** An attempt's report segments, under the rerun's directory on a `--last-failed` rerun. */ +export function attemptSegments(rerunDir: string | undefined, segments: readonly string[]): readonly string[] { + return rerunDir === undefined ? segments : [rerunDir, ...segments]; +} + /** * Rewrites a text-like download through the session's ledger, the way a * trace's text entries are, and returns the redaction the record can claim: diff --git a/packages/e2e/src/run/execute.ts b/packages/e2e/src/run/execute.ts index 3e93befc81..9014549b88 100644 --- a/packages/e2e/src/run/execute.ts +++ b/packages/e2e/src/run/execute.ts @@ -29,7 +29,7 @@ import type { ModuleRegistration, RegisteredTest } from '../collect/registry.ts' import { pairRecordings, type TestTargetPair } from '../collect/select.ts'; import type { AttemptRecording, AttemptRecordings, RecordingKind } from '../internal/recording-modes.ts'; import type { ArtifactStore, Secret } from '../types.ts'; -import { createAttemptArtifacts, sanitizePathSegment } from './artifacts.ts'; +import { attemptSegments, createAttemptArtifacts, sanitizePathSegment } from './artifacts.ts'; import { AttemptBudget } from './budget.ts'; import { createEngineSession } from '../engine/session.ts'; import { createExtendedFixtures } from './extended-fixtures.ts'; @@ -81,6 +81,12 @@ export interface TargetExecutorOptions { readonly target: ResolvedTarget; readonly runId: string; readonly artifactsRoot: string; + /** + * The directory under `artifactsRoot` a `--last-failed` rerun's attempts + * write in (`claimRerunDir`), beside the evidence of the run it reruns; + * undefined when the attempts fill the root themselves. + */ + readonly rerunDir?: string | undefined; readonly sessionStore: SessionStore; readonly headed: boolean; /** This worker's slot among the target's workers; see `EngineInitInfo.workerSlot`. */ @@ -156,6 +162,7 @@ export class TargetExecutor implements SerialHost { return this.config.artifactStore; } readonly artifactsRoot: string; + readonly rerunDir: string | undefined; readonly interruptSignal: AbortSignal; readonly realms: RealmManager; readonly debug: DebugTrace; @@ -173,6 +180,7 @@ export class TargetExecutor implements SerialHost { constructor(private readonly options: TargetExecutorOptions) { this.target = options.target; this.artifactsRoot = options.artifactsRoot; + this.rerunDir = options.rerunDir; this.interruptSignal = options.interruptSignal; this.debug = options.debug ?? new DebugTrace(false); this.models = new WorkerModels((error) => { @@ -850,7 +858,13 @@ export class TargetExecutor implements SerialHost { // several times, from overwriting itself. segments: shared?.artifactSegments ?? - [this.target.name, sanitizePathSegment(registered.artifactName ?? pair.test.id), pair.agent, ...repeatSegment(pair.repeat), `attempt-${attemptIndex}`], + attemptSegments(this.rerunDir, [ + this.target.name, + sanitizePathSegment(registered.artifactName ?? pair.test.id), + pair.agent, + ...repeatSegment(pair.repeat), + `attempt-${attemptIndex}`, + ]), attemptId, currentStepId: () => steps.currentStepId, ...(this.config.artifactStore === undefined ? {} : { store: this.config.artifactStore }), diff --git a/packages/e2e/src/run/in-process.ts b/packages/e2e/src/run/in-process.ts index 46ad288925..bc06ae54a5 100644 --- a/packages/e2e/src/run/in-process.ts +++ b/packages/e2e/src/run/in-process.ts @@ -32,6 +32,8 @@ export interface InProcessRunnerOptions { readonly inMemory?: (InMemoryAttempts & { readonly registration: ModuleRegistration }) | undefined; readonly runId: string; readonly artifactsRoot: string; + /** See `TargetExecutorOptions.rerunDir`. */ + readonly rerunDir: string | undefined; readonly sessionStore: SessionStore; readonly headed: boolean; readonly debug: DebugTrace; @@ -133,6 +135,7 @@ class InProcessRunner implements UnitRunner { sessionStore: this.options.sessionStore, runId: this.options.runId, artifactsRoot: this.options.artifactsRoot, + rerunDir: this.options.rerunDir, headed: this.options.headed, workerSlot: this.workerSlot, env: this.options.envFor(this.targetName), diff --git a/packages/e2e/src/run/last-run.ts b/packages/e2e/src/run/last-run.ts index b4e1b1b464..a4155d625f 100644 --- a/packages/e2e/src/run/last-run.ts +++ b/packages/e2e/src/run/last-run.ts @@ -7,6 +7,8 @@ import type { Report1Document } from '../report/build.ts'; type ReportResult = Report1Document['run']['results'][number]; type ReportError = Report1Document['run']['errors'][number]; +type ReportSerialGroup = Report1Document['run']['serialGroups'][number]; +type ReportCarried = NonNullable; /** Skips that stand for a test the run could not carry out, as opposed to one it chose not to. */ const UNDELIVERED_SKIPS = new Set['cause']>([ @@ -14,8 +16,19 @@ const UNDELIVERED_SKIPS = new Set['cause']>([ 'serial-predecessor-failed', 'hook-failed', 'infrastructure-unavailable', + 'failure-limit', ]); +/** The id `--last-failed` names a result by: its test, target, and agent, whichever its repeat. */ +function rerunId(result: ReportResult): string { + return resultId(result.testId, result.targetId, result.agent); +} + +/** Whether a run error is a failed `beforeAll` or `afterAll`, the failures `--last-failed` runs the scope of again. */ +function isSuiteHookFailure(error: ReportError): boolean { + return error.phase === 'beforeAll' || error.phase === 'afterAll'; +} + /** Whether a result is one `--last-failed` runs again: it did not pass, or the run never got to it. */ function didNotPass(result: ReportResult): boolean { switch (result.status) { @@ -82,20 +95,105 @@ export async function readLastRun(reportPath: string): Promise /** * The result ids of a report's tests that did not pass: failed, timed out, - * interrupted, or skipped because a setup, a serial predecessor, a hook, or - * the worker failed, and every selected test in the scope of a `beforeAll` or - * `afterAll` that failed, until a run where that hook passes. A report older - * than `selected` counts every result as selected. An explicit - * skip and a filtered test passed in the sense that matters here: nothing to - * run again. The ids are `resultId(testId, target, agent)`, so a test is - * named per target and agent whichever of its `--repeat-each` runs did not - * pass. + * interrupted, or skipped because a setup, a serial predecessor, a hook, the + * worker, or the failure limit stopped it, every selected test in the scope + * of a `beforeAll` or `afterAll` that failed, until a run where that hook + * passes, and every test the report carries from an earlier run that it did + * not run again. A report older than `selected` counts every result as + * selected. An explicit skip and a filtered test passed in the sense that + * matters here: nothing to run again. The ids are + * `resultId(testId, target, agent)`, so a test is named per target and agent + * whichever of its `--repeat-each` runs did not pass. */ export function lastFailedIds(document: Report1Document): ReadonlySet { - const hookFailures = document.run.errors.filter((error) => error.phase === 'beforeAll' || error.phase === 'afterAll'); + const hookFailures = document.run.errors.filter(isSuiteHookFailure); const rerun = (result: ReportResult): boolean => didNotPass(result) || (result.selected !== false && hookFailures.some((error) => inHookScope(result, error))); - return new Set(document.run.results.filter(rerun).map((result) => resultId(result.testId, result.targetId, result.agent))); + const ids = new Set(document.run.results.filter(rerun).map(rerunId)); + for (const result of document.run.carried?.results ?? []) ids.add(rerunId(result)); + return ids; +} + +/** Whether two suite hook failures are the same hook's: one phase, one scope. */ +function sameHook(a: ReportError, b: ReportError): boolean { + if (a.phase !== b.phase) return false; + if (a.scope === undefined || b.scope === undefined) return a.scope === b.scope; + return ( + a.scope.file === b.scope.file && + a.scope.targetId === b.scope.targetId && + a.scope.titlePath.length === b.scope.titlePath.length && + a.scope.titlePath.every((title, index) => b.scope!.titlePath[index] === title) + ); +} + +/** What a rerun's collection found: the tests it collected by id, and the files it discovered but could not collect. */ +export interface RerunCollection { + readonly testIds: ReadonlySet; + readonly uncollectedFiles: ReadonlySet; +} + +/** + * What a `--last-failed` rerun carries forward from the report it selected + * from: every result that report owed a rerun and this run did not run, as + * the run that last ran it reported it; the serial groups those results' + * attempts live on; and the suite hook failures whose scope still holds one + * of them. A result is owed when it did not pass, or when it is in the scope + * of a failed `beforeAll` or `afterAll` this run did not see pass: a hook + * whose scope this run ran again without it failing is resolved, and one + * that failed again is this run's own error, which still makes its left-out + * tests owed. A test this run did not run is one it collected (`collected`, + * by test id), on a target the config still has, that it did not select: + * left out by a filter, on a target or agent the run did not ask for, or a + * setup no selected test needed, which the report lists no row for. A test in + * a file the run found but could not collect (`uncollectedFiles`, a narrowed + * run past a file that fails to import) is still there and stays carried. A + * test the run no longer collects cannot run again and is dropped. A test + * this run selected is no longer carried, whatever its outcome: its own + * result says it now. Undefined when nothing is carried. + */ +export function carryForward(lastRun: Report1Document, current: Report1Document, collected: RerunCollection): ReportCarried | undefined { + const selected = new Set(current.run.results.filter((result) => result.selected !== false).map(rerunId)); + const targets = new Set(current.run.targets.map((target) => target.id)); + const stillThere = (result: ReportResult): boolean => + collected.testIds.has(result.testId) || collected.uncollectedFiles.has(result.file); + const notRun = (result: ReportResult): boolean => !selected.has(rerunId(result)) && stillThere(result) && targets.has(result.targetId); + + const failedAgain = current.run.errors.filter(isSuiteHookFailure); + const hooks = [...lastRun.run.errors.filter(isSuiteHookFailure), ...(lastRun.run.carried?.errors ?? [])]; + const reportedAgain = (error: ReportError): boolean => failedAgain.some((again) => sameHook(again, error)); + const passedAgain = (error: ReportError): boolean => + !reportedAgain(error) && + current.run.results.some((result) => result.selected !== false && result.status !== 'skipped' && inHookScope(result, error)); + const unresolved = hooks.filter((error) => !passedAgain(error)); + + // A test the run before left out is known by the row it carried, not by its filtered one. + const history = [...lastRun.run.results.filter((result) => result.selected !== false), ...(lastRun.run.carried?.results ?? [])]; + const results = history.filter( + (result) => notRun(result) && (didNotPass(result) || unresolved.some((error) => inHookScope(result, error))), + ); + if (results.length === 0) return undefined; + + const groupIds = new Set(results.flatMap((result) => (result.serialGroupId === undefined ? [] : [result.serialGroupId]))); + const currentGroupIds = new Set(current.run.serialGroups.map((group) => group.id)); + const serialGroups: ReportSerialGroup[] = [...lastRun.run.serialGroups, ...(lastRun.run.carried?.serialGroups ?? [])].filter( + (group) => groupIds.has(group.id) && !currentGroupIds.has(group.id), + ); + const errors = unresolved.filter((error) => !reportedAgain(error) && results.some((result) => inHookScope(result, error))); + return { results, serialGroups, errors }; +} + +/** + * The artifact paths a report names, relative to the artifacts root: every + * attempt's of its results and serial groups, and of what it carries. What a + * `--last-failed` rerun keeps of the tree when it starts. + */ +export function reportArtifactPaths(document: Report1Document): ReadonlySet { + const parts = [document.run, ...(document.run.carried === undefined ? [] : [document.run.carried])]; + const attempts = parts.flatMap((part) => [ + ...part.results.flatMap((result) => result.attempts), + ...part.serialGroups.flatMap((group) => group.attempts), + ]); + return new Set(attempts.flatMap((attempt) => attempt.artifacts.flatMap((artifact) => (artifact.path === undefined ? [] : [artifact.path])))); } /** @@ -105,13 +203,45 @@ export function lastFailedIds(document: Report1Document): ReadonlySet { */ function isReport(value: unknown): value is Report1Document { if (typeof value !== 'object' || value === null) return false; - const document = value as { schemaVersion?: unknown; run?: { results?: unknown; errors?: unknown } }; + const document = value as { schemaVersion?: unknown; run?: { carried?: unknown } }; return ( document.schemaVersion === 'report-1' && - Array.isArray(document.run?.results) && - document.run.results.every(isResult) && - Array.isArray(document.run.errors) && - document.run.errors.every(isError) + isRunPart(document.run) && + (document.run.carried === undefined || isRunPart(document.run.carried)) + ); +} + +/** A run, or what one carries: results and errors of the shape read here, and its serial groups. */ +function isRunPart(value: unknown): value is { results: ReportResult[]; errors: ReportError[]; serialGroups: unknown[] } { + if (typeof value !== 'object' || value === null) return false; + const part = value as { results?: unknown; errors?: unknown; serialGroups?: unknown }; + return ( + Array.isArray(part.results) && + part.results.every(isResult) && + Array.isArray(part.errors) && + part.errors.every(isError) && + Array.isArray(part.serialGroups) && + part.serialGroups.every((group) => typeof group === 'object' && group !== null && hasAttempts(group)) + ); +} + +/** Whether a result or serial group lists its attempts, each with its artifacts, the way a rerun reads them. */ +function hasAttempts(value: object): boolean { + const { attempts } = value as { attempts?: unknown }; + return Array.isArray(attempts) && attempts.every(hasArtifacts); +} + +/** Whether an attempt lists its artifacts as records whose path, when there is one, is a string. */ +function hasArtifacts(attempt: unknown): boolean { + if (typeof attempt !== 'object' || attempt === null) return false; + const { artifacts } = attempt as { artifacts?: unknown }; + return ( + Array.isArray(artifacts) && + artifacts.every((artifact) => { + if (typeof artifact !== 'object' || artifact === null) return false; + const { path } = artifact as { path?: unknown }; + return path === undefined || typeof path === 'string'; + }) ); } @@ -124,6 +254,7 @@ function isResult(value: unknown): value is ReportResult { typeof result.status === 'string' && typeof result.file === 'string' && Array.isArray(result.titlePath) && + hasAttempts(result) && (skip === undefined || (typeof skip === 'object' && skip !== null && typeof skip.cause === 'string')) ); } diff --git a/packages/e2e/src/run/runner.ts b/packages/e2e/src/run/runner.ts index 8474ebd1f3..702c97d4b5 100644 --- a/packages/e2e/src/run/runner.ts +++ b/packages/e2e/src/run/runner.ts @@ -41,7 +41,8 @@ import { runUnits } from './scheduler.ts'; import { buildWorkPlans, plannedSlots, type TargetWorkPlan } from './units.ts'; import { SessionStore } from './sessions.ts'; import { outputLayout } from './output.ts'; -import { lastFailedIds, readLastRun } from './last-run.ts'; +import { claimRerunDir, pruneArtifacts } from './artifacts.ts'; +import { carryForward, lastFailedIds, readLastRun, reportArtifactPaths, type RerunCollection } from './last-run.ts'; import { childProcessSpawner } from './worker/handle.ts'; import { setSecretRegistry } from '../secrets.ts'; import { withAbort } from '../internal/time.ts'; @@ -411,8 +412,16 @@ export async function run(options: RunOptions = {}): Promise { // Detected once the config names the project root; a report written before // that (a config failure) has no checkout to describe. let vcs: VcsInfo | undefined; - const buildRunReport = (exitCode: RunExitCode): Report1Document => - buildReport({ + // The report `--last-failed` selected from, once collection has read it; + // reporters get it beside this run's report to fold the rerun into it, and + // this run's report carries what it owed that this run left out. + let lastRun: Report1Document | undefined; + // The ids of every test collection found, a setup no selected test needed + // among them, and the files it could not collect: what a rerun can still + // carry when the report lists no row. + let rerunCollection: RerunCollection = { testIds: new Set(), uncollectedFiles: new Set() }; + const buildRunReport = (exitCode: RunExitCode): Report1Document => { + const document = buildReport({ runId, config: loaded.config, vcs, @@ -425,6 +434,9 @@ export async function run(options: RunOptions = {}): Promise { targetProvenance, explore: options.tests?.explore?.snapshot(), }); + const carried = lastRun === undefined ? undefined : carryForward(lastRun, document, rerunCollection); + return carried === undefined ? document : { ...document, run: { ...document.run, carried } }; + }; /** * Writes the canonical report and returns its path only once the file @@ -485,9 +497,6 @@ export async function run(options: RunOptions = {}): Promise { } }; - // The report `--last-failed` selected from, once collection has read it; - // reporters get it beside this run's report to fold the rerun into it. - let lastRun: Report1Document | undefined; /** * Whether the run got as far as its tests. Only such a run writes into the * output directory: one that stopped before leaves the previous run's @@ -616,6 +625,10 @@ export async function run(options: RunOptions = {}): Promise { ); const inputs = await selectionInputs(options, config); lastRun = inputs.lastRun; + rerunCollection = { + testIds: new Set(collection.tests.map((test) => test.id)), + uncollectedFiles: new Set(collection.uncollected.map((skipped) => skipped.file)), + }; const selection = repeatEach( select( collection, @@ -714,15 +727,25 @@ export async function run(options: RunOptions = {}): Promise { // Tests are about to start, and only now is the previous run's evidence // given up: the artifact tree is emptied, so what is there once this run // ends is its own and nothing a report no longer names, and this run's - // report replaces the last. A run that stopped before here (no test - // selected, a collection error, a target that cannot record what it asks, - // an app that failed to start, an interrupt) leaves both, and + // report replaces the last. A `--last-failed` rerun keeps the evidence + // the report it reruns names instead, since that report's results fold + // into the rerun's and its carried tests do not run again, and files its + // own attempts in a fresh `rerun-` directory beside it, so no attempt + // overwrites an earlier one's files. A run that stopped before here (no + // test selected, a collection error, a target that cannot record what it + // asks, an app that failed to start, an interrupt) leaves both, and // `--last-failed` still reads the run that executed. A wipe that fails // part way has already given up the old evidence, so this run's report // records the failure. testsStarted = true; + let rerunDir: string | undefined; try { - await rm(layout.artifacts, { recursive: true, force: true }); + if (lastRun === undefined) { + await rm(layout.artifacts, { recursive: true, force: true }); + } else { + await pruneArtifacts(layout.artifacts, reportArtifactPaths(lastRun)); + rerunDir = await claimRerunDir(layout.artifacts); + } } catch (cause) { recordFailure(cause, 'launch'); return; @@ -748,6 +771,7 @@ export async function run(options: RunOptions = {}): Promise { inMemory: options.tests, runId, artifactsRoot, + rerunDir, sessionStore: store, headed: options.headed ?? false, debug, @@ -761,6 +785,7 @@ export async function run(options: RunOptions = {}): Promise { ports: config.ports, runId, artifactsRoot, + rerunDir, headed: options.headed ?? false, sessionsRoot: layout.sessions, sessionKeyBase64: store.exportKeyForWorker(), diff --git a/packages/e2e/src/run/serial.ts b/packages/e2e/src/run/serial.ts index 49936224e3..0d0392f288 100644 --- a/packages/e2e/src/run/serial.ts +++ b/packages/e2e/src/run/serial.ts @@ -13,7 +13,7 @@ import { groupTitles, type RegisteredTest } from '../collect/registry.ts'; import { pairRecordings, type SkipInfo, type TestTargetPair } from '../collect/select.ts'; import type { ResolvedTarget } from '../config/resolve.ts'; import type { ArtifactStore } from '../types.ts'; -import { createAttemptArtifacts, sanitizePathSegment } from './artifacts.ts'; +import { attemptSegments, createAttemptArtifacts, sanitizePathSegment } from './artifacts.ts'; import type { AttemptContext, ClosingRecord, SessionClose, SessionPlan } from './execute.ts'; import type { ArtifactSink } from './fixtures.ts'; import type { StepRecord } from './steps.ts'; @@ -51,6 +51,8 @@ export interface SharedSerialSession { export interface SerialHost { readonly target: ResolvedTarget; readonly artifactsRoot: string; + /** See `TargetExecutorOptions.rerunDir`. */ + readonly rerunDir: string | undefined; readonly runId: string; /** The configured artifact store, so group-owned artifacts (the shared trace) upload like any other. */ readonly artifactStore: ArtifactStore | undefined; @@ -186,13 +188,13 @@ async function runSerialAttempt( const memberRecords: SerialMemberRecord[] = []; const first = members[0]!; const recordings = pairRecordings(first, attemptIndex); - const artifactSegments = [ + const artifactSegments = attemptSegments(host.rerunDir, [ host.target.name, sanitizePathSegment(first.test.serialId ?? first.test.id), first.agent, ...repeatSegment(first.repeat), `attempt-${attemptIndex}`, - ]; + ]); const artifacts = createAttemptArtifacts({ artifactsRoot: host.artifactsRoot, segments: artifactSegments, diff --git a/packages/e2e/src/run/worker/entry.ts b/packages/e2e/src/run/worker/entry.ts index 6ce691c620..631e6005a4 100644 --- a/packages/e2e/src/run/worker/entry.ts +++ b/packages/e2e/src/run/worker/entry.ts @@ -188,6 +188,7 @@ async function bootstrap( ), runId: message.runId, artifactsRoot: message.artifactsRoot, + rerunDir: message.rerunDir, headed: message.headed, workerSlot: message.workerSlot, env: process.env, diff --git a/packages/e2e/src/run/worker/protocol.ts b/packages/e2e/src/run/worker/protocol.ts index b0968c945c..0e678b081a 100644 --- a/packages/e2e/src/run/worker/protocol.ts +++ b/packages/e2e/src/run/worker/protocol.ts @@ -61,6 +61,8 @@ export interface WorkerBootstrap { readonly workerSlot: number; readonly runId: string; readonly artifactsRoot: string; + /** See `TargetExecutorOptions.rerunDir`. */ + readonly rerunDir: string | undefined; readonly headed: boolean; readonly sessionsRoot: string; /** Per-run AES key; transferred only over this channel, never disk or env. */ diff --git a/packages/e2e/src/run/worker/session.ts b/packages/e2e/src/run/worker/session.ts index e7260f8258..17712a9d71 100644 --- a/packages/e2e/src/run/worker/session.ts +++ b/packages/e2e/src/run/worker/session.ts @@ -41,6 +41,8 @@ export interface TargetWorkerDeps { readonly sessionStore: SessionStore; readonly runId: string; readonly artifactsRoot: string; + /** See `TargetExecutorOptions.rerunDir`. */ + readonly rerunDir: string | undefined; readonly headed: boolean; /** See `TargetExecutorOptions.workerSlot`. */ readonly workerSlot: number; @@ -102,6 +104,7 @@ export class TargetWorker { target: deps.target, runId: deps.runId, artifactsRoot: deps.artifactsRoot, + rerunDir: deps.rerunDir, sessionStore: deps.sessionStore, headed: deps.headed, workerSlot: deps.workerSlot, diff --git a/packages/e2e/tests/integration/output.test.ts b/packages/e2e/tests/integration/output.test.ts index fc350b4427..8ef795ff83 100644 --- a/packages/e2e/tests/integration/output.test.ts +++ b/packages/e2e/tests/integration/output.test.ts @@ -1,18 +1,20 @@ /** * `output` and `--output`: every result a run writes lands under one * directory, the artifact tree is cleared once a run's tests start (a run - * that stops before leaves the last run's evidence), `--last-failed` reads - * the report there, and a store's `putLink` receives the recordings a - * hosted service keeps. + * that stops before leaves the last run's evidence, and a `--last-failed` + * rerun keeps what the report it reruns names), `--last-failed` reads the + * report there, and a store's `putLink` receives the recordings a hosted + * service keeps. */ -import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { createHash } from 'node:crypto'; +import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; import path from 'node:path'; import { describe, expect, it } from 'vitest'; import { createFakeEngine, FAKE_APP, FAKE_APP_URL } from '../helpers/fake-engine.ts'; import { engineConfig } from '../helpers/fixture-config.ts'; import { assertValidReport } from '../helpers/report-schema.ts'; -import { createProject, resultByTitle, runExisting, runProject } from '../helpers/run-project.ts'; +import { createProject, resultByTitle, runExisting, runProject, type RunOutcome } from '../helpers/run-project.ts'; import type { StoredArtifact, StoredArtifactLink } from '../../src/index.ts'; const PASSING_TEST = `import { test } from 'e2e'; @@ -106,6 +108,50 @@ describe('output', () => { 60_000, ); + it( + 'keeps the evidence a --last-failed rerun folds in, byte for byte, and files the rerun\'s own beside it', + async () => { + const project = createProject({ 'tests/pass.e2e.ts': PASSING_TEST, 'tests/fail.e2e.ts': FAILING_TEST }); + try { + const config = engineConfig(createFakeEngine({ artifacts: true }).engine); + const artifacts = path.join(project.dir, '.e2e', 'artifacts'); + const screenshotOf = (outcome: RunOutcome) => + resultByTitle(outcome, 'fails on purpose').attempts[0]!.artifacts.find((artifact) => artifact.kind === 'screenshot')!; + const onDisk = (artifact: { path?: string | undefined; sha256?: string | undefined }) => + createHash('sha256').update(readFileSync(path.join(artifacts, artifact.path!))).digest('hex') === artifact.sha256; + + const first = await runExisting(project, { appUrl: FAKE_APP_URL, config }); + const firstShot = screenshotOf(first); + expect(firstShot.path).toMatch(/^fake\/.*\/attempt-0\//); + const planted = path.join(artifacts, 'fake', 'planted.txt'); + writeFileSync(planted, 'named by no report'); + + const rerun = await runExisting(project, { appUrl: FAKE_APP_URL, config, runOptions: { lastFailed: true } }); + expect(rerun.status).toBe('failed'); + const rerunShot = screenshotOf(rerun); + expect(rerunShot.path).toBe(`rerun-1/${firstShot.path}`); + expect(onDisk(firstShot)).toBe(true); + expect(onDisk(rerunShot)).toBe(true); + expect(existsSync(planted)).toBe(false); + assertValidReport(rerun.report); + + // The next rerun keeps what the report it reruns names, the first run's evidence no more. + const again = await runExisting(project, { appUrl: FAKE_APP_URL, config, runOptions: { lastFailed: true } }); + expect(screenshotOf(again).path).toBe(`rerun-2/${firstShot.path}`); + expect(onDisk(rerunShot)).toBe(true); + expect(existsSync(path.join(artifacts, firstShot.path!))).toBe(false); + + // A full run starts from an empty tree, at the root again. + const full = await runExisting(project, { appUrl: FAKE_APP_URL, config }); + expect(screenshotOf(full).path).toBe(firstShot.path); + expect(readdirSync(artifacts)).toEqual(['fake']); + } finally { + project.cleanup(); + } + }, + 60_000, + ); + it( "keeps the last run's report and artifacts when a run stops before its tests start", async () => { diff --git a/packages/e2e/tests/integration/runner-lifecycle.test.ts b/packages/e2e/tests/integration/runner-lifecycle.test.ts index 2b8a47e596..3fd62d7818 100644 --- a/packages/e2e/tests/integration/runner-lifecycle.test.ts +++ b/packages/e2e/tests/integration/runner-lifecycle.test.ts @@ -1147,6 +1147,127 @@ test('fails', async () => { 120_000, ); + it( + '--last-failed keeps owing what the failure limit or another filter left out until a run carries it out', + async () => { + const failing = (title: string) => `import { test } from 'e2e'; +test('${title}', async () => { + throw new Error('${title} is broken'); +}); +`; + const project = createProject({ 'tests/first.e2e.ts': failing('first'), 'tests/second.e2e.ts': failing('second') }); + const config = { tests: 'tests/**/*.e2e.ts', workers: 1 }; + const selection = (outcome: RunOutcome) => + outcome.results.toSorted((a, b) => (a.test.file < b.test.file ? -1 : 1)).map((result) => [result.test.title, result.selected, result.status, result.skip?.cause]); + + const limited = await runExisting(project, { appUrl: app.url, config, runOptions: { maxFailures: 1 } }); + expect(limited.exitCode).toBe(1); + expect(selection(limited)).toEqual([ + ['first', true, 'failed', undefined], + ['second', true, 'skipped', 'failure-limit'], + ]); + + // The failure limit stopped `second` before it ran, so it is owed; a rerun narrowed to `first` carries it. + writeFileSync(path.join(project.dir, 'tests', 'first.e2e.ts'), `import { test } from 'e2e';\ntest('first', async () => {});\n`); + const rerun = await runExisting(project, { appUrl: app.url, config, runOptions: { lastFailed: true, grep: [/first/] } }); + expect(rerun.exitCode).toBe(0); + expect(selection(rerun)).toEqual([ + ['first', true, 'passed', undefined], + ['second', false, 'skipped', 'filtered'], + ]); + expect(rerun.report.run.carried?.results.map((result) => [result.titlePath.at(-1), result.status, result.skip?.cause])).toEqual([['second', 'skipped', 'failure-limit']]); + assertValidReport(rerun.report); + + // Left out by --grep, `second` is still owed: the next --last-failed runs it, and only it. + const owed = await runExisting(project, { appUrl: app.url, config, runOptions: { lastFailed: true } }); + expect(owed.exitCode).toBe(1); + expect(selection(owed)).toEqual([ + ['first', false, 'skipped', 'filtered'], + ['second', true, 'failed', undefined], + ]); + expect(owed.report.run.carried).toBeUndefined(); + project.cleanup(); + }, + 120_000, + ); + + it( + '--last-failed narrowed past a file that fails to import keeps owing its tests until a run carries them out', + async () => { + const failing = (title: string) => `import { test } from 'e2e'; +test('${title}', async () => { + throw new Error('${title} is broken'); +}); +`; + const project = createProject({ 'tests/first.e2e.ts': failing('first'), 'tests/second.e2e.ts': failing('second') }); + const first = await runExisting(project, { appUrl: app.url }); + expect(first.exitCode).toBe(1); + + // `second` is owed and its file no longer imports; a rerun narrowed to `first` cannot collect it, so it carries it. + writeFileSync(path.join(project.dir, 'tests', 'first.e2e.ts'), `import { test } from 'e2e';\ntest('first', async () => {});\n`); + writeFileSync(path.join(project.dir, 'tests', 'second.e2e.ts'), `import './not-written-yet.ts';\n${failing('second')}`); + const narrowed = await runExisting(project, { appUrl: app.url, runOptions: { lastFailed: true, files: ['tests/first.e2e.ts'] } }); + expect(narrowed.exitCode).toBe(0); + expect(narrowed.results.map((result) => [result.test.title, result.status])).toEqual([['first', 'passed']]); + expect(narrowed.report.run.carried?.results.map((result) => [result.titlePath.at(-1), result.status])).toEqual([['second', 'failed']]); + assertValidReport(narrowed.report); + + // Once the file imports again, the next --last-failed runs `second`, and only it. + writeFileSync(path.join(project.dir, 'tests', 'second.e2e.ts'), `import { test } from 'e2e';\ntest('second', async () => {});\n`); + const owed = await runExisting(project, { appUrl: app.url, runOptions: { lastFailed: true } }); + expect(owed.exitCode).toBe(0); + expect(owed.results.filter((result) => result.selected).map((result) => result.test.title)).toEqual(['second']); + expect(owed.report.run.carried).toBeUndefined(); + project.cleanup(); + }, + 120_000, + ); + + it( + '--last-failed carries a failed hook another filter kept from running again, until its scope runs', + async () => { + const hooks = (teardown: string) => `import { test } from 'e2e'; +test.afterAll(() => { + ${teardown} +}); +test('in the hook scope', async () => {}); +`; + const project = createProject({ + 'tests/hooks.e2e.ts': hooks(`throw new Error('teardown broke');`), + 'tests/body.e2e.ts': `import { test } from 'e2e';\ntest('body', async () => {\n throw new Error('still broken');\n});\n`, + }); + const ran = (outcome: RunOutcome) => outcome.results.filter((result) => result.selected).map((result) => [result.test.title, result.status]); + const hookScope = { file: 'tests/hooks.e2e.ts', targetId: 'web', titlePath: [] }; + + const first = await runExisting(project, { appUrl: app.url }); + expect(first.exitCode).toBe(1); + + writeFileSync(path.join(project.dir, 'tests', 'body.e2e.ts'), `import { test } from 'e2e';\ntest('body', async () => {});\n`); + const narrowed = await runExisting(project, { appUrl: app.url, runOptions: { lastFailed: true, grep: [/body/] } }); + expect(narrowed.exitCode).toBe(0); + expect(ran(narrowed)).toEqual([['body', 'passed']]); + expect(narrowed.report.run.errors).toEqual([]); + expect(narrowed.report.run.carried?.results.map((result) => result.titlePath.at(-1))).toEqual(['in the hook scope']); + expect(narrowed.report.run.carried?.errors.map((error) => [error.code, error.phase, error.scope])).toEqual([['HOOK_FAILED', 'afterAll', hookScope]]); + assertValidReport(narrowed.report); + + // The scope runs again and the hook still fails: reported by the run itself, carried no more. + const again = await runExisting(project, { appUrl: app.url, runOptions: { lastFailed: true } }); + expect(again.exitCode).toBe(1); + expect(ran(again)).toEqual([['in the hook scope', 'passed']]); + expect(again.report.run.errors.map((error) => [error.code, error.scope])).toEqual([['HOOK_FAILED', hookScope]]); + expect(again.report.run.carried).toBeUndefined(); + + writeFileSync(path.join(project.dir, 'tests', 'hooks.e2e.ts'), hooks('')); + const fixed = await runExisting(project, { appUrl: app.url, runOptions: { lastFailed: true } }); + expect(fixed.exitCode).toBe(0); + expect(ran(fixed)).toEqual([['in the hook scope', 'passed']]); + expect(fixed.report.run.carried).toBeUndefined(); + project.cleanup(); + }, + 120_000, + ); + it( '--last-failed runs a setup whose afterAll failed again through the tests that consume its session', async () => { @@ -1182,12 +1303,19 @@ test('unrelated', async () => { writeFileSync(path.join(project.dir, 'tests', 'other.e2e.ts'), `import { test } from 'e2e'; test('unrelated', async () => {}); `); + // A rerun that needs none of the setup's sessions carries its failed afterAll, with no row for the setup. + const narrowed = await runExisting(project, { appUrl: app.url, runOptions: { lastFailed: true, grep: [/unrelated/] } }); + expect(narrowed.exitCode).toBe(0); + expect(ran(narrowed)).toEqual([['unrelated', 'passed']]); + expect(narrowed.report.run.carried?.results.map((result) => [result.kind, result.titlePath.at(-1)])).toEqual([['setup', 'sign in']]); + expect(narrowed.report.run.carried?.errors.map((error) => error.code)).toEqual(['HOOK_FAILED']); + assertValidReport(narrowed.report); + const second = await runExisting(project, { appUrl: app.url, runOptions: { lastFailed: true } }); expect(second.exitCode).toBe(1); expect(ran(second)).toEqual([ ['sign in', 'passed'], ['signed in', 'passed'], - ['unrelated', 'passed'], ]); expect(second.report.run.errors.map((error) => error.code)).toEqual(['HOOK_FAILED']); diff --git a/packages/e2e/tests/types/sdk-types.ts b/packages/e2e/tests/types/sdk-types.ts index c9bbe082e0..1f570206cf 100644 --- a/packages/e2e/tests/types/sdk-types.ts +++ b/packages/e2e/tests/types/sdk-types.ts @@ -504,6 +504,10 @@ report.run.results[0]!.repeat satisfies number; // Interrupted tests are counted on their own, never in failed. report.run.summary.interrupted satisfies number; report.run.explore satisfies { goal: string; findings: readonly { severity: 1 | 2 | 3 | 4 | 5; artifactId?: string | undefined }[] } | undefined; +// A --last-failed rerun carries what it owed and left out as full results, groups, and hook errors, never a looser shape. +report.run.carried satisfies + | { results: Report['run']['results']; serialGroups: Report['run']['serialGroups']; errors: Report['run']['errors'] } + | undefined; // An explore run's events narrow to the exploration's progress. if (runEvent.type === 'explore') { diff --git a/packages/e2e/tests/unit/last-run.test.ts b/packages/e2e/tests/unit/last-run.test.ts index 30d317c1d3..1b5d99ab68 100644 --- a/packages/e2e/tests/unit/last-run.test.ts +++ b/packages/e2e/tests/unit/last-run.test.ts @@ -3,7 +3,8 @@ import os from 'node:os'; import path from 'node:path'; import { afterEach, describe, expect, it } from 'vitest'; import { resultId } from '../../src/internal/ids.ts'; -import { lastFailedIds, readLastRun } from '../../src/run/last-run.ts'; +import type { Report1Document } from '../../src/report/build.ts'; +import { carryForward, lastFailedIds, readLastRun, reportArtifactPaths } from '../../src/run/last-run.ts'; let dir: string; @@ -19,29 +20,47 @@ function reportFile(content: string): string { return file; } +type Row = Record; + /** - * A report whose results each name a test by `id` as their test id and title, - * in `tests/a.e2e.ts` on target `web` as agent `default`, selected, unless a - * result says otherwise. + * A report document whose results each name a test by `id` as their test id + * and title, in `tests/a.e2e.ts` on target `web` as agent `default`, + * selected, with no attempts, unless a result says otherwise. `run` adds or + * overrides run fields; a `carried` there gets the same result defaults. */ -function report(results: readonly Record[], errors: readonly Record[] = []): string { - return JSON.stringify({ +function document(results: readonly Row[], errors: readonly Row[] = [], run: Row = {}): Report1Document { + const row = (result: Row): Row => ({ + testId: result['id'], + titlePath: [result['id']], + file: 'tests/a.e2e.ts', + targetId: 'web', + agent: 'default', + selected: true, + attempts: [], + ...result, + }); + const carried = run['carried'] as { results: Row[]; serialGroups?: Row[]; errors?: Row[] } | undefined; + return { schemaVersion: 'report-1', run: { - results: results.map((result) => ({ - testId: result['id'], - titlePath: [result['id']], - file: 'tests/a.e2e.ts', - targetId: 'web', - agent: 'default', - selected: true, - ...result, - })), + results: results.map(row), errors, + serialGroups: [], + targets: [{ id: 'web' }, { id: 'mobile' }], + ...run, + ...(carried === undefined ? {} : { carried: { serialGroups: [], errors: [], ...carried, results: carried.results.map(row) } }), }, - }); + } as unknown as Report1Document; +} + +/** `document` as the text of a report file. */ +function report(results: readonly Row[], errors: readonly Row[] = [], run: Row = {}): string { + return JSON.stringify(document(results, errors, run)); } +/** A result the run left out with a filter. */ +const leftOut = (id: string, reason = 'title does not match --grep'): Row => ({ id, status: 'skipped', selected: false, skip: { cause: 'filtered', reason } }); + const idOf = (testId: string) => resultId(testId, 'web', 'default'); const readLastFailed = async (file: string): Promise> => lastFailedIds(await readLastRun(file)); @@ -61,11 +80,12 @@ describe('readLastRun and lastFailedIds', () => { { id: 'predecessor', status: 'skipped', skip: { cause: 'serial-predecessor-failed', reason: 'step 1 failed' } }, { id: 'hook', status: 'skipped', skip: { cause: 'hook-failed', reason: 'beforeAll failed' } }, { id: 'worker', status: 'skipped', skip: { cause: 'infrastructure-unavailable', reason: 'worker process exited' } }, + { id: 'limit', status: 'skipped', skip: { cause: 'failure-limit', reason: 'the run stopped at its failure limit' } }, { id: 'no-skip', status: 'skipped' }, ]), ), ); - expect([...ids]).toEqual(['failed', 'timed-out', 'interrupted', 'setup-failed', 'predecessor', 'hook', 'worker'].map(idOf)); + expect([...ids]).toEqual(['failed', 'timed-out', 'interrupted', 'setup-failed', 'predecessor', 'hook', 'worker', 'limit'].map(idOf)); }); it('is empty when every result passed, and names a test once however many of its repeats failed', async () => { @@ -137,8 +157,16 @@ describe('readLastRun and lastFailedIds', () => { '{"schemaVersion":"report-1","run":{"results":[{"id":"a"}]}}', '{"schemaVersion":"report-1","run":{"results":[{"id":"a","status":"skipped","skip":"later"}]}}', '{"schemaVersion":"report-1","run":{"results":[]}}', - '{"schemaVersion":"report-1","run":{"results":[],"errors":[{"phase":1}]}}', - '{"schemaVersion":"report-1","run":{"results":[],"errors":[{"phase":"afterAll","scope":{"file":"a.e2e.ts","targetId":"web"}}]}}', + '{"schemaVersion":"report-1","run":{"results":[],"errors":[]}}', + '{"schemaVersion":"report-1","run":{"results":[],"errors":[{"phase":1}],"serialGroups":[]}}', + '{"schemaVersion":"report-1","run":{"results":[],"errors":[{"phase":"afterAll","scope":{"file":"a.e2e.ts","targetId":"web"}}],"serialGroups":[]}}', + '{"schemaVersion":"report-1","run":{"results":[{"id":"a","status":"passed","file":"a.e2e.ts","titlePath":["a"]}],"errors":[],"serialGroups":[]}}', + '{"schemaVersion":"report-1","run":{"results":[{"id":"a","status":"passed","file":"a.e2e.ts","titlePath":["a"],"attempts":[{}]}],"errors":[],"serialGroups":[]}}', + '{"schemaVersion":"report-1","run":{"results":[{"id":"a","status":"passed","file":"a.e2e.ts","titlePath":["a"],"attempts":[{"artifacts":[null]}]}],"errors":[],"serialGroups":[]}}', + '{"schemaVersion":"report-1","run":{"results":[{"id":"a","status":"passed","file":"a.e2e.ts","titlePath":["a"],"attempts":[{"artifacts":[{"path":1}]}]}],"errors":[],"serialGroups":[]}}', + '{"schemaVersion":"report-1","run":{"results":[],"errors":[],"serialGroups":[{"id":"g"}]}}', + '{"schemaVersion":"report-1","run":{"results":[],"errors":[],"serialGroups":[],"carried":{"results":[{"id":"a"}],"errors":[],"serialGroups":[]}}}', + '{"schemaVersion":"report-1","run":{"results":[],"errors":[],"serialGroups":[],"carried":{"results":[]}}}', ]) { await expect(readLastRun(reportFile(content)), content).rejects.toMatchObject({ code: 'NO_LAST_RUN', @@ -147,3 +175,121 @@ describe('readLastRun and lastFailedIds', () => { } }); }); + +describe('carryForward', () => { + /** `carryForward` with the rerun having collected the tests its report has rows for, unless `collected` says more, and failed to collect `uncollected`. */ + const carry = (lastRun: Report1Document, current: Report1Document, collected: readonly string[] = [], uncollected: readonly string[] = []) => + carryForward(lastRun, current, { + testIds: new Set([...current.run.results.map((result) => result.testId), ...collected]), + uncollectedFiles: new Set(uncollected), + }); + const failed = (id: string, extra: Row = {}): Row => ({ id, status: 'failed', attempts: [{ artifacts: [{ path: `web/${id}/attempt-0/failure.png` }] }], ...extra }); + const passed = (id: string, extra: Row = {}): Row => ({ id, status: 'passed', attempts: [{ artifacts: [] }], ...extra }); + const carriedIds = (carried: ReturnType) => carried?.results.map((result) => result.testId); + const scope = { file: 'tests/a.e2e.ts', targetId: 'web', titlePath: ['teardown'] }; + const afterAll = { code: 'HOOK_FAILED', phase: 'afterAll', scopeId: 'teardown', scope }; + const inScope = (status: (id: string, extra?: Row) => Row) => status('in-scope', { titlePath: ['teardown', 'in-scope'] }); + + it('carries what the run before owed and another filter left out, as that run reported it', () => { + const before = document([failed('broken'), { id: 'limit', status: 'skipped', skip: { cause: 'failure-limit', reason: 'stopped' } }, passed('fine')]); + const carried = carry(before, document([passed('broken'), leftOut('limit'), leftOut('fine', 'did not fail in the last run')])); + expect(carriedIds(carried)).toEqual(['limit']); + expect(carried?.results[0]).toEqual(before.run.results[1]); + expect(carried?.errors).toEqual([]); + // What the rerun ran is its own result now, passed or not; nothing owed left out is nothing carried. + expect(carry(before, document([failed('broken'), passed('limit'), leftOut('fine')]))).toBeUndefined(); + }); + + it('keeps a test owed across consecutive reruns until one runs it, and the next --last-failed selects it', () => { + const first = document([failed('a'), failed('b')]); + const carriedOnce = carry(first, document([passed('a'), leftOut('b')])); + expect(carriedIds(carriedOnce)).toEqual(['b']); + const second = document([passed('a'), leftOut('b')], [], { carried: carriedOnce }); + expect([...lastFailedIds(second)]).toEqual([idOf('b')]); + + // Left out again: still the first run's row, not the filtered one in between. + expect(carry(second, document([leftOut('a', 'did not fail in the last run'), leftOut('b')]))?.results).toEqual([first.run.results[1]]); + // Run again, it is the rerun's own result. + expect(carry(second, document([leftOut('a'), passed('b')]))).toBeUndefined(); + // A test the rerun no longer has cannot run again. + expect(carry(second, document([leftOut('a')]))).toBeUndefined(); + }); + + it('carries a suite hook failure while its scope holds a carried test, and drops it once the scope ran again', () => { + const before = document([inScope(passed), failed('elsewhere', { file: 'tests/b.e2e.ts' })], [afterAll, { code: 'CLEANUP_TIMEOUT', phase: 'cleanup' }]); + const narrowed = carry(before, document([leftOut('in-scope'), passed('elsewhere', { file: 'tests/b.e2e.ts' })])); + expect(carriedIds(narrowed)).toEqual(['in-scope']); + expect(narrowed?.errors).toEqual([afterAll]); + + // The scope ran again and the hook passed: resolved. It failed again: the rerun reports it itself, once. + const elsewhere = passed('elsewhere', { file: 'tests/b.e2e.ts' }); + expect(carry(before, document([inScope(passed), elsewhere]))).toBeUndefined(); + expect(carry(before, document([inScope(passed), elsewhere], [afterAll]))).toBeUndefined(); + + // A hook failure carried from further back stays carried with its scope. + const second = document([leftOut('in-scope'), passed('elsewhere', { file: 'tests/b.e2e.ts' })], [], { carried: narrowed }); + expect(carry(second, document([leftOut('in-scope'), leftOut('elsewhere')]))?.errors).toEqual([afterAll]); + }); + + it('resolves a hook whose scope ran again without it failing, though another filter left part of the scope out', () => { + const sibling = (status: (id: string, extra?: Row) => Row) => status('sibling', { titlePath: ['teardown', 'sibling'] }); + const before = document([inScope(passed), sibling(passed)], [afterAll]); + expect(carry(before, document([inScope(passed), leftOut('sibling')]))).toBeUndefined(); + // Failing again it is the rerun's own error, and the sibling it left out stays owed. + const again = carry(before, document([inScope(passed), leftOut('sibling')], [afterAll])); + expect(carriedIds(again)).toEqual(['sibling']); + expect(again?.errors).toEqual([]); + // A scope test the rerun selected but never ran does not show the hook passing. + const limited = { id: 'in-scope', titlePath: ['teardown', 'in-scope'], status: 'skipped', skip: { cause: 'failure-limit', reason: 'stopped' } }; + expect(carry(before, document([limited, leftOut('sibling')]))?.errors).toEqual([afterAll]); + }); + + it('carries a test on a target or agent the rerun did not select, while the test and the target are still there', () => { + const before = document([failed('a'), failed('a', { targetId: 'mobile', id: 'a-mobile', testId: 'a' }), failed('a', { agent: 'other', id: 'a-other', testId: 'a' })]); + const onWeb = carry(before, document([passed('a')])); + expect(onWeb?.results.map((result) => [result.targetId, result.agent])).toEqual([ + ['mobile', 'default'], + ['web', 'other'], + ]); + // A target the config no longer has cannot run it again. + expect(carry(before, document([passed('a'), passed('a', { agent: 'other', id: 'a-other', testId: 'a' })], [], { targets: [{ id: 'web' }] }))).toBeUndefined(); + }); + + it('carries a setup whose afterAll failed when the rerun needed none of its sessions, so the report has no row for it', () => { + const setupScope = { ...afterAll, scopeId: 'file', scope: { file: 'tests/auth.e2e.ts', targetId: 'web', titlePath: [] } }; + const signIn = passed('sign in', { kind: 'setup', file: 'tests/auth.e2e.ts' }); + const before = document([signIn, passed('signed in'), failed('unrelated')], [setupScope]); + const narrowed = document([leftOut('signed in'), passed('unrelated')]); + const carried = carry(before, narrowed, ['sign in']); + expect(carriedIds(carried)).toEqual(['sign in']); + expect(carried?.errors).toEqual([setupScope]); + // A setup the rerun no longer collects is gone with its debt. + expect(carry(before, narrowed)).toBeUndefined(); + }); + + it('carries a test in a file a narrowed rerun found but could not collect, and drops it once the file is gone', () => { + const before = document([failed('a'), failed('b', { file: 'tests/b.e2e.ts' })]); + const narrowed = document([passed('a')]); + expect(carriedIds(carry(before, narrowed, [], ['tests/b.e2e.ts']))).toEqual(['b']); + expect(carry(before, narrowed)).toBeUndefined(); + }); + + it("carries a serial member's group, where its attempts live", () => { + const group = { id: 'group', attempts: [{ artifacts: [{ path: 'web/group/attempt-0/trace.zip' }] }] }; + const before = document([failed('member', { serialGroupId: 'group', attempts: [] }), failed('other')], [], { serialGroups: [group] }); + const carried = carry(before, document([leftOut('member'), passed('other')])); + expect(carriedIds(carried)).toEqual(['member']); + expect(carried?.serialGroups).toEqual([group]); + }); + + it('names every artifact file a report points at, its carried ones included', () => { + const group = { id: 'group', attempts: [{ artifacts: [{ path: 'web/group/attempt-0/trace.zip' }, { url: 'https://hosted.example/v.mp4' }] }] }; + const carried = { results: [failed('old')], serialGroups: [group] }; + const paths = reportArtifactPaths(document([failed('new'), passed('fine')], [], { carried })); + expect([...paths].toSorted()).toEqual(['web/group/attempt-0/trace.zip', 'web/new/attempt-0/failure.png', 'web/old/attempt-0/failure.png']); + }); + + it('reads the tests a report carries back as ones to run again', async () => { + expect([...(await readLastFailed(reportFile(report([passed('a')], [], { carried: { results: [failed('owed')] } }))))]).toEqual([idOf('owed')]); + }); +}); diff --git a/packages/e2e/tests/unit/rerun-artifacts.test.ts b/packages/e2e/tests/unit/rerun-artifacts.test.ts new file mode 100644 index 0000000000..53feabdcd2 --- /dev/null +++ b/packages/e2e/tests/unit/rerun-artifacts.test.ts @@ -0,0 +1,88 @@ +/** + * The artifact tree a `--last-failed` rerun starts from: the files the report + * it reruns names stay byte for byte, everything else goes, and the rerun's + * own attempts get a `rerun-` directory no earlier run wrote into. + */ + +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { attemptSegments, claimRerunDir, pruneArtifacts } from '../../src/run/artifacts.ts'; + +let root: string; + +beforeEach(() => { + root = path.join(mkdtempSync(path.join(os.tmpdir(), 'e2e-rerun-artifacts-')), 'artifacts'); +}); + +afterEach(() => { + rmSync(path.dirname(root), { recursive: true, force: true }); +}); + +/** Writes a file at a report path under the root, with the path as its content. */ +function plant(reportPath: string): void { + const file = path.join(root, ...reportPath.split('/')); + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, reportPath); +} + +/** Every file under the root, as report paths, sorted. */ +function tree(): string[] { + return (readdirSync(root, { recursive: true, withFileTypes: true }) as { name: string; parentPath: string; isFile(): boolean }[]) + .filter((entry) => entry.isFile()) + .map((entry) => path.relative(root, path.join(entry.parentPath, entry.name)).split(path.sep).join('/')) + .toSorted(); +} + +describe('pruneArtifacts', () => { + it('keeps exactly the files the report names, untouched, and removes the rest and the directories left empty', async () => { + const kept = ['web/a/default/attempt-0/screenshots/001-landing.png', 'web/b/default/attempt-0/trace/trace.zip', 'rerun-1/web/b/default/attempt-0/failure/screen.txt']; + const dropped = ['web/a/default/attempt-0/stray.log', 'web/c/default/attempt-0/trace/trace.zip', 'web/sessions/0192/screen.png', 'top-level.txt']; + for (const file of [...kept, ...dropped]) plant(file); + + await pruneArtifacts(root, new Set(kept)); + + expect(tree()).toEqual(kept.toSorted()); + for (const file of kept) expect(readFileSync(path.join(root, file), 'utf8')).toBe(file); + expect(existsSync(path.join(root, 'web', 'c'))).toBe(false); + expect(existsSync(path.join(root, 'web', 'sessions'))).toBe(false); + }); + + it('empties the tree when the report names nothing, and accepts a tree that is not there', async () => { + plant('web/a/default/attempt-0/screenshots/001.png'); + await pruneArtifacts(root, new Set()); + expect(tree()).toEqual([]); + rmSync(root, { recursive: true }); + await expect(pruneArtifacts(root, new Set(['web/a.png']))).resolves.toBeUndefined(); + }); +}); + +describe('claimRerunDir', () => { + it('claims rerun-1 in a tree without one, then the number past the highest there, never one that exists', async () => { + plant('web/a/default/attempt-0/x.png'); + expect(await claimRerunDir(root)).toBe('rerun-1'); + expect(await claimRerunDir(root)).toBe('rerun-2'); + // An earlier rerun's directory pruned away does not bring its number back. + rmSync(path.join(root, 'rerun-1'), { recursive: true }); + expect(await claimRerunDir(root)).toBe('rerun-3'); + // Names that only look alike, a target called that way among them, do not count. + mkdirSync(path.join(root, 'rerun-07')); + mkdirSync(path.join(root, 'rerun-x')); + expect(await claimRerunDir(root)).toBe('rerun-4'); + expect(readdirSync(root).toSorted()).toEqual(['rerun-07', 'rerun-2', 'rerun-3', 'rerun-4', 'rerun-x', 'web']); + }); + + it('creates the root when the tree is not there', async () => { + expect(await claimRerunDir(root)).toBe('rerun-1'); + expect(existsSync(path.join(root, 'rerun-1'))).toBe(true); + }); +}); + +describe('attemptSegments', () => { + it("files a rerun's attempt under its directory, and a full run's at the root", () => { + const segments = ['web', 'tests_a.e2e.ts__a', 'default', 'attempt-0']; + expect(attemptSegments(undefined, segments)).toEqual(segments); + expect(attemptSegments('rerun-2', segments)).toEqual(['rerun-2', ...segments]); + }); +}); diff --git a/packages/e2e/tests/unit/schema-fixtures.test.ts b/packages/e2e/tests/unit/schema-fixtures.test.ts index c3b6b00f4b..05daf90fb7 100644 --- a/packages/e2e/tests/unit/schema-fixtures.test.ts +++ b/packages/e2e/tests/unit/schema-fixtures.test.ts @@ -80,6 +80,18 @@ describe.each(schemas)('%s schema', (name) => { expect(validate.errors).toEqual(expect.arrayContaining([expect.objectContaining({ keyword: 'required', params: { missingProperty: 'interrupted' } })])); }); + it('lets a --last-failed rerun carry results, serial groups, and hook failures, at least one result of them', () => { + const report = readJson('fixtures', 'report-v1.valid.json') as { run: { carried?: Record } }; + const carried = report.run.carried!; + expect((carried['results'] as unknown[]).length).toBeGreaterThan(0); + for (const bad of [{ results: [] }, { serialGroups: undefined }, { errors: undefined }, { results: [{}] }, { extra: true }]) { + report.run.carried = { ...carried, ...bad }; + expect(validate(report), JSON.stringify(bad)).toBe(false); + } + delete report.run.carried; + expect(validate(report)).toBe(true); + }); + it('requires judgment evidence after a model call, while allowing capture failures before one', () => { const report = readJson('fixtures', 'report-v1.valid.json') as { run: { results: { attempts: { steps: { api: string; status: string; metrics: { modelCalls: number }; observationRevision?: string; explanation?: string }[] }[] }[] }; diff --git a/packages/e2e/tests/unit/worker-handle.test.ts b/packages/e2e/tests/unit/worker-handle.test.ts index bab5c51e12..7c95b3542c 100644 --- a/packages/e2e/tests/unit/worker-handle.test.ts +++ b/packages/e2e/tests/unit/worker-handle.test.ts @@ -58,6 +58,7 @@ describe('ChildProcessRunner', () => { ports: {}, runId: 'run', artifactsRoot: dir, + rerunDir: undefined, headed: false, sessionsRoot: dir, sessionKeyBase64: '', diff --git a/packages/github/src/merge.ts b/packages/github/src/merge.ts index f7d13dd68f..1ae3d4133e 100644 --- a/packages/github/src/merge.ts +++ b/packages/github/src/merge.ts @@ -72,21 +72,31 @@ function summarize(results: readonly ReportResult[], base: ReportSummary): Repor /** * The rerun folded into the run it selected from. A result the rerun has * under the same id is folded with it; a test the rerun left out keeps what - * the run before said. Results the rerun has no id for at all, the further + * the run before said, or what the rerun carries for it when an earlier run + * left it owed (`run.carried`), and so do the serial groups those results' + * attempts live on. Results the rerun has no id for at all, the further * repeats of a `--repeat-each` first pass a plain rerun ran once, fold into * the rerun's first result of that test, or stay as carried rows when the * rerun left the test out. A run before of another project leaves the rerun * as it is. The outcome is the rerun's unless a carried result failed, as a - * test another filter kept out of the rerun can have: then the page is red, - * since it lists a failure. The start is the run before's, so the footer's - * duration spans both. + * test another filter kept out of the rerun can have, or the rerun carries + * a test it owed and never ran, a failure limit's skip among them, or a + * suite hook failure whose scope it did not run again (`run.carried`). Then + * the page is red, since the suite is not known to pass. A carried test the + * first pass interrupted reached no verdict: it leaves the outcome alone and + * the page reads interrupted, not green. The start is the run before's, so + * the footer's duration spans both. */ export function foldLastRun(current: Report, lastRun: Report): Report { if (lastRun.run.project.id !== current.run.project.id) return current; + const carried = current.run.carried; + const carriedById = new Map((carried?.results ?? []).map((result) => [result.id, result])); const currentIds = new Set(current.run.results.map((result) => result.id)); - const beforeById = new Map(lastRun.run.results.map((result) => [result.id, result])); + // The run before's own carried rows stand for the tests it left out, over their filtered rows. + const before = [...lastRun.run.results, ...(lastRun.run.carried?.results ?? [])]; + const beforeById = new Map(before.map((result) => [result.id, result])); const leftovers = new Map(); - for (const result of lastRun.run.results) { + for (const result of beforeById.values()) { if (currentIds.has(result.id)) continue; const key = testKey(result); leftovers.set(key, [...(leftovers.get(key) ?? []), result]); @@ -98,26 +108,32 @@ export function foldLastRun(current: Report, lastRun: Report): Report { const results: ReportResult[] = []; for (const result of current.run.results) { - const before = beforeById.get(result.id); + const previous = beforeById.get(result.id); if (!result.selected) { - results.push(before ?? result); + results.push(carriedById.get(result.id) ?? previous ?? result); continue; } const key = testKey(result); const extra = firstOfKey.get(key) === result.id ? (leftovers.get(key) ?? []) : []; if (extra.length > 0) leftovers.delete(key); - results.push(foldRerun(result, before === undefined ? extra : [before, ...extra])); + results.push(foldRerun(result, previous === undefined ? extra : [previous, ...extra])); } for (const extra of leftovers.values()) results.push(...extra); - const beforeGroups = new Map(lastRun.run.serialGroups.map((group) => [group.id, group])); + const beforeGroups = new Map([...lastRun.run.serialGroups, ...(lastRun.run.carried?.serialGroups ?? [])].map((group) => [group.id, group])); const currentGroupIds = new Set(current.run.serialGroups.map((group) => group.id)); + const carriedGroups = (carried?.serialGroups ?? []).filter((group) => !currentGroupIds.has(group.id) && !beforeGroups.has(group.id)); const serialGroups = [ - ...lastRun.run.serialGroups.filter((group) => !currentGroupIds.has(group.id)), + ...[...beforeGroups.values()].filter((group) => !currentGroupIds.has(group.id)), + ...carriedGroups, ...current.run.serialGroups.map((group) => foldGroup(group, beforeGroups.get(group.id))), ]; - const carriedFailure = results.some((result) => result.selected && FAILED_STATUSES.has(result.status)); + const carriedErrors = carried?.errors ?? []; + const carriedFailure = + carriedErrors.length > 0 || + [...carriedById.values()].some((result) => result.status !== 'interrupted') || + results.some((result) => result.selected && FAILED_STATUSES.has(result.status)); return { ...current, run: { @@ -127,6 +143,7 @@ export function foldLastRun(current: Report, lastRun: Report): Report { startedAt: lastRun.run.startedAt, serialGroups, results, + errors: [...current.run.errors, ...carriedErrors], summary: summarize(results, current.run.summary), }, }; diff --git a/packages/github/tests/unit/fixtures.ts b/packages/github/tests/unit/fixtures.ts index 73e38930c6..ab2b117ce0 100644 --- a/packages/github/tests/unit/fixtures.ts +++ b/packages/github/tests/unit/fixtures.ts @@ -99,6 +99,8 @@ export function report( readonly serialGroups?: readonly ReportSerialGroup[]; readonly targets?: readonly string[]; readonly projectId?: string; + /** What a `--last-failed` rerun carries; the fixture's own carried section is never inherited. */ + readonly carried?: ReportRun['carried']; } = {}, ): Report { const status = input.status ?? 'passed'; @@ -117,6 +119,7 @@ export function report( serialGroups: input.serialGroups ?? [], results, errors: input.errors ?? [], + carried: input.carried, }, }; } diff --git a/packages/github/tests/unit/merge.test.ts b/packages/github/tests/unit/merge.test.ts index 147c40cb72..bff69a72d9 100644 --- a/packages/github/tests/unit/merge.test.ts +++ b/packages/github/tests/unit/merge.test.ts @@ -7,6 +7,7 @@ import { attempt, report, result } from './fixtures.ts'; type ReportSerialGroup = Report['run']['serialGroups'][number]; type ReportSerialAttempt = ReportSerialGroup['attempts'][number]; +type ReportError = Report['run']['errors'][number]; const failedAttempt = attempt({ status: 'failed', error: { code: 'ASSERTION_FAILED', message: 'no cart' } }); const leftOut = { cause: 'filtered' as const, reason: 'did not fail in the last run' }; @@ -190,6 +191,13 @@ describe('foldLastRun', () => { expect(folded.run.summary).toMatchObject({ selected: 2, passed: 1, failed: 0, interrupted: 1, flaky: 0, skipped: 0 }); expect(folded.run.status).toBe('passed'); expect(renderMarkdownReport(folded)).toContain('### ⏹️ e2e: 1 interrupted, 1 passed'); + + // The runner carries B, still owed; a carried interrupted test reached no verdict, so it does not red the page. + const carryingB = report({ results: onlyA.run.results, carried: { results: [before.run.results[1]!], serialGroups: [], errors: [] } }); + const foldedCarried = foldLastRun(carryingB, before); + expect(byTitle(foldedCarried).get('B#0')).toMatchObject({ status: 'interrupted', selected: true }); + expect(foldedCarried.run).toMatchObject({ status: 'passed', exitCode: 0 }); + expect(renderMarkdownReport(foldedCarried)).toContain('### ⏹️ e2e: 1 interrupted, 1 passed'); }); it('keeps the first pass\'s failure when the rerun of that test is interrupted', () => { @@ -202,6 +210,79 @@ describe('foldLastRun', () => { expect(renderMarkdownReport(folded)).toContain('### 🔴 e2e: 1 failed'); }); + it('keeps the page red while the rerun carries a hook failure or a failed test it did not run again, with their evidence', () => { + const scope = { file: 'tests/a.e2e.ts', targetId: 'web', titlePath: [] }; + const hook: ReportError = { category: 'test', code: 'HOOK_FAILED', message: 'afterAll failed: teardown broke', retryable: false, phase: 'afterAll', scopeId: 'file', scope }; + const evidence = attempt({ artifacts: ['screenshot'] }); + const inHookScope = result({ title: 'A', file: 'tests/a.e2e.ts', status: 'passed', attempts: [evidence] }); + const before = report({ status: 'failed', results: [inHookScope, result({ title: 'B', status: 'failed', attempts: [failedAttempt] })], errors: [hook] }); + const onlyB = report({ + results: [ + result({ title: 'A', file: 'tests/a.e2e.ts', status: 'skipped', selected: false, skip: { cause: 'filtered', reason: 'title does not match --grep' } }), + result({ title: 'B', status: 'passed', attempts: [attempt()] }), + ], + carried: { results: [inHookScope], serialGroups: [], errors: [hook] }, + }); + const folded = foldLastRun(onlyB, before); + expect(byTitle(folded).get('A#0')).toEqual(inHookScope); + expect(byTitle(folded).get('B#0')).toMatchObject({ status: 'flaky' }); + expect(folded.run.errors).toEqual([hook]); + expect(folded.run.status).toBe('failed'); + expect(folded.run.exitCode).toBe(1); + const page = renderMarkdownReport(folded); + expect(page).toContain('### 🔴 e2e: 1 flaky, 1 passed'); + expect(page).toContain('HOOK_FAILED'); + + // A carried test that failed reds the page on its own. + const carriedFailure = result({ title: 'C', status: 'failed', attempts: [failedAttempt] }); + const withFailure = report({ + results: [result({ title: 'C', status: 'skipped', selected: false, skip: leftOut }), result({ title: 'B', status: 'passed', attempts: [attempt()] })], + carried: { results: [carriedFailure], serialGroups: [], errors: [] }, + }); + expect(foldLastRun(withFailure, report({ results: [result({ title: 'B', status: 'skipped', selected: false, skip: leftOut })] })).run.status).toBe('failed'); + + // So does one the failure limit stopped before it ever ran. + const neverRan = result({ title: 'D', status: 'skipped', skip: { cause: 'failure-limit', reason: 'run stopped after 1 failure (--max-failures 1)' } }); + const withLimit = report({ + results: [result({ title: 'D', status: 'skipped', selected: false, skip: leftOut }), result({ title: 'B', status: 'passed', attempts: [attempt()] })], + carried: { results: [neverRan], serialGroups: [], errors: [] }, + }); + expect(foldLastRun(withLimit, report({ results: [result({ title: 'B', status: 'skipped', selected: false, skip: leftOut })] })).run).toMatchObject({ status: 'failed', exitCode: 1 }); + }); + + it('reads a test the run before carried by the row it carried, so a rerun that runs it at last folds in its first failure', () => { + const firstFailure = result({ title: 'A', status: 'failed', attempts: [failedAttempt] }); + const narrowed = report({ + results: [ + result({ title: 'A', status: 'skipped', selected: false, skip: { cause: 'filtered', reason: 'title does not match --grep' } }), + result({ title: 'B', status: 'passed', attempts: [attempt()] }), + ], + carried: { results: [firstFailure], serialGroups: [], errors: [] }, + }); + const atLast = report({ + results: [result({ title: 'A', status: 'passed', attempts: [attempt()] }), result({ title: 'B', status: 'skipped', selected: false, skip: leftOut })], + }); + const folded = foldLastRun(atLast, narrowed); + expect(byTitle(folded).get('A#0')).toMatchObject({ status: 'flaky' }); + expect(byTitle(folded).get('A#0')?.attempts.map((entry) => entry.status)).toEqual(['failed', 'passed']); + expect(byTitle(folded).get('B#0')).toMatchObject({ status: 'passed', selected: true }); + expect(folded.run.status).toBe('passed'); + }); + + it("shows a carried serial member's group, where its attempts live", () => { + const memberTestId = 'tests/example.e2e.ts::wizard::step%20one'; + const member = result({ title: ['wizard', 'step one'], status: 'failed', serialGroupId: 'g1' }); + const group = serialGroup('g1', memberTestId, 'failed'); + const narrowed = report({ + results: [{ ...member, status: 'skipped', selected: false, skip: { cause: 'filtered', reason: 'title does not match --grep' } }], + carried: { results: [member], serialGroups: [group], errors: [] }, + }); + const folded = foldLastRun(narrowed, report({ results: [{ ...member, status: 'skipped', selected: false, skip: leftOut }] })); + expect(folded.run.serialGroups).toEqual([group]); + expect(folded.run.status).toBe('failed'); + expect(renderMarkdownReport(folded)).toContain('step one broke'); + }); + it('leaves the rerun alone when the run before is another project\'s', () => { const other = report({ projectId: 'dev.example.other', status: 'failed', results: firstPass.run.results }); expect(foldLastRun(rerun, other)).toBe(rerun); diff --git a/skills/e2e/references/running.md b/skills/e2e/references/running.md index fe8841fef5..5093e42c83 100644 --- a/skills/e2e/references/running.md +++ b/skills/e2e/references/running.md @@ -27,7 +27,7 @@ npx e2e telemetry [disable|enable] # anonymous usage telemetry: status or switch | `--tag ` | Any of the tags, comma-separated or repeated; all of them with `--tag-mode all`. An empty `--target`, `--tag`, or `--agent` value is a usage error, exit 2. | | `--exclude-tag ` | Drop tests carrying any of these tags, however selected. | | `--grep `, `--grep-invert ` | Keep, or drop, tests whose title (describe titles and test title joined by spaces, `checkout pays`; not file or tags) matches a regular expression. Bare pattern or `'/pattern/i'`; repeat for alternatives. | -| `--last-failed` | The tests the previous run (`/report.json`) did not pass, plus every test in a failed `beforeAll` or `afterAll` scope. No report is `NO_LAST_RUN`, exit 2. | +| `--last-failed` | The tests the previous run (`/report.json`) did not pass or never ran (`--max-failures` included), plus every test in a failed `beforeAll` or `afterAll` scope. A test another filter leaves out stays owed (`run.carried` in the report) until a rerun runs it. No report is `NO_LAST_RUN`, exit 2. | | `--shard ` | One contiguous slice of the selected tests (`--shard 2/3`), cut after every other filter; serial groups stay whole, each shard brings its own setup tests. | | `--headed` | Visible browser or simulator when the engine supports it. | | `--agent ` | Run unpinned tests as these `agents.` entries (default `agents.default`), comma-separated or repeated; several names run each such test once per agent. | @@ -87,7 +87,8 @@ its own tools. `summary.md`, `failures/`, `ai-trace.json`, `sessions/`, and `artifacts/` (screenshots, Playwright traces, videos, `--debug` transcripts, downloads). `artifacts/` is cleared once a run's tests start; a run stopping before -leaves the last run's files. The report records every artifact path, a +leaves the last run's files, and a `--last-failed` rerun keeps the files +the report it reruns names and writes its own under `artifacts/rerun-/`. The report records every artifact path, a hosted service's video by URL. - `list` (default): setup steps, one line per file and target, a `Failed