Integrate the Void executor and rule manifests into M01
This commit is contained in:
commit
cf0cc2f32c
10 files changed
+406
-81
No files matched your search
+9
-3
@@ -23,7 +23,7 @@ function(add_void_library)
|
||||
set(BUILD_SHARED_LIBS OFF)
|
||||
set(VOID_ENABLE_TESTING OFF)
|
||||
set(VOID_ENABLE_BENCHMARKS OFF)
|
||||
set(VOID_ENABLED_MODULES Algorithms Binary Core Crypto Data Text)
|
||||
set(VOID_ENABLED_MODULES Algorithms Async Binary Core Crypto Data Text)
|
||||
set(CMAKE_DISABLE_FIND_PACKAGE_OpenSSL ON)
|
||||
if(BUILD_TESTING)
|
||||
list(APPEND VOID_ENABLED_MODULES Testing)
|
||||
@@ -53,7 +53,7 @@ target_include_directories(settlement_core
|
||||
|
||||
target_compile_features(settlement_core PUBLIC cxx_std_23)
|
||||
target_link_libraries(settlement_core
|
||||
PUBLIC Threads::Threads
|
||||
PUBLIC Threads::Threads Void::Async
|
||||
PRIVATE Void::Algorithms Void::Binary Void::Core Void::Crypto Void::Data Void::Text
|
||||
)
|
||||
|
||||
@@ -106,7 +106,13 @@ else()
|
||||
endif()
|
||||
|
||||
if(BUILD_TESTING)
|
||||
add_executable(settlement_core_tests tests/core_tests.cpp tests/replay_tests.cpp tests/rules_tests.cpp tests/test_main.cpp)
|
||||
add_executable(settlement_core_tests
|
||||
tests/core_tests.cpp
|
||||
tests/executor_tests.cpp
|
||||
tests/replay_tests.cpp
|
||||
tests/rules_tests.cpp
|
||||
tests/test_main.cpp
|
||||
)
|
||||
target_link_libraries(settlement_core_tests PRIVATE settlement_core Void::Testing)
|
||||
add_test(NAME settlement_core_tests COMMAND settlement_core_tests)
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
# Adopt the pinned Void executor and drain each simulation batch
|
||||
|
||||
Task ID: S01-02
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive worktree /home/faumaray/Projects/stoneheart_at_home-worktrees/s01, system/s01-simulation at 8d2870a. Main working directory belongs to another task. Serial+replay passed at 8d2870a. Precise M01-R/R2 upstream pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792. M01-F2 approved below failure tests.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Replace the homegrown WorkerPool thread/queue implementation with pinned Void::Async::ThreadExecutor + FuturePool. Preserve existing World parallel and serial outcomes, guarantee lifetime of all admitted batch tasks across exceptions, and demonstrate useful-work/latency effects.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Scope S01 executor migration only. No UI, scheduler, S15 persistence or gameplay redesign. Keep public submit(std callable)->std::future<Result> and thread_count() compatibility where useful; small game-specific pressure/fault seams allowed for real observations.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect engine/include/settlement/core/worker_pool.hpp, engine/src/{worker_pool,world}.cpp three submissions, engine/include/settlement/core/world.hpp, tests/replay_tests.cpp, benchmarks/colony.cpp, docs/plan/void-library.md. Upstream headers and tests pinned in /tmp/stoneheart-verify.KoZwE4o8/candidate/_deps/void_library-src.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/src/world_save.cpp; tests/replay_tests.cpp; engine/include/settlement/core/worker_pool.hpp; engine/src/worker_pool.cpp; engine/src/world.cpp; engine/include/settlement/core/world.hpp; tests/executor_tests.cpp; CMakeLists.txt
|
||||
Not alone. All writes only to named branch/worktree using explicit workdir or absolute paths. Other systems have separate checkouts, root merges CMake. No change of shared Serena project, Git commits or branch switches.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Use Void::Async::ThreadExecutor::create/start and FuturePool::try_submit. Preserve original count>=2 for legacy pool and zero pool in serial. Choose explicit non-dropping policy for overloaded work (e.g. synchronous invoke/future of untouched callable); stopped/error distinguishable. Use per-batch lifetime guard or equivalent that waits ALL accepted work before locals unwind for later submit/first-future exception, reserve storage before submissions. Keep stable result order, avoid extra tasks in serial and stop/join exactly once. Verify startup/queue exceptions against actual API, zero duplicate result. The public Async usage requirements must reach consumers whose headers include Void. Only add module Async and necessary transitive closure.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Existing worker adapter remains game-owned translator of Void contract. NEW test fault/pressure settings should be minimal, e.g. create worker with capacity 1 and a start hook; preserve ordinary defaults. Determine actual original exception type/semantics and deterministic error behavior. Reject waiting on the same worker's own execution. Provide runner-exercised integration proof for World using migrated adapter.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root owns authoritative runtime and remote issue filings; use supported pinned executor, no new generic thread pool. Initial core/replay state 33 core +4 LAN. New tests are in existing core suite and tagged executor. Compile in your own system worktree.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Required failures: capacity saturation with retained move-only callable, propagation of callable exception, start failing after a thread already launched, destroyed pool drains admitted work, capture lifetime survives later admission/future exceptions. Avoid polling sleeps in concurrency tests; use promises/latches/barriers with bounded waits. No OS-specific perf assertions.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. All old and replay tests pass. 2. Fault/pressure/drain tests prove no lost work or surviving task at unwind, including world/batch paths. 3. Small/larger existing colony benchmark runs with a fixed seed compare before/after completed work and timings, clearly labeled Wine (historical native times only contextual). 4. Include any observed regression or residual failure boundary; preserve old path as historical baseline.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/executor-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Select --tag executor and --tag replay under Wine. Use 50/500 residents 6 workers with existing benchmark.exe for measured comparisons against /tmp/stoneheart-milestones.xprJ2SVp/windows/settlement_colony_benchmark.exe; report work and 32 warmup/240 measured if used.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Stop if pin backend cannot build or semantics contradict contract, report distinguishing probe. After two failed repair cycles send both results to root. No unauthorized remote actions, shared checkout edits or child agents.
|
||||
|
||||
Additional integration check approved by root: append defaulted WorkerPoolOptions to read_save, forward to the constructed world, and exercise the existing command/reload fixture under capacity one (tests/replay_tests.cpp). Preserve original replay coverage and the save format.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User approved full plan and branch-per-system development. Strong implementation owner assigned for high-risk cross-thread failure/critical path. Root integrates and pushes after review.
|
||||
|
||||
## 14. Return format
|
||||
Return S01-02 status, actual API/files, failure semantics and lifecycle checks, build/test and benchmark results with commands and baseline, residual risks and integration implications.
|
||||
@@ -59,6 +59,10 @@
|
||||
|
||||
## Приёмка
|
||||
|
||||
На ветке `system/s01-simulation` три параллельные стадии мира используют закреплённые `Void::Async::ThreadExecutor` и `FuturePool`. При заполнении лимита координатор выполняет задание сам. Стадия дожидается ранее принятых заданий и при исключении. Последовательный эталон вызывает те же игровые операции. На журнале из 750 тактов канонические сохранения после каждого такта совпали у эталона и вариантов с 2, 6 и 12 потоками, в том числе при лимите одного задания и после загрузки в процессе переноски. [Исполнитель](../../../engine/include/settlement/core/worker_pool.hpp) · [Проверки отказов](../../../tests/executor_tests.cpp) · [Воспроизведение](../../../tests/replay_tests.cpp)
|
||||
|
||||
В Windows x64-сборках под Wine при шести потоках медиана измерений p95 такта при переходе на Void изменилась с 86 до 96 мкс для 50 жителей и с 407 до 333 мкс для 500. Нативные замеры Windows, неизменяемая публикация завершённого такта и восстановление после ошибки остаются отдельными проверками.
|
||||
|
||||
- Сравнить хеш каждого такта на последовательном эталоне и 2/6/12 потоках, включая одинаковые команды и сохранение внутри стройки.
|
||||
- Задержать выбранные задачи, завершить их в обратном порядке, отменить мир во время расчёта. Новое поколение принимает только свои результаты.
|
||||
- Инъецировать ошибку в середину стадии. Опубликованное состояние остаётся последним завершённым тактом, предметы и резервы согласованы.
|
||||
|
||||
@@ -1,55 +1,78 @@
|
||||
#pragma once
|
||||
|
||||
#include <condition_variable>
|
||||
#include <Void/Async/FuturePool.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <exception>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace settlement {
|
||||
|
||||
// Limits and optional fault hooks are execution settings and are never saved.
|
||||
// Hooks use zero-based worker/submission indices and may throw. Execution
|
||||
// hooks can run concurrently on workers or on the coordinator during overload.
|
||||
struct WorkerPoolOptions {
|
||||
std::size_t max_admitted = 4096;
|
||||
std::function<void(std::size_t)> before_worker_start;
|
||||
std::function<void(std::size_t)> before_submit;
|
||||
std::function<void(std::size_t)> before_execute;
|
||||
};
|
||||
|
||||
class WorkerPool {
|
||||
public:
|
||||
explicit WorkerPool(std::size_t thread_count);
|
||||
explicit WorkerPool(std::size_t thread_count, WorkerPoolOptions options = {});
|
||||
~WorkerPool();
|
||||
|
||||
WorkerPool(const WorkerPool&) = delete;
|
||||
WorkerPool& operator=(const WorkerPool&) = delete;
|
||||
|
||||
// World submits from its coordinator. Nested submission from a worker is
|
||||
// rejected before admission, preventing a worker from waiting on its own pool.
|
||||
template <typename Function>
|
||||
auto submit(Function&& function) -> std::future<std::invoke_result_t<Function>> {
|
||||
using Result = std::invoke_result_t<Function>;
|
||||
auto task = std::make_shared<std::packaged_task<Result()>>(std::forward<Function>(function));
|
||||
std::future<Result> result = task->get_future();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (stopping_) {
|
||||
throw std::runtime_error("cannot submit work to a stopped worker pool");
|
||||
}
|
||||
tasks_.emplace([task]() { (*task)(); });
|
||||
if (executor_->is_executor_thread()) {
|
||||
throw std::logic_error("cannot submit nested work to the same worker pool");
|
||||
}
|
||||
work_available_.notify_one();
|
||||
return result;
|
||||
if (options_.before_submit || options_.before_execute) {
|
||||
const auto index = submission_index_.fetch_add(1, std::memory_order_relaxed);
|
||||
if (options_.before_submit) options_.before_submit(index);
|
||||
return admit([this, index, function = std::forward<Function>(function)]() mutable -> decltype(auto) {
|
||||
if (options_.before_execute) options_.before_execute(index);
|
||||
return std::invoke(function);
|
||||
});
|
||||
}
|
||||
return admit(std::forward<Function>(function));
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t thread_count() const noexcept;
|
||||
|
||||
private:
|
||||
void worker_loop();
|
||||
template <typename Function>
|
||||
auto admit(Function&& function) -> std::future<std::invoke_result_t<Function>> {
|
||||
auto submitted = futures_.try_submit(std::forward<Function>(function));
|
||||
if (submitted) return std::move(*submitted);
|
||||
if (submitted.error() != Void::Async::AdmissionError::overloaded) {
|
||||
throw std::runtime_error("cannot submit work to a stopped worker pool");
|
||||
}
|
||||
// Failed admission leaves the callable untouched. Running it on the
|
||||
// coordinator retains the same logical work and stores exceptions in its future.
|
||||
using Result = std::invoke_result_t<Function>;
|
||||
std::packaged_task<Result()> task(std::forward<Function>(function));
|
||||
auto result = task.get_future();
|
||||
task();
|
||||
return result;
|
||||
}
|
||||
|
||||
std::vector<std::thread> workers_;
|
||||
std::queue<std::function<void()>> tasks_;
|
||||
std::mutex mutex_;
|
||||
std::condition_variable work_available_;
|
||||
bool stopping_ = false;
|
||||
std::size_t thread_count_;
|
||||
WorkerPoolOptions options_;
|
||||
std::atomic<std::size_t> submission_index_{0};
|
||||
std::unique_ptr<Void::Async::ThreadExecutor> executor_;
|
||||
Void::Async::FuturePool futures_;
|
||||
};
|
||||
|
||||
} // namespace settlement
|
||||
@@ -349,7 +349,8 @@ class World {
|
||||
public:
|
||||
// SerialReference uses one logical worker and executes on the calling thread.
|
||||
World(std::uint64_t seed, std::int32_t width, std::int32_t height,
|
||||
std::size_t workers = min_worker_count, ExecutionMode mode = ExecutionMode::Parallel);
|
||||
std::size_t workers = min_worker_count, ExecutionMode mode = ExecutionMode::Parallel,
|
||||
WorkerPoolOptions worker_options = {});
|
||||
|
||||
void set_blocked(GridPosition position, bool blocked = true);
|
||||
[[nodiscard]] bool is_walkable(GridPosition position) const noexcept;
|
||||
@@ -388,7 +389,8 @@ public:
|
||||
void write_svg(const std::string& path) const;
|
||||
void write_save(std::ostream& stream) const;
|
||||
[[nodiscard]] static std::unique_ptr<World> read_save(
|
||||
std::istream& stream, std::size_t workers = min_worker_count, ExecutionMode mode = ExecutionMode::Parallel);
|
||||
std::istream& stream, std::size_t workers = min_worker_count, ExecutionMode mode = ExecutionMode::Parallel,
|
||||
WorkerPoolOptions worker_options = {});
|
||||
|
||||
[[nodiscard]] std::uint64_t tick() const noexcept;
|
||||
[[nodiscard]] std::uint64_t seed() const noexcept;
|
||||
@@ -449,6 +451,7 @@ private:
|
||||
std::int32_t height_;
|
||||
std::size_t worker_count_;
|
||||
ExecutionMode execution_mode_;
|
||||
WorkerPoolOptions worker_options_;
|
||||
std::unique_ptr<WorkerPool> worker_pool_;
|
||||
AgentId next_agent_id_ = 1;
|
||||
JobId next_job_id_ = 1;
|
||||
|
||||
+29
-40
@@ -3,54 +3,43 @@
|
||||
#include <stdexcept>
|
||||
|
||||
namespace settlement {
|
||||
namespace {
|
||||
|
||||
WorkerPool::WorkerPool(std::size_t thread_count) {
|
||||
std::unique_ptr<Void::Async::ThreadExecutor> start_executor(
|
||||
std::size_t thread_count, const WorkerPoolOptions& options) {
|
||||
if (thread_count < 2) {
|
||||
throw std::invalid_argument("worker pool needs at least two threads");
|
||||
}
|
||||
workers_.reserve(thread_count);
|
||||
try {
|
||||
for (std::size_t index = 0; index < thread_count; ++index) {
|
||||
workers_.emplace_back([this] { worker_loop(); });
|
||||
}
|
||||
} catch (...) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
stopping_ = true;
|
||||
}
|
||||
work_available_.notify_all();
|
||||
for (std::thread& worker : workers_) {
|
||||
if (worker.joinable()) worker.join();
|
||||
}
|
||||
throw;
|
||||
if (options.max_admitted == 0) {
|
||||
throw std::invalid_argument("worker pool capacity must be positive");
|
||||
}
|
||||
Void::Async::ThreadExecutorOptions settings;
|
||||
settings.workers = thread_count;
|
||||
settings.max_admitted = options.max_admitted;
|
||||
if (options.before_worker_start) {
|
||||
settings.before_worker_start = [hook = options.before_worker_start](std::size_t index)
|
||||
-> Void::Result::Result<void> {
|
||||
hook(index);
|
||||
return {};
|
||||
};
|
||||
}
|
||||
auto executor = Void::Async::ThreadExecutor::create(std::move(settings));
|
||||
if (!executor) throw std::runtime_error(executor.error().message());
|
||||
const auto started = (*executor)->start();
|
||||
if (!started) throw std::runtime_error(started.error().message());
|
||||
return std::move(*executor);
|
||||
}
|
||||
|
||||
WorkerPool::~WorkerPool() {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
stopping_ = true;
|
||||
}
|
||||
work_available_.notify_all();
|
||||
for (std::thread& worker : workers_) {
|
||||
if (worker.joinable()) worker.join();
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::size_t WorkerPool::thread_count() const noexcept { return workers_.size(); }
|
||||
WorkerPool::WorkerPool(std::size_t thread_count, WorkerPoolOptions options)
|
||||
: thread_count_(thread_count), options_(std::move(options)),
|
||||
executor_(start_executor(thread_count, options_)), futures_(*executor_) {}
|
||||
|
||||
void WorkerPool::worker_loop() {
|
||||
for (;;) {
|
||||
std::function<void()> task;
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
work_available_.wait(lock, [this] { return stopping_ || !tasks_.empty(); });
|
||||
if (stopping_ && tasks_.empty()) return;
|
||||
task = std::move(tasks_.front());
|
||||
tasks_.pop();
|
||||
}
|
||||
task();
|
||||
}
|
||||
}
|
||||
// ThreadExecutor's destructor closes admission and joins every accepted task.
|
||||
// options_ outlives that join so fault-hook captures remain valid through shutdown.
|
||||
WorkerPool::~WorkerPool() = default;
|
||||
|
||||
std::size_t WorkerPool::thread_count() const noexcept { return thread_count_; }
|
||||
|
||||
} // namespace settlement
|
||||
+20
-2
@@ -1,5 +1,7 @@
|
||||
#include "settlement/core/world.hpp"
|
||||
|
||||
#include <Void/Core/Scope.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cassert>
|
||||
@@ -279,12 +281,13 @@ void Storage::add_item(ItemType type) {
|
||||
}
|
||||
|
||||
World::World(std::uint64_t seed, std::int32_t width, std::int32_t height,
|
||||
std::size_t workers, ExecutionMode mode)
|
||||
std::size_t workers, ExecutionMode mode, WorkerPoolOptions worker_options)
|
||||
: seed_(seed),
|
||||
width_(width),
|
||||
height_(height),
|
||||
worker_count_(checked_worker_count(workers, mode)),
|
||||
execution_mode_(mode),
|
||||
worker_options_(std::move(worker_options)),
|
||||
blocked_(checked_cell_count(width, height), 0) {}
|
||||
|
||||
std::size_t World::cell_index(GridPosition position) const noexcept {
|
||||
@@ -1078,6 +1081,11 @@ void World::assign_idle_agents() {
|
||||
} else {
|
||||
std::vector<std::future<std::vector<std::size_t>>> choice_futures;
|
||||
choice_futures.reserve(chunk_count);
|
||||
const auto drain_choices = Void::Scope::on_exit([&choice_futures] {
|
||||
for (auto& future : choice_futures) {
|
||||
if (future.valid()) future.wait();
|
||||
}
|
||||
});
|
||||
for (std::size_t chunk = 0; chunk < chunk_count; ++chunk) {
|
||||
const std::size_t begin = chunk_start(chunk);
|
||||
const std::size_t end = chunk_start(chunk + 1);
|
||||
@@ -1104,6 +1112,11 @@ void World::assign_idle_agents() {
|
||||
if (requests.empty()) return;
|
||||
|
||||
std::vector<std::future<PathResult>> futures;
|
||||
const auto drain_paths = Void::Scope::on_exit([&futures] {
|
||||
for (auto& future : futures) {
|
||||
if (future.valid()) future.wait();
|
||||
}
|
||||
});
|
||||
if (execution_mode_ == ExecutionMode::Parallel) {
|
||||
futures.reserve(requests.size());
|
||||
for (const Request& request : requests) {
|
||||
@@ -1584,7 +1597,7 @@ void World::grow_sites() {
|
||||
void World::step(TickProfile* profile) {
|
||||
if (paused_) return;
|
||||
if (execution_mode_ == ExecutionMode::Parallel && !worker_pool_ && !agents_.empty()) {
|
||||
worker_pool_ = std::make_unique<WorkerPool>(worker_count_);
|
||||
worker_pool_ = std::make_unique<WorkerPool>(worker_count_, worker_options_);
|
||||
}
|
||||
using Clock = std::chrono::steady_clock;
|
||||
auto phase_start = profile ? Clock::now() : Clock::time_point{};
|
||||
@@ -1662,6 +1675,11 @@ void World::step(TickProfile* profile) {
|
||||
const auto chunk_count = std::min(worker_count_, agents_.size());
|
||||
std::vector<std::future<std::uint64_t>> futures;
|
||||
futures.reserve(chunk_count);
|
||||
const auto drain_advancement = Void::Scope::on_exit([&futures] {
|
||||
for (auto& future : futures) {
|
||||
if (future.valid()) future.wait();
|
||||
}
|
||||
});
|
||||
for (std::size_t chunk = 0; chunk < chunk_count; ++chunk) {
|
||||
const std::size_t begin = chunk * agents_.size() / chunk_count;
|
||||
const std::size_t end = (chunk + 1) * agents_.size() / chunk_count;
|
||||
|
||||
@@ -609,7 +609,8 @@ void World::write_save(std::ostream& stream) const {
|
||||
WorldSaveCodec::body(archive, *this, save_version);
|
||||
}
|
||||
|
||||
std::unique_ptr<World> World::read_save(std::istream& stream, std::size_t workers, ExecutionMode mode) {
|
||||
std::unique_ptr<World> World::read_save(std::istream& stream, std::size_t workers, ExecutionMode mode,
|
||||
WorkerPoolOptions worker_options) {
|
||||
SaveReader archive(stream);
|
||||
for (char letter : signature) {
|
||||
char actual = 0;
|
||||
@@ -626,7 +627,7 @@ std::unique_ptr<World> World::read_save(std::istream& stream, std::size_t worker
|
||||
archive.field(seed);
|
||||
archive.field(width);
|
||||
archive.field(height);
|
||||
auto world = std::make_unique<World>(seed, width, height, workers, mode);
|
||||
auto world = std::make_unique<World>(seed, width, height, workers, mode, std::move(worker_options));
|
||||
WorldSaveCodec::body(archive, *world, version);
|
||||
archive.finish();
|
||||
if (version < 5) {
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
#include "settlement/core/world.hpp"
|
||||
|
||||
#include <Void/Core/Scope.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
|
||||
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<void>(world.spawn_agent({1 + i % 3, 1 + i / 3}));
|
||||
static_cast<void>(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<void> blocked;
|
||||
auto entered = blocked.get_future();
|
||||
std::promise<void> release;
|
||||
auto permit = release.get_future().share();
|
||||
std::atomic<bool> 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<void>(world.spawn_agent({1, 1}));
|
||||
static_cast<void>(world.spawn_agent({1, 2}));
|
||||
// Distinct nearest goals avoid a second arbitration batch before paths.
|
||||
static_cast<void>(world.add_job({5, 1}, 3));
|
||||
static_cast<void>(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<ExecutorTests> {
|
||||
[[= 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();
|
||||
};
|
||||
|
||||
Test ExecutorTests::test_limits_and_nested_submission() {
|
||||
expect_throw<std::invalid_argument>([] { WorkerPool pool(1); });
|
||||
expect_throw<std::invalid_argument>([] { 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<std::logic_error>([&] { static_cast<void>(nested.get()); });
|
||||
require(pool.submit([] { return 9; }).get() == 9);
|
||||
}
|
||||
|
||||
Test ExecutorTests::test_capacity_retains_move_only_work_and_exceptions() {
|
||||
std::promise<void> running;
|
||||
auto entered = running.get_future();
|
||||
std::promise<void> 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<int> executions{0};
|
||||
auto answer = pool.submit([value = std::make_unique<int>(17), coordinator, &executions] {
|
||||
require(std::this_thread::get_id() == coordinator);
|
||||
++executions;
|
||||
return *value;
|
||||
});
|
||||
require(answer.get() == 17 && executions.load() == 1);
|
||||
auto failed = pool.submit([]() -> int { throw std::runtime_error("inline failure"); });
|
||||
expect_throw<std::runtime_error>([&] { static_cast<void>(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<std::runtime_error>([&] { 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<std::bad_alloc>([&] { static_cast<void>(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<std::runtime_error>([&] { 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<void> running;
|
||||
auto entered = running.get_future();
|
||||
std::promise<void> release;
|
||||
auto permit = release.get_future().share();
|
||||
std::atomic<int> completed{0};
|
||||
auto pool = std::make_unique<WorkerPool>(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<void> 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
|
||||
+20
-8
@@ -42,9 +42,10 @@ std::string saved_state(const World& world) {
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
std::unique_ptr<World> load_state(const std::string& bytes, ExecutionConfig config) {
|
||||
std::unique_ptr<World> load_state(const std::string& bytes, ExecutionConfig config,
|
||||
WorkerPoolOptions options = {}) {
|
||||
std::istringstream stream(bytes, std::ios::binary);
|
||||
auto world = World::read_save(stream, config.workers, config.mode);
|
||||
auto world = World::read_save(stream, config.workers, config.mode, std::move(options));
|
||||
require(world->worker_count() == config.workers, "load changed the requested worker count");
|
||||
return world;
|
||||
}
|
||||
@@ -53,12 +54,13 @@ std::unique_ptr<World> load_state(const std::string& bytes, ExecutionConfig conf
|
||||
// checkpoint copies are added, so reload is checked against uninterrupted work.
|
||||
class ReplayWorlds {
|
||||
public:
|
||||
explicit ReplayWorlds(const World& initial) {
|
||||
explicit ReplayWorlds(const World& initial, std::size_t capacity = 4096)
|
||||
: options_{.max_admitted = capacity} {
|
||||
const auto bytes = saved_state(initial);
|
||||
reference = load_state(bytes, execution_configs.front());
|
||||
reference = load_state(bytes, execution_configs.front(), options_);
|
||||
require(saved_state(*reference) == bytes, "loading changed the starting fixture");
|
||||
for (std::size_t i = 1; i < execution_configs.size(); ++i) {
|
||||
runs_.push_back({execution_configs[i], false, load_state(bytes, execution_configs[i])});
|
||||
runs_.push_back({execution_configs[i], false, load_state(bytes, execution_configs[i], options_)});
|
||||
}
|
||||
compare();
|
||||
}
|
||||
@@ -85,7 +87,7 @@ public:
|
||||
void checkpoint() {
|
||||
const auto bytes = saved_state(*reference);
|
||||
for (auto config : execution_configs) {
|
||||
runs_.push_back({config, true, load_state(bytes, config)});
|
||||
runs_.push_back({config, true, load_state(bytes, config, options_)});
|
||||
}
|
||||
compare();
|
||||
}
|
||||
@@ -117,6 +119,7 @@ private:
|
||||
}
|
||||
}
|
||||
|
||||
WorkerPoolOptions options_;
|
||||
std::vector<Run> runs_;
|
||||
};
|
||||
|
||||
@@ -125,6 +128,7 @@ struct [[= Void::Testing::name("ReplayTests")]] ReplayTests : Void::Testing::Sui
|
||||
[[= Void::Testing::tag("replay")]] Test test_one_resident_completes_work();
|
||||
[[= Void::Testing::tag("replay")]] Test test_competing_jobs_retry_unreachable_routes();
|
||||
[[= Void::Testing::tag("replay")]] Test test_recorded_colony_commands_and_loaded_delivery();
|
||||
[[= Void::Testing::tag("replay")]] Test test_recorded_colony_at_capacity_one();
|
||||
[[= Void::Testing::tag("replay")]] Test test_last_meal_has_one_winner_and_one_consumer();
|
||||
};
|
||||
|
||||
@@ -199,9 +203,9 @@ Test ReplayTests::test_competing_jobs_retry_unreachable_routes() {
|
||||
"the completed count hid an unfinished reachable job");
|
||||
}
|
||||
|
||||
Test ReplayTests::test_recorded_colony_commands_and_loaded_delivery() {
|
||||
void replay_colony_journal(std::size_t capacity) {
|
||||
const auto initial = make_first_colony(2);
|
||||
ReplayWorlds replay(*initial);
|
||||
ReplayWorlds replay(*initial, capacity);
|
||||
struct RecordedCommand {
|
||||
int attempt;
|
||||
PlayerCommand command;
|
||||
@@ -263,6 +267,14 @@ Test ReplayTests::test_recorded_colony_commands_and_loaded_delivery() {
|
||||
"rejected commands changed player sequence progress");
|
||||
}
|
||||
|
||||
Test ReplayTests::test_recorded_colony_commands_and_loaded_delivery() {
|
||||
replay_colony_journal(4096);
|
||||
}
|
||||
|
||||
Test ReplayTests::test_recorded_colony_at_capacity_one() {
|
||||
replay_colony_journal(1);
|
||||
}
|
||||
|
||||
Test ReplayTests::test_last_meal_has_one_winner_and_one_consumer() {
|
||||
World initial(97, 8, 8);
|
||||
const auto pantry = initial.add_storage({1, 1}, 1, StorageKind::Pantry);
|
||||
|
||||
Reference in new issue
Block a user