freenode
Languages & Toolchains

Swift to add a synchronous task cancellation handler

The core team will pitch an overload so libraries can honor cancellation from synchronous code such as SQLite, without forcing callers to become async.

Swift's concurrency team has agreed to propose a synchronous overload of withTaskCancellationHandler, closing a gap that forces library authors to make otherwise synchronous APIs async if they want to honor task cancellation.

The request came from a developer integrating SQLite. A long sqlite3_step can run for a while without returning a row, so the usual Task.checkCancellation check between steps never gets a chance to run. SQLite already has sqlite3_interrupt, an atomic flag the engine picks up opportunistically, but the only Swift API that installs a cancellation handler requires an async context. That pushes the async requirement up through code that is otherwise a straight C call.

Core team member ktoso said the original structured concurrency design assumed that once you are in an async context you stay there. In practice a synchronous function can still be running on behalf of a task. Making that function async is not always possible, and ktoso called a matching overload a low-complexity addition to the existing task APIs.

Gwendal Roué, maintainer of the GRDB SQLite wrapper, said this is not a problem in practice: only GRDB's async database access honors cancellation, and callers who care can use that overload. The synchronous read stays synchronous because SQLite itself is synchronous. ktoso disagreed. "Arguably that's pretty surprising to be honest," he wrote, arguing that being inside a synchronous function should not silently drop cancellation when a task is already running. Callers who truly want to ignore the signal already have cancellation shields.

After checking with the language team, ktoso said a Swift Evolution proposal should be pitched immediately, with an implementation to follow. The awkward part is where cancellation handlers store their task records when there is no task at all. John McCall noted the handler can simply do nothing in that case, which existing entry points already do by returning early when no task is present. That likely lets the new functions back-deploy to Swift 6.2 rather than waiting on new runtime support in Swift 6.5, though ktoso said that still needs a check.