medium.com 11 min read Original Source

The Flaky Test That Taught Me How Swift Concurrency Actually Works

I was writing unit tests for an IntervalDebouncer — a small @MainActor class that debounces UI actions by 300ms. The test should have been trivial:

@MainActor
func test_debounce_shouldFireActionAfterInterval() async {
    var callCount = 0
    self.sut.debounce { callCount += 1 }
    await self.clock.advance(by: .seconds(0.3))
    XCTAssertEqual(callCount, 1)
}
@MainActor
func test_debounce_shouldFireActionAfterInterval() async {
    var callCount = 0
    self.sut.debounce { callCount += 1 }
    await self.clock.advance(by: .seconds(0.3))
    XCTAssertEqual(callCount, 1)
}

It flaked. Then, when I thought I’d fixed it, it flaked differently. Over a few hours of iteration I built four different MockClock implementations, each broken in progressively more educational ways. This post is the chronological trail — what I tried, why it failed, and what the failure taught me about how Swift concurrency actually schedules work.

If you’ve ever built or used a “test clock,” or if the phrase “Swift Concurrency is deterministic” has ever misled you into a flaky test, this one’s for you.

The Starting Point: A Reasonable-Looking MockClock

My first implementation looked fine. I had a MockClock that stored now on the class and kept sleepers in an actor for thread safety:

<button data-code="public final class MockClock: Clock {
public private(set) var now: MockInstant
private let state = _MockClockState()

public func sleep(until deadline: MockInstant, tolerance: Duration?) async throws {
if deadline MockInstant {
now = now.advanced(by: delta)
await state.fireDue(upTo: now)
return now
}
}

