[Pitch] Split continuation

Hi everyone,

Here is a pitch to make working with continuations easier and enable a more performant way to resume them in cases where the current execution context can be donated: [Concurrency] Proposal for split continuation by FranzBusch · Pull Request #3548 · swiftlang/swift-evolution · GitHub


Split continuations

Summary of changes

Introduces a new form of withContinuation whose body is async and receives both halves of a continuation: the existing Continuation that is used to resume and a new ContinuationWaiter that is used to wait. Waiting on the waiter can install cancellation and priority escalation handlers that are only active while the task is suspended on the continuation.

Additionally, this proposal adds new resumeSynchronously methods to Continuation, UnsafeContinuation and CheckedContinuation that allow an executor to offer its current execution context to the resumed task. If the task resumes on the same executor, it runs inline instead of being enqueued.

Motivation

SE-0528 introduced Continuation, a noncopyable continuation that enforces that it is resumed exactly once. Its withContinuation method follows the shape of the continuation APIs from SE-0300. The body is synchronous and receives the continuation. Once the body returns the task suspends until the continuation is resumed. Creating the continuation and awaiting it are coupled together in one call.

Cancellation and escalation handlers race with the continuation

When creating a continuation, it is very common to also want to handle cancellation of the waiting task. For example, an I/O system that is waiting for a read to complete wants to cancel the pending read once the task is cancelled. Similarly, a thread pool might want to move a work item up in its queue once the priority of the waiting task is escalated.

The only way to do this today is to set up the handlers around the withContinuation call:

func read(into buffer: ReadBuffer) async throws(IOError) -> Int {
    // We need an identity that both the body and the handler know about
    let id = eventLoop.makeOperationID()
    return try await withTaskCancellationHandler {
        try await withContinuation(of: Int.self, throwing: IOError.self) { continuation in
            eventLoop.register(id, .read(fd, buffer), continuation)
        }
    } onCancel: {
        eventLoop.cancel(id)
    }
}

While it looks simple enough it has a few hard-to-handle problems:

  1. The cancellation handler can run before the continuation is even created. If the task is already cancelled onCancel runs inline, before the body of withContinuation is executed. It can also run concurrently with the body from another thread.
  2. Since the handler can't get the continuation, the code has to create an id or another token up front so that the handler and the body can be related each other.
  3. The event loop has to handle a cancel(id) for an id that it hasn't registered an operation for yet. This can either mean the operation was not registered yet, or that it already completed. To tell those apart the event loop has to remember the cancelled ids and it has to clean them up again at some point. This state tracking is very easy to get wrong.

The same problems exist for priority escalation handlers from SE-0462 when they are placed around a withContinuation call. If both handlers are needed, they have to be nested which makes the code even harder to read.

What we really want is to first create the continuation, hand it to whoever is going to resume it, and then await it with the handlers installed. This way the handlers can only run once the continuation is already registered.

Resuming a continuation always enqueues the task

Continuations can be resumed from an executor such as when the executor also handles I/O operations. For example reading from a socket or a file. Once a read completes, the event loop resumes the continuation of the task that is waiting for that read.

final class EventLoop: SerialExecutor {
    func run() {
        while true {
            for completion in selector.waitForCompletions() {
                // The task is enqueued on this event loop and runs later
                completion.continuation.resume(returning: completion.bytesRead)
            }
            runEnqueuedJobs()
        }
    }
}

Today resuming a continuation always enqueues the task on the executor that it resumes on. Even if this executor is the event loop that is currently resuming the continuation. This adds latency with an extra round through the job queue for every I/O operation.

Executors can already run a job synchronously with ExecutorJob.runSynchronously(on:) from SE-0392 and runSynchronously(isolatedTo:taskExecutor:) from SE-0417. However, there is no way to do the same when resuming a continuation.

Proposed solution

Splitting creating and awaiting a continuation

A new withContinuation method passes both halves of a continuation to an async body. The Continuation is used to resume, and the ContinuationWaiter is used to wait.

