You are chasing a stale screen. You set a breakpoint, the timing changes, and the bug disappears. You remove the breakpoint and it comes back once in five runs. Then a meeting starts.

An hour later you remember the symptom and the three files you have open. You do not remember which run showed that the repository was innocent, or why you stopped suspecting the cache. So you check both again.

The investigation lost its state. We put real effort into making apps recover from interruption: we persist drafts, checkpoint uploads, and restore scenes. An investigation into an intermittent bug is a long-running operation with expensive intermediate results, and most of us keep all of it in working memory, which is the most volatile storage available.

What follows is the method I use for bugs that take longer than one sitting. Most of it is ordinary engineering discipline pointed at the investigation itself.

Write the observation before the explanation

"The actor is racing" is a hypothesis. "Response A was requested before B, completed after B, and replaced the visible result" is an observation. The observation stays true when the hypothesis turns out to be wrong, which with intermittent bugs it usually does at least once.

So the first thing I write is a note with no theory in it:

Plain textGitHub
Expected:
After selecting workspace B, visible articles belong to B.

Observed:
The title shows B, but five article IDs belong to A.

Known sequence (run 3, from logs):
1. Request A started.
2. Workspace changed to B.
3. Request B completed and rendered.
4. Request A completed and rendered.

Not yet established:
Whether the repository or the presentation layer accepted A.

The last section matters most. It names the boundary where knowledge stops, and so it tells me what the next experiment has to decide. Nothing in the note assumes actors, caching, or cancellation is at fault.

Keep the competing explanations side by side

Once I have a favorite theory, I start reading every log line as support for it. A short table keeps the alternatives in view, each with the evidence that would distinguish it:

HypothesisWhat I would see if it were true
Repository cache mixes accountsWrong-workspace articles already present in the repository's output
Old request is still allowed to update the screenRepository output correct for A; A applied after B was selected
List reuses cell stateView model holds B's articles; rendered cells show A's
Server returns mixed dataRaw response for B contains A's article IDs

The table exists to choose the next experiment. A good experiment splits the list: one log line at the repository's output separates the first hypothesis from the second and third in a single run. If I have added six log statements and no row has been crossed out, the instrumentation is describing activity instead of testing a claim, and I stop adding to it.

Log identity first, volume second

Twenty thousand lines of "did load" do not show which load. What connects events across layers is a small set of identifiers captured when the operation starts:

SwiftGitHub
import Foundation
import os

struct InvestigationContext: Sendable {
    let operationID: UUID
    let selectionGeneration: UInt64
    let accountScope: String
}

enum Diagnostics {
    @TaskLocal static var context: InvestigationContext?

    static let feed = Logger(
        subsystem: "com.example.reader", category: "feed"
    )
}

func logResponseApplied(articleCount: Int) {
    guard let context = Diagnostics.context else { return }
    Diagnostics.feed.debug("""
        applied op=\(context.operationID, privacy: .public) \
        gen=\(context.selectionGeneration) \
        scope=\(context.accountScope, privacy: .public) \
        count=\(articleCount)
        """)
}

func loadFeed(
    generation: UInt64,
    accountScope: String,
    perform: @Sendable () async -> Int
) async {
    let context = InvestigationContext(
        operationID: UUID(),
        selectionGeneration: generation,
        accountScope: accountScope
    )
    await Diagnostics.$context.withValue(context) {
        let count = await perform()
        logResponseApplied(articleCount: count)
    }
}

Two details make this dependable.

The context is bound with a task-local value. Everything called inside withValue, including child tasks and Task {} created there, sees the same context without it being threaded through every signature. Task.detached does not inherit it, which is one more reason to know where detached tasks exist in the codebase.

The context is captured at the start and never recomputed. The tempting shortcut is to read "the current account" at the moment of logging. For a delayed callback, that stamps the old response with the new account, and your diagnostics now contain the same causality bug you are trying to find.

accountScope should be a diagnostic label such as a short hash or an ordinal for the session. Tokens, email addresses, document contents, and location history do not belong in logs. With Logger, interpolated strings are redacted in collected logs unless marked .public, so mark only what is safe and leave everything else at the default.

To read the result without Xcode attached, which matters when the debugger itself changes the timing:

