MCPInstall

fix-flaky-tests

Fixes flaky tests by analyzing failure patterns from Tuist test insights, identifying root causes, and applying targeted corrections. Can be invoked with a specific test case URL (e.g. https://tuist.dev/{account}/{project}/tests/test-cases/{id}) or without arguments to discover and fix all flaky tests in the project.

Installs
504
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/tuist/agent-skills --skill fix-flaky-tests
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads fix-flaky-tests automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Fix Flaky Tests

Quick Start

You'll typically receive a Tuist test case URL or identifier. Follow these steps to investigate and fix it:

  1. Run tuist test case show <id-or-identifier> --json to get reliability metrics for the test.
  2. Run tuist test case run list Module/Suite/TestCase --flaky --json to see flaky run patterns.
  3. Run tuist test case run show <test-case-run-id> --json on failing flaky runs to get failure messages and file paths.
  4. Read the test source at the reported path and line, identify the flaky pattern, and fix it.
  5. Verify by running the test multiple times to confirm it passes consistently.

If no specific test is provided, start with the Discovery section below.

Discovery

When no specific test case is provided, find all flaky tests in the project:

tuist test case list --flaky --json --page-size 50

This returns all test cases currently flagged as flaky. Key fields:

  • module.name / suite.name / name — the test identifier
  • avg_duration — helps prioritize (fix fast unit tests first)
  • is_quarantined — whether the test is already quarantined

Triage strategy:

  1. Group tests by suite — multiple flaky tests in the same suite often share a root cause.
  2. Check if failures share a test_run_id — tests that all failed in the same run may have been killed by a process crash, not individual test bugs.
  3. Look at failure messages to categorize: test logic bugs vs infrastructure issues (network errors, server 502s, conflicts on retry).

Investigation

1. Get test case metrics

You can pass either the UUID or the Module/Suite/TestCase identifier:

tuist test case show <id> --json
tuist test case show Module/Suite/TestCase --json

Key fields:

  • reliability_rate — percentage of successful runs (higher is better)
  • flakiness_rate — percentage of runs marked flaky in the last 30 days
  • total_runs / failed_runs — volume context
  • last_status — current state

2. View flaky run history

tuist test case run list Module/Suite/TestCase --flaky --json

The identifier uses the format ModuleName/SuiteName/TestCaseName or ModuleName/TestCaseName when there is no suite. This returns only runs that were detected as flaky.

3. View full run history

tuist test case run list Module/Suite/TestCase --json --page-size 20

Look for patterns:

  • Does it fail on specific branches?
  • Does it fail only on CI (is_ci: true) or also locally?
  • Are failures clustered around specific commits?

4. Get failure details

tuist test case run show <test-case-run-id> --json

Key fields:

  • failures[].message — the assertion or error message
  • failures[].path — source file path
  • failures[].line_number — exact line of failure
  • failures[].issue_type — type of issue (assertion_failure, etc.)
  • repetitions — if present, shows retry behavior (pass/fail sequence)
  • test_run_id — the broader test run this execution belongs to
  • crash_report — crash report data (present when the test runner crashed); contains exception_type, signal, exception_subtype, and triggered_thread_frames

Code Analysis

  1. Open the file at failures[0].path and go to failures[0].line_number.
  2. Read the full test function and its setup/teardown.
  3. Identify which of the common flaky patterns below applies.
  4. Check if the test shares state with other tests in the same suite.

Common Flaky Patterns

Timing and async issues

  • Missing waits: Test checks a result before an async operation completes. Fix: use await, expectations with timeouts, or polling.
  • Race conditions: Multiple concurrent operations access shared state. Fix: synchronize access or use serial queues.
  • Hardcoded timeouts: sleep(1) or fixed delays that are too short on CI. Fix: use condition-based waits instead of fixed delays.

Shared state

  • Test pollution: One test modifies global/static state that another test depends on. Fix: reset state in setUp/tearDown or use unique instances per test.
  • Singleton contamination: Shared singletons carry state between tests. Fix: inject dependencies or reset singletons.
  • File system leftovers: Tests leave files that affect subsequent runs. Fix: use temporary directories and clean up.

Environment dependencies

  • Network calls: Tests hit real services that may be slow or unavailable. Fix: mock network calls.
  • Date/time sensitivity: Tests depend on current time or timezone. Fix: inject a clock or freeze time.
  • File system paths: Hardcoded paths that differ between environments. Fix: use relative paths or temp directories.

Order dependence

  • Implicit ordering: Test passes only when run after another test that sets up required state. Fix: make each test self-contained.
  • Parallel execution conflicts: Tests that work in isolation but fail when run concurrently. Fix: use unique resources per test.

Crashes (identified via crash_report)

  • EXC_BREAKPOINT / SIGTRAP — force-unwrap of nil, Swift precondition failure
  • EXC_BAD_ACCESS / SIGSEGV — use-after-free or dangling pointer
  • EXC_CRASH / SIGABRT — uncaught Objective-C exception

Fix Implementation

After identifying the pattern:

  1. Apply the smallest fix that addresses the root cause.
  2. Do not refactor unrelated code.
  3. If the fix requires a test utility (like a mock or helper), check if one already exists before creating a new one.

Verification

Running tests repeatedly

Run the specific test repeatedly until failure using xcodebuild's built-in repetition support:

xcodebuild test -workspace <workspace> -scheme <scheme> -only-testing <module>/<suite>/<test> -test-iterations <count> -run-tests-until-failure

This runs the test up to <count> times and stops at the first failure. Choose the iteration count based on how long the test takes — for fast unit tests use 50–100, for slower integration or acceptance tests use 2–5.

Reproducing before fixing

Before applying a fix, try to reproduce the flaky failure locally. A successful reproduction confirms your root cause analysis and lets you verify the fix directly. Use the "Running tests repeatedly" approach above, or the race condition strategies below if concurrency is suspected.

Some flaky scenarios — especially race conditions, CI-specific timing issues, or environment-dependent failures — may be difficult or impossible to reproduce locally. If you cannot reproduce after reasonable effort, proceed with fixing based on code analysis and failure logs. A fix backed by clear evidence of a bug (e.g. unsynchronized shared state, TOCTOU pattern) is valid even without local reproduction.

Reproducing race conditions

Race conditions and concurrency bugs often only manifest under CI-level parallelism and are hard to reproduce locally. Try these strategies in order:

  1. Increase parallelism: Add -parallel-testing-enabled YES to run test suites concurrently.
  2. Run broader test suites: Instead of running a single test, run the entire module (e.g. -only-testing ModuleTests) to increase contention on shared resources.
  3. Thread Sanitizer: Run with TSan enabled to detect data races deterministically. Note: TSan adds overhead which can change timing, so some races may not trigger under TSan.
xcodebuild test -workspace <workspace> -scheme <scheme> -only-testing <module> -enableThreadSanitizer YES
  1. High iteration count with broad scope: Combine all the above — run the full module with parallelism and many iterations.

If a race condition cannot be reproduced locally but the code is provably thread-unsafe (e.g. unsynchronized mutation of shared state), the fix is still valid. Verify the fix by confirming the tests pass with the same reproduction strategies above. Document in the commit message that the fix addresses a CI-only race condition identified through code analysis and failure logs.

Done Checklist

  • Identified the root cause of flakiness
  • Applied a targeted fix
  • Verified the test passes consistently (multiple runs)
  • Did not introduce new test dependencies or shared state
  • Committed the fix with a descriptive message

FAQ

What does the fix-flaky-tests skill do?

Fixes flaky tests by analyzing failure patterns from Tuist test insights, identifying root causes, and applying targeted corrections. Can be invoked with a specific test case URL (e.g. https://tuist.dev/{account}/{project}/tests/test-cases/{id}) or without arguments to discover and fix all flaky tests in the project.

How do I install fix-flaky-tests?

Run npx skills add https://github.com/tuist/agent-skills --skill fix-flaky-tests in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/fix-flaky-tests/ (personal) or .claude/skills/fix-flaky-tests/ (project).

Which AI agents can use fix-flaky-tests?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is fix-flaky-tests safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains fix-flaky-tests?

It is published by tuist in tuist/agent-skills. It has 504 recorded installs.

More from tuist/agent-skills

View all →

Guides day-to-day work in Tuist-generated Xcode workspaces, including generation, build and test commands, and buildable folders. Use when working in a Tuist-generated project or when users mention tuist generate, xcodebuild test, or generated workspaces.

Testing & QA597 installs

debug-generated-project

tuist/agent-skills

Debugs issues users encounter with Tuist-generated projects by reproducing the scenario locally, building Tuist from source when needed, and triaging whether it is a bug, misconfiguration, or something that needs team input. Use when users report generation failures, build errors after generation, or unexpected project behavior.

Migrates existing Xcode projects to Tuist generated workspaces with build and run validation, external dependency mapping, and migration checklists. Use when adopting Tuist for an existing app or converting a hand-edited Xcode project to generated projects.

Mobile501 installs

compare-builds

tuist/agent-skills

Open the skill to read its SKILL.md instructions.

AI & Agents299 installs

analyze-selective-testing

tuist/agent-skills

Analyzes Xcode selective testing effectiveness for a test run, showing which test targets were skipped or ran, and diagnosing regressions in test selection. Can compare two test runs to identify what changed.

Testing & QA290 installs

compare-generations

tuist/agent-skills

Open the skill to read its SKILL.md instructions.

AI & Agents282 installs

Popular testing & qa skills

View category →

tdd

mattpocock/skills

Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests.

Testing & QA1.2M installs

grilling

mattpocock/skills

Grill the user relentlessly about a plan, decision, or idea. Use when the user wants to stress-test their thinking, or uses any 'grill' trigger phrases.

Testing & QA996.2K installs

migrate-to-shoehorn

mattpocock/skills

Migrate test files from as type assertions to @total-typescript/shoehorn. Use when user mentions shoehorn, wants to replace as in tests, or needs partial test data.

Testing & QA484.1K installs

run-train

lllllllama/rigorpilot-skills

Rigor Train skill for deep learning research repositories. Use when a documented or selected training command should be run conservatively for startup verification, short-run verification, full kickoff, or resume, with command, config, seed, log, checkpoint, status, and metric evidence written to standardized trainoutputs/. Do not use for environment setup, exploratory sweeps, speculative idea implementation, or end-to-end orchestration.

Testing & QA337.8K installs

test-driven-development

obra/superpowers

Use when implementing any feature or bugfix, before writing implementation code

Testing & QA261.8K installs

Use when implementation is complete, all tests pass, and you need to decide how to integrate the work

Testing & QA216.8K installs