Builds on the multi-waiter mailbox: a state can run several sub-machines concurrently on the shared executor. - co_await run_parallel<A, B, ...>() spawns each child (Async::spawn) and joins ALL, yielding std::tuple<A::Outcome, ...>. Children run interleaved on the single executor — when one parks on an event, another runs (only possible now that the mailbox holds multiple waiters). - co_await run_parallel_any<A, B, ...>() resolves on the FIRST to finish, yielding std::variant<A::Outcome, ...> of the winner. Losers keep running cooperatively (coroutines aren't preemptible), so the children are kept alive by the spawned tasks (shared_ptr keepalive) until they finish — a loser parked forever leaks its frame until the machine stops (documented). - Join is a small latch coroutine (completion counter + a parked parent handle posted when it reaches zero / on first arrival); single-consumer, no lock. Children default-constructed, share events/services. 3 new tests (Parallel): join-all (worker + deterministic embedder, both children park concurrently), first-finisher race. 998 tests (995 green, 3 skipped), ASan/UBSan clean (validates the spawned-task lifetimes — no UAF/ leak), -Werror clean. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
190 lines
22 KiB
Markdown
190 lines
22 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) |
|
|
| `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.
|
|
|
|
### 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` (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.
|
|
|
|
`Formatter`s: `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::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`).
|
|
|
|
### Service module
|
|
|
|
`Void::Service` — dependency inversion + FSM orchestration.
|
|
|
|
- `IService` base (`service_name()`, `on_start()`/`on_stop()` lifecycle).
|
|
- `ServiceRegistry` — type-keyed: `provide<I>(impl)`, `get<I>()` (nullptr if absent), `require<I>()` (throws), `has<I>()`, `start_all()`/`stop_all()`. Consumers depend only on interface `I` and resolve at runtime; a concrete deriving `IService` is recovered for lifecycle via `dynamic_cast` even when registered under a plain interface. `shared_mutex`, reads are the hot path.
|
|
- `Fsm::Orchestrator` (in the Fsm module): owns a `ServiceRegistry`, `launch<F>(args...)` constructs an FSM, injects the registry (`set_services`), starts and supervises it via a `FsmHandle` (status/stop); `stop_all()` is balanced once against `start_services()`.
|
|
- `Service/PluginService.hpp`: `PluginServiceBinding<I>` binds a plugin-provided service into a registry and re-binds on hot reload. The interface `I` must derive `IService` (single inheritance) so the host recovers it from the plugin's exported `IService*` by `static_cast` — no `dynamic_cast` across the RTLD_LOCAL boundary. The registry entry pins the plugin instance.
|
|
|
|
### Fsm module (inheritance + coroutine workflow)
|
|
|
|
`Void::Fsm::Machine<Derived>` (CRTP) — derive it; declare states as nested structs deriving the **single** base `State`. There is no statechart/event-graph; states drive themselves.
|
|
|
|
**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 `Step`/`Coro::Task<Step>` with no params (`Task<Step> run()`); a **startup-entry** overload takes the launch data (`Task<Step> run(Cfg)`), used when reached via `startMachine` (data routed there, not the constructor).
|
|
- **reactive** — a member taking `TransitionBuilder&` (`void transitions(TransitionBuilder& on)`); the engine runs its declared table.
|
|
- **continuation handlers** — two members distinguished by parameter type, `ok(ChildSuccess auto s)` / `no(ChildFailure auto f)` (`s.value`/`f.value` are the sub's typed Success/Failure); the engine picks by the launched sub's outcome.
|
|
|
|
Mechanics: at `add<S>()` a `Detail::make_driver<S>()` reflection thunk is stored (reactive table vs entry, chosen by whether `S` has a `TransitionBuilder&` member); `drive()` calls the thunk. `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 builds `ChildSuccessBox<…>`/`ChildFailureBox<…>` 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<Step>` (wrapping plain `Step` via `ready_task`). The discovery is invocability-based — **no parameter-type reflection (P3096)**.
|
|
|
|
**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 + `States<>`, the single nested `State` base, lifecycle, events, nesting, persistence); `Detail/Roles.hpp` (the signature-inference: `ChildSuccess`/`ChildFailure` concepts + boxes, `invoke_entry`/`invoke_startup`/`invoke_handler`/`dispatch_result`/`make_driver`/`has_transitions`); `Detail/Result.hpp` (`SuccessOf`/`FailureOf`/`OutcomeOf<Derived>`); `Detail/Reactive.hpp` (the declarative transition DSL as standalone `Detail::TransitionBuilder`/`EventClause`/`AfterClause`/`TransitionTable<Derived>` templates); `Detail/Awaiter.hpp` (one `Detail::EventAwaiter` behind `make_event_awaiter`, used by all `await_*`); `Detail/Introspect.hpp` (`StateInfo`/`EdgeInfo` + `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 one `Async::ManualExecutor` + worker thread + a lock-free MPSC event queue + a typed event mailbox. A single consumer (worker, or the embedder via `pump()` when `MachineOptions{.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 queued `E` (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 its `Outcome` (`std::expected<R, FsmError>`) — the imperative form, branch on it yourself.
|
|
- **Sub-machine continuations (declarative)**: `co_return startMachine<Sub, Next>(args...)` launches `Sub` (constructed from `args`, on the shared executor/events/services), then enters `Next` and the engine **finds on its own which method to call** — `Next` derives `Continue<Sub::result_type>` and the engine dispatches to `on_success(R)` or `on_failure(FsmError)` by the outcome (a `Continue<void>` takes a nullary `on_success()`). `Next` must derive `Continue<R>` (a `static_assert` enforces it) and be in `States<>`. A `Continue` handler may itself return another `startMachine` (chaining) or any normal `Step`. Mechanics: a `Step::Kind::Launch` carries the target + a type-erased launcher; `drive()` runs it, stashes the `LaunchResult`, and the entered state's `resume()` (overridden by `Continue<R>`) dispatches — a plain state entered with a pending result just `run()`s.
|
|
- **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**, yielding `std::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>()` is `run_child` with introspection — the calling state's `on_enter`/`on_exit` wrap the child region, and the parent's `state_path()` reports the parent→child chain (`{Composite, …child leaf}`) while it runs. Map the child's `Outcome` to a sibling transition (`r ? next<Done>() : next<Recover>()`). Parent-level multi-event handling via `co_await await_any<E1, E2, …>()` → `std::variant<Es...>` (e.g. a region waits for `Tick` or `Cancel` at one level). Coroutines aren't preemptible mid-flight, so child cancellation is **cooperative**: the region awaits a shared `Cancel` event (events route to the deepest awaiter) and returns a failing `Outcome` the 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, …)` (variadic `post`); free in-state jumps via `goto_state<S>()` (any registered state, no declared transition); external `jump<S>()` applied at the next transition boundary (race-safe, non-preemptive — a running state isn't interrupted); lifecycle `reset()` / `restart()` / `restart_at<S>()` and `pause()` / `resume()` (paused = worker stops draining, posted events buffer); Idle-only mutation `remove<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 (P2996 `identifier_of`, fallback to indexed names). `state_path()` is the same but appends an active `run_region` child's path — consumer-consistent (read it from within the machine or once settled; deterministic in `pump()` mode).
|
|
- **Introspection**: `describe()` lists registered states (name, reactive?, initial?) plus the transitions declared by reactive states (event/target names, guard-present); imperative `run()`-chosen edges aren't statically knowable so those states are edgeless nodes. `to_mermaid()` renders a `stateDiagram-v2` string.
|
|
- **Error policies / middleware**: state helpers `delay(d)`, `with_retry(times, backoff, attempt)` (retries a `Coro::Task<bool>` sub-step), `next_or<Fallback>(step)` (route a failing `Step` to 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 (override `on_serialize`/`on_restore` for derived data, reflection-JSON friendly).
|
|
- Hot-plug + state-saving are re-expressed via services: plugins provide `IService` impls; `PluginServiceBinding` swaps the registry entry on reload (state migrated by the plugin's v2 ABI), so running FSMs pick up the new impl on the next `service<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`): 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.
|