Author SHA1 Message Date
faumaray 34cfd9cb39 Merge pull request 'Deterministic package resolver with source diagnostics (#4)' (#20) from issue/4-package-resolver into main 2026-12-03 08:08:15 +00:00
faumaray 72733e2b93 Merge pull request 'Bounded Windows read coverage and sharing documentation (#9)' (#25) from issue/9-windows-bounded-read into main 2026-12-03 08:08:13 +00:00
faumaray dc18d64b18 Merge pull request 'Windows x64 transactional file replacement (#3)' (#19) from issue/3-windows-transactional-replace into main 2026-12-03 08:08:02 +00:00
selikhov f3176c2b54 feat(System): bounded Windows read through one handle, with coverage (#9)
The Windows read_file_bounded path was implemented together with #3 using
a single CreateFileW handle. This adds the #9 acceptance coverage and
documents the contract:

- The size is checked before allocation and every chunk is re-checked, so
  growth after the initial size check still fails with limit_exceeded and
  never returns partial contents.
- Windows shares read/write/delete, so another process may append,
  rename or replace the path while a background read is pending; the
  read continues from the opened handle and sees one coherent version.
- Tests: empty, binary, Unicode path, exact limit, over limit before
  reading, and (POSIX) a stream that grows past the limit mid-read.
2026-12-03 09:45:14 +03:00
selikhov d30384d981 feat(Update): deterministic package resolver with diagnostics (#4)
- resolve_packages() takes caller-supplied package descriptions (id,
  exact version, content digest, exclusive capabilities, dependency
  ranges) plus selected root ids and returns an exact dependency set.
- Deterministic: canonical input ordering, descending SemVer candidate
  order and canonical requirement order make the result invariant under
  permutation of installed/selected input.
- Frozen PackageIdentity compares build metadata and content digest in
  addition to SemVer precedence, so equal-precedence rebuilds are never
  conflated; ambiguous same-id/same-precedence inputs are rejected.
- Actionable diagnostics carry kind, input package, field
  (e.g. dependencies[1].range) and related id: missing dependency,
  incompatible version, cycle, ambiguity, competing exclusive providers.
- Bounded package/edge/search-node limits with backtracking search.
- 13 standalone tests cover closure, order invariance, diagnostics,
  backtracking, cycles, capabilities, frozen identity and limits.
2026-12-03 09:38:27 +03:00
selikhov 51ceb081ac 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.
2026-12-03 09:34:50 +03:00
faumaray 7b0fea6095 Merge branch 'feat/roadmap-p2-wave11' (Wave 11 Async, Time, IO, Runtime execution-path completion) 2026-12-01 22:33:50 +03:00
4 changed files with 1729 additions and 20 deletions

No files matched your search

+549 -20
View File
@@ -36,6 +36,14 @@
#include <linux/fs.h>
#endif
#endif
#else
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#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,7 +150,156 @@ 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<char*>(&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.
///
/// The file is opened once and read through that single handle. The size is
/// checked before allocation and every chunk is checked again while reading,
/// so a file that grows after the initial size check still fails with
/// `limit_exceeded` and never returns partial contents.
///
/// Sharing: POSIX opens read-only; Windows opens with
/// `FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE`, so another process
/// may append, rename or replace the path while a background read is pending.
/// The read continues from the already opened handle and sees one coherent
/// version of the file (the one that was opened), not a mixture with the
/// replacement. On both platforms the path is resolved once at open time.
[[nodiscard]] inline Void::Result::Result<std::string, Void::Result::Error>
read_file_bounded(const std::filesystem::path& path,
ReadFileOptions options = {})
@@ -177,11 +366,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<std::uint64_t>(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<std::uint64_t>(size.QuadPart),
options.max_bytes))};
}
std::string content;
std::array<char, 8192> buffer{};
for (;;) {
DWORD read = 0;
if (::ReadFile(handle.get(),
buffer.data(),
static_cast<DWORD>(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<std::size_t>(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 +484,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<DWORD>(
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 +767,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<ReplaceFailure> {
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<int>(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<DWORD>(
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
}
+634
View File
@@ -0,0 +1,634 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/Text/Semver.hpp>
#include <algorithm>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <format>
#include <functional>
#include <map>
#include <optional>
#include <set>
#include <span>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Void::Update
{
inline constexpr std::size_t kDefaultMaxResolvedPackages = 64;
inline constexpr std::size_t kDefaultMaxResolvedEdges = 256;
inline constexpr std::size_t kDefaultMaxResolutionNodes = 100'000;
/// One dependency edge: the required package id and the accepted versions.
struct PackageDependency {
std::string id;
Void::Semver::VersionRange range;
};
/// Caller-supplied description of one installed package version.
///
/// Each entry in `capabilities` is *exclusive*: at most one resolved package
/// may provide a given capability. `content_digest` is opaque to the resolver
/// (for example `sha256:...`) but participates in the frozen identity.
struct PackageDescription {
std::string id;
Void::Semver::Version version;
std::string content_digest;
std::vector<std::string> capabilities;
std::vector<PackageDependency> dependencies;
};
/// Frozen identity of a resolved package.
///
/// Unlike `Void::Semver::Version::operator==`, equality (and ordering) here
/// includes SemVer build metadata and the content digest, so a rebuild that
/// only changes `+metadata` or the digest is never mistaken for the same
/// package even though its SemVer precedence is equal.
struct PackageIdentity {
std::string id;
Void::Semver::Version version;
std::string content_digest;
[[nodiscard]] std::strong_ordering
operator<=>(const PackageIdentity& other) const noexcept
{
if (const auto comparison = id <=> other.id; comparison != 0) {
return comparison;
}
// Precedence first, then build metadata, then digest: a total order.
if (const auto comparison = version <=> other.version;
comparison != 0) {
return comparison;
}
if (const auto comparison = version.build <=> other.version.build;
comparison != 0) {
return comparison;
}
return content_digest <=> other.content_digest;
}
[[nodiscard]] bool operator==(const PackageIdentity& other) const noexcept
{
return (*this <=> other) == 0;
}
};
struct ResolvedPackage {
PackageIdentity identity;
std::vector<std::string> capabilities;
};
struct Resolution {
/// Sorted by frozen identity; capabilities are sorted and deduplicated.
std::vector<ResolvedPackage> packages;
};
enum class ResolutionErrorKind : std::uint8_t {
invalid_request = 0,
missing_dependency,
incompatible_version,
cyclic_dependency,
ambiguous_package,
exclusive_capability_conflict,
limit_exceeded,
search_exhausted,
};
/// Actionable failure. `package` names the input package (or requested id) and
/// `field` the exact field, e.g. `dependencies[1].range`.
struct ResolutionDiagnostic {
ResolutionErrorKind kind{ResolutionErrorKind::invalid_request};
std::string package;
std::string field;
std::string related;
std::string message;
};
struct ResolutionLimits {
std::size_t max_packages{kDefaultMaxResolvedPackages};
std::size_t max_edges{kDefaultMaxResolvedEdges};
std::size_t max_search_nodes{kDefaultMaxResolutionNodes};
};
struct ResolutionRequest {
std::span<const PackageDescription> installed;
/// Root package ids; each is resolved as `*`.
std::span<const std::string> selected;
ResolutionLimits limits{};
};
namespace Detail
{
struct Requirement {
std::string id;
Void::Semver::VersionRange range;
std::string requester;
std::string field;
[[nodiscard]] bool operator<(const Requirement& other) const noexcept
{
if (const auto comparison = id <=> other.id; comparison != 0) {
return comparison < 0;
}
if (const auto comparison = requester <=> other.requester;
comparison != 0) {
return comparison < 0;
}
return field < other.field;
}
};
struct SearchContext {
const std::map<std::string, std::vector<PackageDescription>>& available;
ResolutionLimits limits;
std::size_t nodes{0};
bool node_limit_hit{false};
std::optional<ResolutionDiagnostic> best;
std::size_t best_depth{0};
void record(ResolutionDiagnostic diagnostic, std::size_t depth)
{
const bool better = !best.has_value() || depth > best_depth ||
(depth == best_depth && diagnose_less(diagnostic, *best));
if (better) {
best = std::move(diagnostic);
best_depth = depth;
}
}
static bool diagnose_less(const ResolutionDiagnostic& lhs,
const ResolutionDiagnostic& rhs) noexcept
{
if (const auto comparison =
static_cast<std::uint8_t>(lhs.kind) <=>
static_cast<std::uint8_t>(rhs.kind);
comparison != 0) {
return comparison < 0;
}
if (const auto comparison = lhs.package <=> rhs.package;
comparison != 0) {
return comparison < 0;
}
if (const auto comparison = lhs.field <=> rhs.field; comparison != 0) {
return comparison < 0;
}
return lhs.related < rhs.related;
}
};
using Assignment = std::map<std::string, std::size_t>;
[[nodiscard]] inline std::optional<ResolutionDiagnostic>
check_capabilities(const Assignment& assignment,
const SearchContext& context)
{
std::map<std::string, std::vector<std::string>> providers;
for (const auto& [id, index] : assignment) {
const auto& package = context.available.at(id)[index];
std::vector<std::string> capabilities = package.capabilities;
std::sort(capabilities.begin(), capabilities.end());
capabilities.erase(
std::unique(capabilities.begin(), capabilities.end()),
capabilities.end());
for (const auto& capability : capabilities) {
providers[capability].push_back(id);
}
}
for (const auto& [capability, owners] : providers) {
if (owners.size() > 1) {
return ResolutionDiagnostic{
.kind = ResolutionErrorKind::exclusive_capability_conflict,
.package = owners[0],
.field = "capabilities",
.related = owners[1],
.message = std::format(
"exclusive capability '{}' is provided by both '{}' and '{}'",
capability,
owners[0],
owners[1])};
}
}
return std::nullopt;
}
[[nodiscard]] inline std::optional<ResolutionDiagnostic>
check_cycle(const Assignment& assignment, const SearchContext& context)
{
std::map<std::string, int> color; // 0 unseen, 1 on stack, 2 done
std::vector<std::string> stack;
const std::function<std::optional<ResolutionDiagnostic>(
const std::string&)>
visit = [&](const std::string& id)
-> std::optional<ResolutionDiagnostic> {
color[id] = 1;
stack.push_back(id);
const auto& package =
context.available.at(id)[assignment.at(id)];
std::vector<std::string> dependencies;
for (const auto& dependency : package.dependencies) {
if (assignment.contains(dependency.id)) {
dependencies.push_back(dependency.id);
}
}
std::sort(dependencies.begin(), dependencies.end());
dependencies.erase(std::unique(dependencies.begin(),
dependencies.end()),
dependencies.end());
for (const auto& dependency : dependencies) {
if (color[dependency] == 1) {
std::string path;
const auto begin =
std::find(stack.begin(), stack.end(), dependency);
for (auto it = begin; it != stack.end(); ++it) {
path += *it;
path += " -> ";
}
path += dependency;
return ResolutionDiagnostic{
.kind = ResolutionErrorKind::cyclic_dependency,
.package = dependency,
.field = "dependencies",
.related = path,
.message =
std::format("cyclic dependency detected: {}", path)};
}
if (color[dependency] == 0) {
if (auto diagnostic = visit(dependency)) {
return diagnostic;
}
}
}
stack.pop_back();
color[id] = 2;
return std::nullopt;
};
for (const auto& [id, index] : assignment) {
(void)index;
if (color[id] == 0) {
if (auto diagnostic = visit(id)) {
return diagnostic;
}
}
}
return std::nullopt;
}
[[nodiscard]] inline bool
solve(const Assignment& assignment,
std::vector<Requirement> pending,
SearchContext& context,
Assignment& solution)
{
if (context.node_limit_hit) {
return false;
}
if (++context.nodes > context.limits.max_search_nodes) {
context.node_limit_hit = true;
return false;
}
if (assignment.size() > context.limits.max_packages) {
context.record(
ResolutionDiagnostic{
.kind = ResolutionErrorKind::limit_exceeded,
.field = "limits.max_packages",
.message = std::format(
"resolved package count exceeds the limit of {}",
context.limits.max_packages)},
assignment.size());
return false;
}
std::size_t edges = 0;
for (const auto& [id, index] : assignment) {
edges += context.available.at(id)[index].dependencies.size();
}
if (edges > context.limits.max_edges) {
context.record(
ResolutionDiagnostic{
.kind = ResolutionErrorKind::limit_exceeded,
.field = "limits.max_edges",
.message = std::format(
"resolved dependency edge count exceeds the limit of {}",
context.limits.max_edges)},
assignment.size());
return false;
}
if (pending.empty()) {
if (auto diagnostic = check_capabilities(assignment, context)) {
context.record(std::move(*diagnostic), assignment.size());
return false;
}
if (auto diagnostic = check_cycle(assignment, context)) {
context.record(std::move(*diagnostic), assignment.size());
return false;
}
solution = assignment;
return true;
}
const auto next = std::min_element(pending.begin(), pending.end());
const Requirement requirement = *next;
pending.erase(next);
const auto found = context.available.find(requirement.id);
if (found == context.available.end()) {
context.record(
ResolutionDiagnostic{
.kind = ResolutionErrorKind::missing_dependency,
.package = requirement.requester.empty()
? requirement.id
: requirement.requester,
.field = requirement.field,
.related = requirement.id,
.message = std::format(
"required package '{}' is not installed", requirement.id)},
assignment.size());
return false;
}
if (const auto existing = assignment.find(requirement.id);
existing != assignment.end()) {
const auto& package = found->second[existing->second];
if (requirement.range.contains(package.version)) {
return solve(assignment, std::move(pending), context, solution);
}
context.record(
ResolutionDiagnostic{
.kind = ResolutionErrorKind::incompatible_version,
.package = requirement.requester.empty()
? requirement.id
: requirement.requester,
.field = requirement.field,
.related = requirement.id,
.message = std::format(
"selected '{}' version {} does not satisfy the requested range",
requirement.id,
package.version.to_string())},
assignment.size());
return false;
}
bool any_candidate = false;
for (std::size_t index = 0; index < found->second.size(); ++index) {
const auto& package = found->second[index];
if (!requirement.range.contains(package.version)) {
continue;
}
any_candidate = true;
Assignment next_assignment = assignment;
next_assignment.emplace(requirement.id, index);
std::vector<Requirement> next_pending = pending;
for (std::size_t dependency_index = 0;
dependency_index < package.dependencies.size();
++dependency_index) {
const auto& dependency = package.dependencies[dependency_index];
next_pending.push_back(Requirement{
.id = dependency.id,
.range = dependency.range,
.requester = package.id,
.field = std::format("dependencies[{}].range",
dependency_index)});
}
if (solve(next_assignment,
std::move(next_pending),
context,
solution)) {
return true;
}
if (context.node_limit_hit) {
return false;
}
}
context.record(
ResolutionDiagnostic{
.kind = ResolutionErrorKind::incompatible_version,
.package = requirement.requester.empty() ? requirement.id
: requirement.requester,
.field = requirement.field,
.related = requirement.id,
.message = any_candidate
? std::format(
"no candidate for '{}' is consistent with the rest of the dependency set",
requirement.id)
: std::format(
"no installed version of '{}' satisfies the requested range",
requirement.id)},
assignment.size());
return false;
}
} // namespace Detail
/// Resolve `request.selected` and their transitive dependencies into an exact,
/// deterministic package set.
///
/// The result is invariant under permutation of `installed` and `selected`.
/// Candidates are tried in descending SemVer precedence (ties broken by build
/// metadata and digest) and requirements are processed in a canonical order.
/// Caller-supplied content digests and versions are retained verbatim; no
/// game-specific schema is assumed.
[[nodiscard]] inline Void::Result::Result<Resolution, ResolutionDiagnostic>
resolve_packages(const ResolutionRequest& request)
{
using namespace Detail;
if (request.limits.max_packages == 0 ||
request.limits.max_edges == 0 ||
request.limits.max_search_nodes == 0) {
return std::unexpected{ResolutionDiagnostic{
.kind = ResolutionErrorKind::invalid_request,
.field = "limits",
.message = "resolution limits must be non-zero"}};
}
// Deterministic canonical input order: everything downstream is
// permutation-invariant.
std::vector<PackageDescription> installed{request.installed.begin(),
request.installed.end()};
std::sort(installed.begin(),
installed.end(),
[](const PackageDescription& lhs, const PackageDescription& rhs) {
const PackageIdentity left{lhs.id, lhs.version,
lhs.content_digest};
const PackageIdentity right{rhs.id, rhs.version,
rhs.content_digest};
return left < right;
});
std::map<std::string, std::vector<PackageDescription>> available;
for (const auto& package : installed) {
if (package.id.empty()) {
return std::unexpected{ResolutionDiagnostic{
.kind = ResolutionErrorKind::invalid_request,
.field = "id",
.message = "package id must not be empty"}};
}
if (package.content_digest.empty()) {
return std::unexpected{ResolutionDiagnostic{
.kind = ResolutionErrorKind::invalid_request,
.package = package.id,
.field = "content_digest",
.message = "package content digest must not be empty"}};
}
for (std::size_t index = 0; index < package.capabilities.size();
++index) {
if (package.capabilities[index].empty()) {
return std::unexpected{ResolutionDiagnostic{
.kind = ResolutionErrorKind::invalid_request,
.package = package.id,
.field = std::format("capabilities[{}]", index),
.message = "capability name must not be empty"}};
}
}
for (std::size_t index = 0; index < package.dependencies.size();
++index) {
if (package.dependencies[index].id.empty()) {
return std::unexpected{ResolutionDiagnostic{
.kind = ResolutionErrorKind::invalid_request,
.package = package.id,
.field =
std::format("dependencies[{}].id", index),
.message = "dependency id must not be empty"}};
}
}
available[package.id].push_back(package);
}
// Reject ambiguous inputs: same id and equal SemVer precedence but a
// different frozen identity (build metadata or digest).
for (auto& [id, candidates] : available) {
std::sort(candidates.begin(),
candidates.end(),
[](const PackageDescription& lhs,
const PackageDescription& rhs) {
if (const auto comparison = rhs.version <=> lhs.version;
comparison != 0) {
return comparison < 0;
}
if (const auto comparison =
rhs.version.build <=> lhs.version.build;
comparison != 0) {
return comparison < 0;
}
return rhs.content_digest < lhs.content_digest;
});
for (std::size_t index = 1; index < candidates.size(); ++index) {
const auto& previous = candidates[index - 1];
const auto& current = candidates[index];
if ((previous.version <=> current.version) == 0 &&
!(PackageIdentity{previous.id, previous.version,
previous.content_digest} ==
PackageIdentity{current.id, current.version,
current.content_digest})) {
return std::unexpected{ResolutionDiagnostic{
.kind = ResolutionErrorKind::ambiguous_package,
.package = id,
.field = "version",
.related = current.content_digest,
.message = std::format(
"ambiguous installed '{}': {} and {} have equal SemVer precedence but different build metadata or digest",
id,
previous.version.to_string(),
current.version.to_string())}};
}
}
// Identical frozen identities are the same package: keep one.
candidates.erase(
std::unique(candidates.begin(),
candidates.end(),
[](const PackageDescription& lhs,
const PackageDescription& rhs) {
return PackageIdentity{
lhs.id, lhs.version,
lhs.content_digest} ==
PackageIdentity{
rhs.id, rhs.version,
rhs.content_digest};
}),
candidates.end());
}
const auto any_range = Void::Semver::VersionRange::parse("*");
if (!any_range.has_value()) {
return std::unexpected{ResolutionDiagnostic{
.kind = ResolutionErrorKind::invalid_request,
.field = "range",
.message = "the always-matching range could not be constructed"}};
}
std::vector<Requirement> pending;
std::set<std::string> roots;
for (std::size_t index = 0; index < request.selected.size(); ++index) {
const auto& id = request.selected[index];
if (id.empty()) {
return std::unexpected{ResolutionDiagnostic{
.kind = ResolutionErrorKind::invalid_request,
.field = std::format("selected[{}]", index),
.message = "selected package id must not be empty"}};
}
if (!roots.insert(id).second) {
continue;
}
pending.push_back(Requirement{
.id = id,
.range = *any_range,
.requester = {},
.field = std::format("selected[{}]", index)});
}
SearchContext context{available, request.limits};
Assignment solution;
if (!solve(Assignment{}, std::move(pending), context, solution)) {
if (context.best.has_value()) {
return std::unexpected{std::move(*context.best)};
}
return std::unexpected{ResolutionDiagnostic{
.kind = context.node_limit_hit
? ResolutionErrorKind::search_exhausted
: ResolutionErrorKind::incompatible_version,
.field = "limits.max_search_nodes",
.message = "resolution search did not produce a package set"}};
}
Resolution resolution;
resolution.packages.reserve(solution.size());
for (const auto& [id, index] : solution) {
const auto& package = available.at(id)[index];
std::vector<std::string> capabilities = package.capabilities;
std::sort(capabilities.begin(), capabilities.end());
capabilities.erase(
std::unique(capabilities.begin(), capabilities.end()),
capabilities.end());
resolution.packages.push_back(ResolvedPackage{
.identity = PackageIdentity{package.id,
package.version,
package.content_digest},
.capabilities = std::move(capabilities)});
}
return resolution;
}
/// Convenience: build a dependency from an id and a SemVer range expression.
[[nodiscard]] inline std::optional<PackageDependency>
make_package_dependency(std::string id, std::string_view range)
{
auto parsed = Void::Semver::VersionRange::parse(range);
if (!parsed.has_value()) {
return std::nullopt;
}
return PackageDependency{.id = std::move(id), .range = std::move(*parsed)};
}
} // namespace Void::Update
+278
View File
@@ -3,8 +3,17 @@
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <cerrno>
#include <cstdint>
#include <filesystem>
#include <format>
#include <fstream>
#include <iterator>
#include <optional>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
Void::Testing::Test read_file_returns_contents()
{
@@ -212,3 +221,272 @@ 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<char>{in},
std::istreambuf_iterator<char>{}};
}
[[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<std::streamsize>(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<int> {
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<int> {
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<int> {
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<std::thread> writers;
for (int t = 0; t < 4; ++t) {
writers.emplace_back([&target, t] {
const std::string payload(4096,
static_cast<char>('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});
}
// Issue #9: read_file_bounded uses one handle, checks the cap before
// allocation and again on every chunk, and handles empty/binary/Unicode paths.
Void::Testing::Test read_file_bounded_handles_empty_binary_and_limits()
{
ScopedTestDir dir{"bounded"};
const auto empty = dir.path / "empty.bin";
seed(empty, "");
auto empty_result = Void::FileSystem::read_file_bounded(empty);
Void::Testing::require(empty_result.has_value());
Void::Testing::expect(empty_result->empty());
const std::string binary{"\x00\x01\x02\xff\x00", 5};
const auto binary_path = dir.path / "binary.bin";
seed(binary_path, binary);
auto binary_result = Void::FileSystem::read_file_bounded(binary_path);
Void::Testing::require(binary_result.has_value());
Void::Testing::expect_eq(*binary_result, binary);
const auto unicode = dir.path / std::filesystem::path{u8"данные-δ.bin"};
seed(unicode, "unicode payload");
auto unicode_result = Void::FileSystem::read_file_bounded(unicode);
Void::Testing::require(unicode_result.has_value());
Void::Testing::expect_eq(*unicode_result, std::string{"unicode payload"});
const auto data = dir.path / "data.bin";
seed(data, std::string(16, 'x'));
// Exactly at the limit is accepted.
auto exact = Void::FileSystem::read_file_bounded(data, {.max_bytes = 16});
Void::Testing::require(exact.has_value());
Void::Testing::expect_eq(exact->size(), std::size_t{16});
// One byte over is rejected by the pre-allocation size check.
auto over = Void::FileSystem::read_file_bounded(data, {.max_bytes = 15});
Void::Testing::require(!over.has_value());
Void::Testing::expect(over.error().message().find("limit") !=
std::string::npos);
}
#ifndef _WIN32
// A stream that keeps producing data after open must be cut off by the
// per-chunk check even though it has no initial size to validate.
Void::Testing::Test read_file_bounded_rejects_growth_past_limit()
{
ScopedTestDir dir{"bounded_growth"};
const auto fifo = dir.path / "stream";
Void::Testing::require(::mkfifo(fifo.c_str(), 0600) == 0);
std::thread writer{[&fifo] {
const int fd = ::open(fifo.c_str(), O_WRONLY);
if (fd < 0) {
return;
}
const std::string payload(64, 'z');
std::size_t offset = 0;
while (offset < payload.size()) {
const ssize_t written =
::write(fd, payload.data() + offset, payload.size() - offset);
if (written <= 0) {
break;
}
offset += static_cast<std::size_t>(written);
}
(void)::close(fd);
}};
auto result = Void::FileSystem::read_file_bounded(fifo, {.max_bytes = 8});
writer.join();
Void::Testing::require(!result.has_value());
Void::Testing::expect(result.error().message().find("limit") !=
std::string::npos);
}
#endif
+268
View File
@@ -0,0 +1,268 @@
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Update/Resolver.hpp>
#include <algorithm>
#include <optional>
#include <string>
#include <tuple>
#include <vector>
namespace
{
using Void::Update::PackageDependency;
using Void::Update::PackageDescription;
using Void::Update::Resolution;
using Void::Update::ResolutionDiagnostic;
using Void::Update::ResolutionRequest;
using Void::Semver::Version;
[[nodiscard]] Version version(std::string_view text)
{
return *Void::Semver::parse_strict(text);
}
[[nodiscard]] PackageDependency dependency(std::string_view id,
std::string_view range)
{
auto parsed = Void::Update::make_package_dependency(std::string{id}, range);
return *parsed;
}
[[nodiscard]] PackageDescription package(
std::string id,
std::string_view version_text,
std::string digest,
std::vector<std::string> capabilities = {},
std::vector<PackageDependency> dependencies = {})
{
return PackageDescription{.id = std::move(id),
.version = version(version_text),
.content_digest = std::move(digest),
.capabilities = std::move(capabilities),
.dependencies = std::move(dependencies)};
}
using Summary = std::tuple<std::string, std::string, std::string>;
[[nodiscard]] std::vector<Summary> summarize(const Resolution& resolution)
{
std::vector<Summary> out;
for (const auto& entry : resolution.packages) {
out.emplace_back(entry.identity.id,
entry.identity.version.to_string(),
entry.identity.content_digest);
}
return out;
}
[[nodiscard]] std::vector<std::string> selected(std::initializer_list<const char*> ids)
{
std::vector<std::string> out;
for (const char* id : ids) {
out.push_back(id);
}
return out;
}
} // namespace
Void::Testing::Test resolve_packages_transitive_closure()
{
std::vector<PackageDescription> installed{
package("app", "1.0.0", "d-app", {}, {dependency("lib", "^1.0")}),
package("lib", "1.0.0", "d-lib-1"),
package("lib", "1.1.0", "d-lib-2"),
package("lib", "2.0.0", "d-lib-3"),
};
auto roots = selected({"app"});
auto result = Void::Update::resolve_packages(
ResolutionRequest{.installed = installed, .selected = roots});
Void::Testing::require(result.has_value());
const auto summary = summarize(*result);
Void::Testing::require(summary.size() == 2);
Void::Testing::expect_eq(std::get<0>(summary[0]), std::string{"app"});
Void::Testing::expect_eq(std::get<0>(summary[1]), std::string{"lib"});
Void::Testing::expect_eq(std::get<1>(summary[1]), std::string{"1.1.0"});
Void::Testing::expect_eq(std::get<2>(summary[1]), std::string{"d-lib-2"});
}
Void::Testing::Test resolve_packages_is_order_invariant()
{
std::vector<PackageDescription> installed{
package("app", "1.0.0", "d-app", {}, {dependency("lib", "^1.0")}),
package("lib", "1.0.0", "d-lib-1"),
package("lib", "1.1.0", "d-lib-2"),
};
auto roots = selected({"app"});
const auto first = Void::Update::resolve_packages(
ResolutionRequest{.installed = installed, .selected = roots});
std::reverse(installed.begin(), installed.end());
const auto second = Void::Update::resolve_packages(
ResolutionRequest{.installed = installed, .selected = roots});
Void::Testing::require(first.has_value() && second.has_value());
Void::Testing::expect(summarize(*first) == summarize(*second));
}
Void::Testing::Test resolve_packages_missing_dependency()
{
std::vector<PackageDescription> installed{
package("app", "1.0.0", "d-app", {}, {dependency("gone", "^1.0")})};
auto roots = selected({"app"});
auto result = Void::Update::resolve_packages(
ResolutionRequest{.installed = installed, .selected = roots});
Void::Testing::require(!result.has_value());
Void::Testing::expect(result.error().kind ==
Void::Update::ResolutionErrorKind::missing_dependency);
Void::Testing::expect_eq(result.error().package, std::string{"app"});
Void::Testing::expect_eq(result.error().field,
std::string{"dependencies[0].range"});
Void::Testing::expect_eq(result.error().related, std::string{"gone"});
}
Void::Testing::Test resolve_packages_incompatible_version()
{
std::vector<PackageDescription> installed{
package("app", "1.0.0", "d-app", {}, {dependency("lib", "^2.0")}),
package("lib", "1.0.0", "d-lib")};
auto roots = selected({"app"});
auto result = Void::Update::resolve_packages(
ResolutionRequest{.installed = installed, .selected = roots});
Void::Testing::require(!result.has_value());
Void::Testing::expect(result.error().kind ==
Void::Update::ResolutionErrorKind::incompatible_version);
Void::Testing::expect_eq(result.error().related, std::string{"lib"});
}
Void::Testing::Test resolve_packages_backtracks_for_constraints()
{
std::vector<PackageDescription> installed{
package("app", "1.0.0", "d-app", {}, {dependency("lib", "=1.0.0")}),
package("lib", "1.0.0", "d-lib-1"),
package("lib", "1.1.0", "d-lib-2")};
auto roots = selected({"app", "lib"});
auto result = Void::Update::resolve_packages(
ResolutionRequest{.installed = installed, .selected = roots});
Void::Testing::require(result.has_value());
const auto summary = summarize(*result);
Void::Testing::require(summary.size() == 2);
Void::Testing::expect_eq(std::get<1>(summary[1]), std::string{"1.0.0"});
}
Void::Testing::Test resolve_packages_detects_cycle()
{
std::vector<PackageDescription> installed{
package("a", "1.0.0", "d-a", {}, {dependency("b", "*")}),
package("b", "1.0.0", "d-b", {}, {dependency("a", "*")})};
auto roots = selected({"a"});
auto result = Void::Update::resolve_packages(
ResolutionRequest{.installed = installed, .selected = roots});
Void::Testing::require(!result.has_value());
Void::Testing::expect(result.error().kind ==
Void::Update::ResolutionErrorKind::cyclic_dependency);
Void::Testing::expect_eq(result.error().related, std::string{"a -> b -> a"});
}
Void::Testing::Test resolve_packages_rejects_ambiguous_identity()
{
std::vector<PackageDescription> installed{
package("lib", "1.0.0+one", "d-one"),
package("lib", "1.0.0+two", "d-two")};
auto roots = selected({"lib"});
auto result = Void::Update::resolve_packages(
ResolutionRequest{.installed = installed, .selected = roots});
Void::Testing::require(!result.has_value());
Void::Testing::expect(result.error().kind ==
Void::Update::ResolutionErrorKind::ambiguous_package);
Void::Testing::expect_eq(result.error().package, std::string{"lib"});
}
Void::Testing::Test resolve_packages_rejects_competing_exclusive_capabilities()
{
std::vector<PackageDescription> installed{
package("gpu-a", "1.0.0", "d-a", {"gpu"}),
package("gpu-b", "1.0.0", "d-b", {"gpu"})};
auto roots = selected({"gpu-a", "gpu-b"});
auto result = Void::Update::resolve_packages(
ResolutionRequest{.installed = installed, .selected = roots});
Void::Testing::require(!result.has_value());
Void::Testing::expect(
result.error().kind ==
Void::Update::ResolutionErrorKind::exclusive_capability_conflict);
Void::Testing::expect_eq(result.error().package, std::string{"gpu-a"});
Void::Testing::expect_eq(result.error().related, std::string{"gpu-b"});
}
Void::Testing::Test resolve_packages_frozen_identity_includes_build_and_digest()
{
const Void::Update::PackageIdentity base{.id = "lib",
.version = version("1.0.0+build.1"),
.content_digest = "sha256:a"};
auto changed_build = base;
changed_build.version = version("1.0.0+build.2");
auto changed_digest = base;
changed_digest.content_digest = "sha256:b";
Void::Testing::expect(!(base == changed_build));
Void::Testing::expect(!(base == changed_digest));
Void::Testing::expect(base == base);
// SemVer precedence alone treats both as equal; the frozen identity must not.
Void::Testing::expect((base.version <=> changed_build.version) == 0);
}
Void::Testing::Test resolve_packages_same_precedence_distinct_digest_is_ambiguous()
{
std::vector<PackageDescription> installed{
package("lib", "1.0.0+build.1", "sha256:a"),
package("lib", "1.0.0+build.1", "sha256:b")};
auto roots = selected({"lib"});
auto result = Void::Update::resolve_packages(
ResolutionRequest{.installed = installed, .selected = roots});
Void::Testing::require(!result.has_value());
Void::Testing::expect(result.error().kind ==
Void::Update::ResolutionErrorKind::ambiguous_package);
}
Void::Testing::Test resolve_packages_rejects_empty_fields()
{
std::vector<PackageDescription> installed{
package("lib", "1.0.0", "")};
auto roots = selected({"lib"});
auto result = Void::Update::resolve_packages(
ResolutionRequest{.installed = installed, .selected = roots});
Void::Testing::require(!result.has_value());
Void::Testing::expect(result.error().kind ==
Void::Update::ResolutionErrorKind::invalid_request);
Void::Testing::expect_eq(result.error().field,
std::string{"content_digest"});
}
Void::Testing::Test resolve_packages_enforces_package_limit()
{
std::vector<PackageDescription> installed{
package("app", "1.0.0", "d-app", {}, {dependency("lib", "*")}),
package("lib", "1.0.0", "d-lib")};
auto roots = selected({"app"});
Void::Update::ResolutionLimits limits;
limits.max_packages = 1;
auto result = Void::Update::resolve_packages(
ResolutionRequest{.installed = installed,
.selected = roots,
.limits = limits});
Void::Testing::require(!result.has_value());
Void::Testing::expect(result.error().kind ==
Void::Update::ResolutionErrorKind::limit_exceeded);
}
Void::Testing::Test resolve_packages_deduplicates_identical_descriptions()
{
std::vector<PackageDescription> installed{
package("lib", "1.0.0", "d-lib"),
package("lib", "1.0.0", "d-lib")};
auto roots = selected({"lib"});
auto result = Void::Update::resolve_packages(
ResolutionRequest{.installed = installed, .selected = roots});
Void::Testing::require(result.has_value());
Void::Testing::expect_eq(result->packages.size(), std::size_t{1});
}