An export screen acquired a server-side lease on a document, wrote a temporary file, and began uploading. The user navigated away. SwiftUI cancelled the .task, the upload stopped, and control reached the cleanup that releases the lease.

The release is a network call. Network calls check for cancellation. The task was cancelled, so the release threw CancellationError before it sent a byte.

The app abandoned the work and kept the resource. The document stayed locked for as long as the server’s timeout allowed, and the next person who tried to export it was told someone else was editing.

This bug survives review because the cleanup is visibly there. A defer block sits on screen, so everyone assumes the obligation is met. The block ran. The release inside it did not. Swift 6.4 adds two features that make the correct version expressible inside structured concurrency. What follows is what they do, what they did when I ran them, and what they still leave to you.

The failure, in a few lines

SwiftGitHub
import Foundation

actor EventLog {
    private(set) var entries: [String] = []
    func record(_ entry: String) { entries.append(entry) }
}

func releaseLease(_ log: EventLog) async {
    do {
        try await Task.sleep(for: .milliseconds(20))   // stands in for a network call
        await log.record("released")
    } catch {
        await log.record("release skipped: \(type(of: error))")
    }
}

func exportWithoutShield(_ log: EventLog) async throws {
    defer { await releaseLease(log) }
    try await Task.sleep(for: .seconds(5))             // the cancellable work
}

Run exportWithoutShield in a task, cancel it after 50 milliseconds, and the log holds one line: release skipped: CancellationError.

Cancellation in Swift is a flag on the task, and the flag stays set. Every cancellation-aware API called from that task afterwards sees it, including the ones in your cleanup. URLSession, Task.sleep, and most async clients are cancellation-aware, which is usually exactly what you want, and exactly what breaks here.

The defer { await … } is itself new. Before Swift 6.4, a defer body could not await, so asynchronous cleanup had to be repeated on every exit path or pushed into an unstructured task.

Two features, two jobs

SE-0493, await in defer. A defer body in an async function may now suspend. The enclosing scope does not finish until the deferred work completes, so cleanup stays in the function that owns the resource and runs on every exit: return, throw, and cancellation. This is a compiler feature; the example above typechecks for a macOS 14 deployment target with the Swift 6.4 toolchain.

SE-0504, task cancellation shields. withTaskCancellationShield runs an operation during which the task’s cancellation is not observable. Inside it, Task.isCancelled is false and Task.checkCancellation() does not throw. When the shield ends, the task is exactly as cancelled as before. This one needs the runtime: in the Xcode 27.2 SDKs it is available from the 27.0 OS releases, so an app that deploys further back needs an availability check and a fallback.

Neither does the other’s job. An async defer without a shield is the failure above. A shield without defer protects cleanup only on the paths where someone remembered to call it.

Together:

SwiftGitHub
@available(macOS 27.0, iOS 27.0, tvOS 27.0, watchOS 27.0, visionOS 27.0, *)
func exportWithShield(_ log: EventLog) async throws {
    defer {
        await withTaskCancellationShield {
            await log.record("in shield: isCancelled=\(Task.isCancelled)")
            await releaseLease(log)
        }
        await log.record("after shield: isCancelled=\(Task.isCancelled)")
    }
    try await Task.sleep(for: .seconds(5))
}

The same experiment on Swift 6.4.2 and macOS 27.2:

Plain textGitHub
in shield: isCancelled=false
released
after shield: isCancelled=true

The work was cancelled, the release completed, and the task is still cancelled, so the caller sees CancellationError as before. The cleanup became reliable. The function’s cancellation semantics did not change.

Name the obligation when you acquire the resource

The language features are the easy part. The design is deciding what is owed, to whom, and what happens when it cannot be paid. At every acquisition, three questions:

  • What do we own once acquisition succeeds?
  • What event ends that ownership?
  • What happens if the process is gone before that event?

The third question is what keeps a cancellation mechanism from being mistaken for crash recovery. A temporary file needs deleting. A lease needs releasing or expiring. A half-finished multipart upload needs an abort or a server-side expiry rule. Different obligations, different failures, and a single cleanup() returning Void hides all of them.