func read(into buffer: ReadBuffer) async throws(IOError) -> Int {
    try await withContinuation(of: Int.self, throwing: IOError.self) { continuation, waiter in
        let id = eventLoop.register(.read(fd, buffer), continuation)
        return try await waiter.wait(onCancel: { eventLoop.cancel(id) })
    }
}

The handlers are only installed while the task awaits the continuation. When onCancel runs, the read is guaranteed to be registered already. The event loop only has to handle a cancel(id) for an operation that already completed, which it can just ignore.

Similar to the existing withContinuation method, the continuation can be resumed before wait() is called on the waiter. In this case wait() returns right away without suspending.

Resuming on the current executor

New resumeSynchronously methods on Continuation allow the resumer to offer
the executor that it is currently running on.

final class EventLoop: SerialExecutor {
    func run() {
        while true {
            for completion in selector.waitForCompletions() {
                // If the task resumes on this event loop it runs right here
                completion.continuation.resumeSynchronously(
                    returning: completion.bytesRead,
                    isolatedTo: self.asUnownedSerialExecutor()
                )
            }
            runEnqueuedJobs()
        }
    }
}

If the awaiting task resumes on the offered executor, the task runs inline until its next suspension point, and resumeSynchronously returns afterwards. If the task resumes on another executor, it is enqueued as usual. This mirrors how ExecutorJob.runSynchronously(on:) runs a job.

Detailed design

withContinuation

/// Creates a continuation and hands `body` both halves: the *resume* half
/// (a ``Continuation``) to give to whoever performs the work, and the *await*
/// half (a ``ContinuationWaiter``) for the task to wait on.
///
/// The continuation must be resumed exactly once, and the waiter waited on
/// exactly once, before `body` returns.
///
/// - Parameters:
///   - of: The `Success` type the continuation is resumed with.
///   - throwing: The `Failure` type the continuation can be resumed by
///     throwing.
///   - body: Receives both halves of the continuation. Its own result
///     becomes the result of this function.
public nonisolated(nonsending) func withContinuation<
    Success: ~Copyable,
    Failure: Error,
    BodyResult: ~Copyable,
    BodyFailure: Error
>(
    of: Success.Type = Success.self,
    throwing: Failure.Type,
    _ body: nonisolated(nonsending) (
        consuming Continuation<Success, Failure>,
        consuming ContinuationWaiter<Success, Failure>
    ) async throws(BodyFailure) -> BodyResult
) async throws(BodyFailure) -> BodyResult

The body runs in the calling task and on the isolation of the caller. Unlike the existing withContinuation, the result and error of the body are independent of the ones of the continuation. This allows the body to transform the value of the continuation or to catch its error and throw another one.

let description = await withContinuation(of: Int.self, throwing: Never.self) { continuation, waiter in
    continuation.resume(returning: 42)
    let value = await waiter.wait()
    return "value: \(value)"
}

The continuation that is passed to the body is the same Continuation type from SE-0528. This means that all existing code that resumes a Continuation works without any changes with a continuation that was created by the new method.

ContinuationWaiter

/// The *wait* half of a continuation, can be used by a task to suspend until
/// the continuation is resumed.
///
/// It must be waited on exactly once and cannot leave the
/// ``withContinuation(of:throwing:_:)`` scope it was passed into, and it traps
/// if it is destroyed without being waited on.
public struct ContinuationWaiter<Success: ~Copyable, Failure: Error>: ~Copyable, ~Escapable {
    /// Suspend until the paired ``Continuation`` is resumed, with a
    /// cancellation handler and a priority-escalation handler installed for the
    /// duration of the suspension.
    ///
    /// If the continuation was already resumed before `wait` is called, this
    /// call does not suspend at all and returns the value immediately.
    ///
    /// If the current task is already cancelled, `onCancel` runs before this
    /// function suspends.
    ///
    /// - Parameters:
    ///   - onCancel: Run when the task is cancelled while suspended
    ///     here. It may run concurrently with the resumption, and on any thread.
    ///   - onEscalate: Run with the new priority when the task's priority is
    ///     escalated while suspended here.
    public nonisolated(nonsending) consuming func wait(
        onCancel handleCancellation: sending () -> Void,
        onEscalate handleEscalation: sending (TaskPriority) -> Void
    ) async throws(Failure) -> sending Success

