Skip to content
Merged
5 changes: 5 additions & 0 deletions .changeset/cleanup-failure-exit-code.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"e2e": patch
---

A run now exits with the cleanup error's code, usually 3, when a test's cleanup failed. The list reporter shows the cleanup failure under the test and in the summary, so a CI job that goes red names the cleanup failure instead of reporting a green summary.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The changeset overstates list-reporter output for skipped tests: their cleanup failure appears in the summary but not under the test row. Say this is shown under passed or flaky tests, or update the reporter to render cleanup lines for skipped tests.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At .changeset/cleanup-failure-exit-code.md, line 5:

<comment>The changeset overstates list-reporter output for skipped tests: their cleanup failure appears in the summary but not under the test row. Say this is shown under passed or flaky tests, or update the reporter to render cleanup lines for skipped tests.</comment>

<file context>
@@ -2,4 +2,4 @@
 ---
 
-A run now exits with the cleanup error's code, usually 3, when a test's cleanup failed. The list reporter shows the cleanup failure under the test and in the summary, so a CI job that goes red names the missing artifact instead of reporting a green summary.
+A run now exits with the cleanup error's code, usually 3, when a test's cleanup failed. The list reporter shows the cleanup failure under the test and in the summary, so a CI job that goes red names the cleanup failure instead of reporting a green summary.
</file context>
Suggested change
A run now exits with the cleanup error's code, usually 3, when a test's cleanup failed. The list reporter shows the cleanup failure under the test and in the summary, so a CI job that goes red names the cleanup failure instead of reporting a green summary.
A run now exits with the cleanup error's code, usually 3, when a test's cleanup failed. The list reporter shows the cleanup failure under passed or flaky tests and in the summary, so a CI job that goes red names the cleanup failure instead of reporting a green summary.

