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>
161 lines
13 KiB
Markdown
161 lines
13 KiB
Markdown
# 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>)`.
|
|
|
|
```bash
|
|
# 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:
|
|
```bash
|
|
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 | 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) |
|
|
| `StateMachine` | INTERFACE | compile-time variant-based FSM |
|
|
| `Fsm` | SHARED | runtime hierarchical FSM (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.
|
|
|
|
### 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 alias `Void::<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` — other `Void::*` modules (linked unconditionally).
|
|
- `EXTERNAL_DEPS` — third-party targets fetched via `cmake/Dependencies.cmake` (`FetchContent`); add new ones there before referencing.
|
|
- `OPTIONAL_DEPS` — `Void::*` modules linked only if they exist; each present dep additionally defines `VOID_HAS_<UPPERCASE>` for conditional code. Resolution is deferred to `void_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
|
|
|
|
Tests are free functions (or methods on a `Void::Testing::Fixture` subclass) returning `Void::Testing::Test` or `Void::Testing::DisabledTest` (both aliases for `void`). **Never write the registration code yourself** — `cmake/VoidTestScanner.cmake` parses each `.cpp` at configure time, generates `*.void_tests.cpp` shims with `Void::Testing::Detail::test_registrar` calls, and rewrites the original source to `HEADER_FILE_ONLY`.
|
|
|
|
```cpp
|
|
#include <Void/Testing/Assert.hpp>
|
|
#include <Void/Testing/Test.hpp>
|
|
|
|
Void::Testing::Test addition() { Void::Testing::expect_eq(1 + 1, 2); }
|
|
|
|
// @tag integration, database
|
|
Void::Testing::Test db_query() { Void::Testing::expect(true); }
|
|
|
|
// @skip "Feature #42 not implemented"
|
|
Void::Testing::DisabledTest broken() { Void::Testing::fail("not ready"); }
|
|
```
|
|
|
|
Fixture-based tests work the same way — declare a class derived from `Void::Testing::Fixture`, override `setup()`/`teardown()`, and write methods returning `Test`/`DisabledTest`.
|
|
|
|
Comment metadata (immediately preceding the function):
|
|
- `// @tag a, b, c` — attaches tags.
|
|
- `// @skip <reason>` — marks the test skipped with a reason; quoted or unquoted strings both work. `DisabledTest` implies `@skip "disabled"` if no explicit reason is given.
|
|
- Any non-comment, non-empty line resets the accumulated tags/skip — keep the comment block adjacent to the function.
|
|
|
|
The sweep in `cmake/VoidTesting.cmake` auto-applies the scan to every executable that transitively links `Void::Testing`. To opt a target out, set the `VOID_TESTING_NO_AUTO_SCAN` property; to opt in explicitly (e.g. for a target that doesn't link `Void::Testing` directly), call `void_add_tests(<target>)`.
|
|
|
|
### 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:
|
|
1. **Override `write(const Entry&)`** — called per-entry (worker thread in Async mode).
|
|
2. **Optionally override `on_flush(std::span<const Entry>)`** — for batch I/O.
|
|
3. **Call `flush()` in your derived destructor** — the base destructor only stops/joins the worker (calling a pure virtual from `~Logger` is UB); entries left after your destructor are silently dropped.
|
|
|
|
Shipped sinks: `ConsoleLogger` (colors via Stacktrace), `FileLogger`, `RotatingFileLogger` (size rotation, max files), `NullLogger`, `CallbackLogger`, `MultiLogger` (tee; uses `Logger::relay`), `SyslogLogger` (POSIX). Sinks accept a `Formatter` (`PatternFormatter` with `{time}/{level}/{scopes}/{message}/...` placeholders, `JsonLinesFormatter`, `LogfmtFormatter`).
|
|
|
|
`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::Disabled` suppresses all output. `Trace < Debug < ... < Fatal`.
|
|
- `push_scope(name)` returns a RAII `ScopedContext` (breadcrumbs in `Entry::scopes`); `scope(name)` emits a boundary pair without touching the stack.
|
|
- `make_preset(level, prefix)` returns a non-owning `Preset` callable.
|
|
- 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 P2996 (defaults = schema). `Watch.hpp`: `ConfigWatch` reloads a file on change with per-key diff (debounced polling via `FileSystem::FileWatcher` in `System`).
|
|
|
|
### Fsm module (runtime FSM)
|
|
|
|
`Void::Fsm` — full-featured runtime state machine, distinct from the compile-time `StateMachine`:
|
|
|
|
- **Definition**: `Builder` declares states by name (`state("a", parent)` — hierarchical), events (`event("go")` or from enums via reflection), `initial`, `parallel` (orthogonal regions), `history(Shallow|Deep)`, `defer`, `timeout(state, ms, event)`, `transition(from, on, to).guard(...).action(...)`, `internal(in, on)`. `build()` validates into an immutable `shared_ptr<const MachineDef>`. Names are the stable identity; ids are per-definition.
|
|
- **Actions** are `std::function<Coro::Task<void>(Machine&, const Event&)>` (sync lambdas via `SyncAction` overloads). The run-to-completion step finishes only when the action's coroutine completes; the worker drives it on its own `ManualExecutor`.
|
|
- **Concurrency (MPSC)**: `post()` is lock-free from any thread (Vyukov queue + park semaphore); exactly one consumer — the owned worker (`start()` returns once the initial configuration is entered) or the embedder via `run_pending()` when constructed with `MachineOptions{.own_worker = false}` (the deterministic mode used by most tests; note `send_wait`/queued `serialize_state` would self-deadlock there — they're for the worker mode). Observation (`current()`, `is_in`) is a seqlock read of a trivially-copyable `StateSnapshot` (≤16 active leaves).
|
|
- **send paths**: `co_await machine.send(ev[, &executor])` resolves with `SendResult{Handled,Deferred,Unhandled,Dropped}` after the step; `send_wait` blocks; resumption defaults to the machine worker.
|
|
- **Hot swap**: `swap_definition(def)` applies between steps. If every active leaf name exists in the new def, the configuration is adopted without re-running entry actions (seamless); otherwise the machine re-enters the initial configuration. History is remapped by name.
|
|
- **Persistence**: `serialize_state()` → JSON with leaf/history *names*; `restore_state(json)` on a stopped machine re-activates silently (no entry actions).
|
|
- History records are snapshotted at exit time in `perform_transition` (not incrementally) — keep it that way; incremental recording accumulates stale leaves.
|
|
|
|
### Plugin module (hot reload)
|
|
|
|
`Void::Plugin` loads C-ABI plugins (`.so`) and hot-reloads them with state transfer:
|
|
|
|
- **C ABI** (`Plugin.hpp`): required `void_plugin_create/destroy/info`; optional `void_plugin_transfer_state(old,new)` (raw) and the v2 state protocol `void_plugin_state_version` + `void_plugin_serialize_state`/`void_plugin_free_string` + `void_plugin_deserialize_state(inst, json, from_version)`. `ABI_VERSION` is checked; `IPlugin`'s vtable is frozen (append-only). State transfer prefers v2 serialize→deserialize (survives layout changes; migrations live in the *new* .so via `Json::MigrationChain`), falling back to `transfer_state`.
|
|
- **`PluginLoader`** — owns one instance; `reload()` copies the `.so` to a fresh-inode temp (so `dlopen` loads 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 a `PluginHandle` (one `atomic<shared_ptr>` load) that keeps its instance alive for the whole call; `reload(name)` builds the new instance, transfers state, then `atomic_exchange`s it in — in-flight handles keep the old instance (and its mapped `.so`, since `dlclose_on_swap=false`) alive until they drop. Work never stops. `watch(name)` auto-reloads via `FileSystem::FileWatcher`; `on_reloaded` fires after each swap.
|
|
- **Reload safety rule**: deployments must install the new `.so` by **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.
|