From 6b3dededacf04105061f603a8c79e4dcebdf264d Mon Sep 17 00:00:00 2001 From: faumaray Date: Thu, 26 Nov 2026 15:57:01 +0300 Subject: [PATCH 1/9] chore(wave8): reserve lifecycle error domains, support .h headers, add task specs --- cmake/Module.cmake | 4 +++- .../tasks/M-CONFIGURATION-01-05.md | 21 ++++++++++++++++ docs/agent-workflow/tasks/M-FSM-01-05.md | 24 +++++++++++++++++++ docs/agent-workflow/tasks/M-PLUGIN-01-06.md | 19 +++++++++++++++ docs/agent-workflow/tasks/M-SERVICE-01-05.md | 22 +++++++++++++++++ include/Void/Functional/Error.hpp | 4 ++++ 6 files changed, 93 insertions(+), 1 deletion(-) create mode 100644 docs/agent-workflow/tasks/M-CONFIGURATION-01-05.md create mode 100644 docs/agent-workflow/tasks/M-FSM-01-05.md create mode 100644 docs/agent-workflow/tasks/M-PLUGIN-01-06.md create mode 100644 docs/agent-workflow/tasks/M-SERVICE-01-05.md diff --git a/cmake/Module.cmake b/cmake/Module.cmake index 365669d..a22652a 100644 --- a/cmake/Module.cmake +++ b/cmake/Module.cmake @@ -12,7 +12,9 @@ function(void_add_module MODULE_NAME) set(ALIAS ${PROJECT_NAME}::${MODULE_NAME}) file(GLOB_RECURSE SRC CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/${MODULE_NAME}/*.cpp") - file(GLOB_RECURSE HDR CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.hpp") + file(GLOB_RECURSE HDR CONFIGURE_DEPENDS + "${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.hpp" + "${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.h") foreach(_excl IN LISTS ARG_EXCLUDE_HEADERS) list(REMOVE_ITEM HDR "${CMAKE_CURRENT_SOURCE_DIR}/include/${_excl}") endforeach() diff --git a/docs/agent-workflow/tasks/M-CONFIGURATION-01-05.md b/docs/agent-workflow/tasks/M-CONFIGURATION-01-05.md new file mode 100644 index 0000000..4fdb092 --- /dev/null +++ b/docs/agent-workflow/tasks/M-CONFIGURATION-01-05.md @@ -0,0 +1,21 @@ +# M-CONFIGURATION-01..05 — Bounded Schemas, Provenance Redaction & Transactional Async Reload + +- **Wave**: Wave 8 (`feat/roadmap-p2-wave8`, branched from `main` at `d83d0f4`) +- **Roadmap reference**: `docs/roadmap/modules/Configuration.md`, `docs/roadmap/DEPENDENCIES.md` + +## Scope & Ownership +- `src/Configuration/module.cmake`: `INTERNAL_DEPS Core Functional System Data Time LogState`, `EXCLUDE_HEADERS Void/Configuration/ReloadController.hpp`. +- `src/ConfigurationAsync/module.cmake`: `INTERNAL_DEPS Configuration SystemAsync Async Time Functional LogState`, `EXTRA_HEADERS Void/Configuration/ReloadController.hpp`. +- `include/Void/Configuration/Bind.hpp`: non-breaking field annotations `Secret{}`, `RestartRequired{}`, `Deprecated{}`, `IntRange{}`, `RealRange{}` while keeping `bind` intact. +- `include/Void/Configuration/Schema.hpp` + `src/Configuration/Schema.cpp`: + - `kConfigurationErrorDomain = 24`, `ConfigErrorCode`, `ConfigLimits` (1 MiB/source, 8 sources, 4 MiB merged, 10,000 keys, 4 KiB key, 64 KiB scalar, depth 32, 1,024 vector items, 100 diagnostics, 64 participants, 4 retained generations, 128 notifications, 5s prepare timeout). + - `SourceKind`, `SourceId`, `SourceLocation`, `ValueState` (`Missing`, `Empty`, `Null`, `Present`, `Removed`), `KeyProvenance`, `Provenance`, `SourceSpec`, `SourceSet`, `MergedConfig`. + - `load_sources(...)`: deterministic precedence (defaults < files in order < allowlisted/prefixed env < explicit CLI), rejects literal-dot vs nested JSON collisions, enforces byte/key/depth/vector caps, redacts secrets in diagnostics. + - `Schema`, `validate(...)` (rejects unknown keys by default, rejects vector gaps, no malformed-to-default fallback, cross-field constraints, up to 100 diagnostics with redacted secrets), `detect_restart_required_changes(...)`. +- `include/Void/Configuration/ReloadController.hpp` + `src/ConfigurationAsync/ReloadController.cpp`: + - Immutable `Snapshot`, `PreparedChange`, `ReloadParticipant`, `ReloadReport`, serialized `ReloadController` with fallible `create(...)`, participant prepare/reverse-rollback/join on unregister, 4-generation retention cap, single atomic pointer swap, post-commit stop observation (`committed = true, stop_observed_after_commit = true`), bounded notification queue + exception isolation, external coordinator prepare port, `WatcherService` coalescing adapter. +- Tests & consumers: `tests/standalone/Configuration/ConfigurationHardening.cpp`, `tests/standalone/ConfigurationAsync/ConfigurationAsync.cpp`, `tests/package/ConfigurationOnly/*`, `tests/package/ConfigurationAsyncOnly/*`, `tests/package/InstalledComponents.cmake`. + +## Verification Criteria +- Standalone `ConfigurationAsync;Testing` RelWithDebInfo `-Werror`: `Configuration*` tests + `ctest` 2/2 (`ConfigurationOnly`, `ConfigurationAsyncOnly`). +- Full Wave 8 RelWithDebInfo `-Werror`, ASan+UBSan `-Werror`, and Wave 8 TSan. diff --git a/docs/agent-workflow/tasks/M-FSM-01-05.md b/docs/agent-workflow/tasks/M-FSM-01-05.md new file mode 100644 index 0000000..280ae06 --- /dev/null +++ b/docs/agent-workflow/tasks/M-FSM-01-05.md @@ -0,0 +1,24 @@ +# M-FSM-01..05 — Structured Scopes, Race-Loser Joins, Boundary Checkpoints & Bounded Supervision + +- **Wave**: Wave 8 (`feat/roadmap-p2-wave8`, branched from `main` at `d83d0f4`) +- **Roadmap reference**: `docs/roadmap/modules/Fsm.md`, `docs/roadmap/DEPENDENCIES.md` + +## Scope & Ownership +- `src/Fsm/module.cmake`: `INTERNAL_DEPS Async Core Data Functional Time Log Service`. +- `include/Void/Fsm/StateKey.hpp`: `kFsmErrorDomain = 25`, `FsmErrorCode`, `make_fsm_error`, shared `constexpr bool terminal(Status)` including `Faulted`, `TerminationReason`, `FsmLimits` (1,024 mailbox events / 4 MiB, 256 deferred, 1,024 timers, 128 child regions, depth 32, 256 retained transitions, 4 MiB checkpoint, 64 events / 1ms per turn), `Checkpoint`, `ExecutionBinding`, `StateId`. +- `include/Void/Fsm/Detail/Engine.hpp` + `src/Fsm/Engine.cpp`: + - Injected `Time::MonotonicClock` and `FsmLimits` for timers and turn budgeting. + - Bounded `try_post` enforcing mailbox event & byte limits (`overloaded`) alongside a bounded control lane so stop/checkpoint/jump always progress. + - Scope-tracked waiters & timers (`cancel_scope_waiters`) cancelled prior to state destruction. +- `include/Void/Fsm/Machine.hpp`: + - Preserve 100% of existing API (`start`, `wait`, `run_blocking`, `run_parallel`, `run_parallel_any`, `serialize`, `restore`). + - Add `acquire_service()` returning owning `Service::ServiceHandle`, `try_post`, `termination_reason`, bounded `transition_history`, `observer_errors`, `state_stop_token()`, `await_event_cancellable`, `safe_point`. + - Add `run(ExecutionBinding, Async::OperationOptions)` with root + per-state stop scopes, waiter/timer cleanup before `on_exit`, `on_exit` exception faulting, observer error isolation. + - Add `run_parallel_structured` (sibling fault stop/join) and `run_parallel_any_structured` (deterministic tie-break + stop/join all losers). + - Add boundary `request_checkpoint` / `restore_checkpoint` / `restore_legacy_checkpoint`. +- `include/Void/Fsm/Orchestrator.hpp`: fix `FsmHandle::finished()` via `terminal(status())`, clarify `shared_ptr` ownership docs, add `SupervisionPolicy` (`StopOnFault`, `BoundedRestart` 3/60s on injected clock, 1,024 max supervised), unlocked observers, `try_launch`. +- Tests & consumers: `tests/standalone/Fsm/FsmHardening.cpp`, `tests/package/FsmOnly/*`, `tests/package/InstalledComponents.cmake`. + +## Verification Criteria +- Standalone `Fsm;Testing` RelWithDebInfo `-Werror`: `Fsm*` tests + `ctest` 2/2 (`FsmOnly`). +- Full Wave 8 RelWithDebInfo `-Werror`, ASan+UBSan `-Werror`, and Wave 8 TSan. diff --git a/docs/agent-workflow/tasks/M-PLUGIN-01-06.md b/docs/agent-workflow/tasks/M-PLUGIN-01-06.md new file mode 100644 index 0000000..ddb313a --- /dev/null +++ b/docs/agent-workflow/tasks/M-PLUGIN-01-06.md @@ -0,0 +1,19 @@ +# M-PLUGIN-01..06 — Pure C11 ABI (`CAbi.h`), Generation Pins, Quiesce/Reload & Unlocked Staging + +- **Wave**: Wave 8 (`feat/roadmap-p2-wave8`, branched from `main` at `d83d0f4`) +- **Roadmap reference**: `docs/roadmap/modules/Plugin.md`, `docs/roadmap/DEPENDENCIES.md` (`G-HOST`) + +## Scope & Ownership +- `src/Plugin/module.cmake`: `INTERNAL_DEPS Core Functional System Data Time Async LogState Text Service`, `DEPS_UNIX dl`. +- `include/Void/Plugin/CAbi.h`: strict ISO C11 public ABI (`VOID_STATUS_*`, `VOID_CABI_MAJOR_V1 = 1`, `VOID_CAP_*`, `void_module_query_v1`, `void_bytes_v1`, `void_owned_bytes_v1`, `void_interface_id_v1`, `void_module_info_v1`, `void_op_options_v1`, `void_error_detail_v1`, `void_host_api_v1`, `void_module_api_v1`, `VOID_MODULE_API_V1_MIN_SIZE`) with zero C++/STL types or exceptions. +- `include/Void/Plugin/Host.hpp` + `src/Plugin/Host.cpp` + `include/Void/Plugin/CAbiAdapter.hpp`: + - `kPluginErrorDomain = 23`, `PluginErrorCode`, `PluginHostLimits` (64 modules, 256 interfaces/module, 4 retained generations/module, 64 MiB mapped image file accounting/module, 4 MiB checkpoint, 1 MiB config, 1,024 async ops/gen, 256 pending callbacks, 5s prepare / 5s quiesce / 10s readiness / 30s total reload timeout, `allow_safe_dlclose = false` default). + - Independent `external_refs` and `activity_pins`; host-owned retirement queue executing `deactivate -> destroy -> optional dlclose` only when both reach 0 and never on a plugin callback's stack; uncooperative generations stay mapped and remain visible via `retained_generations()`. + - `CModuleHost`: validates `void_module_query_v1` against truncation/unknown major/non-zero reserved/oversized lengths; per-module unlocked staged reload coordinator (`quiesce -> checkpoint -> restore -> activate -> readiness` sharing one absolute deadline on injected `Time::MonotonicClock`, rollback + `resume` on pre-publication failure or `Degraded` on resume failure, atomic epoch-checked publication + coherent `ServiceRegistry` swap); topological dependency `load_batch` rejecting cycles and `RestartRequired` conflicts. + - `CAbiAdapter.hpp`: exception-safe C++ `IModule` to `void_module_api_v1` shim. +- `src/Plugin/Manager.cpp`: per-entry `reload_mutex` so candidate staging/validators/config/activation run outside `m_mutex` without deadlocking reentrant lookups. +- Tests & consumers: `tests/plugins/CAbiPluginV{1,2}.c`, `tests/standalone/Plugin/PluginHardening.cpp`, `tests/package/PluginOnly/*`, `tests/CMakeLists.txt`, `tests/package/InstalledComponents.cmake`. + +## Verification Criteria +- Standalone `Plugin;ServicePlugin;Testing` RelWithDebInfo `-Werror`: `Plugin*` tests + `ctest` 2/2 (`PluginOnly`, `ServicePluginOnly`). +- Full Wave 8 RelWithDebInfo `-Werror`, ASan+UBSan `-Werror`, and Wave 8 TSan. diff --git a/docs/agent-workflow/tasks/M-SERVICE-01-05.md b/docs/agent-workflow/tasks/M-SERVICE-01-05.md new file mode 100644 index 0000000..1722561 --- /dev/null +++ b/docs/agent-workflow/tasks/M-SERVICE-01-05.md @@ -0,0 +1,22 @@ +# M-SERVICE-01..05 — Owning ServiceHandles, Immutable Snapshots, DAG Lifecycle & ServicePlugin Split + +- **Wave**: Wave 8 (`feat/roadmap-p2-wave8`, branched from `main` at `d83d0f4`) +- **Roadmap reference**: `docs/roadmap/modules/Service.md`, `docs/roadmap/DEPENDENCIES.md` (Rule #3, `G-HOST`) + +## Scope & Ownership +- `src/Service/module.cmake`: `INTERNAL_DEPS Core Functional Time Async LogState`, `EXCLUDE_HEADERS Void/Service/PluginService.hpp` (zero external deps, zero `Plugin` dependency). +- `src/ServicePlugin/module.cmake`: `INTERNAL_DEPS Service Plugin LogState`, `EXTRA_HEADERS Void/Service/PluginService.hpp`. +- `include/Void/Service/Types.hpp`: `kServiceErrorDomain = 22`, `ServiceErrorCode`, `make_service_error`, `ServiceLimits` (256 providers, 16 parent levels, 1,024 edges, 64 staged changes, 128 lifecycle requests, 4 retained generations), `PublicationEpoch`, `ExpectedEpoch`, `ServicePin`, `ServiceHealth`, `ServiceObservation`, `ShutdownReport`, `IManagedService`, `ServiceHandle`. +- `include/Void/Service/Registry.hpp` + `src/Service/Registry.cpp`: + - Preserve 100% of existing `ServiceRegistry` API (`provide`, `remove`, `get`, `require`, `has`, `start_all`, `stop_all`, `size`). + - Immutable `SnapshotData` swapped atomically under a short guard; old snapshots, destructors, and observers released/invoked outside locks. + - `start_all()`/`stop_all()` copy retained lifecycle list under short lock and invoke callbacks outside locks. + - `ServiceSnapshot` retaining `parent_snapshot` `shared_ptr` so child snapshots outlive parent registries; `snapshot()`, `from_parent_snapshot()`, `refresh_parent()`. + - `acquire() -> Result>` returning `service_stopping` when closed or `missing_service` when absent, pinning generation lifetime until handle drop. + - `ProviderSet` (`add`, `add_alias` sharing one lifecycle node per object pointer), `PreparedPublication`, `prepare_batch` (topological sort + cycle/duplicate/missing-dep/limit validation), `start_staged` (topological start + `abort_start()` + reverse rollback preserving active snapshot), `publish` (epoch check + retention cap + atomic swap), `start`, `close_and_join` (dependent-first stop + `incomplete_owners` reporting without freeing live providers), `retained_generation_count()`. +- `include/Void/Service/PluginService.hpp`: preserved `PluginServiceBinding` + `acquire_plugin_service` pinning exact `PluginHandle` via `ServicePin`. +- Tests & consumers: `tests/standalone/Service/ServiceHardening.cpp`, `tests/package/ServiceOnly/*`, `tests/package/ServicePluginOnly/*`, updated `tests/package/InstalledComponents.cmake`. + +## Verification Criteria +- Standalone `Service;ServicePlugin;Testing` RelWithDebInfo `-Werror`: `Service*` tests + `ctest` 2/2 (`ServiceOnly`, `ServicePluginOnly`). +- Full Wave 8 RelWithDebInfo `-Werror`, ASan+UBSan `-Werror`, and Wave 8 TSan. diff --git a/include/Void/Functional/Error.hpp b/include/Void/Functional/Error.hpp index 1d686be..2908cac 100644 --- a/include/Void/Functional/Error.hpp +++ b/include/Void/Functional/Error.hpp @@ -71,6 +71,10 @@ namespace Void::Result inline constexpr std::uint32_t kSecurityErrorDomain = 19; inline constexpr std::uint32_t kUpdateErrorDomain = 20; inline constexpr std::uint32_t kSqliteErrorDomain = 21; + inline constexpr std::uint32_t kServiceErrorDomain = 22; + inline constexpr std::uint32_t kPluginErrorDomain = 23; + inline constexpr std::uint32_t kConfigurationErrorDomain = 24; + inline constexpr std::uint32_t kFsmErrorDomain = 25; struct ErrorCode { std::uint32_t domain{kGenericErrorDomain}; From 1474a69ab1b2738536de146a7b9f7c45874bccec Mon Sep 17 00:00:00 2001 From: faumaray Date: Thu, 26 Nov 2026 16:03:31 +0300 Subject: [PATCH 2/9] feat(service): immutable snapshots, owning ServiceHandle, DAG lifecycle, and ServicePlugin split --- include/Void/Service/PluginService.hpp | 87 +- include/Void/Service/Registry.hpp | 503 ++++++++-- include/Void/Service/Types.hpp | 227 +++++ src/Service/Registry.cpp | 944 ++++++++++++++++++ src/Service/module.cmake | 3 +- src/ServicePlugin/module.cmake | 4 + tests/package/InstalledComponents.cmake | 15 + tests/package/ServiceOnly/CMakeLists.txt | 11 + tests/package/ServiceOnly/main.cpp | 36 + .../package/ServicePluginOnly/CMakeLists.txt | 11 + tests/package/ServicePluginOnly/main.cpp | 12 + tests/standalone/Service/ServiceHardening.cpp | 451 +++++++++ 12 files changed, 2167 insertions(+), 137 deletions(-) create mode 100644 include/Void/Service/Types.hpp create mode 100644 src/Service/Registry.cpp create mode 100644 src/ServicePlugin/module.cmake create mode 100644 tests/package/ServiceOnly/CMakeLists.txt create mode 100644 tests/package/ServiceOnly/main.cpp create mode 100644 tests/package/ServicePluginOnly/CMakeLists.txt create mode 100644 tests/package/ServicePluginOnly/main.cpp create mode 100644 tests/standalone/Service/ServiceHardening.cpp diff --git a/include/Void/Service/PluginService.hpp b/include/Void/Service/PluginService.hpp index 3e1bba8..1021354 100644 --- a/include/Void/Service/PluginService.hpp +++ b/include/Void/Service/PluginService.hpp @@ -26,6 +26,60 @@ namespace Void::Service inline constexpr const char* kServiceSymbol = "void_plugin_service"; + /// Acquire an owning ServiceHandle directly from a PluginManager entry, + /// pinning the exact PluginHandle so the shared object stays mapped until + /// every copy of the returned handle is destroyed. + template + [[nodiscard]] Void::Result::Result> + acquire_plugin_service(Plugin::PluginManager& manager, + std::string_view plugin_name, + PublicationEpoch epoch = 0) + { + static_assert(std::is_base_of_v, + "plugin service interface must derive IService"); + auto handle = manager.acquire(plugin_name); + if (!handle) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::missing_service, + std::string{"ServicePlugin: plugin '"} + + std::string{plugin_name} + "' is not loaded")); + } + auto* factory = reinterpret_cast( + handle.raw_symbol(kServiceSymbol)); + if (factory == nullptr) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::missing_service, + std::string{"ServicePlugin: plugin '"} + + std::string{plugin_name} + "' does not export " + + kServiceSymbol)); + } + IService* base = nullptr; + try { + base = factory(handle.get()); + } catch (const std::exception& ex) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::internal, ex.what())); + } catch (...) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::internal, + "ServicePlugin: service factory threw")); + } + if (base == nullptr) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::missing_service, + "ServicePlugin: service factory returned null")); + } + I* iface = dynamic_cast(base); + if (iface == nullptr) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::invalid_argument, + "ServicePlugin: incompatible service interface")); + } + auto owner = std::make_shared(std::move(handle)); + std::shared_ptr pinned(std::move(owner), iface); + return ServiceHandle{iface, std::move(pinned), nullptr, epoch}; + } + /// Binds a plugin-provided service (interface I) into a ServiceRegistry /// and keeps it bound across hot reloads: after each reload the new /// instance's service (carrying state migrated by the plugin's v2 ABI) @@ -174,35 +228,14 @@ namespace Void::Service [[nodiscard]] bool bind_locked() noexcept { try { - auto handle = m_manager->acquire(m_name); - if (!handle) { + auto svc_handle = acquire_plugin_service( + *m_manager, m_name); + if (!svc_handle) { + Void::Log::warn("Service.Plugin", "{}", + svc_handle.error().message()); return false; } - auto* factory = - reinterpret_cast( - handle.raw_symbol(kServiceSymbol)); - if (factory == nullptr) { - return false; - } - IService* base = factory(handle.get()); - if (base == nullptr) { - return false; - } - I* iface = dynamic_cast(base); - if (iface == nullptr) { - Void::Log::warn( - "Service.Plugin", - "plugin '{}' exported an incompatible " - "service interface", - m_name); - return false; - } - - // Pin the exact instance and shared object that - // supplied the factory and service subobject. - auto owner = std::make_shared( - std::move(handle)); - std::shared_ptr pinned(std::move(owner), iface); + auto pinned = svc_handle->shared(); if (m_validator && !m_validator(pinned)) { Void::Log::warn( "Service.Plugin", diff --git a/include/Void/Service/Registry.hpp b/include/Void/Service/Registry.hpp index aec3459..4c14ec7 100644 --- a/include/Void/Service/Registry.hpp +++ b/include/Void/Service/Registry.hpp @@ -1,16 +1,23 @@ #pragma once +#include #include #include +#include +#include +#include +#include +#include #include #include -#include +#include #include #include #include #include #include +#include #include namespace Void::Service @@ -25,92 +32,297 @@ namespace Void::Service } #endif - /// Type-keyed service container: providers register an implementation - /// against an interface type, consumers resolve by that interface and - /// never name the concrete type — the core of the dependency-inversion - /// the orchestrator and FSMs rely on. + class ServiceRegistry; + + namespace detail + { + struct RetentionEntry { + PublicationEpoch epoch{0}; + std::weak_ptr token{}; + std::string label{}; + }; + + struct RetentionState; + + struct LifecycleNode { + std::string id{}; + const void* object_key{nullptr}; + std::shared_ptr owner{}; + IService* service{nullptr}; + IManagedService* managed{nullptr}; + std::size_t seq{0}; + std::vector dep_indices{}; + }; + + struct SnapshotEntry { + std::shared_ptr impl{}; // holds provider (+ optional pin) + IService* service{nullptr}; + std::string id{}; + }; + + struct SnapshotData { + PublicationEpoch epoch{0}; + std::shared_ptr gen_token{}; + std::unordered_map services{}; + std::vector legacy_order{}; + std::vector lifecycle_nodes{}; + std::shared_ptr parent_snap{}; + const ServiceRegistry* live_parent{nullptr}; + }; + } // namespace detail + + /// Immutable, self-retaining point-in-time view of a ServiceRegistry + /// (and any snapshot-captured parent chain). Safe to hold after the source + /// registry is modified or destroyed. + class ServiceSnapshot + { + public: + + ServiceSnapshot() = default; + + template [[nodiscard]] std::shared_ptr get() const + { + const detail::SnapshotData* cur = m_data.get(); + std::size_t depth = 0; + while (cur != nullptr && depth <= m_max_parent_levels) { + const auto it = + cur->services.find(std::type_index{typeid(I)}); + if (it != cur->services.end()) { + return std::static_pointer_cast(it->second.impl); + } + cur = cur->parent_snap.get(); + ++depth; + } + return nullptr; + } + + template [[nodiscard]] bool has() const + { + return get() != nullptr; + } + + [[nodiscard]] PublicationEpoch epoch() const noexcept + { + return m_data ? m_data->epoch : 0; + } + + [[nodiscard]] std::size_t size() const noexcept + { + return m_data ? m_data->services.size() : 0; + } + + [[nodiscard]] explicit operator bool() const noexcept + { + return m_data != nullptr; + } + + private: + + friend class ServiceRegistry; + explicit ServiceSnapshot(std::shared_ptr data, + std::size_t max_parent_levels = 16) noexcept + : m_data(std::move(data)), + m_max_parent_levels(max_parent_levels) + { + } + + std::shared_ptr m_data{}; + std::size_t m_max_parent_levels{16}; + }; + + /// Staged description of a coherent batch of services and their dependency + /// graph, ready to be validated by ServiceRegistry::prepare_batch(). + class ProviderSet + { + public: + + struct StagedItem { + std::type_index interface_type; + std::string id{}; + std::shared_ptr owner{}; + const void* object_key{nullptr}; + IService* service{nullptr}; + IManagedService* managed{nullptr}; + std::vector required_deps{}; + std::vector optional_deps{}; + }; + + template + ProviderSet& add( + std::string id, + std::shared_ptr impl, + std::vector required_deps = {}, + std::vector optional_deps = {}, + ServicePin pin = {}) + { + StagedItem item{.interface_type = std::type_index{typeid(I)}, + .id = std::move(id), + .owner = pack_owner(impl, std::move(pin)), + .object_key = impl.get(), + .service = extract_service(impl.get()), + .managed = extract_managed(impl.get()), + .required_deps = std::move(required_deps), + .optional_deps = std::move(optional_deps)}; + m_items.push_back(std::move(item)); + return *this; + } + + template + ProviderSet& add_alias( + std::string id, + std::shared_ptr impl, + std::vector required_deps = {}, + std::vector optional_deps = {}, + ServicePin pin = {}) + { + return add(std::move(id), std::move(impl), + std::move(required_deps), + std::move(optional_deps), std::move(pin)); + } + + [[nodiscard]] const std::vector& items() const noexcept + { + return m_items; + } + + private: + + template + static std::shared_ptr pack_owner(const std::shared_ptr& impl, + ServicePin pin) + { + if (!impl) { + return nullptr; + } + if (!pin) { + return std::shared_ptr(impl, impl.get()); + } + struct PinnedBox { + std::shared_ptr impl; + ServicePin pin; + }; + auto box = std::make_shared( + PinnedBox{std::shared_ptr(impl, impl.get()), + std::move(pin)}); + return std::shared_ptr(std::move(box), impl.get()); + } + + template static IService* extract_service(I* raw) + { + if (raw == nullptr) { + return nullptr; + } + if constexpr (std::is_base_of_v) { + return static_cast(raw); + } else if constexpr (std::is_polymorphic_v) { + return dynamic_cast(raw); + } else { + return nullptr; + } + } + + template + static IManagedService* extract_managed(I* raw) + { + if (raw == nullptr) { + return nullptr; + } + if constexpr (std::is_base_of_v) { + return static_cast(raw); + } else if constexpr (std::is_polymorphic_v) { + return dynamic_cast(raw); + } else { + return nullptr; + } + } + + std::vector m_items{}; + }; + + /// Validated, topologically ordered candidate batch returned by + /// ServiceRegistry::prepare_batch(). + struct PreparedPublication { + ExpectedEpoch expected_epoch{}; + std::shared_ptr snapshot{}; + bool valid{false}; + bool started{false}; + bool aborted{false}; + }; + + /// Thread-safe, snapshot-published service container supporting both + /// legacy single-service mutations (`provide`/`get`/`require`) and + /// transactional DAG lifecycle publication (`acquire`/`prepare_batch`/ + /// `start_staged`/`publish`/`close_and_join`). /// - /// registry.provide(std::make_shared()); - /// auto& clock = registry.require(); // no SystemClock dep - /// - /// Thread-safe. Reads (get/require/has) take a shared lock; they are - /// the hot path for running FSMs resolving services per step. + /// Note: `require()` returns an unpinned reference after unlocking and is + /// kept for legacy compatibility; new code and coroutines should use + /// `acquire()` and retain the returned `ServiceHandle` across calls + /// and `co_await` suspension points. class ServiceRegistry { public: - ServiceRegistry() = default; + ServiceRegistry(); + explicit ServiceRegistry(const ServiceRegistry* parent); + explicit ServiceRegistry( + ServiceLimits limits, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()); + ~ServiceRegistry(); + ServiceRegistry(const ServiceRegistry&) = delete; ServiceRegistry& operator=(const ServiceRegistry&) = delete; - /// Create a scoped child registry that overlays `parent`: lookups - /// fall through to the parent when a key is not provided locally, - /// and a local provide() shadows the parent's entry. Lifecycle - /// (start_all/stop_all) covers only locally-provided services. The - /// parent must outlive this registry. - explicit ServiceRegistry(const ServiceRegistry* parent) - : m_parent{parent} - { - } + /// Construct a child registry retaining an immutable parent + /// snapshot so lookups survive destruction of the parent registry. + [[nodiscard]] static Void::Result::Result< + std::unique_ptr> + from_parent_snapshot( + ServiceSnapshot parent, + ServiceLimits limits = {}, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()); + + /// Explicitly refresh snapshot-based parent linkage from `parent`. + void refresh_parent(const ServiceRegistry& parent); + + /// Capture an immutable point-in-time snapshot. + [[nodiscard]] ServiceSnapshot snapshot() const; + + // ── Legacy compatible API ───────────────────────────────────── - /// Register (or replace) the implementation for interface I. - /// If I derives IService, the instance joins the lifecycle. template void provide(std::shared_ptr impl) { - Entry entry; - entry.impl = std::shared_ptr(impl, impl.get()); - if constexpr (std::is_base_of_v) { - entry.service = static_cast(impl.get()); - } else if constexpr (std::is_polymorphic_v) { - // The interface I doesn't derive IService, but the - // concrete implementation might — recover the lifecycle - // aspect by cross-cast. (dynamic_cast requires a - // polymorphic I.) - entry.service = dynamic_cast(impl.get()); - } else { - // A plain, non-polymorphic service type: storable and - // resolvable, but has no IService lifecycle aspect. - entry.service = nullptr; - } - const std::type_index key{typeid(I)}; - std::unique_lock lock{m_mutex}; - if (!m_services.contains(key)) { - m_order.push_back(key); - } - m_services.insert_or_assign(key, std::move(entry)); - } - - /// Withdraw the implementation for interface I from this registry - /// (a parent's entry is unaffected: later lookups fall through to - /// it again). Consumers still holding the shared_ptr keep the - /// instance alive; only new lookups miss. Returns true when an - /// entry was removed. - template bool remove() - { - const std::type_index key{typeid(I)}; - std::unique_lock lock{m_mutex}; - if (m_services.erase(key) == 0) { - return false; - } - std::erase(m_order, key); - return true; - } - - /// Resolve I, or nullptr if not provided. Falls through to the - /// parent registry (if any) on a local miss. - template [[nodiscard]] std::shared_ptr get() const - { - { - std::shared_lock lock{m_mutex}; - const auto it = m_services.find(std::type_index{typeid(I)}); - if (it != m_services.end()) { - return std::static_pointer_cast(it->second.impl); + IService* svc = nullptr; + if (impl) { + if constexpr (std::is_base_of_v) { + svc = static_cast(impl.get()); + } else if constexpr (std::is_polymorphic_v) { + svc = dynamic_cast(impl.get()); } } - return m_parent ? m_parent->get() : nullptr; + provide_erased( + std::type_index{typeid(I)}, + impl ? std::shared_ptr(impl, impl.get()) + : std::shared_ptr{}, + impl.get(), svc); + } + + template bool remove() + { + return remove_erased(std::type_index{typeid(I)}); + } + + template + [[nodiscard]] std::shared_ptr get() const + { + auto h = acquire(); + if (!h) { + return nullptr; + } + return h->shared(); } - /// Resolve I; throws std::runtime_error if not provided. template [[nodiscard]] I& require() const { auto p = get(); @@ -124,55 +336,128 @@ namespace Void::Service template [[nodiscard]] bool has() const { - { - std::shared_lock lock{m_mutex}; - if (m_services.contains(std::type_index{typeid(I)})) { - return true; - } - } - return m_parent ? m_parent->has() : false; + return acquire().has_value(); } - /// Call on_start() on every lifecycle service, registration + /// Run on_start() outside registry locks in registration/dependency /// order. - void start_all() + void start_all(); + + /// Run on_stop() outside registry locks in reverse order. + void stop_all(); + + [[nodiscard]] std::size_t size() const; + + // ── Hardened owning & transactional lifecycle API ─────────────── + + template + [[nodiscard]] Void::Result::Result> acquire() const { - std::shared_lock lock{m_mutex}; - for (const auto& key : m_order) { - if (auto* s = m_services.at(key).service) { - s->on_start(); - } + auto snap = acquire_snapshot(); + if (!snap) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::service_stopping, + "ServiceRegistry: registry is stopping")); } + return acquire_from_snapshot(*snap, 0); } - /// Call on_stop() on every lifecycle service, reverse order. - void stop_all() - { - std::shared_lock lock{m_mutex}; - for (auto it = m_order.rbegin(); it != m_order.rend(); ++it) { - if (auto* s = m_services.at(*it).service) { - s->on_stop(); - } - } - } + [[nodiscard]] Void::Result::Result + prepare_batch(ProviderSet set, + ExpectedEpoch expected = std::nullopt); - [[nodiscard]] std::size_t size() const - { - std::shared_lock lock{m_mutex}; - return m_services.size(); - } + [[nodiscard]] Void::Result::Result + start_staged(PreparedPublication& prepared, + Async::OperationOptions options = {}); + + [[nodiscard]] Void::Result::Result + publish(PreparedPublication&& prepared); + + [[nodiscard]] Void::Result::Result + start_and_publish(ProviderSet set, + ExpectedEpoch expected = std::nullopt, + Async::OperationOptions options = {}); + + [[nodiscard]] Void::Result::Result + start(Async::OperationOptions options = {}); + + [[nodiscard]] Void::Result::Result + close_and_join(Async::OperationOptions options = {}); + + [[nodiscard]] PublicationEpoch epoch() const noexcept; + [[nodiscard]] std::size_t retained_generation_count() const; + [[nodiscard]] bool is_stopping() const noexcept; + + using ObserverCallback = + std::function; + std::size_t add_observer(ObserverCallback cb); + void remove_observer(std::size_t id); private: - struct Entry { - std::shared_ptr impl; - IService* service = nullptr; // non-null iff I : IService - }; + void provide_erased(std::type_index key, std::shared_ptr impl, + const void* object_key, IService* service); + bool remove_erased(std::type_index key); + std::shared_ptr acquire_snapshot() const; - const ServiceRegistry* m_parent = nullptr; - mutable std::shared_mutex m_mutex; - std::unordered_map m_services; - std::vector m_order; + template + [[nodiscard]] Void::Result::Result> + acquire_from_snapshot(const detail::SnapshotData& snap, + std::size_t depth) const + { + if (depth > m_limits.max_parent_levels) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::overloaded, + "ServiceRegistry: parent depth limit exceeded")); + } + const auto it = + snap.services.find(std::type_index{typeid(I)}); + if (it != snap.services.end()) { + auto* raw = static_cast(it->second.impl.get()); + return ServiceHandle{raw, it->second.impl, + snap.gen_token, snap.epoch}; + } + if (snap.parent_snap) { + return acquire_from_snapshot(*snap.parent_snap, + depth + 1); + } + if (snap.live_parent != nullptr) { + auto parent_snap = snap.live_parent->acquire_snapshot(); + if (!parent_snap) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::service_stopping, + "ServiceRegistry: parent registry is stopping")); + } + return acquire_from_snapshot(*parent_snap, depth + 1); + } + return Void::Result::fail(make_service_error( + ServiceErrorCode::missing_service, + std::string{"ServiceRegistry: no service for '"} + + typeid(I).name() + "'")); + } + + [[nodiscard]] Void::Result::Result rollback_started_nodes( + const std::vector& nodes, + std::size_t count, const Void::Result::Error& primary_error); + + void notify_observers(const ServiceObservation& obs); + [[nodiscard]] std::size_t prune_and_count_retained_locked(); + + ServiceLimits m_limits{}; + const Void::Time::MonotonicClock* m_clock{ + &Void::Time::SystemMonotonicClock::instance()}; + std::shared_ptr m_retention_state; + + mutable std::mutex m_write_mu{}; + mutable std::mutex m_snapshot_mu{}; + std::shared_ptr m_active_snapshot{}; + PublicationEpoch m_epoch{0}; + bool m_stopping{false}; + bool m_started{false}; + + mutable std::mutex m_observer_mu{}; + std::vector> m_observers{}; + std::size_t m_next_observer_id{1}; }; } // namespace Void::Service diff --git a/include/Void/Service/Types.hpp b/include/Void/Service/Types.hpp new file mode 100644 index 0000000..0af96b4 --- /dev/null +++ b/include/Void/Service/Types.hpp @@ -0,0 +1,227 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Service +{ + enum class ServiceErrorCode : std::int32_t { + none = 0, + invalid_argument = 1, + missing_service = 2, + conflict = 3, + duplicate_interface = 4, + cycle_detected = 5, + missing_dependency = 6, + start_failed = 7, + not_ready = 8, + stop_failed = 9, + service_stopping = 10, + cancelled = 11, + timeout = 12, + overloaded = 13, + retention_limit = 14, + internal = 15, + }; + + [[nodiscard]] inline Void::Result::Error + make_service_error(ServiceErrorCode code, std::string message = {}) + { + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case ServiceErrorCode::none: + kind = ErrorKind::internal; + break; + case ServiceErrorCode::invalid_argument: + case ServiceErrorCode::cycle_detected: + kind = ErrorKind::invalid_argument; + break; + case ServiceErrorCode::missing_service: + case ServiceErrorCode::missing_dependency: + kind = ErrorKind::not_found; + break; + case ServiceErrorCode::conflict: + case ServiceErrorCode::duplicate_interface: + case ServiceErrorCode::service_stopping: + kind = ErrorKind::conflict; + break; + case ServiceErrorCode::cancelled: + kind = ErrorKind::cancelled; + break; + case ServiceErrorCode::timeout: + kind = ErrorKind::timeout; + break; + case ServiceErrorCode::overloaded: + kind = ErrorKind::overloaded; + break; + case ServiceErrorCode::retention_limit: + kind = ErrorKind::exhausted; + break; + case ServiceErrorCode::start_failed: + case ServiceErrorCode::not_ready: + case ServiceErrorCode::stop_failed: + case ServiceErrorCode::internal: + kind = ErrorKind::internal; + break; + } + + return Error{kind, std::move(message), + ErrorCode{Void::Result::kServiceErrorDomain, + static_cast(code)}}; + } + + struct ServiceLimits { + std::size_t max_providers{256}; + std::size_t max_parent_levels{16}; + std::size_t max_dependency_edges{1024}; + std::size_t max_staged_changes{64}; + std::size_t max_lifecycle_requests{128}; + std::size_t max_retained_generations{4}; + }; + + using PublicationEpoch = std::uint64_t; + using ExpectedEpoch = std::optional; + using ServicePin = std::shared_ptr; + + enum class LifecyclePhase : std::uint8_t { + Constructed = 0, + Starting, + Ready, + Stopping, + Stopped, + Failed, + }; + + enum class ServiceHealthStatus : std::uint8_t { + Unknown = 0, + Healthy, + Degraded, + Unhealthy, + }; + + struct ServiceHealth { + ServiceHealthStatus status{ServiceHealthStatus::Unknown}; + std::string detail{}; + }; + + struct ServiceObservation { + PublicationEpoch epoch{0}; + std::size_t provider_count{0}; + std::size_t retained_generations{0}; + std::uint64_t duration_ns{0}; + bool rollback{false}; + std::string detail{}; + }; + + struct ShutdownReport { + std::vector stopped_services{}; + std::vector incomplete_owners{}; + std::vector stop_errors{}; + + [[nodiscard]] bool clean() const noexcept + { + return incomplete_owners.empty() && stop_errors.empty(); + } + }; + + /// Extended lifecycle contract with checked failure/readiness reporting and + /// abort cleanup on partial startup failure. + class IManagedService : public IService + { + public: + + [[nodiscard]] virtual Void::Result::Result start_checked() + { + try { + on_start(); + return {}; + } catch (const std::exception& ex) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::start_failed, ex.what())); + } catch (...) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::start_failed, + "service start threw unknown exception")); + } + } + + [[nodiscard]] virtual Void::Result::Result + check_readiness() const + { + return {}; + } + + virtual void abort_start() noexcept {} + + [[nodiscard]] virtual Void::Result::Result stop_checked() + { + try { + on_stop(); + return {}; + } catch (const std::exception& ex) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::stop_failed, ex.what())); + } catch (...) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::stop_failed, + "service stop threw unknown exception")); + } + } + }; + + /// Owning lease to a resolved provider record: keeps the provider object, + /// any external code/resource pin, and its publication generation token alive + /// across removal, replacement, parent destruction, and coroutine suspension. + template class ServiceHandle + { + public: + + ServiceHandle() noexcept = default; + + ServiceHandle(I* ptr, std::shared_ptr owner, + std::shared_ptr gen_token, + PublicationEpoch epoch) noexcept + : m_ptr(ptr), m_owner(std::move(owner)), + m_gen_token(std::move(gen_token)), m_epoch(epoch) + { + } + + [[nodiscard]] I* operator->() const noexcept { return m_ptr; } + [[nodiscard]] I& operator*() const noexcept { return *m_ptr; } + [[nodiscard]] I* get() const noexcept { return m_ptr; } + [[nodiscard]] explicit operator bool() const noexcept + { + return m_ptr != nullptr; + } + [[nodiscard]] PublicationEpoch generation() const noexcept + { + return m_epoch; + } + [[nodiscard]] std::shared_ptr shared() const noexcept + { + return std::shared_ptr(m_owner, m_ptr); + } + + private: + + I* m_ptr{nullptr}; + std::shared_ptr m_owner{}; + std::shared_ptr m_gen_token{}; + PublicationEpoch m_epoch{0}; + }; + +} // namespace Void::Service diff --git a/src/Service/Registry.cpp b/src/Service/Registry.cpp new file mode 100644 index 0000000..e0bb96d --- /dev/null +++ b/src/Service/Registry.cpp @@ -0,0 +1,944 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Service +{ + namespace detail + { + struct RetentionState { + mutable std::mutex mu{}; + std::condition_variable cv{}; + std::vector entries{}; + + void notify_release() noexcept + { + std::lock_guard lk{mu}; + cv.notify_all(); + } + }; + + namespace + { + struct TokenGuard { + std::weak_ptr state{}; + ~TokenGuard() + { + if (auto s = state.lock()) { + s->notify_release(); + } + } + }; + + std::shared_ptr + make_retention_token(const std::shared_ptr& state, + PublicationEpoch epoch, + std::string label) + { + auto tok = std::make_shared(TokenGuard{state}); + { + std::lock_guard lk{state->mu}; + std::erase_if(state->entries, [](const RetentionEntry& e) { + return e.token.expired(); + }); + state->entries.push_back( + RetentionEntry{epoch, tok, std::move(label)}); + } + return tok; + } + + bool has_in_parent_chain(const SnapshotData& snap, + std::type_index key, + std::size_t max_levels, + std::size_t depth = 0) + { + if (depth > max_levels) { + return false; + } + if (snap.services.contains(key)) { + return true; + } + if (snap.parent_snap) { + return has_in_parent_chain(*snap.parent_snap, key, + max_levels, depth + 1); + } + return false; + } + } // namespace + } // namespace detail + + ServiceRegistry::ServiceRegistry() + : ServiceRegistry(ServiceLimits{}, + Void::Time::SystemMonotonicClock::instance()) + { + } + + ServiceRegistry::ServiceRegistry(const ServiceRegistry* parent) + : ServiceRegistry(ServiceLimits{}, + Void::Time::SystemMonotonicClock::instance()) + { + if (parent != nullptr) { + auto snap = std::make_shared(); + snap->live_parent = parent; + m_active_snapshot = std::move(snap); + } + } + + ServiceRegistry::ServiceRegistry(ServiceLimits limits, + const Void::Time::MonotonicClock& clock) + : m_limits(limits), m_clock(&clock), + m_retention_state(std::make_shared()) + { + m_active_snapshot = std::make_shared(); + } + + ServiceRegistry::~ServiceRegistry() + { + // Detach the active snapshot under m_snapshot_mu with m_stopping=true + // before destroying providers, so a provider destructor reentering the + // registry cannot increment the use_count of a half-destroyed SnapshotData. + std::shared_ptr last_snap; + { + std::lock_guard snap_lk{m_snapshot_mu}; + m_stopping = true; + last_snap = std::move(m_active_snapshot); + } + last_snap.reset(); + } + + Void::Result::Result> + ServiceRegistry::from_parent_snapshot( + ServiceSnapshot parent, ServiceLimits limits, + const Void::Time::MonotonicClock& clock) + { + if (!parent) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::invalid_argument, + "ServiceRegistry: parent snapshot must not be empty")); + } + std::size_t depth = 1; + const detail::SnapshotData* cur = parent.m_data.get(); + while (cur->parent_snap != nullptr) { + ++depth; + if (depth > limits.max_parent_levels) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::overloaded, + "ServiceRegistry: parent snapshot nesting exceeds max_parent_levels")); + } + cur = cur->parent_snap.get(); + } + auto reg = std::make_unique(limits, clock); + auto snap = std::make_shared(); + snap->parent_snap = std::move(parent.m_data); + reg->m_active_snapshot = std::move(snap); + return reg; + } + + void ServiceRegistry::refresh_parent(const ServiceRegistry& parent) + { + auto parent_snap = parent.snapshot(); + std::shared_ptr old_snap; + { + std::lock_guard write_lk{m_write_mu}; + auto next = std::make_shared(*m_active_snapshot); + next->parent_snap = parent_snap.m_data; + next->live_parent = nullptr; + std::lock_guard snap_lk{m_snapshot_mu}; + if (m_stopping) { + return; + } + old_snap = std::exchange(m_active_snapshot, std::move(next)); + } + // old_snap released here outside all locks. + } + + ServiceSnapshot ServiceRegistry::snapshot() const + { + std::lock_guard snap_lk{m_snapshot_mu}; + return ServiceSnapshot{m_active_snapshot, m_limits.max_parent_levels}; + } + + std::shared_ptr + ServiceRegistry::acquire_snapshot() const + { + std::lock_guard snap_lk{m_snapshot_mu}; + if (m_stopping) { + return nullptr; + } + return m_active_snapshot; + } + + void ServiceRegistry::provide_erased(std::type_index key, + std::shared_ptr impl, + const void* object_key, + IService* service) + { + std::shared_ptr old_snap; + { + std::lock_guard write_lk{m_write_mu}; + if (m_stopping) { + return; + } + auto next = + std::make_shared(*m_active_snapshot); + next->epoch = ++m_epoch; + if (!next->services.contains(key)) { + next->legacy_order.push_back(key); + } + next->services.insert_or_assign( + key, detail::SnapshotEntry{std::move(impl), service, {}}); + + // Rebuild lifecycle list in legacy registration order (deduping + // shared object instances if multiple interfaces point to one + // IService). + next->lifecycle_nodes.clear(); + std::unordered_set seen_objs; + for (const auto& k : next->legacy_order) { + const auto it = next->services.find(k); + if (it == next->services.end() || it->second.service == nullptr) { + continue; + } + const void* obj = static_cast(it->second.service); + if (!seen_objs.insert(obj).second) { + continue; + } + next->lifecycle_nodes.push_back(detail::LifecycleNode{ + .id = std::string{it->second.service->service_name()}, + .object_key = obj, + .owner = it->second.impl, + .service = it->second.service, + .managed = dynamic_cast(it->second.service), + .seq = next->lifecycle_nodes.size(), + .dep_indices = {}, + }); + } + (void)object_key; + { + std::lock_guard snap_lk{m_snapshot_mu}; + old_snap = std::exchange(m_active_snapshot, std::move(next)); + } + } + // old_snap (and any replaced provider whose external refs reached 0) + // destroys here AFTER releasing all registry locks. + } + + bool ServiceRegistry::remove_erased(std::type_index key) + { + std::shared_ptr old_snap; + bool removed = false; + { + std::lock_guard write_lk{m_write_mu}; + if (m_stopping || !m_active_snapshot->services.contains(key)) { + return false; + } + auto next = + std::make_shared(*m_active_snapshot); + next->epoch = ++m_epoch; + removed = next->services.erase(key) > 0; + std::erase(next->legacy_order, key); + + next->lifecycle_nodes.clear(); + std::unordered_set seen_objs; + for (const auto& k : next->legacy_order) { + const auto it = next->services.find(k); + if (it == next->services.end() || it->second.service == nullptr) { + continue; + } + const void* obj = static_cast(it->second.service); + if (!seen_objs.insert(obj).second) { + continue; + } + next->lifecycle_nodes.push_back(detail::LifecycleNode{ + .id = std::string{it->second.service->service_name()}, + .object_key = obj, + .owner = it->second.impl, + .service = it->second.service, + .managed = dynamic_cast(it->second.service), + .seq = next->lifecycle_nodes.size(), + .dep_indices = {}, + }); + } + { + std::lock_guard snap_lk{m_snapshot_mu}; + old_snap = std::exchange(m_active_snapshot, std::move(next)); + } + } + return removed; + } + + void ServiceRegistry::start_all() + { + auto snap = acquire_snapshot(); + if (!snap) { + return; + } + // Snapshot copied; callbacks invoke strictly outside registry locks. + for (const auto& node : snap->lifecycle_nodes) { + if (node.service != nullptr) { + node.service->on_start(); + } + } + } + + void ServiceRegistry::stop_all() + { + std::shared_ptr snap; + { + std::lock_guard snap_lk{m_snapshot_mu}; + snap = m_active_snapshot; + } + if (!snap) { + return; + } + for (auto it = snap->lifecycle_nodes.rbegin(); + it != snap->lifecycle_nodes.rend(); ++it) { + if (it->service != nullptr) { + it->service->on_stop(); + } + } + } + + std::size_t ServiceRegistry::size() const + { + std::lock_guard snap_lk{m_snapshot_mu}; + return m_active_snapshot ? m_active_snapshot->services.size() : 0; + } + + std::size_t ServiceRegistry::prune_and_count_retained_locked() + { + std::lock_guard lk{m_retention_state->mu}; + std::erase_if(m_retention_state->entries, + [](const detail::RetentionEntry& e) { + return e.token.expired(); + }); + return m_retention_state->entries.size(); + } + + std::size_t ServiceRegistry::retained_generation_count() const + { + std::lock_guard lk{m_retention_state->mu}; + std::size_t live = 0; + for (const auto& e : m_retention_state->entries) { + if (!e.token.expired()) { + ++live; + } + } + return live; + } + + PublicationEpoch ServiceRegistry::epoch() const noexcept + { + std::lock_guard snap_lk{m_snapshot_mu}; + return m_epoch; + } + + bool ServiceRegistry::is_stopping() const noexcept + { + std::lock_guard snap_lk{m_snapshot_mu}; + return m_stopping; + } + + std::size_t ServiceRegistry::add_observer(ObserverCallback cb) + { + std::lock_guard lk{m_observer_mu}; + const std::size_t id = m_next_observer_id++; + m_observers.emplace_back(id, std::move(cb)); + return id; + } + + void ServiceRegistry::remove_observer(std::size_t id) + { + std::lock_guard lk{m_observer_mu}; + std::erase_if(m_observers, + [id](const auto& pair) { return pair.first == id; }); + } + + void ServiceRegistry::notify_observers(const ServiceObservation& obs) + { + std::vector copy; + { + std::lock_guard lk{m_observer_mu}; + copy.reserve(m_observers.size()); + for (const auto& [_, cb] : m_observers) { + if (cb) { + copy.push_back(cb); + } + } + } + for (const auto& cb : copy) { + try { + cb(obs); + } catch (...) { + } + } + } + + Void::Result::Result + ServiceRegistry::prepare_batch(ProviderSet set, ExpectedEpoch expected) + { + std::shared_ptr current_snap; + PublicationEpoch current_epoch = 0; + { + std::lock_guard snap_lk{m_snapshot_mu}; + if (m_stopping) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::service_stopping, + "ServiceRegistry::prepare_batch: registry is stopping")); + } + current_epoch = m_epoch; + current_snap = m_active_snapshot; + } + if (expected.has_value() && *expected != current_epoch) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::conflict, + "ServiceRegistry::prepare_batch: expected epoch mismatch")); + } + + const auto& items = set.items(); + if (items.size() > m_limits.max_staged_changes || + items.size() > m_limits.max_providers) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::overloaded, + "ServiceRegistry::prepare_batch: staged provider limit exceeded")); + } + + if (m_limits.max_retained_generations > 0 && + retained_generation_count() >= m_limits.max_retained_generations) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::retention_limit, + "ServiceRegistry::prepare_batch: retained generation limit reached")); + } + + auto staged = std::make_shared(); + staged->parent_snap = current_snap ? current_snap->parent_snap : nullptr; + staged->live_parent = current_snap ? current_snap->live_parent : nullptr; + + // Validate interfaces, IDs, nulls, edge caps, and coalesce shared-object + // lifecycle aliases into single nodes. + std::unordered_map iface_to_node; + std::unordered_map obj_to_node; + std::unordered_map id_to_obj; + std::vector raw_nodes; + std::size_t total_edges = 0; + + for (const auto& item : items) { + if (!item.owner || item.object_key == nullptr) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::invalid_argument, + "ServiceRegistry::prepare_batch: null service provider")); + } + if (staged->services.contains(item.interface_type)) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::duplicate_interface, + "ServiceRegistry::prepare_batch: duplicate interface in batch")); + } + + const void* canonical_obj = + item.service != nullptr + ? static_cast(item.service) + : item.object_key; + if (!item.id.empty()) { + const auto [it, inserted] = + id_to_obj.emplace(item.id, canonical_obj); + if (!inserted && it->second != canonical_obj) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::conflict, + "ServiceRegistry::prepare_batch: conflicting service id '" + + item.id + "'")); + } + } + + staged->services.emplace( + item.interface_type, + detail::SnapshotEntry{item.owner, item.service, item.id}); + staged->legacy_order.push_back(item.interface_type); + + total_edges += item.required_deps.size() + item.optional_deps.size(); + if (total_edges > m_limits.max_dependency_edges) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::overloaded, + "ServiceRegistry::prepare_batch: dependency edge limit exceeded")); + } + + auto [oit, o_inserted] = + obj_to_node.emplace(canonical_obj, raw_nodes.size()); + if (o_inserted) { + std::string node_id = item.id; + if (node_id.empty() && item.service != nullptr) { + node_id = std::string{item.service->service_name()}; + } + raw_nodes.push_back(detail::LifecycleNode{ + .id = std::move(node_id), + .object_key = canonical_obj, + .owner = item.owner, + .service = item.service, + .managed = item.managed, + .seq = raw_nodes.size(), + .dep_indices = {}, + }); + } + iface_to_node.emplace(item.interface_type, oit->second); + } + + // Build DAG edges: dep_idx -> dependent_idx. + const std::size_t n = raw_nodes.size(); + std::vector> adj(n); + std::vector indegree(n, 0); + std::unordered_set edge_dedup; + + for (const auto& item : items) { + const std::size_t u = iface_to_node.at(item.interface_type); + auto add_dep = [&](std::type_index dep_iface, + bool required) -> Void::Result::Result { + const auto dit = iface_to_node.find(dep_iface); + if (dit == iface_to_node.end()) { + bool in_parent = false; + if (staged->parent_snap) { + in_parent = detail::has_in_parent_chain( + *staged->parent_snap, dep_iface, + m_limits.max_parent_levels); + } + if (!in_parent && staged->live_parent != nullptr) { + if (auto ps = staged->live_parent->acquire_snapshot()) { + in_parent = ps->services.contains(dep_iface); + } + } + if (required && !in_parent) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::missing_dependency, + "ServiceRegistry::prepare_batch: missing required dependency")); + } + return {}; + } + const std::size_t dep = dit->second; + if (dep == u) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::cycle_detected, + "ServiceRegistry::prepare_batch: self-dependency cycle")); + } + const std::uint64_t edge_key = + (static_cast(dep) << 32) | + static_cast(u); + if (edge_dedup.insert(edge_key).second) { + adj[dep].push_back(u); + ++indegree[u]; + } + return {}; + }; + + for (const auto& dep : item.required_deps) { + if (auto r = add_dep(dep, true); !r) { + return Void::Result::fail(std::move(r).error()); + } + } + for (const auto& dep : item.optional_deps) { + if (auto r = add_dep(dep, false); !r) { + return Void::Result::fail(std::move(r).error()); + } + } + } + + // Deterministic Kahn topological sort breaking ties by registration seq. + std::priority_queue, + std::greater> + ready; + for (std::size_t i = 0; i < n; ++i) { + if (indegree[i] == 0) { + ready.push(i); + } + } + + std::vector sorted; + sorted.reserve(n); + while (!ready.empty()) { + const std::size_t u = ready.top(); + ready.pop(); + sorted.push_back(std::move(raw_nodes[u])); + for (const std::size_t v : adj[u]) { + if (--indegree[v] == 0) { + ready.push(v); + } + } + } + + if (sorted.size() != n) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::cycle_detected, + "ServiceRegistry::prepare_batch: dependency cycle detected")); + } + + staged->lifecycle_nodes = std::move(sorted); + PreparedPublication prep; + prep.expected_epoch = expected; + prep.snapshot = std::move(staged); + prep.valid = true; + prep.started = false; + prep.aborted = false; + return prep; + } + + Void::Result::Result ServiceRegistry::rollback_started_nodes( + const std::vector& nodes, std::size_t count, + const Void::Result::Error& primary_error) + { + std::string stop_errs; + for (std::size_t i = count; i > 0; --i) { + const auto& node = nodes[i - 1]; + if (node.managed != nullptr) { + auto sr = node.managed->stop_checked(); + if (!sr) { + if (!stop_errs.empty()) stop_errs += "; "; + stop_errs += sr.error().message(); + } + } else if (node.service != nullptr) { + try { + node.service->on_stop(); + } catch (const std::exception& ex) { + if (!stop_errs.empty()) stop_errs += "; "; + stop_errs += ex.what(); + } catch (...) { + if (!stop_errs.empty()) stop_errs += "; "; + stop_errs += "unknown stop exception"; + } + } + } + if (stop_errs.empty()) { + return Void::Result::fail(primary_error); + } + return Void::Result::fail(make_service_error( + static_cast(primary_error.code().value), + primary_error.message() + " (rollback stop errors: " + stop_errs + + ")")); + } + + Void::Result::Result + ServiceRegistry::start_staged(PreparedPublication& prepared, + Async::OperationOptions options) + { + if (!prepared.valid || !prepared.snapshot || prepared.aborted) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::invalid_argument, + "ServiceRegistry::start_staged: invalid or aborted publication")); + } + if (prepared.started) { + return {}; + } + + const auto& nodes = prepared.snapshot->lifecycle_nodes; + for (std::size_t i = 0; i < nodes.size(); ++i) { + if (options.stop.stop_requested()) { + prepared.aborted = true; + return rollback_started_nodes( + nodes, i, + make_service_error( + ServiceErrorCode::cancelled, + "ServiceRegistry::start_staged: cancelled during startup")); + } + if (Async::is_deadline_expired(options, *m_clock)) { + prepared.aborted = true; + return rollback_started_nodes( + nodes, i, + make_service_error( + ServiceErrorCode::timeout, + "ServiceRegistry::start_staged: deadline expired during startup")); + } + + const auto& node = nodes[i]; + if (node.managed != nullptr) { + auto sr = node.managed->start_checked(); + if (!sr) { + node.managed->abort_start(); + prepared.aborted = true; + return rollback_started_nodes(nodes, i, sr.error()); + } + auto rr = node.managed->check_readiness(); + if (!rr) { + node.managed->abort_start(); + prepared.aborted = true; + return rollback_started_nodes( + nodes, i, + make_service_error(ServiceErrorCode::not_ready, + rr.error().message())); + } + } else if (node.service != nullptr) { + try { + node.service->on_start(); + } catch (const std::exception& ex) { + prepared.aborted = true; + return rollback_started_nodes( + nodes, i, + make_service_error(ServiceErrorCode::start_failed, + ex.what())); + } catch (...) { + prepared.aborted = true; + return rollback_started_nodes( + nodes, i, + make_service_error( + ServiceErrorCode::start_failed, + "ServiceRegistry: service on_start threw")); + } + } + } + + prepared.started = true; + return {}; + } + + Void::Result::Result + ServiceRegistry::publish(PreparedPublication&& prepared) + { + if (!prepared.valid || !prepared.snapshot || prepared.aborted) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::invalid_argument, + "ServiceRegistry::publish: invalid or aborted publication")); + } + + PublicationEpoch new_epoch = 0; + std::size_t provider_count = 0; + std::size_t retained = 0; + std::shared_ptr old_snap; + + { + std::lock_guard write_lk{m_write_mu}; + { + std::lock_guard snap_lk{m_snapshot_mu}; + if (m_stopping) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::service_stopping, + "ServiceRegistry::publish: registry is stopping")); + } + if (prepared.expected_epoch.has_value() && + *prepared.expected_epoch != m_epoch) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::conflict, + "ServiceRegistry::publish: expected epoch conflict")); + } + } + + if (m_limits.max_retained_generations > 0 && + prune_and_count_retained_locked() >= + m_limits.max_retained_generations) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::retention_limit, + "ServiceRegistry::publish: retained generation limit reached")); + } + + new_epoch = ++m_epoch; + prepared.snapshot->epoch = new_epoch; + prepared.snapshot->gen_token = detail::make_retention_token( + m_retention_state, new_epoch, + "generation#" + std::to_string(new_epoch)); + provider_count = prepared.snapshot->services.size(); + + { + std::lock_guard snap_lk{m_snapshot_mu}; + if (m_stopping) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::service_stopping, + "ServiceRegistry::publish: registry is stopping")); + } + old_snap = std::exchange(m_active_snapshot, + std::move(prepared.snapshot)); + } + retained = prune_and_count_retained_locked(); + m_started = prepared.started; + } + prepared.valid = false; + + // Retire old snapshot strictly outside locks, then notify observers. + old_snap.reset(); + notify_observers(ServiceObservation{ + .epoch = new_epoch, + .provider_count = provider_count, + .retained_generations = retained, + .duration_ns = 0, + .rollback = false, + .detail = "published", + }); + return new_epoch; + } + + Void::Result::Result + ServiceRegistry::start_and_publish(ProviderSet set, + ExpectedEpoch expected, + Async::OperationOptions options) + { + const auto t0 = m_clock->now(); + auto prep = prepare_batch(std::move(set), expected); + if (!prep) { + return Void::Result::fail(std::move(prep).error()); + } + auto staged = std::move(*prep); + if (auto sr = start_staged(staged, options); !sr) { + const auto dt = static_cast( + std::max(0, (m_clock->now() - t0).count())); + notify_observers(ServiceObservation{ + .epoch = epoch(), + .provider_count = 0, + .retained_generations = retained_generation_count(), + .duration_ns = dt, + .rollback = true, + .detail = sr.error().message(), + }); + return Void::Result::fail(std::move(sr).error()); + } + auto snapshot_copy = staged.snapshot; + auto pub = publish(std::move(staged)); + if (!pub) { + return Void::Result::fail( + rollback_started_nodes(snapshot_copy->lifecycle_nodes, + snapshot_copy->lifecycle_nodes.size(), + pub.error()) + .error()); + } + return pub; + } + + Void::Result::Result + ServiceRegistry::start(Async::OperationOptions options) + { + auto snap = acquire_snapshot(); + if (!snap) { + return Void::Result::fail(make_service_error( + ServiceErrorCode::service_stopping, + "ServiceRegistry::start: registry is stopping")); + } + + const auto& nodes = snap->lifecycle_nodes; + for (std::size_t i = 0; i < nodes.size(); ++i) { + if (options.stop.stop_requested()) { + return rollback_started_nodes( + nodes, i, + make_service_error(ServiceErrorCode::cancelled, + "ServiceRegistry::start: cancelled")); + } + if (Async::is_deadline_expired(options, *m_clock)) { + return rollback_started_nodes( + nodes, i, + make_service_error(ServiceErrorCode::timeout, + "ServiceRegistry::start: timed out")); + } + const auto& node = nodes[i]; + if (node.managed != nullptr) { + auto sr = node.managed->start_checked(); + if (!sr) { + node.managed->abort_start(); + return rollback_started_nodes(nodes, i, sr.error()); + } + auto rr = node.managed->check_readiness(); + if (!rr) { + node.managed->abort_start(); + return rollback_started_nodes( + nodes, i, + make_service_error(ServiceErrorCode::not_ready, + rr.error().message())); + } + } else if (node.service != nullptr) { + try { + node.service->on_start(); + } catch (const std::exception& ex) { + return rollback_started_nodes( + nodes, i, + make_service_error(ServiceErrorCode::start_failed, + ex.what())); + } catch (...) { + return rollback_started_nodes( + nodes, i, + make_service_error( + ServiceErrorCode::start_failed, + "ServiceRegistry::start: on_start threw")); + } + } + } + + std::lock_guard write_lk{m_write_mu}; + m_started = true; + return {}; + } + + Void::Result::Result + ServiceRegistry::close_and_join(Async::OperationOptions options) + { + std::shared_ptr active_to_stop; + { + std::lock_guard snap_lk{m_snapshot_mu}; + m_stopping = true; + active_to_stop = std::exchange( + m_active_snapshot, std::make_shared()); + } + + ShutdownReport report; + if (active_to_stop) { + for (auto it = active_to_stop->lifecycle_nodes.rbegin(); + it != active_to_stop->lifecycle_nodes.rend(); ++it) { + const auto& node = *it; + const std::string label = + !node.id.empty() ? node.id : std::string{""}; + if (node.managed != nullptr) { + auto sr = node.managed->stop_checked(); + if (!sr) { + report.stop_errors.push_back(std::move(sr).error()); + } else { + report.stopped_services.push_back(label); + } + } else if (node.service != nullptr) { + try { + node.service->on_stop(); + report.stopped_services.push_back(label); + } catch (const std::exception& ex) { + report.stop_errors.push_back(make_service_error( + ServiceErrorCode::stop_failed, ex.what())); + } catch (...) { + report.stop_errors.push_back(make_service_error( + ServiceErrorCode::stop_failed, + "ServiceRegistry::close_and_join: on_stop threw")); + } + } + } + } + active_to_stop.reset(); + + // Check retained generation pins; wait up to deadline only when using the + // real monotonic clock and an explicit deadline. + const bool can_wait_deadline = + options.deadline.has_value() && + m_clock == &Void::Time::SystemMonotonicClock::instance(); + + std::unique_lock lk{m_retention_state->mu}; + auto collect_live = [&]() { + std::erase_if(m_retention_state->entries, + [](const detail::RetentionEntry& e) { + return e.token.expired(); + }); + return m_retention_state->entries.empty(); + }; + + if (!collect_live() && can_wait_deadline && !options.stop.stop_requested()) { + while (!collect_live() && !options.stop.stop_requested()) { + const auto now = m_clock->now(); + if (now >= *options.deadline) { + break; + } + const auto rem = *options.deadline - now; + m_retention_state->cv.wait_for( + lk, std::chrono::duration_cast( + rem)); + } + } + + for (const auto& entry : m_retention_state->entries) { + if (!entry.token.expired()) { + report.incomplete_owners.push_back(entry.label); + } + } + return report; + } + +} // namespace Void::Service diff --git a/src/Service/module.cmake b/src/Service/module.cmake index da42890..fdecc27 100644 --- a/src/Service/module.cmake +++ b/src/Service/module.cmake @@ -1,3 +1,4 @@ void_add_module(Service - INTERNAL_DEPS Core Functional LogState + INTERNAL_DEPS Core Functional Time Async LogState + EXCLUDE_HEADERS Void/Service/PluginService.hpp ) diff --git a/src/ServicePlugin/module.cmake b/src/ServicePlugin/module.cmake new file mode 100644 index 0000000..125158e --- /dev/null +++ b/src/ServicePlugin/module.cmake @@ -0,0 +1,4 @@ +void_add_module(ServicePlugin + INTERNAL_DEPS Service Plugin LogState + EXTRA_HEADERS Void/Service/PluginService.hpp +) diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index a580065..0e4289c 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -237,6 +237,21 @@ if(_has_storage) run_consumer(StorageOnly "${install_prefix}" "StorageOnly" ${_no_external_deps}) endif() +has_modules(_has_service Service Core Functional Time Async LogState) +if(_has_service) + run_consumer(ServiceOnly "${install_prefix}" "ServiceOnly" ${_no_external_deps}) +endif() + +has_modules(_has_service_plugin ServicePlugin Service Plugin Functional System Data LogState Text Time Async Core) +if(_has_service_plugin) + run_consumer(ServicePluginOnly "${install_prefix}" "ServicePluginOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/package/ServiceOnly/CMakeLists.txt b/tests/package/ServiceOnly/CMakeLists.txt new file mode 100644 index 0000000..eae5283 --- /dev/null +++ b/tests/package/ServiceOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidServiceOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Service) + +add_executable(void_service_only_consumer main.cpp) +target_link_libraries(void_service_only_consumer PRIVATE Void::Service) +target_compile_features(void_service_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME ServiceOnlyConsumer COMMAND void_service_only_consumer) diff --git a/tests/package/ServiceOnly/main.cpp b/tests/package/ServiceOnly/main.cpp new file mode 100644 index 0000000..94c9160 --- /dev/null +++ b/tests/package/ServiceOnly/main.cpp @@ -0,0 +1,36 @@ +#include +#include +#include + +#include +#include + +namespace +{ + struct ICounter { + virtual ~ICounter() = default; + virtual int value() const = 0; + }; + + struct Counter final : Void::Service::IManagedService, ICounter { + std::string_view service_name() const override { return "counter"; } + int value() const override { return 42; } + }; +} // namespace + +int main() +{ + Void::Service::ServiceRegistry reg; + Void::Service::ProviderSet set; + set.add("counter", std::make_shared()); + auto ep = reg.start_and_publish(std::move(set)); + if (!ep) { + return 1; + } + auto handle = reg.acquire(); + if (!handle || (*handle)->value() != 42 || handle->generation() != *ep) { + return 2; + } + auto report = reg.close_and_join(); + return report && !report->clean() ? 0 : 3; // handle still held until return +} diff --git a/tests/package/ServicePluginOnly/CMakeLists.txt b/tests/package/ServicePluginOnly/CMakeLists.txt new file mode 100644 index 0000000..1f3fa5d --- /dev/null +++ b/tests/package/ServicePluginOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidServicePluginOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS ServicePlugin) + +add_executable(void_service_plugin_only_consumer main.cpp) +target_link_libraries(void_service_plugin_only_consumer PRIVATE Void::ServicePlugin) +target_compile_features(void_service_plugin_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME ServicePluginOnlyConsumer COMMAND void_service_plugin_only_consumer) diff --git a/tests/package/ServicePluginOnly/main.cpp b/tests/package/ServicePluginOnly/main.cpp new file mode 100644 index 0000000..813ccca --- /dev/null +++ b/tests/package/ServicePluginOnly/main.cpp @@ -0,0 +1,12 @@ +#include + +int main() +{ + Void::Plugin::PluginManager plugins; + Void::Service::ServiceRegistry registry; + Void::Service::PluginServiceBinding binding{ + plugins, registry, "missing"}; + auto direct = Void::Service::acquire_plugin_service( + plugins, "missing"); + return !binding.bind() && !direct.has_value() ? 0 : 1; +} diff --git a/tests/standalone/Service/ServiceHardening.cpp b/tests/standalone/Service/ServiceHardening.cpp new file mode 100644 index 0000000..c27f1ca --- /dev/null +++ b/tests/standalone/Service/ServiceHardening.cpp @@ -0,0 +1,451 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using Void::Service::ExpectedEpoch; + using Void::Service::IManagedService; + using Void::Service::IService; + using Void::Service::ProviderSet; + using Void::Service::ServiceErrorCode; + using Void::Service::ServiceLimits; + using Void::Service::ServiceRegistry; + using Void::Time::ManualClock; + + struct IA { + virtual ~IA() = default; + [[nodiscard]] virtual int id() const = 0; + }; + + struct IB { + virtual ~IB() = default; + [[nodiscard]] virtual int tag() const = 0; + }; + + struct IC { + virtual ~IC() = default; + [[nodiscard]] virtual int rank() const = 0; + }; + + class TrackedService final : public IManagedService, public IA + { + public: + + TrackedService(std::string name, int val, + std::vector* log, + bool fail_start = false, + bool fail_ready = false, + bool throw_stop = false) + : m_name(std::move(name)), m_val(val), m_log(log), + m_fail_start(fail_start), m_fail_ready(fail_ready), + m_throw_stop(throw_stop) + { + } + + [[nodiscard]] std::string_view service_name() const override + { + return m_name; + } + + [[nodiscard]] int id() const override { return m_val; } + + [[nodiscard]] Void::Result::Result start_checked() override + { + if (m_log != nullptr) { + m_log->push_back("start:" + m_name); + } + if (m_fail_start) { + return Void::Result::fail(Void::Service::make_service_error( + ServiceErrorCode::start_failed, + "start failed for " + m_name)); + } + return {}; + } + + [[nodiscard]] Void::Result::Result + check_readiness() const override + { + if (m_fail_ready) { + return Void::Result::fail(Void::Service::make_service_error( + ServiceErrorCode::not_ready, + "not ready: " + m_name)); + } + return {}; + } + + void abort_start() noexcept override + { + if (m_log != nullptr) { + m_log->push_back("abort:" + m_name); + } + } + + [[nodiscard]] Void::Result::Result stop_checked() override + { + if (m_log != nullptr) { + m_log->push_back("stop:" + m_name); + } + if (m_throw_stop) { + return Void::Result::fail(Void::Service::make_service_error( + ServiceErrorCode::stop_failed, + "stop boom: " + m_name)); + } + return {}; + } + + private: + + std::string m_name; + int m_val; + std::vector* m_log; + bool m_fail_start; + bool m_fail_ready; + bool m_throw_stop; + }; + + class DualInterfaceService final : public IManagedService, public IA, public IB + { + public: + + explicit DualInterfaceService(std::vector* log) + : m_log(log) + { + } + + [[nodiscard]] std::string_view service_name() const override + { + return "Dual"; + } + [[nodiscard]] int id() const override { return 10; } + [[nodiscard]] int tag() const override { return 20; } + + [[nodiscard]] Void::Result::Result start_checked() override + { + ++starts; + if (m_log != nullptr) m_log->push_back("dual:start"); + return {}; + } + [[nodiscard]] Void::Result::Result stop_checked() override + { + ++stops; + if (m_log != nullptr) m_log->push_back("dual:stop"); + return {}; + } + + int starts{0}; + int stops{0}; + std::vector* m_log; + }; + + class ReentrantDtorProvider final : public IA + { + public: + + ReentrantDtorProvider(ServiceRegistry& reg, int val, + std::atomic* observations) + : m_reg(reg), m_val(val), m_obs(observations) + { + } + + ~ReentrantDtorProvider() override + { + if (auto h = m_reg.acquire(); h) { + if (m_obs != nullptr) { + m_obs->fetch_add((*h)->id(), std::memory_order_relaxed); + } + } + } + + [[nodiscard]] int id() const override { return m_val; } + + private: + + ServiceRegistry& m_reg; + int m_val; + std::atomic* m_obs; + }; + + class ReentrantStartService final : public IService, public IB + { + public: + + ReentrantStartService(ServiceRegistry& reg, std::atomic* seen) + : m_reg(reg), m_seen(seen) + { + } + + [[nodiscard]] std::string_view service_name() const override + { + return "ReentrantStart"; + } + + void on_start() override + { + if (auto a = m_reg.acquire(); a) { + m_seen->store((*a)->id(), std::memory_order_relaxed); + } + m_reg.provide(std::make_shared(99)); + } + + [[nodiscard]] int tag() const override { return 7; } + + private: + + struct SimpleC final : IC { + explicit SimpleC(int r) : rank_val(r) {} + [[nodiscard]] int rank() const override { return rank_val; } + int rank_val; + }; + + ServiceRegistry& m_reg; + std::atomic* m_seen; + }; +} // namespace + +Void::Testing::Test service_concurrent_remove_acquire_and_reentrant_dtor() +{ + ServiceRegistry reg; + std::atomic dtor_observations{0}; + reg.provide( + std::make_shared(reg, 1, &dtor_observations)); + + auto held_first = reg.acquire(); + Void::Testing::expect(held_first.has_value()); + Void::Testing::expect_eq((*held_first)->id(), 1); + + // Replace with another ReentrantDtorProvider; releasing held_first + // later must invoke ~ReentrantDtorProvider cleanly without deadlocking. + std::atomic stop{false}; + std::thread writer([&] { + for (int i = 2; i < 60 && !stop.load(std::memory_order_relaxed); ++i) { + reg.provide(std::make_shared( + reg, i, &dtor_observations)); + if (i % 7 == 0) { + (void)reg.remove(); + } + } + }); + std::thread reader([&] { + for (int i = 0; i < 200; ++i) { + if (auto h = reg.acquire(); h) { + Void::Testing::expect((*h)->id() >= 1); + } + } + stop.store(true, std::memory_order_relaxed); + }); + writer.join(); + reader.join(); + + Void::Testing::expect_eq((*held_first)->id(), 1); + held_first = Void::Result::fail(Void::Service::make_service_error( + ServiceErrorCode::missing_service, "drop")); + Void::Testing::expect(dtor_observations.load(std::memory_order_relaxed) >= + 0); +} + +Void::Testing::Test service_start_all_allows_reentrant_acquire_and_provide() +{ + ServiceRegistry reg; + std::vector log; + std::atomic seen{0}; + reg.provide(std::make_shared("A", 42, &log)); + reg.provide(std::make_shared(reg, &seen)); + + reg.start_all(); + Void::Testing::expect_eq(seen.load(std::memory_order_relaxed), 42); + auto c = reg.acquire(); + Void::Testing::expect(c.has_value()); + Void::Testing::expect_eq((*c)->rank(), 99); +} + +Void::Testing::Test service_dag_ordering_aliases_cycles_and_rollback() +{ + std::vector log; + ServiceRegistry reg; + + // Baseline snapshot that must remain untouched if staged batch fails. + { + ProviderSet base; + base.add("baseline", std::make_shared("base", 100, &log)); + auto ep = reg.start_and_publish(std::move(base)); + Void::Testing::expect(ep.has_value()); + Void::Testing::expect_eq(*ep, std::uint64_t{1}); + } + log.clear(); + + // Missing dependency rejected. + { + ProviderSet bad; + bad.add("B", std::make_shared(&log), + {std::type_index{typeid(IC)}}); + auto prep = reg.prepare_batch(std::move(bad)); + Void::Testing::expect(!prep.has_value()); + Void::Testing::expect_eq(prep.error().code().value, + static_cast( + ServiceErrorCode::missing_dependency)); + } + + // Cycle rejected. + { + ProviderSet cyc; + auto dual = std::make_shared(&log); + cyc.add("A", std::make_shared("A", 1, &log), + {std::type_index{typeid(IB)}}); + cyc.add("B", dual, {std::type_index{typeid(IA)}}); + auto prep = reg.prepare_batch(std::move(cyc)); + Void::Testing::expect(!prep.has_value()); + Void::Testing::expect_eq( + prep.error().code().value, + static_cast(ServiceErrorCode::cycle_detected)); + } + + // Middle node failure aborts failed node and rolls back started nodes in + // reverse dependency order, leaving baseline untouched. + { + struct RankImpl final : IManagedService, IC { + RankImpl(std::string n, std::vector* l, bool fail) + : impl(std::move(n), 3, l, fail) {} + std::string_view service_name() const override + { return impl.service_name(); } + Void::Result::Result start_checked() override + { return impl.start_checked(); } + Void::Result::Result check_readiness() const override + { return impl.check_readiness(); } + void abort_start() noexcept override { impl.abort_start(); } + Void::Result::Result stop_checked() override + { return impl.stop_checked(); } + int rank() const override { return 3; } + TrackedService impl; + }; + auto dual = std::make_shared(&log); + ProviderSet fail_batch; + // IB depends on IA; IA registered second so DAG must still start IA before IB. + fail_batch.add("B", dual, {std::type_index{typeid(IA)}}); + fail_batch.add("A", std::make_shared("A", 1, &log)); + fail_batch.add( + "C", std::make_shared("C", &log, true), + {std::type_index{typeid(IB)}}); + + auto res = reg.start_and_publish(std::move(fail_batch)); + Void::Testing::expect(!res.has_value()); + Void::Testing::expect_eq( + res.error().code().value, + static_cast(ServiceErrorCode::start_failed)); + // Baseline handle still resolves to id 100. + auto active = reg.acquire(); + Void::Testing::expect(active.has_value()); + Void::Testing::expect_eq((*active)->id(), 100); + // Sequence: start:A, dual:start, start:C, abort:C, dual:stop, stop:A. + Void::Testing::expect_eq(log.size(), std::size_t{6}); + Void::Testing::expect_eq(log[0], std::string{"start:A"}); + Void::Testing::expect_eq(log[1], std::string{"dual:start"}); + Void::Testing::expect_eq(log[2], std::string{"start:C"}); + Void::Testing::expect_eq(log[3], std::string{"abort:C"}); + Void::Testing::expect_eq(log[4], std::string{"dual:stop"}); + Void::Testing::expect_eq(log[5], std::string{"stop:A"}); + } + + // Alias of one lifecycle object starts/stops ONCE. + log.clear(); + auto dual = std::make_shared(&log); + ProviderSet alias_batch; + alias_batch.add("dual.svc", dual); + alias_batch.add_alias("dual.svc.alias", dual); + auto ep = reg.start_and_publish(std::move(alias_batch)); + Void::Testing::expect(ep.has_value()); + Void::Testing::expect_eq(dual->starts, 1); + Void::Testing::expect_eq(reg.acquire().value()->id(), 10); + Void::Testing::expect_eq(reg.acquire().value()->tag(), 20); +} + +Void::Testing::Test service_snapshot_parent_survives_parent_destruction() +{ + std::unique_ptr child; + { + ServiceRegistry parent; + ProviderSet ps; + ps.add("A", std::make_shared("A", 77, nullptr)); + Void::Testing::expect( + parent.start_and_publish(std::move(ps)).has_value()); + + auto built = ServiceRegistry::from_parent_snapshot(parent.snapshot()); + Void::Testing::expect(built.has_value()); + child = std::move(*built); + } // parent destroyed here! + + auto h = child->acquire(); + Void::Testing::expect(h.has_value()); + Void::Testing::expect_eq((*h)->id(), 77); +} + +Void::Testing::Test service_retention_cap_and_close_incomplete_owners() +{ + ManualClock clock; + ServiceLimits limits{}; + limits.max_retained_generations = 4; + + ServiceRegistry reg{limits, clock}; + std::vector log; + std::vector> pinned; + + for (int gen = 1; gen <= 4; ++gen) { + ProviderSet ps; + ps.add( + "A", + std::make_shared( + "A" + std::to_string(gen), gen, &log, false, false, gen == 4)); + auto ep = reg.start_and_publish(std::move(ps)); + Void::Testing::expect(ep.has_value()); + auto h = reg.acquire(); + Void::Testing::expect(h.has_value()); + Void::Testing::expect_eq(h->generation(), *ep); + pinned.push_back(std::move(*h)); + } + + // 4 distinct generations pinned -> 5th publication rejected with retention_limit. + { + ProviderSet ps5; + ps5.add("A", std::make_shared("A5", 5, &log)); + auto prep5 = reg.prepare_batch(std::move(ps5)); + Void::Testing::expect(!prep5.has_value()); + Void::Testing::expect_eq( + prep5.error().code().value, + static_cast(ServiceErrorCode::retention_limit)); + } + + // Dropping oldest handle frees generation 1, allowing generation 5. + pinned.erase(pinned.begin()); + { + ProviderSet ps5; + ps5.add("A", std::make_shared("A5", 5, &log)); + auto ep5 = reg.start_and_publish(std::move(ps5)); + Void::Testing::expect(ep5.has_value()); + } + + // close_and_join closes admission, reports any stop error, and reports + // surviving pinned generations in incomplete_owners without freeing them. + auto rep = reg.close_and_join(); + Void::Testing::expect(rep.has_value()); + Void::Testing::expect(!rep->clean()); + Void::Testing::expect(!rep->incomplete_owners.empty()); + + auto post_close = reg.acquire(); + Void::Testing::expect(!post_close.has_value()); + Void::Testing::expect_eq( + post_close.error().code().value, + static_cast(ServiceErrorCode::service_stopping)); + + // Pinned handles remain dereferenceable until dropped. + Void::Testing::expect_eq(pinned.front()->id(), 2); +} From a24e086e47f2633c16db890683ac3638ac7e491f Mon Sep 17 00:00:00 2001 From: faumaray Date: Thu, 26 Nov 2026 16:16:29 +0300 Subject: [PATCH 3/9] feat(plugin): add CAbi.h v1, CModuleHost quiesce/reload/pins, and unlocked PluginManager staging --- include/Void/Plugin/CAbi.h | 184 +++ include/Void/Plugin/CAbiAdapter.hpp | 165 ++ include/Void/Plugin/Host.hpp | 350 ++++ include/Void/Plugin/Manager.hpp | 12 +- src/Plugin/Host.cpp | 1647 +++++++++++++++++++ src/Plugin/Manager.cpp | 332 ++-- src/Plugin/module.cmake | 2 +- tests/CMakeLists.txt | 52 + tests/package/InstalledComponents.cmake | 10 + tests/package/PluginOnly/CMakeLists.txt | 11 + tests/package/PluginOnly/main.cpp | 18 + tests/plugins/CAbiBadPlugin.c | 78 + tests/plugins/CAbiDepPlugin.c | 104 ++ tests/plugins/CAbiPluginV1.c | 488 ++++++ tests/plugins/CAbiPluginV2.c | 357 ++++ tests/standalone/Plugin/PluginHardening.cpp | 315 ++++ 16 files changed, 3961 insertions(+), 164 deletions(-) create mode 100644 include/Void/Plugin/CAbi.h create mode 100644 include/Void/Plugin/CAbiAdapter.hpp create mode 100644 include/Void/Plugin/Host.hpp create mode 100644 src/Plugin/Host.cpp create mode 100644 tests/package/PluginOnly/CMakeLists.txt create mode 100644 tests/package/PluginOnly/main.cpp create mode 100644 tests/plugins/CAbiBadPlugin.c create mode 100644 tests/plugins/CAbiDepPlugin.c create mode 100644 tests/plugins/CAbiPluginV1.c create mode 100644 tests/plugins/CAbiPluginV2.c create mode 100644 tests/standalone/Plugin/PluginHardening.cpp diff --git a/include/Void/Plugin/CAbi.h b/include/Void/Plugin/CAbi.h new file mode 100644 index 0000000..cfe6db3 --- /dev/null +++ b/include/Void/Plugin/CAbi.h @@ -0,0 +1,184 @@ +#ifndef VOID_PLUGIN_CABI_H +#define VOID_PLUGIN_CABI_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define VOID_CABI_MAJOR_V1 UINT32_C(1) +#define VOID_CABI_MINOR_V1 UINT32_C(0) +#define VOID_MODULE_QUERY_SYMBOL_V1 "void_module_query_v1" + +#define VOID_CAP_STATELESS_RELOAD (UINT64_C(1) << 0) +#define VOID_CAP_STATEFUL_CHECKPOINT (UINT64_C(1) << 1) +#define VOID_CAP_ASYNC_OPS (UINT64_C(1) << 2) +#define VOID_CAP_SERVICE_INTERFACES (UINT64_C(1) << 3) + +enum void_status_v1 { + VOID_STATUS_OK = 0, + VOID_STATUS_INVALID_ARGUMENT = 1, + VOID_STATUS_NOT_FOUND = 2, + VOID_STATUS_CONFLICT = 3, + VOID_STATUS_CANCELLED = 4, + VOID_STATUS_TIMEOUT = 5, + VOID_STATUS_OVERLOADED = 6, + VOID_STATUS_UNSUPPORTED = 7, + VOID_STATUS_CORRUPT = 8, + VOID_STATUS_EXHAUSTED = 9, + VOID_STATUS_INTERNAL = 10, + VOID_STATUS_NOT_READY = 11, + VOID_STATUS_QUIESCING = 12, + VOID_STATUS_STATE_REJECTED = 13, + VOID_STATUS_RESTART_REQUIRED = 14 +}; + +enum void_activation_policy_v1 { + VOID_POLICY_RELOADABLE = 0, + VOID_POLICY_RESTART_REQUIRED = 1, + VOID_POLICY_INSTALLER_REQUIRED = 2 +}; + +typedef struct void_module_handle void_module_handle; +typedef struct void_operation_handle void_operation_handle; +typedef struct void_host_context void_host_context; + +typedef struct void_bytes_v1 { + const uint8_t* data; + uint64_t size; +} void_bytes_v1; + +typedef struct void_owned_bytes_v1 { + const uint8_t* data; + uint64_t size; + void (*release)(void* release_ctx, const uint8_t* data, uint64_t size); + void* release_ctx; +} void_owned_bytes_v1; + +typedef struct void_interface_id_v1 { + uint8_t bytes[16]; +} void_interface_id_v1; + +typedef struct void_dependency_v1 { + const char* module_id; + const char* version_range; + uint8_t optional_dep; + uint8_t reserved[7]; +} void_dependency_v1; + +typedef struct void_module_info_v1 { + uint32_t struct_size; + uint32_t reserved; + const char* module_id; + const char* version; + uint32_t activation_policy; + uint32_t state_schema_version; + const void_dependency_v1* dependencies; + uint64_t dependency_count; +} void_module_info_v1; + +typedef struct void_op_options_v1 { + uint32_t struct_size; + uint32_t flags; + uint64_t deadline_ns; + uint8_t stop_requested; + uint8_t reserved[7]; +} void_op_options_v1; + +typedef struct void_error_detail_v1 { + uint32_t struct_size; + int32_t status; + const char* message; + void (*release)(void* release_ctx, const char* message); + void* release_ctx; +} void_error_detail_v1; + +typedef struct void_interface_view_v1 { + uint32_t struct_size; + uint32_t major; + uint32_t minor; + uint32_t table_size; + const void* function_table; +} void_interface_view_v1; + +typedef struct void_host_api_v1 { + uint32_t struct_size; + uint32_t abi_major; + uint32_t abi_minor; + uint32_t reserved; + void_host_context* host_ctx; + uint64_t generation; + uint64_t (*monotonic_now_ns)(void_host_context* ctx); + int32_t (*acquire_activity_pin)(void_host_context* ctx, uint64_t generation); + void (*release_activity_pin)(void_host_context* ctx, uint64_t generation); + void (*log_message)(void_host_context* ctx, int32_t level, const char* msg); +} void_host_api_v1; + +typedef void (*void_async_complete_fn)(void* user_ctx, + int32_t status, + const void_bytes_v1* result_bytes); + +typedef struct void_module_api_v1 { + uint32_t struct_size; + uint32_t abi_major; + uint32_t abi_minor; + uint32_t reserved; + uint64_t capabilities; + + int32_t (*get_info)(void_module_info_v1* out_info); + int32_t (*create)(const void_host_api_v1* host_api, + void_module_handle** out_handle); + int32_t (*activate)(void_module_handle* handle, + void_bytes_v1 config, + void_error_detail_v1* out_err); + int32_t (*readiness)(void_module_handle* handle, + uint32_t* out_ready, + void_error_detail_v1* out_err); + int32_t (*quiesce)(void_module_handle* handle, + const void_op_options_v1* opts, + void_error_detail_v1* out_err); + int32_t (*resume)(void_module_handle* handle, void_error_detail_v1* out_err); + int32_t (*checkpoint)(void_module_handle* handle, + const void_op_options_v1* opts, + void_owned_bytes_v1* out_state, + void_error_detail_v1* out_err); + int32_t (*restore)(void_module_handle* handle, + void_bytes_v1 state, + void_error_detail_v1* out_err); + int32_t (*query_interface)(void_module_handle* handle, + const void_interface_id_v1* iface_id, + uint32_t min_major, + uint32_t min_table_size, + void_interface_view_v1* out_view); + void (*release_interface)(void_module_handle* handle, + const void_interface_id_v1* iface_id, + const void_interface_view_v1* view); + int32_t (*submit_async)(void_module_handle* handle, + uint32_t op_kind, + void_bytes_v1 payload, + const void_op_options_v1* opts, + void_async_complete_fn cb, + void* cb_ctx, + void_operation_handle** out_op, + void_error_detail_v1* out_err); + int32_t (*cancel_async)(void_module_handle* handle, + void_operation_handle* op); + void (*release_async)(void_module_handle* handle, + void_operation_handle* op); + int32_t (*request_stop)(void_module_handle* handle); + int32_t (*deactivate)(void_module_handle* handle); + void (*destroy)(void_module_handle* handle); +} void_module_api_v1; + +#define VOID_MODULE_API_V1_MIN_SIZE sizeof(void_module_api_v1) + +typedef int32_t (*void_module_query_v1_fn)(uint32_t host_struct_size, + void_module_api_v1* out_api); + +#ifdef __cplusplus +} +#endif + +#endif /* VOID_PLUGIN_CABI_H */ diff --git a/include/Void/Plugin/CAbiAdapter.hpp b/include/Void/Plugin/CAbiAdapter.hpp new file mode 100644 index 0000000..7b72d81 --- /dev/null +++ b/include/Void/Plugin/CAbiAdapter.hpp @@ -0,0 +1,165 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace Void::Plugin +{ + namespace detail + { + inline void free_cabi_cstring(void* /*ctx*/, const char* msg) + { + delete[] msg; + } + + inline void set_error_detail(void_error_detail_v1* out_err, + std::int32_t status, + const std::string& msg) noexcept + { + if (out_err == nullptr || + out_err->struct_size < sizeof(void_error_detail_v1)) { + return; + } + out_err->status = status; + try { + char* buf = new char[msg.size() + 1]; + std::memcpy(buf, msg.c_str(), msg.size() + 1); + out_err->message = buf; + out_err->release = &free_cabi_cstring; + out_err->release_ctx = nullptr; + } catch (...) { + out_err->message = nullptr; + out_err->release = nullptr; + out_err->release_ctx = nullptr; + } + } + + inline void free_cabi_bytes(void* /*ctx*/, const std::uint8_t* data, + std::uint64_t /*size*/) + { + delete[] data; + } + } // namespace detail + + /// Exception-safe bridge adapting a C++ IModule instance to the C11 + /// void_module_api_v1 contract without letting C++ exceptions unwind across C. + struct CModuleAdapterBox { + std::unique_ptr module; + Service::ServiceRegistry fallback_registry; + ModuleHost host{fallback_registry}; + const Void::Time::MonotonicClock* clock{ + &Void::Time::SystemMonotonicClock::instance()}; + }; + + template + [[nodiscard]] inline std::int32_t + invoke_contained(void_error_detail_v1* out_err, CallbackFn&& fn) noexcept + { + try { + return fn(); + } catch (const std::exception& ex) { + detail::set_error_detail(out_err, VOID_STATUS_INTERNAL, ex.what()); + return VOID_STATUS_INTERNAL; + } catch (...) { + detail::set_error_detail(out_err, VOID_STATUS_INTERNAL, + "CAbiAdapter: unknown C++ exception"); + return VOID_STATUS_INTERNAL; + } + } + + [[nodiscard]] inline std::int32_t + adapt_checkpoint(CModuleAdapterBox* box, + void_owned_bytes_v1* out_state, + void_error_detail_v1* out_err) noexcept + { + if (box == nullptr || !box->module || out_state == nullptr) { + return VOID_STATUS_INVALID_ARGUMENT; + } + return invoke_contained(out_err, [&]() -> std::int32_t { + const auto json = Void::Json::serialize(box->module->checkpoint()); + auto* buf = new std::uint8_t[json.size()]; + if (!json.empty()) { + std::memcpy(buf, json.data(), json.size()); + } + out_state->data = buf; + out_state->size = static_cast(json.size()); + out_state->release = &detail::free_cabi_bytes; + out_state->release_ctx = nullptr; + return VOID_STATUS_OK; + }); + } + + [[nodiscard]] inline std::int32_t + adapt_restore(CModuleAdapterBox* box, void_bytes_v1 state, + void_error_detail_v1* out_err) noexcept + { + if (box == nullptr || !box->module) { + return VOID_STATUS_INVALID_ARGUMENT; + } + return invoke_contained(out_err, [&]() -> std::int32_t { + const std::string_view sv{ + reinterpret_cast(state.data), + static_cast(state.size)}; + const auto parsed = Void::Json::parse(sv); + if (!parsed.has_value()) { + detail::set_error_detail(out_err, VOID_STATUS_CORRUPT, + parsed.error().message); + return VOID_STATUS_CORRUPT; + } + const auto res = box->module->restore(*parsed); + if (!res.has_value()) { + detail::set_error_detail(out_err, VOID_STATUS_STATE_REJECTED, + res.error().message()); + return VOID_STATUS_STATE_REJECTED; + } + return VOID_STATUS_OK; + }); + } + + [[nodiscard]] inline std::int32_t + adapt_activate(CModuleAdapterBox* box, + void_error_detail_v1* out_err) noexcept + { + if (box == nullptr || !box->module) { + return VOID_STATUS_INVALID_ARGUMENT; + } + return invoke_contained(out_err, [&]() -> std::int32_t { + const auto r = box->module->activate(box->host); + if (!r.has_value()) { + detail::set_error_detail(out_err, VOID_STATUS_INTERNAL, + r.error().message()); + return VOID_STATUS_INTERNAL; + } + return VOID_STATUS_OK; + }); + } + + [[nodiscard]] inline std::int32_t + adapt_readiness(CModuleAdapterBox* box, std::uint32_t* out_ready, + void_error_detail_v1* out_err) noexcept + { + if (box == nullptr || !box->module || out_ready == nullptr) { + return VOID_STATUS_INVALID_ARGUMENT; + } + *out_ready = 0; + return invoke_contained(out_err, [&]() -> std::int32_t { + const auto r = box->module->readiness(); + *out_ready = r.ready ? 1u : 0u; + if (!r.ready && !r.detail.empty()) { + detail::set_error_detail(out_err, VOID_STATUS_NOT_READY, + r.detail); + } + return VOID_STATUS_OK; + }); + } + +} // namespace Void::Plugin diff --git a/include/Void/Plugin/Host.hpp b/include/Void/Plugin/Host.hpp new file mode 100644 index 0000000..b74c1b4 --- /dev/null +++ b/include/Void/Plugin/Host.hpp @@ -0,0 +1,350 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Plugin +{ + enum class PluginErrorCode : std::int32_t { + none = 0, + invalid_argument = 1, + file_not_found = 2, + dlopen_failed = 3, + symbol_missing = 4, + abi_mismatch = 5, + activation_failed = 6, + not_ready = 7, + quiesce_failed = 8, + resume_degraded = 9, + checkpoint_failed = 10, + restore_failed = 11, + restart_required = 12, + cycle_detected = 13, + missing_dependency = 14, + retention_limit = 15, + budget_exceeded = 16, + conflict = 17, + cancelled = 18, + timeout = 19, + not_found = 20, + internal = 21, + }; + + [[nodiscard]] inline Void::Result::Error + make_plugin_error(PluginErrorCode code, std::string message = {}) + { + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case PluginErrorCode::none: + kind = ErrorKind::internal; + break; + case PluginErrorCode::invalid_argument: + case PluginErrorCode::abi_mismatch: + case PluginErrorCode::cycle_detected: + kind = ErrorKind::invalid_argument; + break; + case PluginErrorCode::file_not_found: + case PluginErrorCode::symbol_missing: + case PluginErrorCode::missing_dependency: + case PluginErrorCode::not_found: + kind = ErrorKind::not_found; + break; + case PluginErrorCode::dlopen_failed: + kind = ErrorKind::io; + break; + case PluginErrorCode::conflict: + case PluginErrorCode::restart_required: + kind = ErrorKind::conflict; + break; + case PluginErrorCode::cancelled: + kind = ErrorKind::cancelled; + break; + case PluginErrorCode::timeout: + kind = ErrorKind::timeout; + break; + case PluginErrorCode::retention_limit: + case PluginErrorCode::budget_exceeded: + kind = ErrorKind::exhausted; + break; + case PluginErrorCode::activation_failed: + case PluginErrorCode::not_ready: + case PluginErrorCode::quiesce_failed: + case PluginErrorCode::resume_degraded: + case PluginErrorCode::checkpoint_failed: + case PluginErrorCode::restore_failed: + case PluginErrorCode::internal: + kind = ErrorKind::internal; + break; + } + return Error{kind, std::move(message), + ErrorCode{Void::Result::kPluginErrorDomain, + static_cast(code)}}; + } + + struct PluginHostLimits { + std::size_t max_modules{64}; + std::size_t max_interfaces_per_module{256}; + std::size_t max_retained_generations{4}; + std::size_t max_mapped_bytes_per_module{64 * 1024 * 1024}; + std::size_t max_checkpoint_bytes{4 * 1024 * 1024}; + std::size_t max_config_bytes{1 * 1024 * 1024}; + std::size_t max_async_activities{1024}; + std::size_t max_pending_callbacks{256}; + std::chrono::milliseconds prepare_timeout{ + std::chrono::seconds{5}}; + std::chrono::milliseconds quiesce_timeout{ + std::chrono::seconds{5}}; + std::chrono::milliseconds readiness_timeout{ + std::chrono::seconds{10}}; + std::chrono::milliseconds total_reload_timeout{ + std::chrono::seconds{30}}; + bool allow_safe_dlclose{false}; + }; + + enum class GenerationHealth : std::uint8_t { + Healthy = 0, + Quiescing, + Degraded, + Retiring, + Retired, + }; + + struct GenerationSummary { + std::uint64_t generation{0}; + std::string module_id{}; + std::string version{}; + std::uint64_t image_bytes{0}; + std::size_t external_refs{0}; + std::size_t activity_pins{0}; + GenerationHealth health{GenerationHealth::Healthy}; + bool dlclosed{false}; + }; + + struct ReloadEvent { + std::string module_id{}; + std::uint64_t generation{0}; + bool rollback{false}; + std::string detail{}; + }; + + struct BatchModuleSpec { + std::filesystem::path path{}; + std::string config{}; + }; + + namespace detail + { + struct GenerationRecord; + } + + /// RAII pin holding an async activity count on a generation. Destroying + /// it may schedule asynchronous host retirement if no refs/pins remain. + class ActivityPin + { + public: + + ActivityPin() noexcept = default; + ~ActivityPin(); + ActivityPin(ActivityPin&& other) noexcept; + ActivityPin& operator=(ActivityPin&& other) noexcept; + ActivityPin(const ActivityPin&) = delete; + ActivityPin& operator=(const ActivityPin&) = delete; + + [[nodiscard]] explicit operator bool() const noexcept + { + return m_rec != nullptr; + } + [[nodiscard]] std::uint64_t generation() const noexcept; + + private: + + friend class CModuleHost; + friend class GenerationLease; + explicit ActivityPin(std::shared_ptr rec) + : m_rec(std::move(rec)) + { + } + std::shared_ptr m_rec{}; + }; + + /// Owning lease to a queried C interface function table from an exact + /// generation. Releases via release_interface before dropping generation ref. + class InterfaceLease + { + public: + + InterfaceLease() noexcept = default; + ~InterfaceLease(); + InterfaceLease(InterfaceLease&& other) noexcept; + InterfaceLease& operator=(InterfaceLease&& other) noexcept; + InterfaceLease(const InterfaceLease&) = delete; + InterfaceLease& operator=(const InterfaceLease&) = delete; + + [[nodiscard]] explicit operator bool() const noexcept + { + return m_view.function_table != nullptr; + } + + template + [[nodiscard]] const TableT* table() const noexcept + { + if (m_view.function_table == nullptr || + m_view.table_size < sizeof(TableT)) { + return nullptr; + } + return static_cast(m_view.function_table); + } + + [[nodiscard]] const void_interface_view_v1& view() const noexcept + { + return m_view; + } + [[nodiscard]] std::uint64_t generation() const noexcept; + + private: + + friend class GenerationLease; + InterfaceLease(std::shared_ptr rec, + void_interface_id_v1 id, + void_interface_view_v1 view) noexcept + : m_rec(std::move(rec)), m_id(id), m_view(view) + { + } + + std::shared_ptr m_rec{}; + void_interface_id_v1 m_id{}; + void_interface_view_v1 m_view{}; + }; + + /// Owning generation reference acquired from CModuleHost. Prevents module + /// deactivation and dlclose while held, and supports activity pinning, + /// C interface querying, and bounded async operation submission. + class GenerationLease + { + public: + + GenerationLease() noexcept = default; + ~GenerationLease(); + GenerationLease(const GenerationLease& other); + GenerationLease& operator=(const GenerationLease& other); + GenerationLease(GenerationLease&& other) noexcept; + GenerationLease& operator=(GenerationLease&& other) noexcept; + + [[nodiscard]] explicit operator bool() const noexcept + { + return m_rec != nullptr; + } + [[nodiscard]] std::uint64_t generation() const noexcept; + [[nodiscard]] std::string_view module_id() const noexcept; + [[nodiscard]] std::string_view version() const noexcept; + [[nodiscard]] GenerationHealth health() const noexcept; + + [[nodiscard]] ActivityPin acquire_activity_pin() const; + + [[nodiscard]] Void::Result::Result + query_interface(const void_interface_id_v1& id, + std::uint32_t min_major, + std::uint32_t min_table_size) const; + + [[nodiscard]] Void::Result::Result> + run_async(std::uint32_t op_kind, + const std::vector& payload, + Void::Async::OperationOptions options = {}) const; + + private: + + friend class CModuleHost; + struct AlreadyRefCountedTag {}; + explicit GenerationLease( + std::shared_ptr rec); + GenerationLease(std::shared_ptr rec, + AlreadyRefCountedTag) noexcept + : m_rec(std::move(rec)) + { + } + + std::shared_ptr m_rec{}; + }; + + /// Hardened C-ABI module host implementing size/version negotiation, + /// independent external_refs & activity_pins, host-thread retirement queue, + /// unlocked quiesce/checkpoint/restore/readiness/resume reload, and + /// dependency-ordered batch loading. + class CModuleHost + { + public: + + struct Impl; + + explicit CModuleHost( + PluginHostLimits limits = {}, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()); + ~CModuleHost(); + + CModuleHost(const CModuleHost&) = delete; + CModuleHost& operator=(const CModuleHost&) = delete; + + [[nodiscard]] Void::Result::Result + load(const std::filesystem::path& path, + std::string_view config = {}, + Void::Async::OperationOptions options = {}); + + [[nodiscard]] Void::Result::Result> + load_batch(const std::vector& specs, + Void::Async::OperationOptions options = {}); + + [[nodiscard]] Void::Result::Result + replace(std::string_view module_id, + const std::filesystem::path& new_path, + std::string_view config = {}, + std::optional expected_generation = + std::nullopt, + Void::Async::OperationOptions options = {}, + std::function( + const GenerationLease&)> + on_publish_locked = {}); + + [[nodiscard]] Void::Result::Result + unload(std::string_view module_id); + + [[nodiscard]] GenerationLease + acquire(std::string_view module_id) const; + + [[nodiscard]] std::vector + retained_generations(std::string_view module_id) const; + + [[nodiscard]] std::size_t + mapped_bytes(std::string_view module_id) const; + + std::size_t add_observer(std::function cb); + void remove_observer(std::size_t id); + + /// Drain retirement queue and shutdown background retirement worker. + void close_and_join(); + + private: + + std::shared_ptr m_impl; + }; + +} // namespace Void::Plugin diff --git a/include/Void/Plugin/Manager.hpp b/include/Void/Plugin/Manager.hpp index dc4bb76..236c2b1 100644 --- a/include/Void/Plugin/Manager.hpp +++ b/include/Void/Plugin/Manager.hpp @@ -215,18 +215,20 @@ namespace Void::Plugin std::filesystem::path path; std::atomic> current; bool watched{false}; + std::mutex reload_mutex; }; Entry* find(std::string_view name) const; - std::expected - reload_locked(Entry& entry, std::string_view name, - const std::filesystem::path& sourcePath); + std::shared_ptr find_shared(std::string_view name) const; + std::expected reload_entry_unlocked( + const std::shared_ptr& entry, std::string_view name, + const std::optional& newPath); std::vector> reload_callbacks_locked() const; Options m_options; - mutable std::mutex m_mutex; // guards the registry map + reloads - std::unordered_map> m_plugins; + mutable std::mutex m_mutex; // guards the registry map & observer list + std::unordered_map> m_plugins; std::vector>> m_on_reloaded; diff --git a/src/Plugin/Host.cpp b/src/Plugin/Host.cpp new file mode 100644 index 0000000..046dd8d --- /dev/null +++ b/src/Plugin/Host.cpp @@ -0,0 +1,1647 @@ +#include + +#include +#include + +#if defined(__unix__) || defined(__APPLE__) +#include +#define VOID_HOST_HAS_DLOPEN 1 +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Plugin +{ + namespace + { + PluginErrorCode map_cabi_status(std::int32_t status, + PluginErrorCode fallback) noexcept + { + switch (status) { + case VOID_STATUS_INVALID_ARGUMENT: + return PluginErrorCode::invalid_argument; + case VOID_STATUS_NOT_FOUND: + return PluginErrorCode::not_found; + case VOID_STATUS_CONFLICT: + return PluginErrorCode::conflict; + case VOID_STATUS_CANCELLED: + return PluginErrorCode::cancelled; + case VOID_STATUS_TIMEOUT: + return PluginErrorCode::timeout; + case VOID_STATUS_OVERLOADED: + case VOID_STATUS_EXHAUSTED: + return PluginErrorCode::budget_exceeded; + case VOID_STATUS_UNSUPPORTED: + return PluginErrorCode::abi_mismatch; + case VOID_STATUS_NOT_READY: + return PluginErrorCode::not_ready; + case VOID_STATUS_QUIESCING: + return PluginErrorCode::quiesce_failed; + case VOID_STATUS_STATE_REJECTED: + return PluginErrorCode::restore_failed; + case VOID_STATUS_RESTART_REQUIRED: + return PluginErrorCode::restart_required; + default: + return fallback; + } + } + + std::string consume_error_detail(void_error_detail_v1& err) + { + std::string msg; + if (err.message != nullptr) { + const std::size_t len = ::strnlen(err.message, 1024); + msg.assign(err.message, len); + if (err.release != nullptr) { + err.release(err.release_ctx, err.message); + } + } + err.message = nullptr; + err.release = nullptr; + return msg; + } + + bool is_all_zero(const void* data, std::size_t n) noexcept + { + const auto* bytes = static_cast(data); + for (std::size_t i = 0; i < n; ++i) { + if (bytes[i] != 0) { + return false; + } + } + return true; + } + + struct DependencySpec { + std::string module_id{}; + std::string version_range{}; + bool optional_dep{false}; + }; + } // namespace + + struct detail::GenerationRecord + : public std::enable_shared_from_this { + struct HostCtx { + std::weak_ptr host_impl; + std::weak_ptr rec; + }; + + std::weak_ptr host_impl{}; + HostCtx host_api_ctx{}; + std::uint64_t generation{0}; + std::string module_id{}; + std::string version{}; + std::uint64_t image_bytes{0}; + void* dl_handle{nullptr}; + void_module_api_v1 api{}; + void_module_handle* mod_handle{nullptr}; + std::vector dependencies{}; + std::uint32_t activation_policy{VOID_POLICY_RELOADABLE}; + std::atomic health{GenerationHealth::Healthy}; + std::atomic external_refs{0}; + std::atomic activity_pins{0}; + std::atomic active_async_ops{0}; + std::atomic retire_requested{false}; + std::atomic retired_enqueued{false}; + std::atomic destroyed{false}; + std::atomic dlclosed{false}; + bool allow_dlclose{false}; + bool activated{false}; + + void add_external_ref() noexcept + { + external_refs.fetch_add(1, std::memory_order_acq_rel); + } + + void release_external_ref() noexcept + { + if (external_refs.fetch_sub(1, std::memory_order_seq_cst) == 1) { + maybe_enqueue_retire(); + } + } + + void add_activity_pin() noexcept + { + activity_pins.fetch_add(1, std::memory_order_acq_rel); + } + + void release_activity_pin() noexcept + { + if (activity_pins.fetch_sub(1, std::memory_order_seq_cst) == 1) { + maybe_enqueue_retire(); + } + } + + void maybe_enqueue_retire() noexcept; + }; + + struct CModuleHost::Impl + : public std::enable_shared_from_this { + struct ModuleSlot { + std::mutex reload_mu{}; + std::shared_ptr current{}; + std::vector> + retained{}; + }; + + explicit Impl(PluginHostLimits l, + const Void::Time::MonotonicClock& c) + : limits(l), clock(&c) + { + retire_thread = std::thread([this] { run_retire_loop(); }); + } + + ~Impl() { shutdown(); } + + void enqueue_retire(std::shared_ptr rec) + { + { + std::lock_guard lk{retire_mu}; + if (retire_stop) { + return; + } + retire_queue.push_back(std::move(rec)); + } + retire_cv.notify_one(); + } + + void run_retire_loop() + { + for (;;) { + std::shared_ptr rec; + { + std::unique_lock lk{retire_mu}; + retire_cv.wait(lk, [this] { + return retire_stop || !retire_queue.empty(); + }); + if (retire_stop && retire_queue.empty()) { + return; + } + rec = std::move(retire_queue.front()); + retire_queue.pop_front(); + } + perform_retire(*rec); + } + } + + void perform_retire(detail::GenerationRecord& rec) noexcept + { + if (rec.external_refs.load(std::memory_order_seq_cst) > 0 || + rec.activity_pins.load(std::memory_order_seq_cst) > 0) { + return; + } + bool exp = false; + if (!rec.destroyed.compare_exchange_strong( + exp, true, std::memory_order_acq_rel)) { + return; + } + rec.health.store(GenerationHealth::Retired, + std::memory_order_release); + if (rec.mod_handle != nullptr) { + if (rec.activated && rec.api.deactivate != nullptr) { + (void)rec.api.deactivate(rec.mod_handle); + } + if (rec.api.destroy != nullptr) { + rec.api.destroy(rec.mod_handle); + } + rec.mod_handle = nullptr; + } +#ifdef VOID_HOST_HAS_DLOPEN + if (rec.allow_dlclose && rec.dl_handle != nullptr) { + dlclose(rec.dl_handle); + rec.dl_handle = nullptr; + rec.dlclosed.store(true, std::memory_order_release); + } +#endif + } + + void shutdown() + { + std::vector> slots; + { + std::lock_guard lk{map_mu}; + closing = true; + for (auto& [_, s] : modules) { + slots.push_back(s); + } + } + for (auto& slot : slots) { + std::lock_guard rlk{slot->reload_mu}; + std::shared_ptr prev; + { + std::lock_guard lk{map_mu}; + prev = std::exchange(slot->current, nullptr); + } + if (prev) { + prev->retire_requested.store(true, + std::memory_order_seq_cst); + if (prev->api.request_stop != nullptr && + prev->mod_handle != nullptr) { + (void)prev->api.request_stop(prev->mod_handle); + } + prev->release_external_ref(); + } + } + { + std::lock_guard lk{retire_mu}; + retire_stop = true; + } + retire_cv.notify_all(); + if (retire_thread.joinable()) { + retire_thread.join(); + } + // Prune destroyed generations once retirement worker finished; any + // generation still holding external_refs or activity_pins stays + // un-dlclosed intentionally. + for (auto& slot : slots) { + std::lock_guard rlk{slot->reload_mu}; + for (auto& r : slot->retained) { + if (r && + r->external_refs.load(std::memory_order_seq_cst) == + 0 && + r->activity_pins.load(std::memory_order_seq_cst) == + 0) { + perform_retire(*r); + } + } + } + } + + static std::uint64_t host_monotonic_ns(void_host_context* ctx) + { + auto* hctx = + reinterpret_cast(ctx); + if (hctx != nullptr) { + if (auto impl = hctx->host_impl.lock()) { + return static_cast(std::max( + 0, impl->clock->now().time_since_epoch().count())); + } + } + return 0; + } + + static std::int32_t host_acquire_pin(void_host_context* ctx, + std::uint64_t generation) + { + auto* hctx = + reinterpret_cast(ctx); + if (hctx == nullptr) { + return VOID_STATUS_INVALID_ARGUMENT; + } + auto rec = hctx->rec.lock(); + if (!rec || rec->generation != generation || + rec->destroyed.load(std::memory_order_acquire)) { + return VOID_STATUS_CONFLICT; + } + rec->add_activity_pin(); + return VOID_STATUS_OK; + } + + static void host_release_pin(void_host_context* ctx, + std::uint64_t generation) + { + auto* hctx = + reinterpret_cast(ctx); + if (hctx == nullptr) { + return; + } + auto rec = hctx->rec.lock(); + if (!rec || rec->generation != generation) { + return; + } + rec->release_activity_pin(); + } + + static void host_log_msg(void_host_context* /*ctx*/, + std::int32_t level, const char* msg) + { + if (msg == nullptr) { + return; + } + const std::size_t len = ::strnlen(msg, 1024); + const std::string_view sv{msg, len}; + if (level <= 0) { + Void::Log::debug("Plugin.CAbi", "{}", sv); + } else { + Void::Log::info("Plugin.CAbi", "{}", sv); + } + } + + void notify_observers(const ReloadEvent& ev) + { + std::vector> copy; + { + std::lock_guard lk{obs_mu}; + copy.reserve(observers.size()); + for (const auto& [_, cb] : observers) { + if (cb) copy.push_back(cb); + } + } + for (const auto& cb : copy) { + try { + cb(ev); + } catch (...) { + } + } + } + + void_op_options_v1 + make_op_opts(std::optional dl, + bool stop) const noexcept + { + void_op_options_v1 opts{}; + opts.struct_size = sizeof(void_op_options_v1); + opts.flags = 0; + opts.deadline_ns = + dl.has_value() + ? static_cast(std::max( + 0, dl->time_since_epoch().count())) + : 0; + opts.stop_requested = stop ? 1 : 0; + return opts; + } + + Void::Result::Result> + open_candidate(const std::filesystem::path& path, + std::uint64_t gen) + { +#ifdef VOID_HOST_HAS_DLOPEN + std::error_code ec; + if (!std::filesystem::is_regular_file(path, ec)) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::file_not_found, + "CModuleHost: module file not found: " + path.string())); + } + const auto file_sz = std::filesystem::file_size(path, ec); + if (ec) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::dlopen_failed, + "CModuleHost: cannot stat module file")); + } + if (file_sz > limits.max_mapped_bytes_per_module) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::budget_exceeded, + "CModuleHost: candidate image exceeds max_mapped_bytes_per_module")); + } + + // Fresh-inode copy so repeated loads at same path load fresh bytes. + const std::uint64_t copy_id = + temp_counter.fetch_add(1, std::memory_order_relaxed); + const auto tmp = path.parent_path() / + (path.filename().string() + ".void_cabi." + + std::to_string(copy_id)); + std::filesystem::copy_file( + path, tmp, std::filesystem::copy_options::overwrite_existing, + ec); + if (ec) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::dlopen_failed, + "CModuleHost: failed to stage module copy")); + } + + void* handle = dlopen(tmp.c_str(), RTLD_NOW | RTLD_LOCAL); + std::filesystem::remove(tmp, ec); + if (handle == nullptr) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::dlopen_failed, + std::string{"CModuleHost: dlopen failed: "} + + (dlerror() ? dlerror() : "unknown"))); + } + + auto cleanup_handle = [&]() { + if (handle != nullptr && limits.allow_safe_dlclose) { + dlclose(handle); + } + handle = nullptr; + }; + + auto query_fn = reinterpret_cast( + dlsym(handle, VOID_MODULE_QUERY_SYMBOL_V1)); + if (query_fn == nullptr) { + cleanup_handle(); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::symbol_missing, + "CModuleHost: missing void_module_query_v1 export")); + } + + void_module_api_v1 api{}; + const std::int32_t qrc = + query_fn(sizeof(void_module_api_v1), &api); + if (qrc != VOID_STATUS_OK) { + cleanup_handle(); + return Void::Result::fail(make_plugin_error( + map_cabi_status(qrc, PluginErrorCode::abi_mismatch), + "CModuleHost: void_module_query_v1 failed")); + } + if (api.struct_size < VOID_MODULE_API_V1_MIN_SIZE || + api.abi_major != VOID_CABI_MAJOR_V1 || api.reserved != 0) { + cleanup_handle(); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::abi_mismatch, + "CModuleHost: invalid C ABI table size, major version, or reserved field")); + } + if (api.get_info == nullptr || api.create == nullptr || + api.activate == nullptr || api.readiness == nullptr || + api.request_stop == nullptr || api.deactivate == nullptr || + api.destroy == nullptr) { + cleanup_handle(); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::abi_mismatch, + "CModuleHost: required C ABI callbacks missing")); + } + if ((api.capabilities & VOID_CAP_STATEFUL_CHECKPOINT) != 0 && + (api.quiesce == nullptr || api.resume == nullptr || + api.checkpoint == nullptr || api.restore == nullptr)) { + cleanup_handle(); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::abi_mismatch, + "CModuleHost: stateful capability requires quiesce/resume/checkpoint/restore")); + } + + void_module_info_v1 info{}; + const std::int32_t irc = api.get_info(&info); + if (irc != VOID_STATUS_OK || + info.struct_size < sizeof(void_module_info_v1) || + info.reserved != 0 || info.module_id == nullptr || + info.version == nullptr || info.module_id[0] == '\0') { + cleanup_handle(); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::abi_mismatch, + "CModuleHost: invalid void_module_info_v1 descriptor")); + } + if (info.dependency_count > limits.max_interfaces_per_module || + (info.dependency_count > 0 && info.dependencies == nullptr)) { + cleanup_handle(); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::abi_mismatch, + "CModuleHost: invalid or oversized dependency list")); + } + + auto rec = std::make_shared(); + rec->host_impl = weak_from_this(); + rec->host_api_ctx.host_impl = weak_from_this(); + rec->host_api_ctx.rec = rec; + rec->generation = gen; + rec->module_id = std::string{ + info.module_id, ::strnlen(info.module_id, 256)}; + rec->version = + std::string{info.version, ::strnlen(info.version, 128)}; + rec->image_bytes = file_sz; + rec->dl_handle = handle; + rec->api = api; + rec->activation_policy = info.activation_policy; + rec->allow_dlclose = limits.allow_safe_dlclose; + + for (std::uint64_t i = 0; i < info.dependency_count; ++i) { + const auto& d = info.dependencies[i]; + if (!is_all_zero(d.reserved, sizeof(d.reserved)) || + d.module_id == nullptr || d.version_range == nullptr || + d.module_id[0] == '\0') { + if (rec->allow_dlclose) dlclose(rec->dl_handle); + rec->dl_handle = nullptr; + return Void::Result::fail(make_plugin_error( + PluginErrorCode::abi_mismatch, + "CModuleHost: malformed dependency entry")); + } + if (!Semver::VersionRange::parse(d.version_range)) { + if (rec->allow_dlclose) dlclose(rec->dl_handle); + rec->dl_handle = nullptr; + return Void::Result::fail(make_plugin_error( + PluginErrorCode::abi_mismatch, + "CModuleHost: invalid dependency semver range")); + } + rec->dependencies.push_back(DependencySpec{ + .module_id = d.module_id, + .version_range = d.version_range, + .optional_dep = d.optional_dep != 0}); + } + + void_host_api_v1 host_api{}; + host_api.struct_size = sizeof(void_host_api_v1); + host_api.abi_major = VOID_CABI_MAJOR_V1; + host_api.abi_minor = VOID_CABI_MINOR_V1; + host_api.reserved = 0; + host_api.host_ctx = + reinterpret_cast(&rec->host_api_ctx); + host_api.generation = gen; + host_api.monotonic_now_ns = &host_monotonic_ns; + host_api.acquire_activity_pin = &host_acquire_pin; + host_api.release_activity_pin = &host_release_pin; + host_api.log_message = &host_log_msg; + + void_module_handle* mod = nullptr; + const std::int32_t crc = api.create(&host_api, &mod); + if (crc != VOID_STATUS_OK || mod == nullptr) { + if (rec->allow_dlclose) dlclose(rec->dl_handle); + rec->dl_handle = nullptr; + return Void::Result::fail(make_plugin_error( + map_cabi_status(crc, PluginErrorCode::activation_failed), + "CModuleHost: plugin create failed")); + } + rec->mod_handle = mod; + return rec; +#else + (void)path; + (void)gen; + return Void::Result::fail(make_plugin_error( + PluginErrorCode::dlopen_failed, + "CModuleHost: dlopen unsupported on this platform")); +#endif + } + + void dispose_uncommitted( + const std::shared_ptr& rec) + { + if (!rec) return; + rec->retire_requested.store(true, std::memory_order_seq_cst); + perform_retire(*rec); + } + + Void::Result::Result + activate_and_verify(detail::GenerationRecord& rec, + std::string_view config, + const Void::Time::MonotonicClock::time_point total_dl, + const Void::Async::OperationOptions& caller_opts) + { + if (config.size() > limits.max_config_bytes) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::budget_exceeded, + "CModuleHost: config payload exceeds max_config_bytes")); + } + if (caller_opts.stop.stop_requested()) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::cancelled, + "CModuleHost: cancelled before activation")); + } + if (clock->now() >= total_dl) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::timeout, + "CModuleHost: reload deadline expired before activation")); + } + + void_bytes_v1 cfg{ + .data = reinterpret_cast( + config.empty() ? "" : config.data()), + .size = static_cast(config.size())}; + void_error_detail_v1 err{}; + err.struct_size = sizeof(void_error_detail_v1); + const std::int32_t arc = + rec.api.activate(rec.mod_handle, cfg, &err); + std::string emsg = consume_error_detail(err); + if (arc != VOID_STATUS_OK) { + return Void::Result::fail(make_plugin_error( + map_cabi_status(arc, PluginErrorCode::activation_failed), + emsg.empty() ? "CModuleHost: module activate failed" + : emsg)); + } + rec.activated = true; + + if (clock->now() >= total_dl || + caller_opts.stop.stop_requested()) { + return Void::Result::fail(make_plugin_error( + caller_opts.stop.stop_requested() + ? PluginErrorCode::cancelled + : PluginErrorCode::timeout, + "CModuleHost: cancelled/timed out before readiness check")); + } + + std::uint32_t ready_flag = 0; + void_error_detail_v1 rerr{}; + rerr.struct_size = sizeof(void_error_detail_v1); + const std::int32_t rrc = + rec.api.readiness(rec.mod_handle, &ready_flag, &rerr); + std::string rmsg = consume_error_detail(rerr); + if (rrc != VOID_STATUS_OK || ready_flag == 0) { + return Void::Result::fail(make_plugin_error( + rrc == VOID_STATUS_OK + ? PluginErrorCode::not_ready + : map_cabi_status(rrc, PluginErrorCode::not_ready), + rmsg.empty() ? "CModuleHost: module reported not ready" + : rmsg)); + } + return {}; + } + + PluginHostLimits limits{}; + const Void::Time::MonotonicClock* clock{ + &Void::Time::SystemMonotonicClock::instance()}; + std::atomic next_gen{1}; + std::atomic temp_counter{1}; + + mutable std::mutex map_mu{}; + bool closing{false}; + std::unordered_map> + modules{}; + + std::mutex retire_mu{}; + std::condition_variable retire_cv{}; + bool retire_stop{false}; + std::deque> + retire_queue{}; + std::thread retire_thread{}; + + std::mutex obs_mu{}; + std::vector< + std::pair>> + observers{}; + std::size_t next_obs_id{1}; + }; + + void detail::GenerationRecord::maybe_enqueue_retire() noexcept + { + if (retire_requested.load(std::memory_order_seq_cst) && + external_refs.load(std::memory_order_seq_cst) == 0 && + activity_pins.load(std::memory_order_seq_cst) == 0) { + bool exp = false; + if (retired_enqueued.compare_exchange_strong( + exp, true, std::memory_order_acq_rel)) { + if (auto impl = host_impl.lock()) { + impl->enqueue_retire(shared_from_this()); + } + } + } + } + + // ── ActivityPin & InterfaceLease & GenerationLease ─────────────────── + + ActivityPin::~ActivityPin() + { + if (m_rec) { + m_rec->release_activity_pin(); + m_rec.reset(); + } + } + + ActivityPin::ActivityPin(ActivityPin&& other) noexcept + : m_rec(std::move(other.m_rec)) + { + } + + ActivityPin& ActivityPin::operator=(ActivityPin&& other) noexcept + { + if (this != &other) { + if (m_rec) { + m_rec->release_activity_pin(); + } + m_rec = std::move(other.m_rec); + } + return *this; + } + + std::uint64_t ActivityPin::generation() const noexcept + { + return m_rec ? m_rec->generation : 0; + } + + InterfaceLease::~InterfaceLease() + { + if (m_rec) { + if (m_view.function_table != nullptr && + m_rec->api.release_interface != nullptr && + m_rec->mod_handle != nullptr) { + m_rec->api.release_interface(m_rec->mod_handle, &m_id, &m_view); + } + m_rec->release_external_ref(); + m_rec.reset(); + } + m_view = {}; + } + + InterfaceLease::InterfaceLease(InterfaceLease&& other) noexcept + : m_rec(std::move(other.m_rec)), m_id(other.m_id), + m_view(other.m_view) + { + other.m_view = {}; + } + + InterfaceLease& InterfaceLease::operator=(InterfaceLease&& other) noexcept + { + if (this != &other) { + if (m_rec) { + if (m_view.function_table != nullptr && + m_rec->api.release_interface != nullptr && + m_rec->mod_handle != nullptr) { + m_rec->api.release_interface(m_rec->mod_handle, &m_id, + &m_view); + } + m_rec->release_external_ref(); + } + m_rec = std::move(other.m_rec); + m_id = other.m_id; + m_view = other.m_view; + other.m_view = {}; + } + return *this; + } + + std::uint64_t InterfaceLease::generation() const noexcept + { + return m_rec ? m_rec->generation : 0; + } + + GenerationLease::GenerationLease( + std::shared_ptr rec) + : m_rec(std::move(rec)) + { + if (m_rec) { + m_rec->add_external_ref(); + } + } + + GenerationLease::GenerationLease(const GenerationLease& other) + : m_rec(other.m_rec) + { + if (m_rec) { + m_rec->add_external_ref(); + } + } + + GenerationLease& GenerationLease::operator=(const GenerationLease& other) + { + if (this != &other) { + if (m_rec) { + m_rec->release_external_ref(); + } + m_rec = other.m_rec; + if (m_rec) { + m_rec->add_external_ref(); + } + } + return *this; + } + + GenerationLease::GenerationLease(GenerationLease&& other) noexcept + : m_rec(std::move(other.m_rec)) + { + } + + GenerationLease& GenerationLease::operator=(GenerationLease&& other) noexcept + { + if (this != &other) { + if (m_rec) { + m_rec->release_external_ref(); + } + m_rec = std::move(other.m_rec); + } + return *this; + } + + GenerationLease::~GenerationLease() + { + if (m_rec) { + m_rec->release_external_ref(); + m_rec.reset(); + } + } + + std::uint64_t GenerationLease::generation() const noexcept + { + return m_rec ? m_rec->generation : 0; + } + + std::string_view GenerationLease::module_id() const noexcept + { + return m_rec ? std::string_view{m_rec->module_id} : std::string_view{}; + } + + std::string_view GenerationLease::version() const noexcept + { + return m_rec ? std::string_view{m_rec->version} : std::string_view{}; + } + + GenerationHealth GenerationLease::health() const noexcept + { + return m_rec ? m_rec->health.load(std::memory_order_acquire) + : GenerationHealth::Retired; + } + + ActivityPin GenerationLease::acquire_activity_pin() const + { + if (!m_rec) { + return ActivityPin{}; + } + m_rec->add_activity_pin(); + return ActivityPin{m_rec}; + } + + Void::Result::Result + GenerationLease::query_interface(const void_interface_id_v1& id, + std::uint32_t min_major, + std::uint32_t min_table_size) const + { + if (!m_rec || m_rec->mod_handle == nullptr || + m_rec->api.query_interface == nullptr) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::abi_mismatch, + "GenerationLease: interface query unsupported")); + } + void_interface_view_v1 view{}; + view.struct_size = sizeof(void_interface_view_v1); + const std::int32_t rc = m_rec->api.query_interface( + m_rec->mod_handle, &id, min_major, min_table_size, &view); + if (rc != VOID_STATUS_OK) { + return Void::Result::fail(make_plugin_error( + map_cabi_status(rc, PluginErrorCode::abi_mismatch), + "GenerationLease: query_interface rejected or missing")); + } + if (view.struct_size < sizeof(void_interface_view_v1) || + view.major != min_major || view.table_size < min_table_size || + view.function_table == nullptr) { + if (m_rec->api.release_interface != nullptr) { + m_rec->api.release_interface(m_rec->mod_handle, &id, &view); + } + return Void::Result::fail(make_plugin_error( + PluginErrorCode::abi_mismatch, + "GenerationLease: interface table version or size mismatch")); + } + m_rec->add_external_ref(); + return InterfaceLease{m_rec, id, view}; + } + + Void::Result::Result> + GenerationLease::run_async(std::uint32_t op_kind, + const std::vector& payload, + Void::Async::OperationOptions options) const + { + if (!m_rec || m_rec->mod_handle == nullptr || + m_rec->api.submit_async == nullptr) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::abi_mismatch, + "GenerationLease: async operations unsupported")); + } + auto impl = m_rec->host_impl.lock(); + const std::size_t cap = + impl ? impl->limits.max_async_activities : 1024; + if (m_rec->active_async_ops.fetch_add(1, std::memory_order_acq_rel) >= + cap) { + m_rec->active_async_ops.fetch_sub(1, std::memory_order_acq_rel); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::budget_exceeded, + "GenerationLease: async activity limit exceeded")); + } + + struct AsyncState { + std::shared_ptr rec; + std::mutex mu{}; + std::condition_variable cv{}; + bool done{false}; + std::int32_t status{VOID_STATUS_INTERNAL}; + std::vector result{}; + }; + + auto st = std::make_shared(); + st->rec = m_rec; + m_rec->add_activity_pin(); + + auto release_guards = [&]() { + m_rec->active_async_ops.fetch_sub(1, std::memory_order_acq_rel); + m_rec->release_activity_pin(); + }; + + const void_bytes_v1 in_bytes{ + .data = payload.empty() ? nullptr : payload.data(), + .size = static_cast(payload.size())}; + + void_op_options_v1 cabi_opts{}; + cabi_opts.struct_size = sizeof(void_op_options_v1); + cabi_opts.deadline_ns = + options.deadline.has_value() + ? static_cast(std::max( + 0, options.deadline->time_since_epoch().count())) + : 0; + cabi_opts.stop_requested = options.stop.stop_requested() ? 1 : 0; + + auto* raw_state = new std::shared_ptr(st); + auto cb = [](void* ctx, std::int32_t status, + const void_bytes_v1* result_bytes) { + auto* holder = + static_cast*>(ctx); + auto s = *holder; + delete holder; + { + std::lock_guard lk{s->mu}; + s->status = status; + if (result_bytes != nullptr && result_bytes->data != nullptr && + result_bytes->size > 0 && + result_bytes->size <= 64 * 1024 * 1024) { + const auto sz = + static_cast(result_bytes->size); + s->result.assign(result_bytes->data, + result_bytes->data + sz); + } + s->done = true; + } + s->cv.notify_all(); + }; + + void_operation_handle* op_handle = nullptr; + void_error_detail_v1 err{}; + err.struct_size = sizeof(void_error_detail_v1); + const std::int32_t rc = m_rec->api.submit_async( + m_rec->mod_handle, op_kind, in_bytes, &cabi_opts, cb, raw_state, + &op_handle, &err); + std::string emsg = consume_error_detail(err); + if (rc != VOID_STATUS_OK || op_handle == nullptr) { + delete raw_state; + release_guards(); + return Void::Result::fail(make_plugin_error( + map_cabi_status(rc, PluginErrorCode::internal), + emsg.empty() ? "GenerationLease: submit_async failed" : emsg)); + } + + { + struct Canceller { + detail::GenerationRecord* rec; + void_operation_handle* op; + void operator()() const noexcept + { + if (rec->api.cancel_async != nullptr) { + (void)rec->api.cancel_async(rec->mod_handle, op); + } + } + }; + std::optional> stop_cb; + if (options.stop.stop_possible()) { + stop_cb.emplace(options.stop, + Canceller{m_rec.get(), op_handle}); + } + std::unique_lock lk{st->mu}; + st->cv.wait(lk, [&] { return st->done; }); + } + if (m_rec->api.release_async != nullptr) { + m_rec->api.release_async(m_rec->mod_handle, op_handle); + } + release_guards(); + + if (st->status != VOID_STATUS_OK) { + return Void::Result::fail(make_plugin_error( + map_cabi_status(st->status, PluginErrorCode::internal), + "GenerationLease: async operation failed")); + } + return st->result; + } + + // ── CModuleHost ────────────────────────────────────────────────────── + + CModuleHost::CModuleHost(PluginHostLimits limits, + const Void::Time::MonotonicClock& clock) + : m_impl(std::make_shared(limits, clock)) + { + } + + CModuleHost::~CModuleHost() + { + if (m_impl) { + m_impl->shutdown(); + } + } + + void CModuleHost::close_and_join() + { + if (m_impl) { + m_impl->shutdown(); + } + } + + std::size_t + CModuleHost::add_observer(std::function cb) + { + std::lock_guard lk{m_impl->obs_mu}; + const std::size_t id = m_impl->next_obs_id++; + m_impl->observers.emplace_back(id, std::move(cb)); + return id; + } + + void CModuleHost::remove_observer(std::size_t id) + { + std::lock_guard lk{m_impl->obs_mu}; + std::erase_if(m_impl->observers, + [id](const auto& pair) { return pair.first == id; }); + } + + Void::Result::Result + CModuleHost::load(const std::filesystem::path& path, + std::string_view config, + Void::Async::OperationOptions options) + { + { + std::lock_guard lk{m_impl->map_mu}; + if (m_impl->closing) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::conflict, + "CModuleHost: host is closing")); + } + if (m_impl->modules.size() >= m_impl->limits.max_modules) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::budget_exceeded, + "CModuleHost: max_modules limit reached")); + } + } + + const std::uint64_t gen = + m_impl->next_gen.fetch_add(1, std::memory_order_relaxed); + auto cand_res = m_impl->open_candidate(path, gen); + if (!cand_res) { + return Void::Result::fail(std::move(cand_res).error()); + } + auto cand = std::move(*cand_res); + + const auto now = m_impl->clock->now(); + auto total_dl = now + m_impl->limits.total_reload_timeout; + if (options.deadline.has_value() && *options.deadline < total_dl) { + total_dl = *options.deadline; + } + if (auto ar = m_impl->activate_and_verify(*cand, config, total_dl, + options); + !ar) { + m_impl->dispose_uncommitted(cand); + return Void::Result::fail(std::move(ar).error()); + } + + std::shared_ptr slot; + std::string mod_id = cand->module_id; + { + std::lock_guard lk{m_impl->map_mu}; + if (m_impl->closing) { + m_impl->dispose_uncommitted(cand); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::conflict, "CModuleHost: host closing")); + } + if (m_impl->modules.contains(mod_id)) { + m_impl->dispose_uncommitted(cand); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::conflict, + "CModuleHost: module already loaded: " + mod_id)); + } + slot = std::make_shared(); + cand->add_external_ref(); + slot->current = cand; + slot->retained.push_back(cand); + m_impl->modules.emplace(mod_id, slot); + } + m_impl->notify_observers(ReloadEvent{ + .module_id = mod_id, .generation = gen, .rollback = false, + .detail = "loaded"}); + return mod_id; + } + + Void::Result::Result> + CModuleHost::load_batch(const std::vector& specs, + Void::Async::OperationOptions options) + { + if (specs.empty()) { + return std::vector{}; + } + { + std::lock_guard lk{m_impl->map_mu}; + if (m_impl->closing) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::conflict, "CModuleHost: host closing")); + } + if (m_impl->modules.size() + specs.size() > + m_impl->limits.max_modules) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::budget_exceeded, + "CModuleHost: batch exceeds max_modules limit")); + } + } + + struct Opened { + std::shared_ptr rec; + std::string config; + std::size_t seq; + }; + std::vector opened; + opened.reserve(specs.size()); + std::unordered_map by_id; + + auto dispose_all = [&](std::size_t active_prefix) { + for (std::size_t i = active_prefix; i > 0; --i) { + m_impl->dispose_uncommitted(opened[i - 1].rec); + } + for (std::size_t i = active_prefix; i < opened.size(); ++i) { + m_impl->dispose_uncommitted(opened[i].rec); + } + }; + + for (std::size_t i = 0; i < specs.size(); ++i) { + const std::uint64_t gen = + m_impl->next_gen.fetch_add(1, std::memory_order_relaxed); + auto cr = m_impl->open_candidate(specs[i].path, gen); + if (!cr) { + dispose_all(0); + return Void::Result::fail(std::move(cr).error()); + } + auto rec = std::move(*cr); + if (!by_id.emplace(rec->module_id, i).second) { + m_impl->dispose_uncommitted(rec); + dispose_all(0); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::conflict, + "CModuleHost::load_batch: duplicate module_id '" + + rec->module_id + "'")); + } + opened.push_back(Opened{std::move(rec), specs[i].config, i}); + } + + // Topological dependency check and policy consistency. + const std::size_t n = opened.size(); + std::vector> adj(n); + std::vector indeg(n, 0); + + for (std::size_t i = 0; i < n; ++i) { + for (const auto& dep : opened[i].rec->dependencies) { + auto it = by_id.find(dep.module_id); + if (it == by_id.end()) { + // Check already-loaded modules. + bool present_active = false; + { + std::lock_guard lk{m_impl->map_mu}; + auto mit = m_impl->modules.find(dep.module_id); + if (mit != m_impl->modules.end() && + mit->second->current) { + if (auto ver = Semver::parse( + mit->second->current->version)) { + if (auto rng = Semver::VersionRange::parse( + dep.version_range); + rng && rng->contains(*ver)) { + present_active = true; + } + } + } + } + if (!dep.optional_dep && !present_active) { + dispose_all(0); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::missing_dependency, + "CModuleHost::load_batch: missing required dependency '" + + dep.module_id + "'")); + } + continue; + } + const std::size_t d = it->second; + if (d == i) { + dispose_all(0); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::cycle_detected, + "CModuleHost::load_batch: self dependency cycle")); + } + const auto ver = + Semver::parse(opened[d].rec->version); + const auto rng = + Semver::VersionRange::parse(dep.version_range); + if (!ver || !rng || !rng->contains(*ver)) { + dispose_all(0); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::missing_dependency, + "CModuleHost::load_batch: incompatible dependency version for '" + + dep.module_id + "'")); + } + adj[d].push_back(i); + ++indeg[i]; + } + } + + std::priority_queue, + std::greater> + ready; + for (std::size_t i = 0; i < n; ++i) { + if (indeg[i] == 0) ready.push(i); + } + std::vector order; + order.reserve(n); + while (!ready.empty()) { + const std::size_t u = ready.top(); + ready.pop(); + order.push_back(std::move(opened[u])); + for (const std::size_t v : adj[u]) { + if (--indeg[v] == 0) ready.push(v); + } + } + if (order.size() != n) { + for (auto& o : opened) m_impl->dispose_uncommitted(o.rec); + for (auto& o : order) m_impl->dispose_uncommitted(o.rec); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::cycle_detected, + "CModuleHost::load_batch: dependency cycle detected")); + } + + const auto now = m_impl->clock->now(); + auto total_dl = now + m_impl->limits.total_reload_timeout; + if (options.deadline.has_value() && *options.deadline < total_dl) { + total_dl = *options.deadline; + } + + std::vector activated_idx; + for (std::size_t i = 0; i < n; ++i) { + if (auto ar = m_impl->activate_and_verify( + *order[i].rec, order[i].config, total_dl, options); + !ar) { + for (auto it = activated_idx.rbegin(); + it != activated_idx.rend(); ++it) { + m_impl->dispose_uncommitted(order[*it].rec); + } + for (std::size_t k = i; k < n; ++k) { + m_impl->dispose_uncommitted(order[k].rec); + } + return Void::Result::fail(std::move(ar).error()); + } + activated_idx.push_back(i); + } + + std::vector ids; + ids.reserve(n); + { + std::lock_guard lk{m_impl->map_mu}; + for (auto& o : order) { + if (m_impl->modules.contains(o.rec->module_id)) { + for (const auto idx : activated_idx) { + m_impl->dispose_uncommitted(order[idx].rec); + } + return Void::Result::fail(make_plugin_error( + PluginErrorCode::conflict, + "CModuleHost::load_batch: conflict with loaded module")); + } + } + for (auto& o : order) { + auto slot = std::make_shared(); + o.rec->add_external_ref(); + slot->current = o.rec; + slot->retained.push_back(o.rec); + ids.push_back(o.rec->module_id); + m_impl->modules.emplace(o.rec->module_id, std::move(slot)); + } + } + return ids; + } + + Void::Result::Result CModuleHost::replace( + std::string_view module_id, const std::filesystem::path& new_path, + std::string_view config, + std::optional expected_generation, + Void::Async::OperationOptions options, + std::function(const GenerationLease&)> + on_publish_locked) + { + std::shared_ptr slot; + { + std::lock_guard lk{m_impl->map_mu}; + if (m_impl->closing) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::conflict, "CModuleHost: host is closing")); + } + auto it = m_impl->modules.find(std::string{module_id}); + if (it == m_impl->modules.end()) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::not_found, + "CModuleHost: unknown module: " + std::string{module_id})); + } + slot = it->second; + } + + std::lock_guard reload_lk{slot->reload_mu}; + + std::shared_ptr old_rec; + std::size_t active_retained_count = 0; + std::size_t total_mapped = 0; + { + std::lock_guard lk{m_impl->map_mu}; + if (m_impl->closing) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::conflict, "CModuleHost: host is closing")); + } + old_rec = slot->current; + std::erase_if(slot->retained, [](const auto& r) { + return !r || (r->destroyed.load(std::memory_order_acquire) && + r->dlclosed.load(std::memory_order_acquire)); + }); + for (const auto& r : slot->retained) { + if (!r->destroyed.load(std::memory_order_acquire)) { + ++active_retained_count; + } + if (!r->dlclosed.load(std::memory_order_acquire)) { + total_mapped += static_cast(r->image_bytes); + } + } + } + + if (!old_rec) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::not_found, "CModuleHost: module unloaded")); + } + if (expected_generation.has_value() && + old_rec->generation != *expected_generation) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::conflict, + "CModuleHost: expected generation conflict")); + } + if (old_rec->activation_policy == VOID_POLICY_RESTART_REQUIRED || + old_rec->activation_policy == VOID_POLICY_INSTALLER_REQUIRED) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::restart_required, + "CModuleHost: active module requires restart for upgrade")); + } + if (m_impl->limits.max_retained_generations > 0 && + active_retained_count >= + m_impl->limits.max_retained_generations) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::retention_limit, + "CModuleHost: max_retained_generations limit reached")); + } + + const std::uint64_t new_gen = + m_impl->next_gen.fetch_add(1, std::memory_order_relaxed); + auto cand_res = m_impl->open_candidate(new_path, new_gen); + if (!cand_res) { + return Void::Result::fail(std::move(cand_res).error()); + } + auto cand = std::move(*cand_res); + + if (cand->module_id != module_id) { + m_impl->dispose_uncommitted(cand); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::conflict, + "CModuleHost: replacement module_id mismatch")); + } + if (cand->activation_policy == VOID_POLICY_RESTART_REQUIRED || + cand->activation_policy == VOID_POLICY_INSTALLER_REQUIRED) { + m_impl->dispose_uncommitted(cand); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::restart_required, + "CModuleHost: candidate module requires restart")); + } + if (total_mapped + cand->image_bytes > + m_impl->limits.max_mapped_bytes_per_module) { + m_impl->dispose_uncommitted(cand); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::budget_exceeded, + "CModuleHost: mapped image byte budget exceeded")); + } + + const auto now = m_impl->clock->now(); + auto total_dl = now + m_impl->limits.total_reload_timeout; + if (options.deadline.has_value() && *options.deadline < total_dl) { + total_dl = *options.deadline; + } + + bool old_quiesced = false; + auto rollback_and_resume_old = + [&](Void::Result::Error primary) -> Void::Result::Result { + m_impl->dispose_uncommitted(cand); + if (old_quiesced && old_rec->api.resume != nullptr && + old_rec->mod_handle != nullptr) { + void_error_detail_v1 res_err{}; + res_err.struct_size = sizeof(void_error_detail_v1); + const std::int32_t rrc = + old_rec->api.resume(old_rec->mod_handle, &res_err); + const std::string rmsg = consume_error_detail(res_err); + if (rrc != VOID_STATUS_OK) { + old_rec->health.store(GenerationHealth::Degraded, + std::memory_order_release); + m_impl->notify_observers(ReloadEvent{ + .module_id = std::string{module_id}, + .generation = old_rec->generation, + .rollback = true, + .detail = "degraded after resume failure: " + rmsg}); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::resume_degraded, + primary.message() + "; old resume failed: " + rmsg)); + } + old_rec->health.store(GenerationHealth::Healthy, + std::memory_order_release); + } + m_impl->notify_observers(ReloadEvent{ + .module_id = std::string{module_id}, + .generation = old_rec->generation, + .rollback = true, + .detail = primary.message()}); + return Void::Result::fail(std::move(primary)); + }; + + const bool stateful = + ((old_rec->api.capabilities & VOID_CAP_STATEFUL_CHECKPOINT) != 0) && + ((cand->api.capabilities & VOID_CAP_STATEFUL_CHECKPOINT) != 0); + + if (stateful) { + old_rec->health.store(GenerationHealth::Quiescing, + std::memory_order_release); + const auto q_dl = + std::min(total_dl, m_impl->clock->now() + + m_impl->limits.quiesce_timeout); + const auto q_opts = + m_impl->make_op_opts(q_dl, options.stop.stop_requested()); + void_error_detail_v1 qerr{}; + qerr.struct_size = sizeof(void_error_detail_v1); + const std::int32_t qrc = + old_rec->api.quiesce(old_rec->mod_handle, &q_opts, &qerr); + const std::string qmsg = consume_error_detail(qerr); + old_quiesced = true; + if (qrc != VOID_STATUS_OK) { + return rollback_and_resume_old(make_plugin_error( + map_cabi_status(qrc, PluginErrorCode::quiesce_failed), + qmsg.empty() ? "CModuleHost: quiesce failed" : qmsg)); + } + + void_owned_bytes_v1 ckpt{}; + void_error_detail_v1 cerr{}; + cerr.struct_size = sizeof(void_error_detail_v1); + const std::int32_t crc = old_rec->api.checkpoint( + old_rec->mod_handle, &q_opts, &ckpt, &cerr); + const std::string cmsg = consume_error_detail(cerr); + + std::vector ckpt_copy; + bool size_ok = true; + if (crc == VOID_STATUS_OK) { + if (ckpt.size > m_impl->limits.max_checkpoint_bytes || + (ckpt.size > 0 && ckpt.data == nullptr)) { + size_ok = false; + } else if (ckpt.size > 0) { + const auto sz = static_cast(ckpt.size); + ckpt_copy.assign(ckpt.data, ckpt.data + sz); + } + } + if (ckpt.release != nullptr && ckpt.data != nullptr) { + ckpt.release(ckpt.release_ctx, ckpt.data, ckpt.size); + } + if (crc != VOID_STATUS_OK) { + return rollback_and_resume_old(make_plugin_error( + map_cabi_status(crc, PluginErrorCode::checkpoint_failed), + cmsg.empty() ? "CModuleHost: checkpoint failed" : cmsg)); + } + if (!size_ok) { + return rollback_and_resume_old(make_plugin_error( + PluginErrorCode::budget_exceeded, + "CModuleHost: checkpoint exceeded max_checkpoint_bytes or invalid buffer")); + } + + const void_bytes_v1 r_bytes{ + .data = ckpt_copy.empty() ? nullptr : ckpt_copy.data(), + .size = static_cast(ckpt_copy.size())}; + void_error_detail_v1 rerr{}; + rerr.struct_size = sizeof(void_error_detail_v1); + const std::int32_t rrc = + cand->api.restore(cand->mod_handle, r_bytes, &rerr); + const std::string rmsg = consume_error_detail(rerr); + if (rrc != VOID_STATUS_OK) { + return rollback_and_resume_old(make_plugin_error( + map_cabi_status(rrc, PluginErrorCode::restore_failed), + rmsg.empty() ? "CModuleHost: restore failed" : rmsg)); + } + } + + if (auto ar = m_impl->activate_and_verify(*cand, config, total_dl, + options); + !ar) { + return rollback_and_resume_old(std::move(ar).error()); + } + + if (on_publish_locked) { + GenerationLease cand_lease{cand}; + if (auto phr = on_publish_locked(cand_lease); !phr) { + return rollback_and_resume_old(std::move(phr).error()); + } + } + + std::shared_ptr retired_old; + bool swap_conflict = false; + { + std::lock_guard lk{m_impl->map_mu}; + if (m_impl->closing || slot->current != old_rec) { + swap_conflict = true; + } else { + cand->add_external_ref(); + retired_old = std::exchange(slot->current, cand); + slot->retained.push_back(cand); + } + } + if (swap_conflict) { + return rollback_and_resume_old(make_plugin_error( + PluginErrorCode::conflict, + "CModuleHost: concurrent generation swap conflict")); + } + + if (retired_old) { + retired_old->health.store(GenerationHealth::Retiring, + std::memory_order_release); + retired_old->retire_requested.store(true, + std::memory_order_seq_cst); + retired_old->release_external_ref(); + } + + m_impl->notify_observers(ReloadEvent{ + .module_id = std::string{module_id}, + .generation = new_gen, + .rollback = false, + .detail = "replaced"}); + return new_gen; + } + + Void::Result::Result CModuleHost::unload(std::string_view module_id) + { + std::shared_ptr slot; + { + std::lock_guard lk{m_impl->map_mu}; + auto it = m_impl->modules.find(std::string{module_id}); + if (it == m_impl->modules.end()) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::not_found, + "CModuleHost: unknown module: " + std::string{module_id})); + } + slot = it->second; + m_impl->modules.erase(it); + } + std::lock_guard reload_lk{slot->reload_mu}; + std::shared_ptr old; + { + std::lock_guard lk{m_impl->map_mu}; + old = std::exchange(slot->current, nullptr); + } + if (old) { + old->health.store(GenerationHealth::Retiring, + std::memory_order_release); + old->retire_requested.store(true, std::memory_order_seq_cst); + if (old->api.request_stop != nullptr && old->mod_handle != nullptr) { + (void)old->api.request_stop(old->mod_handle); + } + old->release_external_ref(); + } + return {}; + } + + GenerationLease CModuleHost::acquire(std::string_view module_id) const + { + std::shared_ptr rec; + { + std::lock_guard lk{m_impl->map_mu}; + if (m_impl->closing) { + return GenerationLease{}; + } + auto it = m_impl->modules.find(std::string{module_id}); + if (it != m_impl->modules.end() && it->second->current) { + rec = it->second->current; + rec->add_external_ref(); + } + } + return rec ? GenerationLease{std::move(rec), + GenerationLease::AlreadyRefCountedTag{}} + : GenerationLease{}; + } + + std::vector + CModuleHost::retained_generations(std::string_view module_id) const + { + std::lock_guard lk{m_impl->map_mu}; + auto it = m_impl->modules.find(std::string{module_id}); + if (it == m_impl->modules.end()) { + return {}; + } + const auto& slot = it->second; + std::vector out; + for (const auto& r : slot->retained) { + if (!r) continue; + if (r->destroyed.load(std::memory_order_acquire) && + r->dlclosed.load(std::memory_order_acquire)) { + continue; + } + out.push_back(GenerationSummary{ + .generation = r->generation, + .module_id = r->module_id, + .version = r->version, + .image_bytes = r->image_bytes, + .external_refs = + r->external_refs.load(std::memory_order_acquire), + .activity_pins = + r->activity_pins.load(std::memory_order_acquire), + .health = r->health.load(std::memory_order_acquire), + .dlclosed = r->dlclosed.load(std::memory_order_acquire)}); + } + return out; + } + + std::size_t CModuleHost::mapped_bytes(std::string_view module_id) const + { + std::size_t sum = 0; + for (const auto& g : retained_generations(module_id)) { + if (!g.dlclosed) { + sum += static_cast(g.image_bytes); + } + } + return sum; + } + +} // namespace Void::Plugin diff --git a/src/Plugin/Manager.cpp b/src/Plugin/Manager.cpp index f727ffc..ee0ff19 100644 --- a/src/Plugin/Manager.cpp +++ b/src/Plugin/Manager.cpp @@ -187,10 +187,7 @@ namespace Void::Plugin } // Copy to a fresh-inode temp path so dlopen does not return the - // already-mapped image when the file is replaced in place. The name - // must be unique per copy: glibc dedupes dlopen by pathname, so - // reusing a temp name would hand back the previously mapped (old) - // image no matter what bytes the file now holds. + // already-mapped image when the file is replaced in place. std::expected hotswap_copy(const std::filesystem::path& path) { @@ -213,9 +210,10 @@ namespace Void::Plugin // ── PluginManager ───────────────────────────────────────────────────── PluginManager::PluginManager(Options options) - : m_options(options), m_watcher(FileSystem::FileWatcherOptions{ - .poll_interval = options.poll_interval, - .debounce_polls = options.debounce_polls}) + : m_options(std::move(options)), + m_watcher(FileSystem::FileWatcherOptions{ + .poll_interval = m_options.poll_interval, + .debounce_polls = m_options.debounce_polls}) { } @@ -227,6 +225,13 @@ namespace Void::Plugin return it == m_plugins.end() ? nullptr : it->second.get(); } + std::shared_ptr + PluginManager::find_shared(std::string_view name) const + { + const auto it = m_plugins.find(std::string{name}); + return it == m_plugins.end() ? nullptr : it->second; + } + std::expected PluginManager::load(const std::filesystem::path& path) { @@ -244,8 +249,6 @@ namespace Void::Plugin } auto inst = open_instance(load_path, m_options.dlclose_on_swap); if (m_options.copy_on_load) { - // The mapping keeps the unlinked inode alive; the registry - // keeps addressing the original path for watch/reload. std::filesystem::remove(load_path, ec); } if (!inst.has_value()) { @@ -278,15 +281,24 @@ namespace Void::Plugin return std::unexpected{LoadError::ActivationFailed}; } - std::lock_guard lock(m_mutex); - auto entry = std::make_unique(); - entry->path = path; - entry->current.store(std::move(*inst), std::memory_order_release); - Void::Log::info("Plugin.Manager", "loaded '{}' as '{}' (v{})", - path.string(), name, - entry->current.load(std::memory_order_relaxed) - ->info.plugin_version); - m_plugins.insert_or_assign(name, std::move(entry)); + std::shared_ptr replaced_entry; + { + std::lock_guard lock(m_mutex); + auto entry = std::make_shared(); + entry->path = path; + entry->current.store(std::move(*inst), std::memory_order_release); + Void::Log::info("Plugin.Manager", "loaded '{}' as '{}' (v{})", + path.string(), name, + entry->current.load(std::memory_order_relaxed) + ->info.plugin_version); + auto it = m_plugins.find(name); + if (it != m_plugins.end()) { + replaced_entry = std::move(it->second); + it->second = std::move(entry); + } else { + m_plugins.emplace(name, std::move(entry)); + } + } return name; } @@ -323,195 +335,199 @@ namespace Void::Plugin std::expected PluginManager::unload(std::string_view name) { - std::lock_guard lock(m_mutex); - auto* entry = find(name); - if (entry == nullptr) { - return std::unexpected{LoadError::UnknownPlugin}; + std::shared_ptr removed; + { + std::lock_guard lock(m_mutex); + auto it = m_plugins.find(std::string{name}); + if (it == m_plugins.end()) { + return std::unexpected{LoadError::UnknownPlugin}; + } + m_watcher.unwatch(it->second->path); + removed = std::move(it->second); + m_plugins.erase(it); } - m_watcher.unwatch(entry->path); - // Erasing drops the registry's reference; outstanding handles keep - // the instance (and its mapped .so) alive until they drop. - m_plugins.erase(std::string{name}); Void::Log::info("Plugin.Manager", "unloaded '{}'", name); return {}; } PluginHandle PluginManager::acquire(std::string_view name) const { - std::lock_guard lock(m_mutex); - auto* entry = find(name); - if (entry == nullptr) { + std::shared_ptr entry; + { + std::lock_guard lock(m_mutex); + entry = find_shared(name); + } + if (!entry) { return PluginHandle{}; } - // One atomic load pins the instance; it survives any later swap. return PluginHandle{entry->current.load(std::memory_order_acquire)}; } std::expected PluginManager::reload(std::string_view name) { - std::vector> callbacks; + std::shared_ptr entry; { std::lock_guard lock(m_mutex); - auto* entry = find(name); - if (entry == nullptr) { - return std::unexpected{LoadError::UnknownPlugin}; - } - auto result = reload_locked(*entry, name, entry->path); - if (!result.has_value()) { - return result; - } - callbacks = reload_callbacks_locked(); + entry = find_shared(name); } - for (const auto& cb : callbacks) { - cb(name); + if (!entry) { + return std::unexpected{LoadError::UnknownPlugin}; } - return {}; + return reload_entry_unlocked(entry, name, std::nullopt); } std::expected PluginManager::replace(std::string_view name, const std::filesystem::path& newPath) { - std::vector> callbacks; - bool restartWatcher = false; + std::shared_ptr entry; { std::lock_guard lock(m_mutex); - auto* entry = find(name); - if (entry == nullptr) { - return std::unexpected{LoadError::UnknownPlugin}; - } - std::error_code error; - if (!std::filesystem::is_regular_file(newPath, error)) { - return std::unexpected{LoadError::FileNotFound}; - } - auto result = reload_locked(*entry, name, newPath); - if (!result) { - return result; - } - restartWatcher = entry->watched; - if (restartWatcher) { - m_watcher.unwatch(entry->path); - } - entry->path = newPath; - callbacks = reload_callbacks_locked(); + entry = find_shared(name); } + if (!entry) { + return std::unexpected{LoadError::UnknownPlugin}; + } + std::error_code error; + if (!std::filesystem::is_regular_file(newPath, error)) { + return std::unexpected{LoadError::FileNotFound}; + } + return reload_entry_unlocked(entry, name, newPath); + } + + std::expected PluginManager::reload_entry_unlocked( + const std::shared_ptr& entry, std::string_view name, + const std::optional& newPath) + { + std::vector> callbacks; + bool restartWatcher = false; + std::shared_ptr retired_old; + + { + // Serialize reloads per plugin entry WITHOUT holding m_mutex, so + // validators, config providers, and concurrent acquire() callers can + // reenter PluginManager without deadlocking. + std::lock_guard reload_lk{entry->reload_mutex}; + + std::filesystem::path sourcePath; + { + std::lock_guard lock(m_mutex); + if (find(name) != entry.get()) { + return std::unexpected{LoadError::UnknownPlugin}; + } + sourcePath = newPath.has_value() ? *newPath : entry->path; + } + + auto tmp = hotswap_copy(sourcePath); + if (!tmp.has_value()) { + return std::unexpected{tmp.error()}; + } + auto next = open_instance(*tmp, m_options.dlclose_on_swap); + std::error_code ec; + std::filesystem::remove(*tmp, ec); + if (!next.has_value()) { + Void::Log::warn("Plugin.Manager", + "reload '{}' failed: {}; keeping old", name, + to_string(next.error())); + return std::unexpected{next.error()}; + } + if ((*next)->plugin->name() != name) { + Void::Log::warn("Plugin.Manager", + "replace '{}' rejected: candidate reports '{}'", + name, (*next)->plugin->name()); + return std::unexpected{LoadError::NameMismatch}; + } + if (m_options.candidate_validator && + !m_options.candidate_validator(PluginHandle{*next})) { + Void::Log::warn("Plugin.Manager", + "reload '{}' aborted: binary validation failed", + name); + return std::unexpected{LoadError::ActivationFailed}; + } + + if (m_options.config_provider && (*next)->configure != nullptr) { + const std::string config = m_options.config_provider(name); + (*next)->configure((*next)->plugin, config.c_str()); + } + + auto old = entry->current.load(std::memory_order_acquire); + if (old) { + if (!transfer_state(*old, **next)) { + Void::Log::warn("Plugin.Manager", + "reload '{}' aborted: state rejected", name); + return std::unexpected{LoadError::StateRejected}; + } + } + + try { + (*next)->plugin->on_load(); + } catch (...) { + return std::unexpected{LoadError::ActivationFailed}; + } + if ((*next)->ready != nullptr && + (*next)->ready((*next)->plugin) != 0) { + Void::Log::warn("Plugin.Manager", + "reload '{}' aborted: activation failed", name); + return std::unexpected{LoadError::ActivationFailed}; + } + if (m_options.instance_validator && + !m_options.instance_validator(*(*next)->plugin, (*next)->info)) { + Void::Log::warn("Plugin.Manager", + "reload '{}' aborted: host validation failed", + name); + return std::unexpected{LoadError::ActivationFailed}; + } + + { + std::lock_guard lock(m_mutex); + if (find(name) != entry.get()) { + return std::unexpected{LoadError::UnknownPlugin}; + } + retired_old = entry->current.exchange( + std::move(*next), std::memory_order_acq_rel); + if (newPath.has_value()) { + restartWatcher = entry->watched; + if (restartWatcher) { + m_watcher.unwatch(entry->path); + } + entry->path = *newPath; + } + callbacks = reload_callbacks_locked(); + } + } + + // Drop old instance and invoke observers strictly outside all locks. + retired_old.reset(); if (restartWatcher) { watch(name); } - for (const auto& callback : callbacks) { - callback(name); - } - return {}; - } - - std::expected - PluginManager::reload_locked(Entry& entry, std::string_view name, - const std::filesystem::path& sourcePath) - { - // Copy to a fresh inode so dlopen loads the new bytes instead of - // returning the still-open handle for this path. The caller must - // have installed the new file via atomic rename (a fresh inode of - // its own) — overwriting the mapped file in place corrupts the - // running instance's mapping (SIGBUS). - auto tmp = hotswap_copy(sourcePath); - if (!tmp.has_value()) { - return std::unexpected{tmp.error()}; - } - auto next = open_instance(*tmp, m_options.dlclose_on_swap); - std::error_code ec; - std::filesystem::remove(*tmp, ec); - if (!next.has_value()) { - Void::Log::warn("Plugin.Manager", - "reload '{}' failed: {}; keeping old", name, - to_string(next.error())); - return std::unexpected{next.error()}; - } - if ((*next)->plugin->name() != name) { - Void::Log::warn("Plugin.Manager", - "replace '{}' rejected: candidate reports '{}'", - name, (*next)->plugin->name()); - return std::unexpected{LoadError::NameMismatch}; - } - if (m_options.candidate_validator && - !m_options.candidate_validator(PluginHandle{*next})) { - Void::Log::warn("Plugin.Manager", - "reload '{}' aborted: binary validation failed", - name); - return std::unexpected{LoadError::ActivationFailed}; - } - - if (m_options.config_provider && (*next)->configure != nullptr) { - const std::string config = m_options.config_provider(name); - (*next)->configure((*next)->plugin, config.c_str()); - } - - // Transfer state with both instances alive (transactional). - auto old = entry.current.load(std::memory_order_acquire); - if (old) { - if (!transfer_state(*old, **next)) { - Void::Log::warn("Plugin.Manager", - "reload '{}' aborted: state rejected", name); - return std::unexpected{LoadError::StateRejected}; - } - } - - try { - (*next)->plugin->on_load(); - } catch (...) { - return std::unexpected{LoadError::ActivationFailed}; - } - if ((*next)->ready != nullptr && (*next)->ready((*next)->plugin) != 0) { - Void::Log::warn("Plugin.Manager", - "reload '{}' aborted: activation failed", name); - return std::unexpected{LoadError::ActivationFailed}; - } - if (m_options.instance_validator && - !m_options.instance_validator(*(*next)->plugin, (*next)->info)) { - Void::Log::warn("Plugin.Manager", - "reload '{}' aborted: host validation failed", - name); - return std::unexpected{LoadError::ActivationFailed}; - } - // Atomic swap. The old instance keeps living while any acquired - // handle still pins it; it is destroyed when the last one drops. - entry.current.store(std::move(*next), std::memory_order_release); Void::Log::info("Plugin.Manager", "reloaded '{}'", name); + for (const auto& cb : callbacks) { + cb(name); + } return {}; } void PluginManager::watch(std::string_view name) { + std::shared_ptr entry; std::filesystem::path path; { std::lock_guard lock(m_mutex); - auto* entry = find(name); - if (entry == nullptr) { + entry = find_shared(name); + if (!entry) { return; } path = entry->path; entry->watched = true; } const std::string name_str{name}; - m_watcher.watch(path, [this, name_str]( + m_watcher.watch(path, [this, entry, name_str]( const FileSystem::FileWatcher::Event& e) { if (!e.exists) { return; } - std::vector> callbacks; - { - std::lock_guard lock(m_mutex); - auto* entry = find(name_str); - if (entry == nullptr) { - return; - } - if (!reload_locked(*entry, name_str, entry->path).has_value()) { - return; - } - callbacks = reload_callbacks_locked(); - } - for (const auto& cb : callbacks) { - cb(name_str); - } + (void)reload_entry_unlocked(entry, name_str, std::nullopt); }); } diff --git a/src/Plugin/module.cmake b/src/Plugin/module.cmake index 3463646..9275728 100644 --- a/src/Plugin/module.cmake +++ b/src/Plugin/module.cmake @@ -1,4 +1,4 @@ void_add_module(Plugin - INTERNAL_DEPS Functional System Data LogState Text Service + INTERNAL_DEPS Core Functional System Data Time Async LogState Text Service DEPS_UNIX dl ) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 458d156..7ab3e31 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -252,4 +252,56 @@ if(TARGET VoidTests AND TARGET Void::Plugin) ) add_dependencies(VoidTests VoidServicePluginV1 VoidServicePluginV2) endif() + + enable_language(C) + function(_void_add_cabi_fixture target_name source_file) + add_library(${target_name} SHARED "${CMAKE_CURRENT_SOURCE_DIR}/plugins/${source_file}") + target_include_directories(${target_name} PRIVATE "${CMAKE_SOURCE_DIR}/include") + set_target_properties(${target_name} PROPERTIES + C_STANDARD 11 + C_STANDARD_REQUIRED ON + C_EXTENSIONS OFF + VOID_TESTING_NO_AUTO_SCAN TRUE) + if(VOID_WARNINGS_AS_ERRORS) + target_compile_options(${target_name} PRIVATE -Wall -Wextra -Wpedantic -Werror) + endif() + if(VOID_ENABLE_ASAN) + target_compile_options(${target_name} PRIVATE -fsanitize=address -fno-omit-frame-pointer) + target_link_options(${target_name} PRIVATE -fsanitize=address) + endif() + if(VOID_ENABLE_UBSAN) + target_compile_options(${target_name} PRIVATE -fsanitize=undefined) + target_link_options(${target_name} PRIVATE -fsanitize=undefined) + endif() + if(VOID_ENABLE_TSAN) + target_compile_options(${target_name} PRIVATE -fsanitize=thread) + target_link_options(${target_name} PRIVATE -fsanitize=thread) + endif() + foreach(_def IN LISTS ARGN) + target_compile_definitions(${target_name} PRIVATE "${_def}") + endforeach() + add_dependencies(VoidTests ${target_name}) + endfunction() + + _void_add_cabi_fixture(VoidCAbiPluginV1 CAbiPluginV1.c) + _void_add_cabi_fixture(VoidCAbiPluginV2 CAbiPluginV2.c) + _void_add_cabi_fixture(VoidCAbiBadTrunc CAbiBadPlugin.c "BAD_MODE=1") + _void_add_cabi_fixture(VoidCAbiBadMajor CAbiBadPlugin.c "BAD_MODE=2") + _void_add_cabi_fixture(VoidCAbiBadReserved CAbiBadPlugin.c "BAD_MODE=3") + _void_add_cabi_fixture(VoidCAbiDepA CAbiDepPlugin.c "DEP_MODE=1") + _void_add_cabi_fixture(VoidCAbiDepB CAbiDepPlugin.c "DEP_MODE=2") + _void_add_cabi_fixture(VoidCAbiCycA CAbiDepPlugin.c "DEP_MODE=3") + _void_add_cabi_fixture(VoidCAbiCycB CAbiDepPlugin.c "DEP_MODE=4") + + target_compile_definitions(VoidTests PRIVATE + "VOID_CABI_V1_PATH=\"$\"" + "VOID_CABI_V2_PATH=\"$\"" + "VOID_CABI_BAD_TRUNC_PATH=\"$\"" + "VOID_CABI_BAD_MAJOR_PATH=\"$\"" + "VOID_CABI_BAD_RESERVED_PATH=\"$\"" + "VOID_CABI_DEP_A_PATH=\"$\"" + "VOID_CABI_DEP_B_PATH=\"$\"" + "VOID_CABI_CYC_A_PATH=\"$\"" + "VOID_CABI_CYC_B_PATH=\"$\"" + ) endif() diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index 0e4289c..0e11b78 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -252,6 +252,16 @@ if(_has_service_plugin) -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) endif() +has_modules(_has_plugin Plugin Core Functional System Data Time Async LogState Text Service) +if(_has_plugin) + run_consumer(PluginOnly "${install_prefix}" "PluginOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/package/PluginOnly/CMakeLists.txt b/tests/package/PluginOnly/CMakeLists.txt new file mode 100644 index 0000000..93b102f --- /dev/null +++ b/tests/package/PluginOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidPluginOnlyConsumer LANGUAGES C CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Plugin) + +add_executable(void_plugin_only_consumer main.cpp) +target_link_libraries(void_plugin_only_consumer PRIVATE Void::Plugin) +target_compile_features(void_plugin_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME PluginOnlyConsumer COMMAND void_plugin_only_consumer) diff --git a/tests/package/PluginOnly/main.cpp b/tests/package/PluginOnly/main.cpp new file mode 100644 index 0000000..cde5c87 --- /dev/null +++ b/tests/package/PluginOnly/main.cpp @@ -0,0 +1,18 @@ +#include +#include +#include +#include + +#include + +int main() +{ + Void::Plugin::PluginHostLimits limits{}; + Void::Plugin::CModuleHost host{limits}; + const auto loaded = host.acquire("missing"); + void_module_api_v1 api{}; + api.struct_size = sizeof(api); + api.abi_major = VOID_CABI_MAJOR_V1; + api.abi_minor = VOID_CABI_MINOR_V1; + return !loaded && api.abi_major == 1u ? 0 : 1; +} diff --git a/tests/plugins/CAbiBadPlugin.c b/tests/plugins/CAbiBadPlugin.c new file mode 100644 index 0000000..610b339 --- /dev/null +++ b/tests/plugins/CAbiBadPlugin.c @@ -0,0 +1,78 @@ +#include + +#include +#include + +#ifndef BAD_MODE +#define BAD_MODE 1 +#endif + +static int32_t stub_get_info(void_module_info_v1* out) +{ + if (out == NULL) return VOID_STATUS_INVALID_ARGUMENT; + memset(out, 0, sizeof(*out)); + out->struct_size = (uint32_t)sizeof(void_module_info_v1); + out->module_id = "cabi.bad"; + out->version = "1.0.0"; + return VOID_STATUS_OK; +} + +static int32_t stub_create(const void_host_api_v1* h, void_module_handle** out) +{ + (void)h; + if (out != NULL) *out = NULL; + return VOID_STATUS_INTERNAL; +} + +static int32_t stub_activate(void_module_handle* h, void_bytes_v1 c, void_error_detail_v1* e) +{ + (void)h; (void)c; (void)e; + return VOID_STATUS_OK; +} + +static int32_t stub_readiness(void_module_handle* h, uint32_t* r, void_error_detail_v1* e) +{ + (void)h; (void)r; (void)e; + return VOID_STATUS_OK; +} + +static int32_t stub_stop(void_module_handle* h) +{ + (void)h; + return VOID_STATUS_OK; +} + +static void stub_destroy(void_module_handle* h) { (void)h; } + +int32_t void_module_query_v1(uint32_t host_struct_size, + void_module_api_v1* out_api) +{ + (void)host_struct_size; + if (out_api == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + memset(out_api, 0, sizeof(*out_api)); + out_api->struct_size = (uint32_t)sizeof(void_module_api_v1); + out_api->abi_major = VOID_CABI_MAJOR_V1; + out_api->abi_minor = VOID_CABI_MINOR_V1; + out_api->reserved = 0; + out_api->get_info = stub_get_info; + out_api->create = stub_create; + out_api->activate = stub_activate; + out_api->readiness = stub_readiness; + out_api->request_stop = stub_stop; + out_api->deactivate = stub_stop; + out_api->destroy = stub_destroy; + +#if BAD_MODE == 1 + /* Truncated struct_size */ + out_api->struct_size = 16u; +#elif BAD_MODE == 2 + /* Unsupported abi_major */ + out_api->abi_major = 99u; +#elif BAD_MODE == 3 + /* Non-zero reserved */ + out_api->reserved = 1u; +#endif + return VOID_STATUS_OK; +} diff --git a/tests/plugins/CAbiDepPlugin.c b/tests/plugins/CAbiDepPlugin.c new file mode 100644 index 0000000..54f1e4e --- /dev/null +++ b/tests/plugins/CAbiDepPlugin.c @@ -0,0 +1,104 @@ +#include + +#include +#include +#include + +#ifndef DEP_MODE +#define DEP_MODE 1 +#endif + +struct void_module_handle { + int dummy; +}; + +#if DEP_MODE == 2 +static const void_dependency_v1 kDeps[] = { + {.module_id = "cabi.dep.a", .version_range = "^1.0.0", .optional_dep = 0}, +}; +#elif DEP_MODE == 3 +static const void_dependency_v1 kDeps[] = { + {.module_id = "cabi.cyc.b", .version_range = "^1.0.0", .optional_dep = 0}, +}; +#elif DEP_MODE == 4 +static const void_dependency_v1 kDeps[] = { + {.module_id = "cabi.cyc.a", .version_range = "^1.0.0", .optional_dep = 0}, +}; +#endif + +static int32_t dep_get_info(void_module_info_v1* out) +{ + if (out == NULL) return VOID_STATUS_INVALID_ARGUMENT; + memset(out, 0, sizeof(*out)); + out->struct_size = (uint32_t)sizeof(void_module_info_v1); +#if DEP_MODE == 1 + out->module_id = "cabi.dep.a"; + out->version = "1.0.0"; + out->activation_policy = VOID_POLICY_RESTART_REQUIRED; +#elif DEP_MODE == 2 + out->module_id = "cabi.dep.b"; + out->version = "1.0.0"; + out->activation_policy = VOID_POLICY_RELOADABLE; + out->dependencies = kDeps; + out->dependency_count = 1u; +#elif DEP_MODE == 3 + out->module_id = "cabi.cyc.a"; + out->version = "1.0.0"; + out->dependencies = kDeps; + out->dependency_count = 1u; +#elif DEP_MODE == 4 + out->module_id = "cabi.cyc.b"; + out->version = "1.0.0"; + out->dependencies = kDeps; + out->dependency_count = 1u; +#endif + return VOID_STATUS_OK; +} + +static int32_t dep_create(const void_host_api_v1* h, void_module_handle** out) +{ + (void)h; + *out = (struct void_module_handle*)calloc(1, sizeof(struct void_module_handle)); + return *out ? VOID_STATUS_OK : VOID_STATUS_EXHAUSTED; +} + +static int32_t dep_activate(void_module_handle* h, void_bytes_v1 c, void_error_detail_v1* e) +{ + (void)h; (void)c; (void)e; + return VOID_STATUS_OK; +} + +static int32_t dep_readiness(void_module_handle* h, uint32_t* r, void_error_detail_v1* e) +{ + (void)h; (void)e; + *r = 1u; + return VOID_STATUS_OK; +} + +static int32_t dep_stop(void_module_handle* h) +{ + (void)h; + return VOID_STATUS_OK; +} + +static void dep_destroy(void_module_handle* h) { free(h); } + +int32_t void_module_query_v1(uint32_t host_struct_size, + void_module_api_v1* out_api) +{ + if (out_api == NULL || host_struct_size < VOID_MODULE_API_V1_MIN_SIZE) { + return VOID_STATUS_INVALID_ARGUMENT; + } + memset(out_api, 0, sizeof(*out_api)); + out_api->struct_size = (uint32_t)sizeof(void_module_api_v1); + out_api->abi_major = VOID_CABI_MAJOR_V1; + out_api->abi_minor = VOID_CABI_MINOR_V1; + out_api->get_info = dep_get_info; + out_api->create = dep_create; + out_api->activate = dep_activate; + out_api->readiness = dep_readiness; + out_api->request_stop = dep_stop; + out_api->deactivate = dep_stop; + out_api->destroy = dep_destroy; + return VOID_STATUS_OK; +} diff --git a/tests/plugins/CAbiPluginV1.c b/tests/plugins/CAbiPluginV1.c new file mode 100644 index 0000000..c3ea077 --- /dev/null +++ b/tests/plugins/CAbiPluginV1.c @@ -0,0 +1,488 @@ +#include + +#include +#include +#include +#include +#include +#include + +typedef struct cabi_calc_v1 { + uint32_t (*version)(void_module_handle* h); + int32_t (*accumulate)(void_module_handle* h, int32_t delta); +} cabi_calc_v1; + +struct void_operation_handle { + void_module_handle* owner; + thrd_t worker; + int worker_started; + atomic_int cancelled; + uint32_t op_kind; + int32_t delta; + void_async_complete_fn cb; + void* cb_ctx; +}; + +struct void_module_handle { + void_host_api_v1 host; + atomic_int total; + atomic_int quiescing; + int fail_quiesce; + int fail_resume; + int ckpt_fail; + int ckpt_oversized; + int ready; + mtx_t ops_mu; + struct void_operation_handle* ops[64]; + size_t ops_count; +}; + +static const void_interface_id_v1 kCalcIfaceId = { + {0x76, 0x6f, 0x69, 0x64, 0x63, 0x61, 0x6c, 0x63, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x01}}; + +static void free_c_str(void* ctx, const char* msg) +{ + (void)ctx; + free((void*)msg); +} + +static void free_c_bytes(void* ctx, const uint8_t* data, uint64_t size) +{ + (void)ctx; + (void)size; + free((void*)data); +} + +static void set_err(void_error_detail_v1* out_err, + int32_t status, + const char* text) +{ + if (out_err == NULL || out_err->struct_size < sizeof(void_error_detail_v1)) { + return; + } + out_err->status = status; + if (text != NULL) { + size_t n = strlen(text); + char* copy = (char*)malloc(n + 1); + if (copy != NULL) { + memcpy(copy, text, n + 1); + out_err->message = copy; + out_err->release = free_c_str; + out_err->release_ctx = NULL; + } + } +} + +static int cfg_has(void_bytes_v1 cfg, const char* needle) +{ + if (cfg.data == NULL || cfg.size == 0) { + return 0; + } + size_t nlen = strlen(needle); + if (cfg.size < nlen) { + return 0; + } + for (uint64_t i = 0; i + nlen <= cfg.size; ++i) { + if (memcmp(cfg.data + i, needle, nlen) == 0) { + return 1; + } + } + return 0; +} + +static int32_t cabi_get_info(void_module_info_v1* out_info) +{ + if (out_info == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + memset(out_info, 0, sizeof(*out_info)); + out_info->struct_size = (uint32_t)sizeof(void_module_info_v1); + out_info->module_id = "cabi.calc"; + out_info->version = "1.0.0"; + out_info->activation_policy = VOID_POLICY_RELOADABLE; + out_info->state_schema_version = 1; + out_info->dependencies = NULL; + out_info->dependency_count = 0; + return VOID_STATUS_OK; +} + +static int32_t cabi_create(const void_host_api_v1* host_api, + void_module_handle** out_handle) +{ + if (out_handle == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + *out_handle = NULL; + if (host_api == NULL || host_api->struct_size < sizeof(void_host_api_v1)) { + return VOID_STATUS_INVALID_ARGUMENT; + } + struct void_module_handle* h = + (struct void_module_handle*)calloc(1, sizeof(*h)); + if (h == NULL) { + return VOID_STATUS_EXHAUSTED; + } + h->host = *host_api; + atomic_init(&h->total, 0); + atomic_init(&h->quiescing, 0); + h->ready = 1; + mtx_init(&h->ops_mu, mtx_plain); + *out_handle = h; + return VOID_STATUS_OK; +} + +static int32_t cabi_activate(void_module_handle* h, + void_bytes_v1 config, + void_error_detail_v1* out_err) +{ + if (h == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + if (cfg_has(config, "fail_activate")) { + set_err(out_err, VOID_STATUS_INTERNAL, "V1 activation rejected"); + return VOID_STATUS_INTERNAL; + } + h->ready = cfg_has(config, "not_ready") ? 0 : 1; + h->fail_quiesce = cfg_has(config, "quiesce_fail"); + h->fail_resume = cfg_has(config, "quiesce_fail_resume_fail"); + if (h->fail_resume) { + h->fail_quiesce = 1; + } + h->ckpt_fail = cfg_has(config, "ckpt_fail"); + h->ckpt_oversized = cfg_has(config, "ckpt_oversized"); + return VOID_STATUS_OK; +} + +static int32_t cabi_readiness(void_module_handle* h, + uint32_t* out_ready, + void_error_detail_v1* out_err) +{ + if (h == NULL || out_ready == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + *out_ready = h->ready ? 1u : 0u; + if (!h->ready) { + set_err(out_err, VOID_STATUS_NOT_READY, "V1 not ready"); + } + return VOID_STATUS_OK; +} + +static int32_t cabi_quiesce(void_module_handle* h, + const void_op_options_v1* opts, + void_error_detail_v1* out_err) +{ + (void)opts; + if (h == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + atomic_store(&h->quiescing, 1); + if (h->fail_quiesce) { + set_err(out_err, VOID_STATUS_QUIESCING, "V1 quiesce refused"); + return VOID_STATUS_QUIESCING; + } + return VOID_STATUS_OK; +} + +static int32_t cabi_resume(void_module_handle* h, void_error_detail_v1* out_err) +{ + if (h == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + if (h->fail_resume) { + set_err(out_err, VOID_STATUS_INTERNAL, "V1 resume failed"); + return VOID_STATUS_INTERNAL; + } + atomic_store(&h->quiescing, 0); + return VOID_STATUS_OK; +} + +static int32_t cabi_checkpoint(void_module_handle* h, + const void_op_options_v1* opts, + void_owned_bytes_v1* out_state, + void_error_detail_v1* out_err) +{ + (void)opts; + if (h == NULL || out_state == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + memset(out_state, 0, sizeof(*out_state)); + if (h->ckpt_fail) { + set_err(out_err, VOID_STATUS_INTERNAL, "V1 checkpoint error"); + return VOID_STATUS_INTERNAL; + } + if (h->ckpt_oversized) { + uint8_t* dummy = (uint8_t*)malloc(16); + out_state->data = dummy; + out_state->size = UINT64_C(8) * UINT64_C(1024) * UINT64_C(1024); + out_state->release = free_c_bytes; + out_state->release_ctx = NULL; + return VOID_STATUS_OK; + } + char buf[64]; + int n = snprintf(buf, sizeof(buf), "v1:%d", atomic_load(&h->total)); + if (n <= 0) { + return VOID_STATUS_INTERNAL; + } + uint8_t* copy = (uint8_t*)malloc((size_t)n); + if (copy == NULL) { + return VOID_STATUS_EXHAUSTED; + } + memcpy(copy, buf, (size_t)n); + out_state->data = copy; + out_state->size = (uint64_t)n; + out_state->release = free_c_bytes; + out_state->release_ctx = NULL; + return VOID_STATUS_OK; +} + +static int32_t cabi_restore(void_module_handle* h, + void_bytes_v1 state, + void_error_detail_v1* out_err) +{ + (void)h; + (void)state; + (void)out_err; + return VOID_STATUS_OK; +} + +static uint32_t iface_get_version(void_module_handle* h) +{ + (void)h; + return 1u; +} + +static int32_t iface_accumulate(void_module_handle* h, int32_t delta) +{ + if (h == NULL) { + return -1; + } + if (atomic_load(&h->quiescing) != 0 && delta != 0) { + return -1; + } + return atomic_fetch_add(&h->total, delta) + delta; +} + +static const cabi_calc_v1 kCalcTable = {iface_get_version, iface_accumulate}; + +static int32_t cabi_query_interface(void_module_handle* h, + const void_interface_id_v1* iface_id, + uint32_t min_major, + uint32_t min_table_size, + void_interface_view_v1* out_view) +{ + if (h == NULL || iface_id == NULL || out_view == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + if (memcmp(iface_id->bytes, kCalcIfaceId.bytes, 16) != 0) { + return VOID_STATUS_NOT_FOUND; + } + if (min_major != 1u || min_table_size > sizeof(cabi_calc_v1)) { + return VOID_STATUS_UNSUPPORTED; + } + out_view->struct_size = (uint32_t)sizeof(void_interface_view_v1); + out_view->major = 1u; + out_view->minor = 0u; + out_view->table_size = (uint32_t)sizeof(cabi_calc_v1); + out_view->function_table = &kCalcTable; + return VOID_STATUS_OK; +} + +static void cabi_release_interface(void_module_handle* h, + const void_interface_id_v1* iface_id, + const void_interface_view_v1* view) +{ + (void)h; + (void)iface_id; + (void)view; +} + +static int async_worker(void* arg) +{ + struct void_operation_handle* op = (struct void_operation_handle*)arg; + int pinned = 0; + if (op->op_kind == 3u && op->owner->host.acquire_activity_pin != NULL) { + if (op->owner->host.acquire_activity_pin( + op->owner->host.host_ctx, op->owner->host.generation) == + VOID_STATUS_OK) { + pinned = 1; + } + } + struct timespec ts = {.tv_sec = 0, .tv_nsec = 2000000}; + for (int i = 0; i < 10; ++i) { + if (atomic_load(&op->cancelled) != 0) { + op->cb(op->cb_ctx, VOID_STATUS_CANCELLED, NULL); + if (pinned) { + op->owner->host.release_activity_pin( + op->owner->host.host_ctx, op->owner->host.generation); + } + return 0; + } + thrd_sleep(&ts, NULL); + } + int32_t val = atomic_fetch_add(&op->owner->total, op->delta) + op->delta; + uint8_t buf[4]; + memcpy(buf, &val, sizeof(val)); + void_bytes_v1 res = {.data = buf, .size = sizeof(buf)}; + op->cb(op->cb_ctx, VOID_STATUS_OK, &res); + if (pinned) { + op->owner->host.release_activity_pin(op->owner->host.host_ctx, + op->owner->host.generation); + } + return 0; +} + +static int32_t cabi_submit_async(void_module_handle* h, + uint32_t op_kind, + void_bytes_v1 payload, + const void_op_options_v1* opts, + void_async_complete_fn cb, + void* cb_ctx, + void_operation_handle** out_op, + void_error_detail_v1* out_err) +{ + (void)out_err; + if (h == NULL || cb == NULL || out_op == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + *out_op = NULL; + if (opts != NULL && opts->stop_requested) { + return VOID_STATUS_CANCELLED; + } + int32_t delta = 0; + if (payload.data != NULL && payload.size >= 4) { + memcpy(&delta, payload.data, 4); + } + struct void_operation_handle* op = + (struct void_operation_handle*)calloc(1, sizeof(*op)); + if (op == NULL) { + return VOID_STATUS_EXHAUSTED; + } + op->owner = h; + op->op_kind = op_kind; + op->delta = delta; + op->cb = cb; + op->cb_ctx = cb_ctx; + atomic_init(&op->cancelled, 0); + + if (op_kind == 2u) { + int32_t val = atomic_fetch_add(&h->total, delta) + delta; + uint8_t buf[4]; + memcpy(buf, &val, sizeof(val)); + void_bytes_v1 res = {.data = buf, .size = sizeof(buf)}; + *out_op = op; + cb(cb_ctx, VOID_STATUS_OK, &res); + return VOID_STATUS_OK; + } + + mtx_lock(&h->ops_mu); + if (h->ops_count < 64) { + h->ops[h->ops_count++] = op; + } + mtx_unlock(&h->ops_mu); + + op->worker_started = 1; + *out_op = op; + if (thrd_create(&op->worker, async_worker, op) != thrd_success) { + op->worker_started = 0; + *out_op = NULL; + free(op); + return VOID_STATUS_INTERNAL; + } + return VOID_STATUS_OK; +} + +static int32_t cabi_cancel_async(void_module_handle* h, void_operation_handle* op) +{ + (void)h; + if (op == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + atomic_store(&op->cancelled, 1); + return VOID_STATUS_OK; +} + +static void cabi_release_async(void_module_handle* h, void_operation_handle* op) +{ + if (op == NULL) { + return; + } + if (op->worker_started) { + thrd_join(op->worker, NULL); + op->worker_started = 0; + } + if (h != NULL) { + mtx_lock(&h->ops_mu); + for (size_t i = 0; i < h->ops_count; ++i) { + if (h->ops[i] == op) { + h->ops[i] = h->ops[h->ops_count - 1]; + --h->ops_count; + break; + } + } + mtx_unlock(&h->ops_mu); + } + free(op); +} + +static int32_t cabi_request_stop(void_module_handle* h) +{ + if (h == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + atomic_store(&h->quiescing, 1); + mtx_lock(&h->ops_mu); + for (size_t i = 0; i < h->ops_count; ++i) { + if (h->ops[i] != NULL) { + atomic_store(&h->ops[i]->cancelled, 1); + } + } + mtx_unlock(&h->ops_mu); + return VOID_STATUS_OK; +} + +static int32_t cabi_deactivate(void_module_handle* h) +{ + return cabi_request_stop(h); +} + +static void cabi_destroy(void_module_handle* h) +{ + if (h == NULL) { + return; + } + mtx_destroy(&h->ops_mu); + free(h); +} + +int32_t void_module_query_v1(uint32_t host_struct_size, + void_module_api_v1* out_api) +{ + if (out_api == NULL || host_struct_size < VOID_MODULE_API_V1_MIN_SIZE) { + return VOID_STATUS_INVALID_ARGUMENT; + } + memset(out_api, 0, sizeof(*out_api)); + out_api->struct_size = (uint32_t)sizeof(void_module_api_v1); + out_api->abi_major = VOID_CABI_MAJOR_V1; + out_api->abi_minor = VOID_CABI_MINOR_V1; + out_api->reserved = 0; + out_api->capabilities = VOID_CAP_STATELESS_RELOAD | + VOID_CAP_STATEFUL_CHECKPOINT | VOID_CAP_ASYNC_OPS | + VOID_CAP_SERVICE_INTERFACES; + out_api->get_info = cabi_get_info; + out_api->create = cabi_create; + out_api->activate = cabi_activate; + out_api->readiness = cabi_readiness; + out_api->quiesce = cabi_quiesce; + out_api->resume = cabi_resume; + out_api->checkpoint = cabi_checkpoint; + out_api->restore = cabi_restore; + out_api->query_interface = cabi_query_interface; + out_api->release_interface = cabi_release_interface; + out_api->submit_async = cabi_submit_async; + out_api->cancel_async = cabi_cancel_async; + out_api->release_async = cabi_release_async; + out_api->request_stop = cabi_request_stop; + out_api->deactivate = cabi_deactivate; + out_api->destroy = cabi_destroy; + return VOID_STATUS_OK; +} diff --git a/tests/plugins/CAbiPluginV2.c b/tests/plugins/CAbiPluginV2.c new file mode 100644 index 0000000..8c81cc0 --- /dev/null +++ b/tests/plugins/CAbiPluginV2.c @@ -0,0 +1,357 @@ +#include + +#include +#include +#include +#include + +typedef struct cabi_calc_v1 { + uint32_t (*version)(void_module_handle* h); + int32_t (*accumulate)(void_module_handle* h, int32_t delta); +} cabi_calc_v1; + +struct void_module_handle { + void_host_api_v1 host; + atomic_int total; + int ready; +}; + +static const void_interface_id_v1 kCalcIfaceId = { + {0x76, 0x6f, 0x69, 0x64, 0x63, 0x61, 0x6c, 0x63, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x01}}; + +static void free_c_str(void* ctx, const char* msg) +{ + (void)ctx; + free((void*)msg); +} + +static void free_c_bytes(void* ctx, const uint8_t* data, uint64_t size) +{ + (void)ctx; + (void)size; + free((void*)data); +} + +static void set_err(void_error_detail_v1* out_err, + int32_t status, + const char* text) +{ + if (out_err == NULL || out_err->struct_size < sizeof(void_error_detail_v1)) { + return; + } + out_err->status = status; + if (text != NULL) { + size_t n = strlen(text); + char* copy = (char*)malloc(n + 1); + if (copy != NULL) { + memcpy(copy, text, n + 1); + out_err->message = copy; + out_err->release = free_c_str; + out_err->release_ctx = NULL; + } + } +} + +static int cfg_has(void_bytes_v1 cfg, const char* needle) +{ + if (cfg.data == NULL || cfg.size == 0) { + return 0; + } + size_t nlen = strlen(needle); + if (cfg.size < nlen) { + return 0; + } + for (uint64_t i = 0; i + nlen <= cfg.size; ++i) { + if (memcmp(cfg.data + i, needle, nlen) == 0) { + return 1; + } + } + return 0; +} + +static int32_t cabi_v2_get_info(void_module_info_v1* out_info) +{ + if (out_info == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + memset(out_info, 0, sizeof(*out_info)); + out_info->struct_size = (uint32_t)sizeof(void_module_info_v1); + out_info->module_id = "cabi.calc"; + out_info->version = "2.0.0"; + out_info->activation_policy = VOID_POLICY_RELOADABLE; + out_info->state_schema_version = 2; + return VOID_STATUS_OK; +} + +static int32_t cabi_v2_create(const void_host_api_v1* host_api, + void_module_handle** out_handle) +{ + if (out_handle == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + *out_handle = NULL; + if (host_api == NULL || host_api->struct_size < sizeof(void_host_api_v1)) { + return VOID_STATUS_INVALID_ARGUMENT; + } + struct void_module_handle* h = + (struct void_module_handle*)calloc(1, sizeof(*h)); + if (h == NULL) { + return VOID_STATUS_EXHAUSTED; + } + h->host = *host_api; + atomic_init(&h->total, 0); + h->ready = 1; + *out_handle = h; + return VOID_STATUS_OK; +} + +static int32_t cabi_v2_activate(void_module_handle* h, + void_bytes_v1 config, + void_error_detail_v1* out_err) +{ + if (h == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + if (cfg_has(config, "fail_activate")) { + set_err(out_err, VOID_STATUS_INTERNAL, "V2 activation failed"); + return VOID_STATUS_INTERNAL; + } + h->ready = cfg_has(config, "not_ready") ? 0 : 1; + return VOID_STATUS_OK; +} + +static int32_t cabi_v2_readiness(void_module_handle* h, + uint32_t* out_ready, + void_error_detail_v1* out_err) +{ + if (h == NULL || out_ready == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + *out_ready = h->ready ? 1u : 0u; + if (!h->ready) { + set_err(out_err, VOID_STATUS_NOT_READY, "V2 not ready"); + } + return VOID_STATUS_OK; +} + +static int32_t cabi_v2_quiesce(void_module_handle* h, + const void_op_options_v1* opts, + void_error_detail_v1* out_err) +{ + (void)h; + (void)opts; + (void)out_err; + return VOID_STATUS_OK; +} + +static int32_t cabi_v2_resume(void_module_handle* h, + void_error_detail_v1* out_err) +{ + (void)h; + (void)out_err; + return VOID_STATUS_OK; +} + +static int32_t cabi_v2_checkpoint(void_module_handle* h, + const void_op_options_v1* opts, + void_owned_bytes_v1* out_state, + void_error_detail_v1* out_err) +{ + (void)opts; + (void)out_err; + if (h == NULL || out_state == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + char buf[64]; + int val = atomic_load(&h->total); + int len = 0; + if (val == 0) { + memcpy(buf, "v2:0", 4); + len = 4; + } else { + /* Decimal conversion without stdio overhead. */ + char rev[32]; + int rlen = 0; + int neg = val < 0; + unsigned u = neg ? (unsigned)(-val) : (unsigned)val; + while (u > 0) { + rev[rlen++] = (char)('0' + (u % 10u)); + u /= 10u; + } + buf[len++] = 'v'; + buf[len++] = '2'; + buf[len++] = ':'; + if (neg) { + buf[len++] = '-'; + } + while (rlen > 0) { + buf[len++] = rev[--rlen]; + } + } + uint8_t* copy = (uint8_t*)malloc((size_t)len); + if (copy == NULL) { + return VOID_STATUS_EXHAUSTED; + } + memcpy(copy, buf, (size_t)len); + out_state->data = copy; + out_state->size = (uint64_t)len; + out_state->release = free_c_bytes; + out_state->release_ctx = NULL; + return VOID_STATUS_OK; +} + +static int32_t cabi_v2_restore(void_module_handle* h, + void_bytes_v1 state, + void_error_detail_v1* out_err) +{ + if (h == NULL || state.data == NULL || state.size < 4) { + set_err(out_err, VOID_STATUS_STATE_REJECTED, "V2 invalid checkpoint"); + return VOID_STATUS_STATE_REJECTED; + } + if (memcmp(state.data, "v1:", 3) != 0 && + memcmp(state.data, "v2:", 3) != 0) { + set_err(out_err, VOID_STATUS_STATE_REJECTED, "V2 unknown checkpoint header"); + return VOID_STATUS_STATE_REJECTED; + } + char buf[64]; + size_t n = (size_t)(state.size - 3); + if (n >= sizeof(buf)) { + return VOID_STATUS_STATE_REJECTED; + } + memcpy(buf, state.data + 3, n); + buf[n] = '\0'; + int val = atoi(buf); + atomic_store(&h->total, val); + return VOID_STATUS_OK; +} + +static uint32_t iface_v2_version(void_module_handle* h) +{ + (void)h; + return 2u; +} + +static int32_t iface_v2_accumulate(void_module_handle* h, int32_t delta) +{ + if (h == NULL) { + return -1; + } + return atomic_fetch_add(&h->total, delta) + delta; +} + +static const cabi_calc_v1 kCalcV2 = {iface_v2_version, iface_v2_accumulate}; + +static int32_t cabi_v2_query_interface(void_module_handle* h, + const void_interface_id_v1* iface_id, + uint32_t min_major, + uint32_t min_table_size, + void_interface_view_v1* out_view) +{ + if (h == NULL || iface_id == NULL || out_view == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + if (memcmp(iface_id->bytes, kCalcIfaceId.bytes, 16) != 0) { + return VOID_STATUS_NOT_FOUND; + } + if (min_major != 1u || min_table_size > sizeof(cabi_calc_v1)) { + return VOID_STATUS_UNSUPPORTED; + } + out_view->struct_size = (uint32_t)sizeof(void_interface_view_v1); + out_view->major = 1u; + out_view->minor = 1u; + out_view->table_size = (uint32_t)sizeof(cabi_calc_v1); + out_view->function_table = &kCalcV2; + return VOID_STATUS_OK; +} + +static void cabi_v2_release_interface(void_module_handle* h, + const void_interface_id_v1* iface_id, + const void_interface_view_v1* view) +{ + (void)h; + (void)iface_id; + (void)view; +} + +static int32_t cabi_v2_submit_async(void_module_handle* h, + uint32_t op_kind, + void_bytes_v1 payload, + const void_op_options_v1* opts, + void_async_complete_fn cb, + void* cb_ctx, + void_operation_handle** out_op, + void_error_detail_v1* out_err) +{ + (void)h; + (void)op_kind; + (void)payload; + (void)opts; + (void)cb; + (void)cb_ctx; + (void)out_op; + (void)out_err; + return VOID_STATUS_UNSUPPORTED; +} + +static int32_t cabi_v2_cancel_async(void_module_handle* h, + void_operation_handle* op) +{ + (void)h; + (void)op; + return VOID_STATUS_UNSUPPORTED; +} + +static void cabi_v2_release_async(void_module_handle* h, + void_operation_handle* op) +{ + (void)h; + (void)op; +} + +static int32_t cabi_v2_request_stop(void_module_handle* h) +{ + (void)h; + return VOID_STATUS_OK; +} + +static int32_t cabi_v2_deactivate(void_module_handle* h) +{ + (void)h; + return VOID_STATUS_OK; +} + +static void cabi_v2_destroy(void_module_handle* h) { free(h); } + +int32_t void_module_query_v1(uint32_t host_struct_size, + void_module_api_v1* out_api) +{ + if (out_api == NULL || host_struct_size < VOID_MODULE_API_V1_MIN_SIZE) { + return VOID_STATUS_INVALID_ARGUMENT; + } + memset(out_api, 0, sizeof(*out_api)); + out_api->struct_size = (uint32_t)sizeof(void_module_api_v1); + out_api->abi_major = VOID_CABI_MAJOR_V1; + out_api->abi_minor = VOID_CABI_MINOR_V1; + out_api->reserved = 0; + out_api->capabilities = VOID_CAP_STATELESS_RELOAD | + VOID_CAP_STATEFUL_CHECKPOINT | + VOID_CAP_SERVICE_INTERFACES; + out_api->get_info = cabi_v2_get_info; + out_api->create = cabi_v2_create; + out_api->activate = cabi_v2_activate; + out_api->readiness = cabi_v2_readiness; + out_api->quiesce = cabi_v2_quiesce; + out_api->resume = cabi_v2_resume; + out_api->checkpoint = cabi_v2_checkpoint; + out_api->restore = cabi_v2_restore; + out_api->query_interface = cabi_v2_query_interface; + out_api->release_interface = cabi_v2_release_interface; + out_api->submit_async = cabi_v2_submit_async; + out_api->cancel_async = cabi_v2_cancel_async; + out_api->release_async = cabi_v2_release_async; + out_api->request_stop = cabi_v2_request_stop; + out_api->deactivate = cabi_v2_deactivate; + out_api->destroy = cabi_v2_destroy; + return VOID_STATUS_OK; +} diff --git a/tests/standalone/Plugin/PluginHardening.cpp b/tests/standalone/Plugin/PluginHardening.cpp new file mode 100644 index 0000000..17d3a99 --- /dev/null +++ b/tests/standalone/Plugin/PluginHardening.cpp @@ -0,0 +1,315 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using namespace Void::Plugin; + + struct CabiCalcTable { + uint32_t (*version)(void_module_handle* h); + int32_t (*accumulate)(void_module_handle* h, int32_t delta); + }; + + const void_interface_id_v1 kCalcIfaceId{ + {0x76, 0x6f, 0x69, 0x64, 0x63, 0x61, 0x6c, 0x63, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x01}}; + + std::vector encode_i32_le(std::int32_t v) + { + std::vector out(4); + std::memcpy(out.data(), &v, 4); + return out; + } + + std::int32_t decode_i32_le(const std::vector& b) + { + std::int32_t v = 0; + if (b.size() >= 4) { + std::memcpy(&v, b.data(), 4); + } + return v; + } +} // namespace + +#if defined(VOID_CABI_V1_PATH) && defined(VOID_CABI_V2_PATH) && \ + __has_include() + +Void::Testing::Test plugin_cabi_v1_to_v2_stateful_quiesce_and_reload() +{ + PluginHostLimits limits{}; + limits.allow_safe_dlclose = true; + CModuleHost host{limits}; + + auto id = host.load(VOID_CABI_V1_PATH); + Void::Testing::require(id.has_value()); + Void::Testing::expect_eq(*id, std::string{"cabi.calc"}); + + auto g1 = host.acquire("cabi.calc"); + Void::Testing::require(static_cast(g1)); + const auto gen1 = g1.generation(); + + auto iface1 = g1.query_interface(kCalcIfaceId, 1, sizeof(CabiCalcTable)); + Void::Testing::require(iface1.has_value()); + const auto* t1 = iface1->table(); + Void::Testing::require(t1 != nullptr); + Void::Testing::expect_eq(t1->version(nullptr), std::uint32_t{1}); + + // Run async op on V1 (kind=3 pins activity via host API, kind=2 sync). + auto op_sync = g1.run_async(2u, encode_i32_le(15)); + Void::Testing::require(op_sync.has_value()); + Void::Testing::expect_eq(decode_i32_le(*op_sync), 15); + + auto op_async = g1.run_async(3u, encode_i32_le(25)); + Void::Testing::require(op_async.has_value()); + Void::Testing::expect_eq(decode_i32_le(*op_async), 40); + + // Reload V1 -> V2 while g1 + iface1 are still pinned! + auto gen2_res = + host.replace("cabi.calc", VOID_CABI_V2_PATH, {}, gen1); + Void::Testing::require(gen2_res.has_value()); + Void::Testing::expect(*gen2_res > gen1); + + // Old generation stays mapped & live until both leases drop. + auto retained_mid = host.retained_generations("cabi.calc"); + Void::Testing::expect_eq(retained_mid.size(), std::size_t{2}); + + // Acquire V2 interface and confirm checkpoint migrated 40 -> V2. + auto g2 = host.acquire("cabi.calc"); + Void::Testing::require(static_cast(g2)); + auto iface2 = g2.query_interface(kCalcIfaceId, 1, sizeof(CabiCalcTable)); + Void::Testing::require(iface2.has_value()); + const auto* t2 = iface2->table(); + Void::Testing::expect_eq(t2->version(nullptr), std::uint32_t{2}); + + auto op2 = g2.run_async(1u, encode_i32_le(5)); + // V2 does not implement async ops -> UNSUPPORTED mapped to abi_mismatch. + Void::Testing::expect(!op2.has_value()); + + // Old iface1/g1 still pinned; V1 sees quiesced mutation return -1. + Void::Testing::expect_eq(t1->version(nullptr), std::uint32_t{1}); + + // Drop all pins to gen1 and verify host retirement thread dlcloses gen1. + iface1 = InterfaceLease{}; + g1 = GenerationLease{}; + for (int i = 0; i < 100; ++i) { + if (host.retained_generations("cabi.calc").size() == 1) { + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds{5}); + } + Void::Testing::expect_eq(host.retained_generations("cabi.calc").size(), + std::size_t{1}); +} + +Void::Testing::Test plugin_cabi_async_cancel_and_safe_dlclose_wait() +{ + PluginHostLimits limits{}; + limits.allow_safe_dlclose = true; + CModuleHost host{limits}; + + Void::Testing::require(host.load(VOID_CABI_V1_PATH).has_value()); + auto lease = host.acquire("cabi.calc"); + ActivityPin extra_pin = lease.acquire_activity_pin(); + + std::stop_source ss; + std::thread canceller([&] { + std::this_thread::sleep_for(std::chrono::milliseconds{2}); + ss.request_stop(); + }); + Void::Async::OperationOptions opts; + opts.stop = ss.get_token(); + auto res = lease.run_async(1u, encode_i32_le(1), opts); + canceller.join(); + Void::Testing::expect(!res.has_value()); + Void::Testing::expect_eq( + res.error().code().value, + static_cast(PluginErrorCode::cancelled)); + + // Unload while extra_pin + lease still exist -> cannot destroy/dlclose yet. + Void::Testing::require(host.unload("cabi.calc").has_value()); + lease = GenerationLease{}; + std::this_thread::sleep_for(std::chrono::milliseconds{10}); + extra_pin = ActivityPin{}; + host.close_and_join(); +} + +Void::Testing::Test plugin_cabi_bad_abi_oversized_ckpt_and_resume_degraded() +{ + CModuleHost host{PluginHostLimits{.allow_safe_dlclose = true}}; + + for (const char* bad_path : + {VOID_CABI_BAD_TRUNC_PATH, VOID_CABI_BAD_MAJOR_PATH, + VOID_CABI_BAD_RESERVED_PATH}) { + auto r = host.load(bad_path); + Void::Testing::expect(!r.has_value()); + Void::Testing::expect_eq( + r.error().code().value, + static_cast(PluginErrorCode::abi_mismatch)); + } + + // Prepublication V2 readiness failure resumes V1 cleanly. + Void::Testing::require(host.load(VOID_CABI_V1_PATH).has_value()); + auto fail_v2 = + host.replace("cabi.calc", VOID_CABI_V2_PATH, "not_ready"); + Void::Testing::expect(!fail_v2.has_value()); + auto after = host.acquire("cabi.calc"); + Void::Testing::expect(after.health() == GenerationHealth::Healthy); + Void::Testing::expect_eq(after.version(), std::string_view{"1.0.0"}); + + // Reload into V1 with quiesce_fail_resume_fail -> failed reload leaves old + // generation marked Degraded. + Void::Testing::require( + host.replace("cabi.calc", VOID_CABI_V1_PATH, + "quiesce_fail_resume_fail") + .has_value()); + auto deg_attempt = host.replace("cabi.calc", VOID_CABI_V2_PATH); + Void::Testing::expect(!deg_attempt.has_value()); + Void::Testing::expect_eq( + deg_attempt.error().code().value, + static_cast(PluginErrorCode::resume_degraded)); + Void::Testing::expect(host.acquire("cabi.calc").health() == + GenerationHealth::Degraded); + Void::Testing::require(host.unload("cabi.calc").has_value()); + + // Oversized checkpoint rejected without crashing or leaking. + Void::Testing::require( + host.load(VOID_CABI_V1_PATH, "ckpt_oversized").has_value()); + auto ov = host.replace("cabi.calc", VOID_CABI_V2_PATH); + Void::Testing::expect(!ov.has_value()); + Void::Testing::expect_eq( + ov.error().code().value, + static_cast(PluginErrorCode::budget_exceeded)); +} + +Void::Testing::Test plugin_cabi_retention_byte_budget_and_dep_batch() +{ + // 4-generation retention cap + byte budget. + PluginHostLimits limits{}; + limits.allow_safe_dlclose = true; + limits.max_retained_generations = 4; + CModuleHost host{limits}; + + Void::Testing::require(host.load(VOID_CABI_V1_PATH).has_value()); + std::vector pins; + for (int i = 0; i < 3; ++i) { + pins.push_back(host.acquire("cabi.calc")); + auto next = host.replace("cabi.calc", VOID_CABI_V1_PATH); + Void::Testing::require(next.has_value()); + } + pins.push_back(host.acquire("cabi.calc")); + // Now 4 distinct generations are pinned -> 5th replace fails retention_limit. + auto cap_fail = host.replace("cabi.calc", VOID_CABI_V2_PATH); + Void::Testing::expect(!cap_fail.has_value()); + Void::Testing::expect_eq( + cap_fail.error().code().value, + static_cast(PluginErrorCode::retention_limit)); + Void::Testing::expect(host.mapped_bytes("cabi.calc") > 0); + pins.clear(); + + // Byte budget rejection. + PluginHostLimits tiny_mem{}; + tiny_mem.max_mapped_bytes_per_module = 1024; + CModuleHost tight{tiny_mem}; + auto too_big = tight.load(VOID_CABI_V1_PATH); + Void::Testing::expect(!too_big.has_value()); + Void::Testing::expect_eq( + too_big.error().code().value, + static_cast(PluginErrorCode::budget_exceeded)); + + // Dependency batch: B depends on A (supplied out of order) -> A sorted first. + CModuleHost batch_host; + auto batch_ok = batch_host.load_batch( + {{.path = VOID_CABI_DEP_B_PATH}, {.path = VOID_CABI_DEP_A_PATH}}); + Void::Testing::require(batch_ok.has_value()); + Void::Testing::expect_eq(batch_ok->size(), std::size_t{2}); + Void::Testing::expect_eq((*batch_ok)[0], std::string{"cabi.dep.a"}); + Void::Testing::expect_eq((*batch_ok)[1], std::string{"cabi.dep.b"}); + + // RestartRequired policy refuses live upgrade. + auto rr = batch_host.replace("cabi.dep.a", VOID_CABI_DEP_A_PATH); + Void::Testing::expect(!rr.has_value()); + Void::Testing::expect_eq( + rr.error().code().value, + static_cast(PluginErrorCode::restart_required)); + + // Cycle in batch rejected before activating anything. + CModuleHost cyc_host; + auto cyc_res = cyc_host.load_batch( + {{.path = VOID_CABI_CYC_A_PATH}, {.path = VOID_CABI_CYC_B_PATH}}); + Void::Testing::expect(!cyc_res.has_value()); + Void::Testing::expect_eq( + cyc_res.error().code().value, + static_cast(PluginErrorCode::cycle_detected)); +} + +Void::Testing::Test plugin_cpp_adapter_contains_exceptions_and_manager_unlocks() +{ + struct ThrowingModule final : Void::Plugin::IModule { + std::string_view name() const noexcept override { return "throw"; } + Void::Result::Result activate(Void::Plugin::ModuleHost&) override + { + throw std::runtime_error("boom"); + } + Void::Json::Value checkpoint() const override + { + throw std::runtime_error("ckpt-boom"); + } + }; + Void::Plugin::CModuleAdapterBox box{.module = std::make_unique()}; + void_error_detail_v1 err{}; + err.struct_size = sizeof(err); + Void::Testing::expect_eq(Void::Plugin::adapt_activate(&box, &err), + static_cast(VOID_STATUS_INTERNAL)); + if (err.release != nullptr && err.message != nullptr) { + Void::Testing::expect_eq(std::string_view{err.message}, + std::string_view{"boom"}); + err.release(err.release_ctx, err.message); + } + void_owned_bytes_v1 ck{}; + void_error_detail_v1 err2{}; + err2.struct_size = sizeof(err2); + Void::Testing::expect_eq(Void::Plugin::adapt_checkpoint(&box, &ck, &err2), + static_cast(VOID_STATUS_INTERNAL)); + if (err2.release != nullptr && err2.message != nullptr) { + err2.release(err2.release_ctx, err2.message); + } + + // Reentrant candidate/instance validator in PluginManager must NOT deadlock + // on m_mutex. +#if defined(VOID_STATEFUL_V1_PATH) && defined(VOID_STATEFUL_V2_PATH) + PluginManager* mgr_ptr = nullptr; + PluginManager mgr{{ + .instance_validator = [&](IPlugin&, const PluginInfo&) { + auto current = mgr_ptr->acquire("StatefulPlugin"); + auto all_names = mgr_ptr->names(); + return all_names.empty() || static_cast(current); + }, + .candidate_validator = [&](const PluginHandle&) { + auto current = mgr_ptr->acquire("StatefulPlugin"); + return static_cast(current) || mgr_ptr->names().empty(); + }, + }}; + mgr_ptr = &mgr; + Void::Testing::require(mgr.load(VOID_STATEFUL_V1_PATH).has_value()); + Void::Testing::require( + mgr.replace("StatefulPlugin", VOID_STATEFUL_V2_PATH).has_value()); +#endif +} + +#endif // C ABI fixtures available From 1dc51d5c434a00459b1950d8dfee7ffb7b0128af Mon Sep 17 00:00:00 2001 From: faumaray Date: Thu, 26 Nov 2026 16:30:30 +0300 Subject: [PATCH 4/9] feat(configuration): bounded schemas, provenance/redaction, and async transactional ReloadController --- include/Void/Configuration/Bind.hpp | 15 + .../Void/Configuration/ReloadController.hpp | 784 +++++++++++++ include/Void/Configuration/Schema.hpp | 1030 +++++++++++++++++ src/Configuration/Schema.cpp | 766 ++++++++++++ src/Configuration/module.cmake | 1 + src/ConfigurationAsync/ReloadController.cpp | 72 ++ src/ConfigurationAsync/module.cmake | 4 + .../ConfigurationAsyncOnly/CMakeLists.txt | 11 + tests/package/ConfigurationAsyncOnly/main.cpp | 20 + .../package/ConfigurationOnly/CMakeLists.txt | 11 + tests/package/ConfigurationOnly/main.cpp | 21 + tests/package/InstalledComponents.cmake | 20 + .../Configuration/ConfigurationHardening.cpp | 256 ++++ .../ConfigurationAsync/ConfigurationAsync.cpp | 340 ++++++ 14 files changed, 3351 insertions(+) create mode 100644 include/Void/Configuration/ReloadController.hpp create mode 100644 include/Void/Configuration/Schema.hpp create mode 100644 src/Configuration/Schema.cpp create mode 100644 src/ConfigurationAsync/ReloadController.cpp create mode 100644 src/ConfigurationAsync/module.cmake create mode 100644 tests/package/ConfigurationAsyncOnly/CMakeLists.txt create mode 100644 tests/package/ConfigurationAsyncOnly/main.cpp create mode 100644 tests/package/ConfigurationOnly/CMakeLists.txt create mode 100644 tests/package/ConfigurationOnly/main.cpp create mode 100644 tests/standalone/Configuration/ConfigurationHardening.cpp create mode 100644 tests/standalone/ConfigurationAsync/ConfigurationAsync.cpp diff --git a/include/Void/Configuration/Bind.hpp b/include/Void/Configuration/Bind.hpp index fcff8c6..2f7c568 100644 --- a/include/Void/Configuration/Bind.hpp +++ b/include/Void/Configuration/Bind.hpp @@ -51,6 +51,21 @@ namespace Void::Configuration }; struct Required { }; + struct Secret { + }; + struct RestartRequired { + }; + struct Deprecated { + Void::Meta::Str message; + }; + struct IntRange { + std::int64_t min{0}; + std::int64_t max{0}; + }; + struct RealRange { + double min{0.0}; + double max{0.0}; + }; #ifdef VOID_HAS_CONFIG_REFLECTION diff --git a/include/Void/Configuration/ReloadController.hpp b/include/Void/Configuration/ReloadController.hpp new file mode 100644 index 0000000..3953ce0 --- /dev/null +++ b/include/Void/Configuration/ReloadController.hpp @@ -0,0 +1,784 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Configuration +{ + struct PreparedChange { + std::shared_ptr view{}; + std::size_t declared_budget_bytes{0}; + std::function>()> + dispose_async{}; + }; + + template struct Snapshot { + std::uint64_t generation{0}; + std::shared_ptr values{}; + std::shared_ptr provenance{}; + std::shared_ptr raw{}; + std::shared_ptr< + const std::unordered_map>> + resources{}; + std::shared_ptr retention_token{}; + + template + [[nodiscard]] std::shared_ptr + resource(std::string_view participant_id) const + { + if (!resources) { + return nullptr; + } + const auto it = resources->find(std::string{participant_id}); + if (it == resources->end()) { + return nullptr; + } + return std::static_pointer_cast(it->second); + } + + [[nodiscard]] explicit operator bool() const noexcept + { + return values != nullptr; + } + }; + + template struct PreparedAggregate { + std::shared_ptr values{}; + std::shared_ptr provenance{}; + std::shared_ptr raw{}; + std::shared_ptr< + const std::unordered_map>> + resources{}; + std::vector staged_changes{}; + std::vector changed_keys{}; + std::vector warnings{}; + + Void::Coro::Task> dispose_all() + { + for (auto it = staged_changes.rbegin(); + it != staged_changes.rend(); ++it) { + if (it->dispose_async) { + (void)co_await it->dispose_async(); + } + } + staged_changes.clear(); + co_return Void::Result::Result{}; + } + }; + + struct ReloadReport { + std::uint64_t generation{0}; + bool committed{false}; + bool restart_required{false}; + std::vector restart_required_keys{}; + bool stop_observed_after_commit{false}; + std::vector changed_keys{}; + std::vector notification_errors{}; + std::vector warnings{}; + std::size_t coalesced_events{0}; + }; + + namespace detail + { + class AsyncReloadGate + { + public: + + struct Waiter { + Void::Async::Executor* exec{nullptr}; + std::coroutine_handle<> h{}; + }; + + struct Guard { + AsyncReloadGate* gate{nullptr}; + Guard() noexcept = default; + explicit Guard(AsyncReloadGate* g) noexcept : gate(g) {} + Guard(Guard&& o) noexcept + : gate(std::exchange(o.gate, nullptr)) + { + } + Guard& operator=(Guard&& o) noexcept + { + if (this != &o) { + if (gate != nullptr) gate->release(); + gate = std::exchange(o.gate, nullptr); + } + return *this; + } + ~Guard() + { + if (gate != nullptr) { + gate->release(); + } + } + Guard(const Guard&) = delete; + Guard& operator=(const Guard&) = delete; + }; + + struct Awaiter { + AsyncReloadGate* gate; + Void::Async::Executor* exec; + bool await_ready() noexcept { return gate->try_lock(); } + bool await_suspend(std::coroutine_handle<> h) noexcept + { + return gate->enqueue_or_acquire(exec, h); + } + Guard await_resume() noexcept { return Guard{gate}; } + }; + + Awaiter lock(Void::Async::Executor* exec) noexcept + { + return Awaiter{this, exec}; + } + + bool try_lock() noexcept; + bool enqueue_or_acquire(Void::Async::Executor* exec, + std::coroutine_handle<> h) noexcept; + void release() noexcept; + + private: + + std::mutex mu_{}; + bool locked_{false}; + std::deque waiters_{}; + }; + + [[nodiscard]] std::vector + diff_merged_keys(const MergedConfig& old_cfg, + const MergedConfig& new_cfg); + } // namespace detail + + struct ControllerOptions { + const Void::Time::MonotonicClock* clock{ + &Void::Time::SystemMonotonicClock::instance()}; + Void::Async::Executor* executor{nullptr}; + }; + + template + class ReloadController + : public std::enable_shared_from_this> + { + public: + + using PrepareFn = std::function< + Void::Coro::Task>( + const Snapshot& old_snapshot, + const std::shared_ptr& candidate, + Void::Async::OperationOptions options)>; + + using CommitListener = + std::function& snapshot, + const ReloadReport& report)>; + + [[nodiscard]] static Void::Result::Result< + std::shared_ptr>> + create(Schema schema, SourceSet initial_sources, + ControllerOptions options = {}) + { + auto merged = load_sources(initial_sources, schema.limits(), + schema.secret_keys()); + if (!merged) { + return Void::Result::fail(std::move(merged).error()); + } + auto validated = validate(*merged, schema); + if (!validated) { + return Void::Result::fail(std::move(validated).error()); + } + + auto ctrl = std::shared_ptr>( + new ReloadController(std::move(schema), options)); + auto merged_ptr = + std::make_shared(std::move(*merged)); + auto val_ptr = + std::make_shared(std::move(validated->value)); + auto res_ptr = std::make_shared>>(); + auto tok = std::make_shared(1); + ctrl->m_retention_tokens.push_back(tok); + ctrl->m_current = Snapshot{ + .generation = 1, + .values = std::move(val_ptr), + .provenance = merged_ptr->provenance, + .raw = std::move(merged_ptr), + .resources = std::move(res_ptr), + .retention_token = std::move(tok), + }; + ctrl->m_generation = 1; + return ctrl; + } + + ~ReloadController() { close_and_join(); } + + ReloadController(const ReloadController&) = delete; + ReloadController& operator=(const ReloadController&) = delete; + + [[nodiscard]] Snapshot current() const + { + std::lock_guard lk{m_pub_mu}; + return m_current; + } + + [[nodiscard]] std::size_t retained_generation_count() const + { + std::lock_guard lk{m_pub_mu}; + std::size_t live = 0; + for (const auto& w : m_retention_tokens) { + if (!w.expired()) ++live; + } + return live; + } + + Void::Result::Result + register_participant(std::string id, + std::size_t declared_budget_bytes, + PrepareFn prepare_fn) + { + if (id.empty() || !prepare_fn) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::invalid_argument, + "ReloadController: participant id and callback required")); + } + std::lock_guard lk{m_part_mu}; + if (m_closing) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::prepare_failed, + "ReloadController: controller closing")); + } + if (m_participants.size() >= m_schema.limits().max_participants) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "ReloadController: max_participants exceeded")); + } + for (const auto& p : m_participants) { + if (p.id == id && !p.removing) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::key_collision, + "ReloadController: duplicate participant id '" + + id + "'")); + } + } + m_participants.push_back(ParticipantEntry{ + .id = std::move(id), + .budget_bytes = declared_budget_bytes, + .prepare = std::move(prepare_fn), + .in_flight = 0, + .removing = false, + }); + return {}; + } + + void unregister_participant(std::string_view id) + { + std::unique_lock lk{m_part_mu}; + for (auto& p : m_participants) { + if (p.id == id) { + p.removing = true; + break; + } + } + m_part_cv.wait(lk, [&] { + for (const auto& p : m_participants) { + if (p.id == id && p.in_flight > 0) return false; + } + return true; + }); + std::erase_if(m_participants, [&](const ParticipantEntry& p) { + return p.id == id; + }); + } + + std::size_t on_committed(CommitListener listener) + { + std::lock_guard lk{m_listener_mu}; + const std::size_t id = m_next_listener_id++; + m_listeners.emplace_back(id, std::move(listener)); + return id; + } + + void remove_listener(std::size_t id) + { + std::lock_guard lk{m_listener_mu}; + std::erase_if(m_listeners, [id](const auto& pair) { + return pair.first == id; + }); + } + + /// Prepare-only port exporting a staged candidate aggregate for a + /// higher-level platform coordinator without swapping m_current. + [[nodiscard]] Void::Coro::Task< + Void::Result::Result>> + prepare_external(SourceSet sources, + Void::Async::OperationOptions opts = {}) + { + auto gate_guard = co_await m_gate.lock(m_executor); + if (opts.stop.stop_requested()) { + co_return Void::Result::fail(make_config_error( + ConfigErrorCode::cancelled, + "ReloadController::prepare_external: cancelled")); + } + auto snap = current(); + co_return co_await prepare_candidate( + std::move(sources), snap, opts, nullptr); + } + + [[nodiscard]] Void::Coro::Task> + reload(SourceSet sources, Void::Async::OperationOptions opts = {}) + { + if (opts.stop.stop_requested()) { + co_return Void::Result::fail(make_config_error( + ConfigErrorCode::cancelled, + "ReloadController::reload: cancelled before admission")); + } + + auto gate_guard = co_await m_gate.lock(m_executor); + if (opts.stop.stop_requested()) { + co_return Void::Result::fail(make_config_error( + ConfigErrorCode::cancelled, + "ReloadController::reload: cancelled while queued")); + } + + Snapshot old_snap; + std::uint64_t expected_gen = 0; + { + std::lock_guard lk{m_pub_mu}; + std::erase_if(m_retention_tokens, [](const auto& w) { + return w.expired(); + }); + if (m_schema.limits().max_retained_generations > 0 && + m_retention_tokens.size() >= + m_schema.limits().max_retained_generations) { + co_return Void::Result::fail(make_config_error( + ConfigErrorCode::retention_limit, + "ReloadController::reload: max_retained_generations reached")); + } + old_snap = m_current; + expected_gen = m_generation; + } + + std::vector restart_keys; + auto cand_res = co_await prepare_candidate( + std::move(sources), old_snap, opts, &restart_keys); + if (!restart_keys.empty()) { + ReloadReport rep; + rep.generation = expected_gen; + rep.committed = false; + rep.restart_required = true; + rep.restart_required_keys = std::move(restart_keys); + co_return rep; + } + if (!cand_res) { + co_return Void::Result::fail(std::move(cand_res).error()); + } + auto agg = std::move(*cand_res); + + // Check pre-commit stop/deadline before swapping m_current. + if (opts.stop.stop_requested()) { + (void)co_await agg.dispose_all(); + co_return Void::Result::fail(make_config_error( + ConfigErrorCode::cancelled, + "ReloadController::reload: cancelled before commit")); + } + if (opts.deadline.has_value() && + m_clock->now() >= *opts.deadline) { + (void)co_await agg.dispose_all(); + co_return Void::Result::fail(make_config_error( + ConfigErrorCode::timeout, + "ReloadController::reload: deadline expired before commit")); + } + + // Short pointer swap — commit point (zero user callbacks or + // allocations under m_pub_mu). + auto tok = std::make_shared(1); + Snapshot new_snap{ + .generation = expected_gen + 1, + .values = std::move(agg.values), + .provenance = std::move(agg.provenance), + .raw = std::move(agg.raw), + .resources = std::move(agg.resources), + .retention_token = tok, + }; + Snapshot retired_old; + { + std::lock_guard lk{m_pub_mu}; + if (m_generation != expected_gen || m_closing) { + // Should be impossible under m_gate, fail-safe rollback. + retired_old = Snapshot{}; + } else { + m_generation = new_snap.generation; + m_retention_tokens.push_back(tok); + retired_old = std::exchange(m_current, new_snap); + } + } + if (!retired_old) { + (void)co_await agg.dispose_all(); + co_return Void::Result::fail(make_config_error( + ConfigErrorCode::internal, + "ReloadController::reload: generation swap conflict")); + } + + // Release old snapshot outside lock. + retired_old = Snapshot{}; + + ReloadReport rep; + rep.generation = new_snap.generation; + rep.committed = true; + rep.changed_keys = std::move(agg.changed_keys); + rep.warnings = std::move(agg.warnings); + rep.stop_observed_after_commit = opts.stop.stop_requested(); + rep.coalesced_events = + m_coalesced_events.exchange(0, std::memory_order_acq_rel); + + // Notify observers strictly outside locks; capture exceptions + // without claiming rollback. + std::vector copy; + { + std::lock_guard lk{m_listener_mu}; + copy.reserve(m_listeners.size()); + for (const auto& [_, fn] : m_listeners) { + if (fn) copy.push_back(fn); + } + } + const std::size_t notify_cap = + std::min(copy.size(), m_schema.limits().max_notifications); + for (std::size_t i = 0; i < notify_cap; ++i) { + try { + copy[i](new_snap, rep); + } catch (const std::exception& ex) { + rep.notification_errors.push_back(make_config_error( + ConfigErrorCode::internal, ex.what())); + } catch (...) { + rep.notification_errors.push_back(make_config_error( + ConfigErrorCode::internal, + "ReloadController: notification callback threw")); + } + } + co_return rep; + } + + [[nodiscard]] Void::Result::Result attach_watcher( + Void::SystemAsync::WatcherService& watcher, + std::vector paths, + std::function build_sources, + Void::Async::Executor& exec) + { + std::lock_guard lk{m_watch_mu}; + if (m_closing) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::internal, + "ReloadController::attach_watcher: controller closing")); + } + std::weak_ptr> weak_self = + this->weak_from_this(); + auto on_change = [weak_self, build = std::move(build_sources), + &exec](const Void::SystemAsync::WatchEvent&) { + auto self = weak_self.lock(); + if (!self) return; + if (self->m_watcher_busy.exchange( + true, std::memory_order_acq_rel)) { + self->m_coalesced_events.fetch_add( + 1, std::memory_order_relaxed); + self->m_watcher_dirty.store(true, + std::memory_order_release); + return; + } + self->schedule_watch_reload(build, exec); + }; + + std::vector subs; + for (const auto& p : paths) { + auto sr = watcher.watch(p, on_change); + if (!sr) { + for (auto& s : subs) (void)s.close_and_join(); + return Void::Result::fail(std::move(sr).error()); + } + subs.push_back(std::move(*sr)); + } + for (auto& s : subs) { + m_watch_subs.push_back(std::move(s)); + } + return {}; + } + + void close_and_join() + { + { + std::lock_guard lk{m_part_mu}; + m_closing = true; + } + { + std::lock_guard lk{m_pub_mu}; + m_closing = true; + } + std::vector subs; + { + std::lock_guard lk{m_watch_mu}; + subs.swap(m_watch_subs); + } + for (auto& s : subs) { + (void)s.close_and_join(); + } + std::unique_lock lk{m_part_mu}; + m_part_cv.wait(lk, [&] { + for (const auto& p : m_participants) { + if (p.in_flight > 0) return false; + } + return true; + }); + } + + private: + + struct ParticipantEntry { + std::string id{}; + std::size_t budget_bytes{0}; + PrepareFn prepare{}; + std::size_t in_flight{0}; + bool removing{false}; + }; + + ReloadController(Schema schema, ControllerOptions opts) + : m_schema(std::move(schema)), + m_clock(opts.clock ? opts.clock + : &Void::Time::SystemMonotonicClock::instance()), + m_executor(opts.executor) + { + } + + static Void::Coro::Task run_watch_reload_task( + std::weak_ptr> weak_self, + std::function build, + Void::Async::Executor* exec) + { + for (;;) { + auto self = weak_self.lock(); + if (!self) co_return; + self->m_watcher_dirty.store(false, + std::memory_order_release); + auto res = co_await self->reload(build()); + (void)res; + if (!self->m_watcher_dirty.load( + std::memory_order_acquire)) { + self->m_watcher_busy.store(false, + std::memory_order_release); + if (!self->m_watcher_dirty.load( + std::memory_order_acquire)) { + co_return; + } + if (self->m_watcher_busy.exchange( + true, std::memory_order_acq_rel)) { + co_return; + } + } + } + (void)exec; + } + + void schedule_watch_reload(const std::function& build, + Void::Async::Executor& exec) + { + Void::Async::spawn( + exec, run_watch_reload_task(this->weak_from_this(), build, + &exec)); + } + + Void::Coro::Task>> + prepare_candidate(SourceSet sources, + const Snapshot& old_snap, + Void::Async::OperationOptions opts, + std::vector* restart_out) + { + auto merged = load_sources(sources, m_schema.limits(), + m_schema.secret_keys()); + if (!merged) { + co_return Void::Result::fail(std::move(merged).error()); + } + auto validated = validate(*merged, m_schema); + if (!validated) { + co_return Void::Result::fail(std::move(validated).error()); + } + if (restart_out != nullptr && old_snap.raw) { + auto rr = detect_restart_required_changes( + *old_snap.raw, *merged, m_schema); + if (!rr.empty()) { + *restart_out = std::move(rr); + co_return Void::Result::fail(make_config_error( + ConfigErrorCode::restart_required, + "ReloadController: restart-required keys changed")); + } + } + + auto merged_ptr = + std::make_shared(std::move(*merged)); + auto cand_ptr = + std::make_shared(std::move(validated->value)); + auto res_map = std::make_shared< + std::unordered_map>>(); + std::vector prepared_list; + + const auto prep_deadline = + m_clock->now() + m_schema.limits().default_prepare_timeout; + Void::Async::OperationOptions p_opts = opts; + if (!p_opts.deadline.has_value() || + prep_deadline < *p_opts.deadline) { + p_opts.deadline = prep_deadline; + } + + // Snapshot participants safely. + struct ActivePart { + std::string id; + std::size_t budget_bytes; + PrepareFn prepare; + }; + std::vector parts; + { + std::lock_guard lk{m_part_mu}; + for (auto& p : m_participants) { + if (!p.removing && p.prepare) { + ++p.in_flight; + parts.push_back( + ActivePart{p.id, p.budget_bytes, p.prepare}); + } + } + } + auto release_inflight = [&]() { + std::lock_guard lk{m_part_mu}; + for (auto& ap : parts) { + for (auto& p : m_participants) { + if (p.id == ap.id && p.in_flight > 0) { + --p.in_flight; + } + } + } + m_part_cv.notify_all(); + }; + + std::optional prep_err; + std::size_t total_budget = 0; + + for (auto& ap : parts) { + if (p_opts.stop.stop_requested()) { + prep_err = make_config_error( + ConfigErrorCode::cancelled, + "ReloadController: cancelled during participant prepare"); + break; + } + if (p_opts.deadline.has_value() && + m_clock->now() >= *p_opts.deadline) { + prep_err = make_config_error( + ConfigErrorCode::timeout, + "ReloadController: participant prepare timed out"); + break; + } + try { + auto pr = + co_await ap.prepare(old_snap, cand_ptr, p_opts); + if (!pr) { + prep_err = std::move(pr).error(); + break; + } + const std::size_t item_budget = std::max( + ap.budget_bytes, pr->declared_budget_bytes); + if (total_budget + item_budget > + m_schema.limits().max_merged_bytes) { + if (pr->dispose_async) { + (void)co_await pr->dispose_async(); + } + prep_err = make_config_error( + ConfigErrorCode::limit_exceeded, + "ReloadController: participant budget exceeded"); + break; + } + total_budget += item_budget; + if (pr->view) { + res_map->insert_or_assign(ap.id, pr->view); + } + prepared_list.push_back(std::move(*pr)); + } catch (const std::exception& ex) { + prep_err = make_config_error( + ConfigErrorCode::prepare_failed, ex.what()); + break; + } catch (...) { + prep_err = make_config_error( + ConfigErrorCode::prepare_failed, + "ReloadController: participant prepare threw"); + break; + } + } + + release_inflight(); + + if (prep_err.has_value()) { + for (auto it = prepared_list.rbegin(); + it != prepared_list.rend(); ++it) { + if (it->dispose_async) { + (void)co_await it->dispose_async(); + } + } + co_return Void::Result::fail(std::move(*prep_err)); + } + + PreparedAggregate agg; + agg.values = std::move(cand_ptr); + agg.provenance = merged_ptr->provenance; + if (old_snap.raw) { + agg.changed_keys = + detail::diff_merged_keys(*old_snap.raw, *merged_ptr); + } + agg.raw = std::move(merged_ptr); + agg.resources = std::move(res_map); + agg.staged_changes = std::move(prepared_list); + agg.warnings = std::move(validated->warnings); + co_return agg; + } + + Schema m_schema; + const Void::Time::MonotonicClock* m_clock; + Void::Async::Executor* m_executor{nullptr}; + + detail::AsyncReloadGate m_gate{}; + mutable std::mutex m_pub_mu{}; + Snapshot m_current{}; + std::uint64_t m_generation{0}; + std::vector> m_retention_tokens{}; + bool m_closing{false}; + + std::mutex m_part_mu{}; + std::condition_variable m_part_cv{}; + std::vector m_participants{}; + + std::mutex m_listener_mu{}; + std::vector> m_listeners{}; + std::size_t m_next_listener_id{1}; + + std::mutex m_watch_mu{}; + std::vector m_watch_subs{}; + std::atomic m_watcher_busy{false}; + std::atomic m_watcher_dirty{false}; + std::atomic m_coalesced_events{0}; + }; + +} // namespace Void::Configuration diff --git a/include/Void/Configuration/Schema.hpp b/include/Void/Configuration/Schema.hpp new file mode 100644 index 0000000..553a7ea --- /dev/null +++ b/include/Void/Configuration/Schema.hpp @@ -0,0 +1,1030 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Configuration +{ + enum class ConfigErrorCode : std::int32_t { + none = 0, + invalid_argument = 1, + io_error = 2, + parse_error = 3, + limit_exceeded = 4, + key_collision = 5, + unknown_key = 6, + missing_required = 7, + type_mismatch = 8, + range_error = 9, + constraint_failed = 10, + vector_gap = 11, + restart_required = 12, + prepare_failed = 13, + cancelled = 14, + timeout = 15, + retention_limit = 16, + not_ready = 17, + internal = 18, + }; + + [[nodiscard]] inline Void::Result::Error + make_config_error(ConfigErrorCode code, std::string message = {}) + { + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case ConfigErrorCode::none: + kind = ErrorKind::internal; + break; + case ConfigErrorCode::invalid_argument: + case ConfigErrorCode::unknown_key: + case ConfigErrorCode::missing_required: + case ConfigErrorCode::type_mismatch: + case ConfigErrorCode::range_error: + case ConfigErrorCode::constraint_failed: + case ConfigErrorCode::vector_gap: + kind = ErrorKind::invalid_argument; + break; + case ConfigErrorCode::io_error: + kind = ErrorKind::io; + break; + case ConfigErrorCode::parse_error: + kind = ErrorKind::corrupt; + break; + case ConfigErrorCode::key_collision: + case ConfigErrorCode::restart_required: + kind = ErrorKind::conflict; + break; + case ConfigErrorCode::cancelled: + kind = ErrorKind::cancelled; + break; + case ConfigErrorCode::timeout: + kind = ErrorKind::timeout; + break; + case ConfigErrorCode::limit_exceeded: + case ConfigErrorCode::retention_limit: + kind = ErrorKind::exhausted; + break; + case ConfigErrorCode::prepare_failed: + case ConfigErrorCode::not_ready: + case ConfigErrorCode::internal: + kind = ErrorKind::internal; + break; + } + return Error{kind, std::move(message), + ErrorCode{Void::Result::kConfigurationErrorDomain, + static_cast(code)}}; + } + + struct ConfigLimits { + std::size_t max_source_bytes{1 * 1024 * 1024}; + std::size_t max_sources{8}; + std::size_t max_merged_bytes{4 * 1024 * 1024}; + std::size_t max_keys{10'000}; + std::size_t max_key_bytes{4 * 1024}; + std::size_t max_scalar_bytes{64 * 1024}; + std::size_t max_nesting_depth{32}; + std::size_t max_vector_items{1024}; + std::size_t max_diagnostics{100}; + std::size_t max_participants{64}; + std::size_t max_retained_generations{4}; + std::size_t max_notifications{128}; + std::chrono::milliseconds default_prepare_timeout{ + std::chrono::seconds{5}}; + }; + + enum class SourceKind : std::uint8_t { + Defaults = 0, + FileKeyValue = 1, + FileIni = 2, + FileJson = 3, + Environment = 4, + CliArgs = 5, + }; + + using SourceId = std::string; + + struct SourceLocation { + SourceId source{}; + std::string key{}; + std::uint32_t line{0}; + }; + + enum class ValueState : std::uint8_t { + Missing = 0, + Empty = 1, + Null = 2, + Present = 3, + Removed = 4, + }; + + struct SourceOrigin { + SourceId source{}; + SourceKind kind{SourceKind::Defaults}; + std::uint32_t line{0}; + ValueState state{ValueState::Present}; + }; + + struct KeyProvenance { + std::string key{}; + SourceOrigin winner{}; + std::vector shadowed{}; + bool redacted{false}; + }; + + struct Provenance { + std::unordered_map entries{}; + + [[nodiscard]] const KeyProvenance* + find(std::string_view key) const noexcept + { + const auto it = entries.find(std::string{key}); + return it == entries.end() ? nullptr : &it->second; + } + }; + + struct SourceSpec { + SourceId id{}; + SourceKind kind{SourceKind::Defaults}; + std::filesystem::path file_path{}; + std::string inline_text{}; + std::vector env_keys{}; + std::string env_prefix{}; + std::vector> entries{}; + std::vector cli_args{}; + std::vector removals{}; + bool is_inline{false}; + }; + + class SourceSet + { + public: + + SourceSet& add_defaults_map( + SourceId id, + std::vector> kv) + { + SourceSpec spec; + spec.id = std::move(id); + spec.kind = SourceKind::Defaults; + spec.entries = std::move(kv); + m_specs.push_back(std::move(spec)); + return *this; + } + + SourceSet& add_json_file(SourceId id, std::filesystem::path path) + { + SourceSpec spec; + spec.id = std::move(id); + spec.kind = SourceKind::FileJson; + spec.file_path = std::move(path); + m_specs.push_back(std::move(spec)); + return *this; + } + + SourceSet& add_json_text(SourceId id, std::string text) + { + SourceSpec spec; + spec.id = std::move(id); + spec.kind = SourceKind::FileJson; + spec.inline_text = std::move(text); + spec.is_inline = true; + m_specs.push_back(std::move(spec)); + return *this; + } + + SourceSet& add_ini_file(SourceId id, std::filesystem::path path) + { + SourceSpec spec; + spec.id = std::move(id); + spec.kind = SourceKind::FileIni; + spec.file_path = std::move(path); + m_specs.push_back(std::move(spec)); + return *this; + } + + SourceSet& add_ini_text(SourceId id, std::string text) + { + SourceSpec spec; + spec.id = std::move(id); + spec.kind = SourceKind::FileIni; + spec.inline_text = std::move(text); + spec.is_inline = true; + m_specs.push_back(std::move(spec)); + return *this; + } + + SourceSet& add_kv_file(SourceId id, std::filesystem::path path) + { + SourceSpec spec; + spec.id = std::move(id); + spec.kind = SourceKind::FileKeyValue; + spec.file_path = std::move(path); + m_specs.push_back(std::move(spec)); + return *this; + } + + SourceSet& add_kv_text(SourceId id, std::string text) + { + SourceSpec spec; + spec.id = std::move(id); + spec.kind = SourceKind::FileKeyValue; + spec.inline_text = std::move(text); + spec.is_inline = true; + m_specs.push_back(std::move(spec)); + return *this; + } + + SourceSet& add_env_allowlist(SourceId id, + std::vector keys) + { + SourceSpec spec; + spec.id = std::move(id); + spec.kind = SourceKind::Environment; + spec.env_keys = std::move(keys); + m_specs.push_back(std::move(spec)); + return *this; + } + + SourceSet& add_env_prefix(SourceId id, std::string prefix) + { + SourceSpec spec; + spec.id = std::move(id); + spec.kind = SourceKind::Environment; + spec.env_prefix = std::move(prefix); + m_specs.push_back(std::move(spec)); + return *this; + } + + SourceSet& add_env_map( + SourceId id, + std::vector> kv) + { + SourceSpec spec; + spec.id = std::move(id); + spec.kind = SourceKind::Environment; + spec.entries = std::move(kv); + m_specs.push_back(std::move(spec)); + return *this; + } + + SourceSet& add_cli_args(SourceId id, std::vector args) + { + SourceSpec spec; + spec.id = std::move(id); + spec.kind = SourceKind::CliArgs; + spec.cli_args = std::move(args); + m_specs.push_back(std::move(spec)); + return *this; + } + + SourceSet& add_removals(SourceId id, SourceKind tier, + std::vector keys) + { + SourceSpec spec; + spec.id = std::move(id); + spec.kind = tier; + spec.removals = std::move(keys); + m_specs.push_back(std::move(spec)); + return *this; + } + + [[nodiscard]] const std::vector& specs() const noexcept + { + return m_specs; + } + + private: + + std::vector m_specs{}; + }; + + struct MergedEntry { + ValueState state{ValueState::Missing}; + std::string value{}; + SourceLocation location{}; + }; + + struct MergedConfig { + std::map entries{}; + std::shared_ptr provenance{ + std::make_shared()}; + std::uint64_t revision_digest{0}; + + [[nodiscard]] ValueState state_of(std::string_view key) const + { + const auto it = entries.find(std::string{key}); + return it == entries.end() ? ValueState::Missing + : it->second.state; + } + + [[nodiscard]] std::optional + value_of(std::string_view key) const + { + const auto it = entries.find(std::string{key}); + if (it == entries.end() || + (it->second.state != ValueState::Present && + it->second.state != ValueState::Empty)) { + return std::nullopt; + } + return std::string_view{it->second.value}; + } + }; + + struct Diagnostic { + ConfigErrorCode code{ConfigErrorCode::none}; + std::string category{}; + SourceLocation location{}; + std::string message{}; + bool redacted{false}; + }; + + [[nodiscard]] Void::Result::Result load_sources( + const SourceSet& sources, const ConfigLimits& limits = {}, + const std::unordered_set& secret_keys = {}, + std::vector* diagnostics_out = nullptr); + + // ── Typed Schema & Strict Binding ──────────────────────────────────── + + struct FieldRule { + std::string key{}; + bool required{false}; + bool secret{false}; + bool restart_required{false}; + bool is_vector{false}; + bool is_optional{false}; + std::optional deprecated_message{}; + std::optional int_min{}; + std::optional int_max{}; + std::optional real_min{}; + std::optional real_max{}; + }; + + template struct Validated { + T value{}; + std::shared_ptr provenance{}; + std::vector warnings{}; + std::vector diagnostics{}; + }; + + namespace detail + { + [[nodiscard]] inline std::string + redact_display(std::string_view raw, bool is_secret) + { + return is_secret ? std::string{"[REDACTED]"} : std::string{raw}; + } + + [[nodiscard]] Void::Result::Result + parse_strict_bool(std::string_view raw); + + [[nodiscard]] Void::Result::Result + parse_strict_i64_or_bytes(std::string_view raw, bool allow_bytes, + bool is_secret); + + [[nodiscard]] Void::Result::Result + parse_strict_u64_or_bytes(std::string_view raw, bool allow_bytes, + bool is_secret); + + [[nodiscard]] Void::Result::Result + parse_strict_real(std::string_view raw, bool is_secret); + + [[nodiscard]] bool try_parse_vector_index(std::string_view suffix, + std::size_t& out); + } // namespace detail + + template class Schema + { + public: + + struct Constraint { + std::string name{}; + std::function(const T&)> check{}; + }; + + explicit Schema(ConfigLimits limits = {}) : m_limits(limits) {} + +#ifdef VOID_HAS_CONFIG_REFLECTION + [[nodiscard]] static Schema + from_reflection(std::string_view prefix = {}, + ConfigLimits limits = {}) + { + Schema s{limits}; + collect_reflection(s, prefix); + return s; + } +#endif + + Schema& allow_unknown_keys(bool allow) + { + m_allow_unknown = allow; + return *this; + } + + [[nodiscard]] bool allows_unknown_keys() const noexcept + { + return m_allow_unknown; + } + + [[nodiscard]] const ConfigLimits& limits() const noexcept + { + return m_limits; + } + + Schema& field(FieldRule rule) + { + m_rules[rule.key] = std::move(rule); + return *this; + } + + Schema& secret(std::string_view key, bool v = true) + { + m_rules[std::string{key}].key = std::string{key}; + m_rules[std::string{key}].secret = v; + return *this; + } + + Schema& restart_required(std::string_view key, bool v = true) + { + m_rules[std::string{key}].key = std::string{key}; + m_rules[std::string{key}].restart_required = v; + return *this; + } + + Schema& deprecate(std::string_view key, std::string msg) + { + m_rules[std::string{key}].key = std::string{key}; + m_rules[std::string{key}].deprecated_message = std::move(msg); + return *this; + } + + Schema& int_range(std::string_view key, std::int64_t lo, + std::int64_t hi) + { + auto& r = m_rules[std::string{key}]; + r.key = std::string{key}; + r.int_min = lo; + r.int_max = hi; + return *this; + } + + Schema& real_range(std::string_view key, double lo, double hi) + { + auto& r = m_rules[std::string{key}]; + r.key = std::string{key}; + r.real_min = lo; + r.real_max = hi; + return *this; + } + + Schema& add_constraint( + std::string name, + std::function(const T&)> fn) + { + m_constraints.push_back( + Constraint{std::move(name), std::move(fn)}); + return *this; + } + + [[nodiscard]] const std::map& + rules() const noexcept + { + return m_rules; + } + + [[nodiscard]] const std::vector& + constraints() const noexcept + { + return m_constraints; + } + + [[nodiscard]] std::unordered_set secret_keys() const + { + std::unordered_set out; + for (const auto& [k, r] : m_rules) { + if (r.secret) { + out.insert(k); + } + } + return out; + } + + [[nodiscard]] const FieldRule* find_rule(std::string_view key) const + { + const auto it = m_rules.find(std::string{key}); + return it == m_rules.end() ? nullptr : &it->second; + } + + private: + +#ifdef VOID_HAS_CONFIG_REFLECTION + template + static void collect_reflection(Schema& s, + std::string_view prefix) + { + template for (constexpr auto m : Void::Meta::members_v) + { + using MT = [:std::meta::type_of(m):]; + constexpr auto ko = Void::Meta::annotation_of(m); + const std::string seg = + ko.has_value() + ? std::string{ko->name.view()} + : std::string{std::meta::identifier_of(m)}; + const std::string full = + prefix.empty() ? seg + : std::string{prefix} + "." + seg; + if constexpr (BindDetail::BindableAggregate && + !BindDetail::Leaf) { + collect_reflection(s, full); + } else { + FieldRule r; + r.key = full; + r.required = Void::Meta::has_annotation(m); + r.secret = Void::Meta::has_annotation(m); + r.restart_required = + Void::Meta::has_annotation(m); + r.is_vector = Void::Meta::is_vector_v; + r.is_optional = Void::Meta::is_optional_v; + if constexpr (constexpr auto dep = + Void::Meta::annotation_of( + m); + dep.has_value()) { + r.deprecated_message = std::string{dep->message.view()}; + } + if constexpr (constexpr auto ir = + Void::Meta::annotation_of(m); + ir.has_value()) { + r.int_min = ir->min; + r.int_max = ir->max; + } + if constexpr (constexpr auto rr = + Void::Meta::annotation_of( + m); + rr.has_value()) { + r.real_min = rr->min; + r.real_max = rr->max; + } + s.m_rules.emplace(full, std::move(r)); + } + } + } +#endif + + ConfigLimits m_limits{}; + bool m_allow_unknown{false}; + std::map m_rules{}; + std::vector m_constraints{}; + }; + + namespace SchemaDetail + { + template + struct IsDuration : std::false_type { + }; + template + struct IsDuration> : std::true_type { + }; + + template + Void::Result::Result convert_strict(std::string_view key, + const MergedEntry& entry, + const FieldRule* rule) + { + const bool is_secret = rule != nullptr && rule->secret; + auto fail_cat = [&](ConfigErrorCode code, std::string_view msg) { + return Void::Result::fail(make_config_error( + code, + std::format( + "Configuration: key '{}' (source={}, line={}): {} ('{}')", + key, entry.location.source, entry.location.line, msg, + detail::redact_display(entry.value, is_secret)))); + }; + + if (entry.state == ValueState::Null) { + return fail_cat(ConfigErrorCode::type_mismatch, + "null cannot bind to non-optional field"); + } + if constexpr (std::is_same_v) { + return entry.value; + } else { + if (entry.state == ValueState::Empty || entry.value.empty()) { + return fail_cat(ConfigErrorCode::type_mismatch, + "empty value is invalid for typed field"); + } + if constexpr (std::is_same_v) { + auto r = detail::parse_strict_bool(entry.value); + if (!r) { + return fail_cat(ConfigErrorCode::type_mismatch, + r.error().message()); + } + return *r; + } else if constexpr (std::is_enum_v) { +#ifdef VOID_HAS_ENUM_REFLECTION + if (auto e = Void::Detail::enum_parse(entry.value); + e.has_value()) { + return *e; + } + return fail_cat(ConfigErrorCode::type_mismatch, + "unknown enum value"); +#else + return fail_cat(ConfigErrorCode::type_mismatch, + "enum reflection disabled"); +#endif + } else if constexpr (IsDuration::value) { + auto parsed = Void::Time::parse_duration(entry.value); + if (!parsed.has_value()) { + return fail_cat(ConfigErrorCode::type_mismatch, + "invalid duration"); + } + return std::chrono::duration_cast(*parsed); + } else if constexpr (std::is_floating_point_v) { + auto r = detail::parse_strict_real(entry.value, is_secret); + if (!r) { + return fail_cat(ConfigErrorCode::type_mismatch, + r.error().message()); + } + if (rule != nullptr) { + if (rule->real_min.has_value() && *r < *rule->real_min) { + return fail_cat(ConfigErrorCode::range_error, + "below minimum"); + } + if (rule->real_max.has_value() && *r > *rule->real_max) { + return fail_cat(ConfigErrorCode::range_error, + "above maximum"); + } + } + return static_cast(*r); + } else if constexpr (std::is_integral_v && + std::is_signed_v) { + auto r = detail::parse_strict_i64_or_bytes( + entry.value, true, is_secret); + if (!r) { + return fail_cat(ConfigErrorCode::type_mismatch, + r.error().message()); + } + if (*r < static_cast( + std::numeric_limits::min()) || + *r > static_cast( + std::numeric_limits::max())) { + return fail_cat(ConfigErrorCode::range_error, + "integer out of target type range"); + } + if (rule != nullptr) { + if (rule->int_min.has_value() && *r < *rule->int_min) { + return fail_cat(ConfigErrorCode::range_error, + "below minimum"); + } + if (rule->int_max.has_value() && *r > *rule->int_max) { + return fail_cat(ConfigErrorCode::range_error, + "above maximum"); + } + } + return static_cast(*r); + } else if constexpr (std::is_integral_v && + std::is_unsigned_v) { + auto r = detail::parse_strict_u64_or_bytes( + entry.value, true, is_secret); + if (!r) { + return fail_cat(ConfigErrorCode::type_mismatch, + r.error().message()); + } + if (*r > static_cast( + std::numeric_limits::max())) { + return fail_cat(ConfigErrorCode::range_error, + "unsigned integer out of target range"); + } + if (rule != nullptr) { + if (rule->int_min.has_value() && + *r < static_cast( + std::max(0, *rule->int_min))) { + return fail_cat(ConfigErrorCode::range_error, + "below minimum"); + } + if (rule->int_max.has_value() && + (*rule->int_max < 0 || + *r > static_cast(*rule->int_max))) { + return fail_cat(ConfigErrorCode::range_error, + "above maximum"); + } + } + return static_cast(*r); + } else { + static_assert(std::is_same_v, + "unsupported strict config field type"); + } + } + } + +#ifdef VOID_HAS_CONFIG_REFLECTION + template + void bind_strict_into(const MergedConfig& cfg, + const Schema& schema, + std::string_view prefix, Agg& out, + std::vector& diags, + std::vector& warnings, + std::unordered_set& consumed_keys) + { + auto push_diag = [&](ConfigErrorCode code, std::string cat, + const SourceLocation& loc, std::string msg, + bool redacted) { + if (diags.size() < schema.limits().max_diagnostics) { + diags.push_back(Diagnostic{code, std::move(cat), loc, + std::move(msg), redacted}); + } + }; + + template for (constexpr auto m : Void::Meta::members_v) + { + using MT = [:std::meta::type_of(m):]; + constexpr auto ko = Void::Meta::annotation_of(m); + const std::string seg = + ko.has_value() ? std::string{ko->name.view()} + : std::string{std::meta::identifier_of(m)}; + const std::string full = + prefix.empty() ? seg : std::string{prefix} + "." + seg; + const FieldRule* rule = schema.find_rule(full); + const bool is_secret = + (rule != nullptr && rule->secret) || + Void::Meta::has_annotation(m); + const bool is_required = + (rule != nullptr && rule->required) || + Void::Meta::has_annotation(m); + + if constexpr (BindDetail::BindableAggregate && + !BindDetail::Leaf) { + bind_strict_into(cfg, schema, full, out.[:m:], + diags, warnings, consumed_keys); + } else if constexpr (Void::Meta::is_optional_v) { + using U = typename MT::value_type; + const auto it = cfg.entries.find(full); + if (it != cfg.entries.end()) { + consumed_keys.insert(full); + if (rule != nullptr && + rule->deprecated_message.has_value()) { + warnings.push_back(full + ": " + + *rule->deprecated_message); + } + if (it->second.state == ValueState::Null) { + out.[:m:].reset(); + } else if (it->second.state != ValueState::Missing && + it->second.state != ValueState::Removed) { + auto v = convert_strict(full, it->second, rule); + if (!v) { + push_diag(static_cast( + v.error().code().value), + "conversion", it->second.location, + v.error().message(), is_secret); + } else { + out.[:m:] = std::move(*v); + } + } + } + } else if constexpr (Void::Meta::is_vector_v) { + using U = typename MT::value_type; + const std::string item_prefix = full + "."; + std::map indexed; + std::size_t max_idx = 0; + bool any = false; + bool had_bad_suffix = false; + for (auto it = cfg.entries.lower_bound(item_prefix); + it != cfg.entries.end() && + it->first.starts_with(item_prefix); + ++it) { + const std::string_view suffix = + std::string_view{it->first}.substr( + item_prefix.size()); + if (suffix.find('.') != std::string_view::npos) { + continue; + } + consumed_keys.insert(it->first); + if (it->second.state == ValueState::Missing || + it->second.state == ValueState::Removed) { + continue; + } + std::size_t idx = 0; + if (!detail::try_parse_vector_index(suffix, idx)) { + had_bad_suffix = true; + push_diag(ConfigErrorCode::vector_gap, "vector", + it->second.location, + "non-numeric vector index key '" + + it->first + "'", + is_secret); + continue; + } + if (idx >= schema.limits().max_vector_items) { + push_diag(ConfigErrorCode::limit_exceeded, "limit", + it->second.location, + "vector index exceeds max_vector_items", + is_secret); + continue; + } + indexed[idx] = &it->second; + if (!any || idx > max_idx) max_idx = idx; + any = true; + } + if (any && !had_bad_suffix) { + MT items; + for (std::size_t i = 0; i <= max_idx; ++i) { + const auto idx_it = indexed.find(i); + if (idx_it == indexed.end()) { + push_diag( + ConfigErrorCode::vector_gap, "vector", + SourceLocation{.source = "", + .key = item_prefix + + std::to_string(i)}, + "gap in vector indices at '" + item_prefix + + std::to_string(i) + "'", + false); + continue; + } + auto v = convert_strict( + item_prefix + std::to_string(i), + *idx_it->second, rule); + if (!v) { + push_diag(static_cast( + v.error().code().value), + "conversion", + idx_it->second->location, + v.error().message(), is_secret); + } else { + items.push_back(std::move(*v)); + } + } + if (diags.empty()) { + out.[:m:] = std::move(items); + } + } + } else { + const auto it = cfg.entries.find(full); + if (it != cfg.entries.end()) { + consumed_keys.insert(full); + if (it->second.state == ValueState::Missing || + it->second.state == ValueState::Removed) { + if (is_required) { + push_diag(ConfigErrorCode::missing_required, + "required", it->second.location, + "missing required key '" + full + "'", + is_secret); + } + } else { + if (rule != nullptr && + rule->deprecated_message.has_value()) { + warnings.push_back(full + ": " + + *rule->deprecated_message); + } + auto v = convert_strict(full, it->second, rule); + if (!v) { + push_diag(static_cast( + v.error().code().value), + "conversion", it->second.location, + v.error().message(), is_secret); + } else { + out.[:m:] = std::move(*v); + } + } + } else if (is_required) { + push_diag( + ConfigErrorCode::missing_required, "required", + SourceLocation{.source = "", .key = full}, + "missing required key '" + full + "'", is_secret); + } + } + } + } +#endif + } // namespace SchemaDetail + + template + [[nodiscard]] Void::Result::Result> + validate(const MergedConfig& cfg, const Schema& schema) + { + Validated result; + result.provenance = cfg.provenance; + std::vector& diags = result.diagnostics; + std::unordered_set consumed_keys; + +#ifdef VOID_HAS_CONFIG_REFLECTION + if constexpr (BindDetail::BindableAggregate) { + SchemaDetail::bind_strict_into( + cfg, schema, {}, result.value, diags, result.warnings, + consumed_keys); + } +#endif + + if (!schema.allows_unknown_keys()) { + for (const auto& [k, entry] : cfg.entries) { + if (entry.state == ValueState::Missing || + entry.state == ValueState::Removed) { + continue; + } + if (!consumed_keys.contains(k) && + diags.size() < schema.limits().max_diagnostics) { + diags.push_back(Diagnostic{ + ConfigErrorCode::unknown_key, + "unknown_key", + entry.location, + "unknown configuration key '" + k + "'", + false, + }); + } + } + } + + if (diags.empty()) { + for (const auto& c : schema.constraints()) { + auto cr = c.check(result.value); + if (!cr && diags.size() < schema.limits().max_diagnostics) { + diags.push_back(Diagnostic{ + ConfigErrorCode::constraint_failed, + "constraint:" + c.name, + SourceLocation{}, + cr.error().message(), + false, + }); + } + } + } + + if (!diags.empty()) { + const auto primary = diags.front(); + std::string summary = primary.message; + if (diags.size() > 1) { + summary += std::format(" (+{} more diagnostic(s))", + diags.size() - 1); + } + return Void::Result::fail(make_config_error(primary.code, summary)); + } + + return result; + } + + template + [[nodiscard]] Void::Result::Result> + validate(const Config& cfg, const Schema& schema) + { + SourceSet ss; + std::vector> kvs; + for (const auto& k : cfg.keys()) { + kvs.emplace_back(k, std::string{cfg.get_or(k)}); + } + ss.add_defaults_map("config", std::move(kvs)); + auto merged = load_sources(ss, schema.limits(), schema.secret_keys()); + if (!merged) { + return Void::Result::fail(std::move(merged).error()); + } + return validate(*merged, schema); + } + + template + [[nodiscard]] std::vector detect_restart_required_changes( + const MergedConfig& old_cfg, const MergedConfig& new_cfg, + const Schema& schema) + { + std::vector changed; + for (const auto& [k, rule] : schema.rules()) { + if (!rule.restart_required) { + continue; + } + const auto old_it = old_cfg.entries.find(k); + const auto new_it = new_cfg.entries.find(k); + const ValueState old_s = + old_it == old_cfg.entries.end() ? ValueState::Missing + : old_it->second.state; + const ValueState new_s = + new_it == new_cfg.entries.end() ? ValueState::Missing + : new_it->second.state; + if (old_s != new_s || + (old_it != old_cfg.entries.end() && + new_it != new_cfg.entries.end() && + old_it->second.value != new_it->second.value)) { + changed.push_back(k); + } + } + return changed; + } + +} // namespace Void::Configuration diff --git a/src/Configuration/Schema.cpp b/src/Configuration/Schema.cpp new file mode 100644 index 0000000..72d891c --- /dev/null +++ b/src/Configuration/Schema.cpp @@ -0,0 +1,766 @@ +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__unix__) || defined(__APPLE__) +extern char** environ; // NOLINT +#define VOID_SCHEMA_HAS_ENVIRON 1 +#endif + +namespace Void::Configuration +{ + namespace detail + { + Void::Result::Result parse_strict_bool(std::string_view raw) + { + std::string lower; + lower.reserve(raw.size()); + for (const char c : raw) { + lower += static_cast( + std::tolower(static_cast(c))); + } + if (lower == "true" || lower == "1" || lower == "yes" || + lower == "on") { + return true; + } + if (lower == "false" || lower == "0" || lower == "no" || + lower == "off") { + return false; + } + return Void::Result::fail(make_config_error( + ConfigErrorCode::type_mismatch, "expected boolean value")); + } + + Void::Result::Result parse_strict_i64_or_bytes( + std::string_view raw, bool allow_bytes, bool is_secret) + { + if (raw.empty()) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::type_mismatch, "empty integer value")); + } + std::int64_t exact = 0; + const char* begin = raw.data(); + const char* end = raw.data() + raw.size(); + const auto [ptr, ec] = std::from_chars(begin, end, exact); + if (ec == std::errc{} && ptr == end) { + return exact; + } + if (ec == std::errc::result_out_of_range) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::range_error, + std::string{"signed integer overflow: "} + + redact_display(raw, is_secret))); + } + + if (allow_bytes) { + double num = 0.0; + const auto [bptr, bec] = std::from_chars(begin, end, num); + if (bec == std::errc{} && bptr != begin && std::isfinite(num) && + num >= 0.0) { + std::string_view suffix{bptr, end}; + while (!suffix.empty() && suffix.front() == ' ') { + suffix.remove_prefix(1); + } + double mult = 0.0; + if (suffix == "B" || suffix.empty()) { + mult = 1.0; + } else if (suffix == "KB") { + mult = 1e3; + } else if (suffix == "MB") { + mult = 1e6; + } else if (suffix == "GB") { + mult = 1e9; + } else if (suffix == "TB") { + mult = 1e12; + } else if (suffix == "KiB") { + mult = 1024.0; + } else if (suffix == "MiB") { + mult = 1024.0 * 1024.0; + } else if (suffix == "GiB") { + mult = 1024.0 * 1024.0 * 1024.0; + } else if (suffix == "TiB") { + mult = 1024.0 * 1024.0 * 1024.0 * 1024.0; + } + if (mult > 0.0) { + const double scaled = num * mult; + if (std::isfinite(scaled) && + scaled <= + static_cast( + std::numeric_limits::max())) { + return static_cast(scaled); + } + return Void::Result::fail(make_config_error( + ConfigErrorCode::range_error, + "byte-size value overflows int64_t")); + } + } + } + + return Void::Result::fail(make_config_error( + ConfigErrorCode::type_mismatch, + std::string{"not a signed integer or byte size: "} + + redact_display(raw, is_secret))); + } + + Void::Result::Result parse_strict_u64_or_bytes( + std::string_view raw, bool allow_bytes, bool is_secret) + { + if (raw.empty()) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::type_mismatch, + "empty unsigned integer value")); + } + std::uint64_t exact = 0; + const char* begin = raw.data(); + const char* end = raw.data() + raw.size(); + const auto [ptr, ec] = std::from_chars(begin, end, exact); + if (ec == std::errc{} && ptr == end) { + return exact; + } + if (ec == std::errc::result_out_of_range) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::range_error, + std::string{"unsigned integer overflow: "} + + redact_display(raw, is_secret))); + } + + if (allow_bytes) { + double num = 0.0; + const auto [bptr, bec] = std::from_chars(begin, end, num); + if (bec == std::errc{} && bptr != begin && std::isfinite(num) && + num >= 0.0) { + std::string_view suffix{bptr, end}; + while (!suffix.empty() && suffix.front() == ' ') { + suffix.remove_prefix(1); + } + double mult = 0.0; + if (suffix == "B" || suffix.empty()) { + mult = 1.0; + } else if (suffix == "KB") { + mult = 1e3; + } else if (suffix == "MB") { + mult = 1e6; + } else if (suffix == "GB") { + mult = 1e9; + } else if (suffix == "TB") { + mult = 1e12; + } else if (suffix == "KiB") { + mult = 1024.0; + } else if (suffix == "MiB") { + mult = 1024.0 * 1024.0; + } else if (suffix == "GiB") { + mult = 1024.0 * 1024.0 * 1024.0; + } else if (suffix == "TiB") { + mult = 1024.0 * 1024.0 * 1024.0 * 1024.0; + } + if (mult > 0.0) { + const double scaled = num * mult; + if (std::isfinite(scaled) && + scaled < 18446744073709551616.0) { + return static_cast(scaled); + } + return Void::Result::fail(make_config_error( + ConfigErrorCode::range_error, + "byte-size value overflows uint64_t")); + } + } + } + + return Void::Result::fail(make_config_error( + ConfigErrorCode::type_mismatch, + std::string{"not an unsigned integer or byte size: "} + + redact_display(raw, is_secret))); + } + + Void::Result::Result parse_strict_real(std::string_view raw, + bool is_secret) + { + if (raw.empty()) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::type_mismatch, "empty real value")); + } + double val = 0.0; + const char* begin = raw.data(); + const char* end = raw.data() + raw.size(); + const auto [ptr, ec] = std::from_chars(begin, end, val); + if (ec != std::errc{} || ptr != end || !std::isfinite(val)) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::type_mismatch, + std::string{"invalid finite real: "} + + redact_display(raw, is_secret))); + } + return val; + } + + bool try_parse_vector_index(std::string_view suffix, std::size_t& out) + { + if (suffix.empty()) { + return false; + } + if (suffix.size() > 1 && suffix.front() == '0') { + return false; + } + std::size_t idx = 0; + const auto [ptr, ec] = std::from_chars( + suffix.data(), suffix.data() + suffix.size(), idx); + if (ec != std::errc{} || ptr != suffix.data() + suffix.size()) { + return false; + } + out = idx; + return true; + } + } // namespace detail + + namespace + { + int precedence_rank(SourceKind kind) noexcept + { + switch (kind) { + case SourceKind::Defaults: + return 0; + case SourceKind::FileKeyValue: + case SourceKind::FileIni: + case SourceKind::FileJson: + return 1; + case SourceKind::Environment: + return 2; + case SourceKind::CliArgs: + return 3; + } + return 0; + } + + struct EmittedItem { + std::string key{}; + ValueState state{ValueState::Present}; + std::string value{}; + std::uint32_t line{0}; + }; + + Void::Result::Result + flatten_json_checked(const Void::Json::Value& v, + const std::string& prefix, std::size_t depth, + const ConfigLimits& limits, + std::vector& out, + std::unordered_set& dot_paths, + std::unordered_set& nested_paths) + { + if (depth > limits.max_nesting_depth) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: JSON nesting depth exceeds max_nesting_depth")); + } + if (v.is_object()) { + for (const auto& [k, child] : v.as_object()) { + if (k.size() > limits.max_key_bytes) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: JSON key exceeds max_key_bytes")); + } + const std::string full = + prefix.empty() ? k : prefix + "." + k; + if (k.find('.') != std::string::npos) { + if (nested_paths.contains(full)) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::key_collision, + "Configuration: key collision between literal dot '" + + full + "' and nested JSON path")); + } + dot_paths.insert(full); + } else if (!prefix.empty()) { + if (dot_paths.contains(full)) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::key_collision, + "Configuration: key collision between nested path '" + + full + "' and literal dotted key")); + } + nested_paths.insert(full); + } + if (auto r = flatten_json_checked( + child, full, depth + 1, limits, out, dot_paths, + nested_paths); + !r) { + return r; + } + } + return {}; + } + if (v.is_array()) { + const auto& arr = v.as_array(); + if (arr.size() > limits.max_vector_items) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: JSON array exceeds max_vector_items")); + } + for (std::size_t i = 0; i < arr.size(); ++i) { + const std::string child_key = + prefix + "." + std::to_string(i); + if (dot_paths.contains(child_key)) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::key_collision, + "Configuration: key collision with dotted path '" + + child_key + "'")); + } + nested_paths.insert(child_key); + if (auto r = flatten_json_checked( + arr[i], child_key, depth + 1, limits, out, + dot_paths, nested_paths); + !r) { + return r; + } + } + return {}; + } + + if (prefix.empty()) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::parse_error, + "Configuration: top-level JSON configuration must be an object")); + } + if (prefix.size() > limits.max_key_bytes) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: flattened key exceeds max_key_bytes")); + } + + if (v.is_null()) { + out.push_back(EmittedItem{prefix, ValueState::Null, {}, 0}); + } else if (v.is_string()) { + const auto& s = v.as_string(); + out.push_back(EmittedItem{ + prefix, + s.empty() ? ValueState::Empty : ValueState::Present, s, 0}); + } else if (v.is_bool()) { + out.push_back(EmittedItem{ + prefix, ValueState::Present, + v.as_bool() ? "true" : "false", 0}); + } else if (v.is_int()) { + out.push_back(EmittedItem{ + prefix, ValueState::Present, std::to_string(v.as_int()), 0}); + } else if (v.is_uint()) { + out.push_back(EmittedItem{ + prefix, ValueState::Present, std::to_string(v.as_uint()), + 0}); + } else if (v.is_number()) { + const double d = v.as_number(); + if (!std::isfinite(d)) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::parse_error, + "Configuration: non-finite number for '" + prefix + + "'")); + } + std::string s; + if (!(d == 0.0 && std::signbit(d)) && std::floor(d) == d && + std::abs(d) < 1e15) { + s = std::to_string(static_cast(d)); + } else { + s = std::format("{}", d); + } + out.push_back( + EmittedItem{prefix, ValueState::Present, std::move(s), 0}); + } + return {}; + } + + Void::Result::Result + read_bounded_source_file(const std::filesystem::path& path, + const ConfigLimits& limits) + { + std::error_code ec; + const auto sz = std::filesystem::file_size(path, ec); + if (ec) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::io_error, + "Configuration: cannot stat source file '" + path.string() + + "'")); + } + if (sz > limits.max_source_bytes) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: source file '" + path.string() + + "' exceeds max_source_bytes")); + } + auto txt = Void::FileSystem::read_file(path); + if (!txt) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::io_error, + "Configuration: read error on '" + path.string() + "'")); + } + if (txt->size() > limits.max_source_bytes) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: source file '" + path.string() + + "' exceeds max_source_bytes")); + } + return *txt; + } + } // namespace + + Void::Result::Result + load_sources(const SourceSet& sources, const ConfigLimits& limits, + const std::unordered_set& secret_keys, + std::vector* diagnostics_out) + { + const auto& specs = sources.specs(); + if (specs.size() > limits.max_sources) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration::load_sources: number of sources exceeds max_sources")); + } + + std::vector order(specs.size()); + std::iota(order.begin(), order.end(), 0); + std::stable_sort(order.begin(), order.end(), [&](std::size_t a, + std::size_t b) { + const int ra = precedence_rank(specs[a].kind); + const int rb = precedence_rank(specs[b].kind); + return ra < rb; + }); + + MergedConfig merged; + std::size_t merged_bytes = 0; + + auto record_diag = [&](const Diagnostic& d) { + if (diagnostics_out != nullptr && + diagnostics_out->size() < limits.max_diagnostics) { + diagnostics_out->push_back(d); + } + }; + + auto apply_item = + [&](const SourceSpec& spec, + const EmittedItem& item) -> Void::Result::Result { + const bool is_secret = secret_keys.contains(item.key); + if (item.key.size() > limits.max_key_bytes) { + Diagnostic d{ConfigErrorCode::limit_exceeded, "limit", + SourceLocation{spec.id, item.key, item.line}, + "Configuration: key exceeds max_key_bytes", + is_secret}; + record_diag(d); + return Void::Result::fail( + make_config_error(d.code, d.message)); + } + if (item.value.size() > limits.max_scalar_bytes) { + Diagnostic d{ + ConfigErrorCode::limit_exceeded, "limit", + SourceLocation{spec.id, item.key, item.line}, + "Configuration: scalar value for '" + item.key + "' (" + + detail::redact_display( + std::to_string(item.value.size()) + "B", + is_secret) + + ") exceeds max_scalar_bytes", + is_secret}; + record_diag(d); + return Void::Result::fail( + make_config_error(d.code, d.message)); + } + + const std::size_t delta = + item.key.size() + (is_secret ? 0 : item.value.size()) + + spec.id.size(); + if (merged_bytes + delta > limits.max_merged_bytes) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: merged configuration exceeds max_merged_bytes")); + } + if (!merged.entries.contains(item.key) && + merged.entries.size() >= limits.max_keys) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: key count exceeds max_keys")); + } + merged_bytes += delta; + + const SourceLocation loc{spec.id, item.key, item.line}; + merged.entries[item.key] = + MergedEntry{item.state, item.value, loc}; + + SourceOrigin origin{spec.id, spec.kind, item.line, item.state}; + auto& prov = merged.provenance->entries[item.key]; + if (!prov.key.empty()) { + prov.shadowed.push_back(std::move(prov.winner)); + } else { + prov.key = item.key; + } + prov.winner = std::move(origin); + prov.redacted = prov.redacted || is_secret; + return {}; + }; + + for (const std::size_t idx : order) { + const auto& spec = specs[idx]; + std::vector items; + + for (const auto& rm_key : spec.removals) { + items.push_back(EmittedItem{rm_key, ValueState::Removed, {}, 0}); + } + + switch (spec.kind) { + case SourceKind::Defaults: { + for (const auto& [k, v] : spec.entries) { + items.push_back(EmittedItem{ + k, v.empty() ? ValueState::Empty : ValueState::Present, + v, 0}); + } + break; + } + case SourceKind::FileKeyValue: { + std::string text; + if (spec.is_inline) { + if (spec.inline_text.size() > limits.max_source_bytes) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: inline KV exceeds max_source_bytes")); + } + text = spec.inline_text; + } else { + auto r = + read_bounded_source_file(spec.file_path, limits); + if (!r) return Void::Result::fail(std::move(r).error()); + text = std::move(*r); + } + std::size_t pos = 0; + std::uint32_t lineno = 0; + while (pos <= text.size()) { + ++lineno; + const auto nl = text.find('\n', pos); + std::string_view line = + nl == std::string::npos + ? std::string_view{text}.substr(pos) + : std::string_view{text}.substr(pos, nl - pos); + if (!line.empty() && line.back() == '\r') { + line.remove_suffix(1); + } + while (!line.empty() && line.front() == ' ') { + line.remove_prefix(1); + } + if (!line.empty() && line.front() != '#') { + const auto eq = line.find('='); + if (eq == std::string_view::npos) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::parse_error, + std::format( + "Configuration: source '{}' line {}: missing '='", + spec.id, lineno))); + } + auto k = line.substr(0, eq); + while (!k.empty() && k.back() == ' ') { + k.remove_suffix(1); + } + auto v = line.substr(eq + 1); + items.push_back(EmittedItem{ + std::string{k}, + v.empty() ? ValueState::Empty + : ValueState::Present, + std::string{v}, lineno}); + } + if (nl == std::string::npos) break; + pos = nl + 1; + } + break; + } + case SourceKind::FileIni: { + std::string text; + if (spec.is_inline) { + if (spec.inline_text.size() > limits.max_source_bytes) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: inline INI exceeds max_source_bytes")); + } + text = spec.inline_text; + } else { + auto r = + read_bounded_source_file(spec.file_path, limits); + if (!r) return Void::Result::fail(std::move(r).error()); + text = std::move(*r); + } + Void::Ini::IniFile ini; + if (auto err = Void::Ini::IniFile::parse(ini, text); + err.has_value()) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::parse_error, + std::format( + "Configuration: INI source '{}' line {}: {}", + spec.id, err->line, err->message))); + } + for (const auto& sec : ini.sections()) { + const auto* tbl = ini.section(sec); + if (tbl == nullptr) continue; + for (const auto& [k, v] : *tbl) { + std::string full = + sec.empty() ? k : sec + "." + k; + items.push_back(EmittedItem{ + std::move(full), + v.empty() ? ValueState::Empty + : ValueState::Present, + v, 0}); + } + } + break; + } + case SourceKind::FileJson: { + std::string text; + if (spec.is_inline) { + if (spec.inline_text.size() > limits.max_source_bytes) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: inline JSON exceeds max_source_bytes")); + } + text = spec.inline_text; + } else { + auto r = + read_bounded_source_file(spec.file_path, limits); + if (!r) return Void::Result::fail(std::move(r).error()); + text = std::move(*r); + } + auto parsed = Void::Json::parse(text); + if (!parsed) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::parse_error, + std::format( + "Configuration: JSON source '{}' line {} col {}: {}", + spec.id, parsed.error().line, + parsed.error().col, parsed.error().message))); + } + if (!parsed->is_object()) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::parse_error, + "Configuration: JSON root must be an object in '" + + spec.id + "'")); + } + std::unordered_set dot_paths; + std::unordered_set nested_paths; + if (auto fr = flatten_json_checked(*parsed, "", 0, limits, + items, dot_paths, + nested_paths); + !fr) { + return Void::Result::fail(std::move(fr).error()); + } + break; + } + case SourceKind::Environment: { + for (const auto& [k, v] : spec.entries) { + items.push_back(EmittedItem{ + k, v.empty() ? ValueState::Empty : ValueState::Present, + v, 0}); + } + for (const auto& k : spec.env_keys) { + if (auto ev = get_env(k); ev) { + items.push_back(EmittedItem{ + k, + ev->empty() ? ValueState::Empty + : ValueState::Present, + std::move(*ev), 0}); + } + } + if (!spec.env_prefix.empty()) { +#ifdef VOID_SCHEMA_HAS_ENVIRON + for (char** env = environ; *env != nullptr; ++env) { + const std::string_view kv{*env}; + const auto eq = kv.find('='); + if (eq == std::string_view::npos || + !kv.starts_with(spec.env_prefix)) { + continue; + } + const auto raw_k = kv.substr( + spec.env_prefix.size(), + eq - spec.env_prefix.size()); + std::string normalized; + normalized.reserve(raw_k.size()); + for (std::size_t i = 0; i < raw_k.size(); ++i) { + if (raw_k[i] == '_' && i + 1 < raw_k.size() && + raw_k[i + 1] == '_') { + normalized += '.'; + ++i; + } else { + normalized += static_cast( + std::tolower( + static_cast( + raw_k[i]))); + } + } + const auto val_sv = kv.substr(eq + 1); + items.push_back(EmittedItem{ + std::move(normalized), + val_sv.empty() ? ValueState::Empty + : ValueState::Present, + std::string{val_sv}, 0}); + } +#endif + } + break; + } + case SourceKind::CliArgs: { + for (std::size_t i = 0; i < spec.cli_args.size(); ++i) { + const std::string_view arg{spec.cli_args[i]}; + if (!arg.starts_with("--") || arg.size() <= 2) { + continue; + } + const auto body = arg.substr(2); + if (const auto eq = body.find('='); + eq != std::string_view::npos) { + const auto val_sv = body.substr(eq + 1); + items.push_back(EmittedItem{ + std::string{body.substr(0, eq)}, + val_sv.empty() ? ValueState::Empty + : ValueState::Present, + std::string{val_sv}, 0}); + } else if (i + 1 < spec.cli_args.size() && + !std::string_view{spec.cli_args[i + 1]} + .starts_with("--")) { + const auto val_sv = + std::string_view{spec.cli_args[i + 1]}; + items.push_back(EmittedItem{ + std::string{body}, + val_sv.empty() ? ValueState::Empty + : ValueState::Present, + std::string{val_sv}, 0}); + ++i; + } else { + items.push_back(EmittedItem{ + std::string{body}, ValueState::Present, "true", + 0}); + } + } + break; + } + } + + for (const auto& item : items) { + if (auto r = apply_item(spec, item); !r) { + return Void::Result::fail(std::move(r).error()); + } + } + } + + // Deterministic FNV-1a digest over sorted entries. + std::uint64_t h = 14695981039346656037ULL; + auto mix = [&](std::string_view s) { + for (const char ch : s) { + h ^= static_cast(ch); + h *= 1099511628211ULL; + } + h ^= 0xff; + h *= 1099511628211ULL; + }; + for (const auto& [k, e] : merged.entries) { + mix(k); + h ^= static_cast(e.state); + h *= 1099511628211ULL; + mix(e.value); + } + merged.revision_digest = h; + return merged; + } +} // namespace Void::Configuration diff --git a/src/Configuration/module.cmake b/src/Configuration/module.cmake index a64ad51..6186de5 100644 --- a/src/Configuration/module.cmake +++ b/src/Configuration/module.cmake @@ -1,3 +1,4 @@ void_add_module(Configuration INTERNAL_DEPS Core Functional System Data Time LogState + EXCLUDE_HEADERS Void/Configuration/ReloadController.hpp ) diff --git a/src/ConfigurationAsync/ReloadController.cpp b/src/ConfigurationAsync/ReloadController.cpp new file mode 100644 index 0000000..da7ce2f --- /dev/null +++ b/src/ConfigurationAsync/ReloadController.cpp @@ -0,0 +1,72 @@ +#include + +#include +#include + +namespace Void::Configuration::detail +{ + bool AsyncReloadGate::try_lock() noexcept + { + std::lock_guard lk{mu_}; + if (locked_) { + return false; + } + locked_ = true; + return true; + } + + bool AsyncReloadGate::enqueue_or_acquire(Void::Async::Executor* exec, + std::coroutine_handle<> h) noexcept + { + std::lock_guard lk{mu_}; + if (!locked_) { + locked_ = true; + return false; // do not suspend + } + waiters_.push_back(Waiter{exec, h}); + return true; + } + + void AsyncReloadGate::release() noexcept + { + Waiter next{}; + bool has_next = false; + { + std::lock_guard lk{mu_}; + if (!waiters_.empty()) { + next = waiters_.front(); + waiters_.pop_front(); + has_next = true; + } else { + locked_ = false; + } + } + if (has_next && next.h) { + if (next.exec != nullptr) { + next.exec->post_completion(next.h); + } else { + next.h.resume(); + } + } + } + + std::vector diff_merged_keys(const MergedConfig& old_cfg, + const MergedConfig& new_cfg) + { + std::set out; + for (const auto& [k, ne] : new_cfg.entries) { + const auto it = old_cfg.entries.find(k); + if (it == old_cfg.entries.end() || it->second.state != ne.state || + it->second.value != ne.value) { + out.insert(k); + } + } + for (const auto& [k, oe] : old_cfg.entries) { + if (!new_cfg.entries.contains(k) && + oe.state != ValueState::Missing) { + out.insert(k); + } + } + return std::vector{out.begin(), out.end()}; + } +} // namespace Void::Configuration::detail diff --git a/src/ConfigurationAsync/module.cmake b/src/ConfigurationAsync/module.cmake new file mode 100644 index 0000000..1e9b3f1 --- /dev/null +++ b/src/ConfigurationAsync/module.cmake @@ -0,0 +1,4 @@ +void_add_module(ConfigurationAsync + INTERNAL_DEPS Configuration SystemAsync Async Time Functional LogState + EXTRA_HEADERS Void/Configuration/ReloadController.hpp +) diff --git a/tests/package/ConfigurationAsyncOnly/CMakeLists.txt b/tests/package/ConfigurationAsyncOnly/CMakeLists.txt new file mode 100644 index 0000000..0e8ee40 --- /dev/null +++ b/tests/package/ConfigurationAsyncOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidConfigurationAsyncOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS ConfigurationAsync) + +add_executable(void_configuration_async_only_consumer main.cpp) +target_link_libraries(void_configuration_async_only_consumer PRIVATE Void::ConfigurationAsync) +target_compile_features(void_configuration_async_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME ConfigurationAsyncOnlyConsumer COMMAND void_configuration_async_only_consumer) diff --git a/tests/package/ConfigurationAsyncOnly/main.cpp b/tests/package/ConfigurationAsyncOnly/main.cpp new file mode 100644 index 0000000..e99a0c0 --- /dev/null +++ b/tests/package/ConfigurationAsyncOnly/main.cpp @@ -0,0 +1,20 @@ +#include +#include + +#include + +struct AsyncCfg { + std::string mode{"ok"}; +}; + +int main() +{ + Void::Async::ManualExecutor exec; + Void::Configuration::SourceSet ss; + ss.add_defaults_map("d", {{"mode", "fast"}}); + auto schema = Void::Configuration::Schema::from_reflection(); + auto ctrl = Void::Configuration::ReloadController::create( + schema, std::move(ss), {.executor = &exec}); + if (!ctrl) return 1; + return (*ctrl)->current().values->mode == "fast" ? 0 : 2; +} diff --git a/tests/package/ConfigurationOnly/CMakeLists.txt b/tests/package/ConfigurationOnly/CMakeLists.txt new file mode 100644 index 0000000..4b6d0ca --- /dev/null +++ b/tests/package/ConfigurationOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidConfigurationOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Configuration) + +add_executable(void_configuration_only_consumer main.cpp) +target_link_libraries(void_configuration_only_consumer PRIVATE Void::Configuration) +target_compile_features(void_configuration_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME ConfigurationOnlyConsumer COMMAND void_configuration_only_consumer) diff --git a/tests/package/ConfigurationOnly/main.cpp b/tests/package/ConfigurationOnly/main.cpp new file mode 100644 index 0000000..e56a316 --- /dev/null +++ b/tests/package/ConfigurationOnly/main.cpp @@ -0,0 +1,21 @@ +#include +#include +#include + +#include + +struct MinimalCfg { + [[= Void::Configuration::Required{}]] std::string name; + [[= Void::Configuration::IntRange{1, 100}]] int workers{4}; +}; + +int main() +{ + Void::Configuration::SourceSet ss; + ss.add_defaults_map("def", {{"name", "svc"}, {"workers", "8"}}); + auto schema = Void::Configuration::Schema::from_reflection(); + auto merged = Void::Configuration::load_sources(ss, schema.limits()); + if (!merged) return 1; + auto val = Void::Configuration::validate(*merged, schema); + return val && val->value.name == "svc" && val->value.workers == 8 ? 0 : 2; +} diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index 0e11b78..1d00274 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -262,6 +262,26 @@ if(_has_plugin) -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) endif() +has_modules(_has_configuration Configuration Core Functional System Data Time LogState) +if(_has_configuration) + run_consumer(ConfigurationOnly "${install_prefix}" "ConfigurationOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) +endif() + +has_modules(_has_configuration_async ConfigurationAsync Configuration SystemAsync Async Time Functional LogState) +if(_has_configuration_async) + run_consumer(ConfigurationAsyncOnly "${install_prefix}" "ConfigurationAsyncOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/standalone/Configuration/ConfigurationHardening.cpp b/tests/standalone/Configuration/ConfigurationHardening.cpp new file mode 100644 index 0000000..74d4581 --- /dev/null +++ b/tests/standalone/Configuration/ConfigurationHardening.cpp @@ -0,0 +1,256 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace +{ + namespace C = Void::Configuration; + + struct StrictServerConfig { + [[= C::Required{}]] std::string host{}; + [[= C::IntRange{1, 65535}]] int port{8080}; + [[= C::Secret{}]] std::string api_token{}; + [[= C::RestartRequired{}]] std::string bind_interface{"0.0.0.0"}; + [[= C::Deprecated{"use tls_min_version"}]] bool legacy_tls{false}; + std::vector shard_ids{}; + std::optional note{}; + }; +} // namespace + +// @tag reflection +Void::Testing::Test config_schema_precedence_provenance_and_redaction() +{ + C::SourceSet ss; + // Passed out of order on purpose: CLI must win over Env, which wins over + // File, which wins over Defaults. + ss.add_cli_args("cli", {"prog", "--host=cli.internal", "--port", "9090"}); + ss.add_env_map("env", + {{"host", "env.internal"}, + {"port", "7070"}, + {"api_token", "super-secret-value-123"}}); + ss.add_json_text( + "file.json", + R"({"host":"json.internal","port":6060,"shard_ids":[10,20]})"); + ss.add_defaults_map("defaults", + {{"host", "def.internal"}, {"port", "8080"}}); + + auto schema = C::Schema::from_reflection(); + auto merged = C::load_sources(ss, schema.limits(), schema.secret_keys()); + Void::Testing::require(merged.has_value()); + + auto res = C::validate(*merged, schema); + Void::Testing::require(res.has_value()); + Void::Testing::expect_eq(res->value.host, std::string{"cli.internal"}); + Void::Testing::expect_eq(res->value.port, 9090); + Void::Testing::expect_eq(res->value.api_token, + std::string{"super-secret-value-123"}); + Void::Testing::expect_eq(res->value.shard_ids.size(), std::size_t{2}); + Void::Testing::expect_eq(res->value.shard_ids[0], 10); + Void::Testing::expect_eq(res->value.shard_ids[1], 20); + + // Provenance tracks winning origin and shadowed origins with redaction flag. + const auto* host_prov = res->provenance->find("host"); + Void::Testing::require(host_prov != nullptr); + Void::Testing::expect_eq(host_prov->winner.source, std::string{"cli"}); + Void::Testing::expect_eq(host_prov->shadowed.size(), std::size_t{3}); + + const auto* tok_prov = res->provenance->find("api_token"); + Void::Testing::require(tok_prov != nullptr); + Void::Testing::expect(tok_prov->redacted); +} + +// @tag reflection +Void::Testing::Test config_schema_secret_redaction_and_bounds() +{ + auto schema = C::Schema::from_reflection(); + + // Bad secret value (overflow / out-of-range) must redact secret value. + { + C::SourceSet ss; + ss.add_defaults_map("d", {{"host", "h"}}); + // Force a scalar limit violation with secret key. + C::ConfigLimits tiny; + tiny.max_scalar_bytes = 8; + C::SourceSet big_sec; + big_sec.add_defaults_map( + "d", {{"host", "h"}, {"api_token", "VERY_SECRET_XYZ_TOKEN"}}); + auto m = C::load_sources(big_sec, tiny, schema.secret_keys()); + Void::Testing::expect(!m.has_value()); + Void::Testing::expect(m.error().message().find("VERY_SECRET_XYZ") == + std::string::npos); + Void::Testing::expect(m.error().message().find("[REDACTED]") != + std::string::npos); + } + + // Out-of-range port (0 or 70000) fails cleanly with range_error. + { + C::SourceSet ss; + ss.add_defaults_map("d", {{"host", "h"}, {"port", "70000"}}); + auto m = C::load_sources(ss, schema.limits(), schema.secret_keys()); + Void::Testing::require(m.has_value()); + auto v = C::validate(*m, schema); + Void::Testing::expect(!v.has_value()); + Void::Testing::expect_eq( + v.error().code().value, + static_cast(C::ConfigErrorCode::range_error)); + } + + // Exceeding max_source_bytes / max_nesting_depth rejected. + { + Void::FileSystem::TempDir tmp{"void_cfg_limits"}; + const auto file = tmp.path() / "big.json"; + std::string junk(256, 'a'); + Void::Testing::require( + Void::FileSystem::write_file(file, "{\"host\":\"" + junk + "\"}") + .has_value()); + C::ConfigLimits small_src; + small_src.max_source_bytes = 64; + C::SourceSet ss; + ss.add_json_file("f", file); + auto m = C::load_sources(ss, small_src); + Void::Testing::expect(!m.has_value()); + Void::Testing::expect_eq( + m.error().code().value, + static_cast(C::ConfigErrorCode::limit_exceeded)); + } + + { + std::string nested; + for (int i = 0; i < 40; ++i) nested += "{\"a\":"; + nested += "1"; + for (int i = 0; i < 40; ++i) nested += "}"; + C::SourceSet ss; + ss.add_json_text("deep", std::move(nested)); + auto m = C::load_sources(ss); + Void::Testing::expect(!m.has_value()); + Void::Testing::expect_eq( + m.error().code().value, + static_cast(C::ConfigErrorCode::limit_exceeded)); + } +} + +// @tag reflection +Void::Testing::Test config_schema_collisions_gaps_null_empty_and_constraints() +{ + auto schema = C::Schema::from_reflection(); + schema.add_constraint("no_root_interface_in_prod", + [](const StrictServerConfig& cfg) + -> Void::Result::Result { + if (cfg.host == "prod" && cfg.port < 1024) { + return Void::Result::fail( + C::make_config_error( + C::ConfigErrorCode::constraint_failed, + "prod requires non-privileged port")); + } + return {}; + }); + + // Dotted key vs nested path collision rejected. + { + C::SourceSet ss; + ss.add_json_text("coll", + R"({"a":{"b":"nested"},"a.b":"literal-dot"})"); + auto m = C::load_sources(ss); + Void::Testing::expect(!m.has_value()); + Void::Testing::expect_eq( + m.error().code().value, + static_cast(C::ConfigErrorCode::key_collision)); + } + + // Unknown key rejected by default. + { + C::SourceSet ss; + ss.add_defaults_map("d", {{"host", "h"}, {"typo_key", "1"}}); + auto m = C::load_sources(ss); + Void::Testing::require(m.has_value()); + auto v = C::validate(*m, schema); + Void::Testing::expect(!v.has_value()); + Void::Testing::expect_eq( + v.error().code().value, + static_cast(C::ConfigErrorCode::unknown_key)); + } + + // Vector index gap rejected. + { + C::SourceSet ss; + ss.add_defaults_map("d", {{"host", "h"}, + {"shard_ids.0", "1"}, + {"shard_ids.2", "3"}}); + auto m = C::load_sources(ss); + Void::Testing::require(m.has_value()); + auto v = C::validate(*m, schema); + Void::Testing::expect(!v.has_value()); + Void::Testing::expect_eq( + v.error().code().value, + static_cast(C::ConfigErrorCode::vector_gap)); + } + + // Null vs Empty vs Missing vs Removed distinction + no fallback on bad port. + { + C::SourceSet ss; + ss.add_json_text("j", R"({"host":"","port":null,"note":null})"); + auto m = C::load_sources(ss); + Void::Testing::require(m.has_value()); + Void::Testing::expect(m->state_of("host") == C::ValueState::Empty); + Void::Testing::expect(m->state_of("port") == C::ValueState::Null); + Void::Testing::expect(m->state_of("missing_x") == C::ValueState::Missing); + // null on non-optional int fails instead of falling back to 8080. + auto v = C::validate(*m, schema); + Void::Testing::expect(!v.has_value()); + } + + // Removed required field fails required validation. + { + C::SourceSet ss; + ss.add_defaults_map("d", {{"host", "h"}}); + ss.add_removals("r", C::SourceKind::Environment, {"host"}); + auto m = C::load_sources(ss); + Void::Testing::require(m.has_value()); + Void::Testing::expect(m->state_of("host") == C::ValueState::Removed); + auto v = C::validate(*m, schema); + Void::Testing::expect(!v.has_value()); + Void::Testing::expect_eq( + v.error().code().value, + static_cast(C::ConfigErrorCode::missing_required)); + } + + // Cross-field constraint + deprecated warning + restart_required diff. + { + C::SourceSet s1; + s1.add_defaults_map( + "d", {{"host", "prod"}, {"port", "80"}}); + auto m1 = C::load_sources(s1); + auto v1 = C::validate(*m1, schema); + Void::Testing::expect(!v1.has_value()); + Void::Testing::expect_eq( + v1.error().code().value, + static_cast(C::ConfigErrorCode::constraint_failed)); + + C::SourceSet s2; + s2.add_defaults_map("d", {{"host", "prod"}, + {"port", "8443"}, + {"legacy_tls", "true"}, + {"bind_interface", "127.0.0.1"}}); + C::SourceSet s3; + s3.add_defaults_map("d", {{"host", "prod"}, + {"port", "8443"}, + {"bind_interface", "10.0.0.1"}}); + auto m2 = C::load_sources(s2); + auto m3 = C::load_sources(s3); + auto v2 = C::validate(*m2, schema); + Void::Testing::require(v2.has_value()); + Void::Testing::expect(!v2->warnings.empty()); + auto rr = C::detect_restart_required_changes(*m2, *m3, schema); + Void::Testing::expect_eq(rr.size(), std::size_t{1}); + Void::Testing::expect_eq(rr[0], std::string{"bind_interface"}); + } +} diff --git a/tests/standalone/ConfigurationAsync/ConfigurationAsync.cpp b/tests/standalone/ConfigurationAsync/ConfigurationAsync.cpp new file mode 100644 index 0000000..68d27b4 --- /dev/null +++ b/tests/standalone/ConfigurationAsync/ConfigurationAsync.cpp @@ -0,0 +1,340 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace void_cfg_async_test +{ + namespace C = Void::Configuration; + + struct AppSettings { + [[= C::Required{}]] std::string host{"localhost"}; + [[= C::IntRange{1, 65535}]] int port{8080}; + [[= C::RestartRequired{}]] std::string bind_addr{"0.0.0.0"}; + }; + + template + Void::Coro::Task assign_task_result(Void::Coro::Task task, + std::optional* out) + { + *out = co_await task; + } + + template + T drive_task(Void::Async::ManualExecutor& exec, Void::Coro::Task task) + { + std::optional out; + Void::Async::spawn(exec, assign_task_result(std::move(task), &out)); + (void)exec.drain(); + return std::move(*out); + } + + Void::Coro::Task> make_resource_ok( + std::string label, std::atomic* disposes) + { + auto view = std::make_shared(std::move(label)); + C::PreparedChange pc; + pc.view = view; + pc.declared_budget_bytes = 64; + pc.dispose_async = + [disposes]() -> Void::Coro::Task> { + if (disposes != nullptr) { + disposes->fetch_add(1, std::memory_order_relaxed); + } + co_return Void::Result::Result{}; + }; + co_return pc; + } + + Void::Coro::Task> make_resource_fail() + { + co_return Void::Result::fail(C::make_config_error( + C::ConfigErrorCode::prepare_failed, "participant 2 prepare failed")); + } + + Void::Coro::Task, + Void::Result::Result>>> + run_two_reloads_concurrent( + std::shared_ptr> ctrl, + C::SourceSet s1, C::SourceSet s2) + { + auto t1 = ctrl->reload(std::move(s1)); + auto t2 = ctrl->reload(std::move(s2)); + auto r1 = co_await t1; + auto r2 = co_await t2; + co_return Void::Result::Result< + std::pair, + Void::Result::Result>>{ + std::pair{std::move(r1), std::move(r2)}}; + } +} // namespace void_cfg_async_test + +using namespace void_cfg_async_test; + +// @tag reflection +Void::Testing::Test config_async_fallible_factory_and_participant_rollback() +{ + auto schema = C::Schema::from_reflection(); + Void::Async::ManualExecutor exec; + + // Invalid initial config fails controller creation cleanly. + { + C::SourceSet bad; + bad.add_defaults_map("d", {{"host", "h"}, {"port", "99999"}}); + auto failed = C::ReloadController::create( + schema, std::move(bad), {.executor = &exec}); + Void::Testing::expect(!failed.has_value()); + } + + C::SourceSet init; + init.add_defaults_map("d", {{"host", "v1"}, {"port", "8080"}}); + auto ctrl_res = C::ReloadController::create( + schema, std::move(init), {.executor = &exec}); + Void::Testing::require(ctrl_res.has_value()); + auto ctrl = std::move(*ctrl_res); + + std::atomic disposals{0}; + Void::Testing::require( + ctrl->register_participant( + "p1", 64, + [&](const C::Snapshot&, + const std::shared_ptr& cand, + Void::Async::OperationOptions) { + return make_resource_ok(cand->host + ":" + + std::to_string(cand->port), + &disposals); + }) + .has_value()); + Void::Testing::require( + ctrl->register_participant( + "p2", 64, + [](const C::Snapshot&, + const std::shared_ptr&, + Void::Async::OperationOptions) { + return make_resource_fail(); + }) + .has_value()); + + // Reload fails in p2 -> must dispose p1 and keep generation 1 intact. + { + C::SourceSet s2; + s2.add_defaults_map("d", {{"host", "v2"}, {"port", "9090"}}); + auto r = drive_task(exec, ctrl->reload(std::move(s2))); + Void::Testing::expect(!r.has_value()); + Void::Testing::expect_eq(disposals.load(), 1); + auto snap = ctrl->current(); + Void::Testing::expect_eq(snap.generation, std::uint64_t{1}); + Void::Testing::expect_eq(snap.values->host, std::string{"v1"}); + } + + // Unregister p2 and commit v2 with notification throw isolation + + // post-commit stop observation + restart-required check. + ctrl->unregister_participant("p2"); + ctrl->on_committed( + [](const C::Snapshot&, const C::ReloadReport&) { + throw std::runtime_error("observer failure"); + }); + + std::stop_source ss; + Void::Testing::require( + ctrl->register_participant( + "p_stop", 64, + [&](const C::Snapshot&, + const std::shared_ptr&, + Void::Async::OperationOptions) + -> Void::Coro::Task> { + // Request stop only inside the second reload if flagged. + co_return co_await make_resource_ok("ok", nullptr); + }) + .has_value()); + + { + C::SourceSet s2; + s2.add_defaults_map("d", {{"host", "v2"}, {"port", "9090"}}); + auto r = drive_task(exec, ctrl->reload(std::move(s2))); + Void::Testing::require(r.has_value()); + Void::Testing::expect(r->committed); + Void::Testing::expect_eq(r->generation, std::uint64_t{2}); + Void::Testing::expect_eq(r->notification_errors.size(), std::size_t{1}); + auto snap = ctrl->current(); + auto view = snap.resource("p1"); + Void::Testing::require(view != nullptr); + Void::Testing::expect_eq(*view, std::string{"v2:9090"}); + } + + // Restart-required key change preserves generation 2 and reports pending. + { + C::SourceSet s_rr; + s_rr.add_defaults_map( + "d", {{"host", "v3"}, {"port", "9091"}, {"bind_addr", "127.0.0.1"}}); + auto r = drive_task(exec, ctrl->reload(std::move(s_rr))); + Void::Testing::require(r.has_value()); + Void::Testing::expect(!r->committed); + Void::Testing::expect(r->restart_required); + Void::Testing::expect_eq(r->generation, std::uint64_t{2}); + Void::Testing::expect_eq(ctrl->current().values->host, + std::string{"v2"}); + } + + ctrl->close_and_join(); +} + +// @tag reflection +Void::Testing::Test config_async_retention_precommit_cancel_and_concurrent_order() +{ + auto schema = C::Schema::from_reflection(); + Void::Async::ManualExecutor exec; + + C::SourceSet init; + init.add_defaults_map("d", {{"host", "g1"}, {"port", "8001"}}); + auto ctrl = + C::ReloadController::create(schema, std::move(init), + {.executor = &exec}) + .value(); + + std::vector> pinned; + pinned.push_back(ctrl->current()); // gen 1 + for (int i = 2; i <= 4; ++i) { + C::SourceSet s; + s.add_defaults_map("d", {{"host", "g" + std::to_string(i)}, + {"port", std::to_string(8000 + i)}}); + auto r = drive_task(exec, ctrl->reload(std::move(s))); + Void::Testing::require(r.has_value()); + pinned.push_back(ctrl->current()); + } + Void::Testing::expect_eq(ctrl->retained_generation_count(), std::size_t{4}); + + // 5th generation rejected while 4 snapshots remain pinned. + { + C::SourceSet s5; + s5.add_defaults_map("d", {{"host", "g5"}, {"port", "8005"}}); + auto r5 = drive_task(exec, ctrl->reload(std::move(s5))); + Void::Testing::expect(!r5.has_value()); + Void::Testing::expect_eq( + r5.error().code().value, + static_cast(C::ConfigErrorCode::retention_limit)); + } + + pinned.erase(pinned.begin()); // Drop gen 1 -> 3 live + + // Pre-commit cancellation disposes candidate and preserves gen 4. + std::stop_source ss; + ss.request_stop(); + { + C::SourceSet sc; + sc.add_defaults_map("d", {{"host", "cancel"}, {"port", "8006"}}); + Void::Async::OperationOptions opts; + opts.stop = ss.get_token(); + auto rc = drive_task(exec, ctrl->reload(std::move(sc), opts)); + Void::Testing::expect(!rc.has_value()); + Void::Testing::expect_eq( + rc.error().code().value, + static_cast(C::ConfigErrorCode::cancelled)); + Void::Testing::expect_eq(ctrl->current().values->host, + std::string{"g4"}); + } + + // Concurrent reloads serialize cleanly within the retention budget. + pinned.clear(); + { + C::SourceSet a, b; + a.add_defaults_map("d", {{"host", "c1"}, {"port", "8011"}}); + b.add_defaults_map("d", {{"host", "c2"}, {"port", "8012"}}); + auto both = drive_task( + exec, run_two_reloads_concurrent(ctrl, std::move(a), std::move(b))); + Void::Testing::require(both.has_value()); + Void::Testing::require(both->first.has_value()); + Void::Testing::require(both->second.has_value()); + Void::Testing::expect(both->second->generation > + both->first->generation); + } +} + +// @tag reflection +Void::Testing::Test config_async_watcher_coalescing_and_prepare_external() +{ + Void::FileSystem::TempDir tmp{"void_cfg_async_watch"}; + const auto cfg_path = tmp.path() / "app.json"; + Void::Testing::require( + Void::FileSystem::write_file(cfg_path, R"({"host":"init","port":8080})") + .has_value()); + + auto schema = C::Schema::from_reflection(); + Void::Async::ManualExecutor exec; + Void::Time::ManualClock clock; + Void::SystemAsync::WatcherService watcher{ + exec, + Void::SystemAsync::WatcherLimits{ + .poll_interval = std::chrono::milliseconds{10}, + .debounce_polls = 1}, + clock}; + + auto build_sources = [&]() { + C::SourceSet ss; + ss.add_json_file("app", cfg_path); + return ss; + }; + auto ctrl = + C::ReloadController::create(schema, build_sources(), + {.clock = &clock, + .executor = &exec}) + .value(); + + std::atomic commits{0}; + ctrl->on_committed([&](const C::Snapshot&, + const C::ReloadReport&) { + commits.fetch_add(1, std::memory_order_relaxed); + }); + Void::Testing::require( + ctrl->attach_watcher(watcher, {cfg_path}, build_sources, exec) + .has_value()); + + // Overwrite with invalid JSON first (must keep old), then valid edit. + Void::Testing::require( + Void::FileSystem::write_file(cfg_path, "{broken").has_value()); + watcher.poll_once(); + (void)exec.drain(); + Void::Testing::expect_eq(ctrl->current().values->host, + std::string{"init"}); + + Void::Testing::require( + Void::FileSystem::write_file(cfg_path, + R"({"host":"watched","port":8099})") + .has_value()); + watcher.poll_once(); + (void)exec.drain(); + Void::Testing::expect_eq(ctrl->current().values->host, + std::string{"watched"}); + Void::Testing::expect_eq(ctrl->current().values->port, 8099); + Void::Testing::expect(commits.load() >= 1); + + // Prepare-only external coordinator port leaves controller unchanged. + { + C::SourceSet ext; + ext.add_defaults_map("d", {{"host", "staged_ext"}, {"port", "8111"}}); + auto prep = drive_task(exec, ctrl->prepare_external(std::move(ext))); + Void::Testing::require(prep.has_value()); + Void::Testing::expect_eq(prep->values->host, + std::string{"staged_ext"}); + Void::Testing::expect_eq(ctrl->current().values->host, + std::string{"watched"}); + (void)drive_task(exec, prep->dispose_all()); + } + + ctrl->close_and_join(); + Void::Testing::expect(watcher.shutdown().has_value()); +} From ef5312c4b3138ffd8dbf413e63475b5a15738b61 Mon Sep 17 00:00:00 2001 From: faumaray Date: Thu, 26 Nov 2026 16:51:35 +0300 Subject: [PATCH 5/9] feat(fsm): structured scopes, race-loser join, boundary checkpoints, and bounded supervision --- include/Void/Fsm/Detail/Awaiter.hpp | 99 +- include/Void/Fsm/Detail/Engine.hpp | 195 ++- include/Void/Fsm/Machine.hpp | 1887 ++++++++++++++++++----- include/Void/Fsm/Orchestrator.hpp | 441 +++++- include/Void/Fsm/StateKey.hpp | 159 ++ src/Fsm/Engine.cpp | 401 ++++- src/Fsm/module.cmake | 2 +- tests/package/FsmOnly/CMakeLists.txt | 11 + tests/package/FsmOnly/main.cpp | 47 + tests/package/InstalledComponents.cmake | 10 + tests/standalone/Fsm/FsmHardening.cpp | 1108 +++++++++++++ 11 files changed, 3819 insertions(+), 541 deletions(-) create mode 100644 tests/package/FsmOnly/CMakeLists.txt create mode 100644 tests/package/FsmOnly/main.cpp create mode 100644 tests/standalone/Fsm/FsmHardening.cpp diff --git a/include/Void/Fsm/Detail/Awaiter.hpp b/include/Void/Fsm/Detail/Awaiter.hpp index 88f719a..b675a35 100644 --- a/include/Void/Fsm/Detail/Awaiter.hpp +++ b/include/Void/Fsm/Detail/Awaiter.hpp @@ -1,41 +1,90 @@ #pragma once #include +#include #include #include #include #include +#include #include #include namespace Void::Fsm::Detail { - /// One awaiter for every "wait for an event (optionally with a deadline)" - /// operation on a machine. `Storage` is the type-list container (a - /// std::array for fixed sets, a std::vector for dynamic ones); `Resume` is - /// the projection `(EventEnvelope&&, bool timed_out) -> R` that shapes the - /// awaited value (the matched event, an optional on timeout, a variant, - /// …). Built on ExecutionContext::{try_take_any,set_waiter}. + struct WaiterCancelFn { + ExecutionContext* ctx{nullptr}; + ExecutionContext::WaiterId waiter_id{0}; + + void operator()() const + { + if (ctx != nullptr && waiter_id != 0) { + (void)ctx->try_post_control( + [c = ctx, wid = waiter_id] { c->cancel_waiter(wid); }); + } + } + }; + + /// Unified awaiter for awaiting an event (or event set), optional timeout + /// on injected clock, and cooperative stop cancellation across both + /// per-state scope stop and caller-supplied OperationOptions stop tokens. template struct EventAwaiter { - ExecutionContext* ctx; - Storage types; - EventEnvelope env; + ExecutionContext* ctx{nullptr}; + Storage types{}; + EventEnvelope env{}; bool timed_out{false}; - std::optional deadline; - Resume resume; + bool cancelled{false}; + std::optional deadline{}; + Resume resume{}; + ExecutionContext::ScopeId scope{ExecutionContext::kNoScope}; + std::stop_token scope_stop{}; + std::stop_token user_stop{}; + ExecutionContext::WaiterId waiter_id{0}; + std::optional> scope_cb{}; + std::optional> user_cb{}; [[nodiscard]] bool await_ready() { - return ctx->try_take_any(span(), env); + if (scope_stop.stop_requested() || user_stop.stop_requested()) { + cancelled = true; + return true; + } + if (ctx != nullptr && !types.empty() && + ctx->try_take_any(span(), env)) { + return true; + } + if (deadline.has_value() && ctx != nullptr && + ctx->clock().now() >= *deadline) { + timed_out = true; + return true; + } + return false; } + void await_suspend(std::coroutine_handle<> h) { - ctx->set_waiter(span(), h, &env, &timed_out, deadline); + waiter_id = ctx->set_waiter(span(), h, &env, &timed_out, + deadline, scope, &cancelled); + if (scope_stop.stop_possible()) { + scope_cb.emplace(scope_stop, + WaiterCancelFn{ctx, waiter_id}); + } + if (user_stop.stop_possible()) { + user_cb.emplace(user_stop, WaiterCancelFn{ctx, waiter_id}); + } } - [[nodiscard]] decltype(auto) await_resume() + + decltype(auto) await_resume() { - return resume(std::move(env), timed_out); + scope_cb.reset(); + user_cb.reset(); + if constexpr (std::is_invocable_v) { + return resume(std::move(env), timed_out, cancelled); + } else { + return resume(std::move(env), timed_out); + } } private: @@ -49,10 +98,24 @@ namespace Void::Fsm::Detail template [[nodiscard]] auto make_event_awaiter( ExecutionContext* ctx, Storage types, - std::optional deadline, - Resume resume) + std::optional deadline, + Resume resume, + ExecutionContext::ScopeId scope = ExecutionContext::kNoScope, + std::stop_token scope_stop = {}, std::stop_token user_stop = {}) { return EventAwaiter{ - ctx, std::move(types), {}, false, deadline, std::move(resume)}; + ctx, + std::move(types), + {}, + false, + false, + deadline, + std::move(resume), + scope, + std::move(scope_stop), + std::move(user_stop), + 0, + std::nullopt, + std::nullopt}; } } // namespace Void::Fsm::Detail diff --git a/include/Void/Fsm/Detail/Engine.hpp b/include/Void/Fsm/Detail/Engine.hpp index fbf42da..1734782 100644 --- a/include/Void/Fsm/Detail/Engine.hpp +++ b/include/Void/Fsm/Detail/Engine.hpp @@ -4,6 +4,8 @@ #include #include #include +#include +#include #include #include @@ -14,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -28,17 +31,14 @@ namespace Void::Fsm::Detail { /// Type-erased state. Concrete states derive the single Machine:: /// State base; the engine drives each via a signature-inferred per-state - /// thunk (entry / reactive table / continuation handlers). + /// thunk (entry / continuation handlers). class StateBase { public: virtual ~StateBase() = default; - /// Optional entry/exit lifecycle hooks (default no-ops). The - /// state's behaviour (entry / reactive table / continuation - /// handlers) is discovered by signature via a per-state driver - /// thunk — there is no virtual run(). + /// Optional entry/exit lifecycle hooks (default no-ops). virtual Coro::Task on_enter(); virtual Coro::Task on_exit(); }; @@ -46,18 +46,28 @@ namespace Void::Fsm::Detail struct EventEnvelope { const std::type_info* type{nullptr}; std::any value; + std::size_t bytes{0}; }; /// Shared execution substrate for a machine and any machines it nests: - /// one executor + one worker thread + one typed event mailbox. A single - /// consumer (the worker, or the embedder via pump()) touches all - /// mailbox state, so state code runs lock-free and single-threaded; - /// cross-thread post() only enqueues. + /// one logical strand (owned worker, embedder pump(), or borrowed external + /// executor) + bounded event mailbox + reserved control lane + Clock-driven + /// timers. Cross-thread posts enqueue owned envelopes; only the active + /// consumer strand touches waiter/timer/buffer tables. class ExecutionContext + : public std::enable_shared_from_this { public: - ExecutionContext() = default; + using TimerId = std::uint64_t; + using WaiterId = std::uint64_t; + using ScopeId = std::uint64_t; + static constexpr ScopeId kNoScope = 0; + + explicit ExecutionContext( + const Time::MonotonicClock* clock = nullptr, + FsmLimits limits = {}, + Async::Executor* external_executor = nullptr); ~ExecutionContext(); ExecutionContext(const ExecutionContext&) = delete; @@ -67,14 +77,61 @@ namespace Void::Fsm::Detail { return m_executor; } + [[nodiscard]] Async::Executor& active_executor() noexcept + { + return m_external_executor != nullptr + ? *m_external_executor + : static_cast(m_executor); + } + [[nodiscard]] const Time::MonotonicClock& clock() const noexcept + { + return *m_clock; + } + [[nodiscard]] const FsmLimits& limits() const noexcept + { + return m_limits; + } + [[nodiscard]] std::uint64_t dispatch_turn() const noexcept + { + return m_dispatch_turn; + } + [[nodiscard]] std::size_t last_turn_events() const noexcept + { + return m_last_turn_events; + } + [[nodiscard]] std::size_t queued_events() const noexcept + { + return m_queued_events.load(std::memory_order_acquire); + } + [[nodiscard]] std::size_t queued_bytes() const noexcept + { + return m_queued_bytes.load(std::memory_order_acquire); + } + [[nodiscard]] std::size_t active_child_regions() const noexcept + { + return m_active_child_regions.load(std::memory_order_acquire); + } + [[nodiscard]] std::size_t timer_count() const noexcept + { + return m_timers.size(); + } - // ── events (post is the only cross-thread entry point) ──────── + [[nodiscard]] bool + try_acquire_child_regions(std::size_t count) noexcept; + void release_child_regions(std::size_t count) noexcept; + + // ── events & control (thread-safe entry points) ────────────── + [[nodiscard]] Void::Result::Result + try_post(EventEnvelope env); void post(EventEnvelope env); + [[nodiscard]] Void::Result::Result + try_post_control(std::function fn); - // Mailbox ops — consumer thread only (called from awaiters that - // run on the executor, and from the worker drain). - - using TimerId = std::uint64_t; + // ── strand-only scope/waiter/timer APIs ────────────────────── + [[nodiscard]] ScopeId allocate_scope() noexcept + { + return m_next_scope.fetch_add(1, std::memory_order_relaxed); + } /// Pop the oldest buffered event whose type is in `types`. [[nodiscard]] bool @@ -82,68 +139,66 @@ namespace Void::Fsm::Detail EventEnvelope& out); /// Suspend until an event of one of `types` arrives, or (if - /// `deadline` is set) the deadline passes. `slot` receives the - /// matched event; `*timed_out` is set true on timeout. - void set_waiter( + /// `deadline` is set) the deadline passes, or the waiter/scope is + /// cancelled. + WaiterId set_waiter( std::span types, std::coroutine_handle<> cont, EventEnvelope* slot, bool* timed_out, - std::optional deadline); + std::optional deadline, + ScopeId scope = kNoScope, bool* cancelled = nullptr); - /// Schedule `on_fire` at `deadline`. Returns an id for - /// cancel_timer. - TimerId add_timer(std::chrono::steady_clock::time_point deadline, - std::function - on_fire); + void cancel_waiter(WaiterId id); + void cancel_scope(ScopeId scope); + void purge_scope(ScopeId scope); + void drain_control_queue(); + + /// Schedule `on_fire` at `deadline` (enforces max_timers). + [[nodiscard]] Void::Result::Result + try_add_timer(Time::MonotonicClock::time_point deadline, + std::function on_fire, + ScopeId scope = kNoScope); + TimerId add_timer(Time::MonotonicClock::time_point deadline, + std::function on_fire, + ScopeId scope = kNoScope); void cancel_timer(TimerId id); - // ── worker lifecycle ───────────────────────────────────────── - /// Spawn the worker thread (idempotent). + // ── worker / pump lifecycle ────────────────────────────────── void start_worker(); - /// Mark finished and wake the worker so it can exit. void finish(); - /// Stop and join the worker. void stop(); - /// Join the worker without forcing finish (waits for the - /// driver to finish() on its own). void join(); [[nodiscard]] bool finished() const noexcept { return m_done.load(std::memory_order_acquire); } - /// Embedder-driven step: deliver queued events + run ready - /// coroutines. Returns work done count. Single consumer only. - /// A no-op (returns 0) while paused. + /// Embedder-driven step: drain control lane, fire due timers on + /// injected clock, deliver up to max_events_per_turn / + /// max_turn_duration user events, and drain internal executor. std::size_t pump(); - /// Pause / resume event processing. While paused the worker stops - /// draining (and pump() is a no-op); posted events buffer. - void set_paused(bool paused); + /// Called on external executor threads via scheduled task. + void run_external_pump_step(); - /// Wake the consumer (e.g. to re-check an external jump request). + void set_paused(bool paused); void nudge() { wake(); } private: - void deliver(EventEnvelope& env); - void run_loop(); - void wake() noexcept; - void fire_due_timers(); - [[nodiscard]] std::optional - next_deadline() const; + struct BufferedEvent { + std::any value; + std::size_t bytes{0}; + }; - Async::ManualExecutor m_executor; - Async::MpscQueue m_queue; - - std::unordered_map> m_buffers; - using WaiterId = std::uint64_t; struct Waiter { WaiterId id{0}; + ScopeId scope{kNoScope}; std::vector types; std::coroutine_handle<> cont{}; EventEnvelope* slot{nullptr}; bool* timed_out{nullptr}; + bool* cancelled{nullptr}; TimerId timer{0}; [[nodiscard]] bool wants(const std::type_info& t) const @@ -156,20 +211,52 @@ namespace Void::Fsm::Detail return false; } }; - // Several waiters can be parked at once (parallel regions, deferred - // events). An event resumes the first (FIFO) that wants its type. + + struct Timer { + Time::MonotonicClock::time_point deadline; + std::function on_fire; + ScopeId scope{kNoScope}; + }; + + void deliver(EventEnvelope& env); + void run_loop(); + void wake() noexcept; + void schedule_external_pump() noexcept; + void fire_due_timers(); + [[nodiscard]] std::optional + next_deadline() const; + + const Time::MonotonicClock* m_clock; + FsmLimits m_limits; + Async::Executor* m_external_executor{nullptr}; + Async::ManualExecutor m_executor; + + Async::MpscQueue m_queue; + std::atomic m_queued_events{0}; + std::atomic m_queued_bytes{0}; + + Async::MpscQueue> m_control_queue; + std::atomic m_queued_control{0}; + + std::unordered_map> + m_buffers; + std::size_t m_buffered_events{0}; + std::size_t m_buffered_bytes{0}; + std::vector m_waiters; WaiterId m_next_waiter{1}; - struct Timer { - std::chrono::steady_clock::time_point deadline; - std::function on_fire; - }; std::map m_timers; TimerId m_next_timer{1}; + std::atomic m_next_scope{1}; + std::atomic m_active_child_regions{0}; + std::uint64_t m_dispatch_turn{0}; + std::size_t m_last_turn_events{0}; + std::counting_semaphore<> m_wakeup{0}; std::atomic m_sleeping{false}; + std::atomic m_pump_scheduled{false}; std::atomic m_done{false}; std::atomic m_paused{false}; std::atomic m_worker_started{false}; diff --git a/include/Void/Fsm/Machine.hpp b/include/Void/Fsm/Machine.hpp index 13ecb24..db9372e 100644 --- a/include/Void/Fsm/Machine.hpp +++ b/include/Void/Fsm/Machine.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include #include @@ -11,20 +12,28 @@ #include #include #include +#include #include #include +#include +#include #include #include #include #include #include #include +#include +#include #include #include #include #include +#include #include +#include +#include #include #include #include @@ -43,6 +52,50 @@ namespace Void::Fsm { + namespace Detail + { + struct CancelledException final : std::exception { + const char* what() const noexcept override + { + return "fsm operation cancelled"; + } + }; + + struct YieldAwaiter { + Async::Executor* exec{nullptr}; + + [[nodiscard]] bool await_ready() const noexcept + { + return exec == nullptr; + } + void await_suspend(std::coroutine_handle<> h) const + { + exec->post(h); + } + void await_resume() const noexcept {} + }; + + struct LatchResumeAwaiter { + bool ready{false}; + std::function)> arm{}; + + [[nodiscard]] bool await_ready() const noexcept { return ready; } + void await_suspend(std::coroutine_handle<> h) const + { + arm(h); + } + void await_resume() const noexcept {} + }; + + [[nodiscard]] inline std::size_t + estimate_checkpoint_bytes(const Checkpoint& cp) + { + return cp.machine_type.size() + cp.state_id.size() + + cp.resume_label.size() + + Void::Json::serialize(cp.state).size() + 64; + } + } // namespace Detail + /// Options for a Machine (namespace scope to dodge the GCC /// nested-default-arg trap). struct MachineOptions { @@ -53,7 +106,7 @@ namespace Void::Fsm /// at the sub-state it last reached (shallow history). enum class Resume { Initial, History }; - /// A transition record handed to observers. + /// A transition record handed to observers and stored in bounded history. struct Transition { std::string from; std::string to; @@ -61,48 +114,12 @@ namespace Void::Fsm }; // ── Machine ────────────────────────────────────────────────── - // - // Inheritance + coroutine workflow FSM, CRTP for typed access. Derive it - // and declare the states as a nested struct of forward declarations: - // struct States { struct FirstState; struct SecondState; … }; - // defined out-of-line (typically in a .cpp), each deriving the single - // `State`. The Machine base auto-registers them by reflecting `States` - // (Detail/StateList.hpp) — the first declared state is the initial one - // unless `using Initial = S;`. All behaviour lives inside a state: the - // engine infers each state's role from its member signatures (entry / - // startup-entry / continuation handlers); states reach their machine (data - // + sub-methods) via self(). Events are handled imperatively inside an - // entry (co_await await_event()) — there is no declarative transition - // table. Result types are the nested `Success`/`Failure` (default void). - // - // // header - // class Login : public Void::Fsm::Machine { - // public: - // using Success = Token; - // int attempts = 0; - // struct States { struct Check; }; - // }; - // // source (namespace scope) - // struct Login::States::Check : Login::State { // entry by signature - // Coro::Task> run() { - // if (++self().attempts > 3) co_return fail(); - // co_return self().service().ok() ? succeed(Token{}) - // : next(); - // } - // }; template class Machine { public: using Options = MachineOptions; - // Result types are reflected by name from Derived's nested - // `Success`/`Failure` (default void). Because Derived is incomplete - // at base instantiation (CRTP), they cannot appear in member - // signatures or data members — only inside function templates / - // bodies, where Derived is complete. So these are alias *templates* - // (lazily resolved), the engine stores outcomes type-erased, and - // the typed Outcome is rebuilt in wait()/take_outcome(). template using Success = Detail::SuccessOf; template @@ -110,12 +127,15 @@ namespace Void::Fsm template using Outcome = Detail::OutcomeOf; + using MigrationFn = std::function( + std::uint32_t from_schema, std::uint32_t to_schema, + Json::Value& data, std::string& state_id)>; + // ── State base ──────────────────────────────────────────────── class State : public Detail::StateBase { public: - /// Typed access to the owning machine — no static_cast. [[nodiscard]] Derived& self() const noexcept { return *static_cast(m_machine); @@ -128,8 +148,6 @@ namespace Void::Fsm protected: - /// Transition to another state. Validated at compile - /// time when the machine declares a `States` list. template [[nodiscard]] StateKey next() const { if constexpr (requires { typename Derived::States; }) { @@ -141,28 +159,18 @@ namespace Void::Fsm return StateKey::transition(typeid(S)); } - /// Transition to a state registered dynamically - /// (add()/add_if()), skipping the static check. template [[nodiscard]] StateKey next_dynamic() const { return StateKey::transition(typeid(S)); } - /// Free jump to any registered state — no declared - /// transition required ("each state can be moved to - /// another state"). Like next_dynamic, skips the - /// States{ … } compile-time check; runtime-fails only if S - /// was never registered. template [[nodiscard]] StateKey goto_state() const { return StateKey::transition(typeid(S)); } - /// Route to a fallback state if `step` is a failure, - /// otherwise pass it through — for error policies: - /// co_return next_or(co_await try_work()); template [[nodiscard]] StateKey next_or(StateKey step) const { @@ -172,7 +180,6 @@ namespace Void::Fsm return step; } - /// Suspend for `duration` (timer-driven), then resume. template [[nodiscard]] auto delay(std::chrono::duration d) const @@ -180,15 +187,18 @@ namespace Void::Fsm return m_machine->delay(d); } - /// Retry an async sub-step up to `times`, waiting - /// `backoff` between attempts. `attempt` returns - /// Coro::Task (true = success). Returns whether it - /// eventually succeeded. + template + [[nodiscard]] auto delay_cancellable( + std::chrono::duration d, + Async::OperationOptions opts = {}) const + { + return m_machine->delay_cancellable(d, std::move(opts)); + } + template [[nodiscard]] Coro::Task with_retry(int times, - std::chrono::duration - backoff, + std::chrono::duration backoff, Fn attempt) const { for (int i = 0; i < times; ++i) { @@ -202,8 +212,6 @@ namespace Void::Fsm co_return false; } - /// Finish with the machine's typed Success result (nested - /// `Success`; nullary when it is void). [[nodiscard]] StateKey succeed() const requires std::is_void_v> { @@ -218,8 +226,6 @@ namespace Void::Fsm std::forward(value))}); } - /// Finish with the machine's typed Failure result (nested - /// `Failure`; nullary when it is void). [[nodiscard]] StateKey fail() const requires std::is_void_v> { @@ -239,12 +245,25 @@ namespace Void::Fsm return m_machine->template service(); } + /// Resolve a service handle that keeps the provider alive + /// across coroutine suspension / hot reload. + template + [[nodiscard]] Void::Result::Result> + acquire_service() const + { + return m_machine->template acquire_service(); + } + + [[nodiscard]] std::stop_token state_stop_token() const noexcept + { + return m_machine->state_stop_token(); + } + template [[nodiscard]] auto await_event() const { return m_machine->template await_event(); } - /// Await E or time out (nullopt on timeout). template [[nodiscard]] auto await_event_for( std::chrono::duration d) const @@ -252,6 +271,26 @@ namespace Void::Fsm return m_machine->template await_event_for(d); } + template + [[nodiscard]] auto await_event_cancellable( + Async::OperationOptions opts = {}) const + { + return m_machine->template await_event_cancellable( + std::move(opts)); + } + + [[nodiscard]] Coro::Task + safe_point(std::string_view resume_label = {}) const + { + return m_machine->safe_point(resume_label); + } + + [[nodiscard]] std::string_view + restored_resume_label() const noexcept + { + return m_machine->restored_resume_label(); + } + template [[nodiscard]] auto run_child(Args&&... args) const { @@ -259,13 +298,6 @@ namespace Void::Fsm std::forward(args)...); } - /// Enter a child region (composite sub-state): a nested - /// machine sharing this machine's executor, event mailbox - /// and services. This state's on_enter/on_exit wrap it, and - /// state_path() reports the parent→child chain while it - /// runs. Map the child's Outcome to a sibling transition: - /// auto r = co_await run_region(); - /// co_return r ? next() : next(); template [[nodiscard]] auto run_region(Resume resume = Resume::Initial) const @@ -273,42 +305,38 @@ namespace Void::Fsm return m_machine->template run_region(resume); } - /// Orthogonal regions: run `Subs...` concurrently on the - /// shared executor and join all, yielding a - /// std::tuple (children share events/ - /// services; map the tuple to a sibling transition). template [[nodiscard]] auto run_parallel() const { return m_machine->template run_parallel(); } - /// Race orthogonal regions: resolve on the first to finish, - /// yielding std::variant (losers keep - /// running cooperatively). template [[nodiscard]] auto run_parallel_any() const { return m_machine->template run_parallel_any(); } - /// Await whichever of several event types arrives first, - /// yielding a std::variant. Handles multiple events - /// at one level (e.g. a parent watching Cancel alongside a - /// child region's own events). + template + [[nodiscard]] auto run_parallel_structured() const + { + return m_machine + ->template run_parallel_structured(); + } + + template + [[nodiscard]] auto run_parallel_any_structured() const + { + return m_machine + ->template run_parallel_any_structured(); + } + template [[nodiscard]] auto await_any() const { return m_machine->template await_any(); } - /// Launch a sub-machine `Sub` (startup data routed to its - /// initial-state startup-entry; shares this machine's - /// executor/events/services), then transition to `Next`. - /// When Sub finishes the engine calls Next's signature - /// -matched handler — a member taking `ChildSuccess` - /// (Sub succeeded) or `ChildFailure` (Sub failed): - /// co_return startMachine(seed); template [[nodiscard]] StateKey startMachine(Args&&... args) const { @@ -327,31 +355,6 @@ namespace Void::Fsm Machine* m_machine{nullptr}; }; - // ── one State, signature-inferred roles ─────────────────────── - // - // There is a single base, `State`. The engine infers what each - // state does from member signatures (no `override`, no fixed - // names): - // - entry : a member returning - // State/Coro::Task>, - // no params (a startup-data overload may take - // the sub's startup argument); - // - continuation : members taking `ChildSuccess` / - // `ChildFailure` (the sub's typed result, read - // via .as(), after `startMachine`). - // - // Events are handled imperatively inside an entry: - // struct Idle : State { // entry - // Coro::Task run() { - // auto e = co_await await_any(); - // co_return std::holds_alternative(e) ? next() - // : next(); } - // }; - // struct After : State { // continuation - // Coro::Task ok(ChildSuccess s){ ... } - // Coro::Task no(ChildFailure f){ ... } }; - // ── construction ────────────────────────────────────────────── explicit Machine(Options options = {}) : m_options(options) { @@ -370,7 +373,7 @@ namespace Void::Fsm Machine(const Machine&) = delete; Machine& operator=(const Machine&) = delete; - // ── registration ────────────────────────────────────────────── + // ── registration & durable identities ───────────────────────── template void add() { static_assert(std::is_base_of_v, @@ -384,13 +387,17 @@ namespace Void::Fsm m_index.emplace(key, idx); m_names.push_back(state_name()); m_name_to_type.emplace(m_names.back(), &ti); + std::string durable = default_state_id(m_names.back()); + m_type_to_id.emplace(key, durable); + if (!m_id_to_type.contains(durable)) { + m_id_to_type.emplace(std::move(durable), &ti); + } m_factories.emplace( key, [this]() -> std::unique_ptr { auto s = std::make_unique(); s->m_machine = this; return s; }); - // Signature-inferred driver thunk (runs the state's entry). m_drivers.emplace(key, Detail::make_driver()); } @@ -412,22 +419,18 @@ namespace Void::Fsm return m_factories.contains(std::type_index{typeid(S)}); } - /// Make `S` the initial state (registers it if needed). Idle-only. template void set_initial() { - if (m_status.load() != Status::Idle) { + if (m_status.load(std::memory_order_acquire) != Status::Idle) { return; } add(); m_initial = &typeid(S); } - /// Unregister a state. Idle-only (running indices are fixed). If it - /// was the initial state, the initial falls back to the first - /// remaining state (or none). template void remove() { - if (m_status.load() != Status::Idle) { + if (m_status.load(std::memory_order_acquire) != Status::Idle) { return; } const std::type_index key{typeid(S)}; @@ -437,11 +440,15 @@ namespace Void::Fsm } const int idx = idxIt->second; m_name_to_type.erase(m_names[static_cast(idx)]); + if (const auto idIt = m_type_to_id.find(key); + idIt != m_type_to_id.end()) { + m_id_to_type.erase(idIt->second); + m_type_to_id.erase(idIt); + } m_names.erase(m_names.begin() + idx); m_factories.erase(key); m_drivers.erase(key); m_index.erase(idxIt); - // Re-pack the indices of states that followed S. for (auto& [k, v] : m_index) { if (v > idx) { --v; @@ -454,11 +461,9 @@ namespace Void::Fsm } } - /// Swap state `S` for `T`, preserving the initial pointer if S was - /// it. Idle-only. template void replace() { - if (m_status.load() != Status::Idle) { + if (m_status.load(std::memory_order_acquire) != Status::Idle) { return; } const bool was_initial = (m_initial == &typeid(S)); @@ -469,6 +474,64 @@ namespace Void::Fsm } } + /// Assign an explicit durable state identifier (used in checkpoints) + /// while Idle. Rejects empty or colliding IDs. + template + [[nodiscard]] Void::Result::Result + register_state_id(std::string durable_id) + { + if (m_status.load(std::memory_order_acquire) != Status::Idle) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_state, + "register_state_id requires Idle machine")); + } + if (durable_id.empty()) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_argument, + "register_state_id: empty id")); + } + const std::type_index key{typeid(S)}; + if (!m_factories.contains(key)) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::not_found, + "register_state_id: state not registered")); + } + if (const auto existing = m_id_to_type.find(durable_id); + existing != m_id_to_type.end() && + existing->second != &typeid(S)) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_argument, + "register_state_id: duplicate durable id '" + + durable_id + "'")); + } + if (const auto prev = m_type_to_id.find(key); + prev != m_type_to_id.end()) { + m_id_to_type.erase(prev->second); + } + m_id_to_type.insert_or_assign(durable_id, &typeid(S)); + m_type_to_id.insert_or_assign(key, std::move(durable_id)); + return {}; + } + + void set_machine_identity(std::string machine_type, + std::uint32_t application_schema = 1) + { + if (m_status.load(std::memory_order_acquire) != Status::Idle) { + return; + } + m_machine_type = std::move(machine_type); + m_application_schema = application_schema; + } + + void set_limits(FsmLimits limits) + { + if (m_status.load(std::memory_order_acquire) != Status::Idle) { + return; + } + m_limits = limits; + m_has_explicit_limits = true; + } + // ── service context ─────────────────────────────────────────── void set_services(Service::ServiceRegistry& registry) noexcept { @@ -480,42 +543,77 @@ namespace Void::Fsm return m_services->template require(); } + template + [[nodiscard]] Void::Result::Result> + acquire_service() const + { + if (m_services == nullptr) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::service_unavailable, + "Machine::acquire_service: no ServiceRegistry bound")); + } + auto r = m_services->template acquire(); + if (!r) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::service_unavailable, + r.error().message())); + } + return r; + } + // ── observability ───────────────────────────────────────────── - /// Register a read-only observer fired on every transition - /// (and on the initial entry). Replaces any prior observer. void observe(std::function observer) { + std::lock_guard lk{m_obs_mu}; m_observer = std::move(observer); } - /// Transition middleware. `before(transition)` fires as a state - /// is entered (after the state changes, before it runs); - /// `after(state_name)` fires once that state finishes running. - /// Interceptors run in registration order — for logging, - /// metrics, validation around transitions. struct Interceptor { std::function before; std::function after; }; void add_interceptor(Interceptor interceptor) { + std::lock_guard lk{m_obs_mu}; m_interceptors.push_back(std::move(interceptor)); } + [[nodiscard]] std::vector transition_history() const + { + std::lock_guard lk{m_obs_mu}; + return {m_transition_history.begin(), + m_transition_history.end()}; + } + + [[nodiscard]] std::vector observer_errors() const + { + std::lock_guard lk{m_obs_mu}; + return m_observer_errors; + } + // ── lifecycle ───────────────────────────────────────────────── void start() { - if (m_status.load() != Status::Idle) { + if (m_status.load(std::memory_order_acquire) != Status::Idle) { return; } if (!m_ctx) { - m_ctx = std::make_shared(); + FsmLimits start_limits = m_limits; + if (!m_has_explicit_limits) { + start_limits.max_mailbox_events = 0; + start_limits.max_mailbox_bytes = 0; + start_limits.max_deferred_events = 0; + } + m_ctx = std::make_shared( + &Time::SystemMonotonicClock::instance(), start_limits, + nullptr); m_owns_ctx = true; } - m_status.store(Status::Running); - // Own the driver coroutine (rather than detaching it) so a - // machine stopped while parked on an event can destroy the - // suspended frame chain instead of leaking it. + m_termination_reason.store(TerminationReason::none, + std::memory_order_release); + m_root_stop.emplace(); + m_root_timeout.store(false, std::memory_order_release); + m_status.store(Status::Running, std::memory_order_release); m_driver.emplace(driver()); m_ctx->executor().post(m_driver->handle()); if (m_options.own_worker && m_owns_ctx) { @@ -523,8 +621,114 @@ namespace Void::Fsm } } - // Function templates so the typed Outcome resolves where Derived is - // complete (CRTP). Call sites stay `fsm.wait()` / `run_blocking()`. + /// Explicit structured async execution on borrowed executor & clock. + template + [[nodiscard]] Coro::Task>> + run(ExecutionBinding binding, + Async::OperationOptions opts = {}) + { + if (m_status.load(std::memory_order_acquire) != Status::Idle) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_state, + "Machine::run: machine must be Idle")); + } + if (binding.limits.max_events_per_turn == 0 || + binding.limits.max_mailbox_events == 0 || + binding.limits.max_hierarchy_depth == 0 || + binding.limits.max_child_regions == 0) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_argument, + "Machine::run: limits must be non-zero")); + } + + const auto* clk = binding.clock != nullptr + ? binding.clock + : &Time::SystemMonotonicClock::instance(); + if (opts.stop.stop_requested()) { + m_termination_reason.store(TerminationReason::cancelled, + std::memory_order_release); + fault("cancelled before start"); + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::cancelled, + "Machine::run: cancelled before start")); + } + if (opts.deadline.has_value() && clk->now() >= *opts.deadline) { + m_termination_reason.store(TerminationReason::timed_out, + std::memory_order_release); + fault("deadline expired before start"); + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::timeout, + "Machine::run: deadline expired before start")); + } + + m_limits = binding.limits; + m_ctx = std::make_shared( + clk, binding.limits, binding.executor); + m_owns_ctx = true; + m_termination_reason.store(TerminationReason::none, + std::memory_order_release); + m_root_timeout.store(false, std::memory_order_release); + m_root_stop.emplace(); + + std::optional>> + ext_stop_cb; + if (opts.stop.stop_possible()) { + ext_stop_cb.emplace(opts.stop, [this] { + if (m_root_stop) { + m_root_stop->request_stop(); + } + }); + } + + Detail::ExecutionContext::TimerId deadline_timer = 0; + if (opts.deadline.has_value()) { + auto t = m_ctx->try_add_timer(*opts.deadline, [this] { + m_root_timeout.store(true, std::memory_order_release); + if (m_root_stop) { + m_root_stop->request_stop(); + } + }); + if (t) { + deadline_timer = *t; + } + } + + m_status.store(Status::Running, std::memory_order_release); + co_await drive(); + + if (deadline_timer != 0 && m_ctx) { + m_ctx->cancel_timer(deadline_timer); + } + ext_stop_cb.reset(); + if (m_owns_ctx && m_ctx) { + m_ctx->finish(); + } + + const auto st = m_status.load(std::memory_order_acquire); + const auto reason = + m_termination_reason.load(std::memory_order_acquire); + if (reason == TerminationReason::timed_out || + m_root_timeout.load(std::memory_order_acquire)) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::timeout, + m_system_error ? m_system_error->message + : std::string{"fsm run timed out"})); + } + if (reason == TerminationReason::cancelled) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::cancelled, + m_system_error ? m_system_error->message + : std::string{"fsm run cancelled"})); + } + if (st == Status::Faulted) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::fault, + m_system_error ? m_system_error->message + : std::string{"fsm system fault"})); + } + co_return take_outcome(); + } + template Outcome wait() { if (m_ctx) { @@ -547,8 +751,6 @@ namespace Void::Fsm return wait(); } - /// The system fault (if any) — a programming error caught by the - /// engine, separate from a typed Failure result. [[nodiscard]] std::optional system_error() const { return m_system_error; @@ -558,59 +760,81 @@ namespace Void::Fsm [[nodiscard]] bool finished() const noexcept { - const auto s = m_status.load(); - return s == Status::Succeeded || s == Status::Failed || - s == Status::Faulted; + return terminal(m_status.load(std::memory_order_acquire)); } [[nodiscard]] Status status() const noexcept { - return m_status.load(); + return m_status.load(std::memory_order_acquire); + } + + [[nodiscard]] TerminationReason + termination_reason() const noexcept + { + return m_termination_reason.load(std::memory_order_acquire); + } + + [[nodiscard]] Detail::ExecutionContext* + execution_context() noexcept + { + return m_ctx.get(); + } + + [[nodiscard]] Detail::ExecutionContext::ScopeId + active_scope() const noexcept + { + return m_active_scope; } void stop() { + if (m_root_stop) { + m_root_stop->request_stop(); + } if (m_owns_ctx && m_ctx) { m_ctx->stop(); } - // The worker is joined now (no concurrent resume), so destroy - // the owned driver — this cascade-destroys the suspended - // coroutine chain (a machine parked on an event) instead of - // leaking it. Safe on a finished coroutine too. m_driver.reset(); } - /// Return a finished (or idle) machine to Idle so it can run - /// again: drops the owned execution context, clears the - /// outcome/current-state/jump. No-op while Running. void reset() { - if (m_status.load() == Status::Running) { + if (m_status.load(std::memory_order_acquire) == Status::Running) { return; } if (m_owns_ctx && m_ctx) { m_ctx->stop(); } - m_driver.reset(); // destroy the (possibly parked) driver chain + m_driver.reset(); m_ctx.reset(); m_owns_ctx = false; m_current.store(-1, std::memory_order_release); m_result_value.reset(); m_system_error.reset(); m_pending_result.reset(); + m_pending_dispatch = nullptr; m_jump.store(nullptr, std::memory_order_release); m_step = 0; + m_restored_resume_label.clear(); + m_root_stop.reset(); + m_root_timeout.store(false, std::memory_order_release); + m_termination_reason.store(TerminationReason::none, + std::memory_order_release); + { + std::lock_guard lk{m_obs_mu}; + m_transition_history.clear(); + m_observer_errors.clear(); + } + m_pending_checkpoints.clear(); m_status.store(Status::Idle, std::memory_order_release); } - /// reset() then start() from the initial state. void restart() { reset(); start(); } - /// reset(), make `S` the initial state, then start(). template void restart_at() { reset(); @@ -618,9 +842,6 @@ namespace Void::Fsm start(); } - /// Pause / resume event processing (best-effort: a state already - /// running finishes; further progress waits). Events posted while - /// paused buffer until resume(). void pause() { if (m_ctx) { @@ -635,17 +856,41 @@ namespace Void::Fsm } // ── events ──────────────────────────────────────────────────── + template + [[nodiscard]] Void::Result::Result + try_post(E event, Async::OperationOptions opts = {}) + { + if (opts.stop.stop_requested()) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::cancelled, + "Machine::try_post: cancelled")); + } + if (!m_ctx) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_state, + "Machine::try_post: machine not started")); + } + if (opts.deadline.has_value() && + m_ctx->clock().now() >= *opts.deadline) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::timeout, + "Machine::try_post: deadline expired")); + } + const std::size_t bytes = event_payload_bytes(event); + return m_ctx->try_post(Detail::EventEnvelope{ + &typeid(E), std::any{std::move(event)}, bytes}); + } + template void post(E event) { if (!m_ctx) { return; } - m_ctx->post(Detail::EventEnvelope{&typeid(E), - std::any{std::move(event)}}); + const std::size_t bytes = event_payload_bytes(event); + m_ctx->post(Detail::EventEnvelope{ + &typeid(E), std::any{std::move(event)}, bytes}); } - /// Re-post an already type-erased event (used by the reactive loop - /// to re-inject deferred events after a transition). void repost(Detail::EventEnvelope env) { if (m_ctx) { @@ -653,79 +898,119 @@ namespace Void::Fsm } } - /// Fluent post: send one or several events in one call. - /// fsm.send(Go{5}); fsm.send(Go{5}, Stop{}); template void send(Es&&... events) { (post(std::forward(events)), ...); } - /// Request a jump to any registered state `S` from outside the - /// machine. Race-safe; applied at the next transition boundary - /// (a running state isn't preempted — coroutines aren't - /// interruptible mid-flight). template void jump() { m_jump.store(&typeid(S), std::memory_order_release); if (m_ctx) { + (void)m_ctx->try_post_control([] {}); m_ctx->nudge(); } } - template [[nodiscard]] auto await_event() + [[nodiscard]] std::stop_token state_stop_token() const noexcept { + if (m_active_state_stop != nullptr) { + return m_active_state_stop->get_token(); + } + if (m_root_stop.has_value()) { + return m_root_stop->get_token(); + } + return {}; + } + + template [[nodiscard]] auto await_event() + { + const std::stop_token st = state_stop_token(); return Detail::make_event_awaiter( m_ctx.get(), std::array{&typeid(E)}, std::nullopt, - [](Detail::EventEnvelope&& env, bool) { + [](Detail::EventEnvelope&& env, bool, bool cancelled) { + if (cancelled) { + throw Detail::CancelledException{}; + } return std::any_cast(std::move(env.value)); - }); + }, + m_active_scope, st); } - /// Await an event of type E or time out after `duration`; - /// returns std::nullopt on timeout. template [[nodiscard]] auto await_event_for(std::chrono::duration duration) { + const auto now = m_ctx != nullptr + ? m_ctx->clock().now() + : std::chrono::steady_clock::now(); + const std::stop_token st = state_stop_token(); return Detail::make_event_awaiter( - m_ctx.get(), std::array{&typeid(E)}, - std::chrono::steady_clock::now() + duration, - [](Detail::EventEnvelope&& env, - bool timed_out) -> std::optional { + m_ctx.get(), std::array{&typeid(E)}, now + duration, + [](Detail::EventEnvelope&& env, bool timed_out, + bool cancelled) -> std::optional { + if (cancelled) { + throw Detail::CancelledException{}; + } if (timed_out) { return std::nullopt; } return std::any_cast(std::move(env.value)); - }); + }, + m_active_scope, st); + } + + template + [[nodiscard]] auto + await_event_cancellable(Async::OperationOptions opts = {}) + { + return Detail::make_event_awaiter( + m_ctx.get(), std::array{&typeid(E)}, opts.deadline, + [](Detail::EventEnvelope&& env, bool timed_out, + bool cancelled) -> Void::Result::Result { + if (cancelled) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::cancelled, + "await_event_cancellable: cancelled")); + } + if (timed_out) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::timeout, + "await_event_cancellable: deadline expired")); + } + return std::any_cast(std::move(env.value)); + }, + m_active_scope, state_stop_token(), opts.stop); } - /// Await any of several event types (optional deadline); used - /// by reactive states. Returns the matched envelope or nullopt - /// on timeout. [[nodiscard]] auto await_any_event( std::vector types, - std::optional deadline) + std::optional deadline) { return Detail::make_event_awaiter( m_ctx.get(), std::move(types), deadline, - [](Detail::EventEnvelope&& env, - bool timed_out) -> std::optional { + [](Detail::EventEnvelope&& env, bool timed_out, + bool cancelled) -> std::optional { + if (cancelled) { + throw Detail::CancelledException{}; + } if (timed_out) { return std::nullopt; } return std::move(env); - }); + }, + m_active_scope, state_stop_token()); } - /// Typed multi-event await: suspend until one of `Es...` arrives, - /// returning it as std::variant. Lets one state react to - /// several event types (parent-level handling for child regions). template [[nodiscard]] auto await_any() { return Detail::make_event_awaiter( m_ctx.get(), std::array{(&typeid(Es))...}, std::nullopt, - [](Detail::EventEnvelope&& env, - bool) -> std::variant { + [](Detail::EventEnvelope&& env, bool, + bool cancelled) -> std::variant { + if (cancelled) { + throw Detail::CancelledException{}; + } std::optional> out; ((env.type != nullptr && *env.type == typeid(Es) ? (out.emplace( @@ -735,31 +1020,72 @@ namespace Void::Fsm : false) || ...); return std::move(*out); - }); + }, + m_active_scope, state_stop_token()); } - /// Suspend for `duration`, then resume (timer-driven). template [[nodiscard]] auto delay(std::chrono::duration d) { - struct Awaiter { - Detail::ExecutionContext* ctx; - std::chrono::steady_clock::time_point deadline; + const auto now = m_ctx != nullptr + ? m_ctx->clock().now() + : std::chrono::steady_clock::now(); + return Detail::make_event_awaiter( + m_ctx.get(), std::array{}, + now + d, + [](Detail::EventEnvelope&&, bool, bool cancelled) { + if (cancelled) { + throw Detail::CancelledException{}; + } + }, + m_active_scope, state_stop_token()); + } - [[nodiscard]] bool await_ready() const noexcept - { - return false; + template + [[nodiscard]] auto delay_cancellable( + std::chrono::duration d, + Async::OperationOptions opts = {}) + { + const auto now = m_ctx != nullptr + ? m_ctx->clock().now() + : std::chrono::steady_clock::now(); + auto deadline = now + d; + if (opts.deadline.has_value() && *opts.deadline < deadline) { + deadline = *opts.deadline; + } + return Detail::make_event_awaiter( + m_ctx.get(), std::array{}, + deadline, + [](Detail::EventEnvelope&&, bool, + bool cancelled) -> Void::Result::Result { + if (cancelled) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::cancelled, + "delay_cancellable: cancelled")); } - void await_suspend(std::coroutine_handle<> h) - { - ctx->add_timer(deadline, [c = ctx, h] { - c->executor().post(h); - }); - } - void await_resume() const noexcept {} - }; - return Awaiter{m_ctx.get(), - std::chrono::steady_clock::now() + d}; + return {}; + }, + m_active_scope, state_stop_token(), opts.stop); + } + + /// Application-declared safe point inside a running state: yields + /// one turn to let pending checkpoint requests serialize cleanly. + [[nodiscard]] Coro::Task + safe_point(std::string_view resume_label = {}) + { + if (m_ctx == nullptr) { + co_return; + } + co_await Detail::YieldAwaiter{&m_ctx->active_executor()}; + m_ctx->drain_control_queue(); + fulfill_pending_checkpoints(current_durable_id(), + std::string{resume_label}); + } + + [[nodiscard]] const std::string& + restored_resume_label() const noexcept + { + return m_restored_resume_label; } // ── nesting ─────────────────────────────────────────────────── @@ -768,24 +1094,16 @@ namespace Void::Fsm run_child(Args&&... args) { Sub child{std::forward(args)...}; - child.attach(m_ctx, m_services); + child.attach(m_ctx, m_services, m_depth + 1, m_active_state_stop); co_await child.drive(); co_return child.template take_outcome(); } - /// Composite sub-state: run `Sub` as a child region sharing this - /// machine's executor, event mailbox and services, and expose its - /// active state through this machine's state_path() while it runs - /// (parent→child chain). Returns the child's Outcome, which the - /// caller maps to a sibling transition. The calling state's - /// on_enter/on_exit naturally wrap the region. template [[nodiscard]] Coro::Task> run_region(Resume resume = Resume::Initial) { Sub child; - // History: resume at the sub-state this region last reached. - // restore() must run before attach() (which marks Running). if (resume == Resume::History) { const auto it = m_region_history.find(std::type_index{typeid(Sub)}); @@ -793,70 +1111,57 @@ namespace Void::Fsm (void)child.restore(it->second); } } - child.attach(m_ctx, m_services); + child.attach(m_ctx, m_services, m_depth + 1, m_active_state_stop); m_region_probe = [&child] { return child.state_path(); }; co_await child.drive(); m_region_probe = nullptr; - // Snapshot the leaf it reached for a later History re-entry. m_region_history[std::type_index{typeid(Sub)}] = child.serialize(); co_return child.template take_outcome(); } - /// Orthogonal regions: run `Subs...` concurrently on the shared - /// executor (interleaved — when one parks on an event, another - /// runs) and join all, yielding a tuple of their Outcomes. Children - /// are default-constructed and share this machine's - /// events/services. template [[nodiscard]] Coro::Task...>> run_parallel() { auto children = std::make_unique>(); std::apply( - [&](auto&... c) { (c.attach(m_ctx, m_services), ...); }, + [&](auto&... c) { + (c.attach(m_ctx, m_services, m_depth + 1, + m_active_state_stop), + ...); + }, *children); struct Latch { int remaining; std::coroutine_handle<> waiter{}; Async::Executor* exec; - void arrive() + void arrive(std::size_t, Status, + std::optional) { if (--remaining == 0 && waiter) { - exec->post(waiter); + exec->post_completion(waiter); } } }; auto latch = std::make_shared( static_cast(sizeof...(Subs)), - std::coroutine_handle<>{}, &m_ctx->executor()); + std::coroutine_handle<>{}, &m_ctx->active_executor()); + std::size_t idx = 0; std::apply( [&](auto&... c) { - (Async::spawn(m_ctx->executor(), - [](auto& child, std::shared_ptr l) - -> Coro::Task { - co_await child.drive(); - l->arrive(); - }(c, latch)), + (Async::spawn( + m_ctx->active_executor(), + drive_child_task(&c, latch, idx++)), ...); }, *children); - struct Awaiter { - std::shared_ptr latch; - [[nodiscard]] bool await_ready() const noexcept - { - return latch->remaining == 0; - } - void await_suspend(std::coroutine_handle<> h) const - { - latch->waiter = h; - } - void await_resume() const noexcept {} - }; - co_await Awaiter{latch}; + co_await Detail::LatchResumeAwaiter{ + latch->remaining == 0, + [latch](std::coroutine_handle<> h) { latch->waiter = h; }}; co_return std::apply( [](auto&... c) { @@ -866,75 +1171,52 @@ namespace Void::Fsm *children); } - /// Like run_parallel but resolves on the **first** child to finish, - /// yielding a std::variant holding the winner's - /// outcome. The losers keep running cooperatively (coroutines - /// aren't preemptible) — the children are kept alive by the spawned - /// tasks until they finish, so a loser parked forever leaks its - /// frame until the machine stops. Document at call sites. template [[nodiscard]] Coro::Task...>> run_parallel_any() { - // Shared so losers (which outlive this call) keep it alive. auto children = std::make_shared>(); std::apply( - [&](auto&... c) { (c.attach(m_ctx, m_services), ...); }, + [&](auto&... c) { + (c.attach(m_ctx, m_services, m_depth + 1, + m_active_state_stop), + ...); + }, *children); struct Latch { int first{-1}; std::coroutine_handle<> waiter{}; Async::Executor* exec; - void arrive(int idx) + std::shared_ptr> keep; + void arrive(std::size_t idx, Status, + std::optional) { if (first < 0) { - first = idx; + first = static_cast(idx); if (waiter) { - exec->post(waiter); + exec->post_completion(waiter); } } } }; auto latch = std::make_shared( - -1, std::coroutine_handle<>{}, &m_ctx->executor()); + -1, std::coroutine_handle<>{}, &m_ctx->active_executor(), + children); - int idx = 0; + std::size_t idx = 0; std::apply( [&](auto&... c) { - ( - [&] { - const int my = idx++; - Async::spawn( - m_ctx->executor(), - [](auto& child, - std::shared_ptr> - keep, - std::shared_ptr - l, - int i) -> Coro::Task { - co_await child.drive(); - l->arrive(i); - (void)keep; - }(c, children, latch, my)); - }(), - ...); + (Async::spawn( + m_ctx->active_executor(), + drive_child_task(&c, latch, idx++)), + ...); }, *children); - struct Awaiter { - std::shared_ptr latch; - [[nodiscard]] bool await_ready() const noexcept - { - return latch->first >= 0; - } - void await_suspend(std::coroutine_handle<> h) const - { - latch->waiter = h; - } - void await_resume() const noexcept {} - }; - co_await Awaiter{latch}; + co_await Detail::LatchResumeAwaiter{ + latch->first >= 0, + [latch](std::coroutine_handle<> h) { latch->waiter = h; }}; const auto winner = static_cast(latch->first); co_return [&](std::index_sequence) @@ -949,9 +1231,256 @@ namespace Void::Fsm }(std::index_sequence_for{}); } - /// Build a Launch step: run `Sub` (constructed from `args`) on this - /// machine's shared executor, then enter `Next` carrying Sub's - /// outcome as a LaunchResult. Reached via State::startMachine. + /// Structured parallel-all: enforces hierarchy depth and live child + /// region limits, stops siblings on any child system Fault, and + /// ALWAYS joins every child before returning. + template + [[nodiscard]] Coro::Task...>>> + run_parallel_structured() + { + constexpr std::size_t n = sizeof...(Subs); + static_assert(n > 0, "run_parallel_structured needs >= 1 sub"); + if (m_ctx == nullptr) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_state, + "run_parallel_structured: no active ExecutionContext")); + } + if (m_depth + 1 > m_ctx->limits().max_hierarchy_depth) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::limit_exceeded, + "run_parallel_structured: max_hierarchy_depth exceeded")); + } + if (!m_ctx->try_acquire_child_regions(n)) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::limit_exceeded, + "run_parallel_structured: max_child_regions exceeded")); + } + + struct RegionGuard { + Detail::ExecutionContext* ctx; + std::size_t count; + ~RegionGuard() { ctx->release_child_regions(count); } + } guard{m_ctx.get(), n}; + + std::stop_source group_stop; + std::optional>> link; + if (state_stop_token().stop_possible()) { + link.emplace(state_stop_token(), + [&group_stop] { group_stop.request_stop(); }); + } + + auto children = std::make_shared>(); + std::apply( + [&](auto&... c) { + (c.attach(m_ctx, m_services, m_depth + 1, &group_stop), + ...); + }, + *children); + + struct Latch { + std::size_t remaining; + std::coroutine_handle<> waiter{}; + Async::Executor* exec; + std::stop_source* stop_src; + std::shared_ptr keep_alive; + std::optional fault{}; + + void arrive(std::size_t, Status st, + std::optional err) + { + if (st == Status::Faulted && !fault.has_value()) { + fault = err.value_or( + FsmError{"parallel child faulted"}); + if (stop_src != nullptr) { + stop_src->request_stop(); + } + } + if (--remaining == 0 && waiter) { + exec->post_completion(waiter); + } + } + }; + auto latch = std::make_shared( + n, std::coroutine_handle<>{}, &m_ctx->active_executor(), + &group_stop, children); + + std::size_t idx = 0; + std::apply( + [&](auto&... c) { + (Async::spawn( + m_ctx->active_executor(), + drive_child_task(&c, latch, idx++)), + ...); + }, + *children); + + co_await Detail::LatchResumeAwaiter{ + latch->remaining == 0, + [latch](std::coroutine_handle<> h) { latch->waiter = h; }}; + link.reset(); + + if (latch->fault.has_value()) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::fault, latch->fault->message)); + } + + co_return std::apply( + [](auto&... c) { + return std::tuple...>{ + c.template take_outcome()...}; + }, + *children); + } + + /// Structured race-any: picks earliest finisher with deterministic + /// child-declaration-order tie-break within the same dispatch turn, + /// requests stop on all losers, and ALWAYS joins EVERY loser before + /// returning. Application Failure can win; system Fault is returned + /// as supervisory error. + template + [[nodiscard]] Coro::Task...>>> + run_parallel_any_structured() + { + constexpr std::size_t n = sizeof...(Subs); + static_assert(n > 0, + "run_parallel_any_structured needs >= 1 sub"); + if (m_ctx == nullptr) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_state, + "run_parallel_any_structured: no active ExecutionContext")); + } + if (m_depth + 1 > m_ctx->limits().max_hierarchy_depth) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::limit_exceeded, + "run_parallel_any_structured: max_hierarchy_depth exceeded")); + } + if (!m_ctx->try_acquire_child_regions(n)) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::limit_exceeded, + "run_parallel_any_structured: max_child_regions exceeded")); + } + + struct RegionGuard { + Detail::ExecutionContext* ctx; + std::size_t count; + ~RegionGuard() { ctx->release_child_regions(count); } + } guard{m_ctx.get(), n}; + + std::stop_source race_stop; + std::optional>> link; + if (state_stop_token().stop_possible()) { + link.emplace(state_stop_token(), + [&race_stop] { race_stop.request_stop(); }); + } + + auto children = std::make_shared>(); + std::apply( + [&](auto&... c) { + (c.attach(m_ctx, m_services, m_depth + 1, &race_stop), + ...); + }, + *children); + + struct Latch { + std::size_t remaining; + bool woke_first{false}; + std::coroutine_handle<> waiter{}; + Detail::ExecutionContext* ctx; + Async::Executor* exec; + std::shared_ptr keep_alive; + std::array completed{}; + std::array turns{}; + std::array statuses{}; + std::array, n> faults{}; + + void arrive(std::size_t idx, Status st, + std::optional err) + { + completed[idx] = true; + turns[idx] = ctx->dispatch_turn(); + statuses[idx] = st; + faults[idx] = std::move(err); + --remaining; + if (!woke_first) { + woke_first = true; + if (waiter) { + auto w = std::exchange(waiter, {}); + exec->post_completion(w); + } + } else if (remaining == 0 && waiter) { + auto w = std::exchange(waiter, {}); + exec->post_completion(w); + } + } + + [[nodiscard]] std::size_t pick_winner() const noexcept + { + std::uint64_t min_turn = + std::numeric_limits::max(); + for (std::size_t i = 0; i < n; ++i) { + if (completed[i] && turns[i] < min_turn) { + min_turn = turns[i]; + } + } + for (std::size_t i = 0; i < n; ++i) { + if (completed[i] && turns[i] == min_turn) { + return i; + } + } + return 0; + } + }; + auto latch = std::make_shared( + n, false, std::coroutine_handle<>{}, m_ctx.get(), + &m_ctx->active_executor(), children); + + std::size_t idx = 0; + std::apply( + [&](auto&... c) { + (Async::spawn( + m_ctx->active_executor(), + drive_child_task(&c, latch, idx++)), + ...); + }, + *children); + + // Wait until at least one child has completed. + co_await Detail::LatchResumeAwaiter{ + latch->woke_first, + [latch](std::coroutine_handle<> h) { latch->waiter = h; }}; + + // Select deterministic winner (earliest turn, declaration + // order tie-break), then cancel and join EVERY loser. + const std::size_t winner = latch->pick_winner(); + race_stop.request_stop(); + + co_await Detail::LatchResumeAwaiter{ + latch->remaining == 0, + [latch](std::coroutine_handle<> h) { latch->waiter = h; }}; + link.reset(); + + if (latch->statuses[winner] == Status::Faulted) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::fault, + latch->faults[winner] + ? latch->faults[winner]->message + : std::string{"winning race child faulted"})); + } + + co_return [&](std::index_sequence) + -> std::variant...> { + std::variant...> v; + ((I == winner ? (void)(v.template emplace( + std::get(*children) + .template take_outcome())) + : void()), + ...); + return v; + }(std::index_sequence_for{}); + } + template [[nodiscard]] StateKey start_machine(Args&&... args) { @@ -965,11 +1494,9 @@ namespace Void::Fsm auto launcher = [this, ... data = std::forward( args)]() mutable -> Coro::Task { - // Run Sub on the shared executor. Startup data (if any) is - // delivered to Sub's initial-state startup-entry via an - // injector, not the constructor. Sub child; - child.attach(m_ctx, m_services); + child.attach(m_ctx, m_services, m_depth + 1, + m_active_state_stop); if constexpr (sizeof...(Args) > 0) { child.m_startup_injector = [... d = std::move(data)]( @@ -1018,12 +1545,6 @@ namespace Void::Fsm return m_names[static_cast(idx)]; } - /// Active state chain (root → leaf). When a child region is - /// running (run_region), its path is appended, so a composite - /// state reports {composite, ...child leaf}. Unlike the lock-free - /// current_state(), the region part is consumer-consistent: read - /// it from within the machine or once it has settled (it is - /// deterministic in embedder/pump mode). [[nodiscard]] std::vector state_path() const { std::vector path; @@ -1039,20 +1560,12 @@ namespace Void::Fsm return path; } - /// All registered state names (registration order). [[nodiscard]] const std::vector& state_names() const noexcept { return m_names; } - // ── introspection / diagram ─────────────────────────────────── - // StateInfo is namespace-scope (Detail/Introspect.hpp). - - /// Structural description: every registered state (name + whether - /// it is the initial state). Transitions are chosen imperatively - /// inside each state's entry, so they are not statically knowable — - /// the description is node-level (no edges). [[nodiscard]] std::vector describe() { std::vector out; @@ -1068,14 +1581,13 @@ namespace Void::Fsm return out; } - /// Render describe() as a Mermaid stateDiagram-v2 string. [[nodiscard]] std::string to_mermaid() { const auto states = describe(); return Detail::to_mermaid(states); } - // ── persistence ─────────────────────────────────────────────── + // ── legacy persistence & boundary checkpoints ───────────────── [[nodiscard]] Json::Value serialize() const { auto obj = Json::object(); @@ -1090,7 +1602,7 @@ namespace Void::Fsm [[nodiscard]] std::expected restore(const Json::Value& state) { - if (m_status.load() != Status::Idle) { + if (m_status.load(std::memory_order_acquire) != Status::Idle) { return std::unexpected{ FsmError{"restore requires an un-started machine"}}; } @@ -1111,22 +1623,308 @@ namespace Void::Fsm return {}; } + /// Request a bounded checkpoint at the next clean state boundary + /// or application safe_point(). Never captures mid-turn live frames. + [[nodiscard]] Coro::Task> + request_checkpoint(Async::OperationOptions opts = {}) + { + if (opts.stop.stop_requested()) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::cancelled, + "request_checkpoint: cancelled before scheduling")); + } + const auto st = m_status.load(std::memory_order_acquire); + if (st == Status::Idle) { + co_return build_checkpoint( + m_initial != nullptr ? durable_id_for(m_initial) + : std::string{}, + m_restored_resume_label); + } + if (terminal(st) || m_ctx == nullptr) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::checkpoint_rejected, + "request_checkpoint: machine is already terminal")); + } + if (opts.deadline.has_value() && + m_ctx->clock().now() >= *opts.deadline) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::timeout, + "request_checkpoint: deadline already expired")); + } + + struct RequestState { + bool settled{false}; + Void::Result::Result result{ + Void::Result::fail(make_fsm_error( + FsmErrorCode::internal, "unsettled"))}; + std::coroutine_handle<> waiter{}; + Async::Executor* exec{nullptr}; + Detail::ExecutionContext::TimerId timer{0}; + }; + auto req = std::make_shared(); + req->exec = &m_ctx->active_executor(); + + std::optional>> stop_cb; + if (opts.stop.stop_possible()) { + stop_cb.emplace(opts.stop, [ctx = m_ctx.get(), req] { + (void)ctx->try_post_control([req] { + if (req->settled) return; + req->settled = true; + req->result = Void::Result::fail(make_fsm_error( + FsmErrorCode::cancelled, + "request_checkpoint: cancelled")); + if (req->waiter) { + req->exec->post_completion(req->waiter); + } + }); + }); + } + + auto pending_entry = PendingCheckpoint{ + .settle = + [ctx = m_ctx.get(), req]( + Void::Result::Result r) { + if (req->settled) return false; + req->settled = true; + if (req->timer != 0) { + ctx->cancel_timer(req->timer); + req->timer = 0; + } + req->result = std::move(r); + if (req->waiter) { + req->exec->post_completion(req->waiter); + } + return true; + }, + .is_done = [req] { return req->settled; }}; + + auto post_res = m_ctx->try_post_control( + [this, ctx = m_ctx.get(), req, opts, + entry = std::move(pending_entry)]() mutable { + if (req->settled) { + return; + } + if (terminal(m_status.load(std::memory_order_acquire))) { + req->settled = true; + req->result = Void::Result::fail(make_fsm_error( + FsmErrorCode::checkpoint_rejected, + "request_checkpoint: machine finished before boundary")); + if (req->waiter) { + req->exec->post_completion(req->waiter); + } + return; + } + if (opts.deadline.has_value()) { + auto t = ctx->try_add_timer( + *opts.deadline, [req] { + if (req->settled) return; + req->settled = true; + req->result = + Void::Result::fail(make_fsm_error( + FsmErrorCode::timeout, + "request_checkpoint: boundary not reached before deadline")); + if (req->waiter) { + req->exec->post_completion(req->waiter); + } + }); + if (t) { + req->timer = *t; + } + } + m_pending_checkpoints.push_back(std::move(entry)); + }); + if (!post_res) { + stop_cb.reset(); + co_return Void::Result::fail(post_res.error()); + } + + co_await Detail::LatchResumeAwaiter{ + req->settled, + [req](std::coroutine_handle<> h) { req->waiter = h; }}; + stop_cb.reset(); + co_return std::move(req->result); + } + + /// Validate-then-commit restore from a boundary Checkpoint while + /// Idle. Any schema, ID, limit, or migration error leaves this + /// machine completely unchanged. + [[nodiscard]] Void::Result::Result + restore_checkpoint(const Checkpoint& cp, + MigrationFn migrator = nullptr) + { + if (m_status.load(std::memory_order_acquire) != Status::Idle) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_state, + "restore_checkpoint requires Idle machine")); + } + if (cp.format_version != Checkpoint::kFormatVersion) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::schema_mismatch, + "restore_checkpoint: unsupported checkpoint format version")); + } + if (!m_machine_type.empty() && !cp.machine_type.empty() && + cp.machine_type != m_machine_type) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::schema_mismatch, + "restore_checkpoint: machine_type mismatch")); + } + if (m_limits.max_checkpoint_bytes > 0 && + Detail::estimate_checkpoint_bytes(cp) > + m_limits.max_checkpoint_bytes) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::limit_exceeded, + "restore_checkpoint: checkpoint exceeds max_checkpoint_bytes")); + } + + Json::Value candidate_data = cp.state; + std::string candidate_state_id = cp.state_id; + if (cp.application_schema != m_application_schema) { + if (!migrator) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::schema_mismatch, + "restore_checkpoint: schema mismatch and no migrator")); + } + try { + auto mr = migrator(cp.application_schema, + m_application_schema, candidate_data, + candidate_state_id); + if (!mr) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::migration_failed, + mr.error().message())); + } + } catch (const std::exception& ex) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::migration_failed, + std::string{"restore_checkpoint migrator threw: "} + + ex.what())); + } catch (...) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::migration_failed, + "restore_checkpoint migrator threw unknown exception")); + } + } + + const auto idIt = m_id_to_type.find(candidate_state_id); + if (idIt == m_id_to_type.end()) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::not_found, + "restore_checkpoint: unknown durable state_id '" + + candidate_state_id + "'")); + } + + try { + auto vr = on_validate_restore(candidate_data); + if (!vr) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::migration_failed, + vr.error().message())); + } + } catch (const std::exception& ex) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::migration_failed, + std::string{"restore_checkpoint validator threw: "} + + ex.what())); + } catch (...) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::migration_failed, + "restore_checkpoint validator threw unknown exception")); + } + + Json::Value rollback_snapshot = Json::object(); + bool has_rollback = false; + try { + on_serialize(rollback_snapshot); + has_rollback = true; + } catch (...) { + } + + try { + on_restore(candidate_data); + } catch (const std::exception& ex) { + if (has_rollback) { + try { + on_restore(rollback_snapshot); + } catch (...) { + } + } + return Void::Result::fail(make_fsm_error( + FsmErrorCode::migration_failed, + std::string{"restore_checkpoint on_restore threw: "} + + ex.what())); + } catch (...) { + if (has_rollback) { + try { + on_restore(rollback_snapshot); + } catch (...) { + } + } + return Void::Result::fail(make_fsm_error( + FsmErrorCode::migration_failed, + "restore_checkpoint on_restore threw unknown exception")); + } + + m_initial = idIt->second; + m_restored_resume_label = cp.resume_label; + m_step = cp.transition_sequence; + return {}; + } + + /// Explicit legacy `{state, data}` reader mapping old state names + /// through an optional migration map into bounded restore_checkpoint. + [[nodiscard]] Void::Result::Result + restore_legacy_checkpoint( + const Json::Value& legacy_json, + const std::unordered_map& + state_id_map = {}, + MigrationFn migrator = nullptr) + { + const auto* st = legacy_json.find("state"); + if (st == nullptr || !st->is_string()) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::schema_mismatch, + "restore_legacy_checkpoint: malformed state field")); + } + std::string mapped_id = st->as_string(); + if (const auto it = state_id_map.find(mapped_id); + it != state_id_map.end()) { + mapped_id = it->second; + } else if (const auto nIt = m_name_to_type.find(mapped_id); + nIt != m_name_to_type.end()) { + mapped_id = durable_id_for(nIt->second); + } + + Checkpoint cp; + cp.format_version = Checkpoint::kFormatVersion; + cp.machine_type = m_machine_type; + cp.application_schema = 1; + if (const auto* sv = legacy_json.find("application_schema"); + sv != nullptr && sv->is_int()) { + cp.application_schema = + static_cast(sv->as_int()); + } + cp.state_id = std::move(mapped_id); + if (const auto* data = legacy_json.find("data")) { + cp.state = *data; + } else { + cp.state = Json::object(); + } + return restore_checkpoint(cp, std::move(migrator)); + } + protected: virtual void on_serialize(Json::Value& /*data*/) const {} virtual void on_restore(const Json::Value& /*data*/) {} + [[nodiscard]] virtual Void::Result::Result + on_validate_restore(const Json::Value& /*data*/) const + { + return {}; + } - /// Machine-level entry/exit hooks (default no-ops; override for - /// machine-wide setup/teardown). `on_machine_enter()` runs once - /// before the initial state is entered; `on_machine_exit()` runs - /// once when the machine reaches a terminal outcome (Success, - /// Failure, or a system Fault). Per-state entry/exit lives on the - /// state itself (State::on_enter()/on_exit()). virtual void on_machine_enter() {} virtual void on_machine_exit() {} - /// Called on every transition (and the initial entry). Default - /// logs at debug; override for custom observability. virtual void on_transition(std::string_view from, std::string_view to) { @@ -1136,18 +1934,49 @@ namespace Void::Fsm private: - template - friend class Machine; // run_child reaches child internals + template friend class Machine; + + struct PendingCheckpoint { + std::function)> + settle; + std::function is_done; + }; + + template + static Coro::Task drive_child_task( + Sub* child, std::shared_ptr latch, std::size_t idx) + { + co_await child->drive(); + latch->arrive(idx, child->status(), child->system_error()); + } void attach(std::shared_ptr ctx, - Service::ServiceRegistry* services) + Service::ServiceRegistry* services, + std::size_t depth = 1, + std::stop_source* parent_stop = nullptr) { m_ctx = std::move(ctx); m_owns_ctx = false; + m_depth = depth; + if (m_ctx != nullptr) { + m_limits = m_ctx->limits(); + } if (services != nullptr) { m_services = services; } - m_status.store(Status::Running); + m_termination_reason.store(TerminationReason::none, + std::memory_order_release); + m_root_stop.emplace(); + m_parent_stop_link.reset(); + if (parent_stop != nullptr) { + m_parent_stop_link.emplace( + parent_stop->get_token(), [this] { + if (m_root_stop) { + m_root_stop->request_stop(); + } + }); + } + m_status.store(Status::Running, std::memory_order_release); } template [[nodiscard]] std::string state_name() @@ -1159,6 +1988,22 @@ namespace Void::Fsm #endif } + template + [[nodiscard]] static std::string + default_state_id(const std::string& fallback_name) + { +#ifdef VOID_HAS_FSM_REFLECTION + constexpr auto id_ann = + Void::Meta::annotation_of(^^S); + if constexpr (id_ann.has_value()) { + if (!id_ann->value.view().empty()) { + return std::string{id_ann->value.view()}; + } + } +#endif + return fallback_name; + } + [[nodiscard]] std::string state_name_for(const std::type_info* type) const { @@ -1169,6 +2014,104 @@ namespace Void::Fsm return {}; } + [[nodiscard]] std::string + durable_id_for(const std::type_info* type) const + { + if (type == nullptr) { + return {}; + } + if (const auto it = m_type_to_id.find(std::type_index{*type}); + it != m_type_to_id.end()) { + return it->second; + } + return state_name_for(type); + } + + [[nodiscard]] std::string current_durable_id() const + { + const int idx = m_current.load(std::memory_order_acquire); + if (idx < 0 || idx >= static_cast(m_names.size())) { + return {}; + } + if (const auto nIt = + m_name_to_type.find(m_names[static_cast(idx)]); + nIt != m_name_to_type.end()) { + return durable_id_for(nIt->second); + } + return m_names[static_cast(idx)]; + } + + [[nodiscard]] Void::Result::Result + build_checkpoint(std::string state_id, + std::string resume_label = {}) const + { + Checkpoint cp; + cp.format_version = Checkpoint::kFormatVersion; + cp.machine_type = m_machine_type; + cp.application_schema = m_application_schema; + cp.transition_sequence = m_step; + cp.state_id = std::move(state_id); + cp.resume_label = std::move(resume_label); + Json::Value data = Json::object(); + try { + on_serialize(data); + } catch (const std::exception& ex) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::checkpoint_rejected, + std::string{"on_serialize threw: "} + ex.what())); + } catch (...) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::checkpoint_rejected, + "on_serialize threw unknown exception")); + } + cp.state = std::move(data); + if (m_limits.max_checkpoint_bytes > 0 && + Detail::estimate_checkpoint_bytes(cp) > + m_limits.max_checkpoint_bytes) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::limit_exceeded, + "checkpoint exceeds max_checkpoint_bytes")); + } + return cp; + } + + void fulfill_pending_checkpoints(const std::string& next_state_id, + const std::string& resume_label) + { + if (m_pending_checkpoints.empty()) { + return; + } + auto pending = std::move(m_pending_checkpoints); + m_pending_checkpoints.clear(); + for (auto& p : pending) { + if (p.is_done && p.is_done()) { + continue; + } + (void)p.settle(build_checkpoint(next_state_id, resume_label)); + } + } + + void reject_pending_checkpoints(const Void::Result::Error& err) + { + if (m_pending_checkpoints.empty()) { + return; + } + auto pending = std::move(m_pending_checkpoints); + m_pending_checkpoints.clear(); + for (auto& p : pending) { + if (p.is_done && p.is_done()) { + continue; + } + (void)p.settle(Void::Result::fail(err)); + } + } + + void record_observer_error(std::string msg) + { + std::lock_guard lk{m_obs_mu}; + m_observer_errors.push_back(std::move(msg)); + } + void set_current(const std::type_info* type) { std::string from = current_state(); @@ -1178,52 +2121,120 @@ namespace Void::Fsm } std::string to = current_state(); ++m_step; - on_transition(from, to); const Transition t{from, to, m_step}; - if (m_observer) { - m_observer(t); + + std::function observer_copy; + std::vector interceptors_copy; + { + std::lock_guard lk{m_obs_mu}; + if (m_limits.max_retained_transitions > 0) { + m_transition_history.push_back(t); + while (m_transition_history.size() > + m_limits.max_retained_transitions) { + m_transition_history.pop_front(); + } + } + observer_copy = m_observer; + interceptors_copy = m_interceptors; } - for (const auto& interceptor : m_interceptors) { + + try { + on_transition(from, to); + } catch (const std::exception& ex) { + record_observer_error( + std::string{"on_transition: "} + ex.what()); + } catch (...) { + record_observer_error("on_transition: unknown exception"); + } + if (observer_copy) { + try { + observer_copy(t); + } catch (const std::exception& ex) { + record_observer_error( + std::string{"observer: "} + ex.what()); + } catch (...) { + record_observer_error("observer: unknown exception"); + } + } + for (const auto& interceptor : interceptors_copy) { if (interceptor.before) { - interceptor.before(t); + try { + interceptor.before(t); + } catch (const std::exception& ex) { + record_observer_error( + std::string{"interceptor.before: "} + + ex.what()); + } catch (...) { + record_observer_error( + "interceptor.before: unknown exception"); + } } } } void fire_after(std::string_view state) { - for (const auto& interceptor : m_interceptors) { + std::vector interceptors_copy; + { + std::lock_guard lk{m_obs_mu}; + interceptors_copy = m_interceptors; + } + for (const auto& interceptor : interceptors_copy) { if (interceptor.after) { - interceptor.after(state); + try { + interceptor.after(state); + } catch (const std::exception& ex) { + record_observer_error( + std::string{"interceptor.after: "} + + ex.what()); + } catch (...) { + record_observer_error( + "interceptor.after: unknown exception"); + } } } } - // Record a system fault (programming error) — separate from a - // typed Failure result. Sets status Faulted + system_error. void fault(std::string message) { m_system_error = FsmError{std::move(message)}; + if (m_termination_reason.load(std::memory_order_acquire) == + TerminationReason::none) { + m_termination_reason.store(TerminationReason::faulted, + std::memory_order_release); + } Void::Log::error("Fsm", "system fault: {}", m_system_error->message); m_status.store(Status::Faulted, std::memory_order_release); + reject_pending_checkpoints(make_fsm_error( + FsmErrorCode::checkpoint_rejected, + "machine faulted before checkpoint boundary")); } - // The state loop. Type-erased: stores the Success/Failure payload - // in m_result_value and sets m_status; the typed Outcome is rebuilt - // in take_outcome() where Derived is complete. Runs on the - // executor. Coro::Task drive() { const std::type_info* cur = m_initial; if (cur == nullptr) { fault("no initial state"); + m_parent_stop_link.reset(); co_return; } on_machine_enter(); bool first = true; for (;;) { - // Apply an external jump() at this transition boundary. + if (m_root_stop && m_root_stop->stop_requested()) { + m_termination_reason.store( + m_root_timeout.load(std::memory_order_acquire) + ? TerminationReason::timed_out + : TerminationReason::cancelled, + std::memory_order_release); + fault(m_root_timeout.load(std::memory_order_acquire) + ? "deadline expired" + : "cancelled"); + on_machine_exit(); + m_parent_stop_link.reset(); + co_return; + } if (const auto* j = m_jump.exchange(nullptr, std::memory_order_acq_rel); j != nullptr) { @@ -1235,37 +2246,124 @@ namespace Void::Fsm if (it == m_factories.end()) { fault("transition to unregistered state"); on_machine_exit(); + m_parent_stop_link.reset(); co_return; } + + // Boundary checkpoint right before next state enters and + // causes effects (note: during initial entry this captures + // clean entry state). + if (m_ctx != nullptr) { + m_ctx->drain_control_queue(); + } + fulfill_pending_checkpoints(durable_id_for(cur), {}); + set_current(cur); auto state = it->second(); - co_await state->on_enter(); - // Decide how the state runs: a launched sub's result (via - // the bound dispatcher), the startup injector for the first - // state, or the signature-inferred driver thunk. + + const auto state_scope = m_ctx->allocate_scope(); + std::stop_source state_stop; + std::optional>> + root_to_state; + if (m_root_stop.has_value()) { + root_to_state.emplace( + m_root_stop->get_token(), + [&state_stop] { state_stop.request_stop(); }); + } + m_active_scope = state_scope; + m_active_state_stop = &state_stop; + StateKey step; - if (m_pending_dispatch) { - LaunchResult pending = std::move(*m_pending_result); - auto dispatch = std::move(m_pending_dispatch); - m_pending_result.reset(); - m_pending_dispatch = nullptr; - if (pending.kind == LaunchResult::Kind::Fault) { - fault(std::move(pending.fault.message)); - on_machine_exit(); - co_return; + bool body_failed = false; + bool body_cancelled = false; + std::string body_error; + + try { + co_await state->on_enter(); + if (m_pending_dispatch) { + LaunchResult pending = std::move(*m_pending_result); + auto dispatch = std::move(m_pending_dispatch); + m_pending_result.reset(); + m_pending_dispatch = nullptr; + if (pending.kind == LaunchResult::Kind::Fault) { + body_failed = true; + body_error = std::move(pending.fault.message); + } else { + step = co_await dispatch(*state, + std::move(pending)); + } + } else if (first && m_startup_injector) { + auto inject = std::move(m_startup_injector); + m_startup_injector = nullptr; + step = co_await inject(*state); + } else { + step = co_await m_drivers.at(std::type_index{*cur})( + *state); } - step = co_await dispatch(*state, std::move(pending)); - } else if (first && m_startup_injector) { - auto inject = std::move(m_startup_injector); - m_startup_injector = nullptr; - step = co_await inject(*state); - } else { - step = co_await m_drivers.at(std::type_index{*cur})( - *state); + } catch (const Detail::CancelledException&) { + body_cancelled = true; + } catch (const std::exception& ex) { + body_failed = true; + body_error = ex.what(); + } catch (...) { + body_failed = true; + body_error = "state execution threw unknown exception"; } first = false; - co_await state->on_exit(); + + // Scope exit before on_exit() and state destruction: stop + // child scope, cancel waiters, and purge timers. + m_active_state_stop = nullptr; + state_stop.request_stop(); + root_to_state.reset(); + if (m_ctx != nullptr) { + m_ctx->cancel_scope(state_scope); + m_ctx->purge_scope(state_scope); + } + m_active_scope = Detail::ExecutionContext::kNoScope; + + bool exit_failed = false; + std::string exit_error; + try { + co_await state->on_exit(); + } catch (const std::exception& ex) { + exit_failed = true; + exit_error = + std::string{"on_exit threw: "} + ex.what(); + } catch (...) { + exit_failed = true; + exit_error = "on_exit threw unknown exception"; + } + state.reset(); fire_after(current_state()); + + if (exit_failed) { + fault(std::move(exit_error)); + on_machine_exit(); + m_parent_stop_link.reset(); + co_return; + } + if (body_cancelled || + (m_root_stop && m_root_stop->stop_requested())) { + m_termination_reason.store( + m_root_timeout.load(std::memory_order_acquire) + ? TerminationReason::timed_out + : TerminationReason::cancelled, + std::memory_order_release); + fault(m_root_timeout.load(std::memory_order_acquire) + ? "deadline expired" + : "cancelled"); + on_machine_exit(); + m_parent_stop_link.reset(); + co_return; + } + if (body_failed) { + fault(std::move(body_error)); + on_machine_exit(); + m_parent_stop_link.reset(); + co_return; + } + switch (step.kind()) { case StateKey::Kind::Transition: cur = step.target(); @@ -1278,20 +2376,35 @@ namespace Void::Fsm continue; case StateKey::Kind::Success: m_result_value = std::move(step.payload()); + m_termination_reason.store( + TerminationReason::succeeded, + std::memory_order_release); m_status.store(Status::Succeeded, std::memory_order_release); + reject_pending_checkpoints(make_fsm_error( + FsmErrorCode::checkpoint_rejected, + "machine succeeded before checkpoint boundary")); on_machine_exit(); + m_parent_stop_link.reset(); co_return; case StateKey::Kind::Fail: m_result_value = std::move(step.payload()); + m_termination_reason.store( + TerminationReason::failed, + std::memory_order_release); m_status.store(Status::Failed, std::memory_order_release); + reject_pending_checkpoints(make_fsm_error( + FsmErrorCode::checkpoint_rejected, + "machine failed before checkpoint boundary")); on_machine_exit(); + m_parent_stop_link.reset(); co_return; case StateKey::Kind::Fault: fault(std::any_cast(step.payload()) .message); on_machine_exit(); + m_parent_stop_link.reset(); co_return; } } @@ -1300,15 +2413,11 @@ namespace Void::Fsm Coro::Task driver() { co_await drive(); - if (m_owns_ctx) { + if (m_owns_ctx && m_ctx) { m_ctx->finish(); } } - // Rebuild the typed Outcome from the type-erased result. Function - // template so SuccessOf/FailureOf resolve where Derived is - // complete. A system fault yields a default-constructed error arm - // (consult system_error()). template Outcome take_outcome() { using Succ = Detail::SuccessOf; @@ -1330,7 +2439,7 @@ namespace Void::Fsm std::unexpect, std::any_cast(m_result_value)}; } - default: // Faulted / not finished + default: static_assert( std::is_default_constructible_v, "a machine with a non-default-constructible " @@ -1342,6 +2451,9 @@ namespace Void::Fsm } Options m_options; + FsmLimits m_limits{}; + bool m_has_explicit_limits{false}; + std::size_t m_depth{0}; std::shared_ptr m_ctx; bool m_owns_ctx{false}; Service::ServiceRegistry* m_services{nullptr}; @@ -1350,7 +2462,6 @@ namespace Void::Fsm std::type_index, std::function()>> m_factories; - // Per-state signature-inferred driver thunk (runs the entry). std::unordered_map< std::type_index, std::function(Detail::StateBase&)>> @@ -1359,43 +2470,45 @@ namespace Void::Fsm std::vector m_names; std::unordered_map m_name_to_type; + std::unordered_map m_type_to_id; + std::unordered_map m_id_to_type; const std::type_info* m_initial{nullptr}; + std::string m_machine_type; + std::uint32_t m_application_schema{1}; + std::string m_restored_resume_label; std::atomic m_current{-1}; std::atomic m_status{Status::Idle}; - // Type-erased finished result (Success or Failure payload), rebuilt - // typed in take_outcome(); system faults in m_system_error. + std::atomic m_termination_reason{ + TerminationReason::none}; std::any m_result_value; std::optional m_system_error; + + mutable std::mutex m_obs_mu; std::function m_observer; std::vector m_interceptors; + std::deque m_transition_history; + std::vector m_observer_errors; std::uint64_t m_step{0}; - // Active child region's path provider (run_region); consulted by - // state_path(). Set/cleared on the consumer thread. std::function()> m_region_probe; - - // Per-region-type snapshot of the leaf last reached, for - // Resume::History re-entry. std::unordered_map m_region_history; - // Set by a Launch step's sub-machine result; consumed by the next - // state via the bound dispatcher below. std::optional m_pending_result; StateKey::Dispatch m_pending_dispatch; - - // Seeds the initial state's startup-entry with launch data (set by - // the parent's launcher before driving this machine). std::function(Detail::StateBase&)> m_startup_injector; - // External jump request (jump()); applied by drive() at the - // next transition boundary. std::atomic m_jump{nullptr}; + std::optional m_root_stop; + std::optional>> + m_parent_stop_link; + std::atomic m_root_timeout{false}; + Detail::ExecutionContext::ScopeId m_active_scope{ + Detail::ExecutionContext::kNoScope}; + std::stop_source* m_active_state_stop{nullptr}; - // The owned top-level driver coroutine (worker mode). Holding it - // (rather than detaching via Async::spawn) lets stop() destroy the - // suspended frame chain of a machine parked on an event. + std::vector m_pending_checkpoints; std::optional> m_driver; }; template using State = Machine::State; diff --git a/include/Void/Fsm/Orchestrator.hpp b/include/Void/Fsm/Orchestrator.hpp index fb8b344..3733846 100644 --- a/include/Void/Fsm/Orchestrator.hpp +++ b/include/Void/Fsm/Orchestrator.hpp @@ -1,27 +1,73 @@ #pragma once #include +#include #include +#include +#include +#include #include +#include +#include #include #include +#include +#include #include #include namespace Void::Fsm { + enum class SupervisionMode : std::uint8_t { + StopOnFault = 0, + BoundedRestart + }; + + struct SupervisionPolicy { + SupervisionMode mode{SupervisionMode::StopOnFault}; + std::size_t max_restarts{3}; + std::chrono::nanoseconds restart_window{std::chrono::seconds{60}}; + std::chrono::nanoseconds initial_backoff{ + std::chrono::milliseconds{10}}; + }; + + struct OrchestratorLimits { + std::size_t max_supervised{1024}; + }; + + struct SupervisionEvent { + enum class Kind : std::uint8_t { + Launched = 0, + RestartScheduled, + Restarted, + Released, + Exhausted + }; + Kind kind{Kind::Launched}; + Status status{Status::Idle}; + TerminationReason reason{TerminationReason::none}; + std::size_t restarts{0}; + std::string detail{}; + }; + namespace Detail { // Type-erased supervised FSM. Models wrap a concrete Machine - // subclass; the orchestrator only needs lifecycle + status. + // subclass; the orchestrator drives lifecycle, status, and bounded + // restart. class FsmConcept { public: virtual ~FsmConcept() = default; virtual void stop() = 0; + virtual void restart() = 0; [[nodiscard]] virtual Status status() const = 0; + [[nodiscard]] virtual TerminationReason + termination_reason() const = 0; + [[nodiscard]] virtual std::optional + system_error() const = 0; }; template class FsmModel final : public FsmConcept @@ -34,10 +80,21 @@ namespace Void::Fsm } void stop() override { m_fsm->stop(); } + void restart() override { m_fsm->restart(); } [[nodiscard]] Status status() const override { return m_fsm->status(); } + [[nodiscard]] TerminationReason + termination_reason() const override + { + return m_fsm->termination_reason(); + } + [[nodiscard]] std::optional + system_error() const override + { + return m_fsm->system_error(); + } [[nodiscard]] F& get() noexcept { return *m_fsm; } @@ -45,10 +102,27 @@ namespace Void::Fsm std::unique_ptr m_fsm; }; + + struct SupervisedEntry { + std::shared_ptr model; + SupervisionPolicy policy{}; + std::vector + restart_timestamps; + std::optional + next_restart_at; + std::atomic restarts{0}; + mutable std::mutex evidence_mu; + bool released{false}; + Status final_status{Status::Idle}; + TerminationReason final_reason{TerminationReason::none}; + std::optional final_error{}; + }; } // namespace Detail - /// A non-owning supervision handle to a launched FSM: query status and - /// stop it. The Orchestrator owns the FSM's lifetime. + /// Owning handle to a supervised FSM instance: holds a shared_ptr so + /// immutable termination evidence and any still-required cleanup ownership + /// survive even after the Orchestrator releases a finished entry from + /// active supervision. class FsmHandle { public: @@ -57,48 +131,92 @@ namespace Void::Fsm void stop() const { - if (m_impl) { - m_impl->stop(); + if (m_entry && m_entry->model) { + m_entry->model->stop(); } } [[nodiscard]] Status status() const { - return m_impl ? m_impl->status() : Status::Idle; + if (!m_entry) { + return Status::Idle; + } + std::lock_guard lk{m_entry->evidence_mu}; + if (m_entry->released) { + return m_entry->final_status; + } + return m_entry->model ? m_entry->model->status() : Status::Idle; } - [[nodiscard]] bool finished() const + [[nodiscard]] bool finished() const { return terminal(status()); } + + [[nodiscard]] TerminationReason termination_reason() const { - const auto s = status(); - return s == Status::Succeeded || s == Status::Failed; + if (!m_entry) { + return TerminationReason::none; + } + std::lock_guard lk{m_entry->evidence_mu}; + if (m_entry->released) { + return m_entry->final_reason; + } + return m_entry->model ? m_entry->model->termination_reason() + : TerminationReason::none; + } + + [[nodiscard]] std::optional system_error() const + { + if (!m_entry) { + return std::nullopt; + } + std::lock_guard lk{m_entry->evidence_mu}; + if (m_entry->released) { + return m_entry->final_error; + } + return m_entry->model ? m_entry->model->system_error() + : std::nullopt; + } + + [[nodiscard]] std::size_t restart_count() const noexcept + { + return m_entry + ? m_entry->restarts.load(std::memory_order_acquire) + : 0; } [[nodiscard]] explicit operator bool() const noexcept { - return m_impl != nullptr; + return m_entry != nullptr && m_entry->model != nullptr; } private: friend class Orchestrator; - explicit FsmHandle(std::shared_ptr impl) - : m_impl(std::move(impl)) + explicit FsmHandle(std::shared_ptr entry) + : m_entry(std::move(entry)) { } - std::shared_ptr m_impl; + std::shared_ptr m_entry; }; // ── Orchestrator ────────────────────────────────────────────────────── - // Owns a ServiceRegistry and supervises a set of FSM instances. Each - // launched FSM is injected with the registry as its context, so its - // states resolve dependencies by interface (no concrete coupling), and - // is started immediately. stop_all() winds everything down. class Orchestrator { public: - Orchestrator() = default; + using ObserverCallback = + std::function; + + explicit Orchestrator( + const Time::MonotonicClock* clock = nullptr, + OrchestratorLimits limits = {}) noexcept + : m_clock(clock != nullptr + ? clock + : &Time::SystemMonotonicClock::instance()), + m_limits(limits) + { + } + ~Orchestrator() { stop_all(); } Orchestrator(const Orchestrator&) = delete; @@ -109,8 +227,6 @@ namespace Void::Fsm return m_registry; } - /// Call on_start() on lifecycle services. Call before launching - /// FSMs that expect started services. void start_services() { m_registry.start_all(); @@ -118,36 +234,177 @@ namespace Void::Fsm m_services_stopped = false; } - /// Construct F, inject the registry, start it, and supervise. - /// F must derive Fsm::Machine<...> (provides set_services / - /// start / stop / status). + template + [[nodiscard]] Void::Result::Result + try_launch(SupervisionPolicy policy, Args&&... args) + { + std::vector observers_copy; + std::shared_ptr entry; + { + reap_finished_and_notify(); + std::lock_guard lock{m_mutex}; + if (m_limits.max_supervised > 0 && + m_entries.size() >= m_limits.max_supervised) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::limit_exceeded, + "Orchestrator: max_supervised limit reached")); + } + auto fsm = + std::make_unique(std::forward(args)...); + fsm->set_services(m_registry); + fsm->start(); + auto model = + std::make_shared>(std::move(fsm)); + entry = std::make_shared(); + entry->model = std::move(model); + entry->policy = policy; + m_entries.push_back(entry); + } + + notify_observers(SupervisionEvent{ + .kind = SupervisionEvent::Kind::Launched, + .status = entry->model->status(), + .reason = entry->model->termination_reason(), + .restarts = 0, + .detail = {}}); + return FsmHandle{std::move(entry)}; + } + template FsmHandle launch(Args&&... args) { - auto fsm = std::make_unique(std::forward(args)...); - fsm->set_services(m_registry); - fsm->start(); - auto model = - std::make_shared>(std::move(fsm)); - std::lock_guard lock{m_mutex}; - m_running.push_back(model); - return FsmHandle{model}; + auto r = try_launch(SupervisionPolicy{}, + std::forward(args)...); + return r ? *r : FsmHandle{}; } - /// Stop and release every supervised FSM, then stop services. - void stop_all() + /// Drive supervision rules (bounded restarts with injected Time + /// backoff, and releasing terminal entries while handles keep + /// immutable evidence). Returns actions taken (restarts + releases). + std::size_t supervise_step() { - std::vector> running; + std::vector events; + std::vector> + to_restart; + const auto now = m_clock->now(); + { std::lock_guard lock{m_mutex}; - running.swap(m_running); + for (auto it = m_entries.begin(); it != m_entries.end();) { + auto& e = *it; + const auto st = e->model->status(); + if (!terminal(st)) { + ++it; + continue; + } + + if (e->policy.mode == SupervisionMode::BoundedRestart && + st == Status::Faulted) { + std::erase_if( + e->restart_timestamps, [&](const auto ts) { + return (now - ts) >= + e->policy.restart_window; + }); + if (e->restart_timestamps.size() < + e->policy.max_restarts) { + if (!e->next_restart_at.has_value()) { + const std::size_t attempt = + e->restart_timestamps.size(); + const auto shift = + attempt < 16 ? attempt : 16; + const auto backoff = + e->policy.initial_backoff * + (std::size_t{1} << shift); + e->next_restart_at = now + backoff; + events.push_back(SupervisionEvent{ + .kind = SupervisionEvent::Kind:: + RestartScheduled, + .status = st, + .reason = + e->model->termination_reason(), + .restarts = e->restarts.load( + std::memory_order_acquire), + .detail = e->model->system_error() + ? e->model->system_error() + ->message + : std::string{}}); + ++it; + continue; + } + if (now < *e->next_restart_at) { + ++it; + continue; + } + e->restart_timestamps.push_back(now); + e->next_restart_at.reset(); + e->restarts.fetch_add( + 1, std::memory_order_acq_rel); + to_restart.push_back(e); + ++it; + continue; + } + + snapshot_released_evidence(*e); + events.push_back(SupervisionEvent{ + .kind = SupervisionEvent::Kind::Exhausted, + .status = e->final_status, + .reason = e->final_reason, + .restarts = + e->restarts.load(std::memory_order_acquire), + .detail = + e->final_error + ? e->final_error->message + : std::string{"restart budget exhausted"}}); + it = m_entries.erase(it); + continue; + } + + snapshot_released_evidence(*e); + events.push_back(SupervisionEvent{ + .kind = SupervisionEvent::Kind::Released, + .status = e->final_status, + .reason = e->final_reason, + .restarts = + e->restarts.load(std::memory_order_acquire), + .detail = e->final_error ? e->final_error->message + : std::string{}}); + it = m_entries.erase(it); + } } - for (auto& m : running) { - m->stop(); + + for (auto& e : to_restart) { + e->model->restart(); + events.push_back(SupervisionEvent{ + .kind = SupervisionEvent::Kind::Restarted, + .status = e->model->status(), + .reason = e->model->termination_reason(), + .restarts = e->restarts.load(std::memory_order_acquire), + .detail = {}}); + } + + const std::size_t count = events.size(); + for (const auto& ev : events) { + notify_observers(ev); + } + return count; + } + + /// Release finished stop-on-fault (or non-faulted) entries from + /// active supervision while existing handles retain evidence. + std::size_t reap_finished() { return reap_finished_and_notify(); } + + void stop_all() + { + std::vector> running; + { + std::lock_guard lock{m_mutex}; + running.swap(m_entries); + } + for (auto& e : running) { + e->model->stop(); + snapshot_released_evidence(*e); } running.clear(); - // Balance start_services() exactly once (stop_all may run - // explicitly and again from the destructor). if (m_services_started && !m_services_stopped) { m_registry.stop_all(); m_services_stopped = true; @@ -157,16 +414,118 @@ namespace Void::Fsm [[nodiscard]] std::size_t running_count() const { std::lock_guard lock{m_mutex}; - return m_running.size(); + return m_entries.size(); + } + + std::size_t observe_supervision(ObserverCallback cb) + { + std::lock_guard lock{m_obs_mu}; + const std::size_t id = m_next_obs_id++; + m_observers.emplace_back(id, std::move(cb)); + return id; + } + + void remove_supervision_observer(std::size_t id) + { + std::lock_guard lock{m_obs_mu}; + std::erase_if(m_observers, [id](const auto& pair) { + return pair.first == id; + }); + } + + [[nodiscard]] std::vector observer_errors() const + { + std::lock_guard lock{m_obs_mu}; + return m_observer_errors; } private: + static void + snapshot_released_evidence(Detail::SupervisedEntry& entry) + { + std::lock_guard elk{entry.evidence_mu}; + if (entry.released) { + return; + } + entry.final_status = entry.model->status(); + entry.final_reason = entry.model->termination_reason(); + entry.final_error = entry.model->system_error(); + entry.released = true; + } + + std::size_t reap_finished_and_notify() + { + std::vector events; + { + std::lock_guard lock{m_mutex}; + for (auto it = m_entries.begin(); it != m_entries.end();) { + auto& e = *it; + const auto st = e->model->status(); + if (!terminal(st)) { + ++it; + continue; + } + if (e->policy.mode == SupervisionMode::BoundedRestart && + st == Status::Faulted) { + ++it; + continue; + } + snapshot_released_evidence(*e); + events.push_back(SupervisionEvent{ + .kind = SupervisionEvent::Kind::Released, + .status = e->final_status, + .reason = e->final_reason, + .restarts = + e->restarts.load(std::memory_order_acquire), + .detail = e->final_error ? e->final_error->message + : std::string{}}); + it = m_entries.erase(it); + } + } + for (const auto& ev : events) { + notify_observers(ev); + } + return events.size(); + } + + void notify_observers(const SupervisionEvent& ev) + { + std::vector copy; + { + std::lock_guard lock{m_obs_mu}; + copy.reserve(m_observers.size()); + for (const auto& [id, fn] : m_observers) { + if (fn) { + copy.push_back(fn); + } + } + } + for (const auto& fn : copy) { + try { + fn(ev); + } catch (const std::exception& ex) { + std::lock_guard lock{m_obs_mu}; + m_observer_errors.push_back(ex.what()); + } catch (...) { + std::lock_guard lock{m_obs_mu}; + m_observer_errors.push_back("observer threw unknown"); + } + } + } + + const Time::MonotonicClock* m_clock; + OrchestratorLimits m_limits{}; Service::ServiceRegistry m_registry; mutable std::mutex m_mutex; - std::vector> m_running; + std::vector> m_entries; bool m_services_started{false}; bool m_services_stopped{false}; + + mutable std::mutex m_obs_mu; + std::vector> m_observers; + std::vector m_observer_errors; + std::size_t m_next_obs_id{1}; }; } // namespace Void::Fsm diff --git a/include/Void/Fsm/StateKey.hpp b/include/Void/Fsm/StateKey.hpp index 205e9f5..6d42a92 100644 --- a/include/Void/Fsm/StateKey.hpp +++ b/include/Void/Fsm/StateKey.hpp @@ -1,10 +1,22 @@ #pragma once +#include #include +#include +#include +#include +#include +#include #include +#include +#include +#include +#include #include #include +#include +#include #include #include @@ -33,6 +45,153 @@ namespace Void::Fsm Faulted // stopped by a system fault (see system_error()) }; + /// Canonical shared predicate identifying every terminal Status value. + [[nodiscard]] constexpr bool terminal(Status s) noexcept + { + return s == Status::Succeeded || s == Status::Failed || + s == Status::Faulted; + } + + /// Why a machine finished (preserving Status values while distinguishing + /// cooperative cancellation and deadline expiration from application + /// outcomes and system faults). + enum class TerminationReason : std::uint8_t { + none = 0, + succeeded, + failed, + faulted, + cancelled, + timed_out + }; + + enum class FsmErrorCode : std::int32_t { + none = 0, + invalid_argument = 1, + invalid_state = 2, + not_found = 3, + overloaded = 4, + cancelled = 5, + timeout = 6, + limit_exceeded = 7, + fault = 8, + checkpoint_rejected = 9, + schema_mismatch = 10, + migration_failed = 11, + service_unavailable = 12, + internal = 13 + }; + + [[nodiscard]] inline Void::Result::Error + make_fsm_error(FsmErrorCode code, std::string message = {}) + { + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case FsmErrorCode::none: + kind = ErrorKind::internal; + break; + case FsmErrorCode::invalid_argument: + kind = ErrorKind::invalid_argument; + break; + case FsmErrorCode::invalid_state: + case FsmErrorCode::checkpoint_rejected: + kind = ErrorKind::conflict; + break; + case FsmErrorCode::not_found: + case FsmErrorCode::service_unavailable: + kind = ErrorKind::not_found; + break; + case FsmErrorCode::overloaded: + kind = ErrorKind::overloaded; + break; + case FsmErrorCode::cancelled: + kind = ErrorKind::cancelled; + break; + case FsmErrorCode::timeout: + kind = ErrorKind::timeout; + break; + case FsmErrorCode::limit_exceeded: + kind = ErrorKind::exhausted; + break; + case FsmErrorCode::schema_mismatch: + case FsmErrorCode::migration_failed: + kind = ErrorKind::corrupt; + break; + case FsmErrorCode::fault: + case FsmErrorCode::internal: + kind = ErrorKind::internal; + break; + } + return Error{kind, std::move(message), + ErrorCode{Void::Result::kFsmErrorDomain, + static_cast(code)}}; + } + + /// Explicit resource and scheduling bounds for FSM execution. + struct FsmLimits { + std::size_t max_mailbox_events{1024}; + std::size_t max_mailbox_bytes{std::size_t{4} * 1024 * 1024}; + std::size_t max_deferred_events{256}; + std::size_t max_timers{1024}; + std::size_t max_child_regions{128}; + std::size_t max_hierarchy_depth{32}; + std::size_t max_retained_transitions{256}; + std::size_t max_checkpoint_bytes{std::size_t{4} * 1024 * 1024}; + std::size_t max_events_per_turn{64}; + std::chrono::nanoseconds max_turn_duration{ + std::chrono::milliseconds{1}}; + std::size_t max_control_messages{256}; + }; + + /// Explicit borrowed execution binding passed to Machine::run(). + struct ExecutionBinding { + Async::Executor* executor{nullptr}; + const Time::MonotonicClock* clock{ + &Time::SystemMonotonicClock::instance()}; + FsmLimits limits{}; + }; + + /// Versioned boundary checkpoint capturing machine identity, schema, + /// durable state ID, optional application safe-point resume label, and + /// serialized application state. + struct Checkpoint { + static constexpr std::uint32_t kFormatVersion = 1; + std::uint32_t format_version{kFormatVersion}; + std::string machine_type; + std::uint32_t application_schema{1}; + std::uint64_t transition_sequence{0}; + std::string state_id; + std::string resume_label; + Json::Value state; + }; + + /// Annotation tag specifying a durable state ID (`[[= Void::Fsm::StateId{"..."}]]`). + struct StateId { + Void::Meta::Str value; + }; + + /// Byte-size accounting helper for typed event admission into bounded + /// FSM mailboxes. + template + [[nodiscard]] constexpr std::size_t event_payload_bytes(const E& e) noexcept + { + if constexpr (requires { + { + e.payload_bytes() + } -> std::convertible_to; + }) { + return static_cast(e.payload_bytes()); + } else if constexpr (std::is_same_v, + std::string>) { + return sizeof(E) + e.size(); + } else { + return sizeof(E); + } + } + /// The outcome of a sub-machine launched via startMachine(): /// a typed Success value, a typed Failure value, or a system fault. struct LaunchResult { diff --git a/src/Fsm/Engine.cpp b/src/Fsm/Engine.cpp index 89cb9ba..5d5d703 100644 --- a/src/Fsm/Engine.cpp +++ b/src/Fsm/Engine.cpp @@ -1,22 +1,152 @@ #include +#include #include #include namespace Void::Fsm::Detail { + namespace + { + Coro::Task external_pump_task( + std::weak_ptr weak_ctx) + { + if (auto ctx = weak_ctx.lock()) { + ctx->run_external_pump_step(); + } + co_return; + } + } // namespace - // Default state lifecycle hooks (no-ops). The state's behaviour is driven - // by a per-state, signature-inferred thunk built at registration. Coro::Task StateBase::on_enter() { co_return; } Coro::Task StateBase::on_exit() { co_return; } + ExecutionContext::ExecutionContext(const Time::MonotonicClock* clock, + FsmLimits limits, + Async::Executor* external_executor) + : m_clock(clock != nullptr ? clock + : &Time::SystemMonotonicClock::instance()), + m_limits(limits), m_external_executor(external_executor) + { + } + ExecutionContext::~ExecutionContext() { stop(); } + bool ExecutionContext::try_acquire_child_regions(std::size_t count) noexcept + { + if (count == 0) { + return true; + } + std::size_t cur = + m_active_child_regions.load(std::memory_order_acquire); + for (;;) { + if (count > m_limits.max_child_regions || + cur > m_limits.max_child_regions - count) { + return false; + } + if (m_active_child_regions.compare_exchange_weak( + cur, cur + count, std::memory_order_acq_rel, + std::memory_order_acquire)) { + return true; + } + } + } + + void ExecutionContext::release_child_regions(std::size_t count) noexcept + { + if (count == 0) { + return; + } + m_active_child_regions.fetch_sub(count, std::memory_order_acq_rel); + } + + Void::Result::Result ExecutionContext::try_post(EventEnvelope env) + { + if (m_done.load(std::memory_order_acquire)) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_state, + "ExecutionContext::try_post: context stopped")); + } + + const std::size_t bytes = env.bytes; + std::size_t cur_ev = m_queued_events.load(std::memory_order_acquire); + for (;;) { + if (m_limits.max_mailbox_events > 0 && + cur_ev >= m_limits.max_mailbox_events) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::overloaded, + "ExecutionContext::try_post: mailbox event limit reached")); + } + if (m_queued_events.compare_exchange_weak( + cur_ev, cur_ev + 1, std::memory_order_acq_rel, + std::memory_order_acquire)) { + break; + } + } + + std::size_t cur_bytes = m_queued_bytes.load(std::memory_order_acquire); + for (;;) { + if (m_limits.max_mailbox_bytes > 0 && + (bytes > m_limits.max_mailbox_bytes || + cur_bytes > m_limits.max_mailbox_bytes - bytes)) { + m_queued_events.fetch_sub(1, std::memory_order_acq_rel); + return Void::Result::fail(make_fsm_error( + FsmErrorCode::overloaded, + "ExecutionContext::try_post: mailbox byte limit reached")); + } + if (m_queued_bytes.compare_exchange_weak( + cur_bytes, cur_bytes + bytes, std::memory_order_acq_rel, + std::memory_order_acquire)) { + break; + } + } + + m_queue.push(std::move(env)); + wake(); + return {}; + } + void ExecutionContext::post(EventEnvelope env) { - m_queue.push(std::move(env)); + auto r = try_post(std::move(env)); + if (!r) { + Void::Log::warn("Fsm", "dropped user event: {}", + r.error().message()); + } + } + + Void::Result::Result + ExecutionContext::try_post_control(std::function fn) + { + if (!fn) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_argument, + "ExecutionContext::try_post_control: empty callback")); + } + if (m_done.load(std::memory_order_acquire)) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_state, + "ExecutionContext::try_post_control: context stopped")); + } + + std::size_t cur = m_queued_control.load(std::memory_order_acquire); + for (;;) { + if (m_limits.max_control_messages > 0 && + cur >= m_limits.max_control_messages) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::overloaded, + "ExecutionContext::try_post_control: control lane limit reached")); + } + if (m_queued_control.compare_exchange_weak( + cur, cur + 1, std::memory_order_acq_rel, + std::memory_order_acquire)) { + break; + } + } + + m_control_queue.push(std::move(fn)); wake(); + return {}; } bool ExecutionContext::try_take_any( @@ -26,57 +156,170 @@ namespace Void::Fsm::Detail const auto it = m_buffers.find(std::type_index{*ty}); if (it != m_buffers.end() && !it->second.empty()) { out.type = ty; - out.value = std::move(it->second.front()); + out.bytes = it->second.front().bytes; + out.value = std::move(it->second.front().value); it->second.pop_front(); + if (m_buffered_events > 0) { + --m_buffered_events; + } + m_buffered_bytes -= std::min(m_buffered_bytes, out.bytes); return true; } } return false; } - void ExecutionContext::set_waiter( + ExecutionContext::WaiterId ExecutionContext::set_waiter( std::span types, std::coroutine_handle<> cont, EventEnvelope* slot, bool* timed_out, - std::optional deadline) + std::optional deadline, + ScopeId scope, bool* cancelled) { Waiter w; w.id = m_next_waiter++; + w.scope = scope; w.types.assign(types.begin(), types.end()); w.cont = cont; w.slot = slot; w.timed_out = timed_out; + w.cancelled = cancelled; w.timer = 0; if (deadline.has_value()) { const WaiterId id = w.id; - w.timer = add_timer(*deadline, [this, id] { - // Timeout: resume that waiter (if still parked) with timed_out. - const auto it = - std::find_if(m_waiters.begin(), m_waiters.end(), - [id](const Waiter& x) { return x.id == id; }); - if (it == m_waiters.end()) { - return; + auto timer_res = try_add_timer( + *deadline, + [this, id] { + const auto it = std::find_if( + m_waiters.begin(), m_waiters.end(), + [id](const Waiter& x) { return x.id == id; }); + if (it == m_waiters.end()) { + return; + } + if (it->timed_out != nullptr) { + *it->timed_out = true; + } + auto cont2 = it->cont; + m_waiters.erase(it); + active_executor().post_completion(cont2); + }, + scope); + if (timer_res) { + w.timer = *timer_res; + } else { + // Fail safe rather than hanging forever if timer table is + // saturated. + if (timed_out != nullptr) { + *timed_out = true; } - if (it->timed_out != nullptr) { - *it->timed_out = true; - } - auto cont2 = it->cont; - m_waiters.erase(it); - m_executor.post(cont2); - }); + active_executor().post_completion(cont); + return w.id; + } } m_waiters.push_back(std::move(w)); + return m_waiters.back().id; } - ExecutionContext::TimerId ExecutionContext::add_timer( - std::chrono::steady_clock::time_point deadline, - std::function - on_fire) + void ExecutionContext::cancel_waiter(WaiterId id) { + const auto it = + std::find_if(m_waiters.begin(), m_waiters.end(), + [id](const Waiter& x) { return x.id == id; }); + if (it == m_waiters.end()) { + return; + } + cancel_timer(it->timer); + if (it->cancelled != nullptr) { + *it->cancelled = true; + } else if (it->timed_out != nullptr) { + *it->timed_out = true; + } + auto cont = it->cont; + m_waiters.erase(it); + if (cont) { + active_executor().post_completion(cont); + } + } + + void ExecutionContext::cancel_scope(ScopeId scope) + { + if (scope == kNoScope) { + return; + } + std::vector> to_resume; + for (auto it = m_waiters.begin(); it != m_waiters.end();) { + if (it->scope == scope) { + cancel_timer(it->timer); + if (it->cancelled != nullptr) { + *it->cancelled = true; + } else if (it->timed_out != nullptr) { + *it->timed_out = true; + } + if (it->cont) { + to_resume.push_back(it->cont); + } + it = m_waiters.erase(it); + } else { + ++it; + } + } + for (auto it = m_timers.begin(); it != m_timers.end();) { + if (it->second.scope == scope) { + it = m_timers.erase(it); + } else { + ++it; + } + } + for (auto h : to_resume) { + active_executor().post_completion(h); + } + } + + void ExecutionContext::purge_scope(ScopeId scope) + { + if (scope == kNoScope) { + return; + } + for (auto it = m_waiters.begin(); it != m_waiters.end();) { + if (it->scope == scope) { + cancel_timer(it->timer); + it = m_waiters.erase(it); + } else { + ++it; + } + } + for (auto it = m_timers.begin(); it != m_timers.end();) { + if (it->second.scope == scope) { + it = m_timers.erase(it); + } else { + ++it; + } + } + } + + Void::Result::Result + ExecutionContext::try_add_timer( + Time::MonotonicClock::time_point deadline, + std::function on_fire, ScopeId scope) + { + if (m_limits.max_timers > 0 && m_timers.size() >= m_limits.max_timers) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::limit_exceeded, + "ExecutionContext::try_add_timer: max_timers reached")); + } const TimerId id = m_next_timer++; - m_timers.emplace(id, Timer{deadline, std::move(on_fire)}); + m_timers.emplace(id, Timer{deadline, std::move(on_fire), scope}); return id; } + ExecutionContext::TimerId + ExecutionContext::add_timer(Time::MonotonicClock::time_point deadline, + std::function on_fire, + ScopeId scope) + { + auto r = try_add_timer(deadline, std::move(on_fire), scope); + return r ? *r : 0; + } + void ExecutionContext::cancel_timer(TimerId id) { if (id != 0) { @@ -84,10 +327,10 @@ namespace Void::Fsm::Detail } } - std::optional + std::optional ExecutionContext::next_deadline() const { - std::optional next; + std::optional next; for (const auto& [id, timer] : m_timers) { if (!next.has_value() || timer.deadline < *next) { next = timer.deadline; @@ -101,7 +344,7 @@ namespace Void::Fsm::Detail if (m_timers.empty()) { return; } - const auto now = std::chrono::steady_clock::now(); + const auto now = m_clock->now(); std::vector> due; for (auto it = m_timers.begin(); it != m_timers.end();) { if (it->second.deadline <= now) { @@ -120,20 +363,36 @@ namespace Void::Fsm::Detail void ExecutionContext::deliver(EventEnvelope& env) { - // Route to the first parked waiter (FIFO) that wants this type — lets - // it receive the event without ever sitting in a buffer. for (auto it = m_waiters.begin(); it != m_waiters.end(); ++it) { if (it->wants(*env.type)) { *it->slot = std::move(env); cancel_timer(it->timer); auto cont = it->cont; m_waiters.erase(it); - m_executor.post(cont); + active_executor().post_completion(cont); return; } } - // Otherwise buffer for a later await. - m_buffers[std::type_index{*env.type}].push_back(std::move(env.value)); + if (m_limits.max_deferred_events > 0 && + m_buffered_events >= m_limits.max_deferred_events) { + Void::Log::warn("Fsm", + "dropping deferred event: max_deferred_events reached"); + return; + } + m_buffered_events += 1; + m_buffered_bytes += env.bytes; + m_buffers[std::type_index{*env.type}].push_back( + BufferedEvent{std::move(env.value), env.bytes}); + } + + void ExecutionContext::drain_control_queue() + { + while (auto fn = m_control_queue.try_pop()) { + m_queued_control.fetch_sub(1, std::memory_order_acq_rel); + if (*fn) { + (*fn)(); + } + } } void ExecutionContext::set_paused(bool paused) @@ -144,22 +403,81 @@ namespace Void::Fsm::Detail std::size_t ExecutionContext::pump() { + drain_control_queue(); if (m_paused.load(std::memory_order_acquire)) { return 0; } + + ++m_dispatch_turn; std::size_t work = 0; + std::size_t events_this_turn = 0; + const auto turn_start = m_clock->now(); + fire_due_timers(); - while (auto env = m_queue.try_pop()) { + + while (events_this_turn < m_limits.max_events_per_turn) { + if (m_limits.max_turn_duration.count() > 0 && + events_this_turn > 0 && + (m_clock->now() - turn_start) >= m_limits.max_turn_duration) { + break; + } + auto env = m_queue.try_pop(); + if (!env) { + break; + } + m_queued_events.fetch_sub(1, std::memory_order_acq_rel); + m_queued_bytes.fetch_sub(env->bytes, std::memory_order_acq_rel); deliver(*env); + ++events_this_turn; ++work; } - work += m_executor.drain(); + m_last_turn_events = events_this_turn; + + drain_control_queue(); + if (m_external_executor == nullptr) { + work += m_executor.drain(); + } fire_due_timers(); + drain_control_queue(); return work; } + void ExecutionContext::run_external_pump_step() + { + if (m_done.load(std::memory_order_acquire)) { + m_pump_scheduled.store(false, std::memory_order_release); + return; + } + m_pump_scheduled.store(false, std::memory_order_seq_cst); + (void)pump(); + if (!m_done.load(std::memory_order_acquire) && + (!m_control_queue.empty() || + (!m_paused.load(std::memory_order_acquire) && !m_queue.empty()))) { + schedule_external_pump(); + } + } + + void ExecutionContext::schedule_external_pump() noexcept + { + if (m_external_executor == nullptr || + m_done.load(std::memory_order_acquire)) { + return; + } + auto weak = weak_from_this(); + if (weak.expired()) { + return; + } + if (!m_pump_scheduled.exchange(true, std::memory_order_acq_rel)) { + Async::spawn(*m_external_executor, + external_pump_task(std::move(weak))); + } + } + void ExecutionContext::wake() noexcept { + if (m_external_executor != nullptr) { + schedule_external_pump(); + } if (m_sleeping.exchange(false, std::memory_order_acq_rel)) { m_wakeup.release(); } @@ -204,22 +522,25 @@ namespace Void::Fsm::Detail const bool paused = m_paused.load(std::memory_order_acquire); if (!paused) { pump(); + } else { + drain_control_queue(); } if (m_done.load(std::memory_order_acquire)) { return; } m_sleeping.store(true, std::memory_order_release); - // Queued events only count as wakeable work when not paused. - if ((!paused && !m_queue.empty()) || + if ((!paused && !m_queue.empty()) || !m_control_queue.empty() || m_done.load(std::memory_order_acquire)) { m_sleeping.store(false, std::memory_order_release); continue; } - // Park until woken (post/resume/finish), or — when running — until - // the earliest timer is due. Paused: no timers, wait to resume. if (const auto deadline = next_deadline(); !paused && deadline.has_value()) { - (void)m_wakeup.try_acquire_until(*deadline); + if (m_clock == &Time::SystemMonotonicClock::instance()) { + (void)m_wakeup.try_acquire_until(*deadline); + } else { + (void)m_wakeup.try_acquire_for(std::chrono::milliseconds{1}); + } } else { m_wakeup.acquire(); } diff --git a/src/Fsm/module.cmake b/src/Fsm/module.cmake index cc6af1f..72d3063 100644 --- a/src/Fsm/module.cmake +++ b/src/Fsm/module.cmake @@ -1,3 +1,3 @@ void_add_module(Fsm - INTERNAL_DEPS Async Core Data Functional Log Service + INTERNAL_DEPS Async Core Data Functional Time Log Service ) diff --git a/tests/package/FsmOnly/CMakeLists.txt b/tests/package/FsmOnly/CMakeLists.txt new file mode 100644 index 0000000..e212e09 --- /dev/null +++ b/tests/package/FsmOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidFsmOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Fsm) + +add_executable(void_fsm_only_consumer main.cpp) +target_link_libraries(void_fsm_only_consumer PRIVATE Void::Fsm) +target_compile_features(void_fsm_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME FsmOnlyConsumer COMMAND void_fsm_only_consumer) diff --git a/tests/package/FsmOnly/main.cpp b/tests/package/FsmOnly/main.cpp new file mode 100644 index 0000000..4be33d8 --- /dev/null +++ b/tests/package/FsmOnly/main.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +#include +#include + +#include + +struct ConsumerMachine : public Void::Fsm::Machine { + using Success = int; + + struct States { + struct Start : State { + Void::Coro::Task run() + { + co_return succeed(42); + } + }; + }; +}; + +Void::Coro::Task drive_consumer_fsm( + Void::Fsm::ExecutionBinding binding, + std::optional>>* out) +{ + ConsumerMachine fsm; + *out = co_await fsm.run(binding); +} + +int main() +{ + if (!Void::Fsm::terminal(Void::Fsm::Status::Faulted)) { + return 1; + } + Void::Async::ManualExecutor exec; + Void::Time::ManualClock clock; + std::optional>> out; + Void::Async::spawn( + exec, + drive_consumer_fsm( + {.executor = &exec, .clock = &clock}, &out)); + (void)exec.drain(); + if (!out.has_value() || !out->has_value() || !out->value().has_value()) { + return 2; + } + return out->value().value() == 42 ? 0 : 3; +} diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index 1d00274..e23d018 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -282,6 +282,16 @@ if(_has_configuration_async) -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) endif() +has_modules(_has_fsm Fsm Async Core Data Functional Time Log Service) +if(_has_fsm) + run_consumer(FsmOnly "${install_prefix}" "FsmOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/standalone/Fsm/FsmHardening.cpp b/tests/standalone/Fsm/FsmHardening.cpp new file mode 100644 index 0000000..07a4d00 --- /dev/null +++ b/tests/standalone/Fsm/FsmHardening.cpp @@ -0,0 +1,1108 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace void_fsm_hardening_test +{ + using Void::Coro::Task; + using Void::Fsm::Checkpoint; + using Void::Fsm::ExecutionBinding; + using Void::Fsm::FsmError; + using Void::Fsm::FsmErrorCode; + using Void::Fsm::FsmLimits; + using Void::Fsm::Machine; + using Void::Fsm::MachineOptions; + using Void::Fsm::Orchestrator; + using Void::Fsm::OrchestratorLimits; + using Void::Fsm::State; + using Void::Fsm::StateId; + using Void::Fsm::StateKey; + using Void::Fsm::Status; + using Void::Fsm::SupervisionEvent; + using Void::Fsm::SupervisionMode; + using Void::Fsm::SupervisionPolicy; + using Void::Fsm::TerminationReason; + using Void::Fsm::Transition; + using namespace std::chrono_literals; + + template + Task assign_task_result(Task task, std::optional* out) + { + *out = co_await task; + } + + template + T drive_task(Void::Async::ManualExecutor& exec, Task task) + { + std::optional out; + Void::Async::spawn(exec, assign_task_result(std::move(task), &out)); + (void)exec.drain(); + return std::move(*out); + } + + struct Ping { + int value{0}; + }; + + struct NeverEvent { + }; + + struct SizedEvent { + std::size_t bytes{0}; + [[nodiscard]] std::size_t payload_bytes() const noexcept + { + return bytes; + } + }; + + // ── Supervision test machines ──────────────────────────────────────── + class FaultingWorker : public Machine + { + public: + + using Success = int; + + struct States { + struct Boom : State { + Task run() + { + throw std::runtime_error("worker fault"); + co_return succeed(0); + } + }; + }; + + explicit FaultingWorker(std::atomic* runs = nullptr) + : m_runs(runs) + { + } + + protected: + + void on_machine_enter() override + { + if (m_runs != nullptr) { + m_runs->fetch_add(1, std::memory_order_acq_rel); + } + } + + private: + + std::atomic* m_runs; + }; + + class ParkedWorker : public Machine + { + public: + + using Success = int; + + struct States { + struct Wait : State { + Task run() + { + auto r = + co_await await_event_cancellable(); + if (!r) { + co_return succeed(0); + } + co_return succeed(r->value); + } + }; + }; + }; + + template bool wait_handle_finished(const HandleT& h) + { + for (int i = 0; i < 500; ++i) { + if (h.finished()) { + return true; + } + std::this_thread::sleep_for(std::chrono::milliseconds{1}); + } + return h.finished(); + } + + // ── Scope, timer purge, exit fault, observer isolation ─────────────── + class CancellableWaitFsm : public Machine + { + public: + + using Success = int; + + struct States { + struct Wait : State { + Task run() + { + auto r = + co_await await_event_cancellable(); + if (!r) { + co_return succeed(-1); + } + co_return succeed(r->value); + } + }; + }; + + CancellableWaitFsm() : Machine(MachineOptions{.own_worker = false}) {} + }; + + class TimerPurgeFsm : public Machine + { + public: + + using Success = int; + + std::atomic* orphaned_timer_fired{nullptr}; + bool* limit_hit{nullptr}; + const Void::Time::MonotonicClock* clock{nullptr}; + + struct States { + struct First : State { + Task run() + { + auto* ctx = machine().execution_context(); + const auto scope = machine().active_scope(); + const auto now = self().clock->now(); + auto t1 = ctx->try_add_timer( + now + 20ms, + [flag = self().orphaned_timer_fired] { + if (flag != nullptr) { + flag->store( + true, std::memory_order_release); + } + }, + scope); + Void::Testing::require(t1.has_value()); + + auto t2 = ctx->try_add_timer( + now + 30ms, [] {}, scope); + Void::Testing::require(t2.has_value()); + + auto t3 = ctx->try_add_timer( + now + 40ms, [] {}, scope); + if (self().limit_hit != nullptr) { + *self().limit_hit = + (!t3.has_value() && + t3.error().code().value == + static_cast( + FsmErrorCode::limit_exceeded)); + } + co_return next(); + } + }; + + struct Second : State { + Task run() + { + (void)co_await await_event_cancellable(); + co_return succeed(7); + } + }; + }; + + TimerPurgeFsm() : Machine(MachineOptions{.own_worker = false}) {} + }; + + class ExitThrowFsm : public Machine + { + public: + + using Success = int; + + struct States { + struct S1 : State { + Task run() { co_return succeed(1); } + Task on_exit() override + { + throw std::runtime_error("exit cleanup error"); + co_return; + } + }; + }; + + ExitThrowFsm() : Machine(MachineOptions{.own_worker = false}) {} + }; + + class BoundedHistoryFsm : public Machine + { + public: + + using Success = int; + int steps{0}; + + struct States { + struct Step : State { + Task run() + { + if (++self().steps >= 8) { + co_return succeed(self().steps); + } + co_return next(); + } + }; + }; + + BoundedHistoryFsm() : Machine(MachineOptions{.own_worker = false}) {} + }; + + // ── Structured parallel & race machines ────────────────────────────── + struct SharedRaceFlags { + std::atomic loser_exited{false}; + std::atomic co_child_exited{false}; + }; + + inline SharedRaceFlags* g_flags = nullptr; + + class FastFailChild : public Machine + { + public: + + using Success = int; + using Failure = FsmError; + + struct States { + struct Run : State { + Task run() + { + (void)co_await delay_cancellable(1ms); + co_return fail(FsmError{"winner_fail"}); + } + }; + }; + }; + + class ForeverLoserChild : public Machine + { + public: + + using Success = int; + + struct States { + struct Park : State { + Task run() + { + (void)co_await await_event_cancellable< + NeverEvent>(); + co_return succeed(0); + } + Task on_exit() override + { + if (g_flags != nullptr) { + g_flags->loser_exited.store( + true, std::memory_order_release); + } + co_return; + } + }; + }; + }; + + class RaceParent : public Machine + { + public: + + using Success = int; + using Failure = FsmError; + + struct States { + struct Race : State { + Task run() + { + auto r = co_await run_parallel_any_structured< + FastFailChild, ForeverLoserChild>(); + if (!r) { + co_return fail( + FsmError{r.error().message()}); + } + if (r->index() == 0) { + auto& winner = std::get<0>(*r); + if (!winner.has_value()) { + co_return fail(winner.error()); + } + } + co_return succeed(99); + } + }; + }; + + RaceParent() : Machine(MachineOptions{.own_worker = false}) {} + }; + + class TieChildA : public Machine + { + public: + + using Success = int; + + struct States { + struct Wait : State { + Task run() + { + (void)co_await delay_cancellable(10ms); + co_return succeed(1); + } + }; + }; + }; + + class TieChildB : public Machine + { + public: + + using Success = int; + + struct States { + struct Wait : State { + Task run() + { + (void)co_await delay_cancellable(5ms); + co_return succeed(2); + } + }; + }; + }; + + class TieRaceParent : public Machine + { + public: + + using Success = int; + + struct States { + struct Race : State { + Task run() + { + auto r = co_await run_parallel_any_structured< + TieChildA, TieChildB>(); + if (!r) { + co_return succeed(-1); + } + co_return succeed(static_cast(r->index())); + } + }; + }; + + TieRaceParent() : Machine(MachineOptions{.own_worker = false}) {} + }; + + class FaultParent : public Machine + { + public: + + using Success = int; + std::string observed_error{}; + + class CoopSibling : public Machine + { + public: + + using Success = int; + + struct States { + struct Park : State { + Task run() + { + (void)co_await await_event_cancellable< + NeverEvent>(); + co_return succeed(1); + } + Task on_exit() override + { + if (g_flags != nullptr) { + g_flags->co_child_exited.store( + true, + std::memory_order_release); + } + co_return; + } + }; + }; + }; + + class BoomSibling : public Machine + { + public: + + using Success = int; + + struct States { + struct Boom : State { + Task run() + { + throw std::runtime_error( + "sibling fault"); + co_return succeed(0); + } + }; + }; + }; + + struct States { + struct JoinAll : State { + Task run() + { + auto r = co_await run_parallel_structured< + CoopSibling, BoomSibling>(); + if (!r) { + self().observed_error = + r.error().message(); + co_return succeed(-1); + } + co_return succeed(1); + } + }; + }; + + FaultParent() : Machine(MachineOptions{.own_worker = false}) {} + }; + + class MailboxMachine : public Machine + { + public: + + using Success = int; + int drained{0}; + + struct States { + struct Drain : State { + Task run() + { + for (;;) { + auto ev = + co_await await_event_cancellable< + SizedEvent>(); + if (!ev) { + co_return succeed(self().drained); + } + if (ev->bytes == 0) { + co_return succeed(self().drained); + } + ++self().drained; + } + } + }; + }; + + MailboxMachine() : Machine(MachineOptions{.own_worker = false}) {} + }; + + // ── Checkpoints, migration & service lease machines ────────────────── + struct ICounterSvc : Void::Service::IService { + virtual int version() const = 0; + }; + + struct CounterSvcImpl final : ICounterSvc { + int ver{1}; + explicit CounterSvcImpl(int v) : ver(v) {} + std::string_view service_name() const override + { + return "CounterSvc"; + } + int version() const override { return ver; } + }; + + class WorkflowMachine : public Machine + { + public: + + using Success = int; + + struct Data { + int count{0}; + std::string note{"init"}; + }; + Data data; + bool fail_validation{false}; + int first_handle_ver{0}; + std::uint64_t first_handle_gen{0}; + int second_handle_ver{0}; + std::uint64_t second_handle_gen{0}; + std::string seen_resume_label; + + struct States { + struct [[= StateId{"v2.ingest"}]] Ingest : State { + Task run() + { + self().data.count += 1; + co_await safe_point("after_step1"); + auto h1 = acquire_service(); + if (h1) { + self().first_handle_ver = (*h1)->version(); + self().first_handle_gen = h1->generation(); + } + (void)co_await await_event_cancellable(); + if (h1) { + self().first_handle_ver = (*h1)->version(); + } + auto h2 = acquire_service(); + if (h2) { + self().second_handle_ver = + (*h2)->version(); + self().second_handle_gen = h2->generation(); + } + co_return next(); + } + }; + + struct [[= StateId{"v2.process"}]] Process : State { + Task run() + { + self().seen_resume_label = + std::string{restored_resume_label()}; + self().data.count += 10; + co_return succeed(self().data.count); + } + }; + }; + + WorkflowMachine() : Machine(MachineOptions{.own_worker = false}) + { + set_machine_identity("Workflow", 2); + } + + protected: + + void on_serialize(Void::Json::Value& out) const override + { + out = Void::Json::to_json(data); + } + + Void::Result::Result + on_validate_restore(const Void::Json::Value& in) const override + { + if (fail_validation) { + return Void::Result::fail(Void::Fsm::make_fsm_error( + FsmErrorCode::migration_failed, + "rejected by validator")); + } + const auto* c = in.find("count"); + if (c == nullptr || !c->is_int() || c->as_int() < 0) { + return Void::Result::fail(Void::Fsm::make_fsm_error( + FsmErrorCode::migration_failed, "negative count")); + } + return {}; + } + + void on_restore(const Void::Json::Value& in) override + { + auto parsed = Void::Json::from_json(in); + if (parsed.has_value()) { + data = std::move(*parsed); + } + } + }; + +} // namespace void_fsm_hardening_test + +using namespace void_fsm_hardening_test; + +// @tag reflection +Void::Testing::Test fsm_faulted_terminal_handle_and_supervision_bounds() +{ + Void::Testing::expect(Void::Fsm::terminal(Status::Succeeded)); + Void::Testing::expect(Void::Fsm::terminal(Status::Failed)); + Void::Testing::expect(Void::Fsm::terminal(Status::Faulted)); + Void::Testing::expect(!Void::Fsm::terminal(Status::Idle)); + Void::Testing::expect(!Void::Fsm::terminal(Status::Running)); + + Void::Time::ManualClock clock; + Orchestrator orch{&clock, OrchestratorLimits{.max_supervised = 2}}; + + std::vector seen_kinds; + std::size_t inside_running_count = 999; + orch.observe_supervision([&](const SupervisionEvent& ev) { + seen_kinds.push_back(ev.kind); + // Must execute outside Orchestrator's m_mutex without deadlock. + inside_running_count = orch.running_count(); + }); + orch.observe_supervision([](const SupervisionEvent&) { + throw std::runtime_error("supervision observer threw"); + }); + + // StopOnFault: FsmHandle::finished() treats Faulted as terminal, and + // handle retains immutable evidence after reap_finished(). + auto h_fault = orch.try_launch(SupervisionPolicy{}); + Void::Testing::require(h_fault.has_value()); + Void::Testing::require(wait_handle_finished(*h_fault)); + Void::Testing::expect(h_fault->finished()); + Void::Testing::expect_eq(h_fault->status(), Status::Faulted); + Void::Testing::expect_eq(h_fault->termination_reason(), + TerminationReason::faulted); + Void::Testing::require(h_fault->system_error().has_value()); + + Void::Testing::expect_eq(orch.reap_finished(), std::size_t{1}); + Void::Testing::expect_eq(orch.running_count(), std::size_t{0}); + Void::Testing::expect(h_fault->finished()); + Void::Testing::expect_eq(h_fault->status(), Status::Faulted); + Void::Testing::expect(inside_running_count <= 2); + Void::Testing::expect(!orch.observer_errors().empty()); + + // Enforce max_supervised = 2. + auto p1 = orch.try_launch(SupervisionPolicy{}); + auto p2 = orch.try_launch(SupervisionPolicy{}); + Void::Testing::require(p1.has_value() && p2.has_value()); + auto p3 = orch.try_launch(SupervisionPolicy{}); + Void::Testing::expect(!p3.has_value()); + Void::Testing::expect_eq( + p3.error().code().value, + static_cast(FsmErrorCode::limit_exceeded)); + orch.stop_all(); + + // BoundedRestart: 3 restarts within 60s on injected ManualClock with + // exponential backoff (10ms, 20ms, 40ms), then budget exhausted. + std::atomic runs{0}; + SupervisionPolicy br_policy{ + .mode = SupervisionMode::BoundedRestart, + .max_restarts = 3, + .restart_window = 60s, + .initial_backoff = 10ms, + }; + auto br = orch.try_launch(br_policy, &runs); + Void::Testing::require(br.has_value()); + Void::Testing::require(wait_handle_finished(*br)); + + const std::chrono::milliseconds backoffs[] = {10ms, 20ms, 40ms}; + for (std::size_t i = 0; i < 3; ++i) { + Void::Testing::expect_eq(orch.supervise_step(), std::size_t{1}); + // Halfway through backoff: must not restart prematurely. + (void)clock.advance(backoffs[i] / 2); + Void::Testing::expect_eq(orch.supervise_step(), std::size_t{0}); + Void::Testing::expect_eq(br->restart_count(), i); + + (void)clock.advance(backoffs[i] - backoffs[i] / 2); + Void::Testing::expect_eq(orch.supervise_step(), std::size_t{1}); + Void::Testing::expect_eq(br->restart_count(), i + 1); + Void::Testing::require(wait_handle_finished(*br)); + } + + // 4th fault within 60s exhausts restart budget and releases active slot. + Void::Testing::expect_eq(orch.supervise_step(), std::size_t{1}); + Void::Testing::expect_eq(orch.running_count(), std::size_t{0}); + Void::Testing::expect_eq(br->restart_count(), std::size_t{3}); + Void::Testing::expect_eq(br->status(), Status::Faulted); + Void::Testing::expect_eq(runs.load(), 4); + Void::Testing::expect(!seen_kinds.empty()); +} + +// @tag reflection +Void::Testing::Test fsm_structured_scopes_cancellation_timers_and_exit_fault() +{ + Void::Async::ManualExecutor exec; + Void::Time::ManualClock clock; + + // Deadline timeout + external stop token cancellation via ExecutionBinding. + { + CancellableWaitFsm fsm; + std::optional>> out; + Void::Async::spawn( + exec, + assign_task_result( + fsm.run({.executor = &exec, .clock = &clock}, + {.deadline = clock.now() + 50ms}), + &out)); + (void)exec.drain(); + Void::Testing::expect(!out.has_value()); + (void)clock.advance(50ms); + (void)fsm.pump(); + (void)exec.drain(); + Void::Testing::require(out.has_value()); + Void::Testing::expect(!out->has_value()); + Void::Testing::expect_eq( + out->error().code().value, + static_cast(FsmErrorCode::timeout)); + Void::Testing::expect_eq(fsm.status(), Status::Faulted); + Void::Testing::expect_eq(fsm.termination_reason(), + TerminationReason::timed_out); + } + { + CancellableWaitFsm fsm; + std::stop_source ss; + std::optional>> out; + Void::Async::spawn( + exec, + assign_task_result( + fsm.run({.executor = &exec, .clock = &clock}, + {.stop = ss.get_token()}), + &out)); + (void)exec.drain(); + Void::Testing::expect(!out.has_value()); + ss.request_stop(); + (void)exec.drain(); + Void::Testing::require(out.has_value()); + Void::Testing::expect(!out->has_value()); + Void::Testing::expect_eq( + out->error().code().value, + static_cast(FsmErrorCode::cancelled)); + Void::Testing::expect_eq(fsm.status(), Status::Faulted); + Void::Testing::expect_eq(fsm.termination_reason(), + TerminationReason::cancelled); + } + + // Queued timer after state exit must never fire + max_timers enforced. + { + std::atomic orphan_fired{false}; + bool limit_hit{false}; + TimerPurgeFsm fsm; + fsm.orphaned_timer_fired = &orphan_fired; + fsm.limit_hit = &limit_hit; + fsm.clock = &clock; + + std::optional>> out; + FsmLimits limits; + limits.max_timers = 2; + Void::Async::spawn( + exec, + assign_task_result( + fsm.run({.executor = &exec, .clock = &clock, .limits = limits}), + &out)); + (void)exec.drain(); + Void::Testing::expect(limit_hit); + + (void)clock.advance(100ms); + (void)fsm.pump(); + (void)exec.drain(); + Void::Testing::expect(!orphan_fired.load(std::memory_order_acquire)); + + Void::Testing::require(fsm.try_post(Ping{1}).has_value()); + (void)exec.drain(); + Void::Testing::require(out.has_value() && out->has_value() && + out->value().has_value()); + Void::Testing::expect_eq(out->value().value(), 7); + } + + // on_exit exception faults the machine cleanly. + { + ExitThrowFsm fsm; + auto res = drive_task( + exec, fsm.run({.executor = &exec, .clock = &clock})); + Void::Testing::expect(!res.has_value()); + Void::Testing::expect_eq(fsm.status(), Status::Faulted); + Void::Testing::expect_eq(fsm.termination_reason(), + TerminationReason::faulted); + Void::Testing::require(fsm.system_error().has_value()); + } + + // Observer throws isolated + bounded transition history (max 4). + { + BoundedHistoryFsm fsm; + fsm.observe([](const Transition&) { + throw std::runtime_error("observer failed"); + }); + fsm.add_interceptor({ + .before = [](const Transition&) { + throw std::runtime_error("interceptor before failed"); + }, + .after = [](std::string_view) { + throw std::runtime_error("interceptor after failed"); + }, + }); + FsmLimits limits; + limits.max_retained_transitions = 4; + auto res = drive_task( + exec, + fsm.run({.executor = &exec, .clock = &clock, .limits = limits})); + Void::Testing::require(res.has_value() && res->has_value()); + Void::Testing::expect_eq(res->value(), 8); + Void::Testing::expect_eq(fsm.transition_history().size(), + std::size_t{4}); + Void::Testing::expect_eq(fsm.observer_errors().size(), std::size_t{24}); + } +} + +// @tag reflection +Void::Testing::Test fsm_parallel_structured_loser_join_tiebreak_and_mailbox_bounds() +{ + Void::Async::ManualExecutor exec; + Void::Time::ManualClock clock; + SharedRaceFlags flags; + g_flags = &flags; + + // Race-any: typed Failure wins and forever-waiting loser is stopped and + // joined BEFORE run_parallel_any_structured returns. + { + RaceParent fsm; + std::optional>> out; + Void::Async::spawn( + exec, + assign_task_result( + fsm.run({.executor = &exec, .clock = &clock}), &out)); + (void)exec.drain(); + Void::Testing::expect(!out.has_value()); + (void)clock.advance(1ms); + (void)fsm.pump(); + (void)exec.drain(); + Void::Testing::require(out.has_value() && out->has_value()); + Void::Testing::expect(!(*out)->has_value()); + Void::Testing::expect_eq((*out)->error().message, + std::string{"winner_fail"}); + Void::Testing::expect(flags.loser_exited.load(std::memory_order_acquire)); + } + + // Same-turn completion tie-break uses child declaration order (index 0). + { + TieRaceParent fsm; + std::optional>> out; + Void::Async::spawn( + exec, + assign_task_result( + fsm.run({.executor = &exec, .clock = &clock}), &out)); + (void)exec.drain(); + // Advance clock past BOTH 5ms and 10ms in one step so both timers fire + // in the same dispatch turn -> TieChildA (index 0) must win! + (void)clock.advance(20ms); + (void)fsm.pump(); + (void)exec.drain(); + Void::Testing::require(out.has_value() && out->has_value() && + out->value().has_value()); + Void::Testing::expect_eq(out->value().value(), 0); + } + + // Structured parallel-all: sibling Fault triggers cooperative stop and join. + { + FaultParent fsm; + auto res = drive_task( + exec, fsm.run({.executor = &exec, .clock = &clock})); + Void::Testing::require(res.has_value() && res->has_value()); + Void::Testing::expect_eq(res->value(), -1); + Void::Testing::expect( + flags.co_child_exited.load(std::memory_order_acquire)); + Void::Testing::expect(fsm.observed_error.find("sibling fault") != + std::string::npos); + } + + g_flags = nullptr; + + // Mailbox event/byte caps + reserved control lane + 64-event turn budget. + { + MailboxMachine fsm; + FsmLimits limits; + limits.max_mailbox_events = 3; + limits.max_mailbox_bytes = 64; + limits.max_events_per_turn = 64; + + std::optional>> out; + Void::Async::spawn( + exec, + assign_task_result( + fsm.run({.executor = &exec, .clock = &clock, .limits = limits}), + &out)); + (void)exec.drain(); + + // Byte limit check. + auto over_bytes = fsm.try_post(SizedEvent{128}); + Void::Testing::expect(!over_bytes.has_value()); + Void::Testing::expect_eq( + over_bytes.error().code().value, + static_cast(FsmErrorCode::overloaded)); + + // Fill 3 events. + Void::Testing::require(fsm.try_post(SizedEvent{8}).has_value()); + Void::Testing::require(fsm.try_post(SizedEvent{8}).has_value()); + Void::Testing::require(fsm.try_post(SizedEvent{8}).has_value()); + auto over_cnt = fsm.try_post(SizedEvent{8}); + Void::Testing::expect(!over_cnt.has_value()); + Void::Testing::expect_eq( + over_cnt.error().code().value, + static_cast(FsmErrorCode::overloaded)); + + // Reserved control lane still accepts checkpoint request under user + // mailbox saturation (timed out once clock advances). + std::optional> cp_out; + Void::Async::spawn( + exec, + assign_task_result( + fsm.request_checkpoint({.deadline = clock.now() + 5ms}), + &cp_out)); + (void)clock.advance(5ms); + (void)fsm.pump(); + (void)exec.drain(); + Void::Testing::require(cp_out.has_value()); + Void::Testing::expect(!cp_out->has_value()); + + Void::Testing::require(fsm.try_post(SizedEvent{0}).has_value()); + (void)exec.drain(); + Void::Testing::require(out.has_value() && out->has_value() && + out->value().has_value()); + Void::Testing::expect_eq(out->value().value(), 3); + } + + // 64-event turn budget on pump(). + { + MailboxMachine fsm; + FsmLimits limits; + limits.max_mailbox_events = 256; + limits.max_events_per_turn = 64; + std::optional>> out; + Void::Async::spawn( + exec, + assign_task_result( + fsm.run({.executor = &exec, .clock = &clock, .limits = limits}), + &out)); + (void)exec.drain(); + + for (int i = 0; i < 100; ++i) { + Void::Testing::require(fsm.try_post(SizedEvent{4}).has_value()); + } + // One pump processes at most 64 user events before yielding. + (void)fsm.pump(); + Void::Testing::expect_eq(fsm.execution_context()->last_turn_events(), + std::size_t{64}); + (void)exec.drain(); + Void::Testing::require(fsm.try_post(SizedEvent{0}).has_value()); + (void)exec.drain(); + Void::Testing::require(out.has_value() && out->has_value() && + out->value().has_value()); + Void::Testing::expect_eq(out->value().value(), 100); + } +} + +// @tag reflection +Void::Testing::Test fsm_boundary_checkpoint_migration_and_owning_service_handle() +{ + Void::Async::ManualExecutor exec; + Void::Time::ManualClock clock; + + // Duplicate durable StateId rejected; checkpoint at safe_point succeeds and + // survives provider swap across await via acquire_service(). + Void::Service::ServiceRegistry registry; + Void::Service::ProviderSet pset1; + pset1.add("c1", std::make_shared(1)); + Void::Testing::require(registry.start_and_publish(std::move(pset1)).has_value()); + + Checkpoint captured_cp; + { + WorkflowMachine fsm; + fsm.set_services(registry); + auto dup = fsm.register_state_id( + "v2.ingest"); + Void::Testing::expect(!dup.has_value()); + + std::optional>> out; + std::optional> cp_out; + Void::Async::spawn( + exec, + assign_task_result( + fsm.run({.executor = &exec, .clock = &clock}), &out)); + Void::Async::spawn( + exec, + assign_task_result( + fsm.request_checkpoint({.deadline = clock.now() + 100ms}), + &cp_out)); + (void)exec.drain(); + + Void::Testing::require(cp_out.has_value() && cp_out->has_value()); + captured_cp = std::move(**cp_out); + Void::Testing::expect_eq(captured_cp.state_id, + std::string{"v2.ingest"}); + Void::Testing::expect_eq(captured_cp.resume_label, + std::string{"after_step1"}); + Void::Testing::expect_eq(captured_cp.application_schema, + std::uint32_t{2}); + + // Hot-swap service from v1 -> v2 while Ingest is suspended waiting for + // Ping; Ingest's held ServiceHandle must keep v1 alive. + Void::Service::ProviderSet pset2; + pset2.add("c2", std::make_shared(2)); + Void::Testing::require( + registry.start_and_publish(std::move(pset2)).has_value()); + + Void::Testing::require(fsm.try_post(Ping{1}).has_value()); + (void)exec.drain(); + + Void::Testing::require(out.has_value() && out->has_value() && + out->value().has_value()); + Void::Testing::expect_eq(out->value().value(), 11); + Void::Testing::expect_eq(fsm.first_handle_ver, 1); + Void::Testing::expect_eq(fsm.first_handle_gen, std::uint64_t{1}); + Void::Testing::expect_eq(fsm.second_handle_ver, 2); + Void::Testing::expect_eq(fsm.second_handle_gen, std::uint64_t{2}); + } + + // Validate-then-commit restore: migration failure leaves Idle machine + // unchanged; valid migration + legacy restore succeed atomically. + { + WorkflowMachine fsm; + fsm.data.count = 42; + fsm.data.note = "untouched"; + + Checkpoint bad_schema = captured_cp; + bad_schema.application_schema = 1; + auto r1 = fsm.restore_checkpoint(bad_schema); // no migrator + Void::Testing::expect(!r1.has_value()); + Void::Testing::expect_eq( + r1.error().code().value, + static_cast(FsmErrorCode::schema_mismatch)); + Void::Testing::expect_eq(fsm.data.count, 42); + + auto r2 = fsm.restore_checkpoint( + bad_schema, [](std::uint32_t, std::uint32_t, Void::Json::Value&, + std::string&) -> Void::Result::Result { + throw std::runtime_error("migrator boom"); + }); + Void::Testing::expect(!r2.has_value()); + Void::Testing::expect_eq( + r2.error().code().value, + static_cast(FsmErrorCode::migration_failed)); + Void::Testing::expect_eq(fsm.data.count, 42); + Void::Testing::expect_eq(fsm.data.note, std::string{"untouched"}); + + // Schema 1 -> Schema 2 valid migration onto Process with resume label. + auto r3 = fsm.restore_checkpoint( + bad_schema, + [](std::uint32_t, std::uint32_t, Void::Json::Value& data, + std::string& sid) -> Void::Result::Result { + sid = "v2.process"; + data = Void::Json::object(); + data.as_object().emplace_back( + "count", Void::Json::Value{std::int64_t{20}}); + data.as_object().emplace_back("note", + Void::Json::Value{"migrated"}); + return {}; + }); + Void::Testing::require(r3.has_value()); + auto res = drive_task( + exec, fsm.run({.executor = &exec, .clock = &clock})); + Void::Testing::require(res.has_value() && res->has_value()); + Void::Testing::expect_eq(res->value(), 30); + Void::Testing::expect_eq(fsm.seen_resume_label, + std::string{"after_step1"}); + } + + // Explicit legacy {state, data} reader with old->durable state map. + { + WorkflowMachine fsm; + const auto legacy = Void::Json::parse( + R"({"state":"OldProcess","data":{"count":5,"note":"legacy"}})"); + Void::Testing::require(legacy.has_value()); + const std::unordered_map id_map{ + {"OldProcess", "v2.process"}}; + auto lr = fsm.restore_legacy_checkpoint( + *legacy, id_map, + [](std::uint32_t, std::uint32_t, Void::Json::Value&, + std::string&) -> Void::Result::Result { return {}; }); + Void::Testing::require(lr.has_value()); + auto res = drive_task( + exec, fsm.run({.executor = &exec, .clock = &clock})); + Void::Testing::require(res.has_value() && res->has_value()); + Void::Testing::expect_eq(res->value(), 15); + } +} From 40b579d68368b237a57d75804ed6493ba08fd947 Mon Sep 17 00:00:00 2001 From: faumaray Date: Thu, 26 Nov 2026 17:10:54 +0300 Subject: [PATCH 6/9] fix(fsm): publish terminal status after exit hooks and join worker before derived teardown --- include/Void/Fsm/Machine.hpp | 71 ++++++++++++++++--------------- include/Void/Fsm/Orchestrator.hpp | 7 +++ 2 files changed, 43 insertions(+), 35 deletions(-) diff --git a/include/Void/Fsm/Machine.hpp b/include/Void/Fsm/Machine.hpp index db9372e..1dcb9bf 100644 --- a/include/Void/Fsm/Machine.hpp +++ b/include/Void/Fsm/Machine.hpp @@ -647,7 +647,7 @@ namespace Void::Fsm if (opts.stop.stop_requested()) { m_termination_reason.store(TerminationReason::cancelled, std::memory_order_release); - fault("cancelled before start"); + finish_with_fault("cancelled before start", false); co_return Void::Result::fail(make_fsm_error( FsmErrorCode::cancelled, "Machine::run: cancelled before start")); @@ -655,7 +655,7 @@ namespace Void::Fsm if (opts.deadline.has_value() && clk->now() >= *opts.deadline) { m_termination_reason.store(TerminationReason::timed_out, std::memory_order_release); - fault("deadline expired before start"); + finish_with_fault("deadline expired before start", false); co_return Void::Result::fail(make_fsm_error( FsmErrorCode::timeout, "Machine::run: deadline expired before start")); @@ -2195,7 +2195,7 @@ namespace Void::Fsm } } - void fault(std::string message) + void finish_with_fault(std::string message, bool call_machine_exit) { m_system_error = FsmError{std::move(message)}; if (m_termination_reason.load(std::memory_order_acquire) == @@ -2205,18 +2205,23 @@ namespace Void::Fsm } Void::Log::error("Fsm", "system fault: {}", m_system_error->message); - m_status.store(Status::Faulted, std::memory_order_release); reject_pending_checkpoints(make_fsm_error( FsmErrorCode::checkpoint_rejected, "machine faulted before checkpoint boundary")); + if (call_machine_exit) { + on_machine_exit(); + } + m_parent_stop_link.reset(); + // Publish terminal status strictly last so polling/joining + // threads synchronize after all virtual hooks and field writes. + m_status.store(Status::Faulted, std::memory_order_release); } Coro::Task drive() { const std::type_info* cur = m_initial; if (cur == nullptr) { - fault("no initial state"); - m_parent_stop_link.reset(); + finish_with_fault("no initial state", false); co_return; } on_machine_enter(); @@ -2228,11 +2233,11 @@ namespace Void::Fsm ? TerminationReason::timed_out : TerminationReason::cancelled, std::memory_order_release); - fault(m_root_timeout.load(std::memory_order_acquire) - ? "deadline expired" - : "cancelled"); - on_machine_exit(); - m_parent_stop_link.reset(); + finish_with_fault( + m_root_timeout.load(std::memory_order_acquire) + ? "deadline expired" + : "cancelled", + true); co_return; } if (const auto* j = @@ -2244,9 +2249,8 @@ namespace Void::Fsm } const auto it = m_factories.find(std::type_index{*cur}); if (it == m_factories.end()) { - fault("transition to unregistered state"); - on_machine_exit(); - m_parent_stop_link.reset(); + finish_with_fault("transition to unregistered state", + true); co_return; } @@ -2338,9 +2342,7 @@ namespace Void::Fsm fire_after(current_state()); if (exit_failed) { - fault(std::move(exit_error)); - on_machine_exit(); - m_parent_stop_link.reset(); + finish_with_fault(std::move(exit_error), true); co_return; } if (body_cancelled || @@ -2350,17 +2352,15 @@ namespace Void::Fsm ? TerminationReason::timed_out : TerminationReason::cancelled, std::memory_order_release); - fault(m_root_timeout.load(std::memory_order_acquire) - ? "deadline expired" - : "cancelled"); - on_machine_exit(); - m_parent_stop_link.reset(); + finish_with_fault( + m_root_timeout.load(std::memory_order_acquire) + ? "deadline expired" + : "cancelled", + true); co_return; } if (body_failed) { - fault(std::move(body_error)); - on_machine_exit(); - m_parent_stop_link.reset(); + finish_with_fault(std::move(body_error), true); co_return; } @@ -2379,32 +2379,31 @@ namespace Void::Fsm m_termination_reason.store( TerminationReason::succeeded, std::memory_order_release); - m_status.store(Status::Succeeded, - std::memory_order_release); reject_pending_checkpoints(make_fsm_error( FsmErrorCode::checkpoint_rejected, "machine succeeded before checkpoint boundary")); on_machine_exit(); m_parent_stop_link.reset(); + m_status.store(Status::Succeeded, + std::memory_order_release); co_return; case StateKey::Kind::Fail: m_result_value = std::move(step.payload()); m_termination_reason.store( TerminationReason::failed, std::memory_order_release); - m_status.store(Status::Failed, - std::memory_order_release); reject_pending_checkpoints(make_fsm_error( FsmErrorCode::checkpoint_rejected, "machine failed before checkpoint boundary")); on_machine_exit(); m_parent_stop_link.reset(); + m_status.store(Status::Failed, + std::memory_order_release); co_return; case StateKey::Kind::Fault: - fault(std::any_cast(step.payload()) - .message); - on_machine_exit(); - m_parent_stop_link.reset(); + finish_with_fault( + std::any_cast(step.payload()).message, + true); co_return; } } @@ -2412,9 +2411,11 @@ namespace Void::Fsm Coro::Task driver() { + const bool owns = m_owns_ctx; + auto ctx = m_ctx; co_await drive(); - if (m_owns_ctx && m_ctx) { - m_ctx->finish(); + if (owns && ctx) { + ctx->finish(); } } diff --git a/include/Void/Fsm/Orchestrator.hpp b/include/Void/Fsm/Orchestrator.hpp index 3733846..1af5c01 100644 --- a/include/Void/Fsm/Orchestrator.hpp +++ b/include/Void/Fsm/Orchestrator.hpp @@ -79,6 +79,13 @@ namespace Void::Fsm { } + ~FsmModel() override + { + if (m_fsm) { + m_fsm->stop(); + } + } + void stop() override { m_fsm->stop(); } void restart() override { m_fsm->restart(); } [[nodiscard]] Status status() const override From 1a54f3857e833433cbd7e5016c661654682a5f0d Mon Sep 17 00:00:00 2001 From: faumaray Date: Thu, 26 Nov 2026 17:10:54 +0300 Subject: [PATCH 7/9] fix(plugin): use POSIX pthreads in C11 test fixture for TSan compatibility --- tests/CMakeLists.txt | 4 ++++ tests/plugins/CAbiPluginV1.c | 37 +++++++++++++++++++----------------- 2 files changed, 24 insertions(+), 17 deletions(-) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 7ab3e31..48c2ecb 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -265,6 +265,10 @@ if(TARGET VoidTests AND TARGET Void::Plugin) if(VOID_WARNINGS_AS_ERRORS) target_compile_options(${target_name} PRIVATE -Wall -Wextra -Wpedantic -Werror) endif() + find_package(Threads QUIET) + if(TARGET Threads::Threads) + target_link_libraries(${target_name} PRIVATE Threads::Threads) + endif() if(VOID_ENABLE_ASAN) target_compile_options(${target_name} PRIVATE -fsanitize=address -fno-omit-frame-pointer) target_link_options(${target_name} PRIVATE -fsanitize=address) diff --git a/tests/plugins/CAbiPluginV1.c b/tests/plugins/CAbiPluginV1.c index c3ea077..ccf49fb 100644 --- a/tests/plugins/CAbiPluginV1.c +++ b/tests/plugins/CAbiPluginV1.c @@ -1,11 +1,14 @@ +#define _POSIX_C_SOURCE 200809L + #include +#include #include #include #include #include #include -#include +#include typedef struct cabi_calc_v1 { uint32_t (*version)(void_module_handle* h); @@ -14,7 +17,7 @@ typedef struct cabi_calc_v1 { struct void_operation_handle { void_module_handle* owner; - thrd_t worker; + pthread_t worker; int worker_started; atomic_int cancelled; uint32_t op_kind; @@ -32,7 +35,7 @@ struct void_module_handle { int ckpt_fail; int ckpt_oversized; int ready; - mtx_t ops_mu; + pthread_mutex_t ops_mu; struct void_operation_handle* ops[64]; size_t ops_count; }; @@ -126,7 +129,7 @@ static int32_t cabi_create(const void_host_api_v1* host_api, atomic_init(&h->total, 0); atomic_init(&h->quiescing, 0); h->ready = 1; - mtx_init(&h->ops_mu, mtx_plain); + pthread_mutex_init(&h->ops_mu, NULL); *out_handle = h; return VOID_STATUS_OK; } @@ -296,7 +299,7 @@ static void cabi_release_interface(void_module_handle* h, (void)view; } -static int async_worker(void* arg) +static void* async_worker(void* arg) { struct void_operation_handle* op = (struct void_operation_handle*)arg; int pinned = 0; @@ -315,9 +318,9 @@ static int async_worker(void* arg) op->owner->host.release_activity_pin( op->owner->host.host_ctx, op->owner->host.generation); } - return 0; + return NULL; } - thrd_sleep(&ts, NULL); + nanosleep(&ts, NULL); } int32_t val = atomic_fetch_add(&op->owner->total, op->delta) + op->delta; uint8_t buf[4]; @@ -328,7 +331,7 @@ static int async_worker(void* arg) op->owner->host.release_activity_pin(op->owner->host.host_ctx, op->owner->host.generation); } - return 0; + return NULL; } static int32_t cabi_submit_async(void_module_handle* h, @@ -374,15 +377,15 @@ static int32_t cabi_submit_async(void_module_handle* h, return VOID_STATUS_OK; } - mtx_lock(&h->ops_mu); + pthread_mutex_lock(&h->ops_mu); if (h->ops_count < 64) { h->ops[h->ops_count++] = op; } - mtx_unlock(&h->ops_mu); + pthread_mutex_unlock(&h->ops_mu); op->worker_started = 1; *out_op = op; - if (thrd_create(&op->worker, async_worker, op) != thrd_success) { + if (pthread_create(&op->worker, NULL, async_worker, op) != 0) { op->worker_started = 0; *out_op = NULL; free(op); @@ -407,11 +410,11 @@ static void cabi_release_async(void_module_handle* h, void_operation_handle* op) return; } if (op->worker_started) { - thrd_join(op->worker, NULL); + pthread_join(op->worker, NULL); op->worker_started = 0; } if (h != NULL) { - mtx_lock(&h->ops_mu); + pthread_mutex_lock(&h->ops_mu); for (size_t i = 0; i < h->ops_count; ++i) { if (h->ops[i] == op) { h->ops[i] = h->ops[h->ops_count - 1]; @@ -419,7 +422,7 @@ static void cabi_release_async(void_module_handle* h, void_operation_handle* op) break; } } - mtx_unlock(&h->ops_mu); + pthread_mutex_unlock(&h->ops_mu); } free(op); } @@ -430,13 +433,13 @@ static int32_t cabi_request_stop(void_module_handle* h) return VOID_STATUS_INVALID_ARGUMENT; } atomic_store(&h->quiescing, 1); - mtx_lock(&h->ops_mu); + pthread_mutex_lock(&h->ops_mu); for (size_t i = 0; i < h->ops_count; ++i) { if (h->ops[i] != NULL) { atomic_store(&h->ops[i]->cancelled, 1); } } - mtx_unlock(&h->ops_mu); + pthread_mutex_unlock(&h->ops_mu); return VOID_STATUS_OK; } @@ -450,7 +453,7 @@ static void cabi_destroy(void_module_handle* h) if (h == NULL) { return; } - mtx_destroy(&h->ops_mu); + pthread_mutex_destroy(&h->ops_mu); free(h); } From cb988fa985095776adfc90abb3b6048128a54ff8 Mon Sep 17 00:00:00 2001 From: faumaray Date: Thu, 26 Nov 2026 17:10:54 +0300 Subject: [PATCH 8/9] fix(test): hold owning ServiceHandle across hot-reload calls in FsmServiceHotReload --- tests/internal/FsmServiceHotReload.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/internal/FsmServiceHotReload.cpp b/tests/internal/FsmServiceHotReload.cpp index 8404c27..f27a0c4 100644 --- a/tests/internal/FsmServiceHotReload.cpp +++ b/tests/internal/FsmServiceHotReload.cpp @@ -50,8 +50,11 @@ namespace struct Work : State { Task run() { - auto& svc = service(); - const int total = svc.accumulate(1); + auto svc = acquire_service(); + if (!svc) { + co_return next(); + } + const int total = (*svc)->accumulate(1); if (total >= 500) { co_return succeed(total); } From 9be51134e88c7f0bb7d2b86dccd307815ca3a290 Mon Sep 17 00:00:00 2001 From: faumaray Date: Thu, 26 Nov 2026 20:19:09 +0300 Subject: [PATCH 9/9] docs(workflow): record Wave 8 Service, Plugin, Configuration, and Fsm verification --- docs/agent-workflow/STATE.md | 27 ++++++++++++++++++++------- docs/agent-workflow/TASKS.md | 9 +++++++++ docs/agent-workflow/VERIFICATION.md | 8 ++++++++ 3 files changed, 37 insertions(+), 7 deletions(-) diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index affc963..3979054 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -1,8 +1,8 @@ # Workflow state Updated: 2026-11-26. -Repository: VoidLibrary; active branch `feat/roadmap-p2-wave7` (from `main` -at `43922d1`, merged Waves 1–6B and pushed to `origin/main`). +Repository: VoidLibrary; active branch `feat/roadmap-p2-wave8` (from `main` +at `d83d0f4`, merged Waves 1–7 and pushed to `origin/main`). ## Completed objective @@ -308,10 +308,23 @@ while leaving local untracked files untouched. - **`Void::Storage` (`G-STORE` Gate)** (`fdf0da5`): built NEW original durable single-writer key-value storage engine with zero SQLite or external dependencies (`Crc32c`, `Types`, `FilePort`/`PosixFilePort`/`FaultInjectingFilePort`, V1 binary codecs `VOIDWAL1`/`VOIDTBL1`/`VOIDMNF1`/`VOIDCUR1`, `Batch` with preconditions, `Engine` with bootstrap/recovery/tail-truncation/checkpoint/incremental compaction/backup, `Tools` verify/restore/salvage, `AsyncStorageAdapter` C-03 stop-race conformance) and `StorageOnly` installed consumer. - Integrated verification (`84e6fe8`): `VoidTests` 1,417 tests (1,414 passed, 3 intentionally skipped hardware/root checks, 0 failed across 43 modules in 21.06s), `ctest` 2/2 (all 28 installed consumers in 65.05s), Debug ASan+UBSan 1,417 tests (0 leaks, 0 UB in 36.47s), TSan (`SqliteAsync;Storage;Testing`) 19/19 in 15.38s with 0 warnings, and post-Wave-7 `VoidFoundationBench`. +### Wave 8 (P2 Lifecycle: `Service`, `ServicePlugin`, `Plugin`, `Configuration`, `ConfigurationAsync`, and `Fsm`) + +- Task specs committed on `feat/roadmap-p2-wave8` (`6b3dede`): `tasks/M-SERVICE-01-05.md`, `tasks/M-PLUGIN-01-06.md`, `tasks/M-CONFIGURATION-01-05.md`, `tasks/M-FSM-01-05.md`; error domains `22..25` reserved in `Functional/Error.hpp` (`kServiceErrorDomain`, `kPluginErrorDomain`, `kConfigurationErrorDomain`, `kFsmErrorDomain`); `cmake/Module.cmake` updated to install `*.h` headers. +- **`Void::Service` & `Void::ServicePlugin`** (`1474a69`): immutable `ServiceSnapshot`, owning `ServiceHandle`, transactional DAG `ProviderSet`/`prepare_batch`/`start_staged`/`publish`/`start_and_publish`/`close_and_join`, split `Void::ServicePlugin` helper target, and `ServiceOnly`/`ServicePluginOnly` installed consumers. +- **`Void::Plugin`** (`a24e086`, TSan pthread fixture fix `1a54f38`): pure-C11 `include/Void/Plugin/CAbi.h` v1 (`VOID_PLUGIN_ABI_VERSION`), `CModuleHost` (pins/quiesce/checkpoint/replace/degraded state/retention/byte budgets/dep topological batching), `CAbiAdapter`, unlocked `PluginManager` staging, 9 pure-C11 `-Werror` test fixtures, and `PluginOnly` installed consumer. +- **`Void::Configuration` & `Void::ConfigurationAsync`** (`1dc51d5`): `Bind.hpp` attributes (`Secret`, `RestartRequired`, `Deprecated`, `IntRange`, `RealRange`), bounded `Schema` reflection/provenance/redaction/deprecation validation, async transactional `ReloadController` + `Snapshot` + `prepare_external` + coalescing `WatcherService`, and `ConfigurationOnly`/`ConfigurationAsyncOnly` installed consumers. +- **`Void::Fsm`** (`ef5312c`, TSan fixes `40b579d`, `cb988fa`): `terminal(Status)`/`TerminationReason`, `FsmErrorCode`/`kFsmErrorDomain = 25`, `FsmLimits`, `ExecutionBinding`, `Checkpoint`/`StateId`, hardened `Detail/Engine` (`MonotonicClock`, bounded `try_post`, `m_control_queue`, `ScopeId` waiter/timer tracking, 64-event/1ms turn budget), `Detail/Awaiter` (scope+user `stop_token` cancellation), `Machine::run`/`acquire_service`/`run_parallel_structured`/`run_parallel_any_structured`/`request_checkpoint`/`restore_checkpoint`, `Orchestrator` (`StopOnFault`/`BoundedRestart`, unlocked observers), `tests/standalone/Fsm/FsmHardening.cpp`, and `FsmOnly` installed consumer. +- Integrated verification (`cb988fa`, `-DVOID_WARNINGS_AS_ERRORS=ON`): + - Full RelWithDebInfo (`/tmp/void-w8-full`, 45 modules): `VoidTests` 1,437 tests (1,434 passed, 3 skipped, 0 failed, `20.99s`); `ctest` 2/2 (`77.11s`, all 34 installed consumers); `VoidFoundationBench` post-W8 (`rev=cb988fa98509`, `/tmp/void-w8-full/post-w8.json`): `harness_empty_loop` 0.38ns, `core_uuid_parse_hyphenated` 24.71ns, `core_uuid_to_string` 16.45ns, `core_hash_fnv1a64_256b` 179.94ns, `core_hash_murmur3_256b` 67.31ns, `functional_result_ok_chain` 1.12ns, `functional_error_with_context` 57.98ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.72ns, `containers_lru_get_put` 20.58ns, `binary_reader_u64_be` 1.30ns, `data_json_parse_small_object` 319.62ns, `data_json_serialize_small_object` 167.55ns. + - Full Debug ASan+UBSan (`/tmp/void-w8-asan`, 45 modules): `VoidTests` 1,437 tests (`37.13s`), 0 leaks, 0 UB. + - Debug TSan (`/tmp/void-w8-tsan`, `ServicePlugin;ConfigurationAsync;Fsm;Testing`, 20 modules): `VoidTests` 1,110 tests (1,107 passed, 3 skipped, 0 failed, `11.49s`), 0 data races. + ## Ownership and next step -Waves 1–7 (`P0`, `P1`, `P2` Operations Foundations, `System`/`SystemAsync`/`IPC`, -`Crypto`/`CryptoAsync`/`Security`/`SecurityAsync`/`Archive`/`Update`, and -`Sqlite`/`SqliteAsync`/`Storage` `G-STORE`) are complete and verified on -`feat/roadmap-p2-wave7`, ready to merge `--no-ff` into `main`, push to `origin`, and -proceed continuously to **Wave 8 (`Configuration`, `Fsm`, `Plugin`, `Service`)**. +Waves 1–8 (`P0`, `P1`, `P2` Operations Foundations, `System`/`SystemAsync`/`IPC`, +`Crypto`/`CryptoAsync`/`Security`/`SecurityAsync`/`Archive`/`Update`, +`Sqlite`/`SqliteAsync`/`Storage` `G-STORE`, and +`Service`/`ServicePlugin`/`Plugin`/`Configuration`/`ConfigurationAsync`/`Fsm`) are complete +and merged to `main`, proceeding to the VoidBuildSystem upstream feature wave +(`VL-001`..`VL-013`) and P2 `Net`. diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 25bffc1..241fdf5 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -101,6 +101,15 @@ These tasks author plans. Future feature task IDs inside those plans remain plan | M-SQLITE-01..05 | Hardened `Sqlite` (`kSqliteErrorDomain = 21`, `ConnectionState`, `OpenOptions` checked WAL/FULL/FK pragmas & disabled extension loading, checked binds & borrowed lifetime owners, typed `RowView`, `Transaction` autocommit/busy guards, `Savepoint`, `migrate_checked`, `checkpoint`/`backup_to`/`restore_from`/`health`, exception-safe callbacks, `ScopedFaultGuard`, TSan lock-order fix outside `interrupt_mu`) + optional `SqliteAsync` (`AsyncPool`), `SqliteOnly` & `SqliteAsyncOnly` consumers (`427cc9a`, `84e6fe8`) | [M-SQLITE-01-05](tasks/M-SQLITE-01-05.md) | VERIFIED | Standalone `Sqlite` 14/14 (`426.5ms`), `ctest` 2/2 (`5.11s`), TSan 19/19 (`15.38s`, 0 warnings), full RelWithDebInfo (`1,414 ✔`), ASan+UBSan (0 leaks/UB) | | S-STORAGE-01..06 | NEW original `Void::Storage` (`kStorageErrorDomain = 9`, zero SQLite/external deps, `Crc32c`, `PosixFilePort`/`FaultInjectingFilePort`, V1 `VOIDWAL1`/`VOIDTBL1`/`VOIDMNF1`/`VOIDCUR1` codecs, `Batch` preconditions, single-writer `Engine` with recovery/tail-truncation/checkpoint/compaction/backup, `Tools` verify/restore/salvage, `AsyncStorageAdapter` C-03 stop-race conformance), `G-STORE` gate, `StorageOnly` consumer (`fdf0da5`) | [S-STORAGE-01-06](tasks/S-STORAGE-01-06.md) | VERIFIED | Standalone zero-ext-deps `Storage` 5/5 (`14.53s`), `ctest` 2/2 (`24.07s`), TSan 19/19 (`15.38s`, 0 warnings), full RelWithDebInfo (`1,414 ✔`), ASan+UBSan (0 leaks/UB) | +## Wave 8 — P2 Service, Plugin, Configuration, and Fsm (`feat/roadmap-p2-wave8`) + +| ID | Deliverable | Spec | State | Verification summary | +| --- | --- | --- | --- | --- | +| M-SERVICE-01..05 | Hardened `Service` (`kServiceErrorDomain = 22`, immutable `ServiceSnapshot`, owning `ServiceHandle`, transactional DAG `ProviderSet`/`prepare_batch`/`start_staged`/`publish`/`start_and_publish`/`close_and_join`, retained generation cap) + split `ServicePlugin` (`acquire_plugin_service`, `PluginServiceBinding`), `ServiceOnly` & `ServicePluginOnly` consumers (`6b3dede`, `1474a69`) | [M-SERVICE-01-05](tasks/M-SERVICE-01-05.md) | VERIFIED | Standalone `Service;ServicePlugin;Testing` 18/18, `ctest` 2/2 (`7.47s`), Debug TSan 1,107 ✔ (0 races), full RelWithDebInfo (`1,434 ✔`), ASan+UBSan (0 leaks/UB) | +| M-PLUGIN-01..06 | Hardened `Plugin` (`kPluginErrorDomain = 23`, pure-C11 `CAbi.h` v1, `CModuleHost` activity pins/quiesce/checkpoint/replace/degraded state/retention/byte budgets/dep topological batching, `CAbiAdapter`, unlocked `PluginManager` staging), `PluginOnly` consumer (`a24e086`, `1a54f38`) | [M-PLUGIN-01-06](tasks/M-PLUGIN-01-06.md) | VERIFIED | Standalone `Plugin;ServicePlugin;Testing` 32 ✔ / 1 skip (`194.5ms`), `ctest` 2/2 (`9.45s`), Debug TSan 1,107 ✔ (0 races), full RelWithDebInfo (`1,434 ✔`), ASan+UBSan (0 leaks/UB) | +| M-CONFIGURATION-01..05 | Hardened `Configuration` (`kConfigurationErrorDomain = 24`, `Bind.hpp` attributes, bounded `Schema` reflection/provenance/redaction/deprecation checks) + split `ConfigurationAsync` (transactional `ReloadController`, `Snapshot`, `prepare_external`, coalescing `WatcherService` integration), `ConfigurationOnly` & `ConfigurationAsyncOnly` consumers (`1dc51d5`) | [M-CONFIGURATION-01-05](tasks/M-CONFIGURATION-01-05.md) | VERIFIED | Standalone `ConfigurationAsync;Testing` `Configuration*` 6/6 (`0.7ms`), `ctest` 2/2 (`13.75s`), Debug TSan 1,107 ✔ (0 races), full RelWithDebInfo (`1,434 ✔`), ASan+UBSan (0 leaks/UB) | +| M-FSM-01..05 | Hardened `Fsm` (`kFsmErrorDomain = 25`, shared `terminal(Status)` incl. `Faulted`, `TerminationReason`, `FsmLimits` bounds & reserved control lane, `MonotonicClock` & borrowed `ExecutionBinding`, per-state stop scopes & waiter/timer purge before `on_exit()`, `run_parallel_structured` / `run_parallel_any_structured` loser stop+join & tie-break, boundary `request_checkpoint` / `safe_point` / `restore_checkpoint` / `restore_legacy_checkpoint`, `acquire_service()`, hardened `Orchestrator` `StopOnFault`/`BoundedRestart` & `FsmModel::~FsmModel()` worker join), `FsmOnly` consumer (`ef5312c`, `40b579d`, `cb988fa`) | [M-FSM-01-05](tasks/M-FSM-01-05.md) | VERIFIED | Standalone `Fsm;Testing` 814 ✔ / 2 skips (`789.1ms`), `ctest` 2/2 (`9.59s`), Debug TSan 1,107 ✔ (0 races, `internal_FsmServiceHotReload` 4/4), full RelWithDebInfo (`1,434 ✔`, `ctest` 2/2 `77.11s`), ASan+UBSan (`1,434 ✔`, 0 leaks/UB) | + All workers share the checkout and have disjoint file ownership defined in their persisted task specifications. Root owns all cross-cutting files and resolves contract changes. No worker owns application code, build files, existing docs/short-url.md, or Git diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index 79302d4..15d6e9c 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -273,3 +273,11 @@ Branch: `feat/roadmap-p2-wave6b` (branched from `main` at `acd77ee`). Toolchain | Wave 7 integrated RelWithDebInfo + consumers (`84e6fe8`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-w7-full`), 43 modules, `VoidTests` + `ctest` | **PASSED**: `1,417` discovered (`1,414 ✔`, `3 ⊘` skipped, `0 ✘`) in `21.06s`; `ctest` 2/2 in `65.05s` (`VoidTests` 20.95s, all 28 installed consumers 44.10s) | | Wave 7 full Debug ASan+UBSan (`84e6fe8`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w7-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 43 modules | **PASSED**: `1,417` discovered (`1,414 ✔`, `3 ⊘` skipped, `0 ✘`) in `36.47s`, 0 leaks, 0 UB | | Post-W7 Benchmark (`84e6fe8`, `VOID_GIT_REV=fdf0da5ca883`) | `/tmp/void-w7-full/benchmarks/VoidFoundationBench --json /tmp/void-w7-full/post-w7.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.40ns, `core_uuid_parse_hyphenated` 25.06ns, `core_uuid_to_string` 16.69ns, `core_hash_fnv1a64_256b` 181.03ns, `core_hash_murmur3_256b` 67.90ns, `functional_result_ok_chain` 1.13ns, `functional_error_with_context` 58.24ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.80ns, `containers_lru_get_put` 20.62ns, `binary_reader_u64_be` 1.31ns, `data_json_parse_small_object` 310.70ns, `data_json_serialize_small_object` 160.98ns | +| Wave 8 `Service` & `ServicePlugin` standalone (`1474a69`) | `dev cpp-gcc` RelWithDebInfo (`-Werror`, `/tmp/void-w8-service`, `Service;ServicePlugin;Testing`), `VoidTests` + `ctest` | **PASSED**: `18/18` in `0.4ms`; `ctest` `2/2` in `7.47s` (`ServiceOnly` & `ServicePluginOnly` consumers) | +| Wave 8 `Plugin` standalone (`a24e086`) | `dev cpp-gcc` RelWithDebInfo (`-Werror`, `/tmp/void-w8-plugin`, `Plugin;ServicePlugin;Testing`), 9 pure-C11 `-Werror` fixtures + `VoidTests` + `ctest` | **PASSED**: `33 tests` (`32 ✔`, `1 ⊘` `plugin_load_and_query_skipped`, `0 ✘`) in `194.5ms`; `ctest` `2/2` in `9.45s` (`PluginOnly` consumer) | +| Wave 8 `Configuration` & `ConfigurationAsync` standalone (`1dc51d5`) | `dev cpp-gcc` RelWithDebInfo (`-Werror`, `/tmp/void-w8-config`, `ConfigurationAsync;Testing`), `VoidTests --filter 'Configuration'` + `ctest` | **PASSED**: `ConfigurationHardening` 3/3 + `ConfigurationAsync` 3/3 = `6/6` in `0.7ms`; `ctest` `2/2` in `13.75s` (`ConfigurationOnly` & `ConfigurationAsyncOnly` consumers) | +| Wave 8 `Fsm` standalone (`ef5312c`) | `dev cpp-gcc` RelWithDebInfo (`-Werror`, `/tmp/void-w8-fsm`, `Fsm;Testing`), `VoidTests` + `ctest` | **PASSED**: `816 tests` (`814 ✔`, `2 ⊘`, `0 ✘`) in `789.1ms`; `ctest` `2/2` in `9.59s` (`FsmOnly` consumer) | +| Wave 8 TSan (`cb988fa`) | `dev cpp-gcc` Debug TSan (`-Werror`, `/tmp/void-w8-tsan`, `TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1`), 20 modules (`ServicePlugin;ConfigurationAsync;Fsm;Testing`), `VoidTests` | **PASSED**: `1,110 tests` (`1,107 ✔`, `3 ⊘` skipped, `0 ✘`) in `11.49s` (incl. `ServiceHardening` 5/5, `PluginHardening` 5/5, `Configuration*` 6/6, `FsmHardening` 4/4, `internal_FsmServiceHotReload` 4/4), exit `0`, `0` TSan warnings | +| Wave 8 integrated RelWithDebInfo + consumers (`cb988fa`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-w8-full`), 45 modules, `VoidTests` + `ctest` | **PASSED**: `1,437` discovered (`1,434 ✔`, `3 ⊘` skipped, `0 ✘`) in `20.99s`; `ctest` `2/2` in `77.11s` (`VoidTests` `20.97s`, all `34` installed consumers `56.13s`) | +| Wave 8 full Debug ASan+UBSan (`cb988fa`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w8-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 45 modules | **PASSED**: `1,437` discovered (`1,434 ✔`, `3 ⊘` skipped, `0 ✘`) in `37.13s`, `0` leaks, `0` UB | +| Post-W8 Benchmark (`cb988fa`, `rev=cb988fa98509`) | `/tmp/void-w8-full/benchmarks/VoidFoundationBench --json /tmp/void-w8-full/post-w8.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.38ns, `core_uuid_parse_hyphenated` 24.71ns, `core_uuid_to_string` 16.45ns, `core_hash_fnv1a64_256b` 179.94ns, `core_hash_murmur3_256b` 67.31ns, `functional_result_ok_chain` 1.12ns, `functional_error_with_context` 57.98ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.72ns, `containers_lru_get_put` 20.58ns, `binary_reader_u64_be` 1.30ns, `data_json_parse_small_object` 319.62ns, `data_json_serialize_small_object` 167.55ns |