Files
Library/docs/roadmap/modules/Async.md

14 KiB
Raw Permalink Blame History

Async completion and structured execution plan

Status: PLANNED feature work. Source baseline: f1f9ba375b22abf1adcc7c550ec21ac20895c0a4, inspected 2026-11-24. This document implements no execution features. Requirements R-005, R-009, R-012, R-014 and R-016 apply; architecture C-02–C-05 and C-11 define the shared boundaries.

Existing surface and gaps

  • Task.hpp provides move-only lazy Void::Coro::Task<T> and Task<void>, stored exceptions, continuation transfer, a borrowed handle(), and frame destruction by the owning Task. run() resumes once and reads the result; it is not a general event-loop driver for externally suspended operations. Generator.hpp is the separate synchronous pull generator.
  • Executor.hpp defines Void::Async::Executor::post(coroutine_handle<>), a single-consumer ManualExecutor, schedule_on, and detached spawn. Queues hold borrowed handles. Detached exceptions terminate; cancellation and joining are absent.
  • ThreadPool.hpp is in Void::Concurrency, returns futures, drains and joins workers on destruction, and offers blocking submit and rejecting try_submit. Its historical max_queue == 0 means unlimited queued work; running work is not part of that queue bound. Channel.hpp is a bounded blocking MPMC channel, not a coroutine channel.
  • MpscQueue.hpp, ParallelFor.hpp, Observable.hpp, and EventBus.hpp supply useful primitives. EventBus async mode starts its own worker and snapshots callbacks at publication; unsubscribe cannot retract those copies. Observable/Signal iterate listener collections directly and need a documented reentrancy/threading policy.
  • module.cmake declares LogState. Remove mandatory concrete logging from the target execution contract through optional error/observation hooks, preserving compatibility adapters.

Executor tests, coroutine tests, backpressure tests, channel tests, and async event tests are existing fixtures. They do not establish structured lifetime or cancellation correctness. Graph coverage was checked for scoped source; Observable line 32 was read directly because it is partially parsed. Important ownership conclusions use source inspection.

NEW API contracts

The following is a design sketch, not a compiling example. Async owns the sole public operation-options type used by IO, Net, RPC, Scheduler and other consumers:

namespace Void::Async {                         // NEW additions
struct OperationOptions {
    std::stop_token stop{};
    std::optional<std::chrono::steady_clock::time_point> deadline{};
};
enum class AdmissionError { overloaded, stopped, deadline_expired };
class TaskScope {
public:
    Result<JoinHandle> spawn(Coro::Task<void>&& task, OperationOptions = {});
    void request_stop() noexcept;
    Coro::Task<Result<void>> join();
};
// Executor evolution: try_post(owned_resume_ticket) -> Result<void>;
// schedule_on(executor, options) -> cancellable scheduling awaitable.
}

Result is shorthand under C-02; Functional owns error representation. JoinHandle, resume tickets, scope construction and executor evolution are NEW Async-owned types. An execution binding borrows the executor, Time's injectable monotonic clock, and optional Memory resource. Their lifetimes extend through scope join. Clock injection is specified in Time; no consumer invents another clock or request context. The options fields above are fixed: consumers add domain options separately. The NEW Time type is Void::Time::MonotonicClock; manual-clock tests advance it and explicitly drive timer progress. Backends derive OS wait durations from the injected now() and must not compare a manual deadline with the host clock's current time.

No deadline means no time limit, not unlimited admission. A deadline is absolute in the injected steady-clock domain and covers queue waiting, execution and backend cleanup initiation. Stop already requested or deadline already expired rejects admission without invoking the operation. An accepted operation keeps its cleanup obligations even after its deadline. Parent stop and child stop combine in an owned stop source; they never rely on a temporary callback registration.