actor _MockClockState {
private var waiting: [UUID: Waiter] = [:]
// enqueue, cancel, fireDue…
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

public final class MockClock: Clock {
  public private(set) var now: MockInstant
  private let state = _MockClockState()

  public func sleep(until deadline: MockInstant, tolerance: Duration?) async throws {
    if deadline <= now { return }
    let id = UUID()
    try await withTaskCancellationHandler {
      try await withCheckedThrowingContinuation { cont in
        Task { await state.enqueue(id: id, deadline: deadline, continuation: cont) }
      }
    } onCancel: {
      Task { await state.cancel(id: id) }
    }
  }
  public func advance(by delta: Duration) async -> MockInstant {
    now = now.advanced(by: delta)
    await state.fireDue(upTo: now)
    return now
  }
}

actor _MockClockState {
  private var waiting: [UUID: Waiter] = [:]
  // enqueue, cancel, fireDue...
}
public final class MockClock: Clock {
  public private(set) var now: MockInstant
  private let state = _MockClockState()

  public func sleep(until deadline: MockInstant, tolerance: Duration?) async throws {
    if deadline <= now { return }
    let id = UUID()
    try await withTaskCancellationHandler {
      try await withCheckedThrowingContinuation { cont in
        Task { await state.enqueue(id: id, deadline: deadline, continuation: cont) }
      }
    } onCancel: {
      Task { await state.cancel(id: id) }
    }
  }
  public func advance(by delta: Duration) async -> MockInstant {
    now = now.advanced(by: delta)
    await state.fireDue(upTo: now)
    return now
  }
}

actor _MockClockState {
  private var waiting: [UUID: Waiter] = [:]
  // enqueue, cancel, fireDue...
}

This has, by my count, five bugs. Let me walk through them, because each one maps to a concept worth internalizing.

Bug 1: The enqueue/advance race

sleep registers its waiter inside Task { await state.enqueue(...) } — a detached task that hops to the state actor. If advance(by:) runs before that task is scheduled, fireDue finds no waiters. The continuation gets registered afterward and sits in the dictionary forever. The sleep never returns.

This is what happens in:

let task = Task { try await clock.sleep(for: .seconds(1)) }
await clock.advance(by: .seconds(1))  // might fire before enqueue lands
try await task.value  // hangs
let task = Task { try await clock.sleep(for: .seconds(1)) }
await clock.advance(by: .seconds(1))  // might fire before enqueue lands
try await task.value  // hangs

Bug 2: The data race on now

now is a stored property on a final class. advance writes it; sleep‘s early-return check if deadline <= now reads it. They can happen from different tasks. Thread Sanitizer will scream at you. Strict Concurrency will refuse to compile.

Bug 3: Cancellation before enqueue

Same shape as Bug 1, different direction. If a task is cancelled before its enqueue Task {} runs, onCancel fires first, finds nothing to remove, returns silently. Then the enqueue lands, adds the waiter, and it never gets cancelled or resumed. Leaked continuation.

Bug 4: Non-deterministic wake order

fireDue iterates waiting.values — dictionary order is undefined in Swift. Two sleepers with the same deadline wake in arbitrary order. A test that schedules A then B might observe B firing first. Intermittent test flakes that “only happen in CI” often trace to this kind of thing.

Bug 5: advance returns before resumed tasks run

After fireDue resumes continuations, those continuations are scheduled, not executed. The code right after await clock.advance(...) runs before the woken tasks do. If your assertion depends on the task’s side effects, it’ll read stale state.

First Fix: Consolidate State, Add Tombstones, Sort, Yield

I rewrote with everything on the actor:

<button data-code="actor _MockClockState {
private var now: MockInstant
private var waiting: [UUID: Waiter] = [:]
private var cancelled: Set = [] // tombstone set
private var nextSequence: UInt64 = 0 // for ordering

func sleep(id: UUID, deadline: MockInstant) async throws {
if deadline <= now { return }
if cancelled.remove(id) != nil {
throw CancellationError() // cancel raced ahead
}
try await withCheckedThrowingContinuation { cont in
let seq = nextSequence
nextSequence &+= 1
waiting[id] = Waiter(id: id, deadline: deadline, sequence: seq, continuation: cont)
}
}
func cancel(id: UUID) {
if let w = waiting.removeValue(forKey: id) {
w.continuation.resume(throwing: CancellationError())
} else {
cancelled.insert(id) // remember for when enqueue lands
}
}
private func fireDue(upTo instant: MockInstant) {
let due = waiting.values
.filter { $0.deadline <= instant }
.sorted { lhs, rhs in
if lhs.deadline != rhs.deadline { return lhs.deadline < rhs.deadline }
return lhs.sequence

actor _MockClockState {
  private var now: MockInstant
  private var waiting: [UUID: Waiter] = [:]
  private var cancelled: Set<UUID> = []        // tombstone set
  private var nextSequence: UInt64 = 0          // for ordering

  func sleep(id: UUID, deadline: MockInstant) async throws {
    if deadline <= now { return }
    if cancelled.remove(id) != nil {
      throw CancellationError()                 // cancel raced ahead
    }
    try await withCheckedThrowingContinuation { cont in
      let seq = nextSequence
      nextSequence &+= 1
      waiting[id] = Waiter(id: id, deadline: deadline, sequence: seq, continuation: cont)
    }
  }
  func cancel(id: UUID) {
    if let w = waiting.removeValue(forKey: id) {
      w.continuation.resume(throwing: CancellationError())
    } else {
      cancelled.insert(id)                      // remember for when enqueue lands
    }
  }
  private func fireDue(upTo instant: MockInstant) {
    let due = waiting.values
      .filter { $0.deadline <= instant }
      .sorted { lhs, rhs in
        if lhs.deadline != rhs.deadline { return lhs.deadline < rhs.deadline }
        return lhs.sequence < rhs.sequence       // deterministic tiebreak
      }
    for waiter in due {
      waiting.removeValue(forKey: waiter.id)
      waiter.continuation.resume()
    }
  }
}
actor _MockClockState {
  private var now: MockInstant
  private var waiting: [UUID: Waiter] = [:]
  private var cancelled: Set<UUID> = []        // tombstone set
  private var nextSequence: UInt64 = 0          // for ordering

  func sleep(id: UUID, deadline: MockInstant) async throws {
    if deadline <= now { return }
    if cancelled.remove(id) != nil {
      throw CancellationError()                 // cancel raced ahead
    }
    try await withCheckedThrowingContinuation { cont in
      let seq = nextSequence
      nextSequence &+= 1
      waiting[id] = Waiter(id: id, deadline: deadline, sequence: seq, continuation: cont)
    }
  }
  func cancel(id: UUID) {
    if let w = waiting.removeValue(forKey: id) {
      w.continuation.resume(throwing: CancellationError())
    } else {
      cancelled.insert(id)                      // remember for when enqueue lands
    }
  }
  private func fireDue(upTo instant: MockInstant) {
    let due = waiting.values
      .filter { $0.deadline <= instant }
      .sorted { lhs, rhs in
        if lhs.deadline != rhs.deadline { return lhs.deadline < rhs.deadline }
        return lhs.sequence < rhs.sequence       // deterministic tiebreak
      }
    for waiter in due {
      waiting.removeValue(forKey: waiter.id)
      waiter.continuation.resume()
    }
  }
}

And on MockClock.advance, I added a post-advance yield loop:

MockInstant {
let newNow = await state.advance(by: delta)
for _ in 0..

public func advance(by delta: Duration) async -> MockInstant {
  let newNow = await state.advance(by: delta)
  for _ in 0..<10 { await Task.yield() }         // let resumed tasks run
  return newNow
}
public func advance(by delta: Duration) async -> MockInstant {
  let newNow = await state.advance(by: delta)
  for _ in 0..<10 { await Task.yield() }         // let resumed tasks run
  return newNow
}

Five bugs, four fixes (Bug 1 and Bug 3 share the same root cause — handling it via synchronous-actor-enqueue solves both).

The test passed.

For one test.

Second Failure: The Debounce Cancellation Test

A more interesting test exercises cancellation:

@MainActor
func test_debounce_whenCalledBeforeIntervalElapsed_shouldCancelPrevious() async {
    var callCount = 0

    self.sut.debounce { callCount += 1 }
    await self.clock.waitForSuspensions(1)
    await self.clock.advance(by: .seconds(0.1))
    self.sut.debounce { callCount += 1 }
    await self.clock.waitForSuspensions(1)
    await self.clock.advance(by: .seconds(0.3))
    XCTAssertEqual(callCount, 1)  // first was cancelled, only second fires
}
@MainActor
func test_debounce_whenCalledBeforeIntervalElapsed_shouldCancelPrevious() async {
    var callCount = 0

    self.sut.debounce { callCount += 1 }
    await self.clock.waitForSuspensions(1)
    await self.clock.advance(by: .seconds(0.1))
    self.sut.debounce { callCount += 1 }
    await self.clock.waitForSuspensions(1)
    await self.clock.advance(by: .seconds(0.3))
    XCTAssertEqual(callCount, 1)  // first was cancelled, only second fires
}

I’d added waitForSuspensions(n) as a helper that yields until n sleepers are registered. Seemed reasonable.

It flaked.

The issue: when the second debounce call runs, it cancels the first task. But Task.cancel() is fire-and-forget. Between “cancel the first task” and “first task’s cancel propagates to the clock’s waiting dictionary,” there’s a window.

During that window, waiting.count can transiently be 1 — because the first task’s waiter is still there, and the second task hasn’t registered yet. waitForSuspensions(1) returns immediately, satisfied by the stale waiter. advance fires the stale waiter. The new one never gets heard.

Why does it flake? When the second debounce call cancels the first task, cancellation propagates asynchronously. The first task’s waiter might still be in waiting when the second debounce runs. But Task.cancel() causes clock.sleep to throw CancellationError, which the debouncer swallows via try?, and the subsequent guard !Task.isCancelled check returns before action()fires.

So: if the cancellation has propagated by the time the waiter is fired, the stale task throws from sleep and bails. If it hasn’t propagated yet, sleep returns normally, but Task.isCancelled is checked right after — and by then the cancellation signal has had time to land.

The guard !Task.isCancelled after the sleep is what makes this correct. It’s not a bug in the debouncer; the flakiness was coming from elsewhere.

The Real Trouble Starts

Back to the simple case:

@MainActor
func test_debounce_shouldFireActionAfterInterval() async {
    var callCount = 0
    self.sut.debounce { callCount += 1 }
    await self.clock.advance(by: .seconds(0.3))
    XCTAssertEqual(callCount, 1)
}
@MainActor
func test_debounce_shouldFireActionAfterInterval() async {
    var callCount = 0
    self.sut.debounce { callCount += 1 }
    await self.clock.advance(by: .seconds(0.3))
    XCTAssertEqual(callCount, 1)
}

Failing. callCount == 0. And it wasn’t a race — it was failing the first run, then sometimes passing, then failing again.

I spent a long time assuming this was another variant of bugs 1–5. It wasn’t. It was something I hadn’t accounted for at all.

Experiment: Point-Free’s TestClock

I looked at how Point-Free’s TestClock handles this:

<button data-code="public func advance(to deadline: Instant) async {
while self.lock.sync(operation: { self.now <= deadline }) {
await Task.megaYield() // <– yield BEFORE firing
let `return` = {
self.lock.lock()
self.suspensions.sort { $0.deadline = next.deadline else {
self.now = deadline
self.lock.unlock()
return true
}
self.now = next.deadline
self.suspensions.removeFirst()
self.lock.unlock()
next.continuation.finish()
return false
}()
if `return` {
await Task.megaYield() // <– yield AFTER returning
return
}
}
await Task.megaYield() //

public func advance(to deadline: Instant) async {
    while self.lock.sync(operation: { self.now <= deadline }) {
        await Task.megaYield()                  // <-- yield BEFORE firing
        let `return` = {
            self.lock.lock()
            self.suspensions.sort { $0.deadline < $1.deadline }
            guard let next = self.suspensions.first, deadline >= next.deadline else {
                self.now = deadline
                self.lock.unlock()
                return true
            }
            self.now = next.deadline
            self.suspensions.removeFirst()
            self.lock.unlock()
            next.continuation.finish()
            return false
        }()
        if `return` {
            await Task.megaYield()              // <-- yield AFTER returning
            return
        }
    }
    await Task.megaYield()                      // <-- final yield
}
public func advance(to deadline: Instant) async {
    while self.lock.sync(operation: { self.now <= deadline }) {
        await Task.megaYield()                  // <-- yield BEFORE firing
        let `return` = {
            self.lock.lock()
            self.suspensions.sort { $0.deadline < $1.deadline }
            guard let next = self.suspensions.first, deadline >= next.deadline else {
                self.now = deadline
                self.lock.unlock()
                return true
            }
            self.now = next.deadline
            self.suspensions.removeFirst()
            self.lock.unlock()
            next.continuation.finish()
            return false
        }()
        if `return` {
            await Task.megaYield()              // <-- yield AFTER returning
            return
        }
    }
    await Task.megaYield()                      // <-- final yield
}

Two things jumped out:

  1. They yield before firing, not just after. This gives any just-spawned sleepers a chance to register themselves before advance looks at the waiting list. It’s waitForSuspensions folded into advance — no test-side ceremony.
  2. Task.megaYield() — from swift-concurrency-extras — defaults to 20 yields, configurable via TASK_MEGA_YIELD_COUNTenv var. Their own docs call it “a blunt tool,” but a bigger hammer than my 10.

I updated my advance to yield both before and after. Still flaked.

The Real Culprit: Where Do Yields Actually Happen?

This is the part that finally clicked, and it’s the whole reason I’m writing this post.

When you write:

await Task.yield()
await Task.yield()

inside an async function, which executor does it yield?

The answer: whatever executor is currently running that function. Not necessarily MainActor. Not necessarily the executor you care about.

My MockClock was a nonisolated final class. Its advance was nonisolated async. When @MainActor test code called await clock.advance(...), the call hopped off MainActor onto the generic cooperative executor. Because (per SE-0338):

A nonisolated async function runs on the generic executor, hopping away from any actor the caller was on.

So the await Task.yield() calls inside advance were yielding the generic cooperative pool. The MainActor queue — where the debounce task’s post-sleep continuation was waiting to run — got no love at all.

From the MainActor’s perspective:

  1. Test awaits clock.advance(...) — MainActor suspends the test task.
  2. advance runs on the cooperative pool, yields there 20 times, state mutates, continuations get resumed.
  3. The debounce task’s continuation is MainActor-bound. When resumed, it’s scheduled on MainActor, but MainActor is idle waiting for advance to return.
  4. advance returns. Test task resumes on MainActor. Assertion runs.
  5. MainActor picks up the debounce continuation after the assertion has already failed.

Yielding the cooperative pool doesn’t drain MainActor. The two schedulers are independent.

This isn’t a fact I’d internalized, even after years of writing Swift Concurrency. The intuition “I’m awaiting, so the other task should get a chance to run” is subtly wrong — other tasks on the same executor get a chance. Tasks on a different executor are at that executor’s mercy.

Attempt: Make the Whole Clock @MainActor

Simplest fix: isolate the class to MainActor.

@MainActor
public final class MockClock: Clock {
@MainActor
public final class MockClock: Clock {

Problem: Clock‘s sleep(until:tolerance:) requirement is nonisolated async. If I mark the class @MainActor, sleep inherits MainActor isolation, and the protocol conformance breaks. I had to mark sleep nonisolated explicitly. Which means sleep now hops off MainActor… back to the cooperative pool… and we’re halfway back to the original problem for anything that uses sleep.

Also: any non-MainActor test code can’t use the clock at all, which is limiting.

It kind of worked, in the sense that tests stopped flaking. But it felt wrong, and I couldn’t articulate why calmly. The feeling was: I’ve removed an axis of flexibility to work around something that should be addressable directly.

The Actual Fix: isolated parameter with #isolation

SE-0420 (Swift 5.9) added isolated parameters and the #isolation macro:

public func advance(
    by delta: Duration = .zero,
    isolation: isolated (any Actor)? = #isolation
) async {
    await megaYield()
    lock.withLock { /* mutate + fire */ }
    await megaYield()
}
public func advance(
    by delta: Duration = .zero,
    isolation: isolated (any Actor)? = #isolation
) async {
    await megaYield()
    lock.withLock { /* mutate + fire */ }
    await megaYield()
}

The isolation: isolated (any Actor)? parameter tells Swift: run this function on whatever actor the caller is isolated to, passed in as this argument. #isolation is a macro that expands to the caller’s current isolation at the call site, so the parameter gets populated automatically.

When MainActor test code calls await clock.advance(by: .seconds(0.3)), advance runs on MainActor. The megaYield inside yields MainActor. The debounce task’s MainActor-bound continuation, resumed by cont.resume(), runs during those yields because MainActor is actively draining its queue.

This is the fix. And it’s the mechanism Point-Free’s TestClock uses too (they use @_unsafeInheritExecutor, the pre-SE-0420 ancestor, for compatibility with older Swift).

Why I Kept Getting This Wrong

Each wrong attempt was informed by an incomplete mental model:

  1. “Just make the state thread-safe” — I thought the flakiness was a data race. Fixing the races made tests more deterministic on paper, but didn’t address the executor mismatch.
  2. “Yield more” — I thought the issue was the scheduler needing time. It did, but not on the executor I was yielding. Yielding the wrong queue 100 times is still yielding the wrong queue.
  3. “Use waitForSuspensions” — I thought I needed an explicit synchronization point. Baking yields into advance should have subsumed this, but only if those yields happen on the right executor.
  4. “Make the clock @MainActor” — this works but at the cost of flexibility. It treats the symptom (yields on wrong executor) rather than the cause (function isolation mismatch with the caller).

The isolation: parameter treats the cause. It acknowledges that advance is a helper whose correct execution depends on running where the caller runs. That relationship is communicated through the type signature, rather than pinned to a specific actor forever.

The Final MockClock

Here are the parts that actually matter:

<button data-code="public final class MockClock: Clock, @unchecked Sendable {
private let lock = NSRecursiveLock()
private var _now: MockInstant
private var waiting: [UUID: Waiter] = [:]
private var cancelled: Set = []
private var nextSequence: UInt64 = 0

// Protocol requirement: nonisolated async. Hops off caller.
public func sleep(until deadline: MockInstant, tolerance: Duration?) async throws {
try Task.checkCancellation()
let id = UUID()
try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { cont in
let action: SleepAction = lock.withLock {
if deadline = .zero)
await megaYield()
let toResume: [CheckedContinuation] = lock.withLock {
_now = _now.advanced(by: delta)
return collectDue()
}
for cont in toResume { cont.resume() }
await megaYield()
}
private func megaYield(count: Int = 20) async {
for _ in 0..

public final class MockClock: Clock, @unchecked Sendable {
  private let lock = NSRecursiveLock()
  private var _now: MockInstant
  private var waiting: [UUID: Waiter] = [:]
  private var cancelled: Set<UUID> = []
  private var nextSequence: UInt64 = 0

// Protocol requirement: nonisolated async. Hops off caller.
  public func sleep(until deadline: MockInstant, tolerance: Duration?) async throws {
    try Task.checkCancellation()
    let id = UUID()
    try await withTaskCancellationHandler {
      try await withCheckedThrowingContinuation { cont in
        let action: SleepAction = lock.withLock {
          if deadline <= _now { return .resumeImmediately }
          if cancelled.remove(id) != nil { return .throwCancellation }
          let seq = nextSequence; nextSequence &+= 1
          waiting[id] = Waiter(id: id, deadline: deadline, sequence: seq, continuation: cont)
          return .suspend
        }
        switch action {
        case .resumeImmediately: cont.resume()
        case .throwCancellation: cont.resume(throwing: CancellationError())
        case .suspend: break
        }
      }
    } onCancel: {
      let waiter: Waiter? = lock.withLock {
        if let w = waiting.removeValue(forKey: id) { return w }
        cancelled.insert(id); return nil
      }
      waiter?.continuation.resume(throwing: CancellationError())
    }
  }
  // The magic: isolation parameter with #isolation default.
  public func advance(
    by delta: Duration = .zero,
    isolation: isolated (any Actor)? = #isolation
  ) async {
    precondition(delta >= .zero)
    await megaYield()
    let toResume: [CheckedContinuation<Void, Error>] = lock.withLock {
      _now = _now.advanced(by: delta)
      return collectDue()
    }
    for cont in toResume { cont.resume() }
    await megaYield()
  }
  private func megaYield(count: Int = 20) async {
    for _ in 0..<count { await Task.yield() }
  }
}
public final class MockClock: Clock, @unchecked Sendable {
  private let lock = NSRecursiveLock()
  private var _now: MockInstant
  private var waiting: [UUID: Waiter] = [:]
  private var cancelled: Set<UUID> = []
  private var nextSequence: UInt64 = 0

// Protocol requirement: nonisolated async. Hops off caller.
  public func sleep(until deadline: MockInstant, tolerance: Duration?) async throws {
    try Task.checkCancellation()
    let id = UUID()
    try await withTaskCancellationHandler {
      try await withCheckedThrowingContinuation { cont in
        let action: SleepAction = lock.withLock {
          if deadline <= _now { return .resumeImmediately }
          if cancelled.remove(id) != nil { return .throwCancellation }
          let seq = nextSequence; nextSequence &+= 1
          waiting[id] = Waiter(id: id, deadline: deadline, sequence: seq, continuation: cont)
          return .suspend
        }
        switch action {
        case .resumeImmediately: cont.resume()
        case .throwCancellation: cont.resume(throwing: CancellationError())
        case .suspend: break
        }
      }
    } onCancel: {
      let waiter: Waiter? = lock.withLock {
        if let w = waiting.removeValue(forKey: id) { return w }
        cancelled.insert(id); return nil
      }
      waiter?.continuation.resume(throwing: CancellationError())
    }
  }
  // The magic: isolation parameter with #isolation default.
  public func advance(
    by delta: Duration = .zero,
    isolation: isolated (any Actor)? = #isolation
  ) async {
    precondition(delta >= .zero)
    await megaYield()
    let toResume: [CheckedContinuation<Void, Error>] = lock.withLock {
      _now = _now.advanced(by: delta)
      return collectDue()
    }
    for cont in toResume { cont.resume() }
    await megaYield()
  }
  private func megaYield(count: Int = 20) async {
    for _ in 0..<count { await Task.yield() }
  }
}

And the debouncer, simpler than you might expect:

<button data-code="@MainActor
final class IntervalDebouncer {
private let debounceInterval: Duration
private let clock: any Clock
private var debounceTask: Task?

func debounce(_ action: @escaping @MainActor () -> Void) {
self.debounceTask?.cancel()
self.debounceTask = Task {
try? await self.clock.sleep(for: self.debounceInterval)
guard !Task.isCancelled else { return }
action()
}
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

@MainActor
final class IntervalDebouncer {
  private let debounceInterval: Duration
  private let clock: any Clock<Duration>
  private var debounceTask: Task<Void, Never>?

  func debounce(_ action: @escaping @MainActor () -> Void) {
    self.debounceTask?.cancel()
    self.debounceTask = Task {
      try? await self.clock.sleep(for: self.debounceInterval)
      guard !Task.isCancelled else { return }
      action()
    }
  }
}
@MainActor
final class IntervalDebouncer {
  private let debounceInterval: Duration
  private let clock: any Clock<Duration>
  private var debounceTask: Task<Void, Never>?

  func debounce(_ action: @escaping @MainActor () -> Void) {
    self.debounceTask?.cancel()
    self.debounceTask = Task {
      try? await self.clock.sleep(for: self.debounceInterval)
      guard !Task.isCancelled else { return }
      action()
    }
  }
}

Note the Task { } has no explicit @MainActor annotation. This is a common source of confusion, but since IntervalDebouncer is @MainActor, the task inherits that isolation automatically — this has been the default behavior of Task.init for a long time, via the @_inheritActorContext attribute on its closure parameter. It applies whether you’re in Swift 5 or Swift 6 language mode. The compiler enforces this — action is typed @MainActor () -> Void, so if the task weren’t MainActor-isolated, calling action() inside it would fail to compile.

(The common misconception — that Task { } runs on the cooperative pool by default — comes from conflating it with Task.detached { }, which explicitly does not inherit isolation. It’s worth internalizing this distinction: Task { } inherits, Task.detached { } does not.)

If you’re skeptical (I was, more than once in this debugging journey), verify it empirically. Drop a print(Thread.isMainThread)or MainActor.assertIsolated() at the top of the task body. Running the test 1000 times with the print in place, you’ll see trueevery time, and the Debug Navigator will show the task’s thread as com.apple.main-thread. The compiler will nudge you toward MainActor.assertIsolated() over Thread.isMainThread in async contexts — that’s the more correct check because it tests isolation, which is what actually matters in Swift Concurrency, not thread, which is a lower-level implementation detail.

The test:

@MainActor
func test_debounce_shouldFireActionAfterInterval() async {
    var callCount = 0
    self.sut.debounce { callCount += 1 }
    await self.clock.advance(by: .seconds(0.3))
    XCTAssertEqual(callCount, 1)
}
@MainActor
func test_debounce_shouldFireActionAfterInterval() async {
    var callCount = 0
    self.sut.debounce { callCount += 1 }
    await self.clock.advance(by: .seconds(0.3))
    XCTAssertEqual(callCount, 1)
}

Deterministic. No waitForSuspensions. No explicit yields. No magic.

It’s worth naming what just happened. Earlier in the debugging, I’d added waitForSuspensions(n) — a helper that yielded until n sleepers were registered — to paper over the “task spawned but hasn’t enqueued its sleeper yet” race. With the final design, that helper becomes redundant. The pre-megaYield inside advance does the same job, but implicitly — and because advance now inherits the caller’s isolation, those yields actually drain the caller’s executor (MainActor, in our case), giving the debounce task time to register before advance fires anyone. The “paper over” helper existed because advance was broken. Fixing advance deleted the helper.

What I Actually Learned

Four things I should have known but didn’t have crisp mental models for:

  1. Task { } inherits actor isolation from the enclosing context. Inside a @MainActor method, Task { } runs on MainActor — no explicit annotation needed. This has been the default since early Swift concurrency via @_inheritActorContext on Task.init‘s closure parameter, in both Swift 5 and Swift 6 language modes. The common misconception that Task { } always runs on the cooperative pool comes from conflating it with Task.detached { }, which genuinely does not inherit. If you find yourself writing Task { @MainActor in } inside a @MainActor type, it’s redundant — though harmless.

  2. nonisolated async functions hop off the caller’s actor. SE-0338 made this the rule. The intuition “I’m on MainActor, my callees are too” is wrong. It’s only true for isolated callees.

  3. Task.yield() yields the current executor — not some universal queue. Yielding the cooperative pool doesn’t drain MainActor. If your test is on MainActor and the work you want drained is on MainActor, your yields must happen on MainActor.

  4. The isolated parameter pattern (SE-0420) is the right tool for utility async functions that need to execute on the caller’s actor. It’s the difference between a helper that cooperates with your isolation model and one that fights it.

The meta-lesson is that Swift Concurrency’s scheduling model is more detailed than the textbook async/await presentation suggests. Tasks, actors, executors, and isolation are four distinct concepts that interact in subtle ways. A test that “should be deterministic” is often assuming a model of execution that doesn’t match what the runtime actually does.

Flaky tests are useful teachers when you refuse to paper over them. I got a cleaner MockClock and a much better mental model of concurrency out of this one. Worth every debugging hour.

Thanks to Point-Free’s swift-clocks and swift-concurrency-extras libraries, whose source code was the reference implementation I kept checking my work against. If you want a production-grade test clock, use theirs.