Kevin Coughlin. Blog

Tests that passed on Task.yield() luck

In ShoutKit, async tests that depended on task order were passing on scheduling luck. A drain of 50 bare Task.yield()s, and negative checks such as pause during loading cancels pending start, passed without testing anything when the endpoint hop was slow. shoutkit#295 (b0511be) runs them inside swift-concurrency-extras' withMainSerialExecutor, where the main actor's jobs and the global executor's share one FIFO queue.

A drain of fifty yields

drainMainQueue had 20 call sites, across PlaybackControllerTests, PlaybackIntentBoundaryTests, PlaybackControllerAlbumArtRetryTests, and PlaybackControllerAlbumArtTests. It was a fixed loop:

func drainMainQueue() async {
    for _ in 0 ..< 50 {
        await Task.yield()
    }
}

pause during loading cancels pending start plays a station, pauses before the endpoint resolution task has a chance to run, drains, and expects startedURLs to stay empty ("stream must not start after the user paused"). Several callers make that kind of negative check. They passed without testing anything if the endpoint hop was slow.

Callers now run under the serial executor, and the drain is one Task.megaYield():

/// Lets every job already queued, and the short chains they start, run before
/// the test continues. Only deterministic inside `withMainSerialExecutor`, where
/// every job (the main actor's and the global executor's) shares one FIFO queue;
/// call it only from tests in a `MainSerialExecutorTests` suite.
func drainMainQueue() async {
    await Task.megaYield()
}

On that queue, Task.megaYield() runs everything already queued, and whatever that work queues in turn, in the same order every time. The yields inside TestClock.advance do the same. The queued endpoint work has run before the assertion.

Late album art waited on a gate

Yield counts were the same kind of guess. late art for previous track is discarded had the old lookup yield 400 times, then the test yield 600 times. track change clears published artwork before publishing new metadata yielded 200 times inside the new lookup and polled with waitUntil.

The old lookup now waits on a Gate, a latch the fake holds until the test opens it. The test checks that the new art applied, opens the gate, and checks that the late old art is dropped:

@Test func `late art for previous track is discarded`() async throws {
    try await withMainSerialExecutor {
        let output = FakeAudioOutput()
        let controller = makeController(stations: [station()], output: output)
        let oldArt = try #require(URL(string: "https://example.com/old.jpg"))
        let newArt = try #require(URL(string: "https://example.com/new.jpg"))
        let oldLookup = Gate()
        controller.trackResourcesProvider = { track in
            if track.title == "Old" {
                // Held until the track change below has resolved;
                // cancellation and the staleness guard must keep this
                // result from applying when it finally lands.
                await oldLookup.wait()
                return TrackResources(artworkURL: oldArt)
            }
            return TrackResources(artworkURL: newArt)
        }

        controller.play(station())
        await waitForStart(output)
        output.onStatusChange?(.playing)
        output.emitTrackInfo("Old", "Band")
        output.emitTrackInfo("New", "Band")
        await drainMainQueue()
        #expect(controller.albumArtURL == newArt)

        oldLookup.open()
        await drainMainQueue()
        #expect(controller.albumArtURL == newArt)
    }
}

The track-change test holds the new lookup the same way, checks that the published events are art:nil then track:New while it is held, then opens the gate. Both tests live in PlaybackControllerAlbumArtOrderingTests, split out so PlaybackControllerAlbumArtTests stays inside SwiftLint's type_body_length.

The same replacement landed in the other racy waits. a meter is attached, fed, and detached when its stream ends looped up to 50 yields while plugins were non-empty. On the serial queue the detach hop is already queued when the consumer's value returns, so one Task.yield() is enough. The RadioDirectory fake held a request for a real 150 ms, and the test had 30 real milliseconds to land a second call beside it. The fake now sleeps on a TestClock. The test checks topStationsCalls == 1 before starting the second call, then advances. The identity test holds the US fetch twice as long as the JP one, so the US result lands last. Browse genre and refresh tests dropped a 2 second waitUntil poll, real 200 ms holds, and sleeps of 20 ms and 300 ms. The test holds the lookup and releases it. Task.megaYield() replaces the poll, and the 2 second helper is gone.

One parent suite, because the hook is process-wide

