#include "settlement/core/world.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { using namespace settlement; using namespace std::chrono_literals; using Void::Testing::expect_throw; using Void::Testing::require; using Void::Testing::Test; std::string bytes(const World& world) { std::ostringstream stream(std::ios::binary); world.write_save(stream); return stream.str(); } void populate_jobs(World& world) { for (int i = 0; i < 12; ++i) { static_cast(world.spawn_agent({1 + i % 3, 1 + i / 3})); static_cast(world.add_job({15, 1 + i}, 3)); } } // The later task remains inside a borrowed world-stage callable while an // earlier get() or a later submission fails. Returning from step must drain it. void check_world_unwind(std::size_t phase, bool submit_failure) { std::promise blocked; auto entered = blocked.get_future(); std::promise release; auto permit = release.get_future().share(); std::atomic completed{false}; WorkerPoolOptions options; options.before_submit = [phase, submit_failure](std::size_t index) { if (submit_failure && index == phase + 1) throw std::bad_alloc(); }; options.before_execute = [&](std::size_t index) { if (index == phase + (submit_failure ? 0U : 1U)) { blocked.set_value(); if (permit.wait_for(5s) != std::future_status::ready) { throw std::runtime_error("test did not release a blocked world task"); } completed.store(true); } if (!submit_failure && index == phase) throw std::runtime_error("injected task failure"); }; World world(55, 16, 16, 2, ExecutionMode::Parallel, options); static_cast(world.spawn_agent({1, 1})); static_cast(world.spawn_agent({1, 2})); // Distinct nearest goals avoid a second arbitration batch before paths. static_cast(world.add_job({5, 1}, 3)); static_cast(world.add_job({5, 2}, 3)); auto result = std::async(std::launch::async, [&] { try { world.step(); } catch (const std::bad_alloc&) { return submit_failure && completed.load(); } catch (const std::runtime_error&) { return !submit_failure && completed.load(); } return false; }); // Declared after result so failure always releases the task before joining. auto release_task = Void::Scope::on_exit([&] { release.set_value(); }); require(entered.wait_for(5s) == std::future_status::ready); require(result.wait_for(0s) == std::future_status::timeout); release_task.release(); release.set_value(); require(result.wait_for(5s) == std::future_status::ready); require(result.get()); } struct [[= Void::Testing::name("ExecutorTests")]] ExecutorTests : Void::Testing::Suite { [[= Void::Testing::tag("executor")]] Test test_completion_observer_results_and_failures(); [[= Void::Testing::tag("executor")]] Test test_completion_observer_precedes_future_readiness(); [[= Void::Testing::tag("executor")]] Test test_limits_and_nested_submission(); [[= Void::Testing::tag("executor")]] Test test_capacity_retains_move_only_work_and_exceptions(); [[= Void::Testing::tag("executor")]] Test test_failed_callable_transfer_releases_capacity(); [[= Void::Testing::tag("executor")]] Test test_partial_start_failure_and_retry(); [[= Void::Testing::tag("executor")]] Test test_shutdown_drains_work(); [[= Void::Testing::tag("executor")]] Test test_world_drains_after_submission_failure(); [[= Void::Testing::tag("executor")]] Test test_world_drains_after_task_failure(); [[= Void::Testing::tag("executor")]] Test test_world_capacity_one_matches_reference(); }; // Exercise the same wrapper on a worker and on the submitting thread. Keeping // index zero admitted forces every other submission through inline overload. Test ExecutorTests::test_completion_observer_results_and_failures() { for (bool inline_work : {false, true}) { std::promise release; auto permit = release.get_future().share(); std::promise entered; auto running = entered.get_future(); std::array, 8> observed{}; std::array, 8> returned{}; std::atomic observed_too_early{false}; WorkerPoolOptions options{.max_admitted = inline_work ? 1U : 4096U}; options.before_submit = [](std::size_t index) { if (index == 8) throw std::bad_alloc(); }; options.before_execute = [](std::size_t index) { if (index == 6) throw std::runtime_error("before invocation"); }; options.after_execute = [&](std::size_t index) { if (index >= observed.size()) throw std::logic_error("observer on failed submission"); if (!returned[index].load()) observed_too_early.store(true); ++observed[index]; if (index == 7) throw std::runtime_error("after invocation"); }; WorkerPool pool(2, std::move(options)); auto release_task = Void::Scope::on_exit([&] { release.set_value(); }); auto held = pool.submit([&] { entered.set_value(); if (permit.wait_for(5s) != std::future_status::ready) throw std::runtime_error("release timeout"); returned[0] = true; }); require(running.wait_for(5s) == std::future_status::ready); const auto caller = std::this_thread::get_id(); auto value = pool.submit([&] { returned[1] = true; return std::pair{17, std::this_thread::get_id() == caller}; }); require(value.get() == std::pair{17, inline_work}); int referent = 23; auto reference = pool.submit([&]() -> int& { returned[2] = true; return referent; }); require(&reference.get() == &referent); auto nothing = pool.submit([&] { returned[3] = true; }); nothing.get(); auto owned = pool.submit([&, value = std::make_unique(31)]() mutable { returned[4] = true; return std::move(value); }); require(*owned.get() == 31); auto failure = pool.submit([]() -> int { throw std::runtime_error("invocation failed"); }); expect_throw([&] { static_cast(failure.get()); }); auto before = pool.submit([&] { returned[6] = true; }); expect_throw([&] { before.get(); }); auto after = pool.submit([&] { returned[7] = true; }); expect_throw([&] { after.get(); }); bool submitted_failure_ran = false; expect_throw([&] { static_cast(pool.submit([&] { submitted_failure_ran = true; })); }); require(!submitted_failure_ran); release_task.release(); release.set_value(); held.get(); for (std::size_t i = 0; i < observed.size(); ++i) { require(observed[i] == ((i == 5 || i == 6) ? 0 : 1)); } require(!returned[6] && !observed_too_early); } } Test ExecutorTests::test_completion_observer_precedes_future_readiness() { std::promise observed; auto entered = observed.get_future(); std::promise release; auto permit = release.get_future().share(); std::atomic calls{0}; WorkerPoolOptions options; // Observer alone must enable monotonically increasing submission indices. options.after_execute = [&](std::size_t index) { if (index != static_cast(calls.fetch_add(1))) throw std::runtime_error("bad index"); if (index == 0) { observed.set_value(); if (permit.wait_for(5s) != std::future_status::ready) throw std::runtime_error("release timeout"); } }; WorkerPool pool(2, std::move(options)); auto release_task = Void::Scope::on_exit([&] { release.set_value(); }); auto result = pool.submit([] { return 11; }); require(entered.wait_for(5s) == std::future_status::ready); require(result.wait_for(0s) == std::future_status::timeout); release_task.release(); release.set_value(); require(result.get() == 11); pool.submit([] {}).get(); require(calls == 2); } Test ExecutorTests::test_limits_and_nested_submission() { expect_throw([] { WorkerPool pool(1); }); expect_throw([] { WorkerPool pool(2, {.max_admitted = 0}); }); WorkerPool pool(2); require(pool.thread_count() == 2); auto nested = pool.submit([&] { return pool.submit([] { return 7; }).get(); }); expect_throw([&] { static_cast(nested.get()); }); require(pool.submit([] { return 9; }).get() == 9); } Test ExecutorTests::test_capacity_retains_move_only_work_and_exceptions() { std::promise running; auto entered = running.get_future(); std::promise release; auto permit = release.get_future().share(); WorkerPool pool(2, {.max_admitted = 1}); auto release_task = Void::Scope::on_exit([&] { release.set_value(); }); auto held = pool.submit([&] { running.set_value(); if (permit.wait_for(5s) != std::future_status::ready) throw std::runtime_error("test release timeout"); return 3; }); require(entered.wait_for(5s) == std::future_status::ready); const auto coordinator = std::this_thread::get_id(); std::atomic executions{0}; auto answer = pool.submit([value = std::make_unique(17), coordinator, &executions] { if (std::this_thread::get_id() != coordinator) throw std::runtime_error("expected inline work"); ++executions; return *value; }); require(answer.get() == 17 && executions.load() == 1); auto failed = pool.submit([]() -> int { throw std::runtime_error("inline failure"); }); expect_throw([&] { static_cast(failed.get()); }); release_task.release(); release.set_value(); require(held.get() == 3); auto threaded_failure = pool.submit([] { throw std::runtime_error("worker failure"); }); expect_throw([&] { threaded_failure.get(); }); } Test ExecutorTests::test_failed_callable_transfer_releases_capacity() { struct FailingMove { FailingMove() = default; FailingMove(const FailingMove&) = delete; FailingMove(FailingMove&&) { throw std::bad_alloc(); } void operator()() const {} }; WorkerPool pool(2, {.max_admitted = 1}); FailingMove function; expect_throw([&] { static_cast(pool.submit(std::move(function))); }); const auto coordinator = std::this_thread::get_id(); require(pool.submit([coordinator] { return std::this_thread::get_id() != coordinator; }).get()); } Test ExecutorTests::test_partial_start_failure_and_retry() { int calls = 0; WorkerPoolOptions options; options.before_worker_start = [&](std::size_t index) { ++calls; if (index == 1) throw std::runtime_error("injected partial start failure"); }; expect_throw([&] { WorkerPool failed(3, options); }); require(calls == 2); WorkerPool retry(3); require(retry.thread_count() == 3 && retry.submit([] { return 4; }).get() == 4); } Test ExecutorTests::test_shutdown_drains_work() { std::promise running; auto entered = running.get_future(); std::promise release; auto permit = release.get_future().share(); std::atomic completed{0}; auto pool = std::make_unique(2); auto work = pool->submit([&] { running.set_value(); if (permit.wait_for(5s) != std::future_status::ready) throw std::runtime_error("test release timeout"); ++completed; }); std::promise destroying; auto started = destroying.get_future(); auto destruction = std::async(std::launch::async, [&, owned = std::move(pool)]() mutable { destroying.set_value(); owned.reset(); return completed.load(); }); auto release_task = Void::Scope::on_exit([&] { release.set_value(); }); require(entered.wait_for(5s) == std::future_status::ready); require(started.wait_for(5s) == std::future_status::ready); require(destruction.wait_for(10ms) == std::future_status::timeout); release_task.release(); release.set_value(); require(destruction.wait_for(5s) == std::future_status::ready); require(destruction.get() == 1 && work.wait_for(0s) == std::future_status::ready); work.get(); } Test ExecutorTests::test_world_drains_after_submission_failure() { for (std::size_t phase : {0U, 2U, 4U}) check_world_unwind(phase, true); } Test ExecutorTests::test_world_drains_after_task_failure() { for (std::size_t phase : {0U, 2U, 4U}) check_world_unwind(phase, false); } Test ExecutorTests::test_world_capacity_one_matches_reference() { World reference(77, 20, 20, 1, ExecutionMode::SerialReference); populate_jobs(reference); for (std::size_t workers : {2U, 6U, 12U}) { World candidate(77, 20, 20, workers, ExecutionMode::Parallel, {.max_admitted = 1}); populate_jobs(candidate); // Each candidate is paired with its own uninterrupted serial run. World serial(77, 20, 20, 1, ExecutionMode::SerialReference); populate_jobs(serial); require(bytes(serial) == bytes(reference)); for (int tick = 0; tick < 60; ++tick) { serial.step(); candidate.step(); require(bytes(candidate) == bytes(serial)); } require(candidate.jobs_completed() == 12); } } } // namespace