Frame ownership and terminal arbitration

  1. A lazy Task owns its frame before admission. Successful scope admission transfers the frame into a scope-owned control block; a failed admission leaves ownership with the caller or returns the task through the specified move-failure adapter. Choose a two-step reserve-then-transfer implementation so rejection never silently destroys an operation the caller still considers submitted.
  2. Executor queues store a retained resume ticket, never a bare handle whose owner may disappear. Only the selected consumer resumes a frame; queued/running flags prohibit concurrent resume and duplicate enqueue. Await suspension registration uses an atomic handshake so completion during await_suspend cannot lose a wake.
  3. The control block tracks admitted, active, stop-requested, backend-released, terminal-recorded and continuation-delivered states. Stop/expiry records intent and initiates cooperative cancellation; it does not immediately fix the result of an effectful operation. Its owner first gathers the required completion/persistence evidence, then one serialized transition or compare/exchange records the domain result. A terminal result already recorded cannot be overwritten by a later stop.
  4. Backend acknowledgement is awaited before buffer release and continuation delivery. Late completion is evidence for domain-result selection as well as cleanup, even when stop was requested first. A side-effect-free scheduling wait can finalize as cancelled/timed-out at its safe abort point; a transfer error preserves observed bytes/effects. A committing adapter returns a known commit receipt, proven NotCommitted cancellation, or explicit Unknown outcome according to its domain. Generic Async code never rewrites those outcomes to cancellation. The domain owns this classification; Async imports no Storage/Update types. Duplicate notifications cannot deliver again. Cancellation callbacks post control messages instead of destroying frames, and user callbacks never run under internal state locks.
  5. Join waits for terminal delivery, all children, backend references and callback registrations to drain. The frame is destroyed once, after final suspension and all resume tickets retire. Continuation delivery uses reserved capacity so a full executor cannot strand already admitted operations.

TaskScope destruction requests stop and joins on a permitted owner thread. On an executor thread, callers must co_await join() before destruction; blocking a worker needed for progress is a detected programmer error. An embedded single-thread driver can pump its executor while synchronously joining. No timeout frees live frames. Explicit detached launch requires an owner retained through completion plus an error sink; it is not the default scope behavior. CPU-bound user code must poll stop or yield; cancellation cannot impose a hard wall-clock shutdown guarantee.

NEW committing adapters keep their domain operation alive through evidence collection, including when a lower-level IO awaitable reports cancellation with partial effects. For a durable write, stopping before append yields NotCommitted; stopping during sync leaves the result pending; successful sync and publication after stop yield the receipt; failed sync after append yields Unknown unless non-commit is independently proved. The one continuation is delivered after backend access ends in every case. These are adapter conformance scenarios, not an Async dependency on the native engine.

Queues, channels and event delivery

NEW defaults: 4,096 admitted tasks per executor including running work; 1,024 child tasks per scope; 1,024 values per coroutine channel; 4 MiB aggregate channel payload budget through a supplied size-accounting policy; 1,024 subscriptions and 1,024 admitted event dispatches. Variable payloads require a byte-accounting policy rather than pretending element count bounds memory. Zero capacity is invalid; an explicitly named unlimited policy is available only where separately documented.

Initial scheduling uses a bounded mutex-protected FIFO and condition/event wakeups. Correct admission and lifetime precede work stealing or lock-free specialization. Work is charged until completion cleanup, with a reserved internal completion lane bounded by admitted operations. Default external submission rejects on overload; async_wait_for_capacity(options) is explicit and bounded to 1,024 waiters. Blocking submission is an off-executor adapter. ThreadPool futures keep their old behavior until a versioned adapter maps rejection and exceptions explicitly.

Coroutine channels offer cancellable send/receive and close-with-drain; failed send does not consume the caller's value. Separate closed, empty, full, cancelled and timed-out results. ParallelFor gains explicit grain/concurrency, stop propagation and deterministic exception aggregation after joining started chunks.

