Skip to content

Commit f9f6fee

Browse files
authored
tests: faster local e2e runs, fix three CI flakes (#3445)
I looked into speeding up local e2e runs and fixing some flakes we keep seeing in CI. Not sure whether the speedup is worth it here, but it is pretty big for the occasional local full suite run. ### Speedup A Playwright [trace](https://playwright.dev/docs/trace-viewer) is a recording of a test run that you open in the trace viewer: a DOM snapshot before and after each action, plus screenshots, network requests and console output. Locally we ran with `trace: 'retain-on-failure'`, which records a trace for every test and throws it away when the test passes. Local runs now default to `off`; pass `--trace retain-on-failure` when chasing a flake (noted in AGENTS.md and the `debug-e2e` skill). CI keeps `on-first-retry`, which only records on retries. Wall-clock time on my 14-core Mac, Chrome only, 9 workers (the local default), with tracing on and off runs interleaved. Times include starting the dev server. | Run | Runs each | Tracing on | Tracing off | Saved | | ---------------------------------------------------- | --------- | ------------------------- | --------------------------- | ----- | | One test (`can resize a failed or stopped instance`) | 5 | 12.0–14.2 s (median 12.1) | 11.3–12.1 s (median 11.5) | ~5% | | `instance.e2e.ts` (19 tests) | 3 | 21.8–22.9 s (median 22.7) | 19.4–20.2 s (median 20.2)\* | ~11% | | Full suite (429 tests) | 2 | 236.5–245.3 s | 182.7–183.0 s | ~24% | \* The range leaves out a third tracing-off run that took 44.6 s. The median includes it. I also considered running e2e against the production build. Every test starts in a fresh browser context, so every page load refetches every unbundled module from the Vite dev server. The production build is faster for the full suite: on the Mac, main took 210 s and the production build with tracing off took 154–156 s (two runs each, 402 tests). But the build runs before every invocation, so a single test got slower, 7.9 s against 6.2 s on the dev server, and the break-even is probably somewhere around 20–30 tests. Locally we mostly run one file or one test, and CI runs the full suite. Supporting both dev and prod servers also meant some noisy fixes for 13 tests that assumed the dev server, across 10 files, and e2e would no longer run with StrictMode double effects or React dev warnings. It could still make sense for CI later. ### Flakes - **`support-bundles › bundle deleted mid-view 404s`** failed on Firefox in 3 of the last 11 CI runs, once on [all three attempts on main](https://github.com/oxidecomputer/console/actions/runs/43102126272). It has 3 s to see the bundle in `destroying`, and the toast helpers slept 1 s after every dismissal (added in #1832, nobody knew why). They now wait for the toast to leave the DOM. On Firefox it went from 5/10 passing to 10/10, and 10 toast-heavy specs showed no new failures. - **`vpcs › can nav to VpcPage from /`** failed its first attempt on Chrome in 7 of the last 11 CI runs. The `VPCs` link locator also matched the `project-no-vpcs` link in the projects table, still on screen on a slow runner. With `exact: true` and Chrome's CPU throttled 2x, it went from 0/20 passing to 20/20. - **`route-announcer › route announcer`** failed on Firefox in 7 of the last 11 CI runs. react-aria removes each announcement after 7 s, before a slow runner gets to the assertion. The test now records announcements as they appear. With a 7.5 s pause added after a nav, the old test failed 5/5 on Firefox and the new one passed 5/5. - Serial console (`theme.e2e.ts:99`), fixed in app/msw-mock-api.ts. - Cause: the mock stream slept after each of 160 boot log lines, so on a busy runner every late timer added to the total. With Firefox held to the slow cores, the stream took 19 s instead of 4.8 s, against a 15 s timeout. - Fix: each line is now due at a fixed offset from the start, and late lines go out together. - Result: 0/6 → 6/6 with one worker on slow cores. With three workers it was 0/9 → 3/9, where page load alone took about 10 s, which is harsher than CI. - CI history: flaked in 11 of the last 120 runs, all Firefox. - Scroll restore (`scroll-restore.e2e.ts:12`), fixed in test/e2e/utils.ts. - Cause: the test scrolled before web fonts loaded. When the fonts arrived, the h1 above the viewport resized and scroll anchoring moved scrollY from 143 to 140.5, which then got saved and restored. - Fix: the scrollTo helper waits for document.fonts.ready first, which covers all its callers. - Result: 31/40 → 40/40. The unmodified spec didn't fail locally in 60 runs, so this was reproduced with a copy of the spec plus a no-op init script under heavy CPU load. - CI history: the most frequent of the three, 32 Firefox runs and 2 Chrome out of 120. - Not fixed: a rarer failure in the same test ("expected 190, got 143", once in CI and twice locally). The subagent's unconfirmed guess is that useScrollRestoration skips saving when a nav has cached data.
1 parent 84c2b7d commit f9f6fee

7 files changed

Lines changed: 96 additions & 36 deletions

File tree

‎.claude/skills/debug-e2e/SKILL.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ Prefer narrowing with `-g` and `--project` first, then increase `--repeat-each`
6969

7070
### 3. Analyze failure artifacts
7171

72-
When tests fail, Playwright saves traces and error context:
72+
When tests fail, Playwright saves error context. Traces are off by default in local runs because recording them slows the suite; add `--trace retain-on-failure` to the test command to keep a trace for each failed test.
7373

7474
```bash
7575
# View error context (page snapshot at failure time)

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@
4747
- Treat Vitest browser specs as small e2e tests: query by accessible role, label, or visible text and use retrying browser matchers. Avoid selectors coupled to CSS classes or internal DOM structure; inspect layout or computed styles only when the behavior has no semantic representation.
4848
- For sweeping styling changes, coordinate with the visual regression harness and follow `test/visual/README.md` for the workflow.
4949
- Fix root causes of flaky timing rather than adding `sleep()` workarounds in tests.
50-
- When an intermittent browser or E2E failure does not reproduce under normal repetition, retry under controlled CPU contention before concluding it is CI-only. Keep the load bounded so the browser and test runner can still make progress, enable failure-only traces when available, and use a shell trap to clean up every churn process.
50+
- When an intermittent browser or E2E failure does not reproduce under normal repetition, retry under controlled CPU contention before concluding it is CI-only. Keep the load bounded so the browser and test runner can still make progress, enable failure-only traces (`--trace retain-on-failure`, off by default locally), and use a shell trap to clean up every churn process.
5151
- Local Playwright runs write a compact plain-text report to `.e2e-logs/` (gitignored, one timestamped `.log` per run, last 10 kept) via the custom reporter at `test/e2e/compact-reporter.ts`. Top line is `status: ... total=N passed=N ...`; each failure is a `── UNEXPECTED|FLAKY file:line title` block followed by the error (ANSI stripped). Latest run: `ls .e2e-logs | tail -1` — Read it directly, no parsing needed.
5252

5353
# Data fetching pattern

‎app/msw-mock-api.ts‎

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -54,17 +54,27 @@ const randomStatus = () => {
5454

5555
const sleep = async (ms: number) => new Promise((res) => setTimeout(res, ms))
5656

57-
/** Stream boot log line-by-line with realistic timing */
57+
function lineDelay(line: string) {
58+
if (line === '' || line.startsWith('Welcome to') || line.includes('login:')) return 200
59+
if (line.startsWith('[ OK ]') || line.startsWith(' Starting')) return 30
60+
return 15
61+
}
62+
63+
/**
64+
* Stream boot log line-by-line with realistic timing. Each line is due at a
65+
* fixed offset from the start instead of a delay after the previous line. On
66+
* a slow CI runner every timer fires late, and over 160 lines the lateness
67+
* added up to more than the e2e timeout. Lines that are already due go out
68+
* together.
69+
*/
5870
async function streamBootLog(socket: WebSocket, text: string) {
71+
const start = performance.now()
72+
let due = 0
5973
for (const line of text.split('\n')) {
74+
const wait = start + due - performance.now()
75+
if (wait > 0) await sleep(wait)
6076
socket.send(line + '\r\n')
61-
if (line === '' || line.startsWith('Welcome to') || line.includes('login:')) {
62-
await sleep(200)
63-
} else if (line.startsWith('[ OK ]') || line.startsWith(' Starting')) {
64-
await sleep(30)
65-
} else {
66-
await sleep(15)
67-
}
77+
due += lineDelay(line)
6878
}
6979
}
7080

‎playwright.config.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,10 @@ export default {
3333
// an LLM agent can read the failures.
3434
reporter: process.env.CI ? 'list' : [['list'], ['./test/e2e/compact-reporter.ts']],
3535
use: {
36-
trace: process.env.CI ? 'on-first-retry' : 'retain-on-failure',
36+
// Recording a trace for every test makes local runs much slower, so it's
37+
// off by default. Pass `--trace retain-on-failure` to keep traces of
38+
// failed tests, e.g. when chasing a flake.
39+
trace: process.env.CI ? 'on-first-retry' : 'off',
3740
baseURL: 'http://localhost:4009',
3841
},
3942
projects: [

‎test/e2e/route-announcer.e2e.ts‎

Lines changed: 35 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,46 @@
77
*/
88
import { expect, test, type Page } from '@playwright/test'
99

10+
declare global {
11+
interface Window {
12+
announcements: string[]
13+
}
14+
}
15+
1016
// react-aria appends each announcement as a child of a hidden polite live
11-
// region shared with toasts. CSS locator because there's a second region for
17+
// region shared with toasts, and removes it 7 seconds later. A slow CI runner
18+
// can take longer than that to get to an assertion, so record announcements as
19+
// they're added. Match on the polite region because there's a second one for
1220
// assertive announcements and we only want the messages from this one.
13-
const announcements = (page: Page) =>
14-
page.locator('[data-live-announcer] [aria-live="polite"] > div')
21+
test.beforeEach(async ({ page }) => {
22+
await page.addInitScript(() => {
23+
window.announcements = []
24+
new MutationObserver((records) => {
25+
for (const { target, addedNodes } of records) {
26+
if (
27+
target instanceof Element &&
28+
target.matches('[data-live-announcer] [aria-live="polite"]')
29+
) {
30+
for (const node of addedNodes) window.announcements.push(node.textContent ?? '')
31+
}
32+
}
33+
}).observe(document, { childList: true, subtree: true })
34+
})
35+
})
36+
37+
const expectAnnouncements = (page: Page) =>
38+
expect.poll(() => page.evaluate(() => window.announcements))
1539

1640
test('route announcer', async ({ page }) => {
1741
await page.goto('/projects')
1842
await expect(page.getByRole('heading', { name: 'Projects' })).toBeVisible()
1943

2044
// nothing on first load — the browser already announced the page
21-
await expect(announcements(page)).toHaveCount(0)
45+
await expectAnnouncements(page).toEqual([])
2246

2347
// nav by a link inside the content, which unmounts along with the page
2448
await page.getByRole('link', { name: 'mock-project' }).click()
25-
await expect(announcements(page)).toHaveText(['Instances, mock-project, Projects'])
49+
await expectAnnouncements(page).toEqual(['Instances, mock-project, Projects'])
2650
// focus goes to the new page's heading, like (better than) a real page load
2751
await expect(page.getByRole('heading', { name: 'Instances' })).toBeFocused()
2852

@@ -32,7 +56,7 @@ test('route announcer', async ({ page }) => {
3256
.getByRole('navigation', { name: 'Sidebar navigation' })
3357
.getByRole('link', { name: 'Disks' })
3458
await disksLink.click()
35-
await expect(announcements(page)).toHaveText([
59+
await expectAnnouncements(page).toEqual([
3660
'Instances, mock-project, Projects',
3761
'Disks, mock-project, Projects',
3862
])
@@ -42,12 +66,12 @@ test('route announcer', async ({ page }) => {
4266
// than replacing it, so it doesn't announce or take focus from the dialog
4367
await page.getByRole('link', { name: 'New Disk' }).click()
4468
await expect(page.getByRole('dialog', { name: 'Create disk' })).toBeVisible()
45-
await expect(announcements(page)).toHaveCount(2)
69+
await expectAnnouncements(page).toHaveLength(2)
4670

4771
// ...and neither does dismissing it
4872
await page.getByRole('button', { name: 'Cancel' }).click()
4973
await expect(page.getByRole('dialog', { name: 'Create disk' })).toBeHidden()
50-
await expect(announcements(page)).toHaveCount(2)
74+
await expectAnnouncements(page).toHaveLength(2)
5175
})
5276

5377
// tabs that live in the query param rather than the path aren't navigations as
@@ -56,7 +80,7 @@ test('route announcer ignores query param tabs', async ({ page }) => {
5680
await page.goto('/system/utilization')
5781
await page.getByRole('tab', { name: 'Metrics' }).click()
5882
await expect(page).toHaveURL(/tab=metrics/)
59-
await expect(announcements(page)).toHaveCount(0)
83+
await expectAnnouncements(page).toEqual([])
6084
})
6185

6286
// VPC tabs, on the other hand, are real routes. Routes like these share a crumb
@@ -65,7 +89,7 @@ test('route announcer on tab routes', async ({ page }) => {
6589
await page.goto('/projects/mock-project/vpcs/default/firewall-rules')
6690
const tab = page.getByRole('tab', { name: 'Routers' })
6791
await tab.click()
68-
await expect(announcements(page)).toHaveText([
92+
await expectAnnouncements(page).toEqual([
6993
'Routers, default, VPCs, mock-project, Projects',
7094
])
7195
// the tab is still there, so it keeps focus
@@ -78,5 +102,5 @@ test('route announcer ignores detail side modals', async ({ page }) => {
78102
await page.goto('/images')
79103
await page.getByRole('link', { name: 'ubuntu-22-04' }).click()
80104
await expect(page.getByRole('dialog', { name: 'Image details' })).toBeVisible()
81-
await expect(announcements(page)).toHaveCount(0)
105+
await expectAnnouncements(page).toEqual([])
82106
})

‎test/e2e/utils.ts‎

Lines changed: 34 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -179,11 +179,20 @@ export async function stopInstance(page: Page) {
179179
}
180180

181181
/**
182-
* Assert that a toast with text matching `expectedText` is visible.
182+
* Assert that a toast with text matching `expectedText` is visible, then
183+
* dismiss that toast and wait for it to go away.
183184
*/
184185
export async function expectToast(page: Page, expectedText: string | RegExp) {
185186
await expect(page.getByTestId('Toasts')).toContainText(expectedText)
186-
await closeToast(page)
187+
// Dismiss the toast we matched, not whichever is first. An error test often
188+
// has a "creating..." toast followed closely by a result toast, and which one
189+
// is first depends on how fast the mock answers.
190+
const toast = page
191+
.getByTestId('Toasts')
192+
.locator(':scope > div')
193+
.filter({ hasText: expectedText })
194+
.first()
195+
await dismissToast(toast.getByRole('button', { name: 'Dismiss notification' }))
187196
}
188197

189198
/**
@@ -193,18 +202,25 @@ export async function expectNoToast(page: Page, expectedText: string | RegExp) {
193202
await expect(page.getByTestId('Toasts')).not.toContainText(expectedText)
194203
}
195204

205+
/** Close the first toast and wait for it to go away. */
206+
export async function closeToast(page: Page) {
207+
await dismissToast(page.getByRole('button', { name: 'Dismiss notification' }).first())
208+
}
209+
196210
/**
197-
* Close first toast and wait for it to fade out. For some reason it prevents
198-
* things from working, but only in tests as far as we can tell.
211+
* Click a toast's dismiss button and wait until the toast has left the DOM
212+
* (after its exit animation), so it can't cover what the test clicks next.
213+
* Hold the element, not the locator: a toast arriving in between would change
214+
* what the locator points to.
199215
*/
200-
export async function closeToast(page: Page) {
201-
// first() is a hack aimed at situations where we're testing an error
202-
// response, which usually means we have an initial "creating..." toast
203-
// followed by an error toast. Sometimes the error toast shows up so fast that
204-
// we don't have time to close the first one. Without first(), this errors out
205-
// because there are two toasts.
206-
await page.getByRole('button', { name: 'Dismiss notification' }).first().click()
207-
await sleep(1000)
216+
async function dismissToast(button: Locator) {
217+
// elementHandle waits for a match and throws on timeout, so it's never null
218+
const handle = (await button.elementHandle())!
219+
await handle.click().catch(async (e) => {
220+
// the toast timed out and left on its own before the click landed
221+
if (await handle.evaluate((el) => el.isConnected)) throw e
222+
})
223+
await handle.waitForElementState('hidden')
208224
}
209225

210226
/**
@@ -308,7 +324,12 @@ export async function expectScrollTop(page: Page, expected: number) {
308324
}
309325

310326
export async function scrollTo(page: Page, to: number) {
311-
await page.evaluate((to) => window.scrollTo(0, to), to)
327+
await page.evaluate(async (to) => {
328+
// If a web font finishes loading after the scroll, the text above the
329+
// viewport reflows and scroll anchoring shifts scrollY by a few pixels
330+
await document.fonts.ready
331+
window.scrollTo(0, to)
332+
}, to)
312333
}
313334

314335
export async function addTlsCert(page: Page) {

‎test/e2e/vpcs.e2e.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@ test('can nav to VpcPage from /', async ({ page }) => {
1313
await page.goto('/')
1414
await page.getByRole('table').getByRole('link', { name: 'mock-project' }).click()
1515
await page.waitForURL('**/projects/mock-project/**')
16-
await page.getByRole('link', { name: 'VPCs' }).click()
16+
// exact because the URL changes before the projects table goes away, and on
17+
// a slow machine a substring match clicks the project-no-vpcs link in it
18+
await page.getByRole('link', { name: 'VPCs', exact: true }).click()
1719
await page.waitForURL('**/vpcs**')
1820

1921
await expectRowVisible(page.getByRole('table'), {

0 commit comments

Comments
 (0)