# Find Race Conditions with Xcode Thread Sanitizer

Canonical: https://figment.so/blog/mac-thread-sanitizer-remote-xcode

Run xcodebuild test with -enableThreadSanitizer YES and parallel testing on, then filter the race blocks out of the log with awk. Expect a 2x to 20x slowdown, so keep the run focused.

**To chase intermittent crashes caused by shared mutable state, enable Thread Sanitizer (TSan) in your test scheme or with `-enableThreadSanitizer YES`, run the suite on the hosted Mac, and filter the race blocks out of the log.** TSan instruments your binary at compile time, watches every memory access at runtime, and reports the exact pair of conflicting accesses whenever two threads touch the same location without synchronisation. Apple documents the enable flags and the Simulator-only scope for iOS in the [Thread Sanitizer section of the Xcode diagnostics guide](https://developer.apple.com/documentation/xcode/diagnosing-memory-thread-and-crash-issues-early). The upstream instrumentation is described in the [Clang ThreadSanitizer documentation](https://clang.llvm.org/docs/ThreadSanitizer.html).

## What does TSan do to my build, and what does it cost?

When you enable it, Xcode passes `-fsanitize=thread` to Clang and `-sanitize=thread` to the Swift compiler. Every load and store in the binary is wrapped with shadow-memory bookkeeping that tracks which thread last wrote each byte.

The runtime cost is real. Apple's [diagnostics guide](https://developer.apple.com/documentation/xcode/diagnosing-memory-thread-and-crash-issues-early) reports a 2x to 20x slowdown and a 5x to 10x memory increase for TSan builds. The upstream Clang docs give a narrower slowdown range of 5x to 15x. A suite that normally finishes in 40 seconds can take several minutes under instrumentation.

Apple restricts TSan to 64-bit macOS binaries and to iOS, iPadOS, tvOS, visionOS and watchOS apps running in Simulator, not on physical devices. A remote Mac absorbs the overhead while you keep working locally, and the Simulator is where TSan produces its reports. Because TSan slows every memory operation, run only the modules or test classes that exercise the shared state you suspect.

## How do I enable TSan?

**In Xcode (scheme editor):** Open **Product → Scheme → Edit Scheme**, select **Diagnostics** under the Test action, and check **Thread Sanitizer**. The setting is stored in the `.xcscheme` file, so it travels with the repo.

**On the command line (CI-friendly):** Pass `-enableThreadSanitizer YES` to `xcodebuild`:

```bash
xcodebuild test \
  -project MyApp.xcodeproj \
  -scheme MyApp \
  -destination 'platform=iOS Simulator,name=iPhone 16,OS=latest' \
  -enableThreadSanitizer YES \
  2>&1 | tee tsan-raw.log
```

The `tee` step keeps the full log for the awk filter below. The scheme name is a placeholder, so substitute your project's real scheme.

Run long jobs over SSH inside a `tmux` or `screen` session, so the test suite keeps running if your connection drops.

## How do I make the test suite trigger races?

TSan reports only races it actually witnesses. A test that never runs two threads against the same memory produces no output. The most reliable way to force contention is parallel test workers:

```bash
xcodebuild test \
  -project MyApp.xcodeproj \
  -scheme MyApp \
  -destination 'platform=iOS Simulator,name=iPhone 16,OS=latest' \
  -enableThreadSanitizer YES \
  -parallel-testing-enabled YES \
  -maximum-parallel-testing-workers 4 \
  2>&1 | tee tsan-raw.log
```

If an `async` function writes a property from a background task, add a test that calls it from multiple `Task {}` blocks and awaits them with `withTaskGroup`. That pattern reliably surfaces races in actor-less reference types.

## How do I pull the conflicting pair out of the log?

Use a short awk filter that extracts only the race blocks from `tsan-raw.log`. Confirm the block terminator against a known TSan log for your toolchain before you rely on it in CI, because some runtimes end the block with a `==<pid>==` footer and others emit a blank line:

```bash
awk '
  /WARNING: ThreadSanitizer: data race/ { in_race=1 }
  in_race { print }
  in_race && NF==0 { in_race=0; print "---" }
' tsan-raw.log > tsan-races.log
```

As a sanity check, `grep -c "WARNING: ThreadSanitizer: data race" tsan-raw.log` should match the number of `---` separators in `tsan-races.log`. If it does not, adjust the terminator pattern (for example, match `/^==[0-9]+==\s*$/`) before trusting the filtered file.

Each extracted block has this shape:

```
WARNING: ThreadSanitizer: data race (pid=12345)
  Write of size 8 at 0x... by thread T2:
    #0 MyModel.update() MyModel.swift:47
    #1 ...
  Previous read of size 8 at 0x... by main thread:
    #0 MyModel.value.getter MyModel.swift:22
    ...
```

The two stacks name the contested property and both call sites. Fix the race by protecting that property with an actor, a lock or a `@MainActor` annotation, whichever matches how your code accesses it.

## Which TSan reports are false positives, and how do I suppress them?

Two Swift patterns are worth double-checking:

1. **`DispatchQueue.async` with a captured immutable value.** If the capture is a value type or a class with no writable state, TSan can still flag the access path. Check whether the flagged property is ever written after initialisation.
2. **`@MainActor` type tested off the main runloop.** If the test runner calls a `@MainActor` method from a background thread, TSan reports on the wrong thread rather than on a real race. Annotate the test function with `@MainActor`, or drive it from a live main-runloop test host.

Suppress a confirmed false positive with a `.tsan-suppressions` file:

```
race:MyModel.frozenConstant
```

Load it with `TSAN_OPTIONS=suppressions=.tsan-suppressions`. Use suppressions sparingly, because they hide reports without changing the access pattern.

## Should I combine TSan with Swift strict concurrency checking?

Yes, in that order. Xcode 16 exposes the `SWIFT_STRICT_CONCURRENCY` build setting with values `minimal`, `targeted` and `complete`. Setting it to `complete` turns actor-isolation violations into compile-time errors rather than runtime races.

1. Build with `SWIFT_STRICT_CONCURRENCY=complete` so the compiler rejects every isolation violation it can prove statically.
2. Run the same suite with `-enableThreadSanitizer YES` to catch the residue: races involving Objective-C types, unstructured `Task` launches or legacy GCD code.

Compiler errors are cheap to fix, so you spend TSan's overhead only on dynamic behaviour the type system cannot verify.

## Which Figment Mac plan fits TSan runs?

The [Intel Mac VM](/mac-hosting#intel-vm) ($25 a month, $2 a day) runs macOS Sequoia and fits Xcode 26.3 or earlier. Pair it with a Simulator runtime that still ships x86_64 variants (check the Xcode and Simulator row in the [Xcode release notes](https://developer.apple.com/documentation/xcode-release-notes)). Xcode 27 is Apple silicon only per Apple's [porting guidance](https://developer.apple.com/documentation/apple-silicon/porting-your-macos-apps-to-apple-silicon), and Xcode 26.4 and later need macOS Tahoe, so use the [Apple Silicon Mac VM](/mac-hosting#apple-silicon-vm) ($39 a month, $6 a day) when your race reproduces only under arm64 or you need a newer Xcode. For long, heavy instrumented suites, the [Dedicated M4 Pro 48 GB](/mac-hosting#dedicated-m4-pro) gives a whole Mac. VM vCPUs are shared, and we have not measured TSan timings on any plan. See all [Mac hosting plans](/mac-hosting).

**Related guides:**
- [Simulate Poor Network Conditions for iOS Testing](/blog/mac-network-link-conditioner-ios)
- [Build DocC Documentation on a Remote Mac](/blog/mac-docc-documentation-remote)
- [Set Up a GitHub Actions Self-Hosted Runner on a Mac](/blog/mac-github-actions-self-hosted-runner)