Subscriptions use immutable dispatch snapshots. Removing a subscription prevents new admission; NEW close_and_join waits for already admitted callbacks. Callback code and error sinks run outside subscriber locks. Self-unsubscribe is supported; self-join is rejected. Reentrant sync Observable updates queue bounded notifications instead of invalidating iteration. Async EventBus accepts an injected executor and keeps its private-worker constructor only as an explicit compatibility convenience.

Backend and performance decisions

Use C++ standard threads, atomics, stop tokens and coroutines; no external execution engine. Async has no IO or Runtime dependency. IO supplies operation backends; Runtime composes them. Timer ordering uses a stable min-heap keyed by deadline and sequence with an injected Time clock. Cancellation removes or tombstones a timer while retaining its operation reference.

Measure empty-task hops, producer contention, 1/64/1,024-byte channel values, ParallelFor skew, event fan-out and cancel storms. Record p50/p95/p99, throughput, allocations/frame, peak RSS/CPU and compile/link cost under each performance profile. A fixed admitted-work bound must imply a flat retained-frame count after repeated cancellation; no speedup is claimed here.

Ordered implementation backlog

Every row is PLANNED; role recommendations are for later root delegation.

ID Phase / depends on Intended scope Acceptance / recommended role
M-ASYNC-01 P0 / current source Characterize Task moves, external suspension, executor and subscription lifetimes; independent-header/package checks Reproduce unsafe lifetime preconditions without invoking UB in the harness; record existing future/exception behavior / sol_implementer
M-ASYNC-02 P1 / M-ASYNC-01; Time clock and Functional error gates OperationOptions, reserve/transfer admission, owned resume tickets, terminal state machine and domain-outcome classification Stop/completion/expiry permutations deliver once after backend release; fake committing adapter preserves known receipt/unknown outcome after stop; fake clock controls deadlines / astra_implementer
M-ASYNC-03 P1 / M-ASYNC-02 TaskScope, join, explicit detached owner and shutdown guards Nested stop joins all children; rejected admission preserves ownership; no self-deadlock / astra_implementer
M-ASYNC-04 P2 / M-ASYNC-03 Bounded executors, cancellable channels, future pool adapter, ParallelFor Bounds include running work; producer stop and close-drain deterministic; chunk errors join / sol_implementer
M-ASYNC-05 P2 / M-ASYNC-04 EventBus/Observable snapshot dispatch, joined subscriptions, injected scheduling Reentrancy, callback throw and unsubscribe races leave no captured state in use after join / sol_implementer
M-ASYNC-06 P3 / M-ASYNC-05; profile harness Profile native queues; optimize only measured hot paths; major API migration Conformance identical across optimized path; bounded allocation and installed consumers verified / astra_implementer

Validation and migration

CURRENT tests are generated into VoidTests by tests/CMakeLists.txt. Current available aggregate check: ctest --test-dir /tmp/voidlibrary-discovery-f1f9ba3 --output-on-failure --timeout 60. It was not rerun for this document; inherited baseline failures are recorded in VALIDATION. PROPOSED tests require the tasks above: deterministic pause points around registration/resume/destruction; cancellation at every await; cross-thread posting during shutdown; full queue at terminal delivery; faulting error sink; infinite cooperative child; byte budget exhaustion; sanitizer lifetime/race runs. Use a fake committing backend to stop before append and during sync, then independently release successful or failed sync. Assert the sole domain result and retained ownership; passing a cancellation-only scheduling test does not cover these commit races.

Keep Void::Coro, Void::Concurrency, Void::EventBus and Void::Observable names visible in migration examples. EXISTING spawn(executor, task) becomes NEW scope.spawn(std::move(task), options) plus co_await scope.join(). EXISTING task.run() remains for proven synchronous completion until deprecated; general blocking wait uses an explicit driver adapter. Preserve old future exception and zero/unbounded semantics in a versioned legacy adapter, never silently reinterpret them. Roll back a new executor backend behind selection before submission; never replay accepted work. See MIGRATION, DEPENDENCIES, and DELIVERY.