    /// Similar to the above, but only installs a cancellation handler.
    public nonisolated(nonsending) consuming func wait(
        onCancel handleCancellation: sending () -> Void
    ) async throws(Failure) -> sending Success

    /// Similar to the above, but only installs a priority-escalation handler.
    public nonisolated(nonsending) consuming func wait(
        onEscalate handleEscalation: sending (TaskPriority) -> Void
    ) async throws(Failure) -> sending Success

    /// Similar to the above, but doesn't install any handlers.
    public nonisolated(nonsending) consuming func wait() async throws(Failure) -> sending Success
}

The waiter is ~Copyable since it must be waited on exactly once. All wait methods are consuming, so the compiler prevents waiting on it twice. Similar to Continuation, dropping the waiter without waiting on it traps at runtime.

The waiter is ~Escapable since the storage of the continuation is allocated with the task allocator and is deallocated once withContinuation returns. Hence, must not escape the body, but it can be passed to other functions including functions with different isolation.

The rules for the handlers in wait are the same as their standalone versions:

  • The handlers are installed when wait is called and removed again before wait returns. Cancelling or escalating the task after wait returned doesn't run them.
  • If the task is already cancelled when wait is called, onCancel runs inline before the task suspends.
  • onCancel runs at most once.
  • Both handlers can run concurrently to resuming the continuation and on any
    thread.

Resuming on executors

extension Continuation where Success: ~Copyable {
    /// Resume the task awaiting this continuation by having it return the given
    /// value, offering the current execution context to run the resumed task.
    ///
    /// The offered execution context is used only if it belongs to the executors
    /// the awaiting task resumes on. If the context doesn't match the task is
    /// enqueued on its expected execution context.
    ///
    /// - Parameters:
    ///   - value: The value to return from the continuation.
    ///   - serialExecutor: The serial executor the resuming thread is running on.
    ///   - taskExecutor: The task executor the resuming thread is running on.
    public consuming func resumeSynchronously(
        returning value: consuming sending Success,
        isolatedTo serialExecutor: UnownedSerialExecutor,
        taskExecutor: UnownedTaskExecutor
    )

    /// Resume the task awaiting this continuation by having it throw the given
    /// error, offering the current execution context to run the resumed task.
    ///
    /// The offered execution context is used only if it belongs to the executors
    /// the awaiting task resumes on. If the context doesn't match the task is
    /// enqueued on its expected execution context.
    ///
    /// - Parameters:
    ///   - error: The error to throw from the continuation.
    ///   - serialExecutor: The serial executor the resuming thread is running on.
    ///   - taskExecutor: The task executor the resuming thread is running on.
    public consuming func resumeSynchronously(
        throwing error: Failure,
        isolatedTo serialExecutor: UnownedSerialExecutor,
        taskExecutor: UnownedTaskExecutor
    )

    /// Resume the task awaiting this continuation by having it either return or
    /// throw based on the given `Result`, offering the current execution context
    /// to run the resumed task.
    ///
    /// The offered execution context is used only if it belongs to the executors
    /// the awaiting task resumes on. If the context doesn't match the task is
    /// enqueued on its expected execution context.
    ///
    /// - Parameters:
    ///   - result: A value to either return or throw from the continuation.
    ///   - serialExecutor: The serial executor the resuming thread is running on.
    ///   - taskExecutor: The task executor the resuming thread is running on.
    public consuming func resumeSynchronously(
        with result: consuming sending Result<Success, Failure>,
        isolatedTo serialExecutor: UnownedSerialExecutor,
        taskExecutor: UnownedTaskExecutor
    )

