#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Every assertion runs on the test thread: jobs executed by workers only touch // atomics or mutex-guarded containers (the assertion context is thread_local). namespace { using namespace Void::Async; using namespace std::chrono_literals; // Detached, self-destroying coroutine frame created suspended: a handle to // post. A job that is never resumed must be destroy()ed by its creator. struct Job { struct promise_type { Job get_return_object() noexcept { return Job{std::coroutine_handle::from_promise(*this)}; } std::suspend_always initial_suspend() noexcept { return {}; } std::suspend_never final_suspend() noexcept { return {}; } void return_void() noexcept {} void unhandled_exception() noexcept { std::terminate(); } }; std::coroutine_handle handle{}; }; Job make_job(std::function body) { body(); co_return; } class Gate { public: void open() { { std::lock_guard lk{mu_}; open_ = true; } cv_.notify_all(); } void wait() { std::unique_lock lk{mu_}; cv_.wait(lk, [this] { return open_; }); } private: std::mutex mu_{}; std::condition_variable cv_{}; bool open_{false}; }; template bool wait_until(Pred pred, std::chrono::milliseconds timeout = 5000ms) { const auto end = std::chrono::steady_clock::now() + timeout; while (!pred()) { if (std::chrono::steady_clock::now() >= end) { return false; } std::this_thread::sleep_for(1ms); } return true; } // Owns the executor and a gate. The destructor opens the gate FIRST, so a // failed assertion can never leave a blocker job hanging ~ThreadExecutor, then // destroys the executor (which joins) and finally the gate. struct Fixture { Gate gate{}; std::unique_ptr exec{}; Fixture(std::size_t workers, std::size_t max_admitted, bool start = true) { auto created = ThreadExecutor::create( ThreadExecutorOptions{.workers = workers, .max_admitted = max_admitted}); Void::Testing::require(created.has_value()); exec = std::move(*created); if (start) { Void::Testing::require(exec->start().has_value()); } } ~Fixture() { gate.open(); } Fixture(const Fixture&) = delete; Fixture& operator=(const Fixture&) = delete; ThreadExecutor& operator*() { return *exec; } ThreadExecutor* operator->() { return exec.get(); } }; // A job that occupies a worker until the fixture gate opens. Job make_blocker(Fixture& fx, std::atomic& running) { return make_job([&fx, &running] { running.store(true, std::memory_order_release); fx.gate.wait(); }); } std::optional async_code(const Void::Result::Error& error) { if (error.code().domain != Void::Result::kAsyncErrorDomain) { return std::nullopt; } return static_cast(error.code().value); } Void::Coro::Task bump_task(std::atomic* counter) { counter->fetch_add(1, std::memory_order_relaxed); co_return; } // Posts `job` through one of the four admission paths (retrying while the // bound is full). Returns false (and destroys the frame) on an unexpected // rejection. Assertion free: runs on poster threads. bool post_one(ThreadExecutor& exec, int kind, Job& job) { switch (kind) { case 0: for (;;) { const auto admitted = exec.try_post(job.handle); if (admitted.has_value()) { return true; } if (admitted.error() != AdmissionError::overloaded) { job.handle.destroy(); return false; } std::this_thread::yield(); } case 1: exec.post(job.handle); return true; case 2: exec.post_completion(job.handle); return true; default: for (;;) { const auto reserved = exec.try_reserve_slot(); if (reserved.has_value()) { break; } if (reserved.error() != AdmissionError::overloaded) { job.handle.destroy(); return false; } std::this_thread::yield(); } exec.commit_reserved(job.handle); return true; } } } // namespace Void::Testing::Test thread_executor_create_starts_no_threads() { std::atomic hook_calls{0}; std::atomic ran{0}; auto created = ThreadExecutor::create(ThreadExecutorOptions{ .workers = 2, .max_admitted = 4, .before_worker_start = [&hook_calls](std::size_t) -> Void::Result::Result { hook_calls.fetch_add(1); return {}; }}); Void::Testing::require(created.has_value()); auto& exec = **created; // No thread (and no hook call) exists yet. Void::Testing::expect_eq(hook_calls.load(), 0); Void::Testing::expect(exec.idle()); Void::Testing::expect_eq(exec.admitted(), std::size_t{0}); Void::Testing::expect(exec.supports_reservation()); Void::Testing::expect(exec.has_background_workers()); // Admission before start() queues normally and nothing runs. auto job = make_job([&ran] { ran.fetch_add(1); }); Void::Testing::require(exec.try_post(job.handle).has_value()); Void::Testing::expect_eq(exec.admitted(), std::size_t{1}); std::this_thread::sleep_for(30ms); Void::Testing::expect_eq(ran.load(), 0); Void::Testing::expect_eq(exec.stats().queued, std::size_t{1}); Void::Testing::expect(!exec.idle()); Void::Testing::require(exec.start().has_value()); Void::Testing::expect_eq(hook_calls.load(), 2); Void::Testing::expect(wait_until([&] { return ran.load() == 1; })); Void::Testing::require(exec.join().has_value()); // create() validates its options. const auto zero_workers = ThreadExecutor::create(ThreadExecutorOptions{.workers = 0}); Void::Testing::require(!zero_workers.has_value()); Void::Testing::expect(async_code(zero_workers.error()) == AsyncErrorCode::invalid_argument); const auto zero_bound = ThreadExecutor::create(ThreadExecutorOptions{.max_admitted = 0}); Void::Testing::require(!zero_bound.has_value()); Void::Testing::expect(async_code(zero_bound.error()) == AsyncErrorCode::invalid_argument); } Void::Testing::Test thread_executor_bound_includes_running_work() { std::atomic blocker_running{false}; std::atomic ran{0}; Fixture exec{1, 2}; auto blocker = make_blocker(exec, blocker_running); Void::Testing::require(exec->try_post(blocker.handle).has_value()); Void::Testing::require(wait_until([&] { return blocker_running.load(); })); // The running blocker keeps its slot. Void::Testing::expect_eq(exec->admitted(), std::size_t{1}); Void::Testing::expect_eq(exec->stats().running, std::size_t{1}); auto queued = make_job([&ran] { ran.fetch_add(1); }); Void::Testing::require(exec->try_post(queued.handle).has_value()); Void::Testing::expect_eq(exec->admitted(), std::size_t{2}); // running (1) + queued (1) == max_admitted (2): the next one is rejected. auto rejected = make_job([&ran] { ran.fetch_add(100); }); const auto overloaded = exec->try_post(rejected.handle); Void::Testing::expect(!overloaded.has_value()); Void::Testing::expect(overloaded.error() == AdmissionError::overloaded); rejected.handle.destroy(); Void::Testing::expect_eq(exec->stats().rejected, std::uint64_t{1}); Void::Testing::expect_eq(exec->stats().queued, std::size_t{1}); // Legacy post() never rejects: it may exceed the bound and is counted. auto legacy = make_job([&ran] { ran.fetch_add(10); }); exec->post(legacy.handle); Void::Testing::expect_eq(exec->admitted(), std::size_t{3}); Void::Testing::expect_eq(exec->stats().legacy_posts, std::uint64_t{1}); // A null handle is invalid for try_post. const auto null_handle = exec->try_post({}); Void::Testing::expect(!null_handle.has_value()); Void::Testing::expect(null_handle.error() == AdmissionError::invalid_argument); exec.gate.open(); Void::Testing::expect(wait_until([&] { return ran.load() == 11 && exec->idle(); })); // A slot is free again once the work returned. auto again = make_job([&ran] { ran.fetch_add(1000); }); Void::Testing::require(exec->try_post(again.handle).has_value()); Void::Testing::expect(wait_until([&] { return ran.load() == 1011; })); Void::Testing::expect(wait_until([&] { return exec->admitted() == 0; })); } Void::Testing::Test thread_executor_reservation_with_task_scope_preserves_task() { std::atomic blocker_running{false}; std::atomic ran{0}; Fixture exec{1, 1}; TaskScope scope{*exec, TaskScopeOptions{.max_tasks = 8}}; auto blocker = make_blocker(exec, blocker_running); Void::Testing::require(exec->try_post(blocker.handle).has_value()); Void::Testing::require(wait_until([&] { return blocker_running.load(); })); // The bound is full: TaskScope's reserve-then-transfer is rejected and the // caller still owns the task. auto preserved = bump_task(&ran); const auto rejected = scope.spawn(std::move(preserved)); Void::Testing::require(!rejected.has_value()); Void::Testing::expect(rejected.error() == AdmissionError::overloaded); Void::Testing::expect(static_cast(preserved.handle())); Void::Testing::expect(!preserved.done()); // The failed reservation did not leak a slot. Void::Testing::expect_eq(exec->admitted(), std::size_t{1}); Void::Testing::expect_eq(ran.load(), 0); exec.gate.open(); Void::Testing::require(wait_until([&] { return exec->admitted() == 0; })); const auto accepted = scope.spawn(std::move(preserved)); Void::Testing::require(accepted.has_value()); Void::Testing::require(scope.join_blocking().has_value()); Void::Testing::expect_eq(ran.load(), 1); Void::Testing::expect(wait_until([&] { return exec->admitted() == 0; })); } Void::Testing::Test thread_executor_completion_lane_bypasses_full_normal_lane() { std::atomic blocker_running{false}; std::atomic completion_ran{0}; Fixture exec{1, 1}; auto blocker = make_blocker(exec, blocker_running); Void::Testing::require(exec->try_post(blocker.handle).has_value()); Void::Testing::require(wait_until([&] { return blocker_running.load(); })); // The normal lane is full ... auto normal = make_job([] {}); const auto overloaded = exec->try_post(normal.handle); Void::Testing::expect(!overloaded.has_value()); normal.handle.destroy(); const auto reserve_rejected = exec->try_reserve_slot(); Void::Testing::expect(!reserve_rejected.has_value()); Void::Testing::expect(reserve_rejected.error() == AdmissionError::overloaded); // ... but the completion lane still accepts and is not part of the bound. auto completion = make_job([&completion_ran] { completion_ran.fetch_add(1); }); exec->post_completion(completion.handle); Void::Testing::expect_eq(exec->stats().completion_queued, std::size_t{1}); Void::Testing::expect_eq(exec->admitted(), std::size_t{1}); exec.gate.open(); Void::Testing::expect(wait_until([&] { return completion_ran.load() == 1; })); Void::Testing::expect(wait_until([&] { return exec->idle(); })); } Void::Testing::Test thread_executor_close_rejects_normal_drains_completion() { std::atomic blocker_running{false}; std::atomic order_counter{0}; std::atomic completion_order{-1}; std::atomic legacy_order{-1}; std::atomic queued_order{-1}; Fixture exec{1, 8}; auto blocker = make_blocker(exec, blocker_running); Void::Testing::require(exec->try_post(blocker.handle).has_value()); Void::Testing::require(wait_until([&] { return blocker_running.load(); })); auto queued = make_job([&] { queued_order.store(order_counter.fetch_add(1)); }); Void::Testing::require(exec->try_post(queued.handle).has_value()); exec->close(); // Normal admission is closed. auto refused = make_job([] {}); const auto stopped_post = exec->try_post(refused.handle); Void::Testing::expect(!stopped_post.has_value()); Void::Testing::expect(stopped_post.error() == AdmissionError::stopped); refused.handle.destroy(); const auto stopped_reserve = exec->try_reserve_slot(); Void::Testing::expect(!stopped_reserve.has_value()); Void::Testing::expect(stopped_reserve.error() == AdmissionError::stopped); // A legacy post after close() is redirected to the completion lane and // counted; post_completion keeps working. auto legacy = make_job([&] { legacy_order.store(order_counter.fetch_add(1)); }); exec->post(legacy.handle); auto completion = make_job([&] { completion_order.store(order_counter.fetch_add(1)); }); exec->post_completion(completion.handle); Void::Testing::expect_eq(exec->stats().completion_queued, std::size_t{2}); Void::Testing::expect_eq(exec->stats().legacy_posts, std::uint64_t{1}); exec.gate.open(); Void::Testing::require(exec->join().has_value()); // Both lanes drained; the completion lane (legacy post, then the explicit // completion) runs before the queued normal handle. Void::Testing::expect_eq(legacy_order.load(), 0); Void::Testing::expect_eq(completion_order.load(), 1); Void::Testing::expect_eq(queued_order.load(), 2); Void::Testing::expect(exec->idle()); } Void::Testing::Test thread_executor_join_self_join_on_worker() { std::atomic code{-1}; std::atomic observed_executor_thread{false}; Fixture exec{1, 4}; auto job = make_job([&] { const auto joined = exec->join(); code.store(joined.has_value() ? 0 : static_cast(joined.error().code().value)); observed_executor_thread.store(exec->is_executor_thread()); }); Void::Testing::require(exec->try_post(job.handle).has_value()); Void::Testing::require(wait_until([&] { return code.load() != -1; })); Void::Testing::expect_eq(code.load(), static_cast(AsyncErrorCode::self_join)); Void::Testing::expect(observed_executor_thread.load()); // A normal join from a non-executor thread still works afterwards. Void::Testing::expect(!exec->is_executor_thread()); Void::Testing::require(exec->join().has_value()); } Void::Testing::Test thread_executor_partial_start_failure_joins_started() { std::atomic hook_calls{0}; std::atomic fail{true}; std::atomic ran{0}; auto created = ThreadExecutor::create(ThreadExecutorOptions{ .workers = 3, .max_admitted = 8, .before_worker_start = [&](std::size_t index) -> Void::Result::Result { hook_calls.fetch_add(1); if (fail.load() && index == 2) { return std::unexpected{make_async_error( AsyncErrorCode::limit_exceeded, "injected thread start failure")}; } return {}; }}); Void::Testing::require(created.has_value()); auto& exec = **created; // Work admitted before start() must not run on workers of a failed start. auto job = make_job([&ran] { ran.fetch_add(1); }); Void::Testing::require(exec.try_post(job.handle).has_value()); const auto failed = exec.start(); Void::Testing::require(!failed.has_value()); Void::Testing::expect(async_code(failed.error()) == AsyncErrorCode::limit_exceeded); Void::Testing::expect_eq(hook_calls.load(), 3); std::this_thread::sleep_for(30ms); Void::Testing::expect_eq(ran.load(), 0); Void::Testing::expect_eq(exec.stats().queued, std::size_t{1}); Void::Testing::expect_eq(exec.stats().running, std::size_t{0}); // The two workers that were already started were joined: a retry starts a // full set again. fail.store(false); Void::Testing::require(exec.start().has_value()); Void::Testing::expect_eq(hook_calls.load(), 6); Void::Testing::expect(wait_until([&] { return ran.load() == 1; })); Void::Testing::require(exec.join().has_value()); } Void::Testing::Test thread_executor_system_error_path_shared_with_hook() { std::atomic mode{0}; // 0 = ok, 1 = system_error, 2 = runtime_error std::atomic hook_calls{0}; std::atomic ran{0}; auto created = ThreadExecutor::create(ThreadExecutorOptions{ .workers = 3, .max_admitted = 8, .before_worker_start = [&](std::size_t index) -> Void::Result::Result { hook_calls.fetch_add(1); if (index == 1 && mode.load() == 1) { throw std::system_error{std::make_error_code(std::errc::resource_unavailable_try_again), "injected thread creation failure"}; } if (index == 1 && mode.load() == 2) { throw std::runtime_error{"injected hook failure"}; } return {}; }}); Void::Testing::require(created.has_value()); auto& exec = **created; auto job = make_job([&ran] { ran.fetch_add(1); }); Void::Testing::require(exec.try_post(job.handle).has_value()); // std::system_error: same cleanup path as a hook error, system code kept. mode.store(1); const auto sys_failed = exec.start(); Void::Testing::require(!sys_failed.has_value()); Void::Testing::expect(async_code(sys_failed.error()) == AsyncErrorCode::backend_error); Void::Testing::expect(sys_failed.error().system_code() == std::make_error_code(std::errc::resource_unavailable_try_again)); Void::Testing::expect_eq(hook_calls.load(), 2); // Any other exception takes the same path, without a system code. mode.store(2); const auto other_failed = exec.start(); Void::Testing::require(!other_failed.has_value()); Void::Testing::expect(async_code(other_failed.error()) == AsyncErrorCode::backend_error); Void::Testing::expect(!other_failed.error().system_code()); Void::Testing::expect_eq(hook_calls.load(), 4); Void::Testing::expect_eq(ran.load(), 0); mode.store(0); Void::Testing::require(exec.start().has_value()); Void::Testing::expect(wait_until([&] { return ran.load() == 1; })); Void::Testing::require(exec.join().has_value()); } namespace { Void::Coro::Task hop_task(ThreadExecutor* exec, std::atomic* stage, std::atomic* on_executor_before, std::atomic* on_executor_after, std::atomic* status_code) { on_executor_before->store(exec->is_executor_thread()); stage->store(1); co_await schedule_on(*exec); stage->store(2); const auto status = co_await schedule_on(*exec, OperationOptions{}); status_code->store(status.has_value() ? 0 : static_cast(status.error().code().value)); on_executor_after->store(exec->is_executor_thread()); stage->store(3); } } // namespace Void::Testing::Test thread_executor_legacy_post_spawn_schedule_on_compat() { std::atomic stage{0}; std::atomic before{false}; std::atomic after{false}; std::atomic status_code{-1}; std::atomic blocker_running{false}; std::atomic ran{0}; Fixture exec{1, 2}; // spawn() and schedule_on(executor) use the legacy post(): never rejected. // spawn() is called from the single worker itself, not from a foreign // thread: ThreadSanitizer reports a data race in Executor.hpp's spawn_impl // (lines 292/296) when spawn() is called from a thread other than the // executor's workers onto a multi-worker executor. That behaviour is // independent of ThreadExecutor and is escalated to the root; it is not // covered here. auto spawner = make_job([&] { spawn(*exec, hop_task(exec.exec.get(), &stage, &before, &after, &status_code)); }); Void::Testing::require(exec->try_post(spawner.handle).has_value()); Void::Testing::require(wait_until([&] { return stage.load() == 3; })); Void::Testing::expect(before.load()); Void::Testing::expect(after.load()); Void::Testing::expect_eq(status_code.load(), 0); Void::Testing::expect(exec->stats().legacy_posts >= 2); // A full bound (running + queued == 2) rejects try_post (and the status // schedule_on built on it) but never the legacy post. auto blocker = make_blocker(exec, blocker_running); Void::Testing::require(exec->try_post(blocker.handle).has_value()); Void::Testing::require(wait_until([&] { return blocker_running.load(); })); auto filler = make_job([&ran] { ran.fetch_add(1); }); Void::Testing::require(exec->try_post(filler.handle).has_value()); auto rejected = make_job([] {}); Void::Testing::expect(!exec->try_post(rejected.handle).has_value()); rejected.handle.destroy(); const std::uint64_t legacy_before = exec->stats().legacy_posts; auto j1 = make_job([&ran] { ran.fetch_add(1); }); auto j2 = make_job([&ran] { ran.fetch_add(1); }); exec->post(j1.handle); exec->post(j2.handle); Void::Testing::expect_eq(exec->stats().legacy_posts, legacy_before + 2); Void::Testing::expect_eq(exec->admitted(), std::size_t{4}); exec.gate.open(); Void::Testing::expect(wait_until([&] { return ran.load() == 3; })); Void::Testing::require(exec->join().has_value()); } Void::Testing::Test thread_executor_inline_after_join_counted() { std::atomic ran{0}; std::mutex mu; std::vector threads; std::atomic guarded{false}; auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 2, .max_admitted = 4}); Void::Testing::require(created.has_value()); auto& exec = **created; Void::Testing::require(exec.start().has_value()); auto before_join = make_job([&] { ran.fetch_add(1); }); Void::Testing::require(exec.try_post(before_join.handle).has_value()); Void::Testing::require(exec.join().has_value()); Void::Testing::expect_eq(ran.load(), 1); Void::Testing::expect_eq(exec.stats().inline_after_join, std::uint64_t{0}); // After join, posts resume inline on the caller (counted), never dropped. const auto caller = std::this_thread::get_id(); auto record = [&] { std::lock_guard lk{mu}; threads.push_back(std::this_thread::get_id()); guarded.store(exec.is_executor_thread()); }; auto j1 = make_job(record); exec.post(j1.handle); auto j2 = make_job(record); exec.post_completion(j2.handle); Void::Testing::expect_eq(threads.size(), std::size_t{2}); Void::Testing::expect(threads[0] == caller); Void::Testing::expect(threads[1] == caller); // The inline resume runs under ExecutorThreadGuard. Void::Testing::expect(guarded.load()); Void::Testing::expect(!exec.is_executor_thread()); Void::Testing::expect_eq(exec.stats().inline_after_join, std::uint64_t{2}); Void::Testing::expect_eq(exec.stats().legacy_posts, std::uint64_t{1}); // Normal admission stays closed after join, and join/start are repeatable // or rejected. auto refused = make_job([] {}); const auto stopped = exec.try_post(refused.handle); Void::Testing::expect(!stopped.has_value()); Void::Testing::expect(stopped.error() == AdmissionError::stopped); refused.handle.destroy(); const auto reserved = exec.try_reserve_slot(); Void::Testing::expect(!reserved.has_value()); Void::Testing::expect(reserved.error() == AdmissionError::stopped); Void::Testing::require(exec.join().has_value()); const auto restarted = exec.start(); Void::Testing::expect(!restarted.has_value()); Void::Testing::expect(exec.idle()); } Void::Testing::Test thread_executor_join_without_start_drains_inline() { std::mutex mu; std::vector order; std::atomic all_on_caller{true}; const auto caller = std::this_thread::get_id(); auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 2, .max_admitted = 8}); Void::Testing::require(created.has_value()); auto& exec = **created; auto make_marker = [&](int id) { return make_job([&, id] { std::lock_guard lk{mu}; order.push_back(id); if (std::this_thread::get_id() != caller) { all_on_caller.store(false); } }); }; auto n1 = make_marker(1); auto n2 = make_marker(2); auto c1 = make_marker(10); auto n3 = make_marker(3); Void::Testing::require(exec.try_post(n1.handle).has_value()); Void::Testing::require(exec.try_post(n2.handle).has_value()); exec.post_completion(c1.handle); exec.post(n3.handle); Void::Testing::expect_eq(exec.admitted(), std::size_t{3}); // No worker exists: join() drains both lanes inline, never waits. Void::Testing::require(exec.join().has_value()); Void::Testing::expect(all_on_caller.load()); // Completion lane first, then the normal lane in FIFO order. Void::Testing::expect_eq(order.size(), std::size_t{4}); if (order.size() == 4) { Void::Testing::expect_eq(order[0], 10); Void::Testing::expect_eq(order[1], 1); Void::Testing::expect_eq(order[2], 2); Void::Testing::expect_eq(order[3], 3); } Void::Testing::expect_eq(exec.stats().inline_after_join, std::uint64_t{4}); Void::Testing::expect(exec.idle()); Void::Testing::expect(!exec.start().has_value()); // The destructor of a never-started executor also drains inline. std::atomic ran{0}; { auto second = ThreadExecutor::create(); Void::Testing::require(second.has_value()); auto pending = make_job([&ran] { ran.fetch_add(1); }); Void::Testing::require((*second)->try_post(pending.handle).has_value()); } Void::Testing::expect_eq(ran.load(), 1); } Void::Testing::Test thread_executor_start_twice_and_after_close_invalid() { auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 2, .max_admitted = 4}); Void::Testing::require(created.has_value()); auto& exec = **created; Void::Testing::require(exec.start().has_value()); const auto twice = exec.start(); Void::Testing::require(!twice.has_value()); Void::Testing::expect(async_code(twice.error()) == AsyncErrorCode::invalid_argument); auto closed_created = ThreadExecutor::create(); Void::Testing::require(closed_created.has_value()); auto& closed = **closed_created; closed.close(); const auto after_close = closed.start(); Void::Testing::require(!after_close.has_value()); Void::Testing::expect(async_code(after_close.error()) == AsyncErrorCode::invalid_argument); Void::Testing::require(exec.join().has_value()); const auto after_join = exec.start(); Void::Testing::require(!after_join.has_value()); Void::Testing::expect(async_code(after_join.error()) == AsyncErrorCode::invalid_argument); } Void::Testing::Test thread_executor_reservation_across_close_binding() { std::atomic ran{0}; std::atomic joined{false}; std::atomic join_ok{false}; std::atomic job_on_joiner{false}; // (1) Workers running: a reservation taken before close() stays binding. { auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 1, .max_admitted = 2}); Void::Testing::require(created.has_value()); auto& exec = **created; Void::Testing::require(exec.start().has_value()); Void::Testing::require(exec.try_reserve_slot().has_value()); // A reserved slot counts in admitted() and in the bound. Void::Testing::expect_eq(exec.admitted(), std::size_t{1}); Void::Testing::require(exec.try_reserve_slot().has_value()); const auto full = exec.try_reserve_slot(); Void::Testing::expect(!full.has_value()); Void::Testing::expect(full.error() == AdmissionError::overloaded); exec.release_reserved(); Void::Testing::expect_eq(exec.admitted(), std::size_t{1}); exec.close(); const auto after_close = exec.try_reserve_slot(); Void::Testing::expect(!after_close.has_value()); Void::Testing::expect(after_close.error() == AdmissionError::stopped); Void::Testing::expect_eq(exec.admitted(), std::size_t{1}); std::thread joiner([&] { join_ok.store(exec.join().has_value()); joined.store(true); }); // join() also waits until no reservation is outstanding. std::this_thread::sleep_for(60ms); Void::Testing::expect(!joined.load()); auto job = make_job([&ran] { ran.fetch_add(1); }); exec.commit_reserved(job.handle); // binding: enqueues normally after close() joiner.join(); Void::Testing::expect(joined.load()); Void::Testing::expect(join_ok.load()); Void::Testing::expect_eq(ran.load(), 1); Void::Testing::expect_eq(exec.admitted(), std::size_t{0}); } // (2) A released reservation also lets join() finish (no workers: the // joiner drains inline, but still waits for the reservation). { joined.store(false); join_ok.store(false); auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 1, .max_admitted = 2}); Void::Testing::require(created.has_value()); auto& exec = **created; Void::Testing::require(exec.try_reserve_slot().has_value()); std::thread joiner([&] { join_ok.store(exec.join().has_value()); joined.store(true); }); std::this_thread::sleep_for(60ms); Void::Testing::expect(!joined.load()); exec.release_reserved(); joiner.join(); Void::Testing::expect(joined.load()); Void::Testing::expect(join_ok.load()); } // (3) No workers + a commit after join() began: the committed handle is // drained by the joining thread. { joined.store(false); join_ok.store(false); const auto joiner_id = std::make_shared>(); auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 1, .max_admitted = 2}); Void::Testing::require(created.has_value()); auto& exec = **created; Void::Testing::require(exec.try_reserve_slot().has_value()); std::thread joiner([&] { joiner_id->store(std::this_thread::get_id()); join_ok.store(exec.join().has_value()); joined.store(true); }); std::this_thread::sleep_for(60ms); auto job = make_job([&] { job_on_joiner.store(std::this_thread::get_id() == joiner_id->load()); ran.fetch_add(1); }); exec.commit_reserved(job.handle); joiner.join(); Void::Testing::expect(join_ok.load()); Void::Testing::expect(job_on_joiner.load()); Void::Testing::expect_eq(ran.load(), 2); } } Void::Testing::Test thread_executor_stress_tsan() { constexpr int kPosters = 4; constexpr int kPerPoster = 1200; std::atomic accepted{0}; std::atomic executed{0}; std::atomic posted_failed_unexpectedly{0}; std::atomic snapshot_inconsistent{0}; std::vector posters; auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 3, .max_admitted = 32}); Void::Testing::require(created.has_value()); auto& exec = **created; Void::Testing::require(exec.start().has_value()); for (int p = 0; p < kPosters; ++p) { posters.emplace_back([&, p] { for (int k = 0; k < kPerPoster; ++k) { const int kind = (p + k) % 4; auto job = make_job([&executed] { executed.fetch_add(1, std::memory_order_relaxed); }); if (post_one(exec, kind, job)) { accepted.fetch_add(1, std::memory_order_relaxed); } else { posted_failed_unexpectedly.fetch_add(1); } if ((k & 63) == 0) { const auto stats = exec.stats(); if (stats.running > 3) { snapshot_inconsistent.fetch_add(1); } (void)exec.idle(); } } }); } for (auto& poster : posters) { poster.join(); } // Repeated and concurrent join(): every caller returns success and the // worker threads are joined exactly once. std::atomic concurrent_join_failures{0}; std::vector joiners; for (int j = 0; j < 3; ++j) { joiners.emplace_back([&] { if (!exec.join().has_value()) { concurrent_join_failures.fetch_add(1); } }); } const bool main_join_ok = exec.join().has_value(); for (auto& joiner : joiners) { joiner.join(); } Void::Testing::require(main_join_ok); Void::Testing::expect_eq(concurrent_join_failures.load(), 0); Void::Testing::expect_eq(posted_failed_unexpectedly.load(), std::uint64_t{0}); Void::Testing::expect_eq(snapshot_inconsistent.load(), std::uint64_t{0}); Void::Testing::expect_eq(accepted.load(), static_cast(kPosters) * kPerPoster); Void::Testing::expect_eq(executed.load(), accepted.load()); Void::Testing::expect(exec.idle()); Void::Testing::expect_eq(exec.admitted(), std::size_t{0}); } // Regression (W11): spawn() from a foreign thread onto a multi-worker executor // must not race with the worker that resumes and destroys the detached frame. namespace { Void::Coro::Task spawn_bump(std::atomic* counter) { counter->fetch_add(1, std::memory_order_relaxed); co_return; } } // namespace Void::Testing::Test thread_executor_spawn_from_foreign_thread_multi_worker_tsan() { auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 4, .max_admitted = 64}); Void::Testing::require(created.has_value()); auto& exec = **created; Void::Testing::require(exec.start().has_value()); constexpr int kSpawns = 2000; std::atomic counter{0}; for (int i = 0; i < kSpawns; ++i) { spawn(exec, spawn_bump(&counter)); } Void::Testing::require(exec.join().has_value()); Void::Testing::expect_eq(counter.load(std::memory_order_relaxed), kSpawns); }