3 changes: 3 additions & 0 deletions docs/reference/errors.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ test('upgrade to Pro', async ({ agent }) => {

- In a mixed run the highest-precedence code present wins,
`130 > 4 > 3 > 2 > 1 > 0`. The report keeps every individual result.
- A test whose cleanup failed (a required video that was not
finalized, a session that did not close) exits with that cleanup error's
code, usually 3.
- A setup assertion failure is a test failure and skips its dependents.
Missing setup infrastructure keeps its configuration or infrastructure
class.
Expand Down
3 changes: 3 additions & 0 deletions packages/e2e/src/report/list-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import type { ResultStatus } from '../run/records.ts';
import type { RecordedModel } from '../cache/trace.ts';
import type { SerializedError } from '../internal/errors.ts';
import type { StepActivity, StepEvent, StepKind, StepProgress } from '../run/steps.ts';
import type { AiUsage } from './format.ts';

Expand Down Expand Up @@ -92,6 +93,8 @@ export interface TestLine {
readonly usage: AiUsage;
readonly firstErrorLine: string | undefined;
readonly skipReason: string | undefined;
/** Cleanup-phase secondary errors of attempts whose cleanup failed. */
readonly cleanupErrors: readonly SerializedError[];
readonly steps: readonly FinishedStep[];
readonly replays: readonly ReplayNotice[];
}
Expand Down
48 changes: 43 additions & 5 deletions packages/e2e/src/report/list.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
/**
* Human-readable list reporter, styled after vitest's default reporter: one
* block per test file and target with each test's agent steps nested, a
* `Failed Tests` section with code frames, and a padded summary. On a TTY a
* `Failed Tests` section with code frames, cleanup failures shown under a
* passed test and in the summary, and a padded summary. On a TTY a
* live window below the log shows the running tree (`RunningTree`) and the
* counters.
*/
Expand All @@ -14,7 +15,7 @@ import { resultId } from '../internal/ids.ts';
import { packageVersion } from '../internal/package-version.ts';
import type { RunEvent, RunEventFact, RunEventOf, RunEventResult, SetupStep } from '../run/events.ts';
import type { AppLogRecord } from '../run/steps.ts';
import { failureBeforeSkip, type ArtifactRecord, type AttemptRecord, type FailureEvidence, type ResultStatus, type SerialGroupRecord } from '../run/records.ts';
import { cleanupErrorsOf, failureBeforeSkip, type ArtifactRecord, type AttemptRecord, type FailureEvidence, type ResultStatus, type SerialGroupRecord } from '../run/records.ts';
import type { Reporter, ReporterSummary } from '../types.ts';
import { codeFrame, userFrame } from './code-frame.ts';
import {
Expand Down Expand Up @@ -118,6 +119,8 @@ interface ResultDetails {
readonly screenPath: string | undefined;
/** What the app logged during the told attempt, as `2 errors, 1 warning`; undefined for nothing. */
readonly appLog: string | undefined;
/** Cleanup-phase secondary errors of attempts whose cleanup failed; shown under a passed or flaky test. */
readonly cleanupErrors: readonly SerializedError[];
/** Why the told attempt skipped itself, when it failed anyway. */
readonly skipReason: string | undefined;
readonly replays: readonly ReplayNotice[];
Expand Down Expand Up @@ -148,6 +151,7 @@ function attemptDetails(attempts: readonly AttemptRecord[], configured: Configur
videos: videoPaths(attempts),
...failureOf(told),
appLog: appLogTally(told?.appLog ?? []),
cleanupErrors: cleanupErrorsOf(attempts),
skipReason: told?.status === 'skipped' ? undefined : told?.skip?.reason,
replays: replayNotices(steps, configured),
};
Expand Down Expand Up @@ -201,6 +205,7 @@ function serialMemberDetails(group: SerialGroupRecord, testId: string, configure
videos: videoPaths(group.attempts),
...failureOf(own === undefined ? undefined : { failure: own.failure, artifacts: last?.attempt.artifacts ?? [] }),
appLog: appLogTally(own?.appLog ?? []),
cleanupErrors: cleanupErrorsOf(group.attempts),
skipReason: neverRan ? undefined : own.skip?.reason,
replays: replayNotices(steps, configured),
};
Expand Down Expand Up @@ -261,6 +266,8 @@ export class ListReporter implements Reporter {
private readonly skippedFailures: Failure[] = [];
/** Every result a test filter left out, in the order they arrived, for the `Left out` row. */
private readonly leftOut: { readonly testId: string; readonly skip: SkipInfo | undefined }[] = [];
/** Passed or flaky tests whose cleanup failed, for the summary's `Cleanup` row. */
private readonly cleanupFailures: { readonly title: string; readonly error: SerializedError }[] = [];
/** Every finished test's run, for the `Repeats` summary of a `--repeat-each` run. */
private readonly runs: { key: string; label: string; run: RepeatRun }[] = [];
/**
Expand Down Expand Up @@ -719,11 +726,15 @@ export class ListReporter implements Reporter {
// Read before `detailsOf` releases the result's serial group.
const skippedAfter = failureBeforeSkip(result, (id) => this.pendingSerial.get(id)?.group);
const id = resultId(result.test.id, result.target.name, result.agent, result.repeat);
const { durationMs, usage, models, cache, error, videos, failure, screenPath, appLog, skipReason, replays } = this.detailsOf(result);
const { durationMs, usage, models, cache, error, videos, failure, screenPath, appLog, skipReason, replays, cleanupErrors } =
this.detailsOf(result);
addUsage(this.runUsage, usage);
addModelTally(this.runModels, models);
addCacheTally(this.runCache, cache);
const title = this.titledAs(result.test.titlePath.join(' > '), result.agent, result.repeat);
if (cleanupErrors.length > 0) {
this.cleanupFailures.push({ title, error: cleanupErrors[0]! });
}
if (this.explore !== undefined) {
// The exploration's verdict is its findings; any other error is a failure of its own, unless the run stopped it.
this.explore.result(result.attempts.flatMap((attempt) => attempt.artifacts));
Expand All @@ -741,6 +752,7 @@ export class ListReporter implements Reporter {
usage,
firstErrorLine: error === undefined ? undefined : bounded(error.message).split('\n')[0],
skipReason: result.skip === undefined ? undefined : bounded(result.skip.reason),
cleanupErrors,
steps,
replays,
};
Expand Down Expand Up @@ -826,6 +838,7 @@ export class ListReporter implements Reporter {
counts.flaky > 0 ||
this.groups.size === 1 ||
group.lines.some((line) => line.replays.length > 0) ||
group.lines.some((line) => line.cleanupErrors.length > 0) ||
(this.live && group.lines.some((line) => line.steps.length > 0));
if (!verbose) return;
const ordered = group.lines.toSorted((a, b) => a.declarationIndex - b.declarationIndex);
Expand All @@ -844,9 +857,15 @@ export class ListReporter implements Reporter {
const ai = segment === undefined ? '' : ` ${pc.dim(segment)}`;
switch (line.status) {
case 'passed':
return [` ${pc.green(F_CHECK)} ${line.title} ${duration}${ai}`];
return [
` ${pc.green(F_CHECK)} ${line.title} ${duration}${ai}`,
...this.cleanupLines(line),
];
case 'flaky':
return [` ${pc.yellow(F_CHECK)} ${line.title} ${pc.yellow('(flaky)')} ${duration}${ai}`];
return [
` ${pc.yellow(F_CHECK)} ${line.title} ${pc.yellow('(flaky)')} ${duration}${ai}`,
...this.cleanupLines(line),
];
case 'skipped': {
// `test.skip` without a message records the bare word; repeating it adds nothing.
const reason =
Expand All @@ -870,6 +889,15 @@ export class ListReporter implements Reporter {
}
}

/** One yellow glance line per cleanup failure under the test. */
private cleanupLines(line: TestLine): string[] {
const { pc } = this;
return line.cleanupErrors.map((error) => {
const [first = ''] = bounded(error.message).split('\n');
return ` ${pc.yellow(`${F_RIGHT} cleanup failed: ${bounded(error.code)}: ${first}`)}`;
});
}

/**
* vitest's padded summary, shared by the live window and the final report:
* files, tests, model usage, the trace cache's part, run errors, start
Expand Down Expand Up @@ -904,6 +932,16 @@ export class ListReporter implements Reporter {
const count = this.errors.length;
rows.push(padTitle(pc, 'Errors') + pc.bold(pc.red(`${count} error${count === 1 ? '' : 's'}`)));
}
if (final && this.cleanupFailures.length > 0) {
const [first, ...rest] = this.cleanupFailures;
const [message = ''] = bounded(first!.error.message).split('\n');
rows.push(
padTitle(pc, 'Cleanup') +
pc.yellow(
`${this.cleanupFailures.length} cleanup failure${this.cleanupFailures.length === 1 ? '' : 's'}: ${bounded(first!.error.code)}: ${message}${rest.length === 0 ? '' : ` (+${rest.length} more)`}`,
),
);
}
const startedAt = this.startedAt ?? (final ? this.launchedAt : undefined);
if (startedAt !== undefined) {
rows.push(padTitle(pc, 'Start at') + formatClock(startedAt));
Expand Down
9 changes: 9 additions & 0 deletions packages/e2e/src/run/records.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,15 @@ export interface FailureBeforeSkip {
readonly artifacts: readonly ArtifactRecord[];
}

/** The cleanup-phase secondary errors of attempts whose cleanup failed. */
export function cleanupErrorsOf(
attempts: readonly { readonly cleanup: string; readonly secondaryErrors: readonly SerializedError[] }[],
): SerializedError[] {
return attempts.flatMap((attempt) =>
attempt.cleanup === 'failed' ? attempt.secondaryErrors.filter((secondary) => secondary.phase === 'cleanup') : [],
);
}

/**
* The failure a test's `test.skip(...)` followed: the last attempt that
* failed before a skipped retry, or an error the skipped attempt kept beside
Expand Down
7 changes: 6 additions & 1 deletion packages/e2e/src/run/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ import { writeJsonReport } from '../report/write.ts';
import { createRunEventEmitter, toEventResult, type RunEventSink, type RunExitCode, type RunStatus, type RunEventFact, type SetupOutcome, type SetupStep } from './events.ts';
import { allocateAppPorts } from './app-ports.ts';
import { inProcessSpawner } from './in-process.ts';
import { someSkippedAfterFailure, tracedResultIds, type ResultRecord, type RunError, type SerialGroupRecord } from './records.ts';
import { cleanupErrorsOf, someSkippedAfterFailure, tracedResultIds, type ResultRecord, type RunError, type SerialGroupRecord } from './records.ts';
import { runUnits } from './scheduler.ts';
import { buildWorkPlans, longestFirst, nonRunResult, plannedSlots, type TargetWorkPlan, type TimeLimit } from './units.ts';
import { SessionStore } from './sessions.ts';
Expand Down Expand Up @@ -1384,6 +1384,8 @@ function statusOf(exitCode: RunExitCode): Exclude<RunStatus, 'blocked'> {
* or its attempts' error category when that is worse. A serial group answers
* for its members, whose results carry no attempts, and for a group attempt
* that failed before any member ran (a launch), whose members are skipped.
*
* An attempt whose cleanup failed adds its cleanup errors' codes, even when the test passed.
*/
function verdictExitCodes(results: readonly ResultRecord[], serialGroups: readonly SerialGroupRecord[]): number[] {
const codes: number[] = [0];
Expand All @@ -1402,6 +1404,9 @@ function verdictExitCodes(results: readonly ResultRecord[], serialGroups: readon
default:
break;
}
for (const cleanupError of cleanupErrorsOf(verdict.attempts)) {
codes.push(exitCodeForCategory(cleanupError.category));
}
}
return codes;
}
Expand Down
3 changes: 3 additions & 0 deletions packages/e2e/tests/helpers/fake-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,8 @@ export interface FakeEngineBehavior {
video?: boolean;
/** Links `stopVideo` reports before its file, as `video/mp4` segments starting with it. */
videoLinks?: readonly string[];
/** Throw to fail video finalization (`stopVideo`). */
onStopVideo?(attemptIndex: number): void | Promise<void>;
/** Throw to fail state restore after startAttempt succeeded. */
onRestore?(state: EngineState): void | Promise<void>;
/** Contributes a `gadget` fixture exercising every fixture-context facility. */
Expand Down Expand Up @@ -465,6 +467,7 @@ export function createFakeEngine(behavior: FakeEngineBehavior = {}): FakeEngineH
},
async stopVideo(operation) {
record('artifacts.stopVideo', operation);
await behavior.onStopVideo?.(current);
const dir = attempts[current]?.artifactsDir;
if (dir === undefined || videoStartedAt === undefined) return [];
mkdirSync(path.join(dir, 'video'), { recursive: true });
Expand Down
32 changes: 30 additions & 2 deletions packages/e2e/tests/integration/engine-contract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,7 @@ test.describe('wizard', { serial: true, retries: 1 }, () => {
);

it(
'a failing endAttempt marks cleanup failed with a secondary error but keeps the test passed',
'a failing endAttempt marks cleanup failed with a secondary error and exits 3 even though the test passed',
async () => {
const fake = createFakeEngine({
onEndAttempt() {
Expand All @@ -504,7 +504,7 @@ test.describe('wizard', { serial: true, retries: 1 }, () => {
const attempt = result.attempts[0]!;
expect(attempt.cleanup).toBe('failed');
expect(attempt.secondaryErrors.some((error) => error.phase === 'cleanup')).toBe(true);
expect(outcome.exitCode).toBe(0);
expect(outcome.exitCode).toBe(3);
project.cleanup();
},
60_000,
Expand Down Expand Up @@ -1081,6 +1081,34 @@ test('fails on purpose', async ({ app }) => {
60_000,
);

it(
'a required video that fails to stop fails cleanup and exits 3 even though the test passed (#1231)',
async () => {
const fake = createFakeEngine({
video: true,
onStopVideo() {
throw new Error('video finalization exploded');
},
});
const { outcome, project } = await runProject(
{ 'tests/video.e2e.ts': PASSING_TEST },
{ appUrl: APP_URL, config: plainConfig(fake), runOptions: { video: 'on' } },
);
const result = resultByTitle(outcome, 'taps a node');
expect(result.status).toBe('passed');
const attempt = result.attempts[0]!;
expect(attempt.cleanup).toBe('failed');
expect(attempt.secondaryErrors.some((error) => error.phase === 'cleanup')).toBe(true);
expect(attempt.secondaryErrors.find((error) => error.phase === 'cleanup')?.message).toContain(
'video finalization exploded',
);
expect(outcome.exitCode).toBe(3);
assertValidReport(outcome.report);
project.cleanup();
},
60_000,
);

it(
'keeps only failed attempts with retain-on-failure',
async () => {
Expand Down
38 changes: 38 additions & 0 deletions packages/e2e/tests/integration/list-reporter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import path from 'node:path';
import { stripVTControlCharacters } from 'node:util';
import { describe, expect, it, vi } from 'vitest';
import { defineEngine } from '../../src/engine/index.ts';
import { createFakeEngine } from '../helpers/fake-engine.ts';
import { engineConfig } from '../helpers/fixture-config.ts';
import { runProject, type FixtureProject } from '../helpers/run-project.ts';
import { snapshot } from '../helpers/snapshot.ts';

Expand Down Expand Up @@ -55,4 +57,40 @@ describe('list reporter output', () => {
project?.cleanup();
}
});

it('shows a cleanup failure under a passed test and in the summary, not a green summary with exit 3', async () => {
const written: string[] = [];
const stdoutWrite = vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => {
written.push(String(chunk));
return true;
});
let project: FixtureProject | undefined;
try {
const fake = createFakeEngine({
onEndAttempt() {
throw new Error('close exploded');
},
});
const run = await runProject(
{
'tests/close-fail.e2e.ts': `import { test } from 'e2e';\n\ntest('taps a node', async ({ app, screen }) => {\n await app.open('/');\n await screen.getByRole('button', { name: 'Submit' }).tap();\n});\n`,
},
{
appUrl: 'http://127.0.0.1:4599',
config: engineConfig(fake.engine),
runOptions: { quiet: false, reporters: ['list'] },
},
);
project = run.project;
stdoutWrite.mockRestore();
const output = stripVTControlCharacters(written.join(''));
expect(run.outcome.exitCode).toBe(3);
expect(output).toMatch(/✓ taps a node/);
expect(output).toMatch(/cleanup failed: ENGINE_FAILURE: attempt end failed: close exploded/);
expect(output).toMatch(/Cleanup +1 cleanup failure: ENGINE_FAILURE: attempt end failed: close exploded/);
} finally {
stdoutWrite.mockRestore();
project?.cleanup();
}
});
});
5 changes: 3 additions & 2 deletions packages/e2e/tests/integration/skip-after-failure.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,15 +145,16 @@ describe('a runtime skip after a failure', () => {
expect(output).not.toContain('Skipped After Failure');
});

it('does not turn post-skip cleanup diagnostics into a test failure', () => {
it('exits 3 when a skipped test cleanup fails, keeping the test skipped', () => {
const { report, output, exitCode } = runSkipped(
`test('clean skip', () => { test.skip('not applicable'); });`,
'failOnSkippedFailure: true,',
0,
`async endAttempt() { throw new Error('cleanup failed'); },`,
);
expect(report.run.results[0]?.attempts[0]?.secondaryErrors).toMatchObject([{ phase: 'cleanup' }]);
expect(exitCode).toBe(0);
expect(report.run.results[0]?.status).toBe('skipped');
expect(exitCode).toBe(3);
expect(output).not.toContain('Skipped After Failure');
});
});
Loading