From c9de739dfa7c9e556548dc77e44ae76aa8dda673 Mon Sep 17 00:00:00 2001 From: Yaraslau Tamashevich Date: Fri, 27 Nov 2026 07:49:37 +0100 Subject: [PATCH 01/11] fix(bridge): destroying a handler no longer scans every live handler Each HandlerBinding records its slot in the bridge's tracking list. deregisterHandler moves the last entry into that slot, fixes the moved binding's slot and pops, so removal is O(1) instead of a lock() over every live handler. Tearing down N handlers is now linear in N. The list is unordered: switchBackend, the reconnect handler and ~Bridge each visit every live binding once and depend on no order. Entries whose binding died without deregistering are compacted whenever the list has doubled since the last compaction, and by switchBackend, which rewrites the slots. Fixes #1173 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT --- docs/spec/core/bridge.md | 2 +- include/morph/core/bridge.hpp | 73 +++++++++++++-- tests/CMakeLists.txt | 1 + tests/test_bridge_tracking.cpp | 160 +++++++++++++++++++++++++++++++++ 4 files changed, 228 insertions(+), 8 deletions(-) create mode 100644 tests/test_bridge_tracking.cpp diff --git a/docs/spec/core/bridge.md b/docs/spec/core/bridge.md index f820e5e01..ca160412d 100644 --- a/docs/spec/core/bridge.md +++ b/docs/spec/core/bridge.md @@ -1047,7 +1047,7 @@ means. | Decision | Choice | Why | |---|---|---| -| Binding storage | **`vector>`** | `Bridge` does not own the bindings — the handler (`BridgeHandler` or `RawHandler`) holds the `shared_ptr`. Weak references let `switchBackend` and the reconnect handler skip dead bindings without keeping handlers alive. | +| Binding storage | **`vector>`** | `Bridge` does not own the bindings — the handler (`BridgeHandler` or `RawHandler`) holds the `shared_ptr`. Weak references let `switchBackend` and the reconnect handler skip dead bindings without keeping handlers alive. Each binding records its slot in the vector, so removal swaps the last entry into the slot and pops: O(1), not a scan of every live handler. The vector is therefore unordered; `switchBackend`, the reconnect handler and `~Bridge` each visit every live binding once and need no order. Entries whose binding died without deregistering are compacted whenever the vector has doubled since the last compaction, and by `switchBackend`. | | Threading | **One owner, given at construction; every verb owner-only, asserted in debug builds** | Consumers call their `Bridge` from one thread, and a free-threaded contract would cost a lock per runtime-settable field, a lifetime gate for teardown on any thread, and a registration handoff for replies that settle on a thread the bridge does not own. Handing the owner to `bindModel`/`promoteModel` as the delivery executor, and having backends post reconnects to it, makes every one of those a task on the owner instead. Teardown follows: handlers before the bridge, on the owner. | | Registration | **Asynchronous, with no policy: the bind rule** | A handler can be constructed inside a running action, off the owner, so its registration has to be posted; once it can be, every bind can be a `Completion` delivered on the owner. A backend that settles before returning keeps the synchronous feel — a `LocalBackend` handler is bound when its constructor returns — and the caller never has to gate a first dispatch on readiness, because `execute` is held until the bind settles. | | Reconnect handler | **Posted to the owner; liveness guard + weak-backend guard + stale check; cleared in `~Bridge`** | `IBackend::setReconnectHandler` takes the executor the handler is posted to, and the bridge passes its owner, so the re-bind is an ordinary owner task. The handler checks the bridge's `CallbackToken`, then that the backend that reconnected is still the active one; a reconnect of a backend switched away from is ignored. `~Bridge` and `switchBackend` clear the outgoing backend's handler. | diff --git a/include/morph/core/bridge.hpp b/include/morph/core/bridge.hpp index 7d494238a..5e9a22a17 100644 --- a/include/morph/core/bridge.hpp +++ b/include/morph/core/bridge.hpp @@ -329,6 +329,14 @@ struct HandlerBinding { /// made. Each is resumed with null to proceed, or with the error it /// is rejected with. std::deque> waiting; + + /// @brief Where the owning `Bridge` keeps this binding in its tracking + /// list, or `untracked`. Lets the bridge remove the binding without + /// scanning the list. Written only by the bridge, on its owner. + std::size_t trackedSlot = untracked; + + /// @brief `trackedSlot` value of a binding no bridge tracks. + static constexpr std::size_t untracked = static_cast(-1); }; /// @brief Renders @p failure as the diagnostic string a log line wants. @@ -837,7 +845,7 @@ class Bridge { /// and `contextKey` must be set. void registerHandler(const std::shared_ptr& binding) { note("Bridge::registerHandler"); - _handlers.push_back(binding); + track(binding); auto superseded = startBind(binding, ::morph::backend::detail::BindRequest{.typeId = binding->typeId, .factory = binding->modelFactory, @@ -860,7 +868,7 @@ class Bridge { std::shared_ptr registerSharedHandler() { note("Bridge::registerSharedHandler"); auto binding = makeBinding(true); - _handlers.push_back(binding); + track(binding); return binding; } @@ -1319,6 +1327,7 @@ class Bridge { } } _handlers = std::move(live); + reindexHandlers(); auto previous = std::exchange(_backend, next); next->notifyBackendChanged(); installReconnectHandler(next); @@ -1354,10 +1363,7 @@ class Bridge { if (raw != 0U) { _backend->deregisterModel(::morph::exec::detail::ModelId{raw}); } - std::erase_if(_handlers, [&binding](const auto& weak) { - auto strong = weak.lock(); - return !strong || strong.get() == binding.get(); - }); + untrack(binding); auto const destroyed = std::make_exception_ptr(::morph::backend::HandlerDestroyedError{}); for (auto& resume : rejected) { resume(destroyed); @@ -1845,7 +1851,7 @@ class Bridge { void adoptOnOwner(const std::shared_ptr& binding) { if (binding->shared) { note("Bridge::registerSharedHandler"); - _handlers.push_back(binding); + track(binding); drainWaiting(*binding); return; } @@ -2529,9 +2535,62 @@ class Bridge { } } + /// @brief Appends @p binding to the tracking list and records its slot. + /// + /// Entries whose binding has been destroyed without deregistering are + /// compacted away whenever the list has doubled since the last compaction, + /// so the sweep is amortised O(1) per registration. + /// @param binding Binding to track. + void track(const std::shared_ptr& binding) { + if (_handlers.size() >= _sweepAt) { + std::erase_if(_handlers, [](const auto& weak) { return weak.expired(); }); + reindexHandlers(); + _sweepAt = std::max(kMinSweepAt, _handlers.size() * 2); + } + binding->trackedSlot = _handlers.size(); + _handlers.push_back(binding); + } + + /// @brief Removes @p binding from the tracking list in O(1). + /// + /// The last entry moves into the vacated slot, so the list's order is not + /// registration order; every reader of the list visits each live binding + /// once and needs no order. A binding this bridge does not track is left + /// alone. + /// @param binding Binding to stop tracking. + void untrack(const std::shared_ptr& binding) { + auto const slot = std::exchange(binding->trackedSlot, detail::HandlerBinding::untracked); + if (slot >= _handlers.size()) { + return; + } + auto const& entry = _handlers[slot]; + if (entry.owner_before(binding) || binding.owner_before(entry)) { + return; + } + if (slot + 1 != _handlers.size()) { + _handlers[slot] = std::move(_handlers.back()); + if (auto const moved = _handlers[slot].lock()) { + moved->trackedSlot = slot; + } + } + _handlers.pop_back(); + } + + /// @brief Rewrites every live binding's `trackedSlot` to its position in the list. + void reindexHandlers() { + for (std::size_t slot = 0; slot < _handlers.size(); ++slot) { + if (auto const binding = _handlers[slot].lock()) { + binding->trackedSlot = slot; + } + } + } + + static constexpr std::size_t kMinSweepAt = 64; + ::morph::exec::detail::OwnerAffinity _affinity; std::shared_ptr<::morph::backend::detail::IBackend> _backend; std::vector> _handlers; + std::size_t _sweepAt = kMinSweepAt; ::morph::session::Context _defaultSession; ::morph::session::Principal _principal; // Client-side execute deadline (see setExecuteDeadline). The scheduler is diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 8b50b8a62..b9ea8c165 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -98,6 +98,7 @@ add_executable(morph_tests test_security_fixes.cpp test_bridge_lifetime.cpp test_bridge_bind_paths.cpp + test_bridge_tracking.cpp test_bridge_owner.cpp test_core_branch_gaps.cpp test_client_execute_deadline.cpp diff --git a/tests/test_bridge_tracking.cpp b/tests/test_bridge_tracking.cpp new file mode 100644 index 000000000..b40cece68 --- /dev/null +++ b/tests/test_bridge_tracking.cpp @@ -0,0 +1,160 @@ +// SPDX-License-Identifier: Apache-2.0 + +// How the Bridge tracks its handlers: removing one in any order must leave +// every other live handler visible to whatever walks the list (a backend +// switch), exactly once, and never revive a removed one. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// NOLINTBEGIN(misc-use-internal-linkage) +struct BtkPing { + int unused = 0; +}; +struct BtkModel { + static int execute(const BtkPing& /*act*/) { return 1; } +}; +BRIDGE_REGISTER_MODEL(BtkModel, "BTK_Model") +BRIDGE_REGISTER_ACTION(BtkModel, BtkPing, "BTK_Ping") +// NOLINTEND(misc-use-internal-linkage) + +namespace { + +using morph::bridge::Bridge; +using Binding = std::shared_ptr; + +/// Counts the binds it is asked for, by the context key of the binding. +class CountingBackend : public morph::backend::LocalBackend { +public: + explicit CountingBackend(morph::exec::IExecutor& pool) : LocalBackend{pool} {} + + morph::async::Completion bindModel(morph::backend::detail::BindRequest request, + morph::exec::IExecutor& cbExec) override { + ++binds[request.contextKey]; + return LocalBackend::bindModel(std::move(request), cbExec); + } + + std::map binds; +}; + +struct Rig { + morph::exec::ThreadPoolExecutor pool{2}; + morph::exec::MainThreadExecutor owner; + Bridge bridge{std::make_unique(pool), owner}; + std::vector bindings; + std::vector removed; + + explicit Rig(std::size_t count) { + for (std::size_t i = 0; i < count; ++i) { + add(); + } + } + + void add() { + auto binding = bridge.registerHandler(); + binding->contextKey = "h" + std::to_string(nextKey++); + bindings.push_back(std::move(binding)); + } + + void destroy(std::size_t position) { + bridge.deregisterHandler(bindings[position]); + // Kept alive so a removal that left its entry behind would show up as + // a rebind of a handler that no longer exists. + removed.push_back(bindings[position]); + bindings.erase(bindings.begin() + static_cast(position)); + } + + /// Switches to a fresh counting backend and checks each surviving binding + /// was rebound exactly once, and no removed one was touched. + void requireSwitchRebindsSurvivors() { + auto next = std::make_unique(pool); + auto const& binds = next->binds; + bridge.switchBackend(std::move(next)); + REQUIRE(binds.size() == bindings.size()); + for (auto const& binding : bindings) { + auto const found = binds.find(binding->contextKey); + REQUIRE(found != binds.end()); + REQUIRE(found->second == 1); + REQUIRE(Bridge::isBound(binding)); + } + } + + int nextKey = 0; +}; + +} // namespace + +TEST_CASE("Bridge tracking keeps survivors after removing the first, last and middle handler", + "[bridge][tracking]") { + Rig rig{7}; + rig.destroy(0); + rig.destroy(rig.bindings.size() - 1); + rig.destroy(2); + rig.requireSwitchRebindsSurvivors(); + REQUIRE(rig.bindings.size() == 4); +} + +TEST_CASE("Bridge tracking keeps survivors when removal interleaves with creation", "[bridge][tracking]") { + Rig rig{4}; + rig.destroy(1); + rig.add(); + rig.add(); + rig.destroy(0); + rig.add(); + rig.destroy(3); + rig.requireSwitchRebindsSurvivors(); +} + +TEST_CASE("Bridge tracking removes handlers correctly after a backend switch", "[bridge][tracking]") { + Rig rig{6}; + rig.destroy(1); + rig.requireSwitchRebindsSurvivors(); + rig.destroy(0); + rig.destroy(rig.bindings.size() - 1); + rig.add(); + rig.requireSwitchRebindsSurvivors(); +} + +TEST_CASE("Bridge tracking survives removing every handler in a random order", "[bridge][tracking]") { + Rig rig{40}; + std::mt19937 gen{12345}; + while (rig.bindings.size() > 1) { + rig.destroy(std::uniform_int_distribution{0, rig.bindings.size() - 1}(gen)); + if (rig.bindings.size() % 7 == 0) { + rig.requireSwitchRebindsSurvivors(); + } + } + rig.requireSwitchRebindsSurvivors(); +} + +TEST_CASE("Bridge tracking ignores a second removal of the same handler", "[bridge][tracking]") { + Rig rig{3}; + auto const dropped = rig.bindings[1]; + rig.destroy(1); + rig.bridge.deregisterHandler(dropped); + rig.requireSwitchRebindsSurvivors(); + REQUIRE(rig.bindings.size() == 2); +} + +TEST_CASE("Bridge tracking drops handlers destroyed without removal", "[bridge][tracking]") { + Rig rig{3}; + for (int i = 0; i < 500; ++i) { + auto const lost = rig.bridge.registerHandler(); + (void)lost; + } + rig.destroy(0); + rig.add(); + rig.destroy(1); + rig.requireSwitchRebindsSurvivors(); +} From 4350d69590dc6e880c0e59c7b6346bf49eb5762c Mon Sep 17 00:00:00 2001 From: Yaraslau Tamashevich Date: Fri, 27 Nov 2026 07:47:02 +0100 Subject: [PATCH 02/11] test(bench): gate user-space instructions per local call morph_bench_instr counts retired user-space instructions (Linux perf_event_open, inherited by the pool's workers) across a steady-state batch of local round trips and fails above --budget. The ceiling is the cache variable MORPH_INSTR_BUDGET_PER_CALL, 65000 in Debug and 9000 in the optimized build types, each the worst measured figure plus a margin. Where the counter cannot be opened, and on every non-Linux platform, the binary prints the reason and exits 77, registered as SKIP_RETURN_CODE, so ctest reports Skipped rather than a pass that measured nothing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT --- docs/spec/testing_strategy.md | 39 +++ tests/bench/CMakeLists.txt | 73 +++++ tests/bench/bench_dispatch_instructions.cpp | 344 ++++++++++++++++++++ 3 files changed, 456 insertions(+) create mode 100644 tests/bench/bench_dispatch_instructions.cpp diff --git a/docs/spec/testing_strategy.md b/docs/spec/testing_strategy.md index 5760fb20f..6eefa5ebd 100644 --- a/docs/spec/testing_strategy.md +++ b/docs/spec/testing_strategy.md @@ -420,6 +420,45 @@ build costs **14.06** and 0.00 per lookup — exactly 3.00 removed, in every one of 40 processes, idle and loaded, on clang Release, clang Debug and gcc Debug alike. A figure from an ungated benchmark is not comparable with either. +### Instructions per local call (`bench_dispatch_instructions.cpp`, target `morph_bench_instr`) + +User-space retired instructions per local `execute` round trip: `Bridge` over +`LocalBackend` over a four-thread `ThreadPoolExecutor`, a model holding one +`double`, a trivial action, 200 warm-up calls excluded and 2000 counted. The +counter is Linux `perf_event_open` (`PERF_COUNT_HW_INSTRUCTIONS`, +`exclude_kernel`, `inherit`), opened before the pool exists so that the pool's +workers, where the action runs, inherit it. `--baseline` also prints a bare +cross-thread condition-variable round trip with no morph in it, the floor a +local call cannot go under (about 0.8k in Release). + +It covers what the allocation census cannot: a cost that allocates nothing — a +lock taken twice, a copy of a large capture, a scan that grew. Wall-clock time +sees those too but is too noisy to gate on a shared runner; an instruction count +does not move with machine load or clock speed. + +The owning thread sleeps on a condition variable while it waits. A polling +owner spends about ten times the instructions spinning, and the figure would +then measure the spin. The owner is a serial executor of the benchmark's own, +because a one-thread pool is not serial and is refused as an owner. + +**It is a gate.** `bench.instr_budget` passes `--budget=`, taken from the +cache variable `MORPH_INSTR_BUDGET_PER_CALL`: 65000 for Debug (the build type CI +runs this target in) and 9000 for the optimized types; 0 disables it; it is not +registered under a sanitizer. The count is not exact — it moves by about ±10% +between processes — so each default is the worst figure measured plus a margin, +and `tests/bench/CMakeLists.txt` carries the measurements. Typical figures on +x86-64 Linux: about 7.4k per call in Release and 55k–59k in Debug, with clang and gcc +within 5% of each other. It was checked against an injected regression: a loop of +volatile operations in the action turns the case red in both configurations. + +**Where there is no counter the case is skipped, not passed.** Containers, +`perf_event_paranoid` above 2 and every non-Linux platform refuse the counter. +The binary then prints the reason (`SKIP: no instruction counter, nothing was +measured: ...`) and exits with 77, which the test registers as +`SKIP_RETURN_CODE`, so ctest reports `Skipped`. Windows and macOS skip it +always: there the counter is not read at all, and the Linux-specific headers +and system call are compiled out, so the target still builds. + ## Concurrent-user benchmark (`scripts/scenario/bench_bookmarks.py`) `morph_bench` measures one dispatch inside one process. This benchmark measures diff --git a/tests/bench/CMakeLists.txt b/tests/bench/CMakeLists.txt index 9df928c6f..fb435ae4d 100644 --- a/tests/bench/CMakeLists.txt +++ b/tests/bench/CMakeLists.txt @@ -136,3 +136,76 @@ if(NOT MORPH_ALLOC_BUDGET_PER_CALL EQUAL 0) "--id-length-budget=0.5") set_tests_properties(bench.alloc_budget PROPERTIES TIMEOUT 120 LABELS "bench") endif() + +# ── Instructions per local call ────────────────────────────────────────────── +# +# User-space retired instructions per local `execute` round trip, from Linux +# `perf_event_open`. The allocation gate above cannot see a cost that +# allocates nothing and a wall-clock gate cannot be tight on a shared runner; +# an instruction count moves with the code and not with the machine's load. +# A binary of its own because the counter has to be opened before the pool's +# threads exist, so that they inherit it. +add_executable(morph_bench_instr bench_dispatch_instructions.cpp) +target_link_libraries(morph_bench_instr PRIVATE morph::morph) +morph_suppress_test_dialogs(morph_bench_instr) +apply_warnings(morph_bench_instr) + +# Exit code 77 is "the counter could not be opened" (containers, +# `perf_event_paranoid` above 2, non-Linux). It is registered as ctest's skip +# return code so such a runner shows `Skipped` instead of a pass that measured +# nothing. +# +# **The ceiling is per toolchain and per build type**, hence a cache variable: +# an instruction count is a property of the compiler, the optimizer and the +# standard library. 0 disables the gate. It is not registered at all under a +# sanitizer, whose instrumentation changes the count by an order of magnitude. +# Measured on this tree, 12 processes per row, user-space instructions per +# local round trip (min / median / max); a bare cross-thread round trip with no +# morph in it costs 0.8k (Release) to 1.1k (Debug) of that: +# +# gcc 16.2.1 / libstdc++ 16.2.1, Release : 6345 / 7019 / 7587 (12 runs while +# the machine was compiling); 7443 / 7445 / +# 7445 (10 runs, idle) +# gcc 16.2.1 / libstdc++ 16.2.1, Debug : 54863 / 57978 / 59229 +# clang 22.1.8 / libstdc++ 16.2.1, Debug : 54155 / 57005 / 57474 +# +# **The figure is not exact, unlike the allocation count**, and the spread is +# the reason for the headroom: it moves by about +-10% between processes, +# because whether a reply beats its `.then` to being attached, and how often a +# thread goes to sleep on a futex, differ from run to run. The defaults are +# therefore the worst figure seen plus a margin a regression has to exceed: +# Debug (what CI builds: Linux `clang-debug` and `gcc-debug`) 65000, 10% over +# the maximum; Release and the other optimized types 9000, 19% over it. A +# regression has to cost more than that margin -- about 6000 instructions in +# Debug, 1400 in Release -- to turn this red, which is a lock, a growing scan +# or a payload copy, not a stray branch. The allocation gate above is the +# fine-grained one. +# +# **Shown firing, not assumed to**: a loop of volatile operations inside the +# model's action, the sole change, turns `bench.instr_budget` red: +# +# Debug, gcc: FAIL: 67238 instructions per call exceeds --budget=65000 +# Release, gcc: FAIL: 10449 instructions per call exceeds --budget=9000 +# +# (1000 iterations of a volatile counter in the action: +8000 and +3000 +# instructions per call.) +# +# and the unmodified tree passes again. Where the counter cannot be opened the +# case reports `Skipped` instead; see the SKIP_RETURN_CODE note above. +if(MSVC OR DEFINED AF_SANITIZER) + set(_morph_instr_budget_default 0) +elseif(CMAKE_BUILD_TYPE MATCHES "^(Release|RelWithDebInfo|MinSizeRel)$") + set(_morph_instr_budget_default 9000) +else() + # Debug, and a multi-config generator, which has no single build type to + # read: the Debug figure is the one CI measured. + set(_morph_instr_budget_default 65000) +endif() +set(MORPH_INSTR_BUDGET_PER_CALL "${_morph_instr_budget_default}" CACHE STRING + "Ceiling, in user-space retired instructions per local execute round trip, that morph_bench_instr enforces as a ctest case. 0 disables the gate. See tests/bench/CMakeLists.txt for how the default was measured.") + +if(NOT MORPH_INSTR_BUDGET_PER_CALL EQUAL 0) + add_test(NAME bench.instr_budget + COMMAND morph_bench_instr "--budget=${MORPH_INSTR_BUDGET_PER_CALL}") + set_tests_properties(bench.instr_budget PROPERTIES TIMEOUT 120 LABELS "bench" SKIP_RETURN_CODE 77) +endif() diff --git a/tests/bench/bench_dispatch_instructions.cpp b/tests/bench/bench_dispatch_instructions.cpp new file mode 100644 index 000000000..f5e46bc0a --- /dev/null +++ b/tests/bench/bench_dispatch_instructions.cpp @@ -0,0 +1,344 @@ +// SPDX-License-Identifier: Apache-2.0 + +// User-space instructions retired per local `execute` round trip. +// +// An allocation count (`morph_bench_alloc`) is exact but blind to a cost that +// allocates nothing: a lock taken twice, a copy of a large capture, a scan that +// grew. Wall-clock time sees those and is too noisy to gate on a shared +// runner. A retired-instruction count sits between the two: it does not move +// with machine load or clock speed, and it moves with every extra instruction +// the dispatch path executes. +// +// The counter is Linux `perf_event_open` with `PERF_COUNT_HW_INSTRUCTIONS`, +// `exclude_kernel` and `inherit`. `inherit` only covers threads created after +// the counter is opened, so it is opened before the `ThreadPoolExecutor` +// exists; the pool's workers, where the action runs, are then counted too. +// +// **When the counter cannot be opened the run is reported as skipped, never as +// passed.** Containers, a `perf_event_paranoid` above 2 and non-Linux hosts all +// refuse it. The binary then prints the reason and exits with `kExitSkipped`, +// which `tests/bench/CMakeLists.txt` registers as ctest's skip return code, so +// a runner without counters shows "Skipped" rather than a green result that +// measured nothing. +// +// Method: +// * `Bridge` over `LocalBackend` over a four-thread pool; the owner is a +// serial executor whose `runUntil` sleeps on a condition variable. A +// polling owner spends ~10x the instructions spinning, and the figure +// would then measure the spin. +// * The model holds one `double`; the action adds to it. The workload is +// the smallest there is, so what remains is framework overhead. +// * `kWarmup` calls are excluded; `kCalls` are counted, each waited out +// before the next starts. +// * `--baseline` also prints the instructions of a bare cross-thread round +// trip (condition variable ping-pong, no morph), the floor a local call +// cannot go under. +// +// The ceiling is `--budget=`; the figure is a property +// of the compiler and standard library, so it is a per-configuration cache +// variable in `tests/bench/CMakeLists.txt` with its measurements beside it. +// +// Build: `-DMORPH_BUILD_LOAD_TESTS=ON`, target `morph_bench_instr`. See +// docs/spec/testing_strategy.md. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) + #include + #include + #include + #include + + #include +#endif + +// External linkage so glaze's reflection can mangle the type names. +struct BenchInstrPing { + double x = 0.0; +}; +struct BenchInstrPong { + double y = 0.0; +}; +struct BenchInstrModel { + double total = 0.0; + BenchInstrPong execute(const BenchInstrPing& action) { + total += action.x; + return BenchInstrPong{.y = total}; + } +}; + +BRIDGE_REGISTER_MODEL(BenchInstrModel, "BenchInstr_Model") +BRIDGE_REGISTER_ACTION(BenchInstrModel, BenchInstrPing, "BenchInstr_Ping") + +namespace { + +/// Exit status meaning "no counter, nothing measured". ctest's +/// `SKIP_RETURN_CODE` is set to the same value. +constexpr int kExitSkipped = 77; +constexpr int kExitUsage = 2; + +constexpr int kWarmup = 200; +constexpr int kCalls = 2000; +constexpr std::size_t kPoolThreads = 4; + +#if defined(__linux__) + +/// A user-space retired-instruction counter that follows threads created after +/// it is opened. +class InstructionCounter { +public: + /// @return The counter, or the reason it could not be opened. + static std::optional open(std::string& why) { + perf_event_attr attr{}; + attr.type = PERF_TYPE_HARDWARE; + attr.size = sizeof(attr); + attr.config = PERF_COUNT_HW_INSTRUCTIONS; + attr.disabled = 1; + attr.inherit = 1; + attr.exclude_kernel = 1; + attr.exclude_hv = 1; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) + long const fd = ::syscall(SYS_perf_event_open, &attr, 0, -1, -1, 0); + if (fd < 0) { + why = std::format("perf_event_open(PERF_COUNT_HW_INSTRUCTIONS) failed: {}", std::strerror(errno)); + return std::nullopt; + } + return InstructionCounter{static_cast(fd)}; + } + + InstructionCounter(InstructionCounter&& other) noexcept : _fd{std::exchange(other._fd, -1)} {} + InstructionCounter& operator=(InstructionCounter&&) = delete; + InstructionCounter(const InstructionCounter&) = delete; + InstructionCounter& operator=(const InstructionCounter&) = delete; + ~InstructionCounter() { + if (_fd >= 0) { + ::close(_fd); + } + } + + void start() const { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) + ::ioctl(_fd, PERF_EVENT_IOC_RESET, 0); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) + ::ioctl(_fd, PERF_EVENT_IOC_ENABLE, 0); + } + + /// @return Instructions retired since `start()`, over this thread and + /// every thread it spawned after the counter was opened. + [[nodiscard]] std::uint64_t stop() const { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) + ::ioctl(_fd, PERF_EVENT_IOC_DISABLE, 0); + std::uint64_t value = 0; + if (::read(_fd, &value, sizeof(value)) != static_cast(sizeof(value))) { + return 0; + } + return value; + } + +private: + explicit InstructionCounter(int fd) : _fd{fd} {} + int _fd; +}; + +#else + +class InstructionCounter { +public: + static std::optional open(std::string& why) { + why = "hardware instruction counters are only read on Linux"; + return std::nullopt; + } + void start() const {} + [[nodiscard]] std::uint64_t stop() const { return 0; } +}; + +#endif + +// A serial executor the owning thread sleeps on. `runUntil` runs queued tasks +// on the calling thread, each inside the executor scope the bridge expects, and +// waits on a condition variable when there is nothing to run. +class SleepingOwner : public ::morph::exec::IExecutor { +public: + void post(std::function task) override { + { + std::scoped_lock const lock{_mtx}; + _queue.push_back(std::move(task)); + } + _cv.notify_one(); + } + + template + void runUntil(Pred done) { + for (;;) { + std::function task; + { + std::unique_lock lock{_mtx}; + _cv.wait(lock, [this] { return !_queue.empty(); }); + task = std::move(_queue.front()); + _queue.pop_front(); + } + { + ::core::async::ExecutorScope const scope{coreExecutor()}; + if (task) { + task(); + } + } + if (done()) { + return; + } + } + } + +private: + std::mutex _mtx; + std::condition_variable _cv; + std::deque> _queue; +}; + +// Instructions per cross-thread round trip with no morph in it: one thread +// wakes another through a condition variable and waits to be woken back. +double baselinePerCall(InstructionCounter const& counter, int calls) { + std::mutex mtx; + std::condition_variable cv; + int turn = 0; // even: main's turn, odd: the worker's + bool stop = false; + std::thread worker{[&] { + std::unique_lock lock{mtx}; + for (;;) { + cv.wait(lock, [&] { return stop || turn % 2 == 1; }); + if (stop) { + return; + } + ++turn; + cv.notify_all(); + } + }}; + auto const ping = [&] { + std::unique_lock lock{mtx}; + ++turn; + cv.notify_all(); + int const target = turn + 1; + cv.wait(lock, [&] { return turn >= target; }); + }; + for (int i = 0; i < kWarmup; ++i) { + ping(); + } + counter.start(); + for (int i = 0; i < calls; ++i) { + ping(); + } + auto const total = counter.stop(); + { + std::scoped_lock const lock{mtx}; + stop = true; + } + cv.notify_all(); + worker.join(); + return static_cast(total) / static_cast(calls); +} + +int run(bool baseline, double budget) { + std::string why; + // Opened before any thread of this process's own is created: `inherit` + // reaches only threads started after the counter exists. + auto counter = InstructionCounter::open(why); + if (!counter) { + std::cout << "SKIP: no instruction counter, nothing was measured: " << why << "\n"; + return kExitSkipped; + } + + ::morph::exec::ThreadPoolExecutor pool{kPoolThreads}; + SleepingOwner owner; + double perCall = 0.0; + { + ::morph::bridge::Bridge bridge{std::make_unique<::morph::backend::LocalBackend>(pool), owner}; + ::morph::bridge::BridgeHandler handler{bridge, &owner}; + + int settled = 0; // touched only by the owner's tasks and this thread between them + auto roundTrip = [&](int value) { + int const target = settled + 1; + handler.execute(BenchInstrPing{.x = static_cast(value)}) + .then([&settled](const BenchInstrPong&) { ++settled; }) + .onError([&settled](const std::exception_ptr&) { ++settled; }); + owner.runUntil([&] { return settled >= target; }); + }; + for (int i = 0; i < kWarmup; ++i) { + roundTrip(i); + } + counter->start(); + for (int i = 0; i < kCalls; ++i) { + roundTrip(i); + } + auto const total = counter->stop(); + perCall = static_cast(total) / static_cast(kCalls); + std::cout << std::format("local execute round-trips : {}\n", kCalls) + << std::format("user instructions total : {} ({:.0f} per call)\n", total, perCall); + } + if (baseline) { + std::cout << std::format("bare cross-thread round trip: {:.0f} instructions per call\n", + baselinePerCall(*counter, kCalls)); + } + if (perCall <= 0.0) { + std::cout << "SKIP: the counter read back zero; nothing was measured\n"; + return kExitSkipped; + } + if (budget > 0.0) { + if (perCall > budget) { + std::cout << std::format("FAIL: {:.0f} instructions per call exceeds --budget={:.0f}\n", perCall, budget); + return 1; + } + std::cout << std::format("ok: {:.0f} instructions per call within --budget={:.0f}\n", perCall, budget); + } + return 0; +} + +} // namespace + +int main(int argc, char** argv) { + try { + bool baseline = false; + double budget = 0.0; + std::span const args{argv, static_cast(argc)}; + for (std::size_t i = 1; i < args.size(); ++i) { + std::string_view const arg{args[i]}; + if (arg == "--baseline") { + baseline = true; + } else if (arg.starts_with("--budget=")) { + budget = std::stod(std::string{arg.substr(std::string_view{"--budget="}.size())}); + } else { + std::cout << "usage: morph_bench_instr [--baseline] [--budget=]\n"; + return kExitUsage; + } + } + return run(baseline, budget); + } catch (const std::exception& exc) { + std::cout << "FAIL: " << exc.what() << "\n"; + return 1; + } catch (...) { + std::cout << "FAIL: unknown exception\n"; + return 1; + } +} From 0a5d8c2a9c75cee5a12a5248db9e797964184fd3 Mon Sep 17 00:00:00 2001 From: Yaraslau Tamashevich Date: Fri, 27 Nov 2026 07:47:02 +0100 Subject: [PATCH 03/11] test(bench): gate handler teardown scaling on a size ratio morph_bench_teardown destroys 2000 and then 32000 live handlers on one Bridge and fails when the per-handler destroy cost at the large count exceeds --max-ratio times the cost at the small one. A ratio cancels machine speed and build type: constant-cost teardown reads near 1 (1.3 to 4.8 measured), a scan of every live handler reads 9.5 to 12.6 in Release. The ceiling is the cache variable MORPH_TEARDOWN_MAX_RATIO, 7. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT --- docs/spec/testing_strategy.md | 24 +++ tests/bench/CMakeLists.txt | 25 ++++ tests/bench/bench_handler_teardown.cpp | 196 +++++++++++++++++++++++++ 3 files changed, 245 insertions(+) create mode 100644 tests/bench/bench_handler_teardown.cpp diff --git a/docs/spec/testing_strategy.md b/docs/spec/testing_strategy.md index 6eefa5ebd..0bf9c86a7 100644 --- a/docs/spec/testing_strategy.md +++ b/docs/spec/testing_strategy.md @@ -459,6 +459,30 @@ measured: ...`) and exits with 77, which the test registers as always: there the counter is not read at all, and the Linux-specific headers and system call are compiled out, so the target still builds. +### Handler teardown scaling (`bench_handler_teardown.cpp`, target `morph_bench_teardown`) + +Destroying one `BridgeHandler` costs the same whether the bridge holds ten +handlers or ten thousand, or tearing a population down is quadratic: invisible +at the sizes a unit test builds, a stall at the sizes a long-lived client +reaches. The benchmark creates and binds 2000 handlers on one `Bridge` over +`LocalBackend`, destroys them one by one and times only the destruction; then +the same for 32000. Each count is the best of several trials (7 and 3), the run +least disturbed by the rest of the machine. + +**It is a gate on a ratio, not on a time**: the per-handler destroy cost at +32000 over the cost at 2000. A constant-cost teardown reads near 1; a teardown +that scans every live handler reads near 16, the count ratio. A ratio cancels +machine speed, compiler and build type, so the one ceiling holds on a loaded +runner, in Debug and under a slower scheduler such as Windows' alike. The +case is `bench.teardown_scaling`, with `--max-ratio` from the cache variable +`MORPH_TEARDOWN_MAX_RATIO` (default 7, 0 disables). + +7 is placed between the two populations measured. With the per-handler scan +removed, the ratio is 1.3–4.8 over 11 runs, above 1 because 32000 handlers no +longer fit in cache. With the scan, it is 9.5–12.6 in Release and about 20 in +Debug. The case therefore fails while `Bridge::deregisterHandler` scans every +live handler, and passes once it does not. + ## Concurrent-user benchmark (`scripts/scenario/bench_bookmarks.py`) `morph_bench` measures one dispatch inside one process. This benchmark measures diff --git a/tests/bench/CMakeLists.txt b/tests/bench/CMakeLists.txt index fb435ae4d..ba9d9863e 100644 --- a/tests/bench/CMakeLists.txt +++ b/tests/bench/CMakeLists.txt @@ -209,3 +209,28 @@ if(NOT MORPH_INSTR_BUDGET_PER_CALL EQUAL 0) COMMAND morph_bench_instr "--budget=${MORPH_INSTR_BUDGET_PER_CALL}") set_tests_properties(bench.instr_budget PROPERTIES TIMEOUT 120 LABELS "bench" SKIP_RETURN_CODE 77) endif() + +# ── Handler teardown scaling ───────────────────────────────────────────────── +# +# Per-handler destroy cost at 32000 live handlers over the cost at 2000. The +# gate is the RATIO, so machine speed, build type and scheduler cancel: a +# constant-cost teardown reads about 1, a teardown that scans every live +# handler reads about 16 (the count ratio). MORPH_TEARDOWN_MAX_RATIO is the +# ceiling; 0 disables the gate. Nothing in it is toolchain-specific, so the +# default is the same everywhere, Windows included. +# +# TEARDOWN-MEASUREMENTS +add_executable(morph_bench_teardown bench_handler_teardown.cpp) +target_link_libraries(morph_bench_teardown PRIVATE morph::morph) +morph_suppress_test_dialogs(morph_bench_teardown) +apply_warnings(morph_bench_teardown) +if(DEFINED AF_SANITIZER) + apply_sanitizers(morph_bench_teardown ${AF_SANITIZER}) +endif() +set(MORPH_TEARDOWN_MAX_RATIO 7.0 CACHE STRING + "Ceiling on per-handler destroy cost at 32000 live handlers over the cost at 2000, enforced by morph_bench_teardown as a ctest case. 0 disables the gate.") +if(NOT MORPH_TEARDOWN_MAX_RATIO EQUAL 0) + add_test(NAME bench.teardown_scaling + COMMAND morph_bench_teardown "--max-ratio=${MORPH_TEARDOWN_MAX_RATIO}") + set_tests_properties(bench.teardown_scaling PROPERTIES TIMEOUT 300 LABELS "bench") +endif() diff --git a/tests/bench/bench_handler_teardown.cpp b/tests/bench/bench_handler_teardown.cpp new file mode 100644 index 000000000..961535440 --- /dev/null +++ b/tests/bench/bench_handler_teardown.cpp @@ -0,0 +1,196 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Handler teardown cost as a function of how many handlers are live. +// +// Destroying one `BridgeHandler` should cost the same whether the bridge holds +// ten handlers or ten thousand. If it scans the bridge's other handlers, the +// cost per handler grows with the count and tearing a whole population down is +// quadratic: invisible at the sizes a unit test builds, a stall at the sizes a +// long-lived client reaches. +// +// What is gated is a RATIO: the per-handler destroy cost at a large count over +// the per-handler destroy cost at a small count. A constant-cost teardown gives +// about 1; a scan of every live handler gives about `large / small`. A ratio +// cancels machine speed, compiler and build type, which an absolute time per +// handler cannot, so one threshold holds on a loaded runner, under Debug and +// on a slower Windows scheduler alike. +// +// Method: +// * `Bridge` over `LocalBackend` over a two-thread pool, owned by this thread. +// * `N` handlers are created and bound, and a call through the last one +// settles so every bind has completed; then they are destroyed one by one +// in creation order and only the destruction is timed. +// * The small count is timed as the best of `kSmallTrials` runs, the large +// count as the best of `kLargeTrials`; the minimum is the run least +// disturbed by the rest of the machine. +// +// Build: `-DMORPH_BUILD_LOAD_TESTS=ON`, target `morph_bench_teardown`. +// See docs/spec/testing_strategy.md. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// External linkage so glaze's reflection can mangle the type names. +struct BenchTeardownPing { + int x = 0; +}; +struct BenchTeardownPong { + int y = 0; +}; +struct BenchTeardownModel { + BenchTeardownPong execute(const BenchTeardownPing& action) { return BenchTeardownPong{.y = action.x}; } +}; + +BRIDGE_REGISTER_MODEL(BenchTeardownModel, "BenchTeardown_Model") +BRIDGE_REGISTER_ACTION(BenchTeardownModel, BenchTeardownPing, "BenchTeardown_Ping") + +namespace { + +constexpr std::size_t kSmall = 2000; +constexpr std::size_t kLarge = 32000; +constexpr int kSmallTrials = 7; +constexpr int kLargeTrials = 3; +constexpr double kDefaultMaxRatio = 7.0; + +// A serial executor the owning thread sleeps on. +class SleepingOwner : public ::morph::exec::IExecutor { +public: + void post(std::function task) override { + { + std::scoped_lock const lock{_mtx}; + _queue.push_back(std::move(task)); + } + _cv.notify_one(); + } + + template + void runUntil(Pred done) { + for (;;) { + std::function task; + { + std::unique_lock lock{_mtx}; + _cv.wait(lock, [this] { return !_queue.empty(); }); + task = std::move(_queue.front()); + _queue.pop_front(); + } + { + ::core::async::ExecutorScope const scope{coreExecutor()}; + if (task) { + task(); + } + } + if (done()) { + return; + } + } + } + +private: + std::mutex _mtx; + std::condition_variable _cv; + std::deque> _queue; +}; + +// Microseconds to destroy @p count live handlers on one bridge, per handler. +double destroyMicrosPerHandler(std::size_t count) { + ::morph::exec::ThreadPoolExecutor pool{2}; + SleepingOwner owner; + auto backend = std::make_unique<::morph::backend::LocalBackend>(pool); + ::morph::bridge::Bridge bridge{std::move(backend), owner}; + + std::vector>> handlers; + handlers.reserve(count); + for (std::size_t i = 0; i < count; ++i) { + handlers.push_back(std::make_unique<::morph::bridge::BridgeHandler>(bridge, &owner)); + } + // A call through the last handler settles only after every bind queued + // ahead of it on the owner has run. + int settled = 0; + handlers.back() + ->execute(BenchTeardownPing{.x = 1}) + .then([&settled](const BenchTeardownPong&) { ++settled; }) + .onError([&settled](const std::exception_ptr&) { ++settled; }); + owner.runUntil([&] { return settled >= 1; }); + + auto const begin = std::chrono::steady_clock::now(); + for (auto& handler : handlers) { + handler.reset(); + } + auto const end = std::chrono::steady_clock::now(); + return std::chrono::duration(end - begin).count() / static_cast(count); +} + +double bestOf(int trials, std::size_t count) { + double best = 0.0; + for (int i = 0; i < trials; ++i) { + double const micros = destroyMicrosPerHandler(count); + best = (i == 0) ? micros : std::min(best, micros); + } + return best; +} + +int run(double maxRatio) { + double const small = bestOf(kSmallTrials, kSmall); + double const large = bestOf(kLargeTrials, kLarge); + double const ratio = large / small; + std::cout << std::format("destroy, {:>6} live handlers : {:8.2f} us per handler (best of {})\n", kSmall, small, + kSmallTrials) + << std::format("destroy, {:>6} live handlers : {:8.2f} us per handler (best of {})\n", kLarge, large, + kLargeTrials) + << std::format("ratio large / small : {:.2f} (linear total cost = 1, quadratic = {:.0f})\n", + ratio, static_cast(kLarge) / static_cast(kSmall)); + if (maxRatio > 0.0) { + if (ratio > maxRatio) { + std::cout << std::format("FAIL: per-handler destroy cost grows {:.2f}x from {} to {} handlers, exceeds " + "--max-ratio={:.2f}\n", + ratio, kSmall, kLarge, maxRatio); + return 1; + } + std::cout << std::format("ok: ratio {:.2f} within --max-ratio={:.2f}\n", ratio, maxRatio); + } + return 0; +} + +} // namespace + +int main(int argc, char** argv) { + try { + double maxRatio = 0.0; + std::span const args{argv, static_cast(argc)}; + for (std::size_t i = 1; i < args.size(); ++i) { + std::string_view const arg{args[i]}; + if (arg.starts_with("--max-ratio=")) { + maxRatio = std::stod(std::string{arg.substr(std::string_view{"--max-ratio="}.size())}); + } else { + std::cout << std::format("usage: morph_bench_teardown [--max-ratio=]\n", + kDefaultMaxRatio); + return 2; + } + } + return run(maxRatio); + } catch (const std::exception& exc) { + std::cout << "FAIL: " << exc.what() << "\n"; + return 1; + } catch (...) { + std::cout << "FAIL: unknown exception\n"; + return 1; + } +} From c5adbd3bf647c3a056906ce1b391dc31c6b57fa8 Mon Sep 17 00:00:00 2001 From: Yaraslau Tamashevich Date: Fri, 27 Nov 2026 07:47:02 +0100 Subject: [PATCH 04/11] test(bench): report ModelStrands throughput as threads are added morph_bench_scaling posts empty, ~1 us and ~5 us tasks over 1024 keys with 1, 2, 4 and 8 producers and workers, to ModelStrands and to the bare pool, and prints rate and efficiency against the one-thread rate. It is a measurement with no ctest case, since wall-clock scaling is machine-dependent; it exits non-zero only when a task is lost, doubled or late. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT --- docs/spec/testing_strategy.md | 23 ++++ tests/bench/CMakeLists.txt | 19 +++ tests/bench/bench_model_scaling.cpp | 175 ++++++++++++++++++++++++++++ 3 files changed, 217 insertions(+) create mode 100644 tests/bench/bench_model_scaling.cpp diff --git a/docs/spec/testing_strategy.md b/docs/spec/testing_strategy.md index 0bf9c86a7..4ec4262a8 100644 --- a/docs/spec/testing_strategy.md +++ b/docs/spec/testing_strategy.md @@ -483,6 +483,29 @@ longer fit in cache. With the scan, it is 9.5–12.6 in Release and about 20 in Debug. The case therefore fails while `Bridge::deregisterHandler` scans every live handler, and passes once it does not. +### Multi-model scaling (`bench_model_scaling.cpp`, target `morph_bench_scaling`) + +Throughput of `ModelStrands::post` over a `ThreadPoolExecutor`, with T producer +threads posting round-robin to 1024 keys and T workers, for T in 1, 2, 4 and 8 +and three task bodies: empty, about 1 µs and about 5 µs of spinning on +`steady_clock`. The bare pool runs the same bodies, so the strand layer's cost +can be told from the pool's. It prints, per T, the rate in tasks per second and +the efficiency against T times the one-thread rate: + +``` +./build/tests/bench/morph_bench_scaling +``` + +**It is a measurement, not a gate, and has no ctest case.** Wall-clock scaling +depends on the core count, the scheduler and whatever else shares the machine, +so no ceiling holds from one runner to the next, and a ceiling loose enough to +hold would catch nothing. It exits non-zero only on a gross fault, which is +machine-independent: every posted task must complete exactly once, counted, and +within two minutes. Empty bodies measure contention on the pool's queue and the +strand's bookkeeping, not parallel work, so their rate falling as threads are +added is expected; the 1 µs and 5 µs rows show how much work per task the +strand layer needs before threads pay. + ## Concurrent-user benchmark (`scripts/scenario/bench_bookmarks.py`) `morph_bench` measures one dispatch inside one process. This benchmark measures diff --git a/tests/bench/CMakeLists.txt b/tests/bench/CMakeLists.txt index ba9d9863e..f873222e4 100644 --- a/tests/bench/CMakeLists.txt +++ b/tests/bench/CMakeLists.txt @@ -234,3 +234,22 @@ if(NOT MORPH_TEARDOWN_MAX_RATIO EQUAL 0) COMMAND morph_bench_teardown "--max-ratio=${MORPH_TEARDOWN_MAX_RATIO}") set_tests_properties(bench.teardown_scaling PROPERTIES TIMEOUT 300 LABELS "bench") endif() + +# ── Multi-model scaling (report only) ──────────────────────────────────────── +# +# `ModelStrands::post` throughput over 1, 2, 4 and 8 threads and 1024 keys, +# against the bare pool, for empty, ~1 us and ~5 us task bodies. Deliberately +# NOT a budget and not a ctest case: wall-clock scaling depends on the core +# count, the scheduler and whatever else shares the machine, so no ceiling +# would hold from one runner to the next, and a ceiling loose enough to hold +# would catch nothing. Run it by hand and read the table: +# ./build/tests/bench/morph_bench_scaling +# It exits non-zero on a gross fault (a task lost or run twice), which is +# machine-independent. +add_executable(morph_bench_scaling bench_model_scaling.cpp) +target_link_libraries(morph_bench_scaling PRIVATE morph::morph) +morph_suppress_test_dialogs(morph_bench_scaling) +apply_warnings(morph_bench_scaling) +if(DEFINED AF_SANITIZER) + apply_sanitizers(morph_bench_scaling ${AF_SANITIZER}) +endif() diff --git a/tests/bench/bench_model_scaling.cpp b/tests/bench/bench_model_scaling.cpp new file mode 100644 index 000000000..5ceff1217 --- /dev/null +++ b/tests/bench/bench_model_scaling.cpp @@ -0,0 +1,175 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Throughput of `ModelStrands::post` over a thread pool, as threads are added. +// +// Per-model work is serial and work for different models runs in parallel, so +// with many models and a few threads the strand layer should add capacity +// close to linearly. This measures how close, for three task bodies: +// empty (the strand's own overhead is all there is), about 1 us and about 5 us +// of spinning. The bare pool runs the same bodies for comparison, so the cost +// of the strand layer can be told apart from the cost of the pool. +// +// For each thread count T, T producer threads post `total` tasks between them, +// spread round-robin over `kKeys` keys, to a pool of T workers. The rate is +// tasks completed per second from the first post to the last completion, and +// the efficiency is that rate over `T` times the one-thread rate. +// +// **This is a measurement, not a gate**: wall-clock scaling depends on the core +// count, the scheduler and what else is running, so no ceiling holds across +// machines. It fails only on a gross fault -- a lost or doubled task, counted +// exactly -- or when tasks do not complete within `kTimeout`. +// +// Build: `-DMORPH_BUILD_LOAD_TESTS=ON`, target `morph_bench_scaling`. +// See docs/spec/testing_strategy.md. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr std::uint64_t kKeys = 1024; +constexpr std::array kThreadCounts{1, 2, 4, 8}; +constexpr std::chrono::seconds kTimeout{120}; + +struct Body { + const char* name; + std::chrono::nanoseconds spin; + std::size_t total; +}; + +constexpr std::array kBodies{{ + {.name = "empty", .spin = std::chrono::nanoseconds{0}, .total = 2'000'000}, + {.name = "~1 us", .spin = std::chrono::nanoseconds{1000}, .total = 400'000}, + {.name = "~5 us", .spin = std::chrono::nanoseconds{5000}, .total = 100'000}, +}}; + +void spinFor(std::chrono::nanoseconds spin) { + if (spin.count() == 0) { + return; + } + auto const deadline = std::chrono::steady_clock::now() + spin; + while (std::chrono::steady_clock::now() < deadline) { + } +} + +struct Result { + double rate = 0.0; // tasks per second + bool exact = true; // every task ran exactly once, in time +}; + +// Posts `body.total` tasks from `threads` producers via @p post(key, task) and +// waits for them all. +template +Result measure(std::size_t threads, Body const& body, PostFn&& post) { + std::atomic done{0}; + std::atomic ready{0}; + std::atomic go{false}; + std::vector producers; + std::size_t const perProducer = body.total / threads; + std::size_t const expected = perProducer * threads; + for (std::size_t p = 0; p < threads; ++p) { + producers.emplace_back([&, p] { + ready.fetch_add(1); + while (!go.load()) { + std::this_thread::yield(); + } + for (std::size_t i = 0; i < perProducer; ++i) { + std::uint64_t const key = ((p * perProducer + i) % kKeys) + 1; + post(key, [&done, spin = body.spin] { + spinFor(spin); + done.fetch_add(1, std::memory_order_relaxed); + }); + } + }); + } + while (ready.load() < threads) { + std::this_thread::yield(); + } + auto const begin = std::chrono::steady_clock::now(); + go.store(true); + for (auto& producer : producers) { + producer.join(); + } + while (done.load() < expected && std::chrono::steady_clock::now() - begin < kTimeout) { + std::this_thread::sleep_for(std::chrono::microseconds{200}); + } + auto const end = std::chrono::steady_clock::now(); + Result result; + result.exact = done.load() == expected; + // A doubled task would push the count past `expected` by the time of this + // read at the latest; a short settle makes that visible. + std::this_thread::sleep_for(std::chrono::milliseconds{20}); + result.exact = result.exact && done.load() == expected; + result.rate = static_cast(expected) / std::chrono::duration(end - begin).count(); + return result; +} + +Result measureStrands(std::size_t threads, Body const& body) { + ::morph::exec::ThreadPoolExecutor pool{threads}; + ::morph::exec::detail::ModelStrands strands{pool}; + auto result = measure(threads, body, [&strands](std::uint64_t key, auto task) { + strands.post(::morph::exec::detail::ModelId{key}, std::move(task)); + }); + strands.drain(); + return result; +} + +Result measurePool(std::size_t threads, Body const& body) { + ::morph::exec::ThreadPoolExecutor pool{threads}; + return measure(threads, body, [&pool](std::uint64_t /*key*/, auto task) { pool.post(std::move(task)); }); +} + +int run() { + bool ok = true; + std::cout << std::format("{} producer threads and {} workers per row; {} keys\n", "T", "T", kKeys); + for (auto const& body : kBodies) { + std::cout << std::format("\ntask body {} ({} tasks)\n", body.name, body.total) + << " T strands tasks/s eff bare pool tasks/s eff\n"; + double strandBase = 0.0; + double poolBase = 0.0; + for (std::size_t const threads : kThreadCounts) { + auto const strand = measureStrands(threads, body); + auto const bare = measurePool(threads, body); + if (threads == 1) { + strandBase = strand.rate; + poolBase = bare.rate; + } + double const width = static_cast(threads); + std::cout << std::format(" {} {:>14.0f} {:5.1f}% {:>14.0f} {:5.1f}%\n", threads, strand.rate, + 100.0 * strand.rate / (width * strandBase), bare.rate, + 100.0 * bare.rate / (width * poolBase)); + if (!strand.exact || !bare.exact) { + std::cout << std::format("FAIL: T={} body {}: a task was lost, doubled or late (strands {}, pool {})\n", + threads, body.name, strand.exact ? "exact" : "WRONG", + bare.exact ? "exact" : "WRONG"); + ok = false; + } + } + } + return ok ? 0 : 1; +} + +} // namespace + +int main() { + try { + return run(); + } catch (const std::exception& exc) { + std::cout << "FAIL: " << exc.what() << "\n"; + return 1; + } catch (...) { + std::cout << "FAIL: unknown exception\n"; + return 1; + } +} From 45ab4a40bfa29b446ca22ff2069377d478189394 Mon Sep 17 00:00:00 2001 From: Yaraslau Tamashevich Date: Fri, 27 Nov 2026 08:22:08 +0100 Subject: [PATCH 05/11] perf(exec): ThreadPoolExecutor spins briefly before sleeping A worker that finds the queue empty spins on an atomic queue counter for up to `PoolOptions::spinBeforeSleep` (25 us by default) before it takes the lock and sleeps. A task posted during the spin is taken with no system call on either side. At most `maxSpinners` workers (default 1) spin at once; the rest sleep immediately. `post()` notifies a sleeper only when one exists and more tasks are queued than workers are spinning. The sleeping and spinning counts change under the pool's mutex, and a worker leaving its spin re-tests the queue under that mutex before it waits, so a task posted in the gap is never missed. A worker that takes a task applies the same rule to what remains. `spinBeforeSleep = 0` restores sleeping at once. The spin is bounded by elapsed time and uses a CPU relax hint (`_mm_pause`, `__yield`, `yield`, or nothing) rather than a system call. Measured with a tiny model on an 8-worker pool (loaded 12-core machine): 64 calls in flight went from about 62k to about 205k calls/s, and CPU per call from 16.5 us to 4.4 us; the owner thread's kernel share fell from 69% to 29%. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT --- docs/spec/core/executor.md | 120 +++++++++++++++++++-- include/morph/core/executor.hpp | 150 ++++++++++++++++++++++++-- tests/test_executor.cpp | 183 ++++++++++++++++++++++++++++++++ 3 files changed, 435 insertions(+), 18 deletions(-) diff --git a/docs/spec/core/executor.md b/docs/spec/core/executor.md index 2de110b93..5e1d30038 100644 --- a/docs/spec/core/executor.md +++ b/docs/spec/core/executor.md @@ -11,6 +11,7 @@ threading, and serialisation semantics differ per implementation. - [Type overview](#type-overview) - [`IExecutor` — the abstract interface](#iexecutor--the-abstract-interface) - [`ThreadPoolExecutor`](#threadpoolexecutor) + - [Spin before sleep](#spin-before-sleep) - [`MainThreadExecutor`](#mainthreadexecutor) - [`QtExecutor`](#qtexecutor) - [Strands: `ModelStrands` and `ModelId`](#strands-modelstrands-and-modelid) @@ -37,7 +38,7 @@ across `morph::exec` and `morph::exec::detail` (in `executor.hpp`, `strand.hpp`, | Type | Namespace | Purpose | |---|---|---| | `IExecutor` | `morph::exec` | Abstract base: a single pure-virtual `post(task)`, and `coreExecutor()`, the executor's stable core-cpp identity. | -| `ThreadPoolExecutor` | `morph::exec` | Fixed-size thread pool, FIFO queue, task exceptions logged (never propagate). | +| `ThreadPoolExecutor` | `morph::exec` | Fixed-size thread pool, FIFO queue, idle workers spin briefly before sleeping (`PoolOptions`), task exceptions logged (never propagate). | | `MainThreadExecutor` | `morph::exec` | Collects tasks from any thread, drains on `runFor()` from the owning thread. | | `QtExecutor` | `morph::qt` | Posts tasks to a Qt event loop; they run on the configured context object's thread (the `QCoreApplication`/GUI thread by default). | | `InlineExecutor` | `morph::exec::detail` (in `executor.hpp`) | Runs each task at once on the posting thread; reached through `detail::inlineExecutor()`. Not serial, so never a `Completion`'s owner. | @@ -88,8 +89,9 @@ must be serial: a `Completion` refuses any other (see ## `ThreadPoolExecutor` A fixed-size thread pool. The constructor spawns `n` worker threads; each worker -loops, waiting for tasks on a shared condition variable. Tasks are dispatched in -FIFO order from a single mutex-protected queue. +loops, taking tasks from one mutex-protected FIFO queue. A worker that finds the +queue empty spins briefly before it sleeps on a shared condition variable (see +[Spin before sleep](#spin-before-sleep)). `n` is **clamped to a minimum of 1**. A pool with zero workers would accept posted tasks that no thread could ever run, so every `post()` would hang forever @@ -109,6 +111,103 @@ exit and may be silently lost. Exceptions from tasks are caught in the worker propagate out of a worker, so one failing task neither kills its thread nor aborts sibling tasks. +### Spin before sleep + +Waking a sleeping worker costs a system call on the poster's side (a futex wake +on Linux) and a scheduler round trip on the worker's. For a task that is cheap +to run, that is most of its cost, and an owner thread that posts to a pool of +sleeping workers spends a large share of its time in the wake call. + +`PoolOptions` (the constructor's second argument) lets idle workers wait without +sleeping: + +| Option | Default | Meaning | +|---|---|---| +| `spinBeforeSleep` | 25 us | How long one worker spins on an atomic queue counter after the queue empties, before it takes the lock and sleeps. `0` disables spinning: a worker sleeps the moment it finds nothing to do. | +| `maxSpinners` | 1 | How many workers may spin at once; the rest sleep at once. `0` also disables spinning. | +| `afterSpin` | empty | Test seam, called on a worker after its spin ends and before it takes the lock. | + +The rules that keep the pool correct: + +- **Counts change under the lock.** `_sleeping` (workers waiting on the condition + variable) and `_spinning` (workers between their decision to spin and the + moment they retake the lock) are read and written only with `_m` held. The + spin loop itself reads two atomics only: `_queued`, a mirror of the queue size + written under `_m`, and `_stop`. +- **`post()` notifies when `_sleeping > 0` and more tasks are queued than workers + are spinning** (`queue size > _spinning`). A single spinner is expected to + take one queued task by itself; a second queued task, or a task queued while + nobody spins, wakes a sleeper. Posting a burst of blocking tasks therefore + still runs them side by side. +- **A worker that takes a task applies the same rule** to what remains in the + queue: if it was the spinner, the tasks left behind have no spinner to take + them. +- **No lost wakeup.** A worker leaving its spin retakes `_m` and tests the queue + before it waits. A task posted after the spin ended but before the lock was + retaken saw the worker as spinning and did not notify; the re-test under the + lock is what finds it. `afterSpin` exists so a test can hold a worker exactly + in that window. +- **`_sleeping` is decremented by the woken worker**, after it wakes, so a + spurious wakeup neither skews the count nor lets two notifies go to the same + worker unaccounted. +- **Stop.** The destructor sets `_stop` under `_m` and notifies all. A spinner + sees the flag within one check, so the join waits at most one spin period past + the drain. + +A worker therefore burns at most `spinBeforeSleep` of CPU after each task that +leaves the queue empty, and none while the pool is idle for longer than that. +At most `maxSpinners` workers do it at the same time, so a pool of 64 workers +costs one spinning core. + +The spin is bounded by elapsed time (`steady_clock`), never by a count of +iterations, because a CPU relax hint costs about 10 cycles on some CPUs and 140 +on others. The hint is `detail::cpuRelax()`: `_mm_pause` on x86 and x64, +`__yield` on ARM64 under MSVC and clang-cl, `yield` on ARM64 under GCC and clang, +nothing elsewhere. It is deliberately not `std::this_thread::yield()`, which is +a system call. + +#### Choosing the default + +The default of 25 us comes from a sweep of `spinBeforeSleep` over {0, 10, 25, 50, +100} us with a pool of 8 workers on a 12-core x86-64 Linux machine (GCC 16, +`-O2`), driving `LocalBackend` with a tiny model from a sleeping owner thread. +The machine was loaded by other builds (load average about 19) and the runs are +2 s each, so wall-clock figures carry large noise; the instruction and CPU-time +columns are stable. "Instructions" counts every user-space instruction of the +process, spin loops included, so it rises with the spin while CPU time falls. +The no-spin baseline is the pool before `PoolOptions` existed. + +| `spinBeforeSleep` | 1 in flight: calls/s | 1 in flight: CPU (user+sys) per call | 64 in flight: calls/s | 64 in flight: instructions per call | 64 in flight: CPU per call | 64 in flight, 16 workers: calls/s | two processes, 8 workers each: calls/s | +|---|---|---|---|---|---|---|---| +| before | 22.4k | 21.4 us | 62.5k | 7.45k | 16.5 us | not run | not run | +| 0 | 20.2k | 22.1 us | 50.4k | 7.60k | 16.9 us | 44.2k | 53.0k and 48.5k | +| 10 us | 53k to 73k | 13.2 us | 215k | 7.94k | 4.4 us | 202k | 228k and 233k | +| 25 us | 59k to 69k | 12.1 us | 203k to 211k | 8.02k | 4.4 us | 216k | 237k and 229k | +| 50 us | 60k to 76k | 10.9 us | 225k | 8.04k | 4.2 us | 202k | 226k and 206k | +| 100 us | 59k to 69k | 10.9 us | 224k | 8.20k | 4.3 us | 208k | 248k and 233k | + +Reading it: the whole gain arrives by 10 us and the differences between 10 and +100 us are inside the noise, so the choice is the cheapest value with margin +for a scheduler hiccup on the worker, and for the owner's turnaround between a +reply and its next call, which is a few microseconds to tens of microseconds. +That is 25 us. The oversubscribed rows (16 workers, and two processes on 12 +cores) stay on the same plateau because at most one worker per pool spins, so +two pools cost two spinning cores and not one per worker. + +Owner-thread view from `perf record` (64 in flight, 8 workers): the share of +the owner thread's own samples spent in the kernel falls from 69% (30.2 of 43.7 +points of all samples) to 29% (12.4 of 42.2). What remains is the owner sleeping +until a reply arrives, which belongs to the owner's executor, not to this pool. + +What a spin costs when nothing arrives soon: one worker burns up to +`spinBeforeSleep` of CPU after each task that leaves the queue empty. A caller +that posts rarely and cares about power sets `spinBeforeSleep` to zero. + +Windows has not been measured. A condition-variable wake there costs at least +as much as a futex wake on Linux, so the spin is expected to help, but the +default is chosen from the Linux numbers. + + ## `MainThreadExecutor` A single-thread executor that does **not** spawn its own thread. Tasks posted @@ -349,10 +448,12 @@ ever seen. Retired strands kept for reuse are bounded at 32. Every executor's `post()` is safe to call from any thread concurrently. -- `ThreadPoolExecutor` guards its queue and `_stop` flag with a single mutex - `_m` and coordinates workers on `_cv`. Multiple workers pop under the lock, so - the FIFO order is a total order across producers; task *execution* is - concurrent across the `n` workers. +- `ThreadPoolExecutor` guards its queue, `_stop` flag and its sleeping and + spinning counts with a single mutex `_m` and coordinates sleeping workers on + `_cv`. A spinning worker reads only two atomics (`_queued`, `_stop`), both + written under `_m`. Multiple workers pop under the lock, so the FIFO order is a + total order across producers; task *execution* is concurrent across the `n` + workers. See [Spin before sleep](#spin-before-sleep). - `MainThreadExecutor` guards its queue with `_m`. `post()` may be called from any thread, but `runFor()` must be called only from the single owning ("main") thread; concurrent `runFor()` calls are not supported. @@ -653,10 +754,11 @@ and `IoLoop::post` catch `(...)` and so contain every exception type. | Member | Signature | Notes | |---|---|---| -| ctor | `explicit ThreadPoolExecutor(std::size_t n)` | Spawns `max(n, 1)` worker threads. `n == 0` is clamped to 1 (a zero-worker pool would hang every task). | +| ctor | `explicit ThreadPoolExecutor(std::size_t n, PoolOptions options = {})` | Spawns `max(n, 1)` worker threads. `n == 0` is clamped to 1 (a zero-worker pool would hang every task). `options` sets how idle workers wait (see [Spin before sleep](#spin-before-sleep)). | | dtor | `~ThreadPoolExecutor() override` | Signals stop, then joins all workers, which drain the queue (run every already-queued task) before exiting. Tasks posted concurrently with or after destruction may be lost. | -| `post` | `void post(std::function task) override` | Enqueues to FIFO; notifies one worker. Thread-safe. Each task runs inside a scope naming this pool; exceptions are caught and logged in the worker loop. | +| `post` | `void post(std::function task) override` | Enqueues to FIFO; notifies one worker only when one is asleep and more tasks are queued than workers are spinning. Thread-safe. Each task runs inside a scope naming this pool; exceptions are caught and logged in the worker loop. | | `isSerial` | `bool isSerial() const noexcept override` | `false`: the workers run tasks at once. | +| `sleepingWorkers` | `std::size_t sleepingWorkers() const` | Workers asleep on the condition variable, a notified one included until it runs. For tests. | ### `MainThreadExecutor : IExecutor` diff --git a/include/morph/core/executor.hpp b/include/morph/core/executor.hpp index fc2b344ce..0ee9dda1f 100644 --- a/include/morph/core/executor.hpp +++ b/include/morph/core/executor.hpp @@ -1,12 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 #pragma once +#include #include #include #include #include #include #include +#include #include #include #include @@ -16,6 +18,12 @@ #include #include +#if defined(_M_X64) || defined(_M_IX86) || defined(__x86_64__) || defined(__i386__) +#include +#elif defined(_M_ARM64) +#include +#endif + #include "../attributes.hpp" #include "logger.hpp" #include "profiler.hpp" @@ -26,6 +34,25 @@ struct IExecutor; namespace detail { +/// @brief Tells the CPU the calling thread is in a spin-wait loop. +/// +/// A relax hint, not `std::this_thread::yield()`: the hint stays in user space, +/// and avoiding the system call is the reason to spin at all. It lowers the +/// loop's power draw and, on a core shared by two hardware threads, hands the +/// sibling the pipeline. Architectures without a known hint make this a no-op; +/// the loops that call it are bounded by elapsed time, not by a count of calls, +/// so the hint's cost (about 10 cycles on some CPUs, 140 on others) changes how +/// often the clock is read and not how long the loop runs. +inline void cpuRelax() noexcept { +#if defined(_M_X64) || defined(_M_IX86) || defined(__x86_64__) || defined(__i386__) + _mm_pause(); +#elif defined(_M_ARM64) + __yield(); +#elif defined(__aarch64__) + asm volatile("yield" ::: "memory"); +#endif +} + /// @brief A `core::async::IExecutor` over a morph executor: how a core-cpp /// strand's pump, and an `ExecutorScope`, reach a thread pool, a /// main-thread pump or Qt. @@ -150,12 +177,41 @@ inline void detail::CoreExecutorOver::submit(::core::async::ParkedWork work) { [&executor](::core::async::ExecutorScope const& scope) { return &scope.executor() == &executor; }); } +/// @brief How a `ThreadPoolExecutor`'s idle workers wait for work. +/// +/// A worker whose queue is empty may spin on an atomic for a short time before +/// it sleeps on the condition variable. A task posted during the spin is taken +/// with no system call on either side: the poster does not notify, and the +/// worker never slept. +struct PoolOptions { + /// How long one worker spins after the queue empties, before it sleeps. + /// Zero disables spinning: a worker sleeps the moment it finds nothing to + /// do, which is the right choice for a battery-sensitive application. A + /// worker burns at most this much CPU after each task that leaves the queue + /// empty, and none while the pool is idle. + std::chrono::microseconds spinBeforeSleep{25}; + + /// How many workers may spin at once. The others sleep at once, so a pool + /// of many workers costs one spinning core, not all of them. Zero also + /// disables spinning. + std::size_t maxSpinners = 1; + + /// Test seam: called on a worker after its spin ends and before it takes + /// the pool's lock, the window in which a `post()` sees that worker as + /// spinning and does not notify. Leave empty outside tests. + std::function afterSpin; +}; + /// @brief Multi-threaded executor backed by a fixed-size thread pool. /// /// Tasks are placed in a FIFO queue and consumed by worker threads. /// Exceptions thrown by tasks are caught and logged via `morph::log` (they do /// not propagate out of the worker or abort sibling tasks). /// The destructor blocks until all worker threads have exited. +/// +/// An idle worker spins briefly before it sleeps (see `PoolOptions`), and +/// `post()` wakes a sleeping worker only when no spinning worker will take the +/// task. // NOLINTNEXTLINE(cppcoreguidelines-special-member-functions) class ThreadPoolExecutor : public IExecutor { public: @@ -166,7 +222,8 @@ class ThreadPoolExecutor : public IExecutor { /// `ThreadPoolExecutor(0)` yields a usable single-worker pool rather than a /// silently dead one. /// @param n Number of threads to spawn. Values below 1 are clamped to 1. - explicit ThreadPoolExecutor(std::size_t n) { + /// @param options How idle workers wait; see `PoolOptions`. + explicit ThreadPoolExecutor(std::size_t n, PoolOptions options = {}) : _options{std::move(options)} { std::size_t const workers = n == 0 ? 1 : n; for (std::size_t i = 0; i < workers; ++i) { _workers.emplace_back([this] { loop(); }); @@ -178,8 +235,10 @@ class ThreadPoolExecutor : public IExecutor { /// Workers drain the queue before exiting: after `_stop` is set they keep /// popping and running already-queued tasks and only return once the queue is /// empty, so the join blocks until every task queued before destruction has - /// run. Tasks `post()`ed concurrently with or after destruction race this and - /// may be silently lost. + /// run. A spinning worker sees the stop flag within one spin check, so the + /// join waits at most one spin period beyond the drain. Tasks `post()`ed + /// concurrently with or after destruction race this and may be silently + /// lost. ~ThreadPoolExecutor() override { { // notify_all() while still holding _m, not after releasing it: a @@ -190,7 +249,7 @@ class ThreadPoolExecutor : public IExecutor { // internal state (this pattern is what post()'s own notify_one(), // below, must avoid too, for the same reason). std::scoped_lock const lock{_m}; - _stop = true; + _stop.store(true, std::memory_order_release); _cv.notify_all(); } for (auto& worker : _workers) { @@ -199,30 +258,95 @@ class ThreadPoolExecutor : public IExecutor { } /// @brief Enqueues @p task for execution on one of the pool threads. + /// + /// Notifies a worker only when one is asleep and more tasks are queued than + /// there are spinning workers to take them. /// @param task Callable to execute. Thread-safe. void post(std::function task) override { std::scoped_lock const lock{_m}; _q.push(std::move(task)); - _cv.notify_one(); + _queued.store(_q.size(), std::memory_order_release); + wakeIfUncovered(); } /// @brief Not serial: the workers run tasks at once. /// @return `false`. [[nodiscard]] bool isSerial() const noexcept override { return false; } + /// @brief How many workers are asleep on the condition variable. + /// + /// A worker counts from just before it waits until it has woken, so a worker + /// that was notified and has not yet run still counts. Meant for tests. + /// @return The number of sleeping workers at the moment of the call. + [[nodiscard]] std::size_t sleepingWorkers() const { + std::scoped_lock const lock{_m}; + return _sleeping; + } + private: + // Wakes one sleeper when more tasks are queued than spinning workers will + // take. Called with `_m` held, as the notify must be (see the destructor). + void wakeIfUncovered() { + if (_sleeping > 0 && _q.size() > _spinning) { + _cv.notify_one(); + } + } + + // Spins until work or stop appears, or `spinBeforeSleep` has elapsed. Reads + // atomics only: the lock is not held and is not taken. + void spin() const { + auto const deadline = std::chrono::steady_clock::now() + _options.spinBeforeSleep; + do { + for (int i = 0; i < 16; ++i) { + if (_queued.load(std::memory_order_acquire) != 0 || _stop.load(std::memory_order_acquire)) { + return; + } + detail::cpuRelax(); + } + } while (std::chrono::steady_clock::now() < deadline); + } + + // Blocks until a task can be taken or the pool is stopping and drained. + // Returns false when the worker should exit. Called with `lock` held on + // `_m`; returns with it held. + bool awaitTask(std::unique_lock& lock) { + if (_q.empty() && !_stop.load(std::memory_order_relaxed) && _spinning < _options.maxSpinners && + _options.spinBeforeSleep.count() > 0) { + ++_spinning; + lock.unlock(); + spin(); + if (_options.afterSpin) { + _options.afterSpin(); + } + lock.lock(); + --_spinning; + } + // The queue is read again under the lock: a task posted after the spin + // ended saw this worker as spinning and did not notify, so only this + // check keeps it from sleeping past that task. + if (_q.empty() && !_stop.load(std::memory_order_relaxed)) { + ++_sleeping; + _cv.wait(lock, [this] { return _stop.load(std::memory_order_relaxed) || !_q.empty(); }); + --_sleeping; + } + return !_q.empty(); + } + void loop() { MORPH_THREAD_NAME("morph.pool"); for (;;) { std::function task; { std::unique_lock lock{_m}; - _cv.wait(lock, [this] { return _stop || !_q.empty(); }); - if (_stop && _q.empty()) { + if (!awaitTask(lock)) { return; } task = std::move(_q.front()); _q.pop(); + _queued.store(_q.size(), std::memory_order_release); + // Tasks left behind a worker that was itself the spinner have + // nobody spinning to take them. + wakeIfUncovered(); } try { // Stated per task, not once per worker: the scope ends with the @@ -239,11 +363,19 @@ class ThreadPoolExecutor : public IExecutor { } } } - std::mutex _m; + + PoolOptions _options; + mutable std::mutex _m; std::condition_variable _cv; std::queue> _q; std::vector _workers; - bool _stop = false; + // Written only under `_m`; read without it by a spinning worker, which is + // why they are atomic. `_queued` mirrors `_q.size()`. + std::atomic _stop{false}; + std::atomic _queued{0}; + // Under `_m` only. + std::size_t _sleeping = 0; + std::size_t _spinning = 0; }; /// @brief Single-thread executor intended for use on the calling (main) thread. diff --git a/tests/test_executor.cpp b/tests/test_executor.cpp index 638b2bf1b..1ca82d513 100644 --- a/tests/test_executor.cpp +++ b/tests/test_executor.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -26,6 +27,188 @@ TEST_CASE("morph::exec::ThreadPoolExecutor swallows exceptions from tasks", "[ex REQUIRE(reached.load()); } +namespace { + +using namespace std::chrono_literals; + +// Polls @p pred until it holds or @p timeout passes; true when it held. +bool waitFor(std::function const& pred, std::chrono::milliseconds timeout = 5000ms) { + auto const deadline = std::chrono::steady_clock::now() + timeout; + while (!pred()) { + if (std::chrono::steady_clock::now() >= deadline) { + return false; + } + std::this_thread::sleep_for(50us); + } + return true; +} + +} // namespace + +TEST_CASE("morph::exec::ThreadPoolExecutor loses no task to a post racing a worker going to sleep", + "[executor][pool-spin]") { + // Bursts separated by pauses longer than the spin, so each burst meets + // workers that are asleep, spinning, or in between. + morph::exec::PoolOptions options; + options.spinBeforeSleep = 100us; + morph::exec::ThreadPoolExecutor pool{4, options}; + std::atomic ran{0}; + int posted = 0; + for (int burst = 0; burst < 300; ++burst) { + int const n = 1 + (burst % 3); + for (int i = 0; i < n; ++i) { + pool.post([&] { ran.fetch_add(1); }); + ++posted; + } + REQUIRE(waitFor([&] { return ran.load() == posted; })); + std::this_thread::sleep_for(std::chrono::microseconds{20 + (burst % 7) * 40}); + } +} + +TEST_CASE("morph::exec::ThreadPoolExecutor runs a task posted between the end of a spin and the lock", + "[executor][pool-spin]") { + std::atomic armed{true}; + std::atomic inGap{false}; + std::atomic release{false}; + morph::exec::PoolOptions options; + options.spinBeforeSleep = 100us; + options.afterSpin = [&] { + if (armed.exchange(false)) { + inGap.store(true); + waitFor([&] { return release.load(); }); + } + }; + std::atomic ran{false}; + { + morph::exec::ThreadPoolExecutor pool{1, options}; + // The single worker is now parked between its spin and the lock, counted + // as spinning, so the post below does not notify anyone. + REQUIRE(waitFor([&] { return inGap.load(); })); + pool.post([&] { ran.store(true); }); + release.store(true); + REQUIRE(waitFor([&] { return ran.load(); }, 2000ms)); + } +} + +TEST_CASE("morph::exec::ThreadPoolExecutor wakes a sleeper for the second queued task while one worker spins", + "[executor][pool-spin]") { + std::atomic armed{true}; + std::atomic inGap{false}; + std::atomic release{false}; + morph::exec::PoolOptions options; + options.spinBeforeSleep = 100us; + options.afterSpin = [&] { + if (armed.exchange(false)) { + inGap.store(true); + waitFor([&] { return release.load(); }); + } + }; + std::atomic ran{0}; + { + morph::exec::ThreadPoolExecutor pool{2, options}; + // One worker is held while counted as spinning; the other is asleep. + REQUIRE(waitFor([&] { return inGap.load() && pool.sleepingWorkers() == 1; })); + pool.post([&] { ran.fetch_add(1); }); + pool.post([&] { ran.fetch_add(1); }); + // The spinner is still held, so only the sleeper can have run them: the + // second post had to wake it. + REQUIRE(waitFor([&] { return ran.load() == 2; }, 2000ms)); + release.store(true); + } +} + +TEST_CASE("morph::exec::ThreadPoolExecutor with a spin runs blocking tasks posted together at once", + "[executor][pool-spin]") { + morph::exec::PoolOptions options; + options.spinBeforeSleep = 20000us; + morph::exec::ThreadPoolExecutor pool{2, options}; + for (int round = 0; round < 10; ++round) { + // One worker spins and the other sleeps. + REQUIRE(waitFor([&] { return pool.sleepingWorkers() == 1; })); + std::atomic arrived{0}; + std::atomic met{0}; + auto const task = [&] { + arrived.fetch_add(1); + if (waitFor([&] { return arrived.load() == 2; }, 2000ms)) { + met.fetch_add(1); + } + }; + pool.post(task); + pool.post(task); + REQUIRE(waitFor([&] { return met.load() == 2; }, 3000ms)); + // Let the pool settle before the next round. + REQUIRE(waitFor([&] { return pool.sleepingWorkers() >= 1; })); + } +} + +TEST_CASE("morph::exec::ThreadPoolExecutor with a zero spin sleeps at once and never spins", "[executor][pool-spin]") { + std::atomic spins{0}; + morph::exec::PoolOptions options; + options.spinBeforeSleep = 0us; + options.afterSpin = [&] { spins.fetch_add(1); }; + morph::exec::ThreadPoolExecutor pool{2, options}; + std::atomic ran{0}; + for (int i = 0; i < 20; ++i) { + pool.post([&] { ran.fetch_add(1); }); + } + REQUIRE(waitFor([&] { return ran.load() == 20; })); + REQUIRE(waitFor([&] { return pool.sleepingWorkers() == 2; })); + REQUIRE(spins.load() == 0); +} + +TEST_CASE("morph::exec::ThreadPoolExecutor with a spin spins after a task and then sleeps", "[executor][pool-spin]") { + std::atomic spins{0}; + morph::exec::PoolOptions options; + options.spinBeforeSleep = 200us; + options.afterSpin = [&] { spins.fetch_add(1); }; + morph::exec::ThreadPoolExecutor pool{2, options}; + std::atomic ran{false}; + pool.post([&] { ran.store(true); }); + REQUIRE(waitFor([&] { return ran.load(); })); + REQUIRE(waitFor([&] { return pool.sleepingWorkers() == 2; })); + REQUIRE(spins.load() > 0); +} + +TEST_CASE("morph::exec::ThreadPoolExecutor lets at most maxSpinners workers spin", "[executor][pool-spin]") { + std::atomic inSpinGap{0}; + std::atomic peak{0}; + std::atomic release{false}; + morph::exec::PoolOptions options; + options.spinBeforeSleep = 50us; + options.maxSpinners = 2; + options.afterSpin = [&] { + int const now = inSpinGap.fetch_add(1) + 1; + int seen = peak.load(); + while (now > seen && !peak.compare_exchange_weak(seen, now)) { + } + waitFor([&] { return release.load(); }); + inSpinGap.fetch_sub(1); + }; + { + morph::exec::ThreadPoolExecutor pool{4, options}; + REQUIRE(waitFor([&] { return pool.sleepingWorkers() == 2 && inSpinGap.load() == 2; })); + // Two are spinners parked in the hook; the other two went to sleep at once. + REQUIRE(peak.load() == 2); + release.store(true); + } +} + +TEST_CASE("morph::exec::ThreadPoolExecutor destructor runs every queued task and does not wait out a long spin", + "[executor][pool-spin]") { + std::atomic ran{0}; + auto const begin = std::chrono::steady_clock::now(); + { + morph::exec::PoolOptions options; + options.spinBeforeSleep = std::chrono::seconds{30}; + morph::exec::ThreadPoolExecutor pool{3, options}; + for (int i = 0; i < 200; ++i) { + pool.post([&] { ran.fetch_add(1); }); + } + } + REQUIRE(ran.load() == 200); + REQUIRE(std::chrono::steady_clock::now() - begin < std::chrono::seconds{5}); +} + TEST_CASE("morph::exec::MainThreadExecutor drains tasks via runFor", "[executor]") { morph::exec::MainThreadExecutor exec; std::atomic count{0}; From e982e4adabd73a72e0a370539d421c742a2207d6 Mon Sep 17 00:00:00 2001 From: Yaraslau Tamashevich Date: Fri, 27 Nov 2026 08:44:28 +0100 Subject: [PATCH 06/11] perf(backend): a local run copies one shared_ptr, and reads the clock only when timed An ordinary run no longer copies the strands pointer: only a Task run reaches the strands after its strand task returns. The cancel record and the in-flight counter live in one shared object, so a run holds one `shared_ptr` for both instead of two. `admitLocal` reads the clock only when a metric sink is installed at that moment; a call that starts with no sink emits no latency sample, and a dispatch with no sink costs no clock reads. Tracing is decided separately at `beginSpan`. Measured with SPIN_US=0 and no sinks (tiny model, 8 workers, instructions per call, three runs each): 7831 before, 7544 after with one call in flight; 7688 and 7708 before, 7347 and 7414 after with 64 in flight. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT --- docs/spec/core/backend.md | 10 ++-- docs/spec/core/observability.md | 6 +++ include/morph/core/backend.hpp | 86 ++++++++++++++++++++------------- tests/test_backend_extra.cpp | 30 ++++++++++++ 4 files changed, 95 insertions(+), 37 deletions(-) diff --git a/docs/spec/core/backend.md b/docs/spec/core/backend.md index f1355e570..827c47c31 100644 --- a/docs/spec/core/backend.md +++ b/docs/spec/core/backend.md @@ -486,7 +486,7 @@ handlers belong to the caller's owner (the bridge's, given through `setOwner`) and are touched only there, without a lock; each verb checks it in a debug build. Only the strand tasks the backend posts run elsewhere, and they reach nothing of the backend but what each carries — the holder, the call, and the -cancel record below. +shared run state below (the cancel record and the in-flight count). **Lifecycle:** - `bindModel` — overridden to keep the shared directory: register (private), @@ -502,8 +502,12 @@ cancel record below. - `executeInto` — looks up the holder; if `mid` is unknown it immediately settles the sink with `std::runtime_error("model not found: id=")`. Otherwise it tracks the sink in the pending list, counts the call in flight, - and posts the call to the model's strand (serialised per-model), where it - enters the instance's action gate, sets up a `ScopedContext` (from + and posts the call to the model's strand (serialised per-model). The call + carries one `shared_ptr` to the backend's shared run state (the cancel record + and the in-flight counter, one allocation with one owner), and a Task run + carries a second, to the strands its resumer and completion callback reach + after the strand task returns; an ordinary run copies no strands pointer. On + the strand the call enters the instance's action gate, sets up a `ScopedContext` (from `call.session`) and runs `localOp` (or starts `localOpAsync`'s Task). The strand side emits `executeLatencyMs`/`executeErrors`, the in-flight decrement and `beginSpan`/`endSpan` before settling the sink — see diff --git a/docs/spec/core/observability.md b/docs/spec/core/observability.md index 9dfc067f2..10b66e3f3 100644 --- a/docs/spec/core/observability.md +++ b/docs/spec/core/observability.md @@ -137,6 +137,12 @@ in-flight gauge's paired decrement, by contrast, is centralized so it fires exactly once regardless of which path (timeout or dispatch) resolves the call first. +`LocalBackend` reads the clock for `executeLatencyMs` only when a metric sink is +installed at the moment the call starts (`admitLocal`). A call that starts with +no sink emits no latency sample, even if a sink is installed before it finishes: +the start reading it would need was never taken. With no sink installed, a +dispatch costs no clock read. Tracing is decided separately, at `beginSpan`. + ## Thread safety Metrics and tracing each have their own mutex (`metricMtx`, `traceMtx`) guarding diff --git a/include/morph/core/backend.hpp b/include/morph/core/backend.hpp index b641fd427..5e5b342b7 100644 --- a/include/morph/core/backend.hpp +++ b/include/morph/core/backend.hpp @@ -1367,23 +1367,27 @@ class LocalBackend : public detail::IBackend { run.holder = std::move(holder); run.sink = std::move(sink); run.hydration = std::move(hydration); - run.strands = _strands; - run.cancels = _cancels; - run.admittedEpoch = admittedEpoch; - run.mid = mid; // Held by shared_ptr, never by raw `this`. A shared_ptr copy has its // own lifetime, independent of LocalBackend's, so it stays valid even // if the backend is torn down while this task is still queued or // running. `hydration` follows the same rule and may be null (a - // private instance has no entry). - run.inFlightCounter = _inFlight; - auto const inFlightAfterInc = run.inFlightCounter->fetch_add(1, std::memory_order_relaxed) + 1; + // private instance has no entry). One copy covers the cancel record and + // the in-flight counter, which share an owner. + run.shared = _shared; + run.admittedEpoch = admittedEpoch; + run.mid = mid; + auto const inFlightAfterInc = run.shared->inFlight.fetch_add(1, std::memory_order_relaxed) + 1; ::morph::observe::detail::emitMetric(::morph::observe::Metric::executeInFlight, static_cast(inFlightAfterInc)); // Through the instance's action gate: an action starts only once the one // before it has finished, which a Task handler does when its Task // completes rather than when the strand task that started it returns. if (run.localOpAsync != nullptr) { + // Only a Task run needs the strands: its resumer and completion + // callback reach them after the strand task that started it has + // returned. An ordinary run never touches them, so it does not + // copy the pointer. + run.strands = _strands; // A Task run is shared: its completion callback outlives the strand // task, and every Task run can be stopped, deadline or not -- the // destructor stops the ones still running. @@ -1425,7 +1429,7 @@ class LocalBackend : public detail::IBackend { _compactAt = kPendingCompactFloor; // With the swap: a run admitted before this point is in `snapshot` // and is failed below, and one admitted after it is not. - _cancels->record(exc); + _shared->record(exc); // Settle before stopping. A stopped Task handler resumes on its strand // and settles its own sink with `OperationCancelled`; requested first, // that settle can land before this one, and the caller would be @@ -1576,19 +1580,26 @@ class LocalBackend : public detail::IBackend { _compactAt = std::max(kPendingCompactFloor, _pending.size() * 2); } _pending.emplace_back(sink); - return _cancels->epoch(); + return _shared->epoch(); } - /// What `cancelPending` has done so far, shared with every run: how many - /// times it has run, and with what reason the last time. - /// - /// Written only by `cancelPending`, on the owner; read by runs on their - /// strands. Each reason is an immutable node published with a release - /// store before the epoch moves, so a run that sees the epoch move reads a - /// complete reason. Nodes live as long as the record: one per - /// `cancelPending`, which runs on a switch, a teardown or a disconnect. - class CancelRecord { + /// What every run of this backend shares, so a dispatch copies one + /// `shared_ptr` for all of it: what `cancelPending` has done so far (how + /// many times it has run, and with what reason the last time), and how many + /// executes are in flight. + /// + /// The cancel record is written only by `cancelPending`, on the owner, and + /// read by runs on their strands. Each reason is an immutable node + /// published with a release store before the epoch moves, so a run that + /// sees the epoch move reads a complete reason. Nodes live as long as this + /// object: one per `cancelPending`, which runs on a switch, a teardown or a + /// disconnect. + class RunShared { public: + /// Concurrent in-flight executes, for the `executeInFlight` metric: + /// incremented when a run is admitted, decremented when it finishes. + std::atomic inFlight{0}; + /// Publishes @p reason, then bumps the epoch. One writer: the owner. void record(const std::exception_ptr& reason) { auto node = std::make_unique(Node{.reason = reason, .previous = std::move(_chain)}); @@ -1631,12 +1642,15 @@ class LocalBackend : public detail::IBackend { std::shared_ptr<::morph::model::detail::IModelHolder> holder; std::shared_ptr<::morph::async::detail::ISettleSink> sink; std::shared_ptr hydration; - std::shared_ptr> inFlightCounter; + // Null for an ordinary run; set for a Task run only. std::shared_ptr<::morph::exec::detail::ModelStrands> strands; - std::shared_ptr cancels; + std::shared_ptr shared; std::uint64_t admittedEpoch = 0; ::morph::exec::detail::ModelId mid{}; + // Stamped by `admitLocal` only when a metric sink was installed then; + // `timed` says whether `start` holds a reading. std::chrono::steady_clock::time_point start; + bool timed = false; ::morph::observe::SpanId spanId{}; }; @@ -1644,9 +1658,15 @@ class LocalBackend : public detail::IBackend { /// settles it instead if `cancelPending` failed it while it waited there. /// @return Whether the handler is to run. static bool admitLocal(LocalRun& run) { - run.start = std::chrono::steady_clock::now(); + // The clock is read only for a latency sample, so only when something + // will receive it. A sink installed after this point gets no sample for + // this run. + run.timed = ::morph::observe::metricsEnabled(); + if (run.timed) { + run.start = std::chrono::steady_clock::now(); + } run.spanId = ::morph::observe::detail::beginSpan(run.session.requestId, run.modelTypeId, run.actionTypeId); - if (run.cancels->epoch() == run.admittedEpoch) { + if (run.shared->epoch() == run.admittedEpoch) { return true; } // `cancelPending` failed this call while it waited for the gate; @@ -1657,7 +1677,7 @@ class LocalBackend : public detail::IBackend { // dropped its `Completion` this run holds the last reference, so // the sink is gone by the time `cancelPending` would reach it. // Where `cancelPending` got there first, this settle is ignored. - finishLocal(run, nullptr, run.cancels->lastReason()); + finishLocal(run, nullptr, run.shared->lastReason()); return false; } @@ -1748,15 +1768,17 @@ class LocalBackend : public detail::IBackend { run.hydration->settle(succeeded); } ::morph::observe::detail::endSpan(run.spanId, succeeded); - auto const elapsedMs = - std::chrono::duration(std::chrono::steady_clock::now() - run.start).count(); std::array, 2> const tags{ {{"modelType", run.modelTypeId}, {"actionType", run.actionTypeId}}}; - ::morph::observe::detail::emitMetric(::morph::observe::Metric::executeLatencyMs, elapsedMs, tags); + if (run.timed) { + auto const elapsedMs = + std::chrono::duration(std::chrono::steady_clock::now() - run.start).count(); + ::morph::observe::detail::emitMetric(::morph::observe::Metric::executeLatencyMs, elapsedMs, tags); + } if (!succeeded) { ::morph::observe::detail::emitMetric(::morph::observe::Metric::executeErrors, 1.0, tags); } - auto const inFlightAfterDec = run.inFlightCounter->fetch_sub(1, std::memory_order_relaxed) - 1; + auto const inFlightAfterDec = run.shared->inFlight.fetch_sub(1, std::memory_order_relaxed) - 1; ::morph::observe::detail::emitMetric(::morph::observe::Metric::executeInFlight, static_cast(inFlightAfterDec)); // Resolve last: the sink is still settled exactly once, only its @@ -1811,9 +1833,9 @@ class LocalBackend : public detail::IBackend { // Size at which `trackPending` next sweeps `_pending` for expired entries; // re-armed at twice the surviving count after each sweep. See `trackPending`. std::size_t _compactAt = kPendingCompactFloor; - // Recorded by `cancelPending` as it takes the pending list. Shared with every run, which notes the epoch it was - // admitted under and skips its handler if the epoch has moved on by the time it starts. - std::shared_ptr _cancels = std::make_shared(); + // What `cancelPending` records as it takes the pending list, and the in-flight count. Shared with every run, which + // notes the epoch it was admitted under and skips its handler if the epoch has moved on by the time it starts. + std::shared_ptr _shared = std::make_shared(); // The Task runs `cancelPending` and the destructor stop. Weak, so a // finished run is not kept. Owner-only. std::vector> _taskRuns; @@ -1822,10 +1844,6 @@ class LocalBackend : public detail::IBackend { std::shared_ptr> _eventHandler; ::morph::exec::IExecutor* _eventExec = nullptr; std::size_t _taskRunsCompactAt = kPendingCompactFloor; - // Concurrent in-flight executes, for the executeInFlight metric. A - // shared_ptr (not a plain atomic member) so strand tasks hold their own - // reference instead of capturing `this` — see execute()'s comment. - std::shared_ptr> _inFlight = std::make_shared>(0); }; } // namespace morph::backend diff --git a/tests/test_backend_extra.cpp b/tests/test_backend_extra.cpp index d71526f07..b486b4ed4 100644 --- a/tests/test_backend_extra.cpp +++ b/tests/test_backend_extra.cpp @@ -494,6 +494,36 @@ TEST_CASE("morph::backend::LocalBackend: executeLatencyMs covers the time the ha CHECK(latencies.front() >= 20.0); } +TEST_CASE("morph::backend::LocalBackend: a call that started with no metric sink emits no latency sample", + "[backend][local][observability]") { + morph::observe::ScopedObserveOverride const guard; + morph::exec::ThreadPoolExecutor pool{2}; + morph::exec::MainThreadExecutor cbExec; + morph::backend::LocalBackend backend{pool}; + auto mid = backend.registerModel("BE_CounterModel", morph::model::detail::ModelFactory::create); + + std::atomic latencies{0}; + auto const sink = [&](const morph::observe::MetricEvent& evt) { + if (evt.metric == morph::observe::Metric::executeLatencyMs) { + latencies.fetch_add(1); + } + }; + + // The sink appears while the handler runs, after the call was admitted + // with none installed: there is no start reading to measure from. + std::atomic first{false}; + backend.execute(mid, pendingCall([&] { morph::observe::setMetricSink(sink); }), &cbExec) + .then([&](const std::shared_ptr&) { first = true; }); + REQUIRE(morph::testing::pumpOwnerUntil(cbExec, [&] { return first.load(); })); + CHECK(latencies.load() == 0); + + // The same sink is installed when the next call starts, so that one is timed. + std::atomic second{false}; + backend.execute(mid, pendingCall([] {}), &cbExec).then([&](const std::shared_ptr&) { second = true; }); + REQUIRE(morph::testing::pumpOwnerUntil(cbExec, [&] { return second.load(); })); + CHECK(latencies.load() == 1); +} + namespace { /// What a hand-built Task handler kept when it started: the token it was given From daa565c15bc4c68ddd242217c4e149ae1740b578 Mon Sep 17 00:00:00 2001 From: Yaraslau Tamashevich Date: Fri, 27 Nov 2026 09:14:28 +0100 Subject: [PATCH 07/11] feat(observe): MORPH_ENABLE_OBSERVABILITY compiles the metric and trace seams out The CMake option (default ON) defines MORPH_OBSERVABILITY_DISABLED publicly on the morph target when OFF. With it defined, `emitMetric`, `beginSpan` and `endSpan` are empty inline functions, `metricsEnabled()` is the constant `false`, and `LocalBackend` takes no clock readings and keeps no in-flight counter, which exists only to feed the `executeInFlight` metric. `setMetricSink`, `setTraceSink` and `ScopedObserveOverride` refuse to compile in that build, with a static_assert whose message names the option, instead of accepting a sink that is never called. The refusal is a dependent static_assert rather than `= delete("...")`, which not every supported compiler accepts. Test cases and the concepts example that install a sink are wrapped in `#if !defined(MORPH_OBSERVABILITY_DISABLED)`. A configure-time try_compile proves each of the three ways of installing a sink fails with the message when the macro is defined, and compiles when it is not. Measured with SPIN_US=0 and no sinks (tiny model, 8 workers, instructions per call): 7543 with the option ON (unchanged), 7437 with it OFF at one call in flight; 7403 and 7297 at 64 in flight. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT --- CMakeLists.txt | 14 +++ docs/BUILDING.md | 8 +- docs/spec/core/observability.md | 47 ++++++++-- .../concepts/observability_and_shutdown.cpp | 2 + include/morph/core/backend.hpp | 11 +++ include/morph/core/observability.hpp | 86 +++++++++++++++++++ src/ui/process_state.cpp | 2 + tests/CMakeLists.txt | 77 +++++++++++++++++ .../observability_disabled_no_sink.cpp | 18 ++++ .../observability_disabled_set_sink.cpp | 20 +++++ .../test_sqlite_offline_queue.cpp | 2 + tests/test_backend_extra.cpp | 14 +++ tests/test_file_offline_queue.cpp | 2 + tests/test_observability.cpp | 6 ++ tests/test_offline_queue.cpp | 2 + tests/test_push_channel.cpp | 2 + tests/test_reconnect_coordinator.cpp | 4 + tests/test_remote_extra.cpp | 14 +++ tests/test_shared_instances.cpp | 4 + tests/test_sync_worker.cpp | 2 + 20 files changed, 331 insertions(+), 6 deletions(-) create mode 100644 tests/compile_checks/observability_disabled_no_sink.cpp create mode 100644 tests/compile_checks/observability_disabled_set_sink.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 1a39bce0e..0a4fbb30c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -160,6 +160,17 @@ option(MORPH_CLIENT_ONLY OFF ) +# Observability (`morph::observe`: metric and trace sinks) is on by default. OFF +# compiles the emit sites out of the dispatch path -- the clock reads and the +# in-flight counter `LocalBackend` keeps for its metrics included -- and makes +# installing a sink a compile error naming this option. PUBLIC on the morph +# target, not per-consumer: the macro changes what inline functions in the +# public headers are, so two translation units disagreeing about it would +# violate ODR. See docs/spec/core/observability.md. +option(MORPH_ENABLE_OBSERVABILITY + "Build the metric and trace seams (morph::observe). OFF compiles them out of the dispatch path and makes installing a sink a compile error." + ON +) # Both Qt consumers (the WebSocket backend and the Qt Quick frontend) need # Qt6 auto-detected on Windows before their find_package(Qt6 ...) calls run. @@ -528,6 +539,9 @@ endif() if(MORPH_CLIENT_ONLY) target_compile_definitions(morph PUBLIC MORPH_CLIENT_ONLY) endif() +if(NOT MORPH_ENABLE_OBSERVABILITY) + target_compile_definitions(morph PUBLIC MORPH_OBSERVABILITY_DISABLED) +endif() if(MORPH_ENABLE_TRACY) target_compile_definitions(morph PUBLIC MORPH_TRACY_ENABLED) target_link_libraries(morph PUBLIC Tracy::TracyClient) diff --git a/docs/BUILDING.md b/docs/BUILDING.md index 1a2665735..8f127ae19 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -64,7 +64,7 @@ need `VCPKG_ROOT` set. | `MORPH_BUILD_CLANG_TIDY` | `OFF` | clang-tidy during the build, warnings as errors | | `MORPH_INSTALL` | top-level project | Install and export rules | -Two options change what the library itself compiles, for deployments that need +Three options change what the library itself compiles, for deployments that need them: - **`MORPH_CLIENT_ONLY`** (`OFF`) suppresses the registrars that construct and @@ -75,6 +75,12 @@ them: - **`MORPH_REQUIRE_VETTED_HMAC`** (`OFF`) removes the default reference HMAC from the token signer and verifier, so every call site must pass a vetted MAC function. See [`spec/security.md`](spec/security.md). +- **`MORPH_ENABLE_OBSERVABILITY`** (`ON`) builds the metric and trace seams. + `OFF` compiles them out of the dispatch path (the clock reads and in-flight + counter a local call keeps for its metrics included) and makes installing a + sink (`setMetricSink`, `setTraceSink`, `ScopedObserveOverride`) a compile + error. See [`spec/core/observability.md`](spec/core/observability.md), + "Compile-time switch". ## Using morph in your own project diff --git a/docs/spec/core/observability.md b/docs/spec/core/observability.md index 10b66e3f3..d1f7a74d9 100644 --- a/docs/spec/core/observability.md +++ b/docs/spec/core/observability.md @@ -17,6 +17,7 @@ if the seam did not exist. `RemoteServer` additionally exposes a - [Tracing](#tracing) - [Health / readiness](#health--readiness) - [Call sites](#call-sites) +- [Compile-time switch](#compile-time-switch) - [Thread safety](#thread-safety) - [API reference](#api-reference) - [Design decisions](#design-decisions) @@ -143,6 +144,41 @@ no sink emits no latency sample, even if a sink is installed before it finishes: the start reading it would need was never taken. With no sink installed, a dispatch costs no clock read. Tracing is decided separately, at `beginSpan`. +## Compile-time switch + +CMake option `MORPH_ENABLE_OBSERVABILITY` (default `ON`). With it `OFF` the +`morph` target defines `MORPH_OBSERVABILITY_DISABLED` publicly: the headers are +mostly inline, so every translation unit that includes them, the library's own +and each consumer's, must see the same value, and a public definition on the +target gives them one. A consumer that does not use the CMake target keeps the +default (observability on) unless it defines the macro itself. + +With the macro defined: + +- `detail::emitMetric`, `detail::beginSpan` and `detail::endSpan` are empty + inline functions, and `metricsEnabled()` is the constant `false`. The process-wide + state (`detail::ObserveState`, `detail::observeState()`) does not exist. +- `LocalBackend` takes no clock reading in `admitLocal`/`finishLocal` and keeps + no in-flight counter or its two atomic updates per call: the counter exists + only to feed `executeInFlight`. +- `setMetricSink`, `setTraceSink` and `ScopedObserveOverride` are templates + (a defaulted template parameter for a complete type) whose body is a + `static_assert` with the message `observability is compiled out + (MORPH_ENABLE_OBSERVABILITY=OFF)`. Installing a sink in such a build is a + compile error at the call site that names the option, rather than a sink that + is never called. `= delete("...")` would carry the same text, but it is C++26 + and not every compiler the project builds with accepts it. +- `RemoteServer::health()` and `ServerConfig::healthHandler` are not part of + the switch: readiness is not a metric. + +Test cases that install a sink are wrapped in +`#if !defined(MORPH_OBSERVABILITY_DISABLED)`, as is the concepts example, so +the unit tests build and pass with the option `OFF` (the sink cases are absent +there). `tests/CMakeLists.txt` proves the refusal at configure time with +`try_compile`, on every platform: each of the three ways to install a sink must +fail to compile with the macro defined, with the message above in the compiler +output, and must compile without it. + ## Thread safety Metrics and tracing each have their own mutex (`metricMtx`, `traceMtx`) guarding @@ -205,8 +241,8 @@ queued or running (see [backend.md](backend.md)'s Lifetime & ownership). | Symbol | Signature | Notes | |---|---|---| | `MetricSink` | `using MetricSink = std::function` | Sink type. | -| `setMetricSink` | `void setMetricSink(MetricSink)` | Thread-safe (mutex-guarded swap). `nullptr` disables metrics. | -| `metricsEnabled` | `[[nodiscard]] bool metricsEnabled() noexcept` | Lock-free hot-path check (relaxed atomic load). | +| `setMetricSink` | `void setMetricSink(MetricSink)` | Thread-safe (mutex-guarded swap). `nullptr` disables metrics. Refused at compile time when observability is compiled out. | +| `metricsEnabled` | `[[nodiscard]] bool metricsEnabled() noexcept` | Lock-free hot-path check (relaxed atomic load). `constexpr false` when observability is compiled out. | ### `SpanId` / `TraceSink` @@ -215,14 +251,15 @@ queued or running (see [backend.md](backend.md)'s Lifetime & ownership). | `SpanId` | `using SpanId = std::uint64_t` | `0` is the "no span" sentinel. | | `TraceSink::beginSpan` | `std::function` | Called at dispatch start (on the strand). | | `TraceSink::endSpan` | `std::function` | Called at dispatch end. | -| `setTraceSink` | `void setTraceSink(TraceSink)` | Both callbacks must be set to enable tracing. Thread-safe. | +| `setTraceSink` | `void setTraceSink(TraceSink)` | Both callbacks must be set to enable tracing. Thread-safe. Refused at compile time when observability is compiled out. | ### `ScopedObserveOverride` RAII guard, snapshot-only constructor, restores the previous metric and trace sinks on destruction. Mirrors `morph::log::ScopedLoggerOverride`'s snapshot-only constructor; used by tests to avoid leaking a sink across test -cases. Not copyable or movable. +cases. Not copyable or movable. Refused at compile time when observability is +compiled out. ### `RemoteServer::HealthStatus` / `health()` / `ServerConfig::healthHandler` @@ -247,7 +284,7 @@ See [backend.md](backend.md)'s `RemoteServer` API reference table. | Two independent sinks (metric, trace), each with its own mutex/atomic | No shared state between them | Installing/using one never contends with the other; matches the fact that they observe different things (numbers vs. spans) and can be wired to entirely different backends. | | `registerCount`/`deregisterCount` count every call, not just successes | Counts attempts | Gives an accurate load/rate signal on that path (an unauthorized or malformed register still costs the server work); `executeErrors` is the separate counter for outcome-scoped failure signal on the execute path. | | `RemoteServer`'s in-flight metric reuses the in-flight count | No second counter added | `LimitPolicy::maxInFlightExecutes` already needs an in-flight count with exactly this admit/complete lifecycle; a parallel one for the metric alone would have to be kept in lockstep for no benefit. `health()`'s `inFlight` field reads the same count. | -| `LocalBackend`'s in-flight counter is a `shared_ptr`, not a plain atomic member | Avoids capturing `this` in a strand-posted lambda | `LocalBackend`'s existing strand tasks already avoid `this` captures for lifetime safety (see Limitations); the counter follows the same rule rather than becoming a new dangling-pointer risk. `RemoteServer`'s equivalent count is a plain member of its server-strand state, reached through tasks that capture `self = shared_from_this()`, keeping the whole object alive. | +| `LocalBackend`'s in-flight counter lives in the shared run state, held by `shared_ptr`, not a plain atomic member | Avoids capturing `this` in a strand-posted lambda, and one `shared_ptr` copy per run covers it and the cancel record | `LocalBackend`'s existing strand tasks already avoid `this` captures for lifetime safety (see Limitations); the counter follows the same rule rather than becoming a new dangling-pointer risk. `RemoteServer`'s equivalent count is a plain member of its server-strand state, reached through tasks that capture `self = shared_from_this()`, keeping the whole object alive. | | `ServerConfig::healthHandler` is called from the constructor | Once, synchronously, with the initial status | A subscriber gets a baseline status without waiting for the first transition; nothing else can reach the server yet, so the call needs no strand. | | `ready`'s sole mutator is `beginShutdown()` | `RemoteServer` sets `_ready` to `false` only from `beginShutdown()`, never back to `true` | Readiness has exactly one transition a load balancer needs to see — "stop sending me new work" — and shutdown is the one event that causes it ([backend.md](backend.md#graceful-shutdown-beginshutdown--drainedwithin)). A server with no un-shutdown has no second transition to report. | diff --git a/examples/concepts/observability_and_shutdown.cpp b/examples/concepts/observability_and_shutdown.cpp index eaea6b7ff..21d2be24a 100644 --- a/examples/concepts/observability_and_shutdown.cpp +++ b/examples/concepts/observability_and_shutdown.cpp @@ -83,6 +83,7 @@ BRIDGE_REGISTER_ACTION(ObsDemoModel, ObsDemoAction, "ObsDemo_Action") // register/execute/deregister call on every server, with no per-call code // anywhere else. +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("observability: setMetricSink observes a registerCount event during register", "[concepts][observability]") { // ScopedObserveOverride snapshots the current sink and restores it on // scope exit, so this test's sink never leaks into another test case. @@ -105,6 +106,7 @@ TEST_CASE("observability: setMetricSink observes a registerCount event during re } REQUIRE(sawRegisterCount); } +#endif // MORPH_OBSERVABILITY_DISABLED // ── (b) Graceful shutdown ──────────────────────────────────────────────────── // diff --git a/include/morph/core/backend.hpp b/include/morph/core/backend.hpp index 5e5b342b7..2cf3cdfe4 100644 --- a/include/morph/core/backend.hpp +++ b/include/morph/core/backend.hpp @@ -1376,9 +1376,11 @@ class LocalBackend : public detail::IBackend { run.shared = _shared; run.admittedEpoch = admittedEpoch; run.mid = mid; +#if !defined(MORPH_OBSERVABILITY_DISABLED) auto const inFlightAfterInc = run.shared->inFlight.fetch_add(1, std::memory_order_relaxed) + 1; ::morph::observe::detail::emitMetric(::morph::observe::Metric::executeInFlight, static_cast(inFlightAfterInc)); +#endif // Through the instance's action gate: an action starts only once the one // before it has finished, which a Task handler does when its Task // completes rather than when the strand task that started it returns. @@ -1596,9 +1598,12 @@ class LocalBackend : public detail::IBackend { /// disconnect. class RunShared { public: +#if !defined(MORPH_OBSERVABILITY_DISABLED) /// Concurrent in-flight executes, for the `executeInFlight` metric: /// incremented when a run is admitted, decremented when it finishes. + /// Absent when observability is compiled out, as nothing else reads it. std::atomic inFlight{0}; +#endif /// Publishes @p reason, then bumps the epoch. One writer: the owner. void record(const std::exception_ptr& reason) { @@ -1649,8 +1654,10 @@ class LocalBackend : public detail::IBackend { ::morph::exec::detail::ModelId mid{}; // Stamped by `admitLocal` only when a metric sink was installed then; // `timed` says whether `start` holds a reading. +#if !defined(MORPH_OBSERVABILITY_DISABLED) std::chrono::steady_clock::time_point start; bool timed = false; +#endif ::morph::observe::SpanId spanId{}; }; @@ -1661,10 +1668,12 @@ class LocalBackend : public detail::IBackend { // The clock is read only for a latency sample, so only when something // will receive it. A sink installed after this point gets no sample for // this run. +#if !defined(MORPH_OBSERVABILITY_DISABLED) run.timed = ::morph::observe::metricsEnabled(); if (run.timed) { run.start = std::chrono::steady_clock::now(); } +#endif run.spanId = ::morph::observe::detail::beginSpan(run.session.requestId, run.modelTypeId, run.actionTypeId); if (run.shared->epoch() == run.admittedEpoch) { return true; @@ -1768,6 +1777,7 @@ class LocalBackend : public detail::IBackend { run.hydration->settle(succeeded); } ::morph::observe::detail::endSpan(run.spanId, succeeded); +#if !defined(MORPH_OBSERVABILITY_DISABLED) std::array, 2> const tags{ {{"modelType", run.modelTypeId}, {"actionType", run.actionTypeId}}}; if (run.timed) { @@ -1781,6 +1791,7 @@ class LocalBackend : public detail::IBackend { auto const inFlightAfterDec = run.shared->inFlight.fetch_sub(1, std::memory_order_relaxed) - 1; ::morph::observe::detail::emitMetric(::morph::observe::Metric::executeInFlight, static_cast(inFlightAfterDec)); +#endif // Resolve last: the sink is still settled exactly once, only its // position relative to the now-recorded instrumentation moved. if (succeeded) { diff --git a/include/morph/core/observability.hpp b/include/morph/core/observability.hpp index cefc72e79..0197b4f83 100644 --- a/include/morph/core/observability.hpp +++ b/include/morph/core/observability.hpp @@ -11,6 +11,14 @@ #include #include +// With `MORPH_OBSERVABILITY_DISABLED` defined (CMake option +// `MORPH_ENABLE_OBSERVABILITY=OFF`, which defines it publicly on the `morph` +// target), the process-wide state does not exist: `detail::emitMetric`, +// `detail::beginSpan` and `detail::endSpan` do nothing, `metricsEnabled()` is +// the constant `false`, and the sink setters and `ScopedObserveOverride` refuse +// to compile. Every translation unit of a program must agree on the macro, as +// it changes what these inline functions are. + namespace morph::observe { /// @brief Kinds of metric observation the framework's hot paths can emit. @@ -78,6 +86,8 @@ struct TraceSink { std::function endSpan; }; +#if !defined(MORPH_OBSERVABILITY_DISABLED) + namespace detail { /// @brief Process-wide observability state: the metric sink and the trace @@ -215,8 +225,33 @@ inline void endSpan(SpanId id, bool ok) { } // namespace detail +#else // MORPH_OBSERVABILITY_DISABLED + +namespace detail { + +/// @brief Compiled out: observability is disabled for this build, so nothing is +/// emitted and nothing is evaluated at the call site beyond its arguments. +inline void emitMetric(Metric /*metric*/, double /*value*/, + std::span> /*tags*/ = {}) noexcept {} + +/// @brief Compiled out: tracing is disabled for this build. +/// @return The `SpanId{0}` sentinel, always. +[[nodiscard]] inline SpanId beginSpan(std::string_view /*requestId*/, std::string_view /*modelType*/, + std::string_view /*actionType*/) noexcept { + return SpanId{0}; +} + +/// @brief Compiled out: tracing is disabled for this build. +inline void endSpan(SpanId /*id*/, bool /*ok*/) noexcept {} + +} // namespace detail + +#endif // MORPH_OBSERVABILITY_DISABLED + // ── Configuration ───────────────────────────────────────────────────────────── +#if !defined(MORPH_OBSERVABILITY_DISABLED) + /// @brief Installs the process-wide metric sink. /// /// Thread-safe (mutex-guarded swap), exactly like `morph::log::setLogger`. Pass @@ -237,6 +272,27 @@ inline void setMetricSink(MetricSink sink) { return detail::observeState().metricsOn.load(std::memory_order_relaxed); } +#else // MORPH_OBSERVABILITY_DISABLED + +/// @brief Refused: observability is compiled out of this build +/// (`MORPH_ENABLE_OBSERVABILITY=OFF`), so a sink would never be called. +/// +/// A template, so the refusal is a compile error at the call site that names +/// the option instead of a sink that silently receives nothing. +/// @tparam Sink Whatever the call passes; never usable. +template +void setMetricSink(Sink /*sink*/) { + static_assert(sizeof(Sink) == 0, "observability is compiled out (MORPH_ENABLE_OBSERVABILITY=OFF)"); +} + +/// @brief Compiled out: no metric sink can be installed, so none is. +/// @return `false`, a constant, so a branch on it is removed. +[[nodiscard]] constexpr bool metricsEnabled() noexcept { return false; } + +#endif // MORPH_OBSERVABILITY_DISABLED + +#if !defined(MORPH_OBSERVABILITY_DISABLED) + /// @brief Installs the process-wide trace sink. /// /// Thread-safe (mutex-guarded swap). Both `TraceSink::beginSpan` and @@ -300,4 +356,34 @@ class ScopedObserveOverride { TraceSink _savedTraceSink; }; +#else // MORPH_OBSERVABILITY_DISABLED + +/// @brief Refused: observability is compiled out of this build +/// (`MORPH_ENABLE_OBSERVABILITY=OFF`), so a sink would never be called. +/// +/// A template, like `setMetricSink` in this configuration: the refusal is a +/// compile error at the call site that names the option. +/// @tparam Sink Whatever the call passes; never usable. +template +void setTraceSink(Sink /*sink*/) { + static_assert(sizeof(Sink) == 0, "observability is compiled out (MORPH_ENABLE_OBSERVABILITY=OFF)"); +} + +/// @brief Refused: there are no sinks to snapshot and restore in this build. +/// +/// Declaring one is a compile error that names the option, as installing a +/// sink is. +class ScopedObserveOverride { +public: + /// @brief Refused at the point of use. + /// @tparam Guard Always `ScopedObserveOverride`; the dependent type that + /// lets the refusal fire only when a guard is constructed. + template + ScopedObserveOverride() { + static_assert(sizeof(Guard) == 0, "observability is compiled out (MORPH_ENABLE_OBSERVABILITY=OFF)"); + } +}; + +#endif // MORPH_OBSERVABILITY_DISABLED + } // namespace morph::observe diff --git a/src/ui/process_state.cpp b/src/ui/process_state.cpp index 5eb724b36..65eae6705 100644 --- a/src/ui/process_state.cpp +++ b/src/ui/process_state.cpp @@ -116,6 +116,7 @@ LogState& logState() { } // namespace morph::log::detail +#if !defined(MORPH_OBSERVABILITY_DISABLED) namespace morph::observe::detail { ObserveState& observeState() { @@ -124,6 +125,7 @@ ObserveState& observeState() { } } // namespace morph::observe::detail +#endif namespace morph::session { diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index b9ea8c165..70b804c76 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -668,6 +668,83 @@ endif() set(CMAKE_TRY_COMPILE_TARGET_TYPE "${_morph_guard_try_target_type}") unset(_morph_guard_try_target_type) +# ── MORPH_ENABLE_OBSERVABILITY=OFF checks ──────────────────────────────────── +# Proof that a build with observability compiled out refuses to install a +# sink, and says why. The probes name the macro themselves (what the option +# defines on the morph target), so this holds whichever way the option is set. +# - disabled_set_sink with the macro, for each of the three ways to install +# a sink: must NOT compile, and the compiler output must carry the +# refusal's message (any other error would also "fail to compile", which +# proves nothing about the refusal). +# - the same file and probe without the macro: must compile (control: the +# file is valid and its includes resolve). +# - disabled_no_sink with and without the macro: must compile (control: the +# header still offers everything but the setters when compiled out). +set(_morph_obs_try_target_type "${CMAKE_TRY_COMPILE_TARGET_TYPE}") +set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) + +foreach(_morph_obs_probe IN ITEMS PROBE_METRIC_SINK PROBE_TRACE_SINK PROBE_SCOPED_OVERRIDE) + unset(MORPH_OBSERVABILITY_OFF_ACCEPTS_SINK CACHE) + try_compile(MORPH_OBSERVABILITY_OFF_ACCEPTS_SINK + SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/compile_checks/observability_disabled_set_sink.cpp" + CMAKE_FLAGS "-DINCLUDE_DIRECTORIES=${MORPH_VETTED_HMAC_GUARD_INCLUDE_DIRS}" + CXX_STANDARD 23 + COMPILE_DEFINITIONS "-DMORPH_OBSERVABILITY_DISABLED" "-D${_morph_obs_probe}" + OUTPUT_VARIABLE MORPH_OBSERVABILITY_OFF_SINK_OUTPUT + ) + if(MORPH_OBSERVABILITY_OFF_ACCEPTS_SINK) + message(FATAL_ERROR + "observability check failed: compile_checks/observability_disabled_set_sink.cpp compiled with " + "MORPH_OBSERVABILITY_DISABLED and ${_morph_obs_probe} defined (expected the sink to be refused).") + endif() + string(FIND "${MORPH_OBSERVABILITY_OFF_SINK_OUTPUT}" + "observability is compiled out (MORPH_ENABLE_OBSERVABILITY=OFF)" _morph_obs_message_at) + if(_morph_obs_message_at EQUAL -1) + message(FATAL_ERROR + "observability check failed: compile_checks/observability_disabled_set_sink.cpp failed to compile with " + "MORPH_OBSERVABILITY_DISABLED and ${_morph_obs_probe} defined, but not with the refusal's message. " + "Compiler output:\n${MORPH_OBSERVABILITY_OFF_SINK_OUTPUT}") + endif() + unset(_morph_obs_message_at) + + unset(MORPH_OBSERVABILITY_ON_ACCEPTS_SINK CACHE) + try_compile(MORPH_OBSERVABILITY_ON_ACCEPTS_SINK + SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/compile_checks/observability_disabled_set_sink.cpp" + CMAKE_FLAGS "-DINCLUDE_DIRECTORIES=${MORPH_VETTED_HMAC_GUARD_INCLUDE_DIRS}" + CXX_STANDARD 23 + COMPILE_DEFINITIONS "-D${_morph_obs_probe}" + OUTPUT_VARIABLE MORPH_OBSERVABILITY_ON_SINK_OUTPUT + ) + if(NOT MORPH_OBSERVABILITY_ON_ACCEPTS_SINK) + message(FATAL_ERROR + "observability check failed: compile_checks/observability_disabled_set_sink.cpp failed to compile with " + "${_morph_obs_probe} defined and MORPH_OBSERVABILITY_DISABLED not (the refusal check above would pass " + "for any broken include). Compiler output:\n${MORPH_OBSERVABILITY_ON_SINK_OUTPUT}") + endif() +endforeach() +unset(_morph_obs_probe) + +# The second value names an unrelated macro, so both runs have the same shape. +foreach(_morph_obs_define IN ITEMS "-DMORPH_OBSERVABILITY_DISABLED" "-DMORPH_OBSERVABILITY_UNDEFINED_CONTROL") + unset(MORPH_OBSERVABILITY_NO_SINK_COMPILES CACHE) + try_compile(MORPH_OBSERVABILITY_NO_SINK_COMPILES + SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/compile_checks/observability_disabled_no_sink.cpp" + CMAKE_FLAGS "-DINCLUDE_DIRECTORIES=${MORPH_VETTED_HMAC_GUARD_INCLUDE_DIRS}" + CXX_STANDARD 23 + COMPILE_DEFINITIONS "${_morph_obs_define}" + OUTPUT_VARIABLE MORPH_OBSERVABILITY_NO_SINK_OUTPUT + ) + if(NOT MORPH_OBSERVABILITY_NO_SINK_COMPILES) + message(FATAL_ERROR + "observability check failed: compile_checks/observability_disabled_no_sink.cpp failed to compile with " + "${_morph_obs_define}. Compiler output:\n${MORPH_OBSERVABILITY_NO_SINK_OUTPUT}") + endif() +endforeach() +unset(_morph_obs_define) + +set(CMAKE_TRY_COMPILE_TARGET_TYPE "${_morph_obs_try_target_type}") +unset(_morph_obs_try_target_type) + # ── MORPH_CLIENT_ONLY guard check ──────────────────────────────────────────── # Proof that MORPH_CLIENT_ONLY actually suppresses the two model-owning # registrars (registerModelOnce, registerActionOnce) -- see diff --git a/tests/compile_checks/observability_disabled_no_sink.cpp b/tests/compile_checks/observability_disabled_no_sink.cpp new file mode 100644 index 000000000..7bb310b68 --- /dev/null +++ b/tests/compile_checks/observability_disabled_no_sink.cpp @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Compile-check fixture for MORPH_ENABLE_OBSERVABILITY=OFF (see the try_compile() +// block in tests/CMakeLists.txt). Uses everything a compiled-out build still +// offers: it must compile with MORPH_OBSERVABILITY_DISABLED defined and with +// it undefined, so the refusal of the sink setters is the only thing the macro +// changes for a caller. + +#include + +#include + +bool emitEverything() { + morph::observe::detail::emitMetric(morph::observe::Metric::executeErrors, 1.0); + auto const span = morph::observe::detail::beginSpan(std::string_view{}, std::string_view{}, std::string_view{}); + morph::observe::detail::endSpan(span, true); + return morph::observe::metricsEnabled(); +} diff --git a/tests/compile_checks/observability_disabled_set_sink.cpp b/tests/compile_checks/observability_disabled_set_sink.cpp new file mode 100644 index 000000000..a7cafeb19 --- /dev/null +++ b/tests/compile_checks/observability_disabled_set_sink.cpp @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Compile-check fixture for MORPH_ENABLE_OBSERVABILITY=OFF (see the try_compile() +// block in tests/CMakeLists.txt). Each probe installs a sink the way a host +// does; PROBE_METRIC_SINK, PROBE_TRACE_SINK and PROBE_SCOPED_OVERRIDE pick which. +// It must compile when MORPH_OBSERVABILITY_DISABLED is not defined, and must be +// refused, naming the option, when it is. + +#include + +void installSink() { +#if defined(PROBE_TRACE_SINK) + morph::observe::setTraceSink(morph::observe::TraceSink{}); +#elif defined(PROBE_SCOPED_OVERRIDE) + morph::observe::ScopedObserveOverride const guard; + (void)guard; +#else + morph::observe::setMetricSink([](const morph::observe::MetricEvent&) {}); +#endif +} diff --git a/tests/offline_sqlite/test_sqlite_offline_queue.cpp b/tests/offline_sqlite/test_sqlite_offline_queue.cpp index 8a71bd881..a70fd372a 100644 --- a/tests/offline_sqlite/test_sqlite_offline_queue.cpp +++ b/tests/offline_sqlite/test_sqlite_offline_queue.cpp @@ -288,6 +288,7 @@ TEST_CASE("morph::offline::SqliteOfflineQueue: a dedup hit at capacity is reject removeDbFiles(dbPath); } +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("morph::offline::SqliteOfflineQueue: enqueue at maxDepth emits queueOverflow metric", "[sqlite][overflow][observability]") { morph::observe::ScopedObserveOverride guard; @@ -310,6 +311,7 @@ TEST_CASE("morph::offline::SqliteOfflineQueue: enqueue at maxDepth emits queueOv } removeDbFiles(dbPath); } +#endif // MORPH_OBSERVABILITY_DISABLED // ── IOfflineQueue conformance ───────────────────────────────────────────────── // diff --git a/tests/test_backend_extra.cpp b/tests/test_backend_extra.cpp index b486b4ed4..7b5690f7f 100644 --- a/tests/test_backend_extra.cpp +++ b/tests/test_backend_extra.cpp @@ -171,6 +171,7 @@ TEST_CASE("morph::bridge::BridgeHandler destructor deregisters model cleanly", " // ── morph::backend::LocalBackend: observability (metrics + tracing) ───────── +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("morph::backend::LocalBackend: execute emits executeLatencyMs and toggles executeInFlight", "[backend][local][observability]") { morph::observe::ScopedObserveOverride guard; @@ -210,7 +211,9 @@ TEST_CASE("morph::backend::LocalBackend: execute emits executeLatencyMs and togg REQUIRE(inFlightSamples[0] == 1.0); REQUIRE(inFlightSamples[1] == 0.0); } +#endif // MORPH_OBSERVABILITY_DISABLED +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("morph::backend::LocalBackend: an erroring action emits executeErrors", "[backend][local][observability]") { morph::observe::ScopedObserveOverride guard; morph::exec::ThreadPoolExecutor pool{2}; @@ -241,7 +244,9 @@ TEST_CASE("morph::backend::LocalBackend: an erroring action emits executeErrors" REQUIRE(morph::testing::pumpOwnerUntil(cbExec, [&] { return errored.load(); })); REQUIRE(errorEvents.load() == 1); } +#endif // MORPH_OBSERVABILITY_DISABLED +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("morph::backend::LocalBackend: registerModel/deregisterModel emit their counters", "[backend][local][observability]") { morph::observe::ScopedObserveOverride guard; @@ -264,7 +269,9 @@ TEST_CASE("morph::backend::LocalBackend: registerModel/deregisterModel emit thei REQUIRE(registerEvents.load() == 1); REQUIRE(deregisterEvents.load() == 1); } +#endif // MORPH_OBSERVABILITY_DISABLED +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("morph::backend::LocalBackend: one execute produces exactly one beginSpan/endSpan pair", "[backend][local][observability]") { morph::observe::ScopedObserveOverride guard; @@ -305,6 +312,7 @@ TEST_CASE("morph::backend::LocalBackend: one execute produces exactly one beginS REQUIRE(beginCalls.load() == 1); REQUIRE(endCalls.load() == 1); } +#endif // MORPH_OBSERVABILITY_DISABLED // ── morph::backend::LocalBackend: amortised pending-list compaction ───────── @@ -465,6 +473,7 @@ TEST_CASE("morph::backend::LocalBackend: trackedPendingCount counts every call s REQUIRE(morph::testing::waitUntil([&] { return ran.load() == 3; })); } +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("morph::backend::LocalBackend: executeLatencyMs covers the time the handler ran", "[backend][local][observability]") { morph::observe::ScopedObserveOverride const guard; @@ -493,7 +502,9 @@ TEST_CASE("morph::backend::LocalBackend: executeLatencyMs covers the time the ha // and how much longer the span took depends on the machine. CHECK(latencies.front() >= 20.0); } +#endif // MORPH_OBSERVABILITY_DISABLED +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("morph::backend::LocalBackend: a call that started with no metric sink emits no latency sample", "[backend][local][observability]") { morph::observe::ScopedObserveOverride const guard; @@ -523,6 +534,7 @@ TEST_CASE("morph::backend::LocalBackend: a call that started with no metric sink REQUIRE(morph::testing::pumpOwnerUntil(cbExec, [&] { return second.load(); })); CHECK(latencies.load() == 1); } +#endif // MORPH_OBSERVABILITY_DISABLED namespace { @@ -580,6 +592,7 @@ TEST_CASE("morph::backend::LocalBackend: destruction requests stop on a Task han slot->finish(std::make_exception_ptr(std::runtime_error{"stopped"})); } +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("morph::backend::LocalBackend: a call cancelled while it waited behind a Task handler finishes as a failure", "[backend][local][observability]") { morph::observe::ScopedObserveOverride const guard; @@ -610,6 +623,7 @@ TEST_CASE("morph::backend::LocalBackend: a call cancelled while it waited behind REQUIRE(morph::testing::waitUntil([&] { return errors.load() == 1; })); CHECK_FALSE(queuedRan.load()); } +#endif // MORPH_OBSERVABILITY_DISABLED // Mutation: call a null serializeAction (undefined behaviour) instead of throwing the named error. TEST_CASE("ActionCall: serialising a call without serializeAction throws a named error", "[backend]") { diff --git a/tests/test_file_offline_queue.cpp b/tests/test_file_offline_queue.cpp index bc5cee2f9..f3ea0c966 100644 --- a/tests/test_file_offline_queue.cpp +++ b/tests/test_file_offline_queue.cpp @@ -772,6 +772,7 @@ TEST_CASE("morph::offline::FileOfflineQueue: size() reflects live pending count" std::filesystem::remove(path); } +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("morph::offline::FileOfflineQueue: enqueue at maxDepth emits queueOverflow metric", "[file_queue][overflow][observability]") { morph::observe::ScopedObserveOverride guard; @@ -794,6 +795,7 @@ TEST_CASE("morph::offline::FileOfflineQueue: enqueue at maxDepth emits queueOver } std::filesystem::remove(path); } +#endif // MORPH_OBSERVABILITY_DISABLED // ── IOfflineQueue conformance ───────────────────────────────────────────────── // diff --git a/tests/test_observability.cpp b/tests/test_observability.cpp index c89e07a48..4d9ffb5ac 100644 --- a/tests/test_observability.cpp +++ b/tests/test_observability.cpp @@ -13,6 +13,10 @@ #include #include +// Every case here installs a sink or reads the process-wide state, which a build +// with MORPH_ENABLE_OBSERVABILITY=OFF does not have. +#if !defined(MORPH_OBSERVABILITY_DISABLED) + using ObserveGuard = morph::observe::ScopedObserveOverride; // ── morph::observe::setMetricSink / metricsEnabled ──────────────────────────── @@ -328,3 +332,5 @@ TEST_CASE("morph::observe: a sink that reinstalls itself does not self-deadlock" REQUIRE(calls.load() == 1); REQUIRE_FALSE(morph::observe::metricsEnabled()); } + +#endif // MORPH_OBSERVABILITY_DISABLED diff --git a/tests/test_offline_queue.cpp b/tests/test_offline_queue.cpp index de9885845..5ed68aeac 100644 --- a/tests/test_offline_queue.cpp +++ b/tests/test_offline_queue.cpp @@ -278,6 +278,7 @@ TEST_CASE("morph::offline::OfflineQueueFullError: carries maxDepth and currentSi REQUIRE(what.find("5") != std::string::npos); } +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("morph::offline::InMemoryOfflineQueue: enqueue at maxDepth emits queueOverflow metric", "[queue][overflow][observability]") { morph::observe::ScopedObserveOverride guard; @@ -296,6 +297,7 @@ TEST_CASE("morph::offline::InMemoryOfflineQueue: enqueue at maxDepth emits queue REQUIRE(samples.size() == 1); REQUIRE(samples[0] == 1.0); } +#endif // MORPH_OBSERVABILITY_DISABLED // ── IOfflineQueue conformance ───────────────────────────────────────────────── // diff --git a/tests/test_push_channel.cpp b/tests/test_push_channel.cpp index 44ced9ef4..a23a66e94 100644 --- a/tests/test_push_channel.cpp +++ b/tests/test_push_channel.cpp @@ -304,6 +304,7 @@ TEST_CASE("a_watch_whose_body_does_not_parse_is_refused", "[push][channel]") { CHECK(reply.callId == 3); } +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("post_above_envelope_cap_is_dropped_and_counted", "[push][channel]") { ::morph::observe::ScopedObserveOverride const restore; std::atomic oversize{0}; @@ -326,6 +327,7 @@ TEST_CASE("post_above_envelope_cap_is_dropped_and_counted", "[push][channel]") { CHECK(oversize.load() == 1); CHECK(wire.snapshot() == std::vector{fits}); } +#endif // MORPH_OBSERVABILITY_DISABLED // Mutation: drop an envelope of exactly `kMaxEnvelopeBytes` (a `<` bound) -- the cap is inclusive. TEST_CASE("post_at_exactly_the_envelope_cap_is_written", "[push][channel]") { diff --git a/tests/test_reconnect_coordinator.cpp b/tests/test_reconnect_coordinator.cpp index 40603cae2..3b4f5a13c 100644 --- a/tests/test_reconnect_coordinator.cpp +++ b/tests/test_reconnect_coordinator.cpp @@ -274,6 +274,7 @@ TEST_CASE("ReconnectCoordinator: concurrent calls are serialised", "[reconnect][ REQUIRE(f.replayCalls == 2 * kPerThread); } +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("ReconnectCoordinator: onOnline emits reconnectAttempts per attempt and a tagged reconnectOutcome once", "[reconnect][observability]") { morph::observe::ScopedObserveOverride guard; @@ -303,7 +304,9 @@ TEST_CASE("ReconnectCoordinator: onOnline emits reconnectAttempts per attempt an REQUIRE(attemptEvents.load() == 3); REQUIRE(outcomeTags == std::vector{"Reconnected"}); } +#endif // MORPH_OBSERVABILITY_DISABLED +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("ReconnectCoordinator: giving up tags reconnectOutcome as GaveUp", "[reconnect][observability]") { morph::observe::ScopedObserveOverride guard; Fakes f; @@ -330,6 +333,7 @@ TEST_CASE("ReconnectCoordinator: giving up tags reconnectOutcome as GaveUp", "[r REQUIRE(outcome == ReconnectOutcome::GaveUp); REQUIRE(outcomeTags == std::vector{"GaveUp"}); } +#endif // MORPH_OBSERVABILITY_DISABLED // ── The owner rule: onOnline()/onOffline() run on the offline strand ───────── diff --git a/tests/test_remote_extra.cpp b/tests/test_remote_extra.cpp index 1d8408f97..9984cda38 100644 --- a/tests/test_remote_extra.cpp +++ b/tests/test_remote_extra.cpp @@ -507,6 +507,7 @@ TEST_CASE( // ── morph::backend::RemoteServer: observability (metrics + tracing) ────────── +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("morph::backend::RemoteServer: execute emits executeLatencyMs and toggles executeInFlight", "[remote][observability]") { morph::observe::ScopedObserveOverride guard; @@ -549,7 +550,9 @@ TEST_CASE("morph::backend::RemoteServer: execute emits executeLatencyMs and togg REQUIRE(inFlightSamples[0] == 1.0); REQUIRE(inFlightSamples[1] == 0.0); } +#endif // MORPH_OBSERVABILITY_DISABLED +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("morph::backend::RemoteServer: executeLatencyMs measures the handler's run time", "[remote][observability]") { morph::observe::ScopedObserveOverride const guard; @@ -590,7 +593,9 @@ TEST_CASE("morph::backend::RemoteServer: executeLatencyMs measures the handler's // least this long. No upper bound, so a loaded machine cannot fail it. CHECK(latencies.front() >= static_cast(kHandlerMs)); } +#endif // MORPH_OBSERVABILITY_DISABLED +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("morph::backend::RemoteServer: an erroring execute emits executeErrors", "[remote][observability]") { morph::observe::ScopedObserveOverride guard; morph::exec::ThreadPoolExecutor pool{2}; @@ -620,7 +625,9 @@ TEST_CASE("morph::backend::RemoteServer: an erroring execute emits executeErrors REQUIRE(waiter.env.kind == "err"); REQUIRE(errorEvents.load() == 1); } +#endif // MORPH_OBSERVABILITY_DISABLED +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("morph::backend::RemoteServer: register/deregister emit their counters", "[remote][observability]") { morph::observe::ScopedObserveOverride guard; morph::exec::ThreadPoolExecutor pool{2}; @@ -647,7 +654,9 @@ TEST_CASE("morph::backend::RemoteServer: register/deregister emit their counters REQUIRE(registerEvents.load() == 1); REQUIRE(deregisterEvents.load() == 1); } +#endif // MORPH_OBSERVABILITY_DISABLED +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("morph::backend::RemoteServer: with no sink installed, register still works and metrics stay disabled", "[remote][observability]") { morph::observe::ScopedObserveOverride guard; @@ -662,7 +671,9 @@ TEST_CASE("morph::backend::RemoteServer: with no sink installed, register still REQUIRE(reg.env.kind == "ok"); REQUIRE_FALSE(morph::observe::metricsEnabled()); } +#endif // MORPH_OBSERVABILITY_DISABLED +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE( "morph::backend::RemoteServer: one execute produces exactly one beginSpan/endSpan pair with the caller's " "requestId", @@ -710,7 +721,9 @@ TEST_CASE( REQUIRE(endCalls.load() == 1); REQUIRE(capturedRequestId == "req-abc"); } +#endif // MORPH_OBSERVABILITY_DISABLED +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("morph::backend::RemoteServer: endSpan reports ok=false for a failing execute", "[remote][observability]") { morph::observe::ScopedObserveOverride guard; morph::exec::ThreadPoolExecutor pool{2}; @@ -746,6 +759,7 @@ TEST_CASE("morph::backend::RemoteServer: endSpan reports ok=false for a failing REQUIRE(endCalls.load() == 1); REQUIRE_FALSE(capturedOk.load()); } +#endif // MORPH_OBSERVABILITY_DISABLED // ── morph::backend::RemoteServer: health / readiness ────────────────────────── diff --git a/tests/test_shared_instances.cpp b/tests/test_shared_instances.cpp index 4667c1c0b..7537c8b47 100644 --- a/tests/test_shared_instances.cpp +++ b/tests/test_shared_instances.cpp @@ -1553,6 +1553,7 @@ TEST_CASE("deregistering a poisoned instance evicted from the directory tears it // instead would leave the first stretch of it -- the one between settling and // `endSpan` -- unpinned, and a regression that moved settling to just after // `endSpan` would sail through. +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("an attach racing a failed first action out of the dispatch is not handed the failed instance", "[shared-instances][backend]") { morph::exec::ThreadPoolExecutor pool{2}; @@ -1601,6 +1602,7 @@ TEST_CASE("an attach racing a failed first action out of the dispatch is not han REQUIRE(attached.load() != 0U); REQUIRE(attached.load() != first.v); } +#endif // MORPH_OBSERVABILITY_DISABLED // The per-type index `listInstances` is served from must shrink as well as // grow: a type whose last shared instance has been released must report no @@ -1634,6 +1636,7 @@ TEST_CASE("releasing the last shared instance of a type empties its listInstance // The server half of the property above. `RemoteServer` kept its own copy of // this logic, so it needs its own proof that the directory learns the outcome // before anything that can attach gets to run. +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("the server does not hand out an instance between its first action failing and the directory learning of it", "[shared-instances][remote]") { morph::exec::ThreadPoolExecutor pool{2}; @@ -1679,6 +1682,7 @@ TEST_CASE("the server does not hand out an instance between its first action fai REQUIRE(attached.load() != 0U); REQUIRE(attached.load() != reg.modelId); } +#endif // MORPH_OBSERVABILITY_DISABLED // An instance that was *created* for a directory key can never be // promoted onto a second one, and "created for a key" outlives being filed diff --git a/tests/test_sync_worker.cpp b/tests/test_sync_worker.cpp index f542e3f7a..ddc6e2772 100644 --- a/tests/test_sync_worker.cpp +++ b/tests/test_sync_worker.cpp @@ -355,6 +355,7 @@ TEST_CASE( REQUIRE(queue.drain().size() == 1); } +#if !defined(MORPH_OBSERVABILITY_DISABLED) TEST_CASE("morph::offline::SyncWorker: run() emits queueDepth with the pending count at drain", "[sync][observability]") { morph::observe::ScopedObserveOverride guard; @@ -376,6 +377,7 @@ TEST_CASE("morph::offline::SyncWorker: run() emits queueDepth with the pending c REQUIRE(samples.size() == 1); REQUIRE(samples[0] == 3.0); } +#endif // MORPH_OBSERVABILITY_DISABLED TEST_CASE("morph::offline::SyncWorker: run() over a queue at maxDepth still drains and replays normally", "[sync][overflow]") { From da34d44f173a9be18d022423366fd3db2b5cd261 Mon Sep 17 00:00:00 2001 From: Yaraslau Tamashevich Date: Fri, 27 Nov 2026 09:24:37 +0100 Subject: [PATCH 08/11] test(bench): the instruction gate measures dispatch, not the pool's spin A spinning worker's instructions follow how long it waited, not what a call executed, so the gate's pool does not spin. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT --- docs/spec/testing_strategy.md | 9 ++++++--- tests/bench/bench_dispatch_instructions.cpp | 10 ++++++++-- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/docs/spec/testing_strategy.md b/docs/spec/testing_strategy.md index 4ec4262a8..4babfcd3a 100644 --- a/docs/spec/testing_strategy.md +++ b/docs/spec/testing_strategy.md @@ -438,8 +438,11 @@ does not move with machine load or clock speed. The owning thread sleeps on a condition variable while it waits. A polling owner spends about ten times the instructions spinning, and the figure would -then measure the spin. The owner is a serial executor of the benchmark's own, -because a one-thread pool is not serial and is refused as an owner. +then measure the spin. The pool's workers do not spin before sleeping +(`PoolOptions::spinBeforeSleep` zero) for the same reason: a spin is bounded by +time, so its instructions follow how long a worker waited, not what dispatch +executed. The owner is a serial executor of the benchmark's own, because a +one-thread pool is not serial and is refused as an owner. **It is a gate.** `bench.instr_budget` passes `--budget=`, taken from the cache variable `MORPH_INSTR_BUDGET_PER_CALL`: 65000 for Debug (the build type CI @@ -447,7 +450,7 @@ runs this target in) and 9000 for the optimized types; 0 disables it; it is not registered under a sanitizer. The count is not exact — it moves by about ±10% between processes — so each default is the worst figure measured plus a margin, and `tests/bench/CMakeLists.txt` carries the measurements. Typical figures on -x86-64 Linux: about 7.4k per call in Release and 55k–59k in Debug, with clang and gcc +x86-64 Linux: about 7.3k per call in Release and 55k–59k in Debug, with clang and gcc within 5% of each other. It was checked against an injected regression: a loop of volatile operations in the action turns the case red in both configurations. diff --git a/tests/bench/bench_dispatch_instructions.cpp b/tests/bench/bench_dispatch_instructions.cpp index f5e46bc0a..b8aa1dce1 100644 --- a/tests/bench/bench_dispatch_instructions.cpp +++ b/tests/bench/bench_dispatch_instructions.cpp @@ -25,7 +25,11 @@ // * `Bridge` over `LocalBackend` over a four-thread pool; the owner is a // serial executor whose `runUntil` sleeps on a condition variable. A // polling owner spends ~10x the instructions spinning, and the figure -// would then measure the spin. +// would then measure the spin. The pool's workers do not spin before +// sleeping (`PoolOptions::spinBeforeSleep` zero) for the same reason: a +// spin is bounded by time, so its instructions follow how long a worker +// waited and not what dispatch executed. What the spin buys is latency +// and throughput, which docs/spec/core/executor.md measures. // * The model holds one `double`; the action adds to it. The workload is // the smallest there is, so what remains is framework overhead. // * `kWarmup` calls are excluded; `kCalls` are counted, each waited out @@ -43,6 +47,7 @@ #include #include +#include #include #include #include @@ -270,7 +275,8 @@ int run(bool baseline, double budget) { return kExitSkipped; } - ::morph::exec::ThreadPoolExecutor pool{kPoolThreads}; + ::morph::exec::ThreadPoolExecutor pool{kPoolThreads, + ::morph::exec::PoolOptions{.spinBeforeSleep = std::chrono::microseconds{0}}}; SleepingOwner owner; double perCall = 0.0; { From e6b64cb027650a312764b7e01a4fcae50b14b1ef Mon Sep 17 00:00:00 2001 From: Yaraslau Tamashevich Date: Fri, 27 Nov 2026 09:43:21 +0100 Subject: [PATCH 09/11] style: single-macro conditions as #ifdef/#ifndef, bench tidy fixes Matches how include/ and src/ write them, and what readability-use-concise-preprocessor-directives asks for. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT --- examples/concepts/observability_and_shutdown.cpp | 2 +- include/morph/core/backend.hpp | 10 +++++----- include/morph/core/observability.hpp | 6 +++--- src/ui/process_state.cpp | 2 +- tests/bench/bench_dispatch_instructions.cpp | 4 ++-- tests/bench/bench_model_scaling.cpp | 4 ++-- .../observability_disabled_set_sink.cpp | 2 +- tests/offline_sqlite/test_sqlite_offline_queue.cpp | 2 +- tests/test_backend_extra.cpp | 14 +++++++------- tests/test_file_offline_queue.cpp | 2 +- tests/test_observability.cpp | 2 +- tests/test_offline_queue.cpp | 2 +- tests/test_push_channel.cpp | 2 +- tests/test_reconnect_coordinator.cpp | 4 ++-- tests/test_remote_extra.cpp | 14 +++++++------- tests/test_shared_instances.cpp | 4 ++-- tests/test_sync_worker.cpp | 2 +- 17 files changed, 39 insertions(+), 39 deletions(-) diff --git a/examples/concepts/observability_and_shutdown.cpp b/examples/concepts/observability_and_shutdown.cpp index 21d2be24a..393ab2093 100644 --- a/examples/concepts/observability_and_shutdown.cpp +++ b/examples/concepts/observability_and_shutdown.cpp @@ -83,7 +83,7 @@ BRIDGE_REGISTER_ACTION(ObsDemoModel, ObsDemoAction, "ObsDemo_Action") // register/execute/deregister call on every server, with no per-call code // anywhere else. -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("observability: setMetricSink observes a registerCount event during register", "[concepts][observability]") { // ScopedObserveOverride snapshots the current sink and restores it on // scope exit, so this test's sink never leaks into another test case. diff --git a/include/morph/core/backend.hpp b/include/morph/core/backend.hpp index 2cf3cdfe4..d75538d94 100644 --- a/include/morph/core/backend.hpp +++ b/include/morph/core/backend.hpp @@ -1376,7 +1376,7 @@ class LocalBackend : public detail::IBackend { run.shared = _shared; run.admittedEpoch = admittedEpoch; run.mid = mid; -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED auto const inFlightAfterInc = run.shared->inFlight.fetch_add(1, std::memory_order_relaxed) + 1; ::morph::observe::detail::emitMetric(::morph::observe::Metric::executeInFlight, static_cast(inFlightAfterInc)); @@ -1598,7 +1598,7 @@ class LocalBackend : public detail::IBackend { /// disconnect. class RunShared { public: -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED /// Concurrent in-flight executes, for the `executeInFlight` metric: /// incremented when a run is admitted, decremented when it finishes. /// Absent when observability is compiled out, as nothing else reads it. @@ -1654,7 +1654,7 @@ class LocalBackend : public detail::IBackend { ::morph::exec::detail::ModelId mid{}; // Stamped by `admitLocal` only when a metric sink was installed then; // `timed` says whether `start` holds a reading. -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED std::chrono::steady_clock::time_point start; bool timed = false; #endif @@ -1668,7 +1668,7 @@ class LocalBackend : public detail::IBackend { // The clock is read only for a latency sample, so only when something // will receive it. A sink installed after this point gets no sample for // this run. -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED run.timed = ::morph::observe::metricsEnabled(); if (run.timed) { run.start = std::chrono::steady_clock::now(); @@ -1777,7 +1777,7 @@ class LocalBackend : public detail::IBackend { run.hydration->settle(succeeded); } ::morph::observe::detail::endSpan(run.spanId, succeeded); -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED std::array, 2> const tags{ {{"modelType", run.modelTypeId}, {"actionType", run.actionTypeId}}}; if (run.timed) { diff --git a/include/morph/core/observability.hpp b/include/morph/core/observability.hpp index 0197b4f83..e7ab4b431 100644 --- a/include/morph/core/observability.hpp +++ b/include/morph/core/observability.hpp @@ -86,7 +86,7 @@ struct TraceSink { std::function endSpan; }; -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED namespace detail { @@ -250,7 +250,7 @@ inline void endSpan(SpanId /*id*/, bool /*ok*/) noexcept {} // ── Configuration ───────────────────────────────────────────────────────────── -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED /// @brief Installs the process-wide metric sink. /// @@ -291,7 +291,7 @@ void setMetricSink(Sink /*sink*/) { #endif // MORPH_OBSERVABILITY_DISABLED -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED /// @brief Installs the process-wide trace sink. /// diff --git a/src/ui/process_state.cpp b/src/ui/process_state.cpp index 65eae6705..f2f4cb5aa 100644 --- a/src/ui/process_state.cpp +++ b/src/ui/process_state.cpp @@ -116,7 +116,7 @@ LogState& logState() { } // namespace morph::log::detail -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED namespace morph::observe::detail { ObserveState& observeState() { diff --git a/tests/bench/bench_dispatch_instructions.cpp b/tests/bench/bench_dispatch_instructions.cpp index b8aa1dce1..7401f3ce1 100644 --- a/tests/bench/bench_dispatch_instructions.cpp +++ b/tests/bench/bench_dispatch_instructions.cpp @@ -71,7 +71,7 @@ #include #include -#if defined(__linux__) +#ifdef __linux__ #include #include #include @@ -109,7 +109,7 @@ constexpr int kWarmup = 200; constexpr int kCalls = 2000; constexpr std::size_t kPoolThreads = 4; -#if defined(__linux__) +#ifdef __linux__ /// A user-space retired-instruction counter that follows threads created after /// it is opened. diff --git a/tests/bench/bench_model_scaling.cpp b/tests/bench/bench_model_scaling.cpp index 5ceff1217..1b4fff429 100644 --- a/tests/bench/bench_model_scaling.cpp +++ b/tests/bench/bench_model_scaling.cpp @@ -71,7 +71,7 @@ struct Result { // Posts `body.total` tasks from `threads` producers via @p post(key, task) and // waits for them all. template -Result measure(std::size_t threads, Body const& body, PostFn&& post) { +Result measure(std::size_t threads, Body const& body, PostFn post) { std::atomic done{0}; std::atomic ready{0}; std::atomic go{false}; @@ -85,7 +85,7 @@ Result measure(std::size_t threads, Body const& body, PostFn&& post) { std::this_thread::yield(); } for (std::size_t i = 0; i < perProducer; ++i) { - std::uint64_t const key = ((p * perProducer + i) % kKeys) + 1; + std::uint64_t const key = (((p * perProducer) + i) % kKeys) + 1; post(key, [&done, spin = body.spin] { spinFor(spin); done.fetch_add(1, std::memory_order_relaxed); diff --git a/tests/compile_checks/observability_disabled_set_sink.cpp b/tests/compile_checks/observability_disabled_set_sink.cpp index a7cafeb19..6ab1d7a9e 100644 --- a/tests/compile_checks/observability_disabled_set_sink.cpp +++ b/tests/compile_checks/observability_disabled_set_sink.cpp @@ -9,7 +9,7 @@ #include void installSink() { -#if defined(PROBE_TRACE_SINK) +#ifdef PROBE_TRACE_SINK morph::observe::setTraceSink(morph::observe::TraceSink{}); #elif defined(PROBE_SCOPED_OVERRIDE) morph::observe::ScopedObserveOverride const guard; diff --git a/tests/offline_sqlite/test_sqlite_offline_queue.cpp b/tests/offline_sqlite/test_sqlite_offline_queue.cpp index a70fd372a..8f3559f3d 100644 --- a/tests/offline_sqlite/test_sqlite_offline_queue.cpp +++ b/tests/offline_sqlite/test_sqlite_offline_queue.cpp @@ -288,7 +288,7 @@ TEST_CASE("morph::offline::SqliteOfflineQueue: a dedup hit at capacity is reject removeDbFiles(dbPath); } -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("morph::offline::SqliteOfflineQueue: enqueue at maxDepth emits queueOverflow metric", "[sqlite][overflow][observability]") { morph::observe::ScopedObserveOverride guard; diff --git a/tests/test_backend_extra.cpp b/tests/test_backend_extra.cpp index 7b5690f7f..c1978ab40 100644 --- a/tests/test_backend_extra.cpp +++ b/tests/test_backend_extra.cpp @@ -171,7 +171,7 @@ TEST_CASE("morph::bridge::BridgeHandler destructor deregisters model cleanly", " // ── morph::backend::LocalBackend: observability (metrics + tracing) ───────── -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("morph::backend::LocalBackend: execute emits executeLatencyMs and toggles executeInFlight", "[backend][local][observability]") { morph::observe::ScopedObserveOverride guard; @@ -213,7 +213,7 @@ TEST_CASE("morph::backend::LocalBackend: execute emits executeLatencyMs and togg } #endif // MORPH_OBSERVABILITY_DISABLED -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("morph::backend::LocalBackend: an erroring action emits executeErrors", "[backend][local][observability]") { morph::observe::ScopedObserveOverride guard; morph::exec::ThreadPoolExecutor pool{2}; @@ -246,7 +246,7 @@ TEST_CASE("morph::backend::LocalBackend: an erroring action emits executeErrors" } #endif // MORPH_OBSERVABILITY_DISABLED -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("morph::backend::LocalBackend: registerModel/deregisterModel emit their counters", "[backend][local][observability]") { morph::observe::ScopedObserveOverride guard; @@ -271,7 +271,7 @@ TEST_CASE("morph::backend::LocalBackend: registerModel/deregisterModel emit thei } #endif // MORPH_OBSERVABILITY_DISABLED -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("morph::backend::LocalBackend: one execute produces exactly one beginSpan/endSpan pair", "[backend][local][observability]") { morph::observe::ScopedObserveOverride guard; @@ -473,7 +473,7 @@ TEST_CASE("morph::backend::LocalBackend: trackedPendingCount counts every call s REQUIRE(morph::testing::waitUntil([&] { return ran.load() == 3; })); } -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("morph::backend::LocalBackend: executeLatencyMs covers the time the handler ran", "[backend][local][observability]") { morph::observe::ScopedObserveOverride const guard; @@ -504,7 +504,7 @@ TEST_CASE("morph::backend::LocalBackend: executeLatencyMs covers the time the ha } #endif // MORPH_OBSERVABILITY_DISABLED -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("morph::backend::LocalBackend: a call that started with no metric sink emits no latency sample", "[backend][local][observability]") { morph::observe::ScopedObserveOverride const guard; @@ -592,7 +592,7 @@ TEST_CASE("morph::backend::LocalBackend: destruction requests stop on a Task han slot->finish(std::make_exception_ptr(std::runtime_error{"stopped"})); } -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("morph::backend::LocalBackend: a call cancelled while it waited behind a Task handler finishes as a failure", "[backend][local][observability]") { morph::observe::ScopedObserveOverride const guard; diff --git a/tests/test_file_offline_queue.cpp b/tests/test_file_offline_queue.cpp index f3ea0c966..89813f697 100644 --- a/tests/test_file_offline_queue.cpp +++ b/tests/test_file_offline_queue.cpp @@ -772,7 +772,7 @@ TEST_CASE("morph::offline::FileOfflineQueue: size() reflects live pending count" std::filesystem::remove(path); } -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("morph::offline::FileOfflineQueue: enqueue at maxDepth emits queueOverflow metric", "[file_queue][overflow][observability]") { morph::observe::ScopedObserveOverride guard; diff --git a/tests/test_observability.cpp b/tests/test_observability.cpp index 4d9ffb5ac..ce64e0267 100644 --- a/tests/test_observability.cpp +++ b/tests/test_observability.cpp @@ -15,7 +15,7 @@ // Every case here installs a sink or reads the process-wide state, which a build // with MORPH_ENABLE_OBSERVABILITY=OFF does not have. -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED using ObserveGuard = morph::observe::ScopedObserveOverride; diff --git a/tests/test_offline_queue.cpp b/tests/test_offline_queue.cpp index 5ed68aeac..f5e8781a1 100644 --- a/tests/test_offline_queue.cpp +++ b/tests/test_offline_queue.cpp @@ -278,7 +278,7 @@ TEST_CASE("morph::offline::OfflineQueueFullError: carries maxDepth and currentSi REQUIRE(what.find("5") != std::string::npos); } -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("morph::offline::InMemoryOfflineQueue: enqueue at maxDepth emits queueOverflow metric", "[queue][overflow][observability]") { morph::observe::ScopedObserveOverride guard; diff --git a/tests/test_push_channel.cpp b/tests/test_push_channel.cpp index a23a66e94..f92c86f7a 100644 --- a/tests/test_push_channel.cpp +++ b/tests/test_push_channel.cpp @@ -304,7 +304,7 @@ TEST_CASE("a_watch_whose_body_does_not_parse_is_refused", "[push][channel]") { CHECK(reply.callId == 3); } -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("post_above_envelope_cap_is_dropped_and_counted", "[push][channel]") { ::morph::observe::ScopedObserveOverride const restore; std::atomic oversize{0}; diff --git a/tests/test_reconnect_coordinator.cpp b/tests/test_reconnect_coordinator.cpp index 3b4f5a13c..2215823a8 100644 --- a/tests/test_reconnect_coordinator.cpp +++ b/tests/test_reconnect_coordinator.cpp @@ -274,7 +274,7 @@ TEST_CASE("ReconnectCoordinator: concurrent calls are serialised", "[reconnect][ REQUIRE(f.replayCalls == 2 * kPerThread); } -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("ReconnectCoordinator: onOnline emits reconnectAttempts per attempt and a tagged reconnectOutcome once", "[reconnect][observability]") { morph::observe::ScopedObserveOverride guard; @@ -306,7 +306,7 @@ TEST_CASE("ReconnectCoordinator: onOnline emits reconnectAttempts per attempt an } #endif // MORPH_OBSERVABILITY_DISABLED -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("ReconnectCoordinator: giving up tags reconnectOutcome as GaveUp", "[reconnect][observability]") { morph::observe::ScopedObserveOverride guard; Fakes f; diff --git a/tests/test_remote_extra.cpp b/tests/test_remote_extra.cpp index 9984cda38..259904a3c 100644 --- a/tests/test_remote_extra.cpp +++ b/tests/test_remote_extra.cpp @@ -507,7 +507,7 @@ TEST_CASE( // ── morph::backend::RemoteServer: observability (metrics + tracing) ────────── -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("morph::backend::RemoteServer: execute emits executeLatencyMs and toggles executeInFlight", "[remote][observability]") { morph::observe::ScopedObserveOverride guard; @@ -552,7 +552,7 @@ TEST_CASE("morph::backend::RemoteServer: execute emits executeLatencyMs and togg } #endif // MORPH_OBSERVABILITY_DISABLED -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("morph::backend::RemoteServer: executeLatencyMs measures the handler's run time", "[remote][observability]") { morph::observe::ScopedObserveOverride const guard; @@ -595,7 +595,7 @@ TEST_CASE("morph::backend::RemoteServer: executeLatencyMs measures the handler's } #endif // MORPH_OBSERVABILITY_DISABLED -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("morph::backend::RemoteServer: an erroring execute emits executeErrors", "[remote][observability]") { morph::observe::ScopedObserveOverride guard; morph::exec::ThreadPoolExecutor pool{2}; @@ -627,7 +627,7 @@ TEST_CASE("morph::backend::RemoteServer: an erroring execute emits executeErrors } #endif // MORPH_OBSERVABILITY_DISABLED -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("morph::backend::RemoteServer: register/deregister emit their counters", "[remote][observability]") { morph::observe::ScopedObserveOverride guard; morph::exec::ThreadPoolExecutor pool{2}; @@ -656,7 +656,7 @@ TEST_CASE("morph::backend::RemoteServer: register/deregister emit their counters } #endif // MORPH_OBSERVABILITY_DISABLED -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("morph::backend::RemoteServer: with no sink installed, register still works and metrics stay disabled", "[remote][observability]") { morph::observe::ScopedObserveOverride guard; @@ -673,7 +673,7 @@ TEST_CASE("morph::backend::RemoteServer: with no sink installed, register still } #endif // MORPH_OBSERVABILITY_DISABLED -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE( "morph::backend::RemoteServer: one execute produces exactly one beginSpan/endSpan pair with the caller's " "requestId", @@ -723,7 +723,7 @@ TEST_CASE( } #endif // MORPH_OBSERVABILITY_DISABLED -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("morph::backend::RemoteServer: endSpan reports ok=false for a failing execute", "[remote][observability]") { morph::observe::ScopedObserveOverride guard; morph::exec::ThreadPoolExecutor pool{2}; diff --git a/tests/test_shared_instances.cpp b/tests/test_shared_instances.cpp index 7537c8b47..79268dec5 100644 --- a/tests/test_shared_instances.cpp +++ b/tests/test_shared_instances.cpp @@ -1553,7 +1553,7 @@ TEST_CASE("deregistering a poisoned instance evicted from the directory tears it // instead would leave the first stretch of it -- the one between settling and // `endSpan` -- unpinned, and a regression that moved settling to just after // `endSpan` would sail through. -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("an attach racing a failed first action out of the dispatch is not handed the failed instance", "[shared-instances][backend]") { morph::exec::ThreadPoolExecutor pool{2}; @@ -1636,7 +1636,7 @@ TEST_CASE("releasing the last shared instance of a type empties its listInstance // The server half of the property above. `RemoteServer` kept its own copy of // this logic, so it needs its own proof that the directory learns the outcome // before anything that can attach gets to run. -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("the server does not hand out an instance between its first action failing and the directory learning of it", "[shared-instances][remote]") { morph::exec::ThreadPoolExecutor pool{2}; diff --git a/tests/test_sync_worker.cpp b/tests/test_sync_worker.cpp index ddc6e2772..5148766f6 100644 --- a/tests/test_sync_worker.cpp +++ b/tests/test_sync_worker.cpp @@ -355,7 +355,7 @@ TEST_CASE( REQUIRE(queue.drain().size() == 1); } -#if !defined(MORPH_OBSERVABILITY_DISABLED) +#ifndef MORPH_OBSERVABILITY_DISABLED TEST_CASE("morph::offline::SyncWorker: run() emits queueDepth with the pending count at drain", "[sync][observability]") { morph::observe::ScopedObserveOverride guard; From 588f20f8393445870dbaf09c9e6ab418f7910c5b Mon Sep 17 00:00:00 2001 From: Yaraslau Tamashevich Date: Fri, 27 Nov 2026 10:59:20 +0100 Subject: [PATCH 10/11] fix: clang-tidy and clang-format findings; pool-spin test no longer races the end of a spin Waiting for exactly one sleeping worker raced the spinner's own timeout, and Windows' coarse sleep clock stepped over that window. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT --- include/morph/core/backend.hpp | 1 + include/morph/core/bridge.hpp | 14 ++++++++------ include/morph/core/executor.hpp | 13 +++++++++++-- tests/bench/bench_dispatch_instructions.cpp | 15 ++++++++------- tests/bench/bench_handler_teardown.cpp | 16 +++++++++------- tests/bench/bench_model_scaling.cpp | 9 +++++---- .../observability_disabled_no_sink.cpp | 1 - tests/test_bridge_tracking.cpp | 6 +++--- tests/test_executor.cpp | 8 +++++--- 9 files changed, 50 insertions(+), 33 deletions(-) diff --git a/include/morph/core/backend.hpp b/include/morph/core/backend.hpp index d75538d94..bc86122b2 100644 --- a/include/morph/core/backend.hpp +++ b/include/morph/core/backend.hpp @@ -1602,6 +1602,7 @@ class LocalBackend : public detail::IBackend { /// Concurrent in-flight executes, for the `executeInFlight` metric: /// incremented when a run is admitted, decremented when it finishes. /// Absent when observability is compiled out, as nothing else reads it. + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes): runs bump it directly. std::atomic inFlight{0}; #endif diff --git a/include/morph/core/bridge.hpp b/include/morph/core/bridge.hpp index 5e9a22a17..228d086be 100644 --- a/include/morph/core/bridge.hpp +++ b/include/morph/core/bridge.hpp @@ -2563,13 +2563,13 @@ class Bridge { if (slot >= _handlers.size()) { return; } - auto const& entry = _handlers[slot]; - if (entry.owner_before(binding) || binding.owner_before(entry)) { + auto const entry = std::next(_handlers.begin(), static_cast(slot)); + if (entry->owner_before(binding) || binding.owner_before(*entry)) { return; } if (slot + 1 != _handlers.size()) { - _handlers[slot] = std::move(_handlers.back()); - if (auto const moved = _handlers[slot].lock()) { + *entry = std::move(_handlers.back()); + if (auto const moved = entry->lock()) { moved->trackedSlot = slot; } } @@ -2578,10 +2578,12 @@ class Bridge { /// @brief Rewrites every live binding's `trackedSlot` to its position in the list. void reindexHandlers() { - for (std::size_t slot = 0; slot < _handlers.size(); ++slot) { - if (auto const binding = _handlers[slot].lock()) { + std::size_t slot = 0; + for (auto const& weak : _handlers) { + if (auto const binding = weak.lock()) { binding->trackedSlot = slot; } + ++slot; } } diff --git a/include/morph/core/executor.hpp b/include/morph/core/executor.hpp index 0ee9dda1f..b256c4914 100644 --- a/include/morph/core/executor.hpp +++ b/include/morph/core/executor.hpp @@ -18,11 +18,15 @@ #include #include +// `#elifdef` is C++23 preprocessor syntax that nothing else in the tree relies on, so these chains keep `#elif +// defined`. +// NOLINTBEGIN(readability-use-concise-preprocessor-directives) #if defined(_M_X64) || defined(_M_IX86) || defined(__x86_64__) || defined(__i386__) #include #elif defined(_M_ARM64) #include #endif +// NOLINTEND(readability-use-concise-preprocessor-directives) #include "../attributes.hpp" #include "logger.hpp" @@ -44,6 +48,7 @@ namespace detail { /// so the hint's cost (about 10 cycles on some CPUs, 140 on others) changes how /// often the clock is read and not how long the loop runs. inline void cpuRelax() noexcept { +// NOLINTBEGIN(readability-use-concise-preprocessor-directives): see the include chain above. #if defined(_M_X64) || defined(_M_IX86) || defined(__x86_64__) || defined(__i386__) _mm_pause(); #elif defined(_M_ARM64) @@ -51,6 +56,7 @@ inline void cpuRelax() noexcept { #elif defined(__aarch64__) asm volatile("yield" ::: "memory"); #endif + // NOLINTEND(readability-use-concise-preprocessor-directives) } /// @brief A `core::async::IExecutor` over a morph executor: how a core-cpp @@ -296,14 +302,17 @@ class ThreadPoolExecutor : public IExecutor { // atomics only: the lock is not held and is not taken. void spin() const { auto const deadline = std::chrono::steady_clock::now() + _options.spinBeforeSleep; - do { + for (;;) { for (int i = 0; i < 16; ++i) { if (_queued.load(std::memory_order_acquire) != 0 || _stop.load(std::memory_order_acquire)) { return; } detail::cpuRelax(); } - } while (std::chrono::steady_clock::now() < deadline); + if (std::chrono::steady_clock::now() >= deadline) { + return; + } + } } // Blocks until a task can be taken or the pool is stopping and drained. diff --git a/tests/bench/bench_dispatch_instructions.cpp b/tests/bench/bench_dispatch_instructions.cpp index 7401f3ce1..d66df3485 100644 --- a/tests/bench/bench_dispatch_instructions.cpp +++ b/tests/bench/bench_dispatch_instructions.cpp @@ -72,12 +72,12 @@ #include #ifdef __linux__ - #include - #include - #include - #include +#include +#include +#include +#include - #include +#include #endif // External linkage so glaze's reflection can mangle the type names. @@ -128,6 +128,7 @@ class InstructionCounter { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) long const fd = ::syscall(SYS_perf_event_open, &attr, 0, -1, -1, 0); if (fd < 0) { + // NOLINTNEXTLINE(concurrency-mt-unsafe): called before the benchmark starts any thread. why = std::format("perf_event_open(PERF_COUNT_HW_INSTRUCTIONS) failed: {}", std::strerror(errno)); return std::nullopt; } @@ -275,8 +276,8 @@ int run(bool baseline, double budget) { return kExitSkipped; } - ::morph::exec::ThreadPoolExecutor pool{kPoolThreads, - ::morph::exec::PoolOptions{.spinBeforeSleep = std::chrono::microseconds{0}}}; + ::morph::exec::ThreadPoolExecutor pool{ + kPoolThreads, ::morph::exec::PoolOptions{.spinBeforeSleep = std::chrono::microseconds{0}}}; SleepingOwner owner; double perCall = 0.0; { diff --git a/tests/bench/bench_handler_teardown.cpp b/tests/bench/bench_handler_teardown.cpp index 961535440..49b035f4c 100644 --- a/tests/bench/bench_handler_teardown.cpp +++ b/tests/bench/bench_handler_teardown.cpp @@ -138,9 +138,10 @@ double destroyMicrosPerHandler(std::size_t count) { return std::chrono::duration(end - begin).count() / static_cast(count); } -double bestOf(int trials, std::size_t count) { +template +double bestOf(std::size_t count) { double best = 0.0; - for (int i = 0; i < trials; ++i) { + for (int i = 0; i < Trials; ++i) { double const micros = destroyMicrosPerHandler(count); best = (i == 0) ? micros : std::min(best, micros); } @@ -148,8 +149,8 @@ double bestOf(int trials, std::size_t count) { } int run(double maxRatio) { - double const small = bestOf(kSmallTrials, kSmall); - double const large = bestOf(kLargeTrials, kLarge); + double const small = bestOf(kSmall); + double const large = bestOf(kLarge); double const ratio = large / small; std::cout << std::format("destroy, {:>6} live handlers : {:8.2f} us per handler (best of {})\n", kSmall, small, kSmallTrials) @@ -159,9 +160,10 @@ int run(double maxRatio) { ratio, static_cast(kLarge) / static_cast(kSmall)); if (maxRatio > 0.0) { if (ratio > maxRatio) { - std::cout << std::format("FAIL: per-handler destroy cost grows {:.2f}x from {} to {} handlers, exceeds " - "--max-ratio={:.2f}\n", - ratio, kSmall, kLarge, maxRatio); + std::cout << std::format( + "FAIL: per-handler destroy cost grows {:.2f}x from {} to {} handlers, exceeds " + "--max-ratio={:.2f}\n", + ratio, kSmall, kLarge, maxRatio); return 1; } std::cout << std::format("ok: ratio {:.2f} within --max-ratio={:.2f}\n", ratio, maxRatio); diff --git a/tests/bench/bench_model_scaling.cpp b/tests/bench/bench_model_scaling.cpp index 1b4fff429..818b8f8b6 100644 --- a/tests/bench/bench_model_scaling.cpp +++ b/tests/bench/bench_model_scaling.cpp @@ -76,6 +76,7 @@ Result measure(std::size_t threads, Body const& body, PostFn post) { std::atomic ready{0}; std::atomic go{false}; std::vector producers; + producers.reserve(threads); std::size_t const perProducer = body.total / threads; std::size_t const expected = perProducer * threads; for (std::size_t p = 0; p < threads; ++p) { @@ -145,14 +146,14 @@ int run() { strandBase = strand.rate; poolBase = bare.rate; } - double const width = static_cast(threads); + auto const width = static_cast(threads); std::cout << std::format(" {} {:>14.0f} {:5.1f}% {:>14.0f} {:5.1f}%\n", threads, strand.rate, 100.0 * strand.rate / (width * strandBase), bare.rate, 100.0 * bare.rate / (width * poolBase)); if (!strand.exact || !bare.exact) { - std::cout << std::format("FAIL: T={} body {}: a task was lost, doubled or late (strands {}, pool {})\n", - threads, body.name, strand.exact ? "exact" : "WRONG", - bare.exact ? "exact" : "WRONG"); + std::cout << std::format( + "FAIL: T={} body {}: a task was lost, doubled or late (strands {}, pool {})\n", threads, body.name, + strand.exact ? "exact" : "WRONG", bare.exact ? "exact" : "WRONG"); ok = false; } } diff --git a/tests/compile_checks/observability_disabled_no_sink.cpp b/tests/compile_checks/observability_disabled_no_sink.cpp index 7bb310b68..cf33c7247 100644 --- a/tests/compile_checks/observability_disabled_no_sink.cpp +++ b/tests/compile_checks/observability_disabled_no_sink.cpp @@ -7,7 +7,6 @@ // changes for a caller. #include - #include bool emitEverything() { diff --git a/tests/test_bridge_tracking.cpp b/tests/test_bridge_tracking.cpp index b40cece68..996c52e68 100644 --- a/tests/test_bridge_tracking.cpp +++ b/tests/test_bridge_tracking.cpp @@ -95,8 +95,7 @@ struct Rig { } // namespace -TEST_CASE("Bridge tracking keeps survivors after removing the first, last and middle handler", - "[bridge][tracking]") { +TEST_CASE("Bridge tracking keeps survivors after removing the first, last and middle handler", "[bridge][tracking]") { Rig rig{7}; rig.destroy(0); rig.destroy(rig.bindings.size() - 1); @@ -128,7 +127,8 @@ TEST_CASE("Bridge tracking removes handlers correctly after a backend switch", " TEST_CASE("Bridge tracking survives removing every handler in a random order", "[bridge][tracking]") { Rig rig{40}; - std::mt19937 gen{12345}; + // A fixed seed, so a failing order can be replayed. + std::mt19937 gen{12345}; // NOLINT(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp) while (rig.bindings.size() > 1) { rig.destroy(std::uniform_int_distribution{0, rig.bindings.size() - 1}(gen)); if (rig.bindings.size() % 7 == 0) { diff --git a/tests/test_executor.cpp b/tests/test_executor.cpp index 1ca82d513..1e4adf2f4 100644 --- a/tests/test_executor.cpp +++ b/tests/test_executor.cpp @@ -61,7 +61,7 @@ TEST_CASE("morph::exec::ThreadPoolExecutor loses no task to a post racing a work ++posted; } REQUIRE(waitFor([&] { return ran.load() == posted; })); - std::this_thread::sleep_for(std::chrono::microseconds{20 + (burst % 7) * 40}); + std::this_thread::sleep_for(std::chrono::microseconds{20 + ((burst % 7) * 40)}); } } @@ -123,8 +123,10 @@ TEST_CASE("morph::exec::ThreadPoolExecutor with a spin runs blocking tasks poste options.spinBeforeSleep = 20000us; morph::exec::ThreadPoolExecutor pool{2, options}; for (int round = 0; round < 10; ++round) { - // One worker spins and the other sleeps. - REQUIRE(waitFor([&] { return pool.sleepingWorkers() == 1; })); + // At least one worker sleeps; the other spins or, once its spin has run + // out, sleeps too. Waiting for exactly one would race the end of the + // spin, and a coarse sleep clock (Windows) can step over that window. + REQUIRE(waitFor([&] { return pool.sleepingWorkers() >= 1; })); std::atomic arrived{0}; std::atomic met{0}; auto const task = [&] { From a654126d35b5825fba6e65706f698c3deaeea097 Mon Sep 17 00:00:00 2001 From: Yaraslau Tamashevich Date: Fri, 27 Nov 2026 12:33:19 +0100 Subject: [PATCH 11/11] ci: move the bridge.hpp allowlist line hint to where the line now is Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT --- scripts/branch_partial_allowlist.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/branch_partial_allowlist.json b/scripts/branch_partial_allowlist.json index 7aa93ffb6..ddfcb939b 100644 --- a/scripts/branch_partial_allowlist.json +++ b/scripts/branch_partial_allowlist.json @@ -109,7 +109,7 @@ }, { "file": "include/morph/core/bridge.hpp", - "line": 2221, + "line": 2227, "source": "if (_executeDeadline.count() <= 0 || !_timeoutScheduler) {", "reason": "The `!_timeoutScheduler` disjunct is unreachable by construction. `setExecuteDeadline` is the only writer of both `_executeDeadline` and `_timeoutScheduler`, and it creates `_timeoutScheduler` in the same call that makes `_executeDeadline` positive; nothing resets `_timeoutScheduler` to null afterwards (setting the deadline back to 0 only stops new calls from arming it, per that method's doc comment). So `_executeDeadline > 0 && !_timeoutScheduler` cannot hold once any positive deadline has been set." },