18 KiB
M-ASYNC-04 — Bounded ThreadExecutor, FuturePool, cancellable AsyncChannel, bounded ParallelFor
Task ID: M-ASYNC-04 Role: sonnet-implementer Status: READY
1. Context and baseline
- Wave 11 package step A2. Repo VoidLibrary, branch
feat/roadmap-p2-wave11. You work in an isolated git worktree of the HEAD given in your prompt (it includes M-FUNCTIONAL-03 and the M-TIME-03Async/Timer.hpp); cwd = worktree root. Never read the user's untracked files in the main checkout. - Baseline: full suite at
38436b1= 1,484 tests, 1,480 passed, 4 skipped, 0 failed. - Observed source (M-ASYNC-01 characterization folded in, D-035):
include/Void/Async/Executor.hpp:58-113:Executorbase (post,try_post,post_completion, reservation APIsupports_reservation/try_reserve_slot/commit_reserved/release_reserved,has_background_workers,is_executor_threadviadetail::ExecutorThreadGuard~:86-96).ManualExecutor(:120-254) is the only executor; its bound excludes running work (:216-228) andpost()bypasses the bound (:128-135). No thread-backed executor exists.include/Void/Async/ThreadPool.hpp(Void::Concurrency::ThreadPool):max_queue == 0unbounded, bound counts only the queue,submitthrows after stop,try_submitreturnsnulloptfor both full and stopped; includes Log.include/Void/Async/Channel.hpp(Concurrency::Channel): blocking only; out of scope (capacity-0 deadlock is a recorded residual).include/Void/Async/ParallelFor.hpp(Void::Concurrency::parallel_for): one future per index; on the first throwingfut.get()returns without joining the rest (lifetime hazard).- Root prep
7f95f89addedAsyncErrorCode::closed = 9(→ErrorKind::cancelled). - M-TIME-03 provides
include/Void/Async/Timer.hpp(TimerQueue,TimerHandle,TimerEvent,schedule_at(when, callback(TimerEvent) noexcept);cancel()==falsemeans fired-or-firing).
- Requirements: roadmap row M-ASYNC-04 ("Bounded executors, cancellable channels, future pool adapter, ParallelFor | Bounds include running work; producer stop and close-drain deterministic; chunk errors join"); C-03..C-05; decisions D-038, D-040, D-W11-10, D-W11-13.
- MANDATORY design sources:
docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md§M-ASYNC-04,W11-PLAN-REV1-OUTPUT.mdF7, F11, F12, P3 (ThreadExecutor),W11-CONTRACT-R2.mdN5. Precedence R2 > REV1 > PLAN.
2. Objective and deliverables
NEW include/Void/Async/ThreadExecutor.hpp, include/Void/Async/FuturePool.hpp,
include/Void/Async/AsyncChannel.hpp; EDIT include/Void/Async/ParallelFor.hpp (NEW bounded overload
- legacy overload joins all futures before rethrowing); NEW tests
tests/standalone/Async/{ThreadExecutor,FuturePool,AsyncChannel,ParallelForBounded}.cpp.
3. Scope and non-goals
Out: Executor.hpp, Operation.hpp, TaskScope.hpp, ThreadPool.hpp, Channel.hpp changes;
async_wait_for_capacity and channel byte budget (D-W11-13); EventBus/Observable (M-ASYNC-05);
build files.
4. Files to inspect
include/Void/Async/{Executor,Operation,TaskScope,Task,ThreadPool,ParallelFor,Timer}.hpp,
include/Void/Async/Detail/Types.hpp, tests/standalone/Async/{OperationScope,Executor,ParallelFor,ThreadPool}.cpp,
and the design sources in §1.
5. Write ownership and coordination
Write scope: include/Void/Async/ThreadExecutor.hpp (NEW), include/Void/Async/FuturePool.hpp (NEW),
include/Void/Async/AsyncChannel.hpp (NEW), include/Void/Async/ParallelFor.hpp,
tests/standalone/Async/ThreadExecutor.cpp, tests/standalone/Async/FuturePool.cpp,
tests/standalone/Async/AsyncChannel.cpp, tests/standalone/Async/ParallelForBounded.cpp (all NEW tests).
Forbidden: every other path. An IO worker may run concurrently in another worktree. No git
commit/branch/stash/reset.
6. Implementation or investigation approach
MANDATORY:
- ThreadExecutor:
createstarts no threads;start()once; abefore_worker_start(i)hook error or a caughtstd::system_errorfromstd::threadjoins started workers and returns an error (shared path). Bound = queued + running normal-lane work (max_admitted >= 1);try_post→overloadedat the bound; a slot is released only after the resumed handle returns. Every resume runs insidedetail::ExecutorThreadGuard. Legacypost()never rejects (counted; may exceed the bound); afterclose()legacypost()goes to the completion lane (counted).post_completionuses a reserved, prioritized lane that drains afterclose().join()= close + drain both lanes until empty and nothing running + join; on a worker returnsself_join. After join, posts resume inline on the caller (countedinline_after_join), never dropped. No drain cap (C-03); a self-reposting handle that prevents join is a documented caller error.~ThreadExecutorwithout join = close()+join(); on its own worker → stderr diagnostic +std::terminate. NEWidle()(both lanes empty, nothing running). Reservation API implemented and compatible withTaskScope. - FuturePool: reserve-then-transfer; on rejection the callable is NOT moved; exceptions go to the future; bound includes running work.
- AsyncChannel (F7 + N5): one mutex for buffer and both waiter lists; waiter nodes with state
{linked, claimed, cancelled, timed_out, closed}; pairing sender/receiver happens in one critical section (unlink+claim the waiter, then move the value) so a value is always in exactly one place (sender node, buffer, or receiver slot). Stop callbacks and timer callbacks take the same lock: if stilllinked→ unlink +cancelled/timed_out(sender keeps/gets back its value); ifclaimed→ no-op. Timer callbacks capture shared waiter state (shared_ptrcontrol block) or aweak_ptrto the channel + waiter id looked up under the lock — NEVER a raw pointer into a coroutine frame (N5). Every resume viapost_completionafter unlock. A wait with a deadline but notimers→invalid_argument.close()gives waiting sendersclosed+ their value; receivers drain the buffer FIFO then getclosed.capacity == 0→invalid_argumentat create. - Bounded parallel_for: shared
detail::PForState(decay-copiedF, chunk counter, error slots); runners submitted withtry_submit; if rejected the caller runs chunks inline; no new chunk after stop or (withstop_on_error) an error; the caller waits for EVERY submitted runner future (including never-started ones); reported error = lowest-indexed failed chunk; nested use on the same pool from a pool worker is documented unsupported. Legacy overload waits for all futures before rethrowing the first exception (D-W11-10).
Amendments from W11-SPEC-REVIEW-1 (MANDATORY; override earlier text where they differ)
Source: docs/agent-workflow/tasks/W11-SPEC-REVIEW-1-OUTPUT.md A1–A3 + P3 (decision D-042).
- A2 no-worker join: admission before
start()queues normally. When no worker is running,join()and the destructor drain both lanes inline on the caller underExecutorThreadGuard(counted asinline_after_join) and never wait.start()afterclose()or after a successfulstart()→invalid_argument; after a failedstart()it may be retried. - A3 reservations: a reserved slot counts in
admitted()and in the bound;try_reserve_slotafterclose()→stopped; a reservation taken beforeclose()stays binding (commit_reservedafterclose()enqueues normally);join()also waits until no reservation is outstanding. - P3:
make_async_error(ChannelError, ...)isinline. AsyncChannel deadlines are judged bytimers->clock(); check stop, then deadline, then "deadline without timers" →invalid_argument, before any state change (value returned inSendFailure);TimerEvent::closed→cancelled;schedule_atfailureoverloaded→ChannelError::overloaded,stopped→cancelled;max_waitersapplies per direction, 0 →invalid_argument; frames holdshared_from_this(); never construct or destroy astd::stop_callbackwhile holding the channel mutex; destroying a suspended Task is a caller error; the resume executor must outlive every pending resume; FIFO means per-producer order. TimerQueue facts (from the M-TIME-03 implementation):cancel() == truedestroys the callback on the caller's thread before returning — so never callTimerHandle::cancel()while holding the channel mutex if the callback's destructor could take it;cancel() == falsemeans fired-or-firing. parallel_for: at mostmax_concurrencychunks run at once (counting the caller when it runs inline);Kind::rejectedis not produced in this wave; precedenceinvalid_argument>failed>stopped;first >= last→ success; compute the range in the unsigned type ofI. ThreadExecutor:idle()/stats()are snapshots; the switch to inline mode happens under the executor mutex;admitted()= queued + running + reserved. FuturePool: if creating the frame throws, release the slot and rethrow.ExecutorThreadGuardis atExecutor.hpp:32-51. Stop and report ifAsync/Timer.hppis missing or differs from M-TIME-03 §7.
7. Interfaces and data contracts
namespace Void::Async {
struct ThreadExecutorOptions { std::size_t workers{1}; std::size_t max_admitted{4096};
std::function<Void::Result::Result<void>(std::size_t)> before_worker_start{}; };
struct ThreadExecutorStats { std::size_t queued, running, completion_queued;
std::uint64_t rejected, legacy_posts, inline_after_join; };
class ThreadExecutor final : public Executor { public:
[[nodiscard]] static Void::Result::Result<std::unique_ptr<ThreadExecutor>> create(ThreadExecutorOptions = {});
[[nodiscard]] Void::Result::Result<void> start();
void post(std::coroutine_handle<>) override;
[[nodiscard]] std::expected<void, AdmissionError> try_post(std::coroutine_handle<>) override;
void post_completion(std::coroutine_handle<>) override;
[[nodiscard]] bool supports_reservation() const noexcept override;
[[nodiscard]] std::expected<void, AdmissionError> try_reserve_slot() override;
void commit_reserved(std::coroutine_handle<>) override; void release_reserved() noexcept override;
[[nodiscard]] bool has_background_workers() const noexcept override;
void close() noexcept; [[nodiscard]] Void::Result::Result<void> join();
[[nodiscard]] bool idle() const noexcept; [[nodiscard]] std::size_t admitted() const noexcept;
[[nodiscard]] ThreadExecutorStats stats() const noexcept; ~ThreadExecutor() override; };
class FuturePool { public: explicit FuturePool(ThreadExecutor&) noexcept;
template <std::invocable F> [[nodiscard]] std::expected<std::future<std::invoke_result_t<F>>, AdmissionError>
try_submit(F&& f); };
enum class ChannelError : std::uint8_t { closed, empty, full, cancelled, timed_out, overloaded, invalid_argument };
struct ChannelOptions { std::size_t capacity{1024}; std::size_t max_waiters{1024}; TimerQueue* timers{nullptr}; };
template <class T> struct SendFailure { ChannelError error; T value; };
template <class T> class AsyncChannel : public std::enable_shared_from_this<AsyncChannel<T>> { public:
[[nodiscard]] static Void::Result::Result<std::shared_ptr<AsyncChannel>> create(Executor& resume, ChannelOptions = {});
[[nodiscard]] std::expected<void, SendFailure<T>> try_send(T);
[[nodiscard]] Coro::Task<std::expected<void, SendFailure<T>>> send(T, OperationOptions = {});
[[nodiscard]] std::expected<T, ChannelError> try_receive();
[[nodiscard]] Coro::Task<std::expected<T, ChannelError>> receive(OperationOptions = {});
void close() noexcept; [[nodiscard]] std::size_t size() const; [[nodiscard]] bool is_closed() const; };
[[nodiscard]] inline Void::Result::Error make_async_error(ChannelError, std::string message = {});
}
namespace Void::Concurrency { // ParallelFor.hpp (NEW overload)
struct ParallelForOptions { std::size_t grain{1}; std::size_t max_concurrency{0}; std::stop_token stop{}; bool stop_on_error{true}; };
struct ParallelForError { enum class Kind : std::uint8_t { invalid_argument, rejected, stopped, failed } kind;
std::size_t chunks_total{0}, chunks_started{0}, chunks_failed{0};
std::optional<std::size_t> first_failed_chunk{}; std::exception_ptr first_exception{}; };
template <std::integral I, std::invocable<I> F>
[[nodiscard]] std::expected<void, ParallelForError> parallel_for(I first, I last, F&& f, ThreadPool&, ParallelForOptions);
}
ChannelError maps into kAsyncErrorDomain via existing codes (closed→AsyncErrorCode::closed,
cancelled→cancelled, timed_out→timeout, overloaded/full→overloaded, empty/invalid_argument→
invalid_argument); the overload must not collide with existing make_async_error overloads.
max_concurrency == 0 = the pool's thread count; grain == 0 → invalid_argument. Unchanged 1.x:
ManualExecutor, ThreadPool, Channel, legacy parallel_for signatures, spawn, schedule_on.
8. Dependencies and integration
Upstream: M-ASYNC-03 (done), M-TIME-03 Timer (gate G2, present in your base). Downstream:
S-RUNTIME-02 uses ThreadExecutor (create/start/close/join/idle/admitted/stats), M-ASYNC-05 may use
ThreadExecutor in tests. Keep §7 exactly. Root integrates and commits.
9. Edge cases security and performance
Stop vs send vs receive vs close vs timer races (TSan); move-only T; exceptions thrown by T's move
constructor (document strong guarantee where possible); bounded waiters; no busy-waiting in join;
no user code under locks; hook throwing; zero workers rejected at create.
10. Acceptance criteria
Tests (all pass; TSan 0 races; ASan+UBSan 0 errors):
ThreadExecutor.cpp:thread_executor_create_starts_no_threads,thread_executor_bound_includes_running_work,thread_executor_reservation_with_task_scope_preserves_task,thread_executor_completion_lane_bypasses_full_normal_lane,thread_executor_close_rejects_normal_drains_completion,thread_executor_join_self_join_on_worker,thread_executor_partial_start_failure_joins_started,thread_executor_system_error_path_shared_with_hook,thread_executor_legacy_post_spawn_schedule_on_compat,thread_executor_inline_after_join_counted,thread_executor_stress_tsan.FuturePool.cpp:future_pool_overloaded_does_not_consume_callable,future_pool_stopped_after_close,future_pool_exception_in_future,future_pool_bound_includes_running.AsyncChannel.cpp:channel_zero_capacity_invalid,channel_try_send_full_returns_value,channel_send_waits_resumes_on_receive,channel_producer_stop_returns_value_cancelled_once,channel_receiver_stop_after_claim_delivers_value_no_loss,channel_sender_stop_vs_receive_race_exactly_once_tsan(10,000 iterations; multiset sent == received ∪ returned),channel_close_wakes_senders_with_value_and_drains_receivers,channel_deadline_requires_timers,channel_deadline_times_out_once_manual_clock_poll,channel_timer_close_settles_waiter_cancelled,channel_timer_fire_after_waiter_destroyed_safe,channel_waiter_bound_overloaded,channel_move_only_values,channel_mpmc_fifo_tsan,channel_deadline_check_order_returns_value.- Additional ThreadExecutor tests:
thread_executor_join_without_start_drains_inline,thread_executor_start_twice_and_after_close_invalid,thread_executor_reservation_across_close_binding. ParallelForBounded.cpp:parallel_for_bounded_grain_and_concurrency_limit,parallel_for_bounded_stop_joins_started_no_new_chunks,parallel_for_bounded_errors_join_all_lowest_index_reported,parallel_for_bounded_zero_grain_invalid,parallel_for_bounded_rejected_pool_runs_inline,parallel_for_bounded_waits_all_submitted_runners,legacy_parallel_for_exception_joins_all.- Existing
ParallelFor,ThreadPool,ThreadPoolBackpressure,Channel,OperationScope,Executor,Coro,TimerQueuetests pass unchanged.-Werrorclean.
11. Verification commands and evidence
Cwd = worktree root; dev with the sandbox disabled. Confirm new suites appear in output.
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async4 -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-async4 --parallel 8 && /tmp/void-w11-async4/tests/VoidTests --filter "^(ThreadExecutor|FuturePool|AsyncChannel|ParallelForBounded|ParallelFor|ThreadPool|ThreadPoolBackpressure|Channel|OperationScope|Executor|Coro|TimerQueue)\." && ctest --test-dir /tmp/void-w11-async4 --output-on-failure --timeout 60'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async4-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-async4-tsan --parallel 8 && /tmp/void-w11-async4-tsan/tests/VoidTests --filter "^(ThreadExecutor|FuturePool|AsyncChannel|ParallelForBounded|ParallelFor)\."'
dev cpp-gcc -c bash -lc 'for f in ThreadExecutor FuturePool AsyncChannel ParallelForBounded; do g++ -std=c++26 -freflection -fsyntax-only -Iinclude -Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers tests/standalone/Async/$f.cpp || exit 1; done'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async4-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-async4-asan --parallel 8 && /tmp/void-w11-async4-asan/tests/VoidTests --filter "^(ThreadExecutor|FuturePool|AsyncChannel|ParallelForBounded|ParallelFor)\."'
12. Constraints and stop conditions
No edits outside write scope; no weakened assertions; no disabled warnings; no change to 1.x semantics other than D-W11-10. Stop and report BLOCKED if the contract needs a forbidden-file edit, the reservation API cannot be satisfied as specified, or two repair attempts at one check fail.
13. Authorization and decisions
Root decisions D-034, D-038, D-040 under user decisions D-027/D-029/D-031. Listed files only; no commits, pushes or other side effects.
14. Return format
Task ID; DONE/BLOCKED/PARTIAL; summary; files changed; decisions/deviations; evidence per acceptance criterion; commands with cwd/results (counts, TSan/ASan); checks not run; residual risks; integration notes (worktree path). Do not spawn children.