The shape for a remote lease:

SwiftGitHub
struct Lease: Hashable, Sendable {
    let id: UUID
}

protocol LeaseService: Sendable {
    func acquire() async throws -> Lease
    func release(_ lease: Lease) async throws
}

protocol PendingReleaseStore: Sendable {
    func add(_ lease: Lease) async
    func remove(_ lease: Lease) async
    func all() async -> [Lease]
}

@available(macOS 27.0, iOS 27.0, tvOS 27.0, watchOS 27.0, visionOS 27.0, *)
func withLease<Value: Sendable>(
    from service: any LeaseService,
    pending: any PendingReleaseStore,
    isolation: isolated (any Actor)? = #isolation,
    operation: (Lease) async throws -> Value
) async throws -> Value {
    let lease = try await service.acquire()
    await pending.add(lease)                 // the obligation exists from this line

    defer {
        await withTaskCancellationShield {
            do {
                try await service.release(lease)
                await pending.remove(lease)
            } catch {
                // The lease stays in the pending store for the recovery pass.
            }
        }
    }

    try Task.checkCancellation()
    return try await operation(lease)
}

func recoverPendingReleases(
    service: any LeaseService,
    pending: any PendingReleaseStore
) async {
    for lease in await pending.all() {
        if (try? await service.release(lease)) != nil {
            await pending.remove(lease)
        }
    }
}

Each decision, in the order it appears:

Acquire and release live in one function. A caller cannot obtain a lease without also obtaining its release. That is why the shape is with…: ownership has the extent of a lexical scope.

The shield wraps only the release. The operation stays fully cancellable. If the user leaves, the export should stop. Only the obligation must survive.

The obligation is recorded as soon as it exists. pending.add writes the lease to durable storage straight after acquisition, before the operation starts. A successful release removes the record. If the process dies in the middle of a 400 MB upload, or the release throws or times out, the record remains and recoverPendingReleases pays it at next launch. Recording it only when the release begins would protect the release and leave the much longer operation uncovered. Without the record, a lease lost to a crash simply disappears.

release is allowed to throw. A non-throwing signature would not make the network reliable. It would only move the failure somewhere invisible. The error is caught deliberately, and the obligation stays in the store.

checkCancellation() comes after the defer. If the task was cancelled while acquire was in flight and the server granted the lease anyway, the function exits at once and the release still runs.

The isolation parameter lets a main-actor caller pass a closure that touches its own state. Without it, the closure would have to be @Sendable, which pushes callers toward unsafe workarounds.

The primary result and the cleanup result stay apart on purpose. If the export succeeded and the release failed, reporting “export failed” invites the user to export again and create a duplicate. Reporting success and forgetting the lease leaks it. The function returns the export’s result; the pending store carries the unpaid obligation. Those two facts have different audiences.

A shielded region must bound itself

Inside a shield, cancellation can no longer stop anything. That is the point, and it is the risk. A release against an unreachable server, through a client configured to wait indefinitely, will hold the task open indefinitely. The view is gone, the user has moved on, and a task is still parked on a socket.

So the shielded work needs a limit that does not rely on cancellation: a request timeout on the release, a fixed number of attempts, a lease with a short server-side expiry. An unbounded retry loop inside a shield is a hang waiting for bad connectivity.

Racing the release against a timer child works inside a shield, provided the release cooperates. A task group inside a shield with a 50-millisecond timer child and a two-second child ended after 52 milliseconds once the group called cancelAll(): the shield hides cancellation arriving from outside, not cancellation you issue inside it. It is still not a hard timeout. A task group waits for every child before returning, so a child that ignores cancellation holds the scope open as long as it likes. The bound belongs in the transport, where it holds whatever the task’s state.

Keep the shield small for a related reason. Shielding the whole export because its last step must finish means the user can no longer cancel a 400 MB upload.

What the shield covers

The proposal is precise about scope, and the behavior is worth seeing before relying on it. Same toolchain, surrounding task already cancelled:

