Equivalent to withTaskCancellationShield to use in previous OS versions

For some reason, I found out that withTaskCancellationShield is only available in 27 OS which is interesting and annoying at the same time.

func processFile(at url: URL) async throws {
    let handle = try FileHandle(forReadingFrom: url)

    defer {
        // flushMetrics is a network call, so it can suspend after cancellation
        // is requested; the shield ensures it runs to completion and isn't
        // included in cancellation.
        await withTaskCancellationShield {
            await flushMetrics(for: url)
            try? handle.close()
        }
    }

    try await processContents(of: handle)
}

So I was asking myself what if I use Task.detached to have the same behaviour but pre 27 OS, something like this:

func processFile(at url: URL) async throws {
    let handle = try FileHandle(forReadingFrom: url)

    defer {
        Task.detached {
            await flushMetrics(for: url)
            try? handle.close()
        }
    }

    try await processContents(of: handle)
}

Since Task.detached detaches the task from the parent task, so if the parent task is canceled this task shouldn't be affected.

if this solution is wrong, is there any other way to have something similar to withTaskCancellationShield to use in previous os versions ?

You don't need to use Task.detached for this (and should generally avoid Task.detached anyway), all Tasks break automatic cancellation since they're technically unstructured.

FYI, when new Swift functionality is OS limited like this, it's typically because they use a new type or Swift runtime capability that can't be back deployed on Apple platforms.

3 Likes

Yeah we're not able to back deploy this easily because it is a new runtime feature;

Your snippet is almost close enough... The problem you have though is that you don't await on the flushing/closing which could be a problem, so I would recommend putting an await Task{}.value there inside the defer (which supports async since swift-evolution/proposals/0493-defer-async.md at main ¡ swiftlang/swift-evolution ¡ GitHub)


    defer {
        await Task {
            await flushMetrics(for: url)
            try? handle.close()
        }.value
    }
3 Likes

but why awaiting on the Task{}.value is better and what is the problems that can happen if otherwise was happened ?

I suspected that this is the reason but wanted to make sure. Either way, thanks for all the swift team for there continues effort on making this language better every day

Detached had the additional effect that it erases the task local values. It can lead to some unexpected side effects of that is not explicitly what you are looking for

It does the same thing as withTaskCancellationShield does so if you want it to be a drop-in replacement you have to do this. Otherwise you have to think about whether it matters if what you're doing in the closure should be happening concurrently with the rest of the parent task.

For instance, with this:

func processFile(at url: URL) async throws {
    let handle = try FileHandle(forReadingFrom: url)

    defer {
        Task {
            await flushMetrics(for: url)
            try? handle.close()
        }
        // not awaitting for the task to be finished
    }

    try await processContents(of: handle)
}

If in processFile you don't wait for the handle to close before returning, calling processFile many times in a loop could end up exhausting the number of file handles the system allocates to your process if the created cleanup tasks cannot keep up for some reason (most likely other threads/tasks keeping the CPU busy). If you wait for the file to close you'll have no such issue because you know the file handle is closed before you can call processFile again.

Another effect is there will be no guaranty about the order flushMetrics will be called since multiple cleanup tasks will be scheduled to run in parallel in the background. Perhaps it does not matter in this specific case, but that depends entirely on what you're doing in that function. And since the order in which those cleanup tasks will run is not deterministic it will introduce some randomness to any bug you might have in there.

So unless there's a compelling reason to cleanup things concurrently, I'd refrain from doing it. Running things in the same order every time will keep your resource usage, your logs, and your debugging sessions more deterministic.

2 Likes

Thanks for this detailed explanation :heart:

public nonisolated(nonsending) func withTaskCancellationShield<Value: Sendable, Failure>(
  _ operation: sending @escaping () async throws(Failure) -> Value
) async throws(Failure) -> Value {
  if #available(anyAppleOS 27, *) {
    return await withTaskCancellationShieldBack { await operation() }
  } else {
    let result: Result<Value, Failure> = await Task {
      do throws(Failure) {
        return .success(try await operation())
      } catch {
        return .failure(error)
      }
    }.value

    return try result.get()
  }
}

is this wrapper right ? or am I missing something ? @michelf

Looks good at a glance.