From a0638946375b9d88a41e9ca4692ce2a4db906028 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Wed, 2 Dec 2026 22:04:58 +0300 Subject: [PATCH] Prepare bounded checkpoint reads and immutable saves off the client thread --- CMakeLists.txt | 2 + docs/agent-workflow/tasks/S15-03.md | 48 +++ docs/plan/systems/S15.md | 6 + engine/include/settlement/core/checkpoint.hpp | 1 + .../settlement/core/checkpoint_files.hpp | 77 ++++ engine/src/checkpoint.cpp | 5 +- engine/src/checkpoint_files.cpp | 248 +++++++++++++ tests/checkpoint_file_tests.cpp | 347 ++++++++++++++++++ 8 files changed, 731 insertions(+), 3 deletions(-) create mode 100644 docs/agent-workflow/tasks/S15-03.md create mode 100644 engine/include/settlement/core/checkpoint_files.hpp create mode 100644 engine/src/checkpoint_files.cpp create mode 100644 tests/checkpoint_file_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 258f3ee..9bdd4e9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -40,6 +40,7 @@ find_package(Threads REQUIRED) add_library(settlement_core engine/src/checkpoint.cpp + engine/src/checkpoint_files.cpp engine/src/command_dispatcher.cpp engine/src/first_colony.cpp engine/src/rules_manifest.cpp @@ -112,6 +113,7 @@ endif() if(BUILD_TESTING) add_executable(settlement_core_tests tests/checkpoint_tests.cpp + tests/checkpoint_file_tests.cpp tests/core_tests.cpp tests/executor_tests.cpp tests/replay_tests.cpp diff --git a/docs/agent-workflow/tasks/S15-03.md b/docs/agent-workflow/tasks/S15-03.md new file mode 100644 index 0000000..fe4cdd7 --- /dev/null +++ b/docs/agent-workflow/tasks/S15-03.md @@ -0,0 +1,48 @@ +# Prepare checkpoint files in the background for the interactive client + +Task ID: S15-03 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +Exclusive s15 checkout /home/faumaray/Projects/stoneheart_at_home-worktrees/s15 system/s15-persistence fast-forwarded to 8c4c1fe. Includes verified runtime PublishedSnapshot, S15 checkpoint and SaveService + builtins. M01-F4 accepted bounded background file adapter; #3 is the linked Windows atomic-write contract. + +## 2. Objective and deliverables +Supply a usable persistence adapter for the real window: submit save of a held PublishedSnapshot, prepare a modern or legacy file asynchronously into a complete WorldCheckpoint; no disk or parsing on UI/owner thread. + +## 3. Scope and non-goals +Only S15 file API/implementation and test/docs/target integration. Viewer itself and its load-ticket/feedback lifecycle are owned separately. Existing SaveService handles writes; existing World/checkpoint codecs handle validation. + +## 4. Files to inspect +Inspect actual simulation_runtime.hpp (PublishedSnapshot immutable), checkpoint.hpp/.cpp, save_service.hpp/.cpp, rules_manifest.hpp/.cpp, world_save.cpp signature/limits/validation, viewer current dialog/select and file handling. Review Void Async ThreadExecutor/FuturePool lifetime/admission tests and pinned Windows IO coverage. M01-V6 requires max_checkpoint_bytes. + +## 5. Write ownership and coordination +Write scope: engine/include/settlement/core/checkpoint_files.hpp; engine/src/checkpoint_files.cpp; tests/checkpoint_file_tests.cpp; CMakeLists.txt; docs/plan/systems/S15.md; engine/include/settlement/core/checkpoint.hpp and engine/src/checkpoint.cpp only if needed to expose canonical signature recognition +No changes to other worktrees/Git/Serena/Win32 UI. You are not alone; other workers own runtime, LAN, UI, World/custody. Parent integrates CMake. + +## 6. Implementation or investigation approach +Introduce NEW CheckpointFiles owning one existing SaveService configured max_checkpoint_bytes and a bounded pinned Void reader executor/FuturePool. try_save(absolute path, shared_ptr) delegates to existing queue, producer owns const world/manifest and runs encode_checkpoint on writer. Caller acquired healthy snapshot already. try_load(absolute path,... immutable installed catalog, workers/mode) returns immediately with explicit admission and accepted future/typed diagnostic or complete candidate. Provide useful error for file access, limits, legacy decode, missing package etc. For modern signature call decode_checkpoint only, never downgrade after a modern failure. For legacy signature parse validated World::read_save and attach fresh stable nonnil UUID, city1, default supported manifest. Preserve exact prior old v1–13 paths; don't invent a mutable live session. Open each path once, enforce maximum read incl growth/EOF before consuming unbounded storage. Reader/writer can run independently; hold input/catalog through work, drain on shutdown. + +## 7. Interfaces and data contracts +Communicate exact header early. Constructor may own shared immutable installed catalog (default builtins) to simplify caller. Caller keeps this service for window lifetime across runtime resets; jobs never capture viewer/raw runtime or call GUI. Return SaveSubmission or precise adapter result preserving prior SaveService metadata. Reader producer can use an optional bounded observer/gate for deterministic tests following existing failure hooks if needed. No thread per file; explicit bounds & stable closed admission. Busy or invalid admission does not consume caller data. Viewer handles begin_load tickets/replacement policy, reporting and 32×32 restriction. + +## 8. Dependencies and integration +Root wires UI later, receives filled result and verifies dimensions before SimulationRuntime::try_install; runtime itself rechecks epoch/ticket. Old valid file import gets a fresh stable ID on each explicit import. Default `.settlement` existing extension and title paths maintained. Store upstream #3 link where relevant; pinned Void supports asynchronous running and file codecs as documented. No external actions. + +## 9. Edge cases security and performance +Check Unicode filesystem path, open-one/read-one with changing files, oversized declared/actual data (bound including growth), corruption/trailing/truncation distinctly, catalog mismatch names missing package, nil UUID generator error, concurrent submit/shutdown/read queue/in-flight count, writer retains held snapshot after source advances. Avoid throwing from worker leaving pending futures. No double-opening for format detection, no fallback rewriting files. Track native/Wine differences. + +## 10. Acceptance criteria +1. Roundtrip actual immutable old snapshot through production save helper to file then load to independent candidate; live world progresses meanwhile. 2. Open true legacy fixtures and modern mismatches; invalid/oversized/trailing/frame corruption rejects. 3. Bounded and closed reader, deterministic held reader blocking test shows UI submit and writes/other work independent, shutdown drains, next read succeeds after bad file. 4. Normal cross build and old suites pass. 5. Frozen interface is usable for viewer async polls without lifetime hazards. + +## 11. Verification commands and evidence +Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/file-adapter-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 --parallel 6, run ctest --test-dir --output-on-failure and your targeted tests. Evidence required. Run wine /settlement_core_tests.exe --tag checkpoint-file, full verbose CTest, git diff --check; files in new temporary Windows directories. Name logs file-adapter-*. + +## 12. Constraints and stop conditions +No editing viewer/custody, raw live World access from workers, remotely written actions or new external deps. If architecture requires a new generic capability report it to root. Two failed fixes for the same issue require escalation. + +## 13. Authorization and decisions +Root owns all Git; user approved roadmap and asked maintain PR/cumulative/issue tracking. F3/F4 and V6 freeze acceptance; Windows physical tests follow separately. + +## 14. Return format +Return S15-03 READY/BLOCKED, early concrete signatures for viewer, owned paths, complete tests/observations and limitations. No children/commits/push. diff --git a/docs/plan/systems/S15.md b/docs/plan/systems/S15.md index 00708c5..e755647 100644 --- a/docs/plan/systems/S15.md +++ b/docs/plan/systems/S15.md @@ -25,6 +25,12 @@ ## Границы интерфейсов +`CheckpointFiles` обслуживает файлы вне потока окна. `try_save` удерживает опубликованный снимок и передаёт формирование контрольной точки единственному писателю с лимитом `max_checkpoint_bytes`. `try_load` возвращает номер запроса и future отдельного кандидата. Один ограниченный исполнитель чтения открывает файл один раз, проверяет размер и читает до конца под общим лимитом, включая рост файла после открытия. Ошибка современного формата сохраняет диагностику кодека. Импорт прежнего сохранения получает новый постоянный UUID и точный поддерживаемый набор правил из установленного каталога. [Интерфейс файлов](../../../engine/include/settlement/core/checkpoint_files.hpp) · [Проверки адаптера](../../../tests/checkpoint_file_tests.cpp) + +Служба живёт до закрытия окна и завершает принятые чтения и записи при остановке. Окно связывает подготовку с `LoadTicket`, проверяет размеры карты и передаёт кандидат владельцу симуляции. Этот же владелец сверяет инкарнацию и последний запрос перед публикацией. Сценарии `--tag checkpoint-file` проверяют удерживаемый снимок при продвижении партии, прежние версии 1/8/9/13, диагностику несовместимых правил, рост файла, переполнение очереди, независимость писателя от задержанного чтения и завершение очереди при выходе. + +Windows-адаптер чтения связан с [Void/Library #9](https://git.faumaray.com/Void/Library/issues/9). Условие перехода на библиотечную операцию — проверки чтения одним дескриптором до конца файла, путей Unicode, исходного размера и роста сверх лимита. Служба продолжает задавать ограничение приёма и владение запросом. + Контрольная точка версии 1 содержит постоянный UUID мира, город, такт, полный выбранный набор пакетов с точными версиями и SHA-256, а также состояние мира в формате 13. Декодер проверяет внешнюю контрольную сумму, заново разрешает набор правил по установленному каталогу и создаёт кандидат мира существующим проверенным загрузчиком. Клиенту доступны имя несовместимого пакета и поле ошибки. Восемь проверок под Wine охватывают переноску материалов, продолжение расчёта, перестановку каталога, обрезанные файлы, недопустимое состояние и тело размером более 16 МиБ. [Кодек контрольной точки](../../../engine/include/settlement/core/checkpoint.hpp) · [Проверки](../../../tests/checkpoint_tests.cpp) `SaveRequest`, `SaveSnapshot`, `SaveManifest` и `LoadCandidate` — предлагаемые новые интерфейсы. Запрос содержит слот и желаемую операцию. Снимок привязан к одному завершённому такту. Манифест описывает все необходимые блоки и контрольные суммы. Кандидат загрузки предоставляет результат проверки до замены мира. Завершение операции возвращает идентификатор запроса, состояние и диагностическую причину ошибки. diff --git a/engine/include/settlement/core/checkpoint.hpp b/engine/include/settlement/core/checkpoint.hpp index 98e8e5e..9d1da79 100644 --- a/engine/include/settlement/core/checkpoint.hpp +++ b/engine/include/settlement/core/checkpoint.hpp @@ -16,6 +16,7 @@ namespace settlement { inline constexpr std::uint32_t checkpoint_version = 1; +inline constexpr std::string_view checkpoint_signature = "STHCHKPT"; inline constexpr std::size_t max_checkpoint_body_bytes = 128 * 1024 * 1024; inline constexpr std::size_t max_checkpoint_metadata_bytes = 64 * 1024; inline constexpr std::size_t max_checkpoint_bytes = diff --git a/engine/include/settlement/core/checkpoint_files.hpp b/engine/include/settlement/core/checkpoint_files.hpp new file mode 100644 index 0000000..5fe71cc --- /dev/null +++ b/engine/include/settlement/core/checkpoint_files.hpp @@ -0,0 +1,77 @@ +#pragma once + +#include "settlement/core/save_service.hpp" +#include "settlement/core/simulation_runtime.hpp" + +#include +#include +#include + +namespace settlement { + +enum class CheckpointFileError { + Io, TooLarge, UnsupportedFormat, InvalidCheckpoint, InvalidLegacy, + IdentityGeneration, ResourceFailure, ReaderFailure, +}; + +struct CheckpointFileDiagnostic { + CheckpointFileError code; + std::string message; + std::uint32_t native_error = 0; + // Present for a modern codec failure, including the exact incompatible package. + std::optional checkpoint; +}; + +using CheckpointLoadResult = std::expected; +enum class CheckpointLoadAdmission { Accepted, Busy, Closed, InvalidRequest, IdExhausted }; + +struct CheckpointLoadSubmission { + CheckpointLoadAdmission admission = CheckpointLoadAdmission::InvalidRequest; + std::uint64_t request_id = 0; + std::future completion; +}; + +enum class CheckpointReadPhase { Opened, BeforeRead }; + +struct CheckpointFilesOptions { + std::size_t load_capacity = 4; // Includes the running read. + std::size_t save_capacity = 8; + std::size_t max_load_bytes = max_checkpoint_bytes; + // Diagnostic/test seam on the reader. Captures must outlive shutdown. + // Calling shutdown from this observer throws logic_error. + std::function read_observer; +}; + +// Keep one instance for the window lifetime so accepted saves retain FIFO order +// across world/session replacements. Workers own their paths, catalog and held +// snapshots. The caller owns load-ticket fencing and UI completion handling. +class CheckpointFiles { +public: + explicit CheckpointFiles(CheckpointFilesOptions options = {}); + explicit CheckpointFiles(std::vector installed, CheckpointFilesOptions options = {}); + ~CheckpointFiles(); + CheckpointFiles(const CheckpointFiles&) = delete; + CheckpointFiles& operator=(const CheckpointFiles&) = delete; + + // Obtain a healthy immutable view with SimulationRuntime::snapshot_for_save(). + // Materialization runs on the existing SaveService writer, bounded to + // max_checkpoint_bytes. Rejected calls do not retain the snapshot. + [[nodiscard]] SaveSubmission try_save( + const std::filesystem::path& destination, + const std::shared_ptr& snapshot); + // Opens once and checks actual size/EOF under the byte limit. Modern failures + // retain their diagnostics. Legacy imports receive a fresh stable world UUID + // and the exact supported default manifest from this instance's catalog. + [[nodiscard]] CheckpointLoadSubmission try_load( + const std::filesystem::path& source, std::size_t workers = min_worker_count, + ExecutionMode mode = ExecutionMode::Parallel); + // Closes admission and drains both services, without holding the admission + // mutex while joining. Destruction requires callers to stop using this object. + void shutdown(); + +private: + struct Impl; + std::unique_ptr impl_; +}; + +} // namespace settlement diff --git a/engine/src/checkpoint.cpp b/engine/src/checkpoint.cpp index 69b5155..4a4069a 100644 --- a/engine/src/checkpoint.cpp +++ b/engine/src/checkpoint.cpp @@ -16,7 +16,6 @@ namespace settlement { namespace { -constexpr std::string_view magic = "STHCHKPT"; constexpr std::size_t header_size = 24; constexpr std::size_t digest_size = 32; constexpr std::size_t fixed_metadata_size = 68; @@ -173,7 +172,7 @@ std::expected encode_checkpoint( } std::string bytes(header_size + metadata_size + body.size() + digest_size, '\0'); Void::Binary::Writer writer(std::as_writable_bytes(std::span{bytes.data(), bytes.size()})); - put_bytes(writer, wire_bytes(magic)); + put_bytes(writer, wire_bytes(checkpoint_signature)); put(writer, checkpoint_version); put(writer, static_cast(metadata_size)); put(writer, static_cast(body.size())); @@ -210,7 +209,7 @@ std::expected decode_checkpoint( fail(CheckpointError::InvalidFrame, "frame", "Checkpoint is incomplete."); } Void::Binary::Reader header(wire_bytes(bytes).first(header_size)); - if (!std::ranges::equal(get_bytes(header, magic.size(), "magic"), wire_bytes(magic))) { + if (!std::ranges::equal(get_bytes(header, checkpoint_signature.size(), "magic"), wire_bytes(checkpoint_signature))) { fail(CheckpointError::InvalidFrame, "magic", "Checkpoint signature does not match."); } if (get(header, "version") != checkpoint_version) { diff --git a/engine/src/checkpoint_files.cpp b/engine/src/checkpoint_files.cpp new file mode 100644 index 0000000..ba8870b --- /dev/null +++ b/engine/src/checkpoint_files.cpp @@ -0,0 +1,248 @@ +#include "settlement/core/checkpoint_files.hpp" + +#include +#include + +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace settlement { +namespace { + +constexpr std::string_view legacy_signature = "SETTLERS"; + +bool valid_path(const std::filesystem::path& path) { + return path.is_absolute() && !path.filename().empty() && + path.native().find(L'\0') == std::wstring::npos; +} + +std::vector default_catalog() { + auto catalog = builtin_rule_packages(); + if (!catalog) throw std::runtime_error(catalog.error().message); + return std::move(*catalog); +} + +struct OpenFile { + HANDLE handle; + ~OpenFile() { CloseHandle(handle); } +}; + +CheckpointFileDiagnostic diagnostic(CheckpointFileError code, std::string message, + std::uint32_t native_error = 0) { + return {code, std::move(message), native_error, std::nullopt}; +} + +// Void::FileSystem::read_file_bounded is unsupported on Windows at the pin. +// https://git.faumaray.com/Void/Library/issues/9 tracks this adapter's replacement. +// Reuse it after checkpoint-file tests prove one-handle reads, Unicode paths, +// initial/growing-file limits, EOF checking and independent bounded admission. +CheckpointLoadResult prepare(const std::filesystem::path& path, + std::span catalog, + const CheckpointFilesOptions& options, + std::size_t workers, ExecutionMode mode) { + try { + OpenFile file{CreateFileW(path.c_str(), GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr)}; + if (file.handle == INVALID_HANDLE_VALUE) { + return std::unexpected{diagnostic(CheckpointFileError::Io, + "Could not open the checkpoint file.", GetLastError())}; + } + LARGE_INTEGER size{}; + if (GetFileType(file.handle) != FILE_TYPE_DISK || !GetFileSizeEx(file.handle, &size)) { + return std::unexpected{diagnostic(CheckpointFileError::Io, + "Could not determine the checkpoint file size.", GetLastError())}; + } + if (size.QuadPart < 0 || + static_cast(size.QuadPart) > options.max_load_bytes) { + return std::unexpected{diagnostic(CheckpointFileError::TooLarge, + "Checkpoint file exceeds the configured byte limit.")}; + } + if (options.read_observer) options.read_observer(CheckpointReadPhase::Opened); + std::string bytes; + bytes.reserve(static_cast(size.QuadPart)); + std::array buffer; + for (;;) { + if (options.read_observer) options.read_observer(CheckpointReadPhase::BeforeRead); + DWORD count = 0; + if (!ReadFile(file.handle, buffer.data(), static_cast(buffer.size()), &count, nullptr)) { + return std::unexpected{diagnostic(CheckpointFileError::Io, + "Could not read the checkpoint file.", GetLastError())}; + } + if (count == 0) break; + if (count > options.max_load_bytes - bytes.size()) { + return std::unexpected{diagnostic(CheckpointFileError::TooLarge, + "Checkpoint file grew beyond the configured byte limit.")}; + } + bytes.append(buffer.data(), count); + } + if (bytes.starts_with(checkpoint_signature)) { + auto candidate = decode_checkpoint(bytes, catalog, workers, mode); + if (!candidate) { + CheckpointFileDiagnostic error{CheckpointFileError::InvalidCheckpoint, + candidate.error().message, 0, std::move(candidate.error())}; + return std::unexpected{std::move(error)}; + } + return std::move(*candidate); + } + if (!bytes.starts_with(legacy_signature)) { + return std::unexpected{diagnostic(CheckpointFileError::UnsupportedFormat, + "File has neither a checkpoint nor a legacy settlement signature.")}; + } + auto defaults = default_rules_manifest(); + if (!defaults) { + return std::unexpected{diagnostic(CheckpointFileError::ResourceFailure, + defaults.error().message)}; + } + std::vector selected; + selected.reserve(defaults->packages().size()); + for (const auto& package : defaults->packages()) selected.push_back(package.id); + auto installed_defaults = resolve_rules(catalog, selected); + if (!installed_defaults || *installed_defaults != *defaults) { + CheckpointDiagnostic detail{CheckpointError::RulesMismatch, "rules.packages", {}, + "Legacy imports require the exact supported default packages."}; + if (!installed_defaults) { + detail.package = installed_defaults.error().package; + detail.message = installed_defaults.error().message; + } else { + for (const auto& package : defaults->packages()) { + const auto found = std::find(installed_defaults->packages().begin(), + installed_defaults->packages().end(), package); + if (found == installed_defaults->packages().end()) { + detail.package = package.id; + break; + } + } + } + return std::unexpected{CheckpointFileDiagnostic{CheckpointFileError::InvalidCheckpoint, + detail.message, 0, std::move(detail)}}; + } + std::unique_ptr world; + try { + std::ispanstream input{std::span{bytes.data(), bytes.size()}}; + world = World::read_save(input, workers, mode); + } catch (const std::bad_alloc&) { + throw; + } catch (const std::exception& error) { + return std::unexpected{diagnostic(CheckpointFileError::InvalidLegacy, error.what())}; + } + const auto id = Void::Uuid::try_v4(); + if (!id || id->is_nil()) { + return std::unexpected{diagnostic(CheckpointFileError::IdentityGeneration, + "Could not create an identity for the imported world.")}; + } + return WorldCheckpoint{std::move(world), *id, 1, std::move(*installed_defaults)}; + } catch (const std::bad_alloc&) { + return std::unexpected{diagnostic(CheckpointFileError::ResourceFailure, "Out of memory.")}; + } catch (const std::exception& error) { + return std::unexpected{diagnostic(CheckpointFileError::ReaderFailure, error.what())}; + } catch (...) { + return std::unexpected{diagnostic(CheckpointFileError::ReaderFailure, "Checkpoint reader failed.")}; + } +} + +} // namespace + +struct CheckpointFiles::Impl { + Impl(std::vector catalog, CheckpointFilesOptions configured) + : options(std::move(configured)), installed(std::move(catalog)), + writer(SaveServiceOptions{.capacity = options.save_capacity, + .max_bytes = max_checkpoint_bytes, .fault_hook = {}}) { + if (options.load_capacity == 0 || options.max_load_bytes == 0 || + options.max_load_bytes > max_checkpoint_bytes) { + throw std::invalid_argument("checkpoint reader limits are invalid"); + } + auto created = Void::Async::ThreadExecutor::create( + {.workers = 1, .max_admitted = options.load_capacity}); + if (!created) throw std::runtime_error("cannot create checkpoint reader"); + executor = std::move(*created); + pool = std::make_unique(*executor); + if (!executor->start()) throw std::runtime_error("cannot start checkpoint reader"); + } + + CheckpointFilesOptions options; + std::vector installed; + SaveService writer; + std::unique_ptr executor; + std::unique_ptr pool; + std::mutex admission_mutex; + bool closed = false; + std::uint64_t next_id = 1; +}; + +CheckpointFiles::CheckpointFiles(CheckpointFilesOptions options) + : CheckpointFiles(default_catalog(), std::move(options)) {} + +CheckpointFiles::CheckpointFiles(std::vector installed, CheckpointFilesOptions options) + : impl_(std::make_unique(std::move(installed), std::move(options))) {} + +CheckpointFiles::~CheckpointFiles() { shutdown(); } + +SaveSubmission CheckpointFiles::try_save( + const std::filesystem::path& destination, + const std::shared_ptr& snapshot) { + std::unique_lock lock(impl_->admission_mutex, std::try_to_lock); + if (!lock.owns_lock()) return {SaveAdmission::Busy, 0, {}}; + if (impl_->closed) return {SaveAdmission::Closed, 0, {}}; + if (!snapshot || !snapshot->world || !snapshot->rules || + snapshot->identity.world.is_nil() || snapshot->identity.city == 0) { + return {SaveAdmission::InvalidRequest, 0, {}}; + } + return impl_->writer.try_submit(SaveRequest{destination, snapshot->world->tick(), + snapshot->identity.session, [snapshot] { + auto bytes = encode_checkpoint(*snapshot->world, snapshot->identity.world, + snapshot->identity.city, *snapshot->rules); + if (!bytes) throw std::runtime_error(bytes.error().message); + return std::move(*bytes); + }}); +} + +CheckpointLoadSubmission CheckpointFiles::try_load( + const std::filesystem::path& source, std::size_t workers, ExecutionMode mode) { + std::unique_lock lock(impl_->admission_mutex, std::try_to_lock); + if (!lock.owns_lock()) return {CheckpointLoadAdmission::Busy, 0, {}}; + if (impl_->closed) return {CheckpointLoadAdmission::Closed, 0, {}}; + if (impl_->executor->admitted() >= impl_->options.load_capacity) { + return {CheckpointLoadAdmission::Busy, 0, {}}; + } + if (!valid_path(source) || + (mode == ExecutionMode::Parallel && (workers < min_worker_count || workers > max_worker_count)) || + (mode != ExecutionMode::Parallel && mode != ExecutionMode::SerialReference)) { + return {CheckpointLoadAdmission::InvalidRequest, 0, {}}; + } + if (impl_->next_id == 0) return {CheckpointLoadAdmission::IdExhausted, 0, {}}; + auto future = impl_->pool->try_submit( + [state = impl_.get(), source = std::filesystem::path(source), workers, mode] { + return prepare(source, state->installed, state->options, workers, mode); + }); + if (!future) { + return {future.error() == Void::Async::AdmissionError::overloaded ? + CheckpointLoadAdmission::Busy : CheckpointLoadAdmission::Closed, 0, {}}; + } + const auto id = impl_->next_id++; + return {CheckpointLoadAdmission::Accepted, id, std::move(*future)}; +} + +void CheckpointFiles::shutdown() { + if (impl_->executor->is_executor_thread()) { + throw std::logic_error("checkpoint reader cannot join itself"); + } + { + std::lock_guard lock(impl_->admission_mutex); + impl_->closed = true; + } + static_cast(impl_->executor->join()); + impl_->writer.shutdown(); +} + +} // namespace settlement diff --git a/tests/checkpoint_file_tests.cpp b/tests/checkpoint_file_tests.cpp new file mode 100644 index 0000000..c835156 --- /dev/null +++ b/tests/checkpoint_file_tests.cpp @@ -0,0 +1,347 @@ +#include "settlement/core/checkpoint_files.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace settlement; +using namespace std::chrono_literals; +using Void::Testing::Test; + +void require(bool condition, const char* message) { + if (!condition) throw std::runtime_error(message); +} + +struct TemporaryDirectory { + std::filesystem::path path = std::filesystem::temp_directory_path() / + ("settlement-checkpoint-files-" + Void::Uuid::v4().to_string()); + TemporaryDirectory() { + require(std::filesystem::create_directory(path), "cannot create exclusive test directory"); + } + ~TemporaryDirectory() { + std::error_code error; + std::filesystem::remove_all(path, error); + } +}; + +std::string saved(const World& world) { + std::ostringstream stream(std::ios::binary); + world.write_save(stream); + return std::move(stream).str(); +} + +Void::Uuid::Uuid identity(std::uint8_t last) { + Void::Uuid::Uuid id; + id.bytes.back() = last; + return id; +} + +std::shared_ptr snapshot(const World& world) { + auto rules = default_rules_manifest(); + require(rules.has_value(), "cannot resolve fixture rules"); + return std::make_shared(PublishedSnapshot{ + {identity(1), identity(2), 7}, 1, world.capture(), + std::make_shared(std::move(*rules)), {1, 1}}); +} + +std::string encoded(const World& world) { + const auto view = snapshot(world); + auto bytes = encode_checkpoint(*view->world, view->identity.world, view->identity.city, *view->rules); + require(bytes.has_value(), "cannot encode fixture"); + return std::move(*bytes); +} + +void write(const std::filesystem::path& path, std::string_view bytes, bool append = false) { + std::ofstream file(path, std::ios::binary | (append ? std::ios::app : std::ios::trunc)); + file.write(bytes.data(), static_cast(bytes.size())); + file.close(); + require(static_cast(file), "cannot write fixture"); +} + +template +auto admitted(Submit submit) { + const auto limit = std::chrono::steady_clock::now() + 10s; + for (;;) { + auto operation = submit(); + if (operation.admission != decltype(operation.admission)::Busy) return operation; + require(std::chrono::steady_clock::now() < limit, "admission remained busy"); + std::this_thread::yield(); + } +} + +CheckpointLoadResult loaded(CheckpointLoadSubmission operation) { + require(operation.admission == CheckpointLoadAdmission::Accepted && operation.request_id != 0, + "load was not accepted"); + require(operation.completion.wait_for(10s) == std::future_status::ready, "load timed out"); + return operation.completion.get(); +} + +CheckpointLoadResult load(CheckpointFiles& files, const std::filesystem::path& path) { + return loaded(admitted([&] { return files.try_load(path, 1, ExecutionMode::SerialReference); })); +} + +SaveResult saved_file(SaveSubmission operation) { + require(operation.admission == SaveAdmission::Accepted && operation.request_id != 0, + "save was not accepted"); + require(operation.completion.wait_for(10s) == std::future_status::ready, "save timed out"); + auto result = operation.completion.get(); + require(result.request_id == operation.request_id, "save completion lost identity"); + return result; +} + +struct Gate { + std::promise entered; + std::future arrival = entered.get_future(); + std::promise released; + std::shared_future release = released.get_future().share(); + std::atomic used = false; + std::atomic opened = false; + void block_once() { + if (used.exchange(true)) return; + entered.set_value(); + require(release.wait_for(10s) == std::future_status::ready, "reader gate timed out"); + } + void await_entry() { + require(arrival.wait_for(10s) == std::future_status::ready, "reader did not reach gate"); + } + void open() { + if (!opened.exchange(true)) released.set_value(); + } +}; + +struct [[= Void::Testing::name("CheckpointFileTests")]] +CheckpointFileTests : Void::Testing::Suite { + [[= Void::Testing::tag("checkpoint-file")]] Test saves_held_snapshot_while_runtime_advances(); + [[= Void::Testing::tag("checkpoint-file")]] Test legacy_versions_import_with_fresh_identity(); + [[= Void::Testing::tag("checkpoint-file")]] Test modern_failures_retain_exact_diagnostics(); + [[= Void::Testing::tag("checkpoint-file")]] Test bounds_cover_initial_size_and_growth(); + [[= Void::Testing::tag("checkpoint-file")]] Test reader_bound_writer_progress_and_shutdown_drain(); + [[= Void::Testing::tag("checkpoint-file")]] Test failures_recover_and_invalid_admission_preserves_inputs(); + [[= Void::Testing::tag("checkpoint-file")]] Test reader_self_shutdown_is_rejected_without_closing(); +}; + +Test CheckpointFileTests::saves_held_snapshot_while_runtime_advances() { + TemporaryDirectory directory; + CheckpointFiles files; + auto rules = default_rules_manifest(); + require(rules.has_value(), "fixture rules unavailable"); + auto clock = std::make_shared(); + SimulationRuntime runtime( + {make_first_colony(2), identity(23), 1, std::move(*rules)}, {.clock = clock}); + auto healthy = runtime.snapshot_for_save(); + require(healthy.has_value(), "healthy snapshot unavailable"); + const auto old = *healthy; + const auto bytes = saved(*old->world); + const auto path = directory.path / L"Поселение_старый_снимок.settlement"; + auto saving = admitted([&] { return files.try_save(path, old); }); + require(clock->advance(1s).has_value(), "manual clock failed"); + auto fence = admitted([&] { return runtime.synchronize(); }); + require(fence.admission == RuntimeAdmission::Accepted, "runtime fence rejected"); + require(fence.completion.wait_for(10s) == std::future_status::ready, "runtime did not advance"); + require(fence.completion.get().outcome == RuntimeOutcome::Completed, "runtime fence failed"); + require(runtime.latest()->world->tick() == old->world->tick() + 20, "live world did not progress"); + const auto result = saved_file(std::move(saving)); + require(result.succeeded() && result.tick == old->world->tick() && + result.session == old->identity.session, "save metadata or publication changed"); + runtime.shutdown(); + auto restored = load(files, path); + require(restored.has_value(), "saved snapshot could not load"); + require(restored->world_id == old->identity.world && restored->city == old->identity.city && + restored->rules == *old->rules && saved(*restored->world) == bytes, + "background save read later mutable state"); +} + +Test CheckpointFileTests::legacy_versions_import_with_fresh_identity() { + TemporaryDirectory directory; + CheckpointFiles files; + World world(0x0102030405060708, 5, 5, 1, ExecutionMode::SerialReference); + const auto current = saved(world); + require(current.size() == 183, "legacy fixture layout changed"); + std::vector versions{current.substr(0, 146), current, current, current}; + versions[0][8] = 1; + versions[0].append("\x58\xc1\x77\x19\x3a\x69\xca\x2c", 8); + versions[1][8] = 8; + versions[1].append("\x33\x73\x67\x28\xa8\x53\x56\xfa", 8); + versions[2][8] = 9; + const auto rules = default_rules_manifest(); + require(rules.has_value(), "fixture default rules unavailable"); + Void::Uuid::Uuid previous; + for (const auto& version : versions) { + const auto path = directory.path / L"старое.settlement"; + write(path, version); + auto restored = load(files, path); + require(restored.has_value(), "historical fixture rejected"); + require(!restored->world_id.is_nil() && restored->world_id != previous && + restored->city == 1 && restored->rules == *rules && saved(*restored->world) == current, + "legacy import lost state or identity isolation"); + previous = restored->world_id; + } + const auto path = directory.path / "legacy-trailing.settlement"; + write(path, current + 'x'); + const auto trailing = load(files, path); + require(!trailing && trailing.error().code == CheckpointFileError::InvalidLegacy, + "legacy trailing bytes were accepted"); +} + +Test CheckpointFileTests::modern_failures_retain_exact_diagnostics() { + TemporaryDirectory directory; + CheckpointFiles files; + World world(1, 5, 5, 1, ExecutionMode::SerialReference); + const auto current = encoded(world); + const auto path = directory.path / "modern.settlement"; + for (const auto& invalid : {current.substr(0, 8), current.substr(0, current.size() - 1), current + 'x'}) { + write(path, invalid); + const auto result = load(files, path); + require(!result && result.error().code == CheckpointFileError::InvalidCheckpoint && + result.error().checkpoint.has_value() && !result.error().message.empty(), + "modern failure lost its codec diagnostic"); + } + auto unsupported = current; + unsupported[8] = 2; + write(path, unsupported); + const auto version = load(files, path); + require(!version && version.error().checkpoint && + version.error().checkpoint->code == CheckpointError::UnsupportedVersion, + "modern unsupported version was downgraded or obscured"); + write(path, current); + CheckpointFiles missing(std::vector{}); + const auto mismatch = load(missing, path); + require(!mismatch && mismatch.error().checkpoint && + mismatch.error().checkpoint->code == CheckpointError::RulesMismatch && + !mismatch.error().checkpoint->package.empty(), "missing package diagnostic was lost"); + write(path, saved(world)); + const auto legacy_mismatch = load(missing, path); + require(!legacy_mismatch && legacy_mismatch.error().checkpoint && + legacy_mismatch.error().checkpoint->code == CheckpointError::RulesMismatch, + "legacy import bound unavailable default packages"); + write(path, current); + require(load(files, path).has_value(), "reader did not recover after malformed files"); +} + +Test CheckpointFileTests::bounds_cover_initial_size_and_growth() { + TemporaryDirectory directory; + const auto path = directory.path / "oversized.settlement"; + write(path, ""); + std::filesystem::resize_file(path, max_checkpoint_bytes + 1); + CheckpointFiles files; + const auto large = load(files, path); + require(!large && large.error().code == CheckpointFileError::TooLarge, + "oversized initial file reached decoding"); + write(path, "SETTLERS"); + auto grew = std::make_shared>(false); + CheckpointFiles growing({.max_load_bytes = 512, + .read_observer = [grew, path](CheckpointReadPhase phase) { + if (phase == CheckpointReadPhase::Opened && !grew->exchange(true)) { + write(path, std::string(1024, 'x'), true); + } + }}); + const auto growth = load(growing, path); + require(!growth && growth.error().code == CheckpointFileError::TooLarge, + "growth after initial size check escaped the cap"); +} + +Test CheckpointFileTests::reader_bound_writer_progress_and_shutdown_drain() { + TemporaryDirectory directory; + World world(7, 5, 5, 1, ExecutionMode::SerialReference); + const auto path = directory.path / "read.settlement"; + write(path, encoded(world)); + World newer(8, 5, 5, 1, ExecutionMode::SerialReference); + const auto new_path = directory.path / "newer.settlement"; + write(new_path, encoded(newer)); + auto gate = std::make_shared(); + CheckpointFiles files({.load_capacity = 2, .read_observer = [gate](CheckpointReadPhase phase) { + if (phase == CheckpointReadPhase::Opened) gate->block_once(); + }}); + auto unblock = Void::Scope::on_exit([gate] { gate->open(); }); + auto first = files.try_load(path); + require(first.admission == CheckpointLoadAdmission::Accepted, "first reader rejected"); + gate->await_entry(); + auto second = files.try_load(new_path); + require(second.admission == CheckpointLoadAdmission::Accepted && second.request_id > first.request_id, + "second reader did not queue in order"); + require(files.try_load(path).admission == CheckpointLoadAdmission::Busy, + "running reader was excluded from bound"); + const auto view = snapshot(world); + require(saved_file(admitted([&] { return files.try_save(directory.path / "write.settlement", view); })).succeeded(), + "held reader blocked independent writer"); + require(first.completion.wait_for(0s) == std::future_status::timeout, "gate did not hold active read"); + auto stopping = std::async(std::launch::async, [&] { files.shutdown(); }); + auto release_shutdown = Void::Scope::on_exit([gate] { gate->open(); }); + const auto deadline = std::chrono::steady_clock::now() + 10s; + for (;;) { + const auto operation = files.try_load(path); + if (operation.admission == CheckpointLoadAdmission::Closed) break; + require(operation.admission == CheckpointLoadAdmission::Busy, "shutdown unexpectedly admitted a read"); + require(std::chrono::steady_clock::now() < deadline, "shutdown did not close admission"); + std::this_thread::yield(); + } + require(files.try_save(directory.path / "closed.settlement", view).admission == SaveAdmission::Closed, + "shutdown left save admission open"); + gate->open(); + auto first_result = loaded(std::move(first)); + auto second_result = loaded(std::move(second)); + require(first_result.has_value() && second_result.has_value() && + first_result->world->seed() == world.seed() && second_result->world->seed() == newer.seed(), + "shutdown lost or mixed queued load candidates"); + require(stopping.wait_for(10s) == std::future_status::ready, "shutdown did not finish"); + stopping.get(); +} + +Test CheckpointFileTests::failures_recover_and_invalid_admission_preserves_inputs() { + TemporaryDirectory directory; + World world(1, 5, 5, 1, ExecutionMode::SerialReference); + const auto path = directory.path / "valid.settlement"; + write(path, encoded(world)); + auto fail = std::make_shared>(true); + CheckpointFiles files({.read_observer = [fail](CheckpointReadPhase phase) { + if (phase == CheckpointReadPhase::Opened && fail->exchange(false)) { + throw std::runtime_error("injected read observer failure"); + } + }}); + require(files.try_load("relative.settlement").admission == CheckpointLoadAdmission::InvalidRequest, + "relative input was admitted"); + require(files.try_load(path, 1).admission == CheckpointLoadAdmission::InvalidRequest, + "unsupported parallel worker count admitted"); + require(files.try_save(path, {}).admission == SaveAdmission::InvalidRequest, "null snapshot admitted"); + const auto view = snapshot(world); + require(files.try_save("relative.settlement", view).admission == SaveAdmission::InvalidRequest && + view->world->tick() == world.tick(), "invalid save altered its input"); + const auto failed = load(files, path); + require(!failed && failed.error().code == CheckpointFileError::ReaderFailure, + "observer failure did not settle future"); + const auto missing = load(files, directory.path / "missing.settlement"); + require(!missing && missing.error().code == CheckpointFileError::Io && missing.error().native_error != 0, + "missing file lost native error"); + write(directory.path / "unknown.settlement", "arbitrary bytes"); + const auto unknown = load(files, directory.path / "unknown.settlement"); + require(!unknown && unknown.error().code == CheckpointFileError::UnsupportedFormat, + "unknown signature was accepted"); + require(load(files, path).has_value(), "failed read poisoned the service"); +} + +Test CheckpointFileTests::reader_self_shutdown_is_rejected_without_closing() { + TemporaryDirectory directory; + World world(3, 5, 5, 1, ExecutionMode::SerialReference); + const auto path = directory.path / "self.settlement"; + write(path, encoded(world)); + CheckpointFiles* owner = nullptr; + auto first = std::make_shared>(true); + CheckpointFiles files({.read_observer = [&owner, first](CheckpointReadPhase phase) { + if (phase == CheckpointReadPhase::Opened && first->exchange(false)) owner->shutdown(); + }}); + owner = &files; + const auto failure = load(files, path); + require(!failure && failure.error().code == CheckpointFileError::ReaderFailure, + "self shutdown did not report failure"); + require(load(files, path).has_value(), "self shutdown closed admission before rejecting"); +} + +} // namespace