Add Plugin hot-plug: PluginManager, versioned state ABI, file watching

Backward-compatible C ABI v2 (Plugin.hpp; ABI_VERSION unchanged, IPlugin
vtable frozen): optional void_plugin_state_version / serialize_state /
free_string / deserialize_state(inst, json, from_version). State transfer
prefers serialize->deserialize (survives layout changes; migrations live
in the new .so via Json::MigrationChain), falling back to the existing
transfer_state, then no-op. PluginLoader::reload gains this chain; the
shared transfer_plugin_state helper drives it. Existing ABI-v1 plugins
(TestPlugin) load and reload unchanged.

PluginManager (Manager.hpp/.cpp): multi-plugin registry with RCU-style
pinned handles. acquire(name) is one atomic<shared_ptr> load returning a
PluginHandle that keeps its instance alive for the whole call. reload()
is transactional: build new instance, transfer state from old, then
atomic-exchange it in; on any failure the old instance stays. In-flight
handles keep the old instance and its mapped .so alive (dlclose_on_swap=
false) until they drop, so work never stops and callers never see a torn
or freed object. watch(name) auto-reloads via FileSystem::FileWatcher
(debounced); on_reloaded fires after each swap.

Reload-safety: dlopen of a fresh-inode hotswap copy is required to load
new bytes; deployments must install the new .so by atomic rename, never
in-place overwrite of the mapped file (corrupts the running mapping ->
SIGBUS). Documented; tests install via copy-to-.incoming + rename.

Tests: StatefulPluginV1/V2 (shared IStateful interface, atomic counter;
v2 adds a field and migrates v1 JSON). Manager.cpp covers load/acquire,
v1->v2 migration, pinned-handle-survives-reload, legacy transfer_state
fallback, and watch auto-reload. HotReloadUnderLoad.cpp: 6 reader threads
calling through acquire() while 24 v1<->v2 reloads run concurrently --
zero crashes, state survives every migration, ASan+UBSan clean, stable
across 10+ runs.

965 tests green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Fable 5 committed 2026-06-13 18:08:06 +03:00
1 parent 697e07843c
commit b343bce396
13 files changed
+1179 -38

No files matched your search