ArrangementChild observes cancellation?
Task group created inside the shieldNo
async let created inside the shieldNo
Group created outside; only the addTask call wrapped in a shieldYes

The last row is the one to remember. A shield protects the execution that happens within it. Wrapping the statement that schedules a child does nothing for the child’s body, which runs later, outside the shield. Put the shield around the structured scope that owns the children, or inside the child around the part that must finish. (A Task {} created inside a shield also runs uncancelled, but it would anyway: unstructured tasks never inherit cancellation.)

When a release has strict ordering (stop the upload, abort the multipart session, delete the local file), write it sequentially. Concurrency in cleanup buys little and makes partial failure harder to reason about.

The unstructured escape hatch changes the contract

The pre-6.4 workaround is still everywhere:

SwiftGitHub
func exportWithDetachedCleanup(_ log: EventLog) async throws {
    defer {
        Task { await releaseLease(log) }
    }
    try await Task.sleep(for: .seconds(5))
}

The new task is not cancelled, so the release goes out. But the function now promises something else: it returns before the release has finished. Its caller cannot know whether the lease is free, a test cannot await the cleanup, and an error in the release has nowhere to go. If the caller retries immediately, it may race its own previous release.

For OS versions without shield support, there is a structured form of the same idea:

SwiftGitHub
func releaseSurvivingCancellation(_ log: EventLog) async {
    if #available(macOS 27.0, iOS 27.0, tvOS 27.0, watchOS 27.0, visionOS 27.0, *) {
        await withTaskCancellationShield {
            await releaseLease(log)
        }
    } else {
        await Task { await releaseLease(log) }.value
    }
}

The fallback creates an unstructured task, which does not inherit the caller’s cancellation, and awaits its value, so the caller still does not return until the release completes. Unlike Task.detached, it keeps the caller’s task-local values, priority, and actor context. What it gives up is its place in the task tree: it is not a child, so a task group’s cancelAll() cannot reach it, and tools that show the tree will not list it under the export. On older runtimes, it is the best available trade.

Handing the release to a long-lived owner, an app-level service that outlives any screen, can be the right design. Then make the transfer explicit in the API and durable in storage. A detached task is not durability. When the process is terminated, it goes too.

Crash recovery lives outside the task

Everything above is one process finishing what it started. No Swift scope survives the process being killed, the device restarting, or the battery dying. Each obligation needs a second mechanism that does not depend on your code getting another chance to run:

  • a server lease expires without renewal;
  • an incomplete multipart upload is removed by a storage lifecycle rule;
  • a local staging directory is reconciled at launch;
  • a committed business action is announced through a transactional outbox.

Write the two guarantees as separate sentences and give each an owner. “The release is awaited before this function returns” is a statement about one process. “An abandoned lease becomes available again within two minutes” is a statement about recovery. Neither implies the other, and a design review should find both.

Tests at each cancellation point

Cancel at every boundary and assert the state of the resource, not just the thrown error:

  • before acquire returns: no lease is held afterwards;
  • immediately after acquisition: the lease is released;
  • in the middle of the operation: the lease is released and the caller gets CancellationError;
  • while the release is in flight: the release completes;
  • release fails: the lease is in the pending store, and the recovery pass clears it;
  • release sent twice for the same lease: the server treats the second as a no-op.

Use a controllable fake so the test can hold the release open and verify that withLease has not yet returned. Test recovery separately by never running the cleanup at all, which is what a crash looks like.

The last case is a requirement on the server as much as the client. A release the recovery pass can retry must be idempotent and must name the lease, not “whatever this session currently holds.”

What to ask of your own code

  • Which defer blocks or catch clauses call a cancellation-aware API?
  • For each shielded region, what bounds it?
  • Does any cleanup run in a Task {} whose completion nobody awaits?
  • For each resource, where is the recovery path that works after a crash?
  • Which cleanup still depends on the user keeping a screen open long enough?

Cancellation is part of an operation’s protocol, with obligations of its own. Treated as an afterthought, it is how resources leak between functions that each look perfectly structured.

References

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