    /// Similar to the above, but only offers a serial executor.
    public consuming func resumeSynchronously(
        returning value: consuming sending Success,
        isolatedTo serialExecutor: UnownedSerialExecutor
    )

    /// Similar to the above, but only offers a serial executor.
    public consuming func resumeSynchronously(
        throwing error: Failure,
        isolatedTo serialExecutor: UnownedSerialExecutor
    )

    /// Similar to the above, but only offers a serial executor.
    public consuming func resumeSynchronously(
        with result: consuming sending Result<Success, Failure>,
        isolatedTo serialExecutor: UnownedSerialExecutor
    )

    /// Similar to the above, but only offers a task executor. The offer is only
    /// taken if the awaiting task resumes without any serial isolation.
    public consuming func resumeSynchronously(
        returning value: consuming sending Success,
        on taskExecutor: UnownedTaskExecutor
    )

    /// Similar to the above, but only offers a task executor. The offer is only
    /// taken if the awaiting task resumes without any serial isolation.
    public consuming func resumeSynchronously(
        throwing error: Failure,
        on taskExecutor: UnownedTaskExecutor
    )

    /// Similar to the above, but only offers a task executor. The offer is only
    /// taken if the awaiting task resumes without any serial isolation.
    public consuming func resumeSynchronously(
        with result: consuming sending Result<Success, Failure>,
        on taskExecutor: UnownedTaskExecutor
    )
}

The three variants mirror the existing runSynchronously methods on
ExecutorJob:

Continuation ExecutorJob
resumeSynchronously(returning:isolatedTo:taskExecutor:) runSynchronously(isolatedTo:taskExecutor:)
resumeSynchronously(returning:isolatedTo:) runSynchronously(on: UnownedSerialExecutor)
resumeSynchronously(returning:on:) runSynchronously(on: UnownedTaskExecutor)

Offering an executor is a best effort. The executor that the task resumes on is decided when the task awaits the continuation. The resumer, however, gets the continuation earlier and can't know in advance whether its executor will match. For example, the task might change its isolation or take a task executor preference between handing out the continuation and awaiting it. In these cases, the offer simply isn't taken and the task is enqueued instead. Since the resumed task runs nested inside of the resumeSynchronously call, the resumer must only offer an executor from a point where that executor could run one of its own jobs.

These methods work for every Continuation, independent of whether it was created by the existing withContinuation or by the new split form. The same methods are also added to UnsafeContinuation and CheckedContinuation.

extension UnsafeContinuation {
    public func resumeSynchronously(returning value: sending T, isolatedTo serialExecutor: UnownedSerialExecutor, taskExecutor: UnownedTaskExecutor)
    public func resumeSynchronously(throwing error: E, isolatedTo serialExecutor: UnownedSerialExecutor, taskExecutor: UnownedTaskExecutor)
    public func resumeSynchronously(with result: sending Result<T, E>, isolatedTo serialExecutor: UnownedSerialExecutor, taskExecutor: UnownedTaskExecutor)

    public func resumeSynchronously(returning value: sending T, isolatedTo serialExecutor: UnownedSerialExecutor)
    public func resumeSynchronously(throwing error: E, isolatedTo serialExecutor: UnownedSerialExecutor)
    public func resumeSynchronously(with result: sending Result<T, E>, isolatedTo serialExecutor: UnownedSerialExecutor)

    public func resumeSynchronously(returning value: sending T, on taskExecutor: UnownedTaskExecutor)
    public func resumeSynchronously(throwing error: E, on taskExecutor: UnownedTaskExecutor)
    public func resumeSynchronously(with result: sending Result<T, E>, on taskExecutor: UnownedTaskExecutor)
}

extension CheckedContinuation {
    public func resumeSynchronously(returning value: sending T, isolatedTo serialExecutor: UnownedSerialExecutor, taskExecutor: UnownedTaskExecutor)
    public func resumeSynchronously(throwing error: E, isolatedTo serialExecutor: UnownedSerialExecutor, taskExecutor: UnownedTaskExecutor)
    public func resumeSynchronously(with result: sending Result<T, E>, isolatedTo serialExecutor: UnownedSerialExecutor, taskExecutor: UnownedTaskExecutor)