Plain textGitHub
log stream --level debug --predicate 'subsystem == "com.example.reader"'

Measure elapsed time with a clock that cannot jump

Wall-clock timestamps are useful for lining events up with a server log or a user's report. They are unreliable for durations, because the system clock can be adjusted while your code is running.

SwiftGitHub
func measureLoad(
    isolation: isolated (any Actor)? = #isolation,
    _ work: () async -> Void
) async -> Duration {
    let clock = ContinuousClock()
    let start = clock.now
    await work()
    return start.duration(to: clock.now)
}

func signpostedLoad(
    isolation: isolated (any Actor)? = #isolation,
    _ work: () async -> Void
) async {
    let signposter = OSSignposter(logger: Diagnostics.feed)
    let state = signposter.beginInterval("feed-load", id: signposter.makeSignpostID())
    await work()
    signposter.endInterval("feed-load", state)
}

The isolation parameter makes each helper run on the caller's actor. Without it, a nonisolated async function hops off the main actor, the closure has to cross that boundary, and Swift 6 rejects a call such as await measureLoad { await model.refresh() } from main-actor code. A measuring helper that cannot be called from the code you want to measure is not much use.

ContinuousClock keeps counting while the device is asleep; SuspendingClock pauses. Pick the one that matches the question ("how long did the user wait" versus "how much time did the process spend"). The signpost version records the same interval where Instruments can display it on a timeline next to CPU and network activity, without a debugger pause.

An instant from one device's monotonic clock cannot be compared with another device's. Cross-device ordering needs shared identifiers and an honest allowance for clock skew. A nanosecond-precision timestamp does not make up for a missing correlation ID.

Replace timing luck with controlled ordering

At this point the note says request A finished after B. The usual next step is a test that starts A, sleeps 100 milliseconds, starts B, and hopes. That test passes on your machine, fails on CI under load, and reproduces the bug in neither place reliably.

The alternative is a service double that holds every request until the test releases it, and lets the test wait until a request has actually arrived:

SwiftGitHub
actor ControlledService<Key: Hashable & Sendable, Value: Sendable> {
    private var pending: [Key: CheckedContinuation<Value, any Error>] = [:]
    private var arrivalWaiters: [Key: [CheckedContinuation<Void, Never>]] = [:]

    func request(_ key: Key) async throws -> Value {
        try await withTaskCancellationHandler {
            try await withCheckedThrowingContinuation { continuation in
                if Task.isCancelled {
                    continuation.resume(throwing: CancellationError())
                    return
                }
                pending[key] = continuation
                arrivalWaiters.removeValue(forKey: key)?.forEach { $0.resume() }
            }
        } onCancel: {
            Task { await self.cancel(key) }
        }
    }

    func waitUntilRequested(_ key: Key) async {
        if pending[key] != nil { return }
        await withCheckedContinuation { waiter in
            arrivalWaiters[key, default: []].append(waiter)
        }
    }

    func complete(_ key: Key, with value: Value) {
        pending.removeValue(forKey: key)?.resume(returning: value)
    }

    func fail(_ key: Key, with error: any Error) {
        pending.removeValue(forKey: key)?.resume(throwing: error)
    }

    private func cancel(_ key: Key) {
        pending.removeValue(forKey: key)?.resume(throwing: CancellationError())
    }
}

Each request has exactly one terminal transition: completed, failed, or cancelled. All three go through removeValue, so a continuation can never be resumed twice, and a cancelled request can never stay suspended forever. Those are the two ways a hand-rolled test double usually breaks, and the second one shows up as a test suite that hangs.

With it, the sequence from the note becomes a test that produces the same interleaving on every run:

SwiftGitHub
@MainActor
final class WorkspaceScreen {
    private(set) var visibleArticles: [String] = []
    private var generation = 0
    private let service: ControlledService<String, [String]>

    init(service: ControlledService<String, [String]>) {
        self.service = service
    }

    func select(workspace: String) async {
        generation += 1
        let token = generation
        guard let articles = try? await service.request(workspace) else { return }
        guard token == generation else { return }
        visibleArticles = articles
    }
}

