The ContextAwaitable Protocol
The Problem: Context Propagation
Standard C++20 coroutines define awaiters with this await_suspend signature:
void await_suspend(std::coroutine_handle<> h);
// or
bool await_suspend(std::coroutine_handle<> h);
// or
std::coroutine_handle<> await_suspend(std::coroutine_handle<> h);
The awaiter receives only a handle to the suspended coroutine. But real applications need more:
-
Executor — Where should completions be dispatched?
-
Stop token — Should this operation support cancellation?
-
Allocator — Where should memory be allocated?
|
Nothing on this page is specific to I/O. An executor, a stop token, and an allocator are what any asynchronous operation needs. It makes no difference whether the operation waits on a socket, a GPU queue, a timer, or another thread. |
Backward Query Approach
One approach: the awaitable queries the calling coroutine’s promise for context. This requires the awaitable to know the promise type, creating tight coupling.
The Two-Argument await_suspend
Every awaitable that a task awaits must take part in propagating the execution environment.
[1]
task enforces this statically.
Such an awaitable provides a member function await_suspend, like the one in C++ awaiters, with a second parameter: the execution environment.
A promise built on context_awaitable_promise_base passes other awaitables through unchanged unless it adds the same check.
auto await_suspend(std::coroutine_handle<> h, capy::await_context const* env);
This signature receives:
-
h: The coroutine handle (as in standard awaiters) -
env: The execution environment containing:-
env→executor: The caller’s executor for dispatching completions -
env→stop_token: A stop token for cooperative cancellation -
env→frame_allocator: An optional frame allocator -
env→owner: The owner of the chain, which teardown uses to abandon it
-
Following the convention of awaiters in C++, the function returns void, bool, or a coroutine handle.
ContextAwaitable gives the exact requirements.
Many types modelling ContextAwaitable return std::coroutine_handle<> to enable
symmetric transfer.
ContextAwaitable Concept
Concept ContextAwaitable specifies all requirements on a type that can be co_awaited
in Capy-coroutines. Besides the two-argument await_suspend, the type provides the awaiter
members await_ready and await_resume. The concept reference lists the remaining requirements.
To model ContextAwaitable, a type need not be associated with any coroutine. In fact,
this is the case for a number of ContextAwaitables in Corosio.
ContextRunnable Concept
For tasks that can be started from non-coroutine contexts, the ContextRunnable concept refines ContextAwaitable.
It requires a promise_type and task members that give access to the coroutine handle and release the frame.
It also requires promise members that return the captured exception and, for non-void tasks, the result.
Other promise members set the continuation and the await_context.
The concept reference lists the exact members, their noexcept requirements, and the ownership protocol.
These members exist because the functions that start a task, like run_async, cannot co_await the task directly. The trampoline must be allocated before the task type is known, so it type-erases the task through function pointers. The trampoline therefore needs a common API to manage lifetime and extract results.
Those functions access set_continuation and set_environment through the typed handle provided by handle().
Capy’s task<T> satisfies this concept.
The Writing Your Own Task Type (Early Quitter) example builds a second task type that satisfies it, outside the library.
How Context Flows
When you write co_await child_task() inside a task<T>:
-
Member function
await_transformof thetask'spromise_typetransforms the awaitable into an awaiter (see Awaitables and Awaiters). -
The resulting awaiter’s
await_suspendpasses context:
template<class Promise>
auto await_suspend(std::coroutine_handle<Promise> h)
{
// Forward caller's context to child
return awaitable_.await_suspend(h, promise_.environment());
}
The child receives the parent’s executor and stop token automatically.
Why Forward Propagation?
Forward propagation offers several advantages:
-
Decoupling: Awaitables don’t need to know caller’s promise type
-
Composability: Any I/O awaitable works with any task that models
ContextRunnable -
Explicit flow: Context flows downward through the call chain, not queried upward
This design enables Capy’s type-erased wrappers (any_stream, etc.) to work without knowing the concrete executor type.
Why Not std::execution? contrasts forward propagation with the backward queries of senders and receivers.
A Vocabulary for Coroutine Interop
Because the protocol is just a two-argument await_suspend, ContextAwaitable is more than an internal mechanism. It is a shared vocabulary for interoperation. Any coroutine library that speaks the protocol can propagate execution environment across a co_await boundary without knowing the other side’s concrete task type.
This is the interop problem framed on the home page. A shared protocol replaces the set of pairwise adapters that separate coroutine libraries would otherwise need to talk to one another. Capy is the reference implementation of that protocol.
Implementing a Custom I/O Awaitable
To create a custom I/O awaitable:
struct my_awaitable
{
capy::await_context const* env_ = nullptr;
capy::continuation cont_;
result_type result_;
bool await_ready() const noexcept
{
return false; // Or true if result is immediately available
}
std::coroutine_handle<> await_suspend(
std::coroutine_handle<> h, capy::await_context const* env)
{
// Store pointer to environment, never copy
env_ = env;
// Wrap the caller's handle in a continuation we own, so it stays
// at a stable address until the executor resumes it.
cont_.h = h;
// Lets whoever holds the continuation at teardown abandon the
// whole chain, not just this frame.
cont_.owner = env->owner;
// Start async operation...
start_operation();
// Return noop to suspend
return std::noop_coroutine();
}
result_type await_resume()
{
return result_;
}
private:
void on_completion()
{
// Resume the caller on its executor. post() takes the
// continuation by reference and queues it; never resume inline
// from a completion callback (it may run on the wrong thread).
env_->executor.post(cont_);
}
};
The key points:
-
Store the
await_contextas a pointer (await_context const*), never a copy. The functions that start a task guarantee theawait_contextoutlives the awaitable’s operation. -
To resume the caller, wrap its handle in a
continuationand pass that to the executor’spost(ordispatch). These take acontinuation&, not a rawcoroutine_handle. Store thecontinuationin the awaitable so it keeps a stable address until the executor dequeues and resumes it. The executor links continuations intrusively, so a temporary would dangle. -
Set the continuation’s
ownertoenv→ownerbefore anything else can hold it. An executor that shuts down passes the continuations it holds toabandon. The owner letsabandonunwind the whole chain. Without it, only the awaiting frame is destroyed, and the frames above it hold a destroyed frame. -
Respect the stop token for cancellation
Stop Callbacks Must Post, Not Resume
When implementing a stoppable awaitable, you may register a std::stop_callback to wake the coroutine when cancellation is requested.
Stop Tokens and Cancellation introduces std::stop_callback and request_stop(). The callback fires synchronously on whatever thread calls request_stop(), which is typically not the executor’s thread.
|
Never resume a coroutine handle directly from a stop_callback. Doing so executes the coroutine on the wrong thread, corrupting the thread-local frame allocator. This causes use-after-free on the next coroutine allocation, possibly in unrelated code. |
Post the resume through the executor instead of resuming inline. The stop callback also races the completion of the operation, and only one of them may resume the coroutine. Each must first win an atomic claim on the operation. Implementing Stoppable Awaitables shows a complete I/O awaitable that handles both.
The incorrect pattern compiles and appears to work, but it corrupts memory:
// WRONG: resumes coroutine on the calling thread
stop_cb_.emplace(env->stop_token, h); // h is a raw coroutine_handle
For a production implementation of the claim, read the source of async_waker::wait_awaiter. It registers a stop callback that posts the resume through the executor, and arbitrates between wakeup and cancellation with a single atomic claim. Unlike the example in Implementing Stoppable Awaitables, it does not make the winner wait for await_suspend. It requires a single-threaded executor or a strand instead, because each resumes one coroutine at a time.
Running a Custom I/O Awaitable
This awaitable produces a value and resumes the caller by posting its continuation through the caller’s executor:
// A complete ContextAwaitable following the pattern above. It produces a
// value, then resumes the caller on the caller's own executor by posting
// its continuation. A real one would do this from an async completion
// callback; here the "operation" finishes immediately.
struct add_awaitable
{
int a_;
int b_;
capy::await_context const* env_ = nullptr;
// Defaulted, so the call site supplies only a_ and b_.
capy::continuation cont_{};
result_type result_{};
bool await_ready() const noexcept { return false; }
std::coroutine_handle<> await_suspend(
std::coroutine_handle<> h, capy::await_context const* env)
{
env_ = env;
cont_.h = h;
cont_.owner = env->owner; // the executor holds it once posted
result_ = a_ + b_; // the operation produced a value
env_->executor.post(cont_); // resume the caller on its executor
return std::noop_coroutine();
}
result_type await_resume() { return result_; }
};
// A task awaits the custom ContextAwaitable and returns what it delivered.
capy::task<int> add_via_awaitable()
{
co_return co_await add_awaitable{2, 3};
}
To run that task from ordinary, non-coroutine code, hand it to run_async with an executor and a completion handler:
// Run the task on a thread pool and observe the value the
// custom ContextAwaitable delivered to the completion handler.
capy::thread_pool pool(1);
int result = 0;
capy::run_async(pool.get_executor(), [&result](int value) {
result = value; // the awaitable delivered 5
})(add_via_awaitable());
pool.join();
The task runs on the thread_pool executor. When the awaitable posts its continuation, the pool resumes the task, await_resume returns the value, and the completion handler receives it: here, 5.
Bridging a Foreign Awaitable
What happens when you co_await an awaitable that does not implement the protocol? Consider a "plain" awaitable from another library, with the standard one-argument await_suspend.
Capy rejects it at compile time:
// In task.hpp, when the awaited type is not a ContextAwaitable:
static_assert(capy::ContextAwaitable<A>, "requires ContextAwaitable");
This is intentional. A plain awaitable receives only the coroutine handle; it can resume the coroutine on any thread by calling handle.resume() directly. That silently breaks the same-executor invariant—the coroutine could wake on a foreign completion thread, leaving shared state you believed was strand-protected exposed to races. Rejecting such an awaitable at compile time prevents that. The constraint does not lock you in; it requires environment propagation to be explicit rather than silently dropped.
The escape hatch is to wrap the foreign awaitable (or callback, or future) in a small I/O awaitable. That awaitable captures the executor and re-posts the resumption through it:
// Bridge a foreign async operation into a Capy coroutine.
struct foreign_bridge
{
capy::await_context const* env_ = nullptr;
capy::continuation cont_;
result_type result_;
bool await_ready() const noexcept { return false; }
std::coroutine_handle<> await_suspend(
std::coroutine_handle<> h, capy::await_context const* env)
{
env_ = env;
cont_.h = h; // stable address; the executor links continuations intrusively
cont_.owner = env->owner; // so a holder can abandon the whole chain
// Start the foreign operation. Its completion callback may run on
// ANY thread, so it must not resume h directly. Instead it posts
// the continuation back through the caller's executor, restoring
// the same-executor invariant.
start_foreign_op([this]() noexcept {
store_result();
env_->executor.post(cont_);
});
return std::noop_coroutine();
}
result_type await_resume() { return std::move(result_); }
};
The single rule that makes any bridge correct: on completion, post through env→executor instead of resuming the handle inline.
The foreign runtime must also finish before the execution context is destroyed.
An executor’s post is valid only until its context is destroyed, so a late completion that posts afterward is undefined behavior.
There Is No Universal Bridge
Capy does not provide a generic co_await foreign_awaitable(x) that adapts arbitrary awaitables automatically. Such an adapter has no way to know how a foreign runtime schedules its completions, so it cannot guarantee the invariant. A shared protocol addresses this where a hidden adapter cannot. A small, explicit bridge per foreign runtime keeps the guarantee intact and the cost visible.
Worked Bridges
Two complete, buildable bridges live in the examples:
-
Bridging a P2300 Sender —
await_senderadapts astd::executionsender, mapping its completion channels ontoresultsand posting the resumption through the executor. -
Calling Asio from a Capy Coroutine — the
use_capycompletion token turns any Asio async operation into aContextAwaitable.
this_coro: environment, executor, frame_allocator and stop_token.