# Parallelize XCTests Across Multiple Mac Nodes

Canonical: https://figment.so/blog/mac-xctest-parallel-ci-nodes

Split the suite by test-class identifier, run each shard on its own Mac with xcodebuild -only-testing, then merge the xcresult bundles. Two Apple Silicon Mac VMs cost $78 a month ($39 x 2).

**Shard your XCTest suite by test-class identifier, run each shard on its own Mac node with `xcodebuild ... -only-testing`, then merge the per-shard xcresult bundles.** A 40-minute suite blocks every pull request for 40 minutes. `-parallel-testing-enabled YES` fans tests across simulator clones on one Mac but stops at that host's CPU and RAM, and `xcodebuild` cannot coordinate a run across several hosts on its own. This guide gives a sharding script, a CI matrix that runs one shard per Mac, and a merge step.

## Why does single-node parallel testing run out?

It runs out because every simulator clone shares one host's CPU and RAM. `xcodebuild -parallel-testing-enabled YES` starts multiple simulator instances and divides tests across them, and `-parallel-testing-worker-count N` caps the simulator count. Both flags act on one host. Apple's [Running tests and interpreting results](https://developer.apple.com/documentation/xcode/running-tests-and-interpreting-results) and the [xcodebuild technote TN2339](https://developer.apple.com/library/archive/technotes/tn2339/_index.html) document the command-line surface, including `-only-testing`, `-skip-testing`, destinations and schemes. Modern Xcode also schedules independent targets within one scheme in parallel, so a strict sum-of-target-times floor rarely matches your wall-clock time. Measure before assuming.

Two practical limits on one Mac:

1. **Core and memory ceiling.** Past roughly four to six workers the returns taper off and the flake rate tends to rise.
2. **No cross-machine distribution.** Each node has to be handed its own identifier list.

The floor for a sharded suite is the time of your longest single test class, because no shard can finish before its slowest member. Measure that class on your own code before you decide how many nodes to pay for.

## Should I shard by test identifier or by generated test plans?

Shard by test identifier with `-only-testing`. Generating per-shard `.xctestplan` files at CI time and passing them with `xcodebuild -testPlan shard-0.xctestplan` does not work, because that flag selects a plan already attached to the scheme by name. It is not an arbitrary file-path argument, so a plan file generated outside the scheme is not picked up.

`-only-testing` accepts an identifier of the form `TestTarget/TestClass` or `TestTarget/TestClass/testMethod` (see TN2339) and can be passed multiple times on one invocation. Give each node a different set of identifiers and you have a cross-machine shard.

Two strategies are common: by class count (simple, deterministic, works on the first run) and by estimated duration (needs historical timings per class). This guide uses class count. Once you have a stable timings file you can swap in duration-balanced bins without changing the matrix shape.

## How do I split the test list into shards?

Use a small script that reads one identifier per line, splits them round-robin into N buckets and writes one file per shard. It makes no network calls, writes only inside `--out-dir`, and is safe to re-run. The example is untested here, so run it against a copy of your list and inspect the shard files by hand before wiring anything into CI.

```python
#!/usr/bin/env python3
"""shard_tests.py -- split a test-identifier list into N shard files.

Input:  a text file with one identifier per line, e.g. MyAppTests/LoginTests
Output: shard-0.txt ... shard-(N-1).txt inside --out-dir
Each line is suitable to pass as `xcodebuild -only-testing <identifier>`.
"""
import argparse
import pathlib
import sys


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("ids_file")
    ap.add_argument("n", type=int)
    ap.add_argument("--out-dir", required=True)
    args = ap.parse_args()
    if args.n < 1:
        sys.exit("N must be >= 1")

    raw = pathlib.Path(args.ids_file).read_text().splitlines()
    ids = [line.strip() for line in raw
           if line.strip() and not line.strip().startswith("#")]
    if not ids:
        sys.exit("No identifiers found. Populate the input list first.")

    out = pathlib.Path(args.out_dir)
    out.mkdir(parents=True, exist_ok=True)

    buckets: list[list[str]] = [[] for _ in range(args.n)]
    for i, ident in enumerate(ids):
        buckets[i % args.n].append(ident)

    for idx, bucket in enumerate(buckets):
        (out / f"shard-{idx}.txt").write_text("\n".join(bucket) + "\n")
        print(f"shard-{idx}: {len(bucket)} id(s)")


if __name__ == "__main__":
    main()
```

Walk the splitter through these checks before trusting its output in CI:

| Step | What to check |
| --- | --- |
| 1 | `wc -l tests/ids.txt` equals the sum of line counts across all `shard-*.txt` files. |
| 2 | Every identifier appears in exactly one shard file (`sort shards/shard-*.txt \| uniq -d` prints nothing). |
| 3 | Shard sizes differ by at most one line (the round-robin property). |
| 4 | Copy the CI step below for `shard_index: 0`, run it on one Mac, and confirm it executes only the classes listed in `shards/shard-0.txt`. |
| 5 | Mark one known test to fail inside `shards/shard-0.txt`. Confirm only shard 0 fails and the other shards keep running (`fail-fast: false`). |

Step 4 only works if `$APP_SCHEME` points at a scheme that exists in your workspace. Do not hard-code a scheme name you have not verified in the project.

## How do I run one shard per Mac and merge the results?

Generate the shard files once in a preparatory job, then fan them out across a matrix where each job runs on its own Mac runner. Each shard runs sequentially inside its job, so simulator-level parallelism does not stack on node-level sharding and oversubscribe the host:

```yaml
# GitHub Actions example. Adjust runs-on labels for your self-hosted pool.
jobs:
  generate-shards:
    runs-on: [self-hosted, macOS, arm64]
    steps:
      - uses: actions/checkout@v4
      - name: Generate shard identifier lists
        run: python3 scripts/shard_tests.py tests/ids.txt 4 --out-dir shards/
      - uses: actions/upload-artifact@v4
        with: { name: shards, path: shards/ }

  test-shard:
    needs: generate-shards
    runs-on: [self-hosted, macOS, arm64]   # one Figment Mac per matrix job
    strategy:
      fail-fast: false
      matrix:
        shard_index: [0, 1, 2, 3]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/download-artifact@v4
        with: { name: shards, path: shards/ }
      - name: Run shard ${{ matrix.shard_index }}
        shell: bash
        env:
          APP_SCHEME: ${{ vars.APP_SCHEME }}
          SHARD: ${{ matrix.shard_index }}
        run: |
          set -euo pipefail
          mkdir -p results
          ONLY_FLAGS=()
          while IFS= read -r id; do
            [ -z "$id" ] && continue
            ONLY_FLAGS+=( -only-testing "$id" )
          done < "shards/shard-${SHARD}.txt"
          xcodebuild test \
            -scheme "$APP_SCHEME" \
            -destination 'platform=iOS Simulator,name=iPhone 15' \
            -parallel-testing-enabled NO \
            -resultBundlePath "results/shard-${SHARD}.xcresult" \
            "${ONLY_FLAGS[@]}"
      - if: always()
        uses: actions/upload-artifact@v4
        with:
          name: xcresult-${{ matrix.shard_index }}
          path: results/shard-${{ matrix.shard_index }}.xcresult
```

Notes on the matrix:

- `set -euo pipefail` makes the step fail on a non-zero `xcodebuild` exit, so a failed build is never counted as a fast run.
- `APP_SCHEME` is injected from a CI variable, so no scheme name is hard-coded. It is not a secret channel. Keep signing secrets in your CI secret store, not in `vars`.
- `-parallel-testing-enabled NO` stops simulator-level parallelism from stacking on top of node-level sharding.
- `-destination` is only an example. Adapt it to a simulator or physical device your scheme supports.
- `if: always()` uploads each shard's `.xcresult` even when tests fail, so the merge job can still inspect broken shards.

After all shard jobs finish, a follow-up job downloads the `.xcresult` bundles and merges them. The xcresulttool surface changed in Xcode 16: several introspection subcommands such as `get object` now require a `--legacy` flag, and tooling that parsed the legacy JSON has had to update. `merge` is a separate subcommand, but verify it against your installed Xcode before relying on it:

```bash
set -euo pipefail
xcrun --find xcresulttool     # confirm the tool is on PATH
xcrun xcresulttool version    # record the version in the job log
xcrun xcresulttool merge \
  results/shard-0.xcresult \
  results/shard-1.xcresult \
  results/shard-2.xcresult \
  results/shard-3.xcresult \
  --output-path results/merged.xcresult
```

If `merge` is unavailable or changes shape on your toolchain, a version-tolerant fallback is to convert each shard's `.xcresult` to JUnit XML with a third-party parser such as `xcresultparser`, then concatenate the `<testsuite>` elements under a single `<testsuites>` root. That path skips `merge` entirely and tends to feed CI dashboards more cleanly.

## How many Macs do I need, and what do they cost?

Start with two nodes, and add a third only when the merged time still dominates merge-queue waits. Two Apple Silicon Mac VMs cost 2 x $39 = $78/month, and two Dedicated M4 Pro 48 GB Macs cost 2 x $349 = $698/month. Prices are USD before tax. A day on the Apple Silicon VM is $6, so a trial of a two-node setup for one day costs 2 x $6 = $12. More than a few Macs is quoted on a call.

The matrix above targets `arm64` runners, so it assumes Apple silicon. You install and manage the CI agent on each Mac yourself. It connects out to your CI service, and you can reach the Mac over SSH, remote desktop or the browser. VM vCPUs are shared, not reserved cores, so measure shard times on your own suite.

A worksheet, not a benchmark. Fill in your own first two rows before trusting the rest:

| Input | Value |
| --- | --- |
| Unsharded wall-clock time per PR | 40 min |
| Wall-clock time with 2 shards (illustrative, measure yours) | 22 min |
| Minutes saved per PR | 18 min |
| Blocked PRs per working day | 20 |
| Minutes recovered per day | `18 x 20 = 360 min = 6.0 h` |
| Loaded engineering rate | $150/h |
| Recovered engineering value per day | `6.0 x 150 = $900` |
| Incremental hosting cost of the second node | $39/month (Apple Silicon Mac VM) or $349/month (Dedicated M4 Pro 48 GB) |

If your longest single test class is already close to your target wall-clock, more shards will not help. Refactor that class instead.

## Which Figment Mac plan fits sharded XCTests?

The [Apple Silicon Mac VM](/mac-hosting#apple-silicon-vm) ($39/month) fits most sharded suites, because each shard runs one simulator at a time. Choose the [Dedicated M4 Pro 48 GB](/mac-hosting#dedicated-m4-pro) ($349/month, M4 Pro, 48GB RAM) if shards are CPU-heavy or you need steady timings. The [Intel Mac VM](/mac-hosting#intel-vm) ($25/month) runs Xcode 26.0 to 26.3 only, so use it only if your suite builds on that range, and change the `arm64` runner labels.

---

**Related guides:**
- [Build and Export an IPA in CI](/blog/mac-ipa-archive-export-ci)
- [Swift Package CI Build Pipeline](/blog/mac-swift-package-ci-build)
- [Xcode on Windows: Remote Mac Setup](/blog/mac-xcode-on-windows-remote-setup)