+19
View File
@@ -97,4 +97,23 @@ if(TARGET Void::Plugin)
)
add_dependencies(VoidTests VoidTestPlugin)
endif()
# Stateful plugins (schema v1 + v2) for hot-reload/state-migration
# tests. Same plugin name; v2 adds a field and migrates v1 JSON.
add_library(VoidStatefulPluginV1 SHARED
"${CMAKE_CURRENT_SOURCE_DIR}/plugins/StatefulPluginV1.cpp")
add_library(VoidStatefulPluginV2 SHARED
"${CMAKE_CURRENT_SOURCE_DIR}/plugins/StatefulPluginV2.cpp")
foreach(_sp VoidStatefulPluginV1 VoidStatefulPluginV2)
target_link_libraries(${_sp} PRIVATE Void::Plugin Void::Data)
target_include_directories(${_sp} PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/plugins")
endforeach()
target_compile_definitions(VoidTests PRIVATE
"VOID_STATEFUL_V1_PATH=\"$<TARGET_FILE:VoidStatefulPluginV1>\""
"VOID_STATEFUL_V2_PATH=\"$<TARGET_FILE:VoidStatefulPluginV2>\""
)
target_include_directories(VoidTests PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/plugins")
add_dependencies(VoidTests VoidStatefulPluginV1 VoidStatefulPluginV2)
endif()
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include <Void/Plugin/Plugin.hpp>
#include <string_view>
// Shared interface for the stateful hot-reload test plugins. The host
// holds an IPlugin*; because every stateful plugin's concrete type derives
// from IStateful through a single-inheritance chain, the host recovers the
// richer interface with static_cast (dynamic_cast is unreliable across
// RTLD_LOCAL boundaries). The vtable layout is identical on both sides as
// long as this header is shared — which it is.
namespace VoidTest
{
class IStateful : public Void::Plugin::IPlugin
{
public:
[[nodiscard]] virtual int counter() const = 0;
virtual void bump() = 0;
[[nodiscard]] virtual int schema_version() const = 0;
};
[[nodiscard]] inline IStateful* as_stateful(Void::Plugin::IPlugin* p)
{
return static_cast<IStateful*>(p);
}
} // namespace VoidTest
+98
View File
@@ -0,0 +1,98 @@
#include "Stateful.hpp"
#include <Void/Data/Reflect.hpp>
#include <atomic>
#include <cstdlib>
#include <cstring>
#include <string>
// Stateful plugin, schema v1. State is a single counter, serialized as
// {"__version":1,"data":{"count":N}} via the reflection JSON serializer.
namespace
{
struct StateV1 {
int count = 0;
};
class PluginV1 final : public VoidTest::IStateful
{
public:
[[nodiscard]] std::string_view name() const noexcept override
{
return "StatefulPlugin";
}
[[nodiscard]] int counter() const override
{
return m_count.load(std::memory_order_relaxed);
}
void bump() override
{
m_count.fetch_add(1, std::memory_order_relaxed);
}
[[nodiscard]] int schema_version() const override { return 1; }
std::atomic<int> m_count{0};
};
} // namespace
template <> struct Void::Json::StateTraits<StateV1> {
static constexpr std::uint32_t version = 1;
};
extern "C" {
void* void_plugin_create() { return new PluginV1; }
void void_plugin_destroy(void* p) { delete static_cast<PluginV1*>(p); }
Void::Plugin::PluginInfo void_plugin_info()
{
return {
.abi_version = Void::Plugin::ABI_VERSION,
.name = "StatefulPlugin",
.plugin_version = "1.0.0",
.description = "Stateful test plugin (schema v1)",
};
}
std::uint32_t void_plugin_state_version() { return 1; }
const char* void_plugin_serialize_state(void* instance)
{
const auto* self = static_cast<PluginV1*>(instance);
const StateV1 state{.count = self->counter()};
const auto json =
Void::Json::serialize(Void::Json::to_versioned_json(state));
char* out = static_cast<char*>(std::malloc(json.size() + 1));
if (out != nullptr) {
std::memcpy(out, json.c_str(), json.size() + 1);
}
return out;
}
void void_plugin_free_string(const char* s)
{
std::free(const_cast<char*>(s)); // NOLINT
}
int void_plugin_deserialize_state(void* instance, const char* json,
std::uint32_t /*from_version*/)
{
auto* self = static_cast<PluginV1*>(instance);
const auto parsed = Void::Json::parse(json);
if (!parsed.has_value()) {
return 1;
}
const auto state = Void::Json::from_versioned_json<StateV1>(*parsed);
if (!state.has_value()) {
return 2;
}
self->m_count.store(state->count, std::memory_order_relaxed);
return 0;
}
} // extern "C"
+116
View File
@@ -0,0 +1,116 @@
#include "Stateful.hpp"
#include <Void/Data/Reflect.hpp>
#include <atomic>
#include <cstdlib>
#include <cstring>
#include <string>
// Stateful plugin, schema v2 — same plugin name as v1, so a PluginManager
// reload swaps v1 -> v2 in place. State gains a `tag` field; v1 JSON is
// migrated by the chain living here (the new build knows the old format).
namespace
{
struct StateV2 {
int count = 0;
std::string tag = "v2"; // added in v2
};
class PluginV2 final : public VoidTest::IStateful
{
public:
[[nodiscard]] std::string_view name() const noexcept override
{
return "StatefulPlugin";
}
[[nodiscard]] int counter() const override
{
return m_count.load(std::memory_order_relaxed);
}
void bump() override
{
m_count.fetch_add(1, std::memory_order_relaxed);
}
[[nodiscard]] int schema_version() const override { return 2; }
std::atomic<int> m_count{0};
std::string m_tag{"v2"};
};
Void::Json::MigrationChain migrations()
{
Void::Json::MigrationChain chain;
// v1 -> v2: keep count, introduce tag marking the upgrade.
chain.add(1, [](Void::Json::Value data) {
data.as_object().emplace_back("tag", Void::Json::Value{"migrated"});
return data;
});
return chain;
}
} // namespace
template <> struct Void::Json::StateTraits<StateV2> {
static constexpr std::uint32_t version = 2;
};
extern "C" {
void* void_plugin_create() { return new PluginV2; }
void void_plugin_destroy(void* p) { delete static_cast<PluginV2*>(p); }
Void::Plugin::PluginInfo void_plugin_info()
{
return {
.abi_version = Void::Plugin::ABI_VERSION,
.name = "StatefulPlugin",
.plugin_version = "2.0.0",
.description = "Stateful test plugin (schema v2)",
};
}
std::uint32_t void_plugin_state_version() { return 2; }
const char* void_plugin_serialize_state(void* instance)
{
const auto* self = static_cast<PluginV2*>(instance);
const StateV2 state{.count = self->counter(), .tag = self->m_tag};
const auto json =
Void::Json::serialize(Void::Json::to_versioned_json(state));
char* out = static_cast<char*>(std::malloc(json.size() + 1));
if (out != nullptr) {
std::memcpy(out, json.c_str(), json.size() + 1);
}
return out;
}
void void_plugin_free_string(const char* s)
{
std::free(const_cast<char*>(s)); // NOLINT
}
int void_plugin_deserialize_state(void* instance, const char* json,
std::uint32_t /*from_version*/)
{
auto* self = static_cast<PluginV2*>(instance);
const auto parsed = Void::Json::parse(json);
if (!parsed.has_value()) {
return 1;
}
// from_versioned_json reads the envelope's own __version and migrates
// up to StateV2's version (2) using the chain.
const auto state =
Void::Json::from_versioned_json<StateV2>(*parsed, migrations());
if (!state.has_value()) {
return 2;
}
self->m_count.store(state->count, std::memory_order_relaxed);
self->m_tag = state->tag;
return 0;
}
} // extern "C"
@@ -0,0 +1,108 @@
#include <Void/Plugin/Manager.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include "Stateful.hpp"
#include <atomic>
#include <chrono>
#include <filesystem>
#include <thread>
#include <vector>
using namespace Void::Plugin;
#if defined(VOID_STATEFUL_V1_PATH) && defined(VOID_STATEFUL_V2_PATH) && \
__has_include(<dlfcn.h>)
namespace
{
// Atomic-rename install (fresh inode) — overwriting a mapped .so in
// place corrupts the running mapping (SIGBUS).
void install(const std::filesystem::path& src,
const std::filesystem::path& dst)
{
auto staging = dst;
staging += ".incoming";
std::filesystem::copy_file(
src, staging, std::filesystem::copy_options::overwrite_existing);
std::filesystem::rename(staging, dst);
}
} // namespace
// @tag stress, concurrency
Void::Testing::Test hot_reload_under_concurrent_load()
{
Void::FileSystem::TempDir tmp{"void_hotload"};
const auto so = tmp.path() / "plugin.so";
std::filesystem::copy_file(VOID_STATEFUL_V1_PATH, so);
PluginManager mgr;
Void::Testing::expect(mgr.load(so).has_value());
std::atomic<bool> stop{false};
std::atomic<long long> ops{0};
std::atomic<bool> sane{true};
std::atomic<int> crashes{0};
// Reader threads continuously acquire a pinned handle and use the
// plugin through it. acquire() returns a handle that keeps whichever
// instance was current alive for the whole call — so even as the main
// thread swaps instances underneath, no reader ever touches a freed
// object (ASan would catch it otherwise).
std::vector<std::thread> readers;
readers.reserve(6);
for (int r = 0; r < 6; ++r) {
readers.emplace_back([&] {
while (!stop.load(std::memory_order_relaxed)) {
auto h = mgr.acquire("StatefulPlugin");
if (!h) {
crashes.fetch_add(1);
continue;
}
auto* s = VoidTest::as_stateful(h.get());
const int before = s->counter();
s->bump();
const int after = s->counter();
// The pinned instance is consistent within the call.
if (after < before + 1) {
sane.store(false);
}
const int v = s->schema_version();
if (v != 1 && v != 2) {
sane.store(false);
}
ops.fetch_add(1, std::memory_order_relaxed);
}
});
}
// Main thread flips the file v1<->v2 and reloads repeatedly.
for (int i = 0; i < 24; ++i) {
const char* src =
(i % 2 == 0) ? VOID_STATEFUL_V2_PATH : VOID_STATEFUL_V1_PATH;
install(src, so);
const auto r = mgr.reload("StatefulPlugin");
Void::Testing::expect(r.has_value());
std::this_thread::sleep_for(std::chrono::milliseconds{2});
}
stop.store(true);
for (auto& t : readers) {
t.join();
}
Void::Testing::expect(sane.load());
Void::Testing::expect_eq(crashes.load(), 0);
Void::Testing::expect(ops.load() > 0);
// State survived every migration: the final instance's counter is at
// least the number of reloads' worth of preserved bumps (monotonic,
// never reset to zero by a swap).
auto final = mgr.acquire("StatefulPlugin");
Void::Testing::expect(static_cast<bool>(final));
Void::Testing::expect(VoidTest::as_stateful(final.get())->counter() > 0);
}
#endif // stateful plugins available
+169
View File
@@ -0,0 +1,169 @@
#include <Void/Plugin/Manager.hpp>
#include <Void/Plugin/Loader.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include "Stateful.hpp"
#include <atomic>
#include <chrono>
#include <filesystem>
#include <string>
#include <thread>
using namespace Void::Plugin;
#if defined(VOID_STATEFUL_V1_PATH) && defined(VOID_STATEFUL_V2_PATH) && \
__has_include(<dlfcn.h>)
namespace
{
VoidTest::IStateful* stateful(const PluginHandle& h)
{
return VoidTest::as_stateful(h.get());
}
// Install a plugin version by atomic rename (fresh inode). Overwriting
// a mapped .so in place would corrupt the running instance's mapping
// (SIGBUS) — deployments must swap the file, not rewrite it.
void install(const std::filesystem::path& src,
const std::filesystem::path& dst)
{
auto staging = dst;
staging += ".incoming";
std::filesystem::copy_file(
src, staging, std::filesystem::copy_options::overwrite_existing);
std::filesystem::rename(staging, dst);
}
} // namespace
Void::Testing::Test manager_loads_and_acquires()
{
PluginManager mgr;
const auto name = mgr.load(VOID_STATEFUL_V1_PATH);
Void::Testing::expect(name.has_value());
Void::Testing::expect_eq(*name, std::string{"StatefulPlugin"});
auto h = mgr.acquire("StatefulPlugin");
Void::Testing::expect(static_cast<bool>(h));
Void::Testing::expect_eq(stateful(h)->schema_version(), 1);
stateful(h)->bump();
stateful(h)->bump();
Void::Testing::expect_eq(stateful(h)->counter(), 2);
}
Void::Testing::Test manager_unknown_plugin_yields_empty_handle()
{
PluginManager mgr;
Void::Testing::expect(!static_cast<bool>(mgr.acquire("nope")));
Void::Testing::expect(mgr.reload("nope").error() ==
LoadError::UnknownPlugin);
}
Void::Testing::Test manager_reload_migrates_v1_state_to_v2()
{
// Copy v1 into a temp path we control, then overwrite with v2 and
// reload — exactly the in-place upgrade a deployment performs.
Void::FileSystem::TempDir tmp{"void_mgr"};
const auto so = tmp.path() / "plugin.so";
std::filesystem::copy_file(VOID_STATEFUL_V1_PATH, so);
PluginManager mgr;
const auto name = mgr.load(so);
Void::Testing::expect(name.has_value());
{
auto h = mgr.acquire("StatefulPlugin");
Void::Testing::expect_eq(stateful(h)->schema_version(), 1);
stateful(h)->bump();
stateful(h)->bump();
stateful(h)->bump(); // count = 3
}
install(VOID_STATEFUL_V2_PATH, so);
const auto reloaded = mgr.reload("StatefulPlugin");
Void::Testing::expect(reloaded.has_value());
auto h = mgr.acquire("StatefulPlugin");
Void::Testing::expect_eq(stateful(h)->schema_version(), 2);
Void::Testing::expect_eq(stateful(h)->counter(), 3); // migrated
}
Void::Testing::Test manager_pinned_handle_survives_reload()
{
Void::FileSystem::TempDir tmp{"void_mgr"};
const auto so = tmp.path() / "plugin.so";
std::filesystem::copy_file(VOID_STATEFUL_V1_PATH, so);
PluginManager mgr;
Void::Testing::expect(mgr.load(so).has_value());
// Pin the v1 instance, then reload to v2 while still holding it.
auto old = mgr.acquire("StatefulPlugin");
stateful(old)->bump();
stateful(old)->bump(); // old count = 2
install(VOID_STATEFUL_V2_PATH, so);
Void::Testing::expect(mgr.reload("StatefulPlugin").has_value());
// The pinned handle still addresses the live v1 instance (no torn
// state, no use-after-free — the old .so stays mapped while pinned).
Void::Testing::expect_eq(stateful(old)->schema_version(), 1);
Void::Testing::expect_eq(stateful(old)->counter(), 2);
// A fresh acquire gets the migrated v2 instance.
auto fresh = mgr.acquire("StatefulPlugin");
Void::Testing::expect_eq(stateful(fresh)->schema_version(), 2);
Void::Testing::expect_eq(stateful(fresh)->counter(), 2);
}
Void::Testing::Test manager_legacy_transfer_state_plugin_still_reloads()
{
// The original TestPlugin uses only transfer_state (no v2 protocol);
// the manager must still reload it via the fallback path.
#ifdef VOID_TEST_PLUGIN_PATH
Void::FileSystem::TempDir tmp{"void_mgr"};
const auto so = tmp.path() / "legacy.so";
std::filesystem::copy_file(VOID_TEST_PLUGIN_PATH, so);
PluginManager mgr;
const auto name = mgr.load(so);
Void::Testing::expect(name.has_value());
Void::Testing::expect(mgr.reload(*name).has_value());
Void::Testing::expect(static_cast<bool>(mgr.acquire("TestPlugin")));
#endif
}
// @tag integration
Void::Testing::Test manager_watch_auto_reloads_on_file_change()
{
Void::FileSystem::TempDir tmp{"void_mgr"};
const auto so = tmp.path() / "plugin.so";
std::filesystem::copy_file(VOID_STATEFUL_V1_PATH, so);
PluginManager mgr{
{.poll_interval = std::chrono::milliseconds{10}, .debounce_polls = 2}};
Void::Testing::expect(mgr.load(so).has_value());
std::atomic<int> reloads{0};
mgr.on_reloaded([&](std::string_view) { ++reloads; });
mgr.watch("StatefulPlugin");
Void::Testing::expect_eq(
mgr.acquire("StatefulPlugin").info().plugin_version,
std::string_view{"1.0.0"});
// Replace the file with v2 (atomic rename); the watcher reloads it.
install(VOID_STATEFUL_V2_PATH, so);
for (int i = 0; i < 300 && reloads.load() == 0; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds{5});
}
Void::Testing::expect(reloads.load() >= 1);
Void::Testing::expect_eq(mgr.acquire("StatefulPlugin")->name(),
std::string_view{"StatefulPlugin"});
mgr.unwatch("StatefulPlugin");
}
#endif // stateful plugins available