withMainSerialExecutor sets swift_task_enqueueGlobal_hook for the whole process and restores the previous value when it returns. Two calls that overlap can restore each other's state. One test loses serial execution partway through, or the hook stays on after both finish. Swift Testing runs suites in parallel, and .serialized only orders the tests inside the suite it is on. Two .serialized suites still run alongside each other.

Each test target therefore has exactly one .serialized suite that uses the hook. In Playback that suite replaces the PlaybackTimingTests parent from the clock change, and the timer suites and the controller suites are nested under it:

/// `withMainSerialExecutor` sets a process-wide runtime hook and restores the
/// previous value when it returns. Two calls that overlap can restore each
/// other's state: one test loses serial execution partway through, or the hook
/// stays on after both finish. `.serialized` here covers every suite nested
/// under it, so only one of these tests runs at a time; separate `.serialized`
/// suites would still run alongside each other, which is why there is one
/// parent. No suite outside it in this target uses the hook.
@Suite(.serialized)
struct MainSerialExecutorTests {}

RadioDirectory's suite is CachingRadioDirectoryInFlightTests. BrowseFeatureCore's is BrowseViewModelTests. Other suites in the same process keep running in parallel. While the hook is on, their global-executor jobs run on the main queue too. That is slower, and those jobs can delay a test's chain of work. They cannot reorder it. Nothing in the three targets' sources or tests blocks the main thread waiting on another task: no semaphores, no DispatchGroup.wait, no .sync, no thread sleeps.

swift-concurrency-extras 1.4.3 is exact, MIT, and a test-only dependency of RadioDirectory, Playback, and BrowseFeatureCore. BrowseFeatureCore/Package.resolved pins 1.4.3. It is not linked into the app.

On the host, swift test --disable-xctest (Xcode beta, each package rebuilt from a clean .build), five runs with --parallel and five with --no-parallel, passed 10/10 for each package. RadioDirectory was 144 tests in 23 suites. Playback was 208 tests in 25 suites, about 1.4–1.5 s each. BrowseFeatureCore was 18 tests in 2 suites, 0.007–0.009 s. The old real holds there took about 0.5 s. Removing the genre-selection guard in BrowseViewModel fails stale prior genre response is discarded after switching selection at the post-release assertion. The simulator plan was not run. That Mac has no iOS Simulator runtime.

What the hook does not reorder

The hook moves Swift global-executor jobs onto the main queue. It does not touch the main dispatch queue. Persistence's DiagnosticsService and LibraryStore remote-change tests wait on an Observations hop and a NotificationCenter post on that dispatch queue, and they stay polls. PlaybackEngineAudioStreaming's eventually waits on callbacks from Foundation's stream threads, which are not the Swift global executor.

Also left as they were: SearchFeatureCore's debounce tests (400 ms sleeps and a 5 s poll), because the delay is the behavior under test and the view model has no clock seam. DesignSystem's lookup coalesces concurrent requests still holds for a real 100 ms. That package is iOS-only, so there is no host run that could check a change. waitForStart and waitUntil stay a condition poll with a 30-second failure deadline, used by about 100 playback tests. They only wait until the condition becomes true.

The clock was the previous change

shoutkit#293 (8a7e976) injected any Clock<Duration> into the one-minute discovery cache and the playback timers: reconnect backoff, the stall ceiling while a station is still connecting, paused-release, the resume watchdog, the hintless-interruption window, and the sleep timer. Production defaults each parameter to ContinuousClock. Tests pass a TestClock into the initializer and advance it. There is no Container.clock registration. The deadline is taken when the timer is scheduled, as clock.now.advanced(by: duration), and the task sleeps until that instant. Advancing a TestClock immediately after scheduling cannot move time before the deadline exists. Production timing is unchanged. The timer suites already ran inside withMainSerialExecutor, under one serialized parent, so TestClock.advance ran the timer task, its registration, and the fire in a fixed order.

On a TestClock, the discovery cache is still fresh at 59 seconds and refetches genres and top stations at 61. Reconnect does nothing at 1 second of a 2 second backoff, starts the retry at 2 seconds, and the next backoff is 4 seconds. A station that is still connecting is buffering at 29 seconds and torn down at 30. After that, what was left was task order. That is what #295 fixes.

What I would repeat