@MainActor
func lateResponseDoesNotReplaceCurrentSelection() async -> Bool {
    let service = ControlledService<String, [String]>()
    let screen = WorkspaceScreen(service: service)

    let selectA = Task { await screen.select(workspace: "A") }
    await service.waitUntilRequested("A")

    let selectB = Task { await screen.select(workspace: "B") }
    await service.waitUntilRequested("B")

    await service.complete("B", with: ["b1", "b2"])
    await selectB.value

    await service.complete("A", with: ["a1", "a2"])
    await selectA.value

    return screen.visibleArticles == ["b1", "b2"]
}

Delete the line guard token == generation else { return } and this returns false every time. A test like that is worth far more than a mock asserting that request was called twice, because it encodes the user's failure and not the implementation's call pattern. In a Swift Testing target the function body becomes a @Test with #expect on the last line.

A breakpoint changes the system you are studying

Pausing a thread changes scheduling, lets timeouts expire, lets buffers fill, and reorders callbacks. When the bug goes away under the debugger, that tells you something: the defect depends on timing. It does not tell you the bug is fixed.

So I use several kinds of evidence and keep track of how much each one disturbs execution. Breakpoints are best for inspecting state at a known moment and worst for ordering. Logs and signposts perturb very little. Deterministic tests remove timing from the picture altogether. Crash reports and MetricKit payloads describe what really happened on users' devices.

For a problem that appears only in Release, reproduce with the Release configuration: optimization on, the same compiler flags, the same build of each binary dependency. A Debug build can confirm your logic while never generating the code path or the timing that fails. Changing the scheme's Run action to Release for an afternoon is cheaper than a week of reasoning about a build you are not running.

Leave a checkpoint you can resume from

Before stopping, for a meeting or for the day, I write five things:

  • the latest confirmed observation;
  • each hypothesis eliminated, with the evidence;
  • the current leading hypothesis;
  • the exact next experiment;
  • the branch, build, device, and reproduction input.
Plain textGitHub
Confirmed:
Repository returns correctly scoped snapshots (run 7, log line at
repository output shows only A-IDs for request A).
Presentation applies a completion without checking selection generation.

Eliminated:
Cache mixing: purging the cache did not change reproduction (runs 4-5).
Server payload: response for B contains only B-IDs (run 7).

Next experiment:
Add generation comparison where the response is applied.
Run the B-then-A controlled test before any live networking.

Environment:
Commit, build number, device and OS as recorded in run-7 metadata.

Record the environment from the actual run. An invented or remembered build number is worse than a blank, because the next person will trust it.

The "Eliminated" section saves the most time. It stops tomorrow's version of me, a colleague, or a coding assistant picking up the task from spending an hour re-testing the cache. Handing an investigation to an AI assistant without this section reliably produces a confident re-exploration of the first two hypotheses.

Tell a repair from a symptom suppressor

Several changes make this bug rarer without fixing it.

Cancelling request A when B starts reduces the window. Cancellation is cooperative, though, and a response that was already decoded when the flag was set will still be delivered.

Moving the assignment onto the main actor serializes the writes. They are now data-race free and still in the wrong order. Freedom from data races and correctness of the domain are separate properties, and Swift 6 only checks the first.

Adding a 300 millisecond debounce makes the reproduction harder for you and unchanged for a user on a slow network.

A repair states an invariant, here "a response may only be applied if its generation is still the current one", and enforces it at the point where the result is accepted. The regression test must fail against the old code. If a test only asserts that a new helper was called, it is testing the patch and not the failure.

Leave something reusable behind

When the investigation closes, what remains should be small: the regression test, two or three sentences in the pull request explaining the mechanism, and whatever instrumentation deserves to stay in production (the generation and operation IDs usually do; the verbose payload logging does not). Remove temporary logging that touches user data. Keep the reproduction input if it can be stored without personal data in it.

The next engineer should be able to explain why the fix works without reconstructing your afternoon.

What to ask of your own practice

  • Can you state the current bug as an observation with no cause in it?
  • Which hypotheses have you eliminated, and where is that written?
  • Do your logs carry an operation identity captured at the start?
  • Does your reproduction control ordering, or does it wait and hope?
  • If you were interrupted now, how long would resuming take?

Good debugging does not require holding the whole system in your head. It requires keeping enough evidence outside it that the next decision is still grounded when your attention comes back.

References

If this edition sharpened your next review, you can buy me a coffee.