From 51ceb081ac7ff01ea8e744d66350373ec3d8478a Mon Sep 17 00:00:00 2001 From: selikhov Date: Thu, 3 Dec 2026 09:34:50 +0300 Subject: [PATCH] feat(System): transactional file replacement on Windows x64 (#3) - replace_file/atomic_write gain a Win32 implementation: exclusive CREATE_NEW staging in the destination directory, WriteFile loop, FlushFileBuffers for durable_sync, MoveFileExW(MOVEFILE_REPLACE_EXISTING [| MOVEFILE_WRITE_THROUGH]) for atomic publication and a parent-directory flush for durability. - read_file_bounded/write_file implemented on Windows so the contract is usable and testable there. - Documented Windows guarantees per durability level, including the application-crash vs power-loss distinction and post-rename failure reporting (sync_parent + visible_on_disk + durability_unknown). - Added a portable contract test (first creation, replacement, Unicode name, pre-publication faults preserving old contents, post-publication fault reporting, no staging leftovers, live destination never deleted) and a concurrent-writer atomicity test. --- include/Void/System/Path.hpp | 557 +++++++++++++++++++++++++++++-- tests/standalone/System/Path.cpp | 202 +++++++++++ 2 files changed, 739 insertions(+), 20 deletions(-) diff --git a/include/Void/System/Path.hpp b/include/Void/System/Path.hpp index a9d82ec..6d66af5 100644 --- a/include/Void/System/Path.hpp +++ b/include/Void/System/Path.hpp @@ -36,6 +36,14 @@ #include #endif #endif +#else +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include #endif namespace Void::FileSystem @@ -45,6 +53,38 @@ struct ReadFileOptions { std::size_t max_bytes{16ULL * 1024ULL * 1024ULL}; }; +/// How much `replace_file` guarantees before reporting success. +/// +/// - `atomic_visibility`: publication is a single atomic directory-entry +/// replacement. A concurrent reader opens either the complete old file or the +/// complete new file, never a partial one. This survives an application +/// (process) crash: whatever rename already happened remains. It does *not* +/// promise that the new directory entry survives a power loss without a +/// subsequent `durable_sync`. +/// - `durable_sync`: additionally flushes the staged data before publication and +/// the parent directory after it. A successful return means the new contents +/// and their directory entry have reached stable storage (subject to the +/// device honoring flush requests). +/// +/// Windows x64 notes: +/// - Staging uses an exclusively created (`CREATE_NEW`, share mode 0) temporary +/// file in the destination directory, so names never collide and no other +/// process can observe partial contents. +/// - Publication uses `MoveFileExW(MOVEFILE_REPLACE_EXISTING)`. On NTFS this is +/// one atomic directory-entry replacement, so readers observe old-or-new. +/// - `durable_sync` adds `MOVEFILE_WRITE_THROUGH`, `FlushFileBuffers` on the +/// staged file, and `FlushFileBuffers` on the parent directory handle. If the +/// flush after the rename fails the result is `ReplacePhase::sync_parent` +/// with `visible_on_disk = true` and `durability_unknown = true`: the new file +/// is visible but may not survive power loss. +/// - Application crash vs power loss: a crash keeps the rename that already +/// happened (atomic_visibility is enough); power loss may lose it unless +/// durable_sync succeeded. Even durable_sync depends on the volume and its +/// filter drivers honoring flushes (NTFS does; some network/antivirus layers +/// do not). +/// - Replacing a destination that another process opened without +/// `FILE_SHARE_DELETE` fails in the rename phase and leaves the destination +/// intact. enum class ReplaceDurability { atomic_visibility, durable_sync, @@ -110,6 +150,143 @@ namespace detail } // namespace detail +#ifdef _WIN32 +namespace detail +{ + +/// Owning wrapper for a Win32 HANDLE (INVALID_HANDLE_VALUE is the empty state). +class OwnedHandle +{ +public: + OwnedHandle() noexcept = default; + explicit OwnedHandle(HANDLE handle) noexcept : handle_(handle) {} + ~OwnedHandle() noexcept { reset(); } + + OwnedHandle(const OwnedHandle&) = delete; + OwnedHandle& operator=(const OwnedHandle&) = delete; + + OwnedHandle(OwnedHandle&& other) noexcept + : handle_(std::exchange(other.handle_, INVALID_HANDLE_VALUE)) + { + } + + OwnedHandle& operator=(OwnedHandle&& other) noexcept + { + if (this != &other) { + reset(); + handle_ = std::exchange(other.handle_, INVALID_HANDLE_VALUE); + } + return *this; + } + + [[nodiscard]] bool valid() const noexcept + { + return handle_ != INVALID_HANDLE_VALUE && handle_ != nullptr; + } + [[nodiscard]] HANDLE get() const noexcept { return handle_; } + + void reset(HANDLE handle = INVALID_HANDLE_VALUE) noexcept + { + const HANDLE old = std::exchange(handle_, handle); + if (old != INVALID_HANDLE_VALUE && old != nullptr) { + (void)::CloseHandle(old); + } + } + + /// Close explicitly, reporting whether CloseHandle succeeded. + [[nodiscard]] bool close() noexcept + { + const HANDLE old = std::exchange(handle_, INVALID_HANDLE_VALUE); + if (old == INVALID_HANDLE_VALUE || old == nullptr) { + return true; + } + return ::CloseHandle(old) != 0; + } + +private: + HANDLE handle_{INVALID_HANDLE_VALUE}; +}; + +[[nodiscard]] inline std::string win32_message(DWORD error) +{ + char* buffer = nullptr; + const DWORD length = ::FormatMessageA( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + nullptr, + error, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + reinterpret_cast(&buffer), + 0, + nullptr); + std::string message = (length != 0 && buffer != nullptr) + ? std::string{buffer, length} + : std::string{"unknown error"}; + if (buffer != nullptr) { + ::LocalFree(buffer); + } + while (!message.empty() && + (message.back() == '\n' || message.back() == '\r' || + message.back() == ' ' || message.back() == '.')) { + message.pop_back(); + } + return message; +} + +[[nodiscard]] inline Void::System::SystemErrorCode + map_win32_error(DWORD error) noexcept +{ + switch (error) { + case ERROR_FILE_NOT_FOUND: + case ERROR_PATH_NOT_FOUND: + case ERROR_INVALID_DRIVE: + return Void::System::SystemErrorCode::not_found; + case ERROR_ACCESS_DENIED: + case ERROR_WRITE_PROTECT: + case ERROR_SHARING_VIOLATION: + case ERROR_LOCK_VIOLATION: + return Void::System::SystemErrorCode::permission_denied; + case ERROR_FILE_EXISTS: + case ERROR_ALREADY_EXISTS: + return Void::System::SystemErrorCode::already_exists; + case ERROR_INVALID_NAME: + case ERROR_INVALID_PARAMETER: + case ERROR_BAD_PATHNAME: + case ERROR_FILENAME_EXCED_RANGE: + return Void::System::SystemErrorCode::invalid_argument; + case ERROR_DISK_FULL: + case ERROR_HANDLE_DISK_FULL: + return Void::System::SystemErrorCode::limit_exceeded; + case ERROR_NOT_SUPPORTED: + case ERROR_CALL_NOT_IMPLEMENTED: + case ERROR_INVALID_FUNCTION: + return Void::System::SystemErrorCode::unsupported; + case ERROR_BUSY: + case ERROR_RETRY: + return Void::System::SystemErrorCode::busy; + case ERROR_OPERATION_ABORTED: + return Void::System::SystemErrorCode::cancelled; + case ERROR_TIMEOUT: + return Void::System::SystemErrorCode::timed_out; + case ERROR_NOT_ENOUGH_MEMORY: + case ERROR_OUTOFMEMORY: + return Void::System::SystemErrorCode::unavailable; + default: + return Void::System::SystemErrorCode::io_error; + } +} + +[[nodiscard]] inline Void::Result::Error make_win32_error( + Void::System::SystemErrorCode code, std::string_view what, DWORD error) +{ + return Void::System::make_system_error( + code, + std::format("{} (win32={}: {})", what, error, win32_message(error))); +} + +} // namespace detail +#endif + /// Read up to `options.max_bytes` from `path` cleanly with typed errors. [[nodiscard]] inline Void::Result::Result read_file_bounded(const std::filesystem::path& path, @@ -177,11 +354,73 @@ namespace detail content.size()); return content; #else - (void)path; - (void)options; - return std::unexpected{Void::System::make_system_error( - Void::System::SystemErrorCode::unsupported, - "FileSystem::read_file: unsupported platform")}; + const HANDLE raw = ::CreateFileW(path.c_str(), + GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE | + FILE_SHARE_DELETE, + nullptr, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + nullptr); + if (raw == INVALID_HANDLE_VALUE) { + const DWORD err = ::GetLastError(); + Void::Log::warn( + "FileSystem", "read_file: cannot open '{}'", path.string()); + return std::unexpected{detail::make_win32_error( + detail::map_win32_error(err), + std::format("FileSystem::read_file: cannot open '{}'", + path.string()), + err)}; + } + detail::OwnedHandle handle{raw}; + + LARGE_INTEGER size{}; + if (::GetFileSizeEx(handle.get(), &size) != 0 && size.QuadPart >= 0 && + static_cast(size.QuadPart) > options.max_bytes) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + std::format("FileSystem::read_file: '{}' ({} bytes) exceeds limit ({})", + path.string(), + static_cast(size.QuadPart), + options.max_bytes))}; + } + + std::string content; + std::array buffer{}; + for (;;) { + DWORD read = 0; + if (::ReadFile(handle.get(), + buffer.data(), + static_cast(buffer.size()), + &read, + nullptr) == 0) { + const DWORD err = ::GetLastError(); + Void::Log::warn( + "FileSystem", "read_file: I/O error reading '{}'", path.string()); + return std::unexpected{detail::make_win32_error( + detail::map_win32_error(err), + std::format("FileSystem::read_file: I/O error reading '{}'", + path.string()), + err)}; + } + if (read == 0) { + break; + } + const auto count = static_cast(read); + if (count > options.max_bytes - content.size()) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + std::format("FileSystem::read_file: '{}' exceeded limit ({})", + path.string(), + options.max_bytes))}; + } + content.append(buffer.data(), count); + } + Void::Log::debug("FileSystem", + "read_file: '{}' ({} bytes)", + path.string(), + content.size()); + return content; #endif } @@ -233,11 +472,58 @@ namespace detail } return guard.close(); #else - (void)path; - (void)content; - return std::unexpected{Void::System::make_system_error( - Void::System::SystemErrorCode::unsupported, - "FileSystem::write_file: unsupported platform")}; + const HANDLE raw = ::CreateFileW(path.c_str(), + GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE | + FILE_SHARE_DELETE, + nullptr, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + nullptr); + if (raw == INVALID_HANDLE_VALUE) { + const DWORD err = ::GetLastError(); + Void::Log::warn( + "FileSystem", "write_file: cannot open '{}'", path.string()); + return std::unexpected{detail::make_win32_error( + detail::map_win32_error(err), + std::format("FileSystem::write_file: cannot open '{}'", + path.string()), + err)}; + } + detail::OwnedHandle handle{raw}; + + std::size_t offset = 0; + while (offset < content.size()) { + const auto remaining = content.size() - offset; + constexpr std::size_t kMaxChunk = 0x4000'0000; + const DWORD chunk = static_cast( + remaining < kMaxChunk ? remaining : kMaxChunk); + DWORD written = 0; + if (::WriteFile(handle.get(), + content.data() + offset, + chunk, + &written, + nullptr) == 0) { + const DWORD err = ::GetLastError(); + Void::Log::warn( + "FileSystem", "write_file: I/O error writing '{}'", path.string()); + return std::unexpected{detail::make_win32_error( + detail::map_win32_error(err), + std::format("FileSystem::write_file: I/O error writing '{}'", + path.string()), + err)}; + } + offset += written; + } + if (!handle.close()) { + const DWORD err = ::GetLastError(); + return std::unexpected{detail::make_win32_error( + detail::map_win32_error(err), + std::format("FileSystem::write_file: close failed for '{}'", + path.string()), + err)}; + } + return {}; #endif } @@ -469,16 +755,247 @@ namespace detail bytes.size()); return {}; #else - (void)path; - (void)bytes; - (void)options; - return std::unexpected{ReplaceFailure{ - Void::System::make_system_error( - Void::System::SystemErrorCode::unsupported, - "FileSystem::replace_file: unsupported platform"), - ReplacePhase::validation, - false, - false}}; + auto check_fault = [&](ReplacePhase phase, + bool visible, + bool unknown) -> std::optional { + if (options.fault_hook) { + if (const auto injected = options.fault_hook(phase)) { + return ReplaceFailure{ + Void::System::make_system_error( + unknown + ? Void::System::SystemErrorCode::durability_unknown + : Void::System::map_errno_to_system_code(*injected), + std::format("FileSystem::replace_file: injected fault for '{}'", + path.string()), + *injected), + phase, + visible, + unknown}; + } + } + return std::nullopt; + }; + + if (auto f = check_fault(ReplacePhase::validation, false, false)) { + return std::unexpected{std::move(*f)}; + } + + if (path.empty() || !path.has_filename()) { + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "FileSystem::replace_file: empty path or missing filename"), + ReplacePhase::validation, + false, + false}}; + } + + const std::filesystem::path parent = + path.parent_path().empty() ? std::filesystem::path{"."} + : path.parent_path(); + const std::wstring target_name = path.filename().wstring(); + if (target_name == L"." || target_name == L"..") { + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "FileSystem::replace_file: invalid target filename"), + ReplacePhase::validation, + false, + false}}; + } + + if (auto f = check_fault(ReplacePhase::create_stage, false, false)) { + return std::unexpected{std::move(*f)}; + } + + std::filesystem::path temp_path; + detail::OwnedHandle temp_handle; + DWORD last_err = 0; + for (int attempt = 0; attempt < 32; ++attempt) { + const auto entropy = detail::next_temp_entropy(); + const std::string tail = std::format("{:016x}", entropy); + std::wstring name = L"."; + name += target_name; + name += L".void_tmp_"; + name.append(tail.begin(), tail.end()); + temp_path = parent / name; + const HANDLE raw = ::CreateFileW(temp_path.c_str(), + GENERIC_WRITE, + 0, + nullptr, + CREATE_NEW, + FILE_ATTRIBUTE_NORMAL, + nullptr); + if (raw != INVALID_HANDLE_VALUE) { + temp_handle.reset(raw); + break; + } + last_err = ::GetLastError(); + if (last_err != ERROR_FILE_EXISTS && last_err != ERROR_ALREADY_EXISTS) { + return std::unexpected{ReplaceFailure{ + detail::make_win32_error( + detail::map_win32_error(last_err), + std::format( + "FileSystem::replace_file: cannot create temp in '{}'", + parent.string()), + last_err), + ReplacePhase::create_stage, + false, + false}}; + } + } + if (!temp_handle.valid()) { + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::SystemErrorCode::already_exists, + "FileSystem::replace_file: exhausted temp names", + static_cast(last_err)), + ReplacePhase::create_stage, + false, + false}}; + } + + bool cleanup_temp = true; + struct TempCleanup { + const std::filesystem::path* path{nullptr}; + bool* active{nullptr}; + ~TempCleanup() noexcept + { + if (active != nullptr && *active && path != nullptr) { + (void)::DeleteFileW(path->c_str()); + } + } + } temp_guard{&temp_path, &cleanup_temp}; + + if (auto f = check_fault(ReplacePhase::write_stage, false, false)) { + return std::unexpected{std::move(*f)}; + } + + std::size_t offset = 0; + while (offset < bytes.size()) { + const auto remaining = bytes.size() - offset; + constexpr std::size_t kMaxChunk = 0x4000'0000; + const DWORD chunk = static_cast( + remaining < kMaxChunk ? remaining : kMaxChunk); + DWORD written = 0; + if (::WriteFile(temp_handle.get(), + bytes.data() + offset, + chunk, + &written, + nullptr) == 0) { + const DWORD err = ::GetLastError(); + return std::unexpected{ReplaceFailure{ + detail::make_win32_error( + detail::map_win32_error(err), + std::format( + "FileSystem::replace_file: write failed for '{}'", + path.string()), + err), + ReplacePhase::write_stage, + false, + false}}; + } + offset += written; + } + + if (options.durability == ReplaceDurability::durable_sync) { + if (auto f = check_fault(ReplacePhase::sync_stage, false, false)) { + return std::unexpected{std::move(*f)}; + } + if (::FlushFileBuffers(temp_handle.get()) == 0) { + const DWORD err = ::GetLastError(); + return std::unexpected{ReplaceFailure{ + detail::make_win32_error( + Void::System::SystemErrorCode::sync_failed, + std::format( + "FileSystem::replace_file: stage flush failed for '{}'", + path.string()), + err), + ReplacePhase::sync_stage, + false, + false}}; + } + } + + if (!temp_handle.close()) { + const DWORD err = ::GetLastError(); + return std::unexpected{ReplaceFailure{ + detail::make_win32_error( + detail::map_win32_error(err), + std::format( + "FileSystem::replace_file: close failed for '{}'", + path.string()), + err), + ReplacePhase::write_stage, + false, + false}}; + } + + if (auto f = check_fault(ReplacePhase::rename, false, false)) { + return std::unexpected{std::move(*f)}; + } + + DWORD move_flags = MOVEFILE_REPLACE_EXISTING; + if (options.durability == ReplaceDurability::durable_sync) { + move_flags |= MOVEFILE_WRITE_THROUGH; + } + if (::MoveFileExW(temp_path.c_str(), path.c_str(), move_flags) == 0) { + const DWORD err = ::GetLastError(); + return std::unexpected{ReplaceFailure{ + detail::make_win32_error( + detail::map_win32_error(err), + std::format("FileSystem::replace_file: rename failed for '{}'", + path.string()), + err), + ReplacePhase::rename, + false, + false}}; + } + + // Rename succeeded: target is now visible on disk; never delete target! + cleanup_temp = false; + + if (options.durability == ReplaceDurability::durable_sync) { + if (auto f = check_fault(ReplacePhase::sync_parent, true, true)) { + return std::unexpected{std::move(*f)}; + } + bool flushed = false; + DWORD err = 0; + const HANDLE dir_raw = ::CreateFileW(parent.c_str(), + GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE, + nullptr, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, + nullptr); + if (dir_raw != INVALID_HANDLE_VALUE) { + detail::OwnedHandle dir_handle{dir_raw}; + flushed = ::FlushFileBuffers(dir_handle.get()) != 0; + if (!flushed) { + err = ::GetLastError(); + } + } else { + err = ::GetLastError(); + } + if (!flushed) { + return std::unexpected{ReplaceFailure{ + detail::make_win32_error( + Void::System::SystemErrorCode::durability_unknown, + std::format( + "FileSystem::replace_file: parent dir flush failed after rename for '{}'", + path.string()), + err), + ReplacePhase::sync_parent, + true, + true}}; + } + } + + Void::Log::debug("FileSystem", + "replace_file: '{}' committed ({} bytes)", + path.string(), + bytes.size()); + return {}; #endif } diff --git a/tests/standalone/System/Path.cpp b/tests/standalone/System/Path.cpp index 29f4523..8d93cbb 100644 --- a/tests/standalone/System/Path.cpp +++ b/tests/standalone/System/Path.cpp @@ -3,8 +3,17 @@ #include #include +#include +#include +#include +#include #include +#include +#include #include +#include +#include +#include Void::Testing::Test read_file_returns_contents() { @@ -212,3 +221,196 @@ Void::Testing::Test filesystem_file_lock_symlink_swap_reflink_and_timestamps() kLinkMtime); } } + +namespace +{ + +/// Portable scoped temp directory (TempDir is POSIX-only today, but the +/// replace_file contract must also run on Windows x64). +struct ScopedTestDir +{ + std::filesystem::path path; + + explicit ScopedTestDir(std::string_view label) + { + path = std::filesystem::temp_directory_path() / + std::format("void_path_{}_{:016x}", + label, + Void::FileSystem::detail::next_temp_entropy()); + std::filesystem::create_directories(path); + } + + ~ScopedTestDir() + { + std::error_code ec; + std::filesystem::remove_all(path, ec); + } + + ScopedTestDir(const ScopedTestDir&) = delete; + ScopedTestDir& operator=(const ScopedTestDir&) = delete; +}; + +[[nodiscard]] std::string slurp(const std::filesystem::path& path) +{ + std::ifstream in{path, std::ios::binary}; + return std::string{std::istreambuf_iterator{in}, + std::istreambuf_iterator{}}; +} + +[[nodiscard]] std::size_t entry_count(const std::filesystem::path& dir) +{ + std::size_t count = 0; + for (const auto& entry : std::filesystem::directory_iterator{dir}) { + (void)entry; + ++count; + } + return count; +} + +void seed(const std::filesystem::path& path, std::string_view content) +{ + std::ofstream out{path, std::ios::binary | std::ios::trunc}; + out.write(content.data(), static_cast(content.size())); +} + +} // namespace + +// Contract for replace_file/atomic_write that must hold on every supported +// platform: pre-publication failures preserve the old file, post-publication +// failures report visibility + unknown durability, and staging files never +// outlive a call or endanger the live destination. +Void::Testing::Test replace_file_contract_durability_and_faults() +{ + ScopedTestDir dir{"contract"}; + const auto target = dir.path / "slot.bin"; + + // First creation: there is no previous destination. + { + auto r = Void::FileSystem::replace_file(target, std::string_view{"first"}); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(slurp(target), std::string{"first"}); + Void::Testing::expect_eq(entry_count(dir.path), std::size_t{1}); + } + + // Replacement of an existing destination. + { + auto r = Void::FileSystem::replace_file(target, std::string_view{"second"}); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(slurp(target), std::string{"second"}); + } + + // Failure while staging (before publication): old contents stay readable + // and intact, and the staging file is cleaned up. + { + seed(target, "A"); + Void::FileSystem::ReplaceOptions opts; + opts.fault_hook = [](Void::FileSystem::ReplacePhase phase) + -> std::optional { + if (phase == Void::FileSystem::ReplacePhase::write_stage) { + return EIO; + } + return std::nullopt; + }; + auto r = + Void::FileSystem::replace_file(target, std::string_view{"B"}, opts); + Void::Testing::expect(!r.has_value()); + Void::Testing::expect(r.error().phase == + Void::FileSystem::ReplacePhase::write_stage); + Void::Testing::expect(!r.error().visible_on_disk); + Void::Testing::expect(!r.error().durability_unknown); + Void::Testing::expect_eq(slurp(target), std::string{"A"}); + Void::Testing::expect_eq(entry_count(dir.path), std::size_t{1}); + } + + // Failure injected immediately before the publish operation: the old file + // must remain completely intact. + { + seed(target, "A"); + Void::FileSystem::ReplaceOptions opts; + opts.fault_hook = [](Void::FileSystem::ReplacePhase phase) + -> std::optional { + if (phase == Void::FileSystem::ReplacePhase::rename) { + return EIO; + } + return std::nullopt; + }; + auto r = + Void::FileSystem::replace_file(target, std::string_view{"B"}, opts); + Void::Testing::expect(!r.has_value()); + Void::Testing::expect(r.error().phase == + Void::FileSystem::ReplacePhase::rename); + Void::Testing::expect(!r.error().visible_on_disk); + Void::Testing::expect(!r.error().durability_unknown); + Void::Testing::expect_eq(slurp(target), std::string{"A"}); + Void::Testing::expect_eq(entry_count(dir.path), std::size_t{1}); + } + + // Failure after visibility changed: the new file is visible, durability is + // explicitly unknown, and the live destination is never deleted. + { + seed(target, "A"); + Void::FileSystem::ReplaceOptions opts; + opts.fault_hook = [](Void::FileSystem::ReplacePhase phase) + -> std::optional { + if (phase == Void::FileSystem::ReplacePhase::sync_parent) { + return EIO; + } + return std::nullopt; + }; + auto r = + Void::FileSystem::replace_file(target, std::string_view{"B"}, opts); + Void::Testing::expect(!r.has_value()); + Void::Testing::expect(r.error().phase == + Void::FileSystem::ReplacePhase::sync_parent); + Void::Testing::expect(r.error().visible_on_disk); + Void::Testing::expect(r.error().durability_unknown); + Void::Testing::expect_eq(slurp(target), std::string{"B"}); + Void::Testing::expect_eq(entry_count(dir.path), std::size_t{1}); + } + + // atomic_write is the convenience wrapper over the same publication path. + { + auto r = Void::FileSystem::atomic_write(target, "via atomic_write"); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(slurp(target), std::string{"via atomic_write"}); + } + + // Unicode destination name (UTF-8 on POSIX, UTF-16 on Windows). + { + const auto unicode = dir.path / std::filesystem::path{u8"слот-δ.txt"}; + auto r = + Void::FileSystem::replace_file(unicode, std::string_view{"unicode"}); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(slurp(unicode), std::string{"unicode"}); + } +} + +// Concurrent writers must never expose partial contents and must not leave +// staging files behind (exclusive temporary names + atomic publication). +Void::Testing::Test replace_file_concurrent_writers_are_atomic() +{ + ScopedTestDir dir{"concurrent"}; + const auto target = dir.path / "slot.bin"; + seed(target, "initial"); + + std::vector writers; + for (int t = 0; t < 4; ++t) { + writers.emplace_back([&target, t] { + const std::string payload(4096, + static_cast('a' + t)); + for (int i = 0; i < 20; ++i) { + (void)Void::FileSystem::replace_file( + target, std::string_view{payload}); + } + }); + } + for (auto& writer : writers) { + writer.join(); + } + + const std::string content = slurp(target); + Void::Testing::expect_eq(content.size(), std::size_t{4096}); + Void::Testing::expect(content.find_first_not_of(content.front()) == + std::string::npos); + Void::Testing::expect_eq(entry_count(dir.path), std::size_t{1}); +}