    public func resumeSynchronously(returning value: sending T, isolatedTo serialExecutor: UnownedSerialExecutor)
    public func resumeSynchronously(throwing error: E, isolatedTo serialExecutor: UnownedSerialExecutor)
    public func resumeSynchronously(with result: sending Result<T, E>, isolatedTo serialExecutor: UnownedSerialExecutor)

    public func resumeSynchronously(returning value: sending T, on taskExecutor: UnownedTaskExecutor)
    public func resumeSynchronously(throwing error: E, on taskExecutor: UnownedTaskExecutor)
    public func resumeSynchronously(with result: sending Result<T, E>, on taskExecutor: UnownedTaskExecutor)
}

Source compatibility

This proposal is purely additive and doesn't affect source compatibility.

ABI compatibility

This proposal is purely an extension of the ABI of the Concurrency library and doesn't change any existing features. It adds the ContinuationWaiter type and new runtime entry points to create, await, destroy and resume split continuations.

The storage of a split continuation is laid out such that the existing runtime functions for resuming a continuation keep working. This means that code that was compiled before split continuations existed can resume a Continuation that was created by the new withContinuation.

Implications on adoption

The additions described in this proposal require a new version of the Swift standard library and runtime. Libraries that want to adopt split continuations while supporting older platforms have to keep their current implementation with the handlers around withContinuation for those platforms.

Alternatives considered

Add handler parameters to the existing withContinuation

Instead of splitting the continuation, we could add onCancel and onEscalate parameters to the existing withContinuation method and install the handlers after the body returned. This solves the race with the handlers, but it is less flexible. The body still has to be synchronous so it can't await anything before the task suspends, e.g. registering the continuation with an actor. The split form allows to do any async work between creating and awaiting the continuation and composes with other scoped methods.

Return both halves instead of using a scope

We could return both halves from a method; however, this doesn't work since the storage of the continuation is allocated with the task allocator, which requires that it is deallocated in a stack discipline. The scope of withContinuation defines the lifetime of the storage and the waiter being ~Escapable ensures that it can't outlive it.

Naming the wait half ContinuationAwaiter

We considered naming the wait half ContinuationAwaiter. However, the method to suspend on it is called wait() since await is a keyword. Naming the type ContinuationWaiter matches the name of its method.

21 Likes

The existing withCheckedContinuation API is difficult to use, and full of footguns. In particular, people forget the withTaskCancellationHandler, or if they remember to add it, they get the early-cancellation condition wrong.

I've mostly moved to using AsyncStream.makeStream(of:) rather than the continuation APIs, simply because it's more ergonomic. The similarity of this proposal to AsyncStream makes me think this is probably a good direction.

I generally think that people calling ContinuationWaiter.wait overloads that don't specify onCancel: is probably going to turn out to be a mistake (just as omitting withTaskCancellationHandler now is a mistake). Obviously these overloads need to exist for cases where there truly isn't anything you can do about cancellation, but I wonder if we could make the API harder to reach for (waitWithoutHandlingTaskCancellation for example)?

1 Like

You could always pass an empty closure for onCancel just like you can pass an empty block to catch to suppress the error. So if we think it is important not to forget about cancellation, it may be worthwhile to formalize that by requiring the user to explicitly handle or ignore cancellation.

2 Likes

When writing and implementing this I considered both an empty closure and optional closures. The latter to reduce the number of overloads. Optional closures don't work since they are always @escaping which is not the case for these handlers. I decided against required closures since installing these handlers comes with some cost and we can't detect if the user passed an empty closure to avoid that cost.

1 Like

Nice. Can we also add ~Copyable support to UnsafeContinuation?

I don't think that would be desirable; the Unsafe... versions of APIs are for use in situations where you literarily can't rely on Swift's safety mechanisms -- i.e. need to call it from some closure that isn't guaranteed to be once etc; making the Unsafe... APIs try to be kinda safe isn't a goal, they're usafe and that's expected.

