Host-side additions for applications embedding a plugin system: - PluginManager::load_directory(dir) loads every shared-library file in a directory (filename order) with per-file expected results. - PluginManager::unload(name) drops the registry entry; the instance dies with its last pinned handle (RCU semantics, as on reload). - Optional C entry void_plugin_configure(inst, config): fed from PluginManagerOptions::config_provider after create and after each reload swap, before on_load(). - on_reloaded() is now multi-observer: returns a ReloadCallbackId, remove_on_reloaded() unregisters. Manual reload() now notifies observers too (previously only watched reloads did, contradicting the documented contract). PluginServiceBinding deregisters its callback on destruction (was a dangling-callback hazard). - PluginManager::serialize_state/deserialize_state expose the plugin's v2 state exports so an embedder can carry plugin state through its own hot reload. - ServiceRegistry::remove<I>() withdraws a provided service (child removal re-exposes a parent's entry). - EventBus::subscribe_scoped<E>() returns a move-only RAII Subscription that unsubscribes on destruction. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018yj92cCihyaYtf4gKCT3nv
29 KiB
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Build
Requires CMake 4.0+ and a C++26 compiler. GCC 16+ is the default — it ships
the experimental -freflection flag and the <meta> header that several
modules use. Clang is supported but currently lacks P2996 reflection, so
modules that use it stay reflection-free behind __has_include(<meta>).
# Configure (g++, Ninja, Debug)
cmake -B build -S . -G Ninja -DCMAKE_CXX_COMPILER=g++ -DCMAKE_BUILD_TYPE=Debug
# Build
cmake --build build
# Run all tests
ctest --test-dir build
# Or run the single test binary directly (supports --filter, --parallel, ...)
./build/tests/VoidTests --filter "Json*"
Format code with:
clang-format -i <file>
Architecture
VoidLibrary is a C++26 modular shared library organized as umbrella modules — one CMake target each, grouping related functionality. The C++ namespaces of absorbed components are unchanged (e.g. Void::Ring lives in include/Void/Containers/Ring.hpp, linked via Void::Containers).
| Module | Type | Contents |
|---|---|---|
Core |
INTERFACE | Meta (shared reflection layer), Scope, Lazy, Counted, Flags, Hash, Bits, Uuid, TypeList, TypeMap, Variant |
Functional |
INTERFACE | Pipeline (+Curry, +Memo), Either (+Opt), Result, Retry |
Containers |
INTERFACE | Ring, Pool, PriorityQueue, LRU, Trie, Graph, DisjointSet, Bitset, Interval |
Math |
INTERFACE | Vec/Mat, Matrix, Numeric, Random, Histogram |
Text |
INTERFACE | Str, Format, Tokenizer, Diff, Encoding, Semver |
Data |
INTERFACE | Json, Csv, Ini |
Async |
INTERFACE | Coro (Task, Generator), Concurrency (ThreadPool, Channel, ParallelFor), EventBus, Observable |
Time |
INTERFACE | Stopwatch, Format (durations/ISO-8601), Bench |
Log |
SHARED | Void::Log header-only facade + Void::Logging framework |
System |
SHARED | FileSystem (Path, Query, TempDir) + Process |
Configuration |
SHARED | Config, Env + Argparse |
Stacktrace |
SHARED | Boost.Stacktrace capture, color helpers (kept separate to isolate the Boost dep) |
Plugin |
SHARED | dlopen loader + manager, C ABI, hot reload (see below) |
Service |
INTERFACE | IService + type-keyed ServiceRegistry (DI); plugin-service bridge |
Fsm |
SHARED | inheritance + coroutine workflow FSM + Orchestrator (see below) |
Testing / TestingMock |
STATIC / INTERFACE | test + mock frameworks |
include/Void/Detail/ (e.g. Enum.hpp — P2996 enum reflection) is not a module; it is header-only and reachable from every module via the shared include root.
Reflection layer (Void::Meta, include/Void/Core/Meta.hpp)
The single shared C++26 P2996 layer the whole codebase reflects through. Header-only, in Core:
- Shape traits (one source):
is_optional_v,is_vector_v,is_string_map_v,is_duration_v,Leaf,Struct— the trait sets that used to be duplicated inData/Reflect.hppandConfiguration/Bind.hppnow live here. - Member walk:
members_v<T>(the onenonstatic_data_members_of+define_static_array),field_count<T>(),field_names<T>(),for_each_field(obj, fn),type_name<T>(). - Annotations:
Str(a value-based fixed-capacity string — annotation payloads can't bestd::string_view/const char*, which aren't structural),has_annotation<Tag>(member),annotation_of<Tag>(member). Member annotations work; enumerator annotations do not parse in this GCC (so enum labels stay identifier-based). - Generic algorithms:
equal/compare/hash(member-folded, recursive) andrepr(formatter →.format()→ reflectedType{a: 1, …}).Functional/Detail/Repr.hppis now a thin alias overMeta::repr. - Enum utilities (extend
Detail/Enum.hpp):enum_name/enum_parse/enum_cast(re-exported) plusenum_count<E>,enum_values<E>(),enum_entries<E>().
Annotation vocabularies (small structs over Meta::Str, used as [[= ns::Tag{…}]]):
Json::Rename{"k"}/Json::Skip/Json::Required/Json::Flatten(Data/Reflect.hpp).Configuration::Key{"k"}/Configuration::Required(Bind.hpp).Argparse::Short{'v'}/Help{"…"}/Name{"…"}/Positional(Argparse.hpp).Fsm::entry(FSM entry designation).
Other reflective consumers: Data/Csv.hpp maps a flat struct to/from a CSV Row (header_row<T>(), to_row, from_row); Logging::FieldScope::from(struct) reflects a struct's fields into structured log fields; Core/Flags.hpp renders/parses a flag set by enumerator name (Flags::to_string/parse via enum_entries); Containers/Debug.hpp debug_dump(range) renders elements via repr; Service::interface_name<I>() gives a reflected default service name; the FSM entry marker now goes through Meta::has_annotation. Non-aggregate structs (e.g. Math::Vec3) reflect for read (repr/equal/hash) via Meta even though they're excluded from the aggregate-only JSON path; aggregates like Semver::Version are JSON-reflectable directly.
Module system
cmake/Module.cmake defines void_add_module(NAME ...). The root CMakeLists.txt auto-discovers every subdirectory under src/ and calls it (or includes the dir's module.cmake if present), then calls void_finalize_modules(). A module with only headers becomes an INTERFACE library; one with .cpp sources becomes SHARED — except Testing, which is special-cased to STATIC.
Module layout:
- Headers:
include/Void/<Module>/*.hpp - Sources:
src/<Module>/*.cpp - CMake target:
Void_<Module>with aliasVoid::<Module>
Every header-only module must have at least a one-line src/<Module>/module.cmake (void_add_module(<Module>)) — git does not track empty directories, and discovery iterates src/*.
void_add_module accepts three dependency lists:
INTERNAL_DEPS— otherVoid::*modules (linked unconditionally).EXTERNAL_DEPS— third-party targets fetched viacmake/Dependencies.cmake(FetchContent); add new ones there before referencing.OPTIONAL_DEPS—Void::*modules linked only if they exist; each present dep additionally definesVOID_HAS_<UPPERCASE>for conditional code. Resolution is deferred tovoid_finalize_modules(), so it does not depend on discovery order.
Tests
All tests compile into one binary, build/tests/VoidTests (registered as the single ctest entry):
| Category | Location | Suite label |
|---|---|---|
| Standalone | tests/standalone/<Module>/<Feature>.cpp |
<Feature> (file stem) |
| Internal (cross-module) | tests/internal/*.cpp |
internal_<stem> |
The tests/standalone/<Module> directory name must exactly match a module name — the scanner iterates registered modules and silently skips unknown directories. After moving/renaming tests, compare the runner's total test count.
Writing a test
The primary model is a reflection-based suite (Void/Testing/Suite.hpp):
derive a struct from Void::Testing::Suite<YourSuite> (CRTP). Every public,
0-argument member returning Void::Testing::Test/DisabledTest (both void) —
except setup/teardown — is auto-registered by reflecting the struct. No
macros, no CMake scan, no registrar line, no instance: a [[gnu::used]] static
in the base forces registration at program start, even though the suite is never
constructed for its own sake. Metadata is annotations (reuse Meta::Str):
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
namespace {
struct MathTests : Void::Testing::Suite<MathTests> {
void setup() {} // optional, per-test
Void::Testing::Test addition() { Void::Testing::expect_eq(1 + 1, 2); }
[[= Void::Testing::tag("integration")]] Void::Testing::Test db() { /*…*/ }
[[= Void::Testing::skip("Feature #42")]] Void::Testing::Test wip() { /*…*/ }
};
}
- Suite label = the struct's name; override with
[[= Testing::name("Math")]]on the struct. [[= Testing::tag("x")]](repeatable) attaches tags;[[= Testing::skip("reason")]]disables a test (replacesDisabledTest+@skip).setup()/teardown()run around each test method (fresh instance per test) — the reflection-discovered replacement for the oldFixturebase. File/line come fromstd::meta::source_location_of.
Global-namespace reflection ICEs this GCC and an #include can't be namespace-wrapped, so tests must live in a named struct — hence the CRTP Suite wrapper rather than bare free functions.
Scanner (permanent fallback). Free-function tests
(Void::Testing::Test name() with // @tag/// @skip comments) are still
picked up by cmake/VoidTestScanner.cmake, which generates *.void_tests.cpp
shims (the original .cpp is HEADER_FILE_ONLY). This path is kept as a
fallback — both for compilers without <meta> and for tests written in the
old free-function style. The two models coexist with no migration required: a
Suite-only file produces an empty shim and self-registers via reflection (the
scanner always emits a valid #include of the source), while free-function files
register through the scanner. Use Suite for new tests; existing free-function
files keep working as-is.
Mock reflection (Void/TestingMock/Reflect.hpp): method_names<I>() lists an
interface's virtual methods; covers<Mock, I>() is a compile-time check that a
hand-written mock implements all of I. Full auto-mock (synthesizing the virtual
overrides) is not possible here — <meta> has define_aggregate (it can
generate a MockFunction<Sig> member per virtual) but no code injection for the
override bodies, so MockFunction<Sig> members are still wired up by hand.
Logging
Two layers, both in the Log module:
Void::Log facade (Log/Log.hpp, header-only — usable from any module with zero link deps). Leveled function templates Log::trace/debug/info/warn/error/fatal("Module.Feature", fmt, args...) format lazily — with no sink installed a call is one relaxed atomic load and zero allocation. set_sink(fn) routes everything to any callable (this is the hook for external logging libraries; LoggingAdapter.hpp bridges to Void::Logging). set_min_level + set_module_level filter before formatting. No macros — this codebase forbids macro APIs; behavior toggles are runtime options.
Void::Logging::Logger — abstract sink base class, async by default: entries go through a lock-free MPSC queue to a logger-owned worker thread that delivers batches via on_flush. Mode::Immediate/Buffered make the same class synchronous (constructor arg or set_mode — no separate async/sync classes). Async capacity + OverflowPolicy{Block,DropNewest,DropOldest} bound the queue. flush() blocks until everything submitted before the call is delivered; it is virtual so composite sinks propagate it.
Deriving a sink:
- Override
write(const Entry&)— called per-entry (worker thread in Async mode). - Optionally override
on_flush(std::span<const Entry>)— for batch I/O. - Call
flush()in your derived destructor — the base destructor only stops/joins the worker (calling a pure virtual from~Loggeris UB); entries left after your destructor are silently dropped.
Shipped sinks: ConsoleLogger (color via a default colored PatternFormatter; set_color_policy), FileLogger, RotatingFileLogger, SplitFileLogger (one file per level under a dir + a combined all.log), HistoryLogger (always-on, never-filtered durable JSON-lines audit trail, rolling), NullLogger, CallbackLogger, MultiLogger (tee; uses Logger::relay), SyslogLogger (POSIX). File rotation is factored into Detail::RollingFile (size + max-files), shared by the rotating/split/history sinks.
Formatters: PatternFormatter, JsonLinesFormatter, LogfmtFormatter. The pattern grammar is {token:spec} where spec = [align][width][,color] (align </>/^, width like std::format, color a name or auto=level color). Built-in tokens: time/level/thread/scopes/message/file/line/kind; unknown tokens resolve against register_token(name, fn) custom renderers, then Entry::fields by key, else stay literal. ColorPolicy{enabled, level_colors, token_colors} (ColorPolicy::defaults()) drives color; only PatternFormatter colorizes, never file/JSON/logfmt. Structured fields come from Logging::FieldScope (RAII, thread-local, snapshotted into Entry::fields like scopes). from_config sink keys: console/file/rotating/split/history/syslog plus log.color, log.split.dir, log.split.combined, log.history.path, etc.
Logging::from_config(cfg) builds the whole tree from Configuration::Config keys (log.sinks, log.level, log.format, log.async, ...); apply_facade_config sets facade levels.
Other key points:
- Virtual extension points are called outside any internal lock.
Level::Disabledsuppresses all output.Trace < Debug < ... < Fatal.push_scope(name)returns a RAIIScopedContext(breadcrumbs inEntry::scopes);scope(name)emits a boundary pair without touching the stack.make_preset(level, prefix)returns a non-owningPresetcallable.- Stop logging from other threads before destroying a logger.
Configuration module
Configuration::Config: flat string store with dotted keys. Sources (overlay-composable, last wins): from_env, from_env_prefix("APP_") (__→., lowercased), from_file (KEY=VALUE), from_ini, from_json (flattened), from_args (--key=value). Typed access get_as<T> / get_or_as<T> (numbers, bool spellings, enums by name via reflection, chrono durations like "250ms"). subtree(prefix) strips a prefix. Bind.hpp: bind<T>(cfg, prefix) fills an aggregate via Void::Meta (defaults = schema); members may carry [[= Configuration::Key{"…"}]] (key override) / [[= Configuration::Required{}]] (error if absent). Argparse.hpp also offers reflective parse<Opts>(argc, argv) — define an options struct, annotate fields (arg::Short/Help/Name/Positional), parse straight into it (bool→flag, string→option w/ default, optional→option) — alongside the fluent Parser. Watch.hpp: ConfigWatch reloads a file on change with per-key diff (debounced polling via FileSystem::FileWatcher in System).
Service module
Void::Service — dependency inversion + FSM orchestration.
IServicebase (service_name(),on_start()/on_stop()lifecycle).ServiceRegistry— type-keyed:provide<I>(impl),get<I>()(nullptr if absent),require<I>()(throws),has<I>(),remove<I>()(withdraws the local entry; holders keep the instance alive, a parent's entry is re-exposed),start_all()/stop_all(). Consumers depend only on interfaceIand resolve at runtime; a concrete derivingIServiceis recovered for lifecycle viadynamic_casteven when registered under a plain interface.shared_mutex, reads are the hot path.Fsm::Orchestrator(in the Fsm module): owns aServiceRegistry,launch<F>(args...)constructs an FSM, injects the registry (set_services), starts and supervises it via aFsmHandle(status/stop);stop_all()is balanced once againststart_services().Service/PluginService.hpp:PluginServiceBinding<I>binds a plugin-provided service into a registry and re-binds on hot reload. The interfaceImust deriveIService(single inheritance) so the host recovers it from the plugin's exportedIService*bystatic_cast— nodynamic_castacross the RTLD_LOCAL boundary. The registry entry pins the plugin instance.
Fsm module (inheritance + coroutine workflow)
Void::Fsm::Machine<Derived> (CRTP) — derive it. Declare the states as a nested struct of forward declarations, struct States { struct First; struct Second; … };, each deriving the single base State; realise them out-of-line (typically in a .cpp: struct M::States::First : M::State { Coro::Task<StateKey>> run(){…} };). The base auto-registers them by reflecting members_of(^^States) — the first declared state is the initial one unless using Initial = States::S;. There is no statechart/event-graph and no declarative transition table: states drive themselves and handle events imperatively. Define the constructor out-of-line, after the realisations, so the states are complete when the base registers them.
One State, signature-inferred roles. There is one base class; the engine infers what each state does purely from member signatures via P2996 (Detail/Roles.hpp) — no override, no framework-mandated names:
- entry — a member returning
State/Coro::Task<StateKey>>with no params (Task<State> run()); a startup-entry overload takes the launch data (Task<State> run(Cfg)), used when reached viastartMachine(data routed there, not the constructor). Events are awaited imperatively in the entry (co_await await_event<E>()). The nullaryrun()and the startup overloadrun(Cfg)coexist: the overload is chosen when the machine is launched with data (startMachine<…>(cfg)), the nullary entry otherwise. When several members match the entry signature, the one annotated[[= Void::Fsm::entry]]wins; unannotated, the first-declared match is used. - continuation handlers — two members distinguished by parameter type,
ok(ChildSuccess s)/no(ChildFailure f); the sub's typed Success/Failure rides type-erased in the result struct and is read withs.as<T>()/f.as<T>()(ChildSuccess/ChildFailureare concrete types, noauto). The engine picks by the launched sub's outcome.
Mechanics: at add<S>() a Detail::make_driver<S>() reflection thunk (runs the entry) is stored; drive() calls the thunk. State-list reflection lives in Detail/StateList.hpp (register_states_from, FirstStateOf/InitialStateOf, states_contains for the next<S>() / startMachine<,Next> compile-time target check). startMachine<Sub, Next>(data…) (knows Sub, Next, and the data types) builds a Launch step carrying a launcher (runs Sub, injecting data into its initial state's startup-entry) and a dispatcher (Detail::dispatch_result<Next, Sub>) that wraps the sub's outcome in a type-erased ChildSuccess/ChildFailure (value in a std::any, read via .as<T>()) and calls Next's matching handler. The reflection selectors must not be coroutines (template for + member splicing fails inside a coroutine body in this GCC build), so they return a Task<State> (wrapping plain State via ready_task). The discovery is invocability-based — no parameter-type reflection (P3096). Machine-level entry/exit are overridable virtuals on_machine_enter()/on_machine_exit(); per-state entry/exit are the state's own on_enter()/on_exit().
Typed results. A machine declares its result types as nested types reflected by name — struct Success {…} (or using Success = int;) and struct Failure {…}, each defaulting to void. Outcome = std::expected<Success, Failure> (a void failure becomes std::monostate); succeed(Success{…}) / fail(Failure{…}) carry them (nullary when void). Engine/system faults (no initial state, jump to an unregistered state, a state with no entry) are a separate FsmError channel — status()==Faulted, system_error() returns the FsmError, never the typed Failure. Because Derived is incomplete at CRTP base instantiation, the engine stores outcomes type-erased and rebuilds the typed Outcome in wait()/run_blocking() (function templates defaulted on Derived); Detail::SuccessOf/FailureOf<Derived> resolve the nested types by plain name lookup (Detail/Result.hpp).
Header layout (include <Void/Fsm/Fsm.hpp> — a thin umbrella): Machine.hpp (the Machine<Derived> template, the single nested State base, lifecycle, events, nesting, persistence); Detail/StateList.hpp (state-list reflection over the nested struct States: register_states_from, FirstStateOf/InitialStateOf, states_contains); Detail/Roles.hpp (the signature-inference: ChildSuccess/ChildFailure result structs, the entry annotation marker, invoke_entry/invoke_startup/invoke_handler/dispatch_result/make_driver); Detail/Result.hpp (SuccessOf/FailureOf/OutcomeOf<Derived>); Detail/Awaiter.hpp (one Detail::EventAwaiter behind make_event_awaiter, used by all await_*); Detail/Introspect.hpp (StateInfo + node-level to_mermaid); Detail/Engine.{hpp,cpp} (the non-template ExecutionContext + StateBase — only on_enter/on_exit remain virtual); Detail/TypeName.hpp (type_name<T>()).
- Async by default: a non-template
Detail::ExecutionContext(src/Fsm/Engine.cpp) owns oneAsync::ManualExecutor+ worker thread + a lock-free MPSC event queue + a typed event mailbox. A single consumer (worker, or the embedder viapump()whenMachineOptions{.own_worker=false}) touches all mutable state, so state code is lock-free/single-threaded.start()/run_blocking()/wait()for worker mode;pump()for embedder mode (deterministic tests). - Events:
co_await await_event<E>()consumes the oldest queuedE(typed mailbox), suspending until one arrives;post<E>(e)is lock-free from any thread. - Nesting:
co_await run_child<Sub>(args...)runs a child on the same executor (shared events + services) and yields itsOutcome(std::expected<R, FsmError>) — the imperative form, branch on it yourself. - Sub-machine continuations (declarative):
co_return startMachine<Sub, Next>(args...)launchesSub(constructed fromargs, on the shared executor/events/services), then entersNextand the engine finds on its own which method to call —NextderivesContinue<Sub::result_type>and the engine dispatches toon_success(R)oron_failure(FsmError)by the outcome (aContinue<void>takes a nullaryon_success()).Nextmust deriveContinue<R>(astatic_assertenforces it) and be inStates<>. A continuation handler may itself return anotherstartMachine(chaining) or any normalState.Nextmust be inStates{…}(compile-time checked). Mechanics: aState::Kind::Launchcarries the target + a type-erased launcher;drive()runs it, stashes theLaunchResult, and the entered state's bound dispatcher routes it to the matchingok/nohandler — a plain state entered with no pending result just runs its entry. - Parallel / orthogonal regions:
co_await run_parallel<A, B, …>()runs several sub-machines concurrently on the shared executor (interleaved — when one parks on an event, another runs; multi-waiter mailbox) and joins all, yieldingstd::tuple<A::Outcome, …>.run_parallel_any<…>()resolves on the first to finish →std::variant<…::Outcome…>; losers keep running cooperatively (not preemptible), so they're kept alive by the spawned tasks until they finish — a loser parked forever leaks its frame until the machine stops. Children are default-constructed and share events/services. Join uses a small latch coroutine (Async::spawn+ a completion counter); single-consumer ⇒ no lock. - Composite sub-states (hierarchy):
co_await run_region<Sub>()isrun_childwith introspection — the calling state'son_enter/on_exitwrap the child region, and the parent'sstate_path()reports the parent→child chain ({Composite, …child leaf}) while it runs. Map the child'sOutcometo a sibling transition (r ? next<Done>() : next<Recover>()). Parent-level multi-event handling viaco_await await_any<E1, E2, …>()→std::variant<Es...>(e.g. a region waits forTickorCancelat one level). Coroutines aren't preemptible mid-flight, so child cancellation is cooperative: the region awaits a sharedCancelevent (events route to the deepest awaiter) and returns a failingOutcomethe parent maps — no frame is abandoned. - Dynamic:
add<S>()/add_if<S>(cond);next<unregistered>fails;has_state<S>()lets a state branch. - Direct control: fluent
send(e1, e2, …)(variadicpost); free in-state jumps viagoto_state<S>()(any registered state, no declared transition); externaljump<S>()applied at the next transition boundary (race-safe, non-preemptive — a running state isn't interrupted); lifecyclereset()/restart()/restart_at<S>()andpause()/resume()(paused = worker stops draining, posted events buffer); Idle-only mutationremove<S>()/set_initial<S>()/replace<S, T>(). - Services:
set_services(registry);state.service<I>()resolves through the injected context. - Observation:
current_state()is a lock-free atomic-index read of an immutable name table (P2996identifier_of, fallback to indexed names).state_path()is the same but appends an activerun_regionchild's path — consumer-consistent (read it from within the machine or once settled; deterministic inpump()mode). - Event idioms (all imperative): timeout —
co_await await_event_for<E>(d)(→optional,nullopton timeout) ordelay(d); multi-event —co_await await_any<A, B>()→std::variant<A,B>; guard — a plainifafter the await; internal/self transition — afor(;;)loop in the entry that handles events without returning (ornext<Self>()); deferred events are automatic — the typed mailbox buffers any event a state doesn't await, so a later state consumes it (nothing is dropped, nodeferdeclaration needed). - Introspection:
describe()lists registered states (name, initial?). Transitions are chosen imperatively inside each entry and aren't statically knowable, so the description is node-level —to_mermaid()renders astateDiagram-v2string with the initial marker plus one node per state (no edges). - Error policies / middleware: state helpers
delay(d),with_retry(times, backoff, attempt)(retries aCoro::Task<bool>sub-step),next_or<Fallback>(step)(route a failingStateto a fallback state).add_interceptor({before(Transition), after(state_name)})runs ordered hooks around each transition;observe(fn)is the single read-only observer. - Persistence:
serialize()→{state name, on_serialize data};restore()on an un-started machine resumes at the named state (overrideon_serialize/on_restorefor derived data, reflection-JSON friendly). - Hot-plug + state-saving are re-expressed via services: plugins provide
IServiceimpls;PluginServiceBindingswaps the registry entry on reload (state migrated by the plugin's v2 ABI), so running FSMs pick up the new impl on the nextservice<I>()call without being patched.
Plugin module (hot reload)
Void::Plugin loads C-ABI plugins (.so) and hot-reloads them with state transfer:
- C ABI (
Plugin.hpp): requiredvoid_plugin_create/destroy/info; optionalvoid_plugin_transfer_state(old,new)(raw),void_plugin_configure(inst, config)(host-supplied config string, called after create and after each reload swap, beforeon_load()), and the v2 state protocolvoid_plugin_state_version+void_plugin_serialize_state/void_plugin_free_string+void_plugin_deserialize_state(inst, json, from_version).ABI_VERSIONis checked;IPlugin's vtable is frozen (append-only). State transfer prefers v2 serialize→deserialize (survives layout changes; migrations live in the new .so viaJson::MigrationChain), falling back totransfer_state. PluginLoader— owns one instance;reload()copies the.soto a fresh-inode temp (sodlopenloads new bytes), creates the new instance, transfers state, swaps, destroys the old. Move-only.PluginManager— multi-plugin registry with RCU-style pinned handles:acquire(name)returns aPluginHandle(oneatomic<shared_ptr>load) that keeps its instance alive for the whole call;reload(name)builds the new instance, transfers state, thenatomic_exchanges it in — in-flight handles keep the old instance (and its mapped.so, sincedlclose_on_swap=false) alive until they drop. Work never stops.watch(name)auto-reloads viaFileSystem::FileWatcher. Discovery:load_directory(dir)loads every shared-library file in a directory (filename order, per-fileexpectedresults).unload(name)drops the registry entry (instance dies with its last handle).on_reloaded(cb)is multi-observer — it returns aReloadCallbackIdforremove_on_reloadedand fires after every successful reload, manual or watched.PluginManagerOptions::config_providerfeedsvoid_plugin_configure. Host-side state carry:serialize_state(name)→StateSnapshot{json, version}anddeserialize_state(name, json, from_version)wrap the plugin's v2 exports so an embedder can persist plugin state across its own hot reload.- Reload safety rule: deployments must install the new
.soby atomic rename (fresh inode), never by overwriting the mapped file in place — in-place overwrite corrupts the running instance's mmap (SIGBUS). The tests'install()helper shows the pattern (copy to.incoming, then rename).
Code style
Enforced by .clang-format (LLVM-based): 4-space indent (tabs), 80-column limit, Linux brace wrapping style, pointer alignment right.