Publish queued Windows saves through atomic same-directory replacement
This commit is contained in:
1 parent
8d2870a6f8
commit
3844ebb205
6 files changed
+774
-4
No files matched your search
+5
-4
@@ -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 Binary Core)
|
||||
set(VOID_ENABLED_MODULES Async Binary Core)
|
||||
if(BUILD_TESTING)
|
||||
list(APPEND VOID_ENABLED_MODULES Testing)
|
||||
endif()
|
||||
@@ -39,6 +39,7 @@ find_package(Threads REQUIRED)
|
||||
|
||||
add_library(settlement_core
|
||||
engine/src/first_colony.cpp
|
||||
engine/src/save_service_win32.cpp
|
||||
engine/src/worker_pool.cpp
|
||||
engine/src/world.cpp
|
||||
engine/src/world_save.cpp
|
||||
@@ -51,8 +52,8 @@ target_include_directories(settlement_core
|
||||
|
||||
target_compile_features(settlement_core PUBLIC cxx_std_20)
|
||||
target_link_libraries(settlement_core
|
||||
PUBLIC Threads::Threads
|
||||
PRIVATE Void::Binary Void::Core
|
||||
PUBLIC Threads::Threads Void::Core
|
||||
PRIVATE Void::Async Void::Binary
|
||||
)
|
||||
|
||||
if(MSVC)
|
||||
@@ -104,7 +105,7 @@ else()
|
||||
endif()
|
||||
|
||||
if(BUILD_TESTING)
|
||||
add_executable(settlement_core_tests tests/core_tests.cpp tests/replay_tests.cpp tests/test_main.cpp)
|
||||
add_executable(settlement_core_tests tests/core_tests.cpp tests/replay_tests.cpp tests/save_service_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,48 @@
|
||||
# Publish immutable save requests asynchronously on Windows
|
||||
|
||||
Task ID: S15-01
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive /home/faumaray/Projects/stoneheart_at_home-worktrees/s15 system/s15-persistence, baseline 8d2870a. Root and other authors use different checkouts. S15-W02, M01-P2/F3, Void pin 7b0fea6. Root created https://git.faumaray.com/Void/Library/issues/3 for unsupported Windows replace_file.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Implement a bounded FIFO background Windows save service, with atomic same-volume publication of immutable request content and meaningful failure outcomes. Provide API/test surface for viewer and later checkpoint framing.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Own independent S15 file service only. No UI/World/serialization format change. Input is a snapshot-owning producer (or shared immutable bytes) with tick, epoch and request identity; synchronous existing save helper remains until owner integration.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect app/viewer_win32.cpp::save_world_file, current save codec, docs/plan/systems/S15.md. In exact pin inspect Void/System/Path.hpp (ReplaceFailure, unsupported Windows), Void/Async/{ThreadExecutor,FuturePool}.hpp for a single writer and bounded admission. Existing env and library checkout are in /tmp/stoneheart-verify.KoZwE4o8.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/save_service.hpp; engine/src/save_service_win32.cpp; tests/save_service_tests.cpp; CMakeLists.txt
|
||||
You are not alone. Use explicit workdir/absolute paths only in specified worktree; others own independent systems. Root handles CMake merges/Git. Do not edit main or change shared Serena project.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Give each accepted save a monotonic request identity, captured tick and session UUID (reuse Void::Uuid::Uuid or consistent fixed bytes). Materialize from immutable producer on writer thread or allow shared immutable bytes, further integration must keep snapshot acquisition cheap. Bound queue including in-flight and return Busy/Closed before ownership side effects. One FIFO writer ensures older accepted saves cannot replace newer same-slot requests. Use pinned Void Async where suitable. Worker completes all accepted requests on shutdown. A failed producer/write must deliver completion and next FIFO task continues.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Publish to a unique same-directory staging file created exclusively, write all bytes incl embedded NUL, handle short/error or close failure, explicitly FlushFileBuffers, atomically rename with replacement on the same volume; preserve previous slot on any prepublication failure, remove only owned staging files and distinguish postpublication visible/durability-unknown. First create, Unicode paths, sharing errors. Keep application-crash observations separate from power-loss guarantees. Local adapter + replacement criterion and upstream #3 link. Deterministic fault injection at phases for test; do not broaden external access. Communicate API early.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
S01 runtime later captures immutable snapshot/manifests, S15 checkpoint codec constructs bytes, UI will enqueue this service and poll completion. No dependency on unfinished runtime/system branch. CMake public types require actual transitive includes for callers.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Serialize FIFO submission ordering even if concurrent callers; expose or check order via returned IDs. No blocking UI submission, no mutex held waiting for disk/producer or while joining. Same-directory sibling preserved on failures. Use isolated temporary directory for tests, never overwrite user files. Reject missing parent/closed service; documents should make overwrite/new behavior clear.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Unicode path succeeds on create/replace while readers see full contents. 2. Prepublication failures preserve old bytes, temp cleaned, postpublication failure truthful. 3. Slow earlier/newer order on a single slot, bounds, shutdown drain, producer exception followed by next success verified. 4. Tests establish immutable snapshot life & UI caller progress without sleep-only assertions; tag save-slot and run under Wine.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/save-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. Tests use new empty temp dirs, Windows/Wine results labelled. Collect native limitations. Provide specific replacement test for Void #3.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Stop if Windows primitive cannot meet claimed contract or tests prove a different outcome. After two failed repairs escalate with artifacts. No external writes, further agents, branch operations, admin actions or out-of-scope edits.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User approved entire roadmap and per-system development with commits/push from root. F3 accepted FIFO ordering and failure semantics. Upstream issue already exists.
|
||||
|
||||
## 14. Return format
|
||||
Return S15-01 status, exact API/files, failure/visibility semantics, commands/counts, native verification still needed and integration notes. No subagents.
|
||||
@@ -46,6 +46,10 @@
|
||||
|
||||
## Приёмка
|
||||
|
||||
Первый Windows-срез службы сохранений ставит в ограниченную очередь запись с удерживаемым снимком, тактом и инкарнацией. Единственный исполнитель формирует байты, создаёт временный файл рядом со слотом, записывает и сбрасывает данные, закрывает дескриптор и публикует замену. Результат отдельно сообщает о видимости нового файла и об ошибке очистки. Принятые записи завершаются в порядке приёма, включая несколько запросов в один слот. [Интерфейс](../../../engine/include/settlement/core/save_service.hpp) · [Условие замены на Void](https://git.faumaray.com/Void/Library/issues/3)
|
||||
|
||||
Девять проверок `--tag save-slot` прошли в Windows x64 под Wine. Если во время замены читатель удерживал дескриптор с разрешением удаления, Wine вернул ошибку доступа 5. Служба сохранила прежние байты и удалила временный файл. Следующая запись после закрытия читателя успешно заменила слот. Нативная Windows и сохранность после потери питания требуют отдельной проверки. [Исполняемые проверки](../../../tests/save_service_tests.cpp)
|
||||
|
||||
- **S15-A01.** Сохранить демо при доставке на второй этаж. После загрузки сравнить сумки, склад, резервы и детали стройки, затем завершить дом без повторной оплаты материала.
|
||||
- **S15-A02.** Прервать запись после каждого блока и перед публикацией. Каждый запуск открывает целую предыдущую либо целую новую генерацию.
|
||||
- **S15-A03.** Воспроизвести один журнал в последовательном режиме и на 2, 6 и 12 потоках с задержанным чтением чанков. Канонические хеши совпадают на каждом такте.
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Uuid.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace settlement {
|
||||
|
||||
enum class SavePhase {
|
||||
Materialize, CreateStage, WriteStage, FlushStage, CloseStage, Publish, Published,
|
||||
};
|
||||
|
||||
enum class SaveError {
|
||||
None, ProducerFailed, TooLarge, Io, Internal, Injected,
|
||||
};
|
||||
|
||||
struct SaveRequest {
|
||||
// Absolute filesystem path. The parent must exist. Both creation and
|
||||
// replacement are supported; acceptance does not imply the path is writable.
|
||||
// Open readers may make Windows reject replacement, even with delete
|
||||
// sharing (observed ERROR_ACCESS_DENIED on Wine 11). Such failures preserve
|
||||
// the old slot; they never trigger a delete/truncate publication fallback.
|
||||
std::filesystem::path destination;
|
||||
std::uint64_t tick{};
|
||||
Void::Uuid::Uuid session{};
|
||||
// Capture an immutable snapshot/shared byte buffer by value. Invoked exactly
|
||||
// once, on the writer. Never capture live mutable World/UI state by reference.
|
||||
// Copies must be cheap; materialization and its memory budget belong here.
|
||||
std::function<std::string()> produce;
|
||||
};
|
||||
|
||||
struct SaveResult {
|
||||
std::uint64_t request_id{};
|
||||
std::uint64_t tick{};
|
||||
Void::Uuid::Uuid session{};
|
||||
SaveError error{SaveError::None};
|
||||
SavePhase phase{SavePhase::Materialize};
|
||||
std::uint32_t native_error{};
|
||||
bool visible_on_disk{false};
|
||||
// True for an error after publication: the new file is visible and must not
|
||||
// be reported as rolled back. Success promises flushed bytes and atomic
|
||||
// visibility, not resilience to power loss on every filesystem/device.
|
||||
bool durability_unknown{false};
|
||||
std::uint32_t cleanup_error{};
|
||||
// Set only if removal of this request's staging file failed.
|
||||
std::filesystem::path retained_staging_file;
|
||||
|
||||
[[nodiscard]] bool succeeded() const noexcept { return error == SaveError::None; }
|
||||
};
|
||||
|
||||
enum class SaveAdmission { Accepted, Busy, Closed, InvalidRequest, IdExhausted };
|
||||
|
||||
struct SaveSubmission {
|
||||
SaveAdmission admission{SaveAdmission::InvalidRequest};
|
||||
// Zero and an invalid future on rejection. Accepted IDs start at one and
|
||||
// increase in FIFO publication order, including for concurrent submitters.
|
||||
std::uint64_t request_id{};
|
||||
std::future<SaveResult> completion;
|
||||
};
|
||||
|
||||
struct SaveServiceOptions {
|
||||
std::size_t capacity{8}; // Includes the running request.
|
||||
std::size_t max_bytes{64 * 1024 * 1024}; // Checked after materialization.
|
||||
// Test seam, executed on the writer before each phase (each write chunk).
|
||||
// Nonzero injects a native error. Published runs after the rename.
|
||||
std::function<std::uint32_t(SavePhase)> fault_hook;
|
||||
};
|
||||
|
||||
// One bounded Void::Async FIFO writer per service. Use one service for all
|
||||
// requests to a slot; separate services/processes are independent writers.
|
||||
// Windows adapter tracked by https://git.faumaray.com/Void/Library/issues/3.
|
||||
// Replace it when Void::FileSystem::replace_file supports Windows and passes
|
||||
// the save-slot create/replace, reader, phase-failure and sibling-preservation
|
||||
// tests with the same visibility and cleanup reporting.
|
||||
class SaveService {
|
||||
public:
|
||||
explicit SaveService(SaveServiceOptions options = {});
|
||||
~SaveService(); // Drains accepted work; never destroy on its writer thread.
|
||||
SaveService(const SaveService&) = delete;
|
||||
SaveService& operator=(const SaveService&) = delete;
|
||||
|
||||
// Does no file IO or producer invocation and never waits for a slot, disk,
|
||||
// or another submitter. Contention is Busy. Rejection does not copy/move the
|
||||
// producer. Allocation/copy failures throw before accepting the request.
|
||||
[[nodiscard]] SaveSubmission try_submit(const SaveRequest& request);
|
||||
|
||||
// Closes admission and drains every accepted request. Safe concurrently
|
||||
// with submissions and other shutdown calls, but not object destruction.
|
||||
// Throws logic_error if called from this service's producer/fault hook.
|
||||
void shutdown();
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
} // namespace settlement
|
||||
@@ -0,0 +1,221 @@
|
||||
#include "settlement/core/save_service.hpp"
|
||||
|
||||
#include <Void/Async/FuturePool.hpp>
|
||||
#include <Void/Async/ThreadExecutor.hpp>
|
||||
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <windows.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace settlement {
|
||||
namespace {
|
||||
|
||||
// CREATE_NEW establishes ownership. No cleanup ever scans by filename prefix.
|
||||
struct StagingFile {
|
||||
HANDLE handle{INVALID_HANDLE_VALUE};
|
||||
std::filesystem::path path;
|
||||
bool owned{false};
|
||||
|
||||
void cleanup(SaveResult& result) noexcept {
|
||||
if (handle != INVALID_HANDLE_VALUE) {
|
||||
if (!CloseHandle(handle)) result.cleanup_error = GetLastError();
|
||||
handle = INVALID_HANDLE_VALUE;
|
||||
}
|
||||
if (owned && !DeleteFileW(path.c_str())) {
|
||||
result.cleanup_error = GetLastError();
|
||||
// Moving a path is noexcept, including during allocation failure.
|
||||
result.retained_staging_file = std::move(path);
|
||||
}
|
||||
owned = false;
|
||||
}
|
||||
};
|
||||
|
||||
bool valid_request(const SaveRequest& request) {
|
||||
const auto& path = request.destination;
|
||||
if (!request.produce || request.session.is_nil() || !path.is_absolute() ||
|
||||
path.native().find(L'\0') != std::wstring::npos) return false;
|
||||
const auto filename = path.filename();
|
||||
return !filename.empty() && filename != L"." && filename != L".." &&
|
||||
filename.native().find(L':') == std::wstring::npos;
|
||||
}
|
||||
|
||||
SaveResult publish(const SaveRequest& request, std::uint64_t id,
|
||||
const SaveServiceOptions& options) noexcept {
|
||||
SaveResult result;
|
||||
result.request_id = id;
|
||||
result.tick = request.tick;
|
||||
result.session = request.session;
|
||||
StagingFile staging;
|
||||
const auto phase = [&](SavePhase next) {
|
||||
result.phase = next;
|
||||
if (options.fault_hook) {
|
||||
result.native_error = options.fault_hook(next);
|
||||
if (result.native_error != 0) {
|
||||
result.error = SaveError::Injected;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
const auto io_error = [&] {
|
||||
result.error = SaveError::Io;
|
||||
result.native_error = GetLastError();
|
||||
};
|
||||
try {
|
||||
// A single exit after this body performs cleanup before returning the
|
||||
// result, including when path allocation or the producer throws.
|
||||
[&] {
|
||||
if (!phase(SavePhase::Materialize)) return;
|
||||
std::string bytes;
|
||||
try {
|
||||
bytes = request.produce();
|
||||
} catch (...) {
|
||||
result.error = SaveError::ProducerFailed;
|
||||
return;
|
||||
}
|
||||
if (bytes.size() > options.max_bytes) {
|
||||
result.error = SaveError::TooLarge;
|
||||
return;
|
||||
}
|
||||
if (!phase(SavePhase::CreateStage)) return;
|
||||
for (int attempt = 0; attempt < 16; ++attempt) {
|
||||
const auto uuid = Void::Uuid::try_v4();
|
||||
if (!uuid) {
|
||||
result.error = SaveError::Internal;
|
||||
return;
|
||||
}
|
||||
const auto name = uuid->to_string();
|
||||
staging.path = request.destination.parent_path() /
|
||||
(L".settlement-save-" + std::wstring(name.begin(), name.end()) + L".tmp");
|
||||
staging.handle = CreateFileW(staging.path.c_str(), GENERIC_WRITE, 0, nullptr,
|
||||
CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (staging.handle != INVALID_HANDLE_VALUE) {
|
||||
staging.owned = true;
|
||||
break;
|
||||
}
|
||||
const auto error = GetLastError();
|
||||
if (error != ERROR_FILE_EXISTS && error != ERROR_ALREADY_EXISTS) {
|
||||
result.error = SaveError::Io;
|
||||
result.native_error = error;
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!staging.owned) {
|
||||
result.error = SaveError::Io;
|
||||
result.native_error = ERROR_FILE_EXISTS;
|
||||
return;
|
||||
}
|
||||
std::size_t offset = 0;
|
||||
while (offset < bytes.size()) {
|
||||
if (!phase(SavePhase::WriteStage)) return;
|
||||
const auto count = static_cast<DWORD>(std::min<std::size_t>(bytes.size() - offset, 65536));
|
||||
DWORD written = 0;
|
||||
if (!WriteFile(staging.handle, bytes.data() + offset, count, &written, nullptr)) {
|
||||
io_error();
|
||||
return;
|
||||
}
|
||||
if (written == 0 || written > count) {
|
||||
result.error = SaveError::Io;
|
||||
result.native_error = ERROR_WRITE_FAULT;
|
||||
return;
|
||||
}
|
||||
offset += written; // Includes short successful writes.
|
||||
}
|
||||
if (!phase(SavePhase::FlushStage)) return;
|
||||
if (!FlushFileBuffers(staging.handle)) {
|
||||
io_error();
|
||||
return;
|
||||
}
|
||||
if (!phase(SavePhase::CloseStage)) return;
|
||||
if (!CloseHandle(staging.handle)) {
|
||||
io_error();
|
||||
return;
|
||||
}
|
||||
staging.handle = INVALID_HANDLE_VALUE;
|
||||
if (!phase(SavePhase::Publish)) return;
|
||||
// Same-directory rename, no MOVEFILE_COPY_ALLOWED fallback. This
|
||||
// publishes complete flushed bytes; WRITE_THROUGH alone does not
|
||||
// establish power-loss durability of directory metadata.
|
||||
if (!MoveFileExW(staging.path.c_str(), request.destination.c_str(),
|
||||
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
|
||||
io_error();
|
||||
return;
|
||||
}
|
||||
staging.owned = false;
|
||||
result.visible_on_disk = true;
|
||||
static_cast<void>(phase(SavePhase::Published));
|
||||
}();
|
||||
} catch (...) {
|
||||
result.error = SaveError::Internal;
|
||||
}
|
||||
result.durability_unknown = result.visible_on_disk && result.error != SaveError::None;
|
||||
staging.cleanup(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
struct SaveService::Impl {
|
||||
explicit Impl(SaveServiceOptions configured) : options(std::move(configured)) {
|
||||
if (options.capacity == 0 || options.max_bytes == 0) {
|
||||
throw std::invalid_argument("save service limits must be positive");
|
||||
}
|
||||
auto created = Void::Async::ThreadExecutor::create({.workers = 1, .max_admitted = options.capacity});
|
||||
if (!created) throw std::runtime_error("cannot create save writer");
|
||||
executor = std::move(*created);
|
||||
pool = std::make_unique<Void::Async::FuturePool>(*executor);
|
||||
if (!executor->start()) throw std::runtime_error("cannot start save writer");
|
||||
}
|
||||
|
||||
SaveServiceOptions options;
|
||||
std::unique_ptr<Void::Async::ThreadExecutor> executor;
|
||||
std::unique_ptr<Void::Async::FuturePool> pool;
|
||||
std::mutex admission_mutex;
|
||||
bool closed{false};
|
||||
std::uint64_t next_id{1};
|
||||
};
|
||||
|
||||
SaveService::SaveService(SaveServiceOptions options) : impl_(std::make_unique<Impl>(std::move(options))) {}
|
||||
|
||||
SaveService::~SaveService() { shutdown(); }
|
||||
|
||||
SaveSubmission SaveService::try_submit(const SaveRequest& request) {
|
||||
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 (impl_->executor->admitted() >= impl_->options.capacity) return {SaveAdmission::Busy, 0, {}};
|
||||
if (!valid_request(request)) return {SaveAdmission::InvalidRequest, 0, {}};
|
||||
if (impl_->next_id == 0) return {SaveAdmission::IdExhausted, 0, {}};
|
||||
const auto id = impl_->next_id;
|
||||
auto submitted = impl_->pool->try_submit([state = impl_.get(), request = SaveRequest(request), id]() mutable {
|
||||
auto result = publish(request, id, state->options);
|
||||
request.produce = {}; // Release snapshot even if the caller keeps its future.
|
||||
return result;
|
||||
});
|
||||
if (!submitted) {
|
||||
return {submitted.error() == Void::Async::AdmissionError::overloaded ?
|
||||
SaveAdmission::Busy : SaveAdmission::Closed, 0, {}};
|
||||
}
|
||||
++impl_->next_id; // Unsigned wrap to zero permanently exhausts identities.
|
||||
return {SaveAdmission::Accepted, id, std::move(*submitted)};
|
||||
}
|
||||
|
||||
void SaveService::shutdown() {
|
||||
if (impl_->executor->is_executor_thread()) {
|
||||
throw std::logic_error("save writer cannot join itself");
|
||||
}
|
||||
{
|
||||
std::lock_guard lock(impl_->admission_mutex);
|
||||
impl_->closed = true;
|
||||
}
|
||||
static_cast<void>(impl_->executor->join());
|
||||
}
|
||||
|
||||
} // namespace settlement
|
||||
@@ -0,0 +1,393 @@
|
||||
#include "settlement/core/save_service.hpp"
|
||||
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <windows.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <latch>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
using namespace settlement;
|
||||
using Void::Testing::Test;
|
||||
|
||||
void require(bool condition, const char* message) {
|
||||
if (!condition) throw std::runtime_error(message);
|
||||
}
|
||||
|
||||
struct TemporaryDirectory {
|
||||
std::filesystem::path path;
|
||||
TemporaryDirectory() {
|
||||
const auto token = Void::Uuid::v4().to_string();
|
||||
path = std::filesystem::temp_directory_path() / ("settlement-save-test-" + token);
|
||||
require(std::filesystem::create_directory(path), "test directory was not exclusively created");
|
||||
}
|
||||
~TemporaryDirectory() {
|
||||
std::error_code error;
|
||||
std::filesystem::remove_all(path, error);
|
||||
}
|
||||
};
|
||||
|
||||
struct Reader {
|
||||
HANDLE handle{INVALID_HANDLE_VALUE};
|
||||
Reader(const std::filesystem::path& path, DWORD sharing)
|
||||
: handle(CreateFileW(path.c_str(), GENERIC_READ, sharing, nullptr, OPEN_EXISTING,
|
||||
FILE_ATTRIBUTE_NORMAL, nullptr)) {
|
||||
require(handle != INVALID_HANDLE_VALUE, "cannot open test reader");
|
||||
}
|
||||
~Reader() { CloseHandle(handle); }
|
||||
std::string read() const {
|
||||
LARGE_INTEGER beginning{};
|
||||
require(SetFilePointerEx(handle, beginning, nullptr, FILE_BEGIN), "cannot rewind test reader");
|
||||
std::string bytes;
|
||||
std::array<char, 8192> buffer;
|
||||
for (;;) {
|
||||
DWORD count = 0;
|
||||
require(ReadFile(handle, buffer.data(), static_cast<DWORD>(buffer.size()), &count, nullptr),
|
||||
"test read failed");
|
||||
if (count == 0) return bytes;
|
||||
bytes.append(buffer.data(), count);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
std::string read(const std::filesystem::path& path) {
|
||||
return Reader(path, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE).read();
|
||||
}
|
||||
|
||||
void write(const std::filesystem::path& path, const std::string& bytes) {
|
||||
std::ofstream file(path, std::ios::binary);
|
||||
file.write(bytes.data(), static_cast<std::streamsize>(bytes.size()));
|
||||
file.close();
|
||||
require(static_cast<bool>(file), "cannot write test fixture");
|
||||
}
|
||||
|
||||
Void::Uuid::Uuid session() {
|
||||
Void::Uuid::Uuid id;
|
||||
id.bytes[0] = 42;
|
||||
return id;
|
||||
}
|
||||
|
||||
SaveRequest request(const std::filesystem::path& path, std::string bytes, std::uint64_t tick = 9) {
|
||||
return {path, tick, session(), [bytes = std::move(bytes)] { return bytes; }};
|
||||
}
|
||||
|
||||
SaveResult completed(SaveSubmission& submission) {
|
||||
require(submission.admission == SaveAdmission::Accepted && submission.request_id != 0,
|
||||
"request was not accepted");
|
||||
require(submission.completion.wait_for(10s) == std::future_status::ready, "save did not complete");
|
||||
auto result = submission.completion.get();
|
||||
require(result.request_id == submission.request_id, "completion identity changed");
|
||||
return result;
|
||||
}
|
||||
|
||||
void only_files(const TemporaryDirectory& directory, std::size_t count) {
|
||||
const auto actual = static_cast<std::size_t>(std::distance(
|
||||
std::filesystem::directory_iterator(directory.path), std::filesystem::directory_iterator{}));
|
||||
require(actual == count, "unexpected file or staging file left in test directory");
|
||||
}
|
||||
|
||||
// Every wait has an explicit causal signal. The timeout is only a deadlock
|
||||
// watchdog; it never creates the ordering being tested.
|
||||
struct Gate {
|
||||
std::promise<void> entered;
|
||||
std::future<void> arrival{entered.get_future()};
|
||||
std::promise<void> released;
|
||||
std::shared_future<void> release{released.get_future().share()};
|
||||
std::atomic<bool> opened{false};
|
||||
void wait() {
|
||||
entered.set_value();
|
||||
require(release.wait_for(10s) == std::future_status::ready, "test gate timed out");
|
||||
}
|
||||
void await_entry() {
|
||||
require(arrival.wait_for(10s) == std::future_status::ready, "writer did not reach test gate");
|
||||
}
|
||||
void open() {
|
||||
if (!opened.exchange(true)) released.set_value();
|
||||
}
|
||||
~Gate() { open(); }
|
||||
};
|
||||
|
||||
struct [[= Void::Testing::name("SaveServiceTests")]]
|
||||
SaveServiceTests : Void::Testing::Suite<SaveServiceTests> {
|
||||
[[= Void::Testing::tag("save-slot")]] Test unicode_create_replace_and_open_reader();
|
||||
[[= Void::Testing::tag("save-slot")]] Test prepublication_faults_preserve_slot_and_siblings();
|
||||
[[= Void::Testing::tag("save-slot")]] Test partial_staging_is_never_visible();
|
||||
[[= Void::Testing::tag("save-slot")]] Test fifo_bound_snapshot_lifetime_and_shutdown_drain();
|
||||
[[= Void::Testing::tag("save-slot")]] Test failed_producer_does_not_stop_writer();
|
||||
[[= Void::Testing::tag("save-slot")]] Test invalid_missing_parent_and_sharing_failure();
|
||||
[[= Void::Testing::tag("save-slot")]] Test concurrent_submission_identity_matches_publication_order();
|
||||
[[= Void::Testing::tag("save-slot")]] Test empty_file_and_size_limit();
|
||||
[[= Void::Testing::tag("save-slot")]] Test self_shutdown_is_rejected_without_closing_service();
|
||||
};
|
||||
|
||||
Test SaveServiceTests::unicode_create_replace_and_open_reader() {
|
||||
TemporaryDirectory directory;
|
||||
const auto path = directory.path / L"\u0441\u043e\u0445\u0440\u0430\u043d\u0435\u043d\u0438\u0435-\u96ea.bin";
|
||||
SaveService service;
|
||||
const std::string old_bytes("old\0save", 8);
|
||||
auto first = service.try_submit(request(path, old_bytes, 17));
|
||||
const auto created = completed(first);
|
||||
require(created.succeeded() && created.visible_on_disk && !created.durability_unknown,
|
||||
"first save not published");
|
||||
require(created.tick == 17 && created.session == session(), "snapshot metadata was not preserved");
|
||||
std::string new_bytes(200000, 'x');
|
||||
new_bytes[65536] = '\0';
|
||||
new_bytes.back() = 'z';
|
||||
bool retry_after_reader_closes = false;
|
||||
{
|
||||
Reader old_reader(path, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE);
|
||||
auto second = service.try_submit(request(path, new_bytes));
|
||||
const auto replacement = completed(second);
|
||||
require(second.request_id > first.request_id, "save identity did not increase");
|
||||
require(old_reader.read() == old_bytes, "open reader saw partial or replaced old file bytes");
|
||||
if (replacement.succeeded()) {
|
||||
require(replacement.visible_on_disk && !replacement.durability_unknown,
|
||||
"successful replacement not reported as visible");
|
||||
require(read(path) == new_bytes, "fresh reader did not see complete binary replacement");
|
||||
} else {
|
||||
// Wine 11 returns ERROR_ACCESS_DENIED (5), even with delete sharing.
|
||||
// Windows/filesystem open-handle restrictions may reject publication;
|
||||
// atomic visibility does not promise replacement under every lock.
|
||||
require(replacement.error == SaveError::Io && replacement.phase == SavePhase::Publish &&
|
||||
(replacement.native_error == ERROR_ACCESS_DENIED ||
|
||||
replacement.native_error == ERROR_SHARING_VIOLATION) &&
|
||||
!replacement.visible_on_disk && !replacement.durability_unknown,
|
||||
"replacement failed outside the permitted sharing/access boundary");
|
||||
require(read(path) == old_bytes, "rejected replacement changed the existing slot");
|
||||
require(replacement.cleanup_error == 0 && replacement.retained_staging_file.empty(),
|
||||
"rejected replacement did not clean its staging file");
|
||||
only_files(directory, 1);
|
||||
retry_after_reader_closes = true;
|
||||
}
|
||||
}
|
||||
if (retry_after_reader_closes) {
|
||||
auto retry = service.try_submit(request(path, new_bytes));
|
||||
require(completed(retry).succeeded(), "next replacement failed after the reader closed");
|
||||
}
|
||||
require(read(path) == new_bytes, "fresh reader did not see complete binary replacement");
|
||||
service.shutdown();
|
||||
only_files(directory, 1);
|
||||
}
|
||||
|
||||
Test SaveServiceTests::prepublication_faults_preserve_slot_and_siblings() {
|
||||
const std::array phases{SavePhase::Materialize, SavePhase::CreateStage, SavePhase::WriteStage,
|
||||
SavePhase::FlushStage, SavePhase::CloseStage, SavePhase::Publish,
|
||||
SavePhase::Published};
|
||||
for (const auto failed_phase : phases) {
|
||||
TemporaryDirectory directory;
|
||||
const auto path = directory.path / L"slot.bin";
|
||||
const auto sibling = directory.path / L".settlement-save-unrelated.tmp";
|
||||
write(path, "previous complete generation");
|
||||
write(sibling, "unrelated sibling");
|
||||
std::size_t writes = 0;
|
||||
SaveService service({.fault_hook = [&](SavePhase phase) -> std::uint32_t {
|
||||
if (phase != failed_phase) return 0;
|
||||
if (phase == SavePhase::WriteStage && ++writes == 1) return 0;
|
||||
return ERROR_DISK_FULL;
|
||||
}});
|
||||
const std::string bytes(150000, 'n');
|
||||
auto submitted = service.try_submit(request(path, bytes));
|
||||
const auto failed = completed(submitted);
|
||||
service.shutdown();
|
||||
const bool published = failed_phase == SavePhase::Published;
|
||||
require(failed.error == SaveError::Injected && failed.phase == failed_phase &&
|
||||
failed.native_error == ERROR_DISK_FULL, "incorrect phase failure reporting");
|
||||
require(failed.visible_on_disk == published && failed.durability_unknown == published,
|
||||
"failure incorrectly reported publication or rollback");
|
||||
require(read(path) == (published ? bytes : "previous complete generation"),
|
||||
"failure exposed incomplete data or lost previous slot");
|
||||
require(read(sibling) == "unrelated sibling", "cleanup removed an unowned staging sibling");
|
||||
require(failed.cleanup_error == 0 && failed.retained_staging_file.empty(), "cleanup failed");
|
||||
only_files(directory, 2);
|
||||
}
|
||||
}
|
||||
|
||||
Test SaveServiceTests::partial_staging_is_never_visible() {
|
||||
TemporaryDirectory directory;
|
||||
const auto path = directory.path / L"slot.bin";
|
||||
write(path, "old");
|
||||
auto gate = std::make_shared<Gate>();
|
||||
std::size_t writes = 0;
|
||||
SaveService service({.fault_hook = [gate, &writes](SavePhase phase) -> std::uint32_t {
|
||||
if (phase == SavePhase::WriteStage && ++writes == 2) gate->wait();
|
||||
return 0;
|
||||
}});
|
||||
const std::string bytes(150000, 'n');
|
||||
auto submitted = service.try_submit(request(path, bytes));
|
||||
gate->await_entry();
|
||||
require(read(path) == "old", "partial staging replaced old slot");
|
||||
require(submitted.completion.wait_for(0s) == std::future_status::timeout, "gate did not block writer");
|
||||
gate->open();
|
||||
require(completed(submitted).succeeded() && read(path) == bytes, "complete generation was not published");
|
||||
}
|
||||
|
||||
Test SaveServiceTests::fifo_bound_snapshot_lifetime_and_shutdown_drain() {
|
||||
TemporaryDirectory directory;
|
||||
const auto path = directory.path / L"slot.bin";
|
||||
auto gate = std::make_shared<Gate>();
|
||||
auto snapshot = std::make_shared<const std::string>("captured tick 123");
|
||||
std::weak_ptr<const std::string> lifetime = snapshot;
|
||||
SaveService service({.capacity = 2});
|
||||
SaveRequest immutable{path, 123, session(), [snapshot, gate] { gate->wait(); return *snapshot; }};
|
||||
auto first = service.try_submit(immutable);
|
||||
immutable.produce = {};
|
||||
snapshot.reset();
|
||||
gate->await_entry();
|
||||
require(!lifetime.expired(), "queued save did not retain immutable snapshot");
|
||||
|
||||
// This producer cannot run until the first is released. Admission itself
|
||||
// must finish while that writer is blocked (without a disk/producer lock).
|
||||
auto caller = std::async(std::launch::async, [&] { return service.try_submit(request(path, "newer", 124)); });
|
||||
require(caller.wait_for(2s) == std::future_status::ready, "submission waited on the writer");
|
||||
auto second = caller.get();
|
||||
require(second.admission == SaveAdmission::Accepted && second.request_id == first.request_id + 1,
|
||||
"second FIFO request not admitted");
|
||||
std::atomic<std::size_t> rejected_invocations{0};
|
||||
SaveRequest third{path, 125, session(), [&] { ++rejected_invocations; return "not accepted"; }};
|
||||
const auto rejected = service.try_submit(third);
|
||||
require(rejected.admission == SaveAdmission::Busy && rejected.request_id == 0 &&
|
||||
!rejected.completion.valid() && static_cast<bool>(third.produce), "capacity did not include running request");
|
||||
|
||||
std::promise<void> shutdown_started;
|
||||
auto starting = shutdown_started.get_future();
|
||||
auto draining = std::async(std::launch::async, [&] { shutdown_started.set_value(); service.shutdown(); });
|
||||
starting.get();
|
||||
const auto deadline = std::chrono::steady_clock::now() + 2s;
|
||||
SaveAdmission while_draining;
|
||||
do {
|
||||
while_draining = service.try_submit(third).admission;
|
||||
if (while_draining == SaveAdmission::Closed) break;
|
||||
std::this_thread::yield();
|
||||
} while (std::chrono::steady_clock::now() < deadline);
|
||||
require(while_draining == SaveAdmission::Closed, "shutdown held admission lock while draining");
|
||||
require(draining.wait_for(0s) == std::future_status::timeout, "shutdown did not wait for accepted work");
|
||||
gate->open();
|
||||
require(draining.wait_for(10s) == std::future_status::ready, "shutdown failed to drain");
|
||||
draining.get();
|
||||
require(completed(first).succeeded() && completed(second).succeeded(), "accepted saves lost during shutdown");
|
||||
require(read(path) == "newer", "older FIFO request overwrote newer save");
|
||||
require(lifetime.expired(), "completed save unnecessarily retained its snapshot");
|
||||
require(rejected_invocations == 0, "rejected producer was invoked");
|
||||
require(service.try_submit(third).admission == SaveAdmission::Closed, "shutdown did not close admission");
|
||||
}
|
||||
|
||||
Test SaveServiceTests::failed_producer_does_not_stop_writer() {
|
||||
TemporaryDirectory directory;
|
||||
const auto path = directory.path / L"slot.bin";
|
||||
write(path, "old");
|
||||
SaveService service;
|
||||
SaveRequest broken{path, 1, session(), []() -> std::string { throw std::runtime_error("producer failure"); }};
|
||||
auto first = service.try_submit(broken);
|
||||
const auto failed = completed(first);
|
||||
require(failed.error == SaveError::ProducerFailed && failed.phase == SavePhase::Materialize &&
|
||||
!failed.visible_on_disk && read(path) == "old", "producer failure changed the slot");
|
||||
auto second = service.try_submit(request(path, "recovered"));
|
||||
require(completed(second).succeeded() && read(path) == "recovered", "writer stopped after producer failure");
|
||||
service.shutdown();
|
||||
only_files(directory, 1);
|
||||
}
|
||||
|
||||
Test SaveServiceTests::invalid_missing_parent_and_sharing_failure() {
|
||||
TemporaryDirectory directory;
|
||||
SaveService service;
|
||||
auto relative = request(L"relative.bin", "bytes");
|
||||
require(service.try_submit(relative).admission == SaveAdmission::InvalidRequest, "relative path accepted");
|
||||
auto nil = request(directory.path / L"nil.bin", "bytes");
|
||||
nil.session = {};
|
||||
require(service.try_submit(nil).admission == SaveAdmission::InvalidRequest, "nil session accepted");
|
||||
auto absent = service.try_submit(request(directory.path / L"missing" / L"slot.bin", "bytes"));
|
||||
const auto absent_result = completed(absent);
|
||||
require(absent_result.error == SaveError::Io && absent_result.phase == SavePhase::CreateStage &&
|
||||
!absent_result.visible_on_disk, "missing parent was not rejected by the writer");
|
||||
const auto path = directory.path / L"locked.bin";
|
||||
write(path, "locked previous generation");
|
||||
{
|
||||
Reader lock(path, FILE_SHARE_READ);
|
||||
auto blocked = service.try_submit(request(path, "replacement"));
|
||||
const auto result = completed(blocked);
|
||||
require(result.error == SaveError::Io && result.phase == SavePhase::Publish &&
|
||||
result.native_error != 0 && !result.visible_on_disk && !result.durability_unknown,
|
||||
"sharing failure was not reported before publication");
|
||||
require(lock.read() == "locked previous generation", "sharing failure modified existing file");
|
||||
}
|
||||
auto retry = service.try_submit(request(path, "replacement"));
|
||||
require(completed(retry).succeeded() && read(path) == "replacement", "sharing failure stopped writer");
|
||||
service.shutdown();
|
||||
only_files(directory, 1);
|
||||
}
|
||||
|
||||
Test SaveServiceTests::concurrent_submission_identity_matches_publication_order() {
|
||||
TemporaryDirectory directory;
|
||||
const auto path = directory.path / L"slot.bin";
|
||||
SaveService service({.capacity = 16});
|
||||
constexpr std::size_t callers = 8;
|
||||
std::latch start(callers);
|
||||
std::array<SaveSubmission, callers> submissions;
|
||||
std::array<std::thread, callers> threads;
|
||||
for (std::size_t index = 0; index < callers; ++index) {
|
||||
threads[index] = std::thread([&, index] {
|
||||
const auto input = request(path, std::to_string(index));
|
||||
start.arrive_and_wait();
|
||||
do {
|
||||
submissions[index] = service.try_submit(input);
|
||||
if (submissions[index].admission == SaveAdmission::Busy) std::this_thread::yield();
|
||||
} while (submissions[index].admission == SaveAdmission::Busy);
|
||||
});
|
||||
}
|
||||
for (auto& thread : threads) thread.join();
|
||||
service.shutdown();
|
||||
std::array<std::uint64_t, callers> ids;
|
||||
std::size_t newest = 0;
|
||||
for (std::size_t index = 0; index < callers; ++index) {
|
||||
require(completed(submissions[index]).succeeded(), "concurrent save failed");
|
||||
ids[index] = submissions[index].request_id;
|
||||
if (ids[index] > ids[newest]) newest = index;
|
||||
}
|
||||
require(read(path) == std::to_string(newest), "publication order disagreed with acceptance identity");
|
||||
std::ranges::sort(ids);
|
||||
for (std::size_t index = 0; index < callers; ++index) require(ids[index] == index + 1, "duplicate or missing identity");
|
||||
only_files(directory, 1);
|
||||
}
|
||||
|
||||
Test SaveServiceTests::empty_file_and_size_limit() {
|
||||
TemporaryDirectory directory;
|
||||
const auto path = directory.path / L"slot.bin";
|
||||
SaveService service({.max_bytes = 3});
|
||||
auto empty = service.try_submit(request(path, ""));
|
||||
require(completed(empty).succeeded() && read(path).empty(), "empty save failed");
|
||||
auto large = service.try_submit(request(path, "four"));
|
||||
const auto rejected = completed(large);
|
||||
require(rejected.error == SaveError::TooLarge && !rejected.visible_on_disk && read(path).empty(),
|
||||
"oversized generation modified slot");
|
||||
service.shutdown();
|
||||
only_files(directory, 1);
|
||||
}
|
||||
|
||||
Test SaveServiceTests::self_shutdown_is_rejected_without_closing_service() {
|
||||
TemporaryDirectory directory;
|
||||
const auto path = directory.path / L"slot.bin";
|
||||
SaveService service;
|
||||
SaveRequest recursive{path, 1, session(), [&]() -> std::string { service.shutdown(); return "unreachable"; }};
|
||||
auto first = service.try_submit(recursive);
|
||||
require(completed(first).error == SaveError::ProducerFailed, "writer self-join did not fail safely");
|
||||
auto second = service.try_submit(request(path, "still running"));
|
||||
require(completed(second).succeeded(), "self-join closed service");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
Reference in new issue
Block a user