I think they’re asking for the result type to be allowed to be ~Copyable. For the continuation type itself, we already have a non-copyable Continuation.

2 Likes

Ah, yeah that part definitely!

1 Like

During the implementation of new async file I/O prototypes, I noticed that the proposed APIs here are leaving open a race when trying to handle task priority:

try await withContinuation(of: Int.self, throwing: IOError.self) { (continuation, awaiter) async throws(IOError) -> Int in
  let id = queue.submit(
     operation: operation,
     priority: Task.currentPriority,
     continuation: continuation
   )
   return try await awaiter.wait(
     onCancel: { queue.cancel(id) },
     onEscalate: { newPriority in queue.escalate(id, to: newPriority) }
  )
}

Between the call to Task.currentPriority and setting up the onEscalate handler the priority might have been escalated. This is not a problem for cancellation since the onCancel handler is always called inline when the task is already cancelled. I thought of two potential ways to address this:

  1. Always call the onEscalate handler once inline
  2. Pass a snapshot of the last known priority to wait

While (1) would work it would come with some cost since we have to call the handler and the handler at least needs to compare if the priority changed to last snapshotted value. (2) would effetely give us the same behavior as the onCancel handler where the onEscalate handler would run inline if the priority changed compared to the passed snapshotted value.

I'm interested to hear what everyone thinks about this.

1 Like

It seems this could have been used to implement synchronous delivery of notifications in SF-0011 too, and overall simplify the API. The post method would synchronously deliver the message to all listeners started on the same isolation being posted from (using resumeSynchronously), and then all other listeners get notified asynchronously.

If that's the case, then I'm definitely for this, and there are a few other situations I have run into that would benefit from this!

1 Like

I understand where the desire for this is coming from but the proposed APIs can currently not be used for this. They behave similarly to the job.runSynchronously APIs and must be called from the executor's context. While in theory calling continuation.resumeSynchronously(isolatedTo: #isolation.unownedSerialExecutor) works it breaks an important guarantee about actor reentrancy. Right now we guarantee that actors can only be re-entered at potential suspension points and that between potential suspension points the synchronous code is guaranteed to not re-enter the actor. If we allow what you are suggesting here then calling the sync post would re-enter the current actor and break this guarantee. It can also lead to new exclusivity violations if the post method is called from places that have dynamic exclusivity enforcement.

I've been thinking about this and I'm warming up to just always calling the onEscalate; it doesn't really change the contract of it at all -- one has to be ready for it to be called multiple times; and we don't have to change to add more parameters priority elsewhere that folks would not necessarily be sure what to do about.

2 Likes

I updated the proposal to address the feedback brought up here. The modifications include:

  • Add support for cancellation reasons on the various onCancel closures of the wait method
  • Rename the onEscalate closure to onPriorityEscalated to align the naming with withTaskPriorityEscalationHandler
  • Always call the onPriorityEscalated closure inline once to remove a race conditions when handling priority escalation
  • Apply the same inline call semantics to the existing withTaskPriorityEscalationHandler to align the behavior since it exhibited the same race
  • Document when donation of execution context is allowed following the rules that the existing job.runSynchronously methods established
3 Likes

How should an example using the split API define completion of registration when setup crosses an actor boundary?

My understanding of the intended ordering is:

  1. Create the continuation and waiter.
  2. Await registration until the operation’s cancellation target has actually been stored.
  3. Call wait with the cancellation handler.

If the task is cancelled during step 2, will entering wait invoke onCancel for that already-cancelled task, after registration has completed?

The distinction I want to clarify is between awaiting registration and merely enqueueing it. If a registration helper returns after spawning an unawaited Task to install the target, the handler could still observe no target. Actor isolation can serialize those accesses without retaining the earlier cancellation request.

Could the examples show actor-isolated registration together with cancellation before wait, and explicitly state when registration must be complete? That would help make clear which ordering the split API supplies and which ordering the adapter must establish.