GuidesZero flaky tests

Solve your most common flakes every week

A repeatable weekly routine, manual or agent-driven, to find and fix the two flaky tests hurting your suite most often.

Most flaky suites do not have fifty equally broken tests. Flake pain follows a power law: two or three unstable tests usually cause the vast majority of red pull requests and wasted retries.

That is why fixing the two most unstable tests every week beats one-off "flake sprints". It takes a small, steady slice of time, pulls a noisy suite back toward 99.9% quickly, and catches new instability the week it enters main instead of months later.

Every weekly run starts from one question: "What are the two most unstable tests we have right now, and does each fix belong in the application or the test?"

Weekly agent flake loop: 1. Rank the top 2 unstable tests on main over 7 days; 2. Inspect to find the root cause (with automatic diff); 3. Fix root cause in either the app or the test; 4. Verify with --repeat-each=10 --retries=0 and open a reviewable PR; human reviews and merges, then repeat next week.

To see how real flake history looks across repeated runs, browse BikeBook's public Flake Lab organization (endform-guides-flaky), which runs suites/05-flake-lab every six hours against an intentionally flaky deployment:

Live demoPublic org · flaky app

BikeBook Flake Lab organization

A live public Endform organization running robust and intermittently flaky BikeBook tests every six hours, showing real pass-rate trends and top recurring flakes.

The weekly 4-step workflow

You can run this loop yourself in ten minutes or hand it to a coding agent connected to Endform's MCP server. Switch between MCP and CLI on any step below to see the exact calls.

  1. Rank: find the two most unstable tests on main over the last 7 days

    Filter to your default branch (branch = main) so work-in-progress pull requests never distort the ranking.

    Find the two most unstable tests
    You
    What are our two most unstable end-to-end tests?

    Let me check test pass rates on main over the last 7 days.

    MCP toolanalytics_query
    {
      "dataset": "test-runs",
      "metric": "pass-rate",
      "groupBy": "test",
      "where": "branch = main",
      "period": "7D"
    }

    Your two most unstable tests on main this week are "a member books a bike for next week" (91.4% pass rate) and "a name typed straight after opening settings is saved" (94.8% pass rate).

    Check retried runs alongside outright pass rate (samples_query with branch = main, testRun.testAttemptsCount > 1). Retries hide 1-in-10 flakes behind green checkmarks until they happen to fail twice in a row and block a pull request. Pick the two tests failing or retrying most often in the 1-in-10 to 1-in-100 range, and skip rare 1-in-1,000 blips.

  2. Inspect: find the root cause of each failure

    Pull recent retried or failed samples for each of the two tests, then inspect the failing attempts with test_attempt_inspect (or npx endform@latest test-attempt inspect <testAttemptId>). Endform downloads traces, screenshots, network requests, and console output, and automatically includes a step-by-step diff against a recent passing run whenever one is available.

    Inspect why the failing tests failed
    You
    Can you inspect why those two tests failed?

    I'll pull recent retried runs for each test and inspect the failing attempts. Endform includes a diff against a recent passing run automatically when one is available.

    MCP toolsamples_query
    {
      "dataset": "test-runs",
      "where": "test.id = <testId>, testRun.testAttemptsCount > 1",
      "period": "7D",
      "limit": 5
    }
    MCP tooltest_attempt_inspect
    {
      "testAttemptId": "<testAttemptId>"
    }

    Found both root causes: in "a name typed straight after opening settings is saved", the Suspense fallback renders an editable form that wipes typed input when /api/user resolves (app bug). In "a member books a bike for next week", waitForTimeout(500) expires before the chosen date finishes loading (test bug).

    Grab a test_attempt_replay link for each failing attempt so the pull request reviewer can scrub the failure in one click (paired beside a passing run whenever Endform has one). If the trace alone does not explain DOM or focus state, open the test in a live paused browser with live_test_start and live_test_run (see Working with agents).

  3. Classify and fix: application bug, test bug, or environment flake

    Before editing anything, decide where the bug actually lives. BikeBook's suites/05-flake-lab intentionally exercises all three buckets you will hit in production:

    BucketReal BikeBook examples (05-flake-lab)Where to fix
    Application bugSettings form renders an editable Suspense fallback that wipes typed text when /api/user resolves (tests/account.spec.ts); activity log shuffles entries sharing a timestamp (tests/account.spec.ts); lagging read-through team cache serves stale data (tests/account.spec.ts).Fix the application code. Real users hit these races too, and keeping the test strict ensures the bug never returns.
    Test bugtests/bookings.spec.ts calls waitForTimeout(500) after filling a date instead of waiting for the selected day to render; tests/billing.spec.ts uses waitForTimeout(1000) plus a one-shot if (isVisible()) check for a delayed cookie consent dialog.Fix the test using web-first assertions, locator handlers, or isolated fixtures instead of fixed sleeps.
    Upstream or environment flakeTransient 503 responses from the team API or invitation email provider (tests/team.spec.ts), or backend saturation under parallel load.Add proper app retry/error handling, or cap concurrency on the constrained dependency (see Optimize test load).

    Here is what a clean weekly pull request looks like in BikeBook when one of the top two flakes is a real app bug and the other is a bad wait in a test:

    Fix weekly flakes: settings form hydration race and booking date wait
    endform-agent wants to merge into main from fix/weekly-flakes+4-2

    Fixes the two most unstable tests on main from the past 7 days: one application race in Settings and one fixed timeout in the bookings test.

    app/(dashboard)/dashboard/general/page.tsxApp fix

    Disable the Suspense fallback form until user data resolves so neither fast tests nor users on slow connections lose typed input.

     function AccountForm({   state,   nameValue = "",   emailValue = "",+  disabled = false, }: AccountFormProps) {   // ...+  disabled={disabled}   // ...-<Suspense fallback={<AccountForm state={state} />}>+<Suspense fallback={<AccountForm state={state} disabled />}>   <AccountFormWithData state={state} /> </Suspense>
    tests/bookings.spec.tsTest fix

    Replace the fixed 500ms sleep after picking a date with an assertion that waits for the chosen day to render.

     await test.step("Pick a day next week on the bikes page", async () => {   await page.goto("/dashboard");   await page.getByRole("textbox", { name: "Date" }).fill(nextWeek);-  await page.waitForTimeout(500);+  await expect(page.getByText(formatDay(nextWeek))).toBeVisible(); });
  4. Verify without retries, open a PR, and clear quarantine

    Run only the affected spec files on Endform with --repeat-each=10 and --retries=0. Endform runs every repeat in parallel on its own isolated machine, so proving an intermittent race is gone takes seconds.

    Re-run the fixed specs ten times before merging
    You
    Run both specs 10 times on Endform with retries off to make sure the fixes hold.

    Starting a repeated suite run on Endform with retries disabled.

    MCP toolsuite_run_startLocal MCP
    {
      "directory": "/path/to/repo/suites/05-flake-lab",
      "testFileFilters": [
        "tests/bookings.spec.ts",
        "tests/account.spec.ts"
      ],
      "repeatEach": 10,
      "retries": 0
    }

    All 20 repeated runs passed on the first attempt in 18s with 0 retries. The pull request is ready to merge.

    Open a small pull request with the replay link and root-cause explanation. If either test had an active quarantine rule from Triage failed tests on demand, check its post-merge runs and deactivate the rule (npx endform@latest quarantine deactivate <ruleId>) once it is consistently green.

Automate the weekly loop with a scheduled coding agent

Start by running the loop manually with your coding agent for one or two weeks so you see how it investigates your repo and whether its fixes match your codebase conventions. Once those pull requests look solid, schedule it to run automatically every Monday morning.

Here is a GitHub Actions example that runs weekly on a cron schedule, wires up the Endform MCP server, and opens a reviewable pull request:

.github/workflows/weekly-flake-fix.yml
name: Weekly top-2 flake fix

on:
  schedule:
    - cron: "0 8 * * 1" # Every Monday at 08:00 UTC
  workflow_dispatch:

permissions:
  contents: write
  id-token: write
  pull-requests: write

jobs:
  fix-top-flakes:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: anthropics/claude-code-action@v1
        env:
          ENDFORM_API_KEY: ${{ secrets.ENDFORM_API_KEY }}
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          claude_args: >-
            --mcp-config '{"mcpServers":{"endform":{"command":"npx","args":["-y","endform@latest","mcp"]}}}'
            --allowedTools "mcp__endform__*,Bash(npx endform@latest test:*)"
          prompt: |
            Run our weekly top-2 E2E flake check using the Endform MCP server:
            - Look at the last 7 days of test runs on main, considering both
              pass rate and tests that only passed after retries.
            - If every test on main is above 99.5% pass rate with minimal
              retries, exit cleanly without opening a PR.
            - Otherwise pick at most the 2 worst tests, inspect their failing
              attempts to find the true root cause, and classify each as an
              application bug, a test bug, or an environment issue.
            - Fix the underlying root cause. NEVER add waitForTimeout,
              increase global timeouts, wrap actions in .catch(() => {}),
              weaken assertions, or skip/quarantine tests to make them pass.
            - Verify only the changed specs with:
              npx endform@latest test --repeat-each=10 --retries=0 <files>
            - Open a pull request titled "Fix weekly E2E flakes" listing
              each test, whether the fix touched app or test code, the root
              cause, a replay link when available, and the verification output.

ENDFORM_API_KEY authenticates the Endform MCP server in CI (create one with npx endform@latest api-key create --name "GitHub Actions"). When the Endform GitHub App is installed, npx endform@latest test can also authenticate via id-token: write.

Four guardrails keep automated weekly pull requests trustworthy:

  • Always open a PR for human review: Include a replay link when available and explicitly label whether each change touches application code or test code.
  • Ban fake fixes in the prompt: Explicitly forbid waitForTimeout, bumped timeouts, swallowed errors, weakened assertions, and silent skips.
  • Cap each run to 2 tests: Keeping every Monday PR small makes it take five minutes to review and trivial to revert if anything looks off.
  • Allow a clean no-op exit: When every test on main is already above your stability bar (for example, 99.5% or higher with low retries), skip opening a PR.

How to tell the routine is working

Watch two trends in Endform over four to six weeks:

  • Default-branch pass rate climbing back above 99% toward 99.9%.
  • Retried-pass volume dropping so green pull requests are genuinely passing on the first attempt rather than leaning on retries.

Once the backlog of 1-in-10 to 1-in-100 flakes is cleared, the weekly loop shifts into steady state: instead of digging out of old noise, it catches any new race condition or brittle wait the week after a feature ships.

For full query fields and filter operators, see the analytics, samples, and test attempt info reference pages.

Next steps

Last updated