From 5e5505e5ca2f276922efd7c826c100413dd75296 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 13:17:09 -0600 Subject: [PATCH 1/4] server: engine_module, the C++ counterpart of continuum's ServiceModule (host-pool slice 2) From fable/host-pool (3cf8a4e0d, b1d78ee24, ae8b41925; Codex's reviews folded in), as its final form: an engine module owns its thread (std::jthread, stop by token), takes move-only jobs as tickets with a completion ring (a job system, not a promise library), wakes only on work or stop, publishes an immutable snapshot readers copy without waiting on its work, refuses typed (std::expected<..., module_refusal>), and a module's stop cancels queued jobs typed and releases their captures. No call sites yet: the server target moves to C++23 in the slice that wires the first module; only this test needs it now. Receipt (M5, Apple clang 21): test-server-module ok from the cmake build, and standalone at -std=c++23 -Wall -Wextra -Werror under -fsanitize=thread: ok, 0 reports. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tests/CMakeLists.txt | 6 + tests/test-server-module.cpp | 168 +++++++++++++++++++++++++ tools/server/server-module.h | 231 +++++++++++++++++++++++++++++++++++ 3 files changed, 405 insertions(+) create mode 100644 tests/test-server-module.cpp create mode 100644 tools/server/server-module.h diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index ee695dd04b09..e17215e0edf8 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -32,6 +32,12 @@ target_compile_features(test-server-learn-ledger PRIVATE cxx_std_17) add_test(NAME test-server-learn-ledger COMMAND test-server-learn-ledger) set_tests_properties(test-server-learn-ledger PROPERTIES LABELS "main") +# Model-free engine-module validator: own thread, move-only jobs, typed refusals, snapshots that never wait. +add_executable(test-server-module test-server-module.cpp) +target_compile_features(test-server-module PRIVATE cxx_std_23) +add_test(NAME test-server-module COMMAND test-server-module) +set_tests_properties(test-server-module PROPERTIES LABELS "main") + # Model-free validator: streams of frames and moving bytes by reference (rings, doorbell, memory_mover). add_executable(test-server-frames test-server-frames.cpp) target_compile_features(test-server-frames PRIVATE cxx_std_20) diff --git a/tests/test-server-module.cpp b/tests/test-server-module.cpp new file mode 100644 index 000000000000..9eae6efd7c9b --- /dev/null +++ b/tests/test-server-module.cpp @@ -0,0 +1,168 @@ +// what this catches: the engine module's contract (server-module.h) without a model: jobs run off the +// caller's thread, in order, writing results into storage their owner owns (no promise, no future); +// completion is a monotonic ticket counter a caller can wait on; a snapshot is read while the module +// works without waiting on it; a stop CANCELS: the job in flight finishes, every queued job is called +// cancelled once and its captures released, and the counter advances past every ticket so no waiter +// hangs (regression for Codex's review of fork 84aba863e: queued jobs were drained after a stop); the +// owner's capacity bounds the fixed ring with a typed refusal; the module measures itself. +#include "../tools/server/server-module.h" + +#include +#include +#include +#include + +static void require(bool condition, const char * message) { + if (!condition) { + std::cerr << "FAILED: " << message << '\n'; + std::exit(1); + } +} + +struct counter_state { + int64_t total = 0; +}; + +// A minimal module: it adds numbers off the caller's thread, writes each running total into the +// caller's slot, and publishes the total. +class adder final : public engine_module { +public: + explicit adder(size_t capacity) : engine_module("adder", counter_state{}, capacity) {} + ~adder() override { stop_and_join(); } + + // `out` is the owner's storage; the job writes there. + auto add(int64_t n, int64_t * out) { + return submit([this, n, out](job_state s) { + if (s == job_state::cancelled) { + *out = -1; + return; + } + counter_state next = *snapshot(); + next.total += n; + publish(next); + *out = next.total; + }); + } + + void stop() { stop_and_join(); } +}; + +static void jobs_write_into_owner_storage_in_order() { + adder module(128); + std::thread::id worker{}; + auto t = module.submit([&worker](job_state) { worker = std::this_thread::get_id(); }); + require(t.has_value(), "a running module takes a job"); + module.wait(*t); + require(worker != std::this_thread::get_id(), "the job ran on the module's own thread"); + std::vector totals(100, 0); // the owner's storage, allocated once + job_ticket last = 0; + for (int64_t n = 1; n <= 100; ++n) { + auto ticket = module.add(n, &totals[(size_t) n - 1]); + require(ticket.has_value(), "queued"); + last = *ticket; + } + module.wait(last); // one wait covers every earlier ticket: completion is in order + int64_t expected = 0; + for (int64_t n = 1; n <= 100; ++n) { + expected += n; + require(totals[(size_t) n - 1] == expected, "jobs ran in submission order, each result in the owner's slot"); + } + require(module.completed() == last, "the completion counter is the last ticket"); + require(module.snapshot()->total == 5050, "the published snapshot is the module's state"); + require(module.stats().done == 101 && module.stats().queued == 0, "the module counts what it ran"); +} + +static void a_snapshot_never_waits_on_work() { + adder module(4); + std::atomic release{false}; + auto blocker = module.submit([&](job_state) { while (!release.load()) { std::this_thread::yield(); } }); + require(blocker.has_value(), "queued"); + const auto t0 = std::chrono::steady_clock::now(); + for (int i = 0; i < 1000; ++i) { + require(module.snapshot()->total == 0, "a reader sees the last published state"); + } + require(std::chrono::steady_clock::now() - t0 < std::chrono::milliseconds(50), "1,000 snapshot reads during a long job never wait on it"); + release = true; + module.wait(*blocker); +} + +struct tracker { + std::atomic * alive; + explicit tracker(std::atomic * a) : alive(a) { ++*alive; } + tracker(const tracker &) = delete; + ~tracker() { --*alive; } +}; + +static void a_stop_cancels_queued_jobs_and_no_waiter_hangs() { + adder module(64); + std::atomic started{false}, release{false}; + std::atomic alive{0}; + int ran_value = 0; + auto running = module.submit([&](job_state s) { + if (s == job_state::cancelled) return; + started = true; + while (!release.load()) { std::this_thread::yield(); } + ran_value = 7; + }); + while (!started.load()) { std::this_thread::yield(); } + std::vector slots(3, 0); // the owner's storage for the queued jobs + job_ticket last = 0; + for (int i = 0; i < 3; ++i) { + auto held = std::make_shared(&alive); // a captured handle: released with its job + auto t = module.submit([held, slot = &slots[(size_t) i]](job_state s) { *slot = s == job_state::run ? 1 : -1; }); + require(t.has_value(), "queued behind the running job"); + last = *t; + } + require(alive.load() == 3, "the queued jobs hold their captures"); + std::thread waiter([&] { module.wait(last); }); // must return even though these never run + std::thread stopper([&] { module.stop(); }); + int probes = 0; + while (true) { + auto probe = module.submit([](job_state) {}); + if (!probe && probe.error() == module_refusal::full) { + std::this_thread::yield(); // the ring filled before the stop landed: the stop is coming + continue; + } + if (!probe) { + require(probe.error() == module_refusal::stopping, "a stopping module refuses typed"); + break; + } + ++probes; + } + release = true; + stopper.join(); + waiter.join(); + require(ran_value == 7, "the job in flight finishes"); + for (int v : slots) { + require(v == -1, "every queued job is called cancelled once and marks its owner's slot"); + } + require(alive.load() == 0, "a cancelled job's captures are released by the stop"); + require(module.stats().cancelled == (uint64_t) (3 + probes), "every cancelled job is counted"); + require(module.stats().refused >= 1, "refusals are counted"); + require(module.stats().done == 1, "nothing queued ran after the stop"); + require(module.completed() == *running + 3 + (uint64_t) probes, "the counter advanced past every ticket"); +} + +static void the_owners_capacity_bounds_the_ring() { + adder module(2); + std::atomic started{false}, release{false}; + auto running = module.submit([&](job_state) { started = true; while (!release.load()) { std::this_thread::yield(); } }); + while (!started.load()) { std::this_thread::yield(); } + int64_t a = 0, b = 0, c = 0; + require(module.add(1, &a).has_value() && module.add(2, &b).has_value(), "two may wait"); + auto third = module.add(3, &c); + require(!third && third.error() == module_refusal::full, "a full ring refuses typed, never grows"); + require(module.stats().refused == 1, "the refusal is counted"); + release = true; + module.wait(*running + 2); + require(a == 1 && b == 3 && c == 0, "the queued jobs ran; the refused one never did"); +} + +int main() { + jobs_write_into_owner_storage_in_order(); + a_snapshot_never_waits_on_work(); + a_stop_cancels_queued_jobs_and_no_waiter_hangs(); + the_owners_capacity_bounds_the_ring(); + std::cout << "test-server-module: ok\n"; + return 0; +} diff --git a/tools/server/server-module.h b/tools/server/server-module.h new file mode 100644 index 000000000000..da060f66d484 --- /dev/null +++ b/tools/server/server-module.h @@ -0,0 +1,231 @@ +#pragma once + +// Continuum fork: the engine-side module, the C++ counterpart of continuum's Rust ServiceModule +// (CBAR-SUBSTRATE-ARCHITECTURE.md), shaped like a game engine's job system, not a promise library. +// +// One owner per concern: it owns its thread and a FIXED ring of jobs sized by its owner, and publishes +// its state as an immutable snapshot readers copy without waiting on its work. A job writes its result +// into storage its OWNER already owns (a frame slot, the arena, a field of the owner); nothing is +// allocated to carry a result back. Completion is a monotonic counter: `submit` returns a ticket (the +// job's sequence number), `completed()` is how many have finished, and a caller that must block uses +// `wait(ticket)`, an atomic wait on that counter (a futex on the platforms we run), never a future. +// +// A job is called exactly once: with `job_state::run` to do its work, or with `job_state::cancelled` +// when a stop dropped it, so it can mark its owner's slot. Stop cancels: the job in flight finishes, +// every queued job is called cancelled and destroyed (its captures released), and the counter still +// advances past every ticket, so no waiter waits forever. The worker sleeps until there is work or a +// stop: never a poll, never a timer. Jobs capture a pointer to their owner's storage, not payloads: +// memory-holding data is a pool-charged handle (host_bytes, parked_seq), never a copy. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// An immutable value published by one writer and read by many: a reader takes a pointer, never a lock +// held across the writer's work. Swapping the pointer is the only critical section. +template +class snapshot_cell { +public: + explicit snapshot_cell(T initial) : current_(std::make_shared(std::move(initial))) {} + + std::shared_ptr read() const { + std::scoped_lock lock(mutex_); + return current_; + } + + void publish(T next) { + auto fresh = std::make_shared(std::move(next)); + std::scoped_lock lock(mutex_); + current_.swap(fresh); + } + +private: + mutable std::mutex mutex_; + std::shared_ptr current_; +}; + +// Why a module did not take a job. +enum class module_refusal : uint8_t { + stopping, // the module is shutting down: the job was not queued + full, // the owner's capacity is reached: the job was not queued +}; + +// How a job is called: once, either to run or because a stop dropped it. +enum class job_state : uint8_t { run, cancelled }; + +// A job's sequence number; it is complete once completed() >= its ticket. +using job_ticket = uint64_t; + +// What every module measures about itself. +struct module_stats { + uint64_t queued = 0; // jobs waiting now + uint64_t done = 0; // jobs run since start + uint64_t cancelled = 0; // queued jobs a stop dropped + uint64_t refused = 0; // submissions refused (stopping or full) + uint64_t busy_us = 0; // time spent in jobs since start + uint64_t max_job_us = 0; // the longest single job since start +}; + +template +class engine_module { +public: + using job = std::function; + + // `capacity`: how many jobs may wait, from what the owner owns (never zero). The ring is allocated + // once, here. + engine_module(std::string name, Snapshot initial, size_t capacity) + : name_(std::move(name)), snapshot_(std::move(initial)), ring_(std::max(capacity, 1)), + worker_([this](std::stop_token stop) { run(stop); }) {} + + engine_module(const engine_module &) = delete; + engine_module & operator=(const engine_module &) = delete; + + // A module's own destructor calls stop_and_join() first: its members die before this base's + // destructor runs, so a job still running would otherwise touch them. Enforced here, loudly. + virtual ~engine_module() { + if (worker_.joinable()) { + std::fprintf(stderr, "engine_module '%s': the derived destructor must call stop_and_join() first\n", name_.c_str()); + std::abort(); + } + } + + const std::string & name() const { return name_; } + + // Queue `j`; its ticket is complete once completed() reaches it. + std::expected submit(job j) { + job_ticket ticket; + { + std::scoped_lock lock(mutex_); + if (worker_.get_stop_token().stop_requested()) { + stats_.refused++; + return std::unexpected(module_refusal::stopping); + } + if (count_ == ring_.size()) { + stats_.refused++; + return std::unexpected(module_refusal::full); + } + ring_[(head_ + count_) % ring_.size()] = std::move(j); + count_++; + ticket = ++submitted_; + stats_.queued = count_; + } + wake_.notify_one(); + return ticket; + } + + // How many jobs have finished (run or cancelled), in submission order. + uint64_t completed() const { return completed_.load(std::memory_order_acquire); } + + // Block until `ticket` is complete: an atomic wait on the completion counter. + void wait(job_ticket ticket) const { + for (uint64_t seen = completed(); seen < ticket; seen = completed()) { + completed_.wait(seen, std::memory_order_acquire); + } + } + + std::shared_ptr snapshot() const { return snapshot_.read(); } + + module_stats stats() const { + std::scoped_lock lock(mutex_); + return stats_; + } + +protected: + void publish(Snapshot next) { snapshot_.publish(std::move(next)); } + + // Stop taking work, let the job in flight finish, join the worker; every job still queued is called + // cancelled and destroyed, and the counter advances past it. Idempotent. Every module's destructor + // calls it before anything else. + void stop_and_join() { + { + std::scoped_lock lock(mutex_); + worker_.request_stop(); + } + wake_.notify_all(); + if (worker_.joinable()) { + worker_.join(); + } + cancel_queued(); + } + +private: + void finish_one() { + completed_.fetch_add(1, std::memory_order_release); + completed_.notify_all(); + } + + void run(std::stop_token stop) { + while (true) { + job j; + { + std::unique_lock lock(mutex_); + // wakes on work or on stop. A stop wins over queued work: stop_and_join cancels it. + wake_.wait(lock, stop, [this] { return count_ > 0; }); + if (stop.stop_requested()) { + return; + } + j = std::move(ring_[head_]); + head_ = (head_ + 1) % ring_.size(); + count_--; + stats_.queued = count_; + } + const auto started = std::chrono::steady_clock::now(); + j(job_state::run); + j = nullptr; // its captures are released before completion is announced + const auto us = (uint64_t) std::chrono::duration_cast( + std::chrono::steady_clock::now() - started).count(); + { + std::scoped_lock lock(mutex_); + stats_.done++; + stats_.busy_us += us; + stats_.max_job_us = std::max(stats_.max_job_us, us); + } + finish_one(); + } + } + + // After the worker joined: every job still queued is called cancelled, destroyed, and counted. + void cancel_queued() { + std::vector dropped; + { + std::scoped_lock lock(mutex_); + dropped.reserve(count_); + for (; count_ > 0; count_--) { + dropped.push_back(std::move(ring_[head_])); + head_ = (head_ + 1) % ring_.size(); + } + stats_.cancelled += dropped.size(); + stats_.queued = 0; + } + for (auto & j : dropped) { + j(job_state::cancelled); + j = nullptr; + finish_one(); + } + } + + std::string name_; + snapshot_cell snapshot_; + mutable std::mutex mutex_; + std::condition_variable_any wake_; + std::vector ring_; + size_t head_ = 0; + size_t count_ = 0; + job_ticket submitted_ = 0; + std::atomic completed_{0}; + module_stats stats_; + std::jthread worker_; // last: started after every member it uses exists +}; From c7d2c1c50e620278aecff84e9a605429d06570ad Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 13:26:20 -0600 Subject: [PATCH 2/4] engine_module: jobs stored inline and move-only, a throwing call is a typed fault, snapshots read with no lock (Codex's review of #135) - inplace_job: a move-only callable stored INLINE in the ring (a fixed capture size, checked at compile time; nothrow-move; never a heap allocation, never a copyable target). std::function is gone. - A run or cancel call that throws is contained: recorded as module_fault {ticket, during, what} and counted in stats.faulted; its ticket still completes and the worker lives on (it terminated before). - snapshot_cell is a seqlock over atomic words: the writer never waits; a reader copies by value and retries only when a publish overlapped its copy; Snapshot must be trivially copyable (counters and ids), enforced. snapshot() returns the value, not a shared_ptr behind a mutex. - cancel_queued takes one job at a time with no allocation and no lock held across a call. Tests (one regression each): a throwing job is a typed fault, the next job runs, the faulted ticket completes; a throwing cancel during stop is typed and no waiter hangs; a job owning a unique_ptr queues, runs once and releases it; a reader racing 200,000 publishes never sees a torn value. Receipt (M5, Apple clang 21): test-server-module ok; -std=c++23 -Wall -Wextra -Werror under -fsanitize=thread 3 of 3 ok, under -fsanitize=address,undefined ok. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tests/test-server-module.cpp | 72 ++++++++++- tools/server/server-module.h | 240 +++++++++++++++++++++++++++-------- 2 files changed, 259 insertions(+), 53 deletions(-) diff --git a/tests/test-server-module.cpp b/tests/test-server-module.cpp index 9eae6efd7c9b..2018475aa2f5 100644 --- a/tests/test-server-module.cpp +++ b/tests/test-server-module.cpp @@ -7,6 +7,8 @@ // owner's capacity bounds the fixed ring with a typed refusal; the module measures itself. #include "../tools/server/server-module.h" +#include + #include #include #include @@ -37,7 +39,7 @@ class adder final : public engine_module { *out = -1; return; } - counter_state next = *snapshot(); + counter_state next = snapshot(); next.total += n; publish(next); *out = next.total; @@ -68,7 +70,7 @@ static void jobs_write_into_owner_storage_in_order() { require(totals[(size_t) n - 1] == expected, "jobs ran in submission order, each result in the owner's slot"); } require(module.completed() == last, "the completion counter is the last ticket"); - require(module.snapshot()->total == 5050, "the published snapshot is the module's state"); + require(module.snapshot().total == 5050, "the published snapshot is the module's state"); require(module.stats().done == 101 && module.stats().queued == 0, "the module counts what it ran"); } @@ -79,7 +81,7 @@ static void a_snapshot_never_waits_on_work() { require(blocker.has_value(), "queued"); const auto t0 = std::chrono::steady_clock::now(); for (int i = 0; i < 1000; ++i) { - require(module.snapshot()->total == 0, "a reader sees the last published state"); + require(module.snapshot().total == 0, "a reader sees the last published state"); } require(std::chrono::steady_clock::now() - t0 < std::chrono::milliseconds(50), "1,000 snapshot reads during a long job never wait on it"); release = true; @@ -158,11 +160,75 @@ static void the_owners_capacity_bounds_the_ring() { require(a == 1 && b == 3 && c == 0, "the queued jobs ran; the refused one never did"); } +// what this catches (Codex on #135): a run or cancel call that threw escaped the worker (std::terminate) and +// left later tickets unfinished +static void a_throwing_job_is_a_typed_fault_and_the_worker_lives() { + adder module(8); + auto bad = module.submit([](job_state) { throw std::runtime_error("job failed"); }); + int64_t out = 0; + auto good = module.add(7, &out); + require(bad.has_value() && good.has_value(), "both queued"); + module.wait(*good); + require(out == 7, "the job after a fault still runs"); + require(module.completed() >= *bad, "the faulted ticket completed"); + const auto f = module.last_fault(); + require(module.stats().faulted == 1 && f.ticket == *bad && f.during == job_state::run && f.what == "job failed", + "the fault is typed and named by its ticket"); + + // a cancel call that throws, during stop + std::atomic release{false}; + auto blocker = module.submit([&](job_state) { while (!release.load()) { std::this_thread::yield(); } }); + auto doomed = module.submit([](job_state s) { if (s == job_state::cancelled) throw std::logic_error("cancel failed"); }); + require(blocker.has_value() && doomed.has_value(), "queued"); + std::thread stopper([&] { module.stop(); }); + release = true; + stopper.join(); + require(module.completed() >= *doomed, "no waiter hangs on a ticket whose cancel threw"); + require(module.stats().faulted == 2 && module.last_fault().during == job_state::cancelled, "a cancel fault is typed too"); +} + +// what this catches (Codex on #135): std::function required a copyable target; a job owning a move-only +// handle must queue, run once and release it +static void a_move_only_job_runs_once_and_releases_its_capture() { + adder module(4); + auto handle = std::make_unique(41); + int value = 0; + auto t = module.submit([h = std::move(handle), &value](job_state s) mutable { + if (s == job_state::run) value = *h + 1; + }); + require(t.has_value(), "a move-only capture queues"); + module.wait(*t); + require(value == 42, "it ran once with its owned handle"); +} + +// what this catches (Codex on #135): a reader took the publish mutex; now a reader racing a writer must +// see only whole published values, and never wait on it +struct pair_state { uint64_t a = 0, b = 0; }; +static void a_snapshot_read_is_never_torn() { + snapshot_cell cell(pair_state{}); + std::atomic stop{false}; + std::thread writer([&] { + for (uint64_t i = 1; i <= 200000; ++i) cell.publish(pair_state{ i, ~i }); + stop = true; + }); + uint64_t reads = 0; + while (!stop.load()) { + const auto v = cell.read(); + require(v.b == ~v.a || (v.a == 0 && v.b == 0), "a read is one whole published value"); + reads++; + } + writer.join(); + require(reads > 0, "the reader ran alongside the writer"); +} + int main() { jobs_write_into_owner_storage_in_order(); a_snapshot_never_waits_on_work(); a_stop_cancels_queued_jobs_and_no_waiter_hangs(); the_owners_capacity_bounds_the_ring(); + a_throwing_job_is_a_typed_fault_and_the_worker_lives(); + a_move_only_job_runs_once_and_releases_its_capture(); + a_snapshot_read_is_never_torn(); std::cout << "test-server-module: ok\n"; return 0; } diff --git a/tools/server/server-module.h b/tools/server/server-module.h index da060f66d484..d78f58b6604c 100644 --- a/tools/server/server-module.h +++ b/tools/server/server-module.h @@ -4,57 +4,156 @@ // (CBAR-SUBSTRATE-ARCHITECTURE.md), shaped like a game engine's job system, not a promise library. // // One owner per concern: it owns its thread and a FIXED ring of jobs sized by its owner, and publishes -// its state as an immutable snapshot readers copy without waiting on its work. A job writes its result -// into storage its OWNER already owns (a frame slot, the arena, a field of the owner); nothing is -// allocated to carry a result back. Completion is a monotonic counter: `submit` returns a ticket (the -// job's sequence number), `completed()` is how many have finished, and a caller that must block uses -// `wait(ticket)`, an atomic wait on that counter (a futex on the platforms we run), never a future. +// its state as a snapshot readers copy with no lock. A job writes its result into storage its OWNER +// already owns (a frame slot, the arena, a field of the owner); nothing is allocated to carry a result +// back, and a job itself is stored inline in the ring (a fixed capture size, move-only, never a heap +// allocation). Completion is a monotonic counter: `submit` returns a ticket (the job's sequence number), +// `completed()` is how many have finished, and a caller that must block uses `wait(ticket)`, an atomic +// wait on that counter (a futex on the platforms we run), never a future. // // A job is called exactly once: with `job_state::run` to do its work, or with `job_state::cancelled` -// when a stop dropped it, so it can mark its owner's slot. Stop cancels: the job in flight finishes, -// every queued job is called cancelled and destroyed (its captures released), and the counter still -// advances past every ticket, so no waiter waits forever. The worker sleeps until there is work or a -// stop: never a poll, never a timer. Jobs capture a pointer to their owner's storage, not payloads: -// memory-holding data is a pool-charged handle (host_bytes, parked_seq), never a copy. +// when a stop dropped it, so it can mark its owner's slot. A call that throws is contained: the fault is +// recorded typed against its ticket, the ticket still completes, and the worker lives on. Stop cancels: +// the job in flight finishes, every queued job is called cancelled and destroyed (its captures released), +// and the counter still advances past every ticket, so no waiter waits forever. The worker sleeps until +// there is work or a stop: never a poll, never a timer. Jobs capture a pointer to their owner's storage, +// not payloads: memory-holding data is a pool-charged handle (host_bytes, parked_seq), never a copy. #include #include #include #include +#include #include #include #include +#include +#include #include -#include -#include #include +#include #include #include #include +#include #include #include -// An immutable value published by one writer and read by many: a reader takes a pointer, never a lock -// held across the writer's work. Swapping the pointer is the only critical section. +// A value published by one writer and read by many, with no lock anywhere (Codex on #135: a mutex let a +// reader wait on a publication). A seqlock over atomic words: the writer never waits; a reader copies the +// words and retries only when a publish overlapped its copy. A snapshot is counters and ids, so it is +// trivially copyable, enforced. template class snapshot_cell { + static_assert(std::is_trivially_copyable_v, "a snapshot is counters and ids, copied by value"); + static constexpr size_t WORDS = (sizeof(T) + sizeof(uint64_t) - 1) / sizeof(uint64_t); + public: - explicit snapshot_cell(T initial) : current_(std::make_shared(std::move(initial))) {} + explicit snapshot_cell(const T & initial) { publish(initial); } - std::shared_ptr read() const { - std::scoped_lock lock(mutex_); - return current_; + T read() const { + uint64_t buf[WORDS]; + while (true) { + const uint64_t before = seq_.load(std::memory_order_acquire); + if (before & 1) { + continue; // a publish is mid-copy: read again, never wait on it + } + for (size_t i = 0; i < WORDS; ++i) { + buf[i] = words_[i].load(std::memory_order_relaxed); + } + std::atomic_thread_fence(std::memory_order_acquire); + if (seq_.load(std::memory_order_relaxed) == before) { + T out; + std::memcpy(&out, buf, sizeof(T)); + return out; + } + } } - void publish(T next) { - auto fresh = std::make_shared(std::move(next)); - std::scoped_lock lock(mutex_); - current_.swap(fresh); + // One writer at a time (the module's worker, or its owner before the worker runs). + void publish(const T & next) { + uint64_t buf[WORDS] = {}; + std::memcpy(buf, &next, sizeof(T)); + const uint64_t s = seq_.load(std::memory_order_relaxed); + seq_.store(s + 1, std::memory_order_relaxed); + std::atomic_thread_fence(std::memory_order_release); + for (size_t i = 0; i < WORDS; ++i) { + words_[i].store(buf[i], std::memory_order_relaxed); + } + seq_.store(s + 2, std::memory_order_release); } private: - mutable std::mutex mutex_; - std::shared_ptr current_; + std::atomic seq_{0}; + std::atomic words_[WORDS] = {}; +}; + +// A move-only callable stored INLINE (Codex on #135: std::function requires a copyable target and may +// allocate). The capture must fit `Bytes`, checked at compile time; nothing is ever allocated to hold it. +template +class inplace_job { +public: + inplace_job() = default; + + template > + requires(!std::is_same_v && std::is_invocable_v) + inplace_job(F && f) { // implicit, like the lambda handed to submit() + static_assert(sizeof(D) <= Bytes, "a job captures pointers to its owner's storage, not payloads: it must fit"); + static_assert(alignof(D) <= alignof(std::max_align_t), "a job's capture must not be over-aligned"); + static_assert(std::is_nothrow_move_constructible_v, "a job moves between ring slots without throwing"); + ::new (static_cast(store_)) D(std::forward(f)); + ops_ = &ops_for; + } + + inplace_job(inplace_job && o) noexcept { take(o); } + inplace_job & operator=(inplace_job && o) noexcept { + if (this != &o) { + reset(); + take(o); + } + return *this; + } + inplace_job(const inplace_job &) = delete; + inplace_job & operator=(const inplace_job &) = delete; + ~inplace_job() { reset(); } + + explicit operator bool() const { return ops_ != nullptr; } + void operator()(Args... args) { ops_->invoke(store_, args...); } + + void reset() { + if (ops_) { + ops_->destroy(store_); + ops_ = nullptr; + } + } + +private: + struct ops { + void (*invoke)(std::byte *, Args...); + void (*move)(std::byte * to, std::byte * from) noexcept; + void (*destroy)(std::byte *) noexcept; + }; + template + static constexpr ops ops_for = { + [](std::byte * s, Args... a) { (*std::launder(reinterpret_cast(s)))(a...); }, + [](std::byte * to, std::byte * from) noexcept { + D * src = std::launder(reinterpret_cast(from)); + ::new (static_cast(to)) D(std::move(*src)); + src->~D(); + }, + [](std::byte * s) noexcept { std::launder(reinterpret_cast(s))->~D(); }, + }; + + void take(inplace_job & o) noexcept { + if (o.ops_) { + o.ops_->move(store_, o.store_); + ops_ = o.ops_; + o.ops_ = nullptr; + } + } + + alignas(std::max_align_t) std::byte store_[Bytes]; + const ops * ops_ = nullptr; }; // Why a module did not take a job. @@ -75,19 +174,29 @@ struct module_stats { uint64_t done = 0; // jobs run since start uint64_t cancelled = 0; // queued jobs a stop dropped uint64_t refused = 0; // submissions refused (stopping or full) + uint64_t faulted = 0; // calls (run or cancel) that threw: contained, their tickets still completed uint64_t busy_us = 0; // time spent in jobs since start uint64_t max_job_us = 0; // the longest single job since start }; -template +// The most recent call that threw (Codex on #135: a throwing job terminated the worker and left tickets +// unfinished). The worker survives; the fault is typed and named by its ticket. +struct module_fault { + job_ticket ticket = 0; // 0: none yet + job_state during = job_state::run; + std::string what; +}; + +// `JobBytes`: the inline capture size of every job of this module, fixed at compile time. +template class engine_module { public: - using job = std::function; + using job = inplace_job; // `capacity`: how many jobs may wait, from what the owner owns (never zero). The ring is allocated // once, here. - engine_module(std::string name, Snapshot initial, size_t capacity) - : name_(std::move(name)), snapshot_(std::move(initial)), ring_(std::max(capacity, 1)), + engine_module(std::string name, const Snapshot & initial, size_t capacity) + : name_(std::move(name)), snapshot_(initial), ring_(std::max(capacity, 1)), worker_([this](std::stop_token stop) { run(stop); }) {} engine_module(const engine_module &) = delete; @@ -117,9 +226,9 @@ class engine_module { stats_.refused++; return std::unexpected(module_refusal::full); } - ring_[(head_ + count_) % ring_.size()] = std::move(j); - count_++; ticket = ++submitted_; + ring_[(head_ + count_) % ring_.size()] = slot{ std::move(j), ticket }; + count_++; stats_.queued = count_; } wake_.notify_one(); @@ -136,15 +245,21 @@ class engine_module { } } - std::shared_ptr snapshot() const { return snapshot_.read(); } + // The last published state, copied with no lock. + Snapshot snapshot() const { return snapshot_.read(); } module_stats stats() const { std::scoped_lock lock(mutex_); return stats_; } + module_fault last_fault() const { + std::scoped_lock lock(mutex_); + return fault_; + } + protected: - void publish(Snapshot next) { snapshot_.publish(std::move(next)); } + void publish(const Snapshot & next) { snapshot_.publish(next); } // Stop taking work, let the job in flight finish, join the worker; every job still queued is called // cancelled and destroyed, and the counter advances past it. Idempotent. Every module's destructor @@ -162,14 +277,36 @@ class engine_module { } private: + struct slot { + job fn; + job_ticket ticket = 0; + }; + void finish_one() { completed_.fetch_add(1, std::memory_order_release); completed_.notify_all(); } + // A job's call, contained: whatever it throws is recorded typed against its ticket; the worker lives on. + void call(job & j, job_state s, job_ticket ticket) { + try { + j(s); + } catch (const std::exception & e) { + record_fault(ticket, s, e.what()); + } catch (...) { + record_fault(ticket, s, "a non-standard exception"); + } + } + + void record_fault(job_ticket ticket, job_state s, const char * what) { + std::scoped_lock lock(mutex_); + stats_.faulted++; + fault_ = module_fault{ ticket, s, what }; + } + void run(std::stop_token stop) { while (true) { - job j; + slot s; { std::unique_lock lock(mutex_); // wakes on work or on stop. A stop wins over queued work: stop_and_join cancels it. @@ -177,14 +314,14 @@ class engine_module { if (stop.stop_requested()) { return; } - j = std::move(ring_[head_]); + s = std::move(ring_[head_]); head_ = (head_ + 1) % ring_.size(); count_--; stats_.queued = count_; } const auto started = std::chrono::steady_clock::now(); - j(job_state::run); - j = nullptr; // its captures are released before completion is announced + call(s.fn, job_state::run, s.ticket); + s.fn.reset(); // its captures are released before completion is announced const auto us = (uint64_t) std::chrono::duration_cast( std::chrono::steady_clock::now() - started).count(); { @@ -197,22 +334,24 @@ class engine_module { } } - // After the worker joined: every job still queued is called cancelled, destroyed, and counted. + // After the worker joined, this thread is the ring's only user: each queued job is taken, called + // cancelled (contained), destroyed and counted; no allocation, no lock held across a call. void cancel_queued() { - std::vector dropped; - { - std::scoped_lock lock(mutex_); - dropped.reserve(count_); - for (; count_ > 0; count_--) { - dropped.push_back(std::move(ring_[head_])); + while (true) { + slot s; + { + std::scoped_lock lock(mutex_); + if (count_ == 0) { + stats_.queued = 0; + return; + } + s = std::move(ring_[head_]); head_ = (head_ + 1) % ring_.size(); + count_--; + stats_.cancelled++; } - stats_.cancelled += dropped.size(); - stats_.queued = 0; - } - for (auto & j : dropped) { - j(job_state::cancelled); - j = nullptr; + call(s.fn, job_state::cancelled, s.ticket); + s.fn.reset(); finish_one(); } } @@ -221,11 +360,12 @@ class engine_module { snapshot_cell snapshot_; mutable std::mutex mutex_; std::condition_variable_any wake_; - std::vector ring_; + std::vector ring_; size_t head_ = 0; size_t count_ = 0; job_ticket submitted_ = 0; std::atomic completed_{0}; module_stats stats_; + module_fault fault_; std::jthread worker_; // last: started after every member it uses exists }; From 6df7316818a333baee2540e036a329de00dd4e1c Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 13:42:04 -0600 Subject: [PATCH 3/4] engine_module: each job ends in a typed outcome in its owner's storage, no string; empty jobs refused; the seqlock is described as it is (Codex's re-review of #135; Joel: strings, allocation and locking are the enemy) - job_outcome {pending, ran, run_faulted, cancelled, cancel_faulted}: submit(job, &outcome) takes the owner's storage and the module writes how the job ended there. Nothing is lost when several jobs fault, and the catch allocates nothing and cannot throw (module_fault and its std::string are gone; job_outcome_name renders text only at an export edge). stats.faulted is an atomic counter. - submit refuses an empty or moved-from job (module_refusal::empty): it is never queued or called. - snapshot_cell: reads take no lock but are NOT wait-free; a writer descheduled mid-publish stalls readers, who yield after a few retries instead of spinning. Said so in the header. - stopping(): owners (and tests) observe a requested stop. Tests: two faulting jobs each keep their own run_faulted while the next job runs; a throwing cancel during stop ends cancel_faulted and no waiter hangs (the blocker is released only after the stop is observed, so the run is deterministic); an empty and a moved-from job are refused typed while the moved-to job runs. Receipt (M5, Apple clang 21): -std=c++23 -Wall -Wextra -Werror under -fsanitize=thread 5 of 5 ok and under -fsanitize=address,undefined 5 of 5 ok. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tests/test-server-module.cpp | 48 +++++++++++----- tools/server/server-module.h | 107 ++++++++++++++++++++++------------- 2 files changed, 102 insertions(+), 53 deletions(-) diff --git a/tests/test-server-module.cpp b/tests/test-server-module.cpp index 2018475aa2f5..50ef0dcaa195 100644 --- a/tests/test-server-module.cpp +++ b/tests/test-server-module.cpp @@ -160,31 +160,50 @@ static void the_owners_capacity_bounds_the_ring() { require(a == 1 && b == 3 && c == 0, "the queued jobs ran; the refused one never did"); } -// what this catches (Codex on #135): a run or cancel call that threw escaped the worker (std::terminate) and -// left later tickets unfinished -static void a_throwing_job_is_a_typed_fault_and_the_worker_lives() { +// what this catches (Codex on #135): a run or cancel call that threw escaped the worker (std::terminate), one +// "last fault" slot overwrote earlier failures, and recording the text allocated inside the catch. Now each job +// ends in a typed outcome in its OWNER's storage, and the worker lives on. +static void a_throwing_job_ends_typed_in_its_owners_storage() { adder module(8); - auto bad = module.submit([](job_state) { throw std::runtime_error("job failed"); }); + std::atomic first{job_outcome::pending}, second{job_outcome::pending}, after{job_outcome::pending}; + auto bad1 = module.submit([](job_state) { throw std::runtime_error("job failed"); }, &first); + auto bad2 = module.submit([](job_state) { throw 7; }, &second); int64_t out = 0; - auto good = module.add(7, &out); - require(bad.has_value() && good.has_value(), "both queued"); + auto good = module.submit([&out](job_state s) { if (s == job_state::run) out = 7; }, &after); + require(bad1.has_value() && bad2.has_value() && good.has_value(), "all queued"); module.wait(*good); - require(out == 7, "the job after a fault still runs"); - require(module.completed() >= *bad, "the faulted ticket completed"); - const auto f = module.last_fault(); - require(module.stats().faulted == 1 && f.ticket == *bad && f.during == job_state::run && f.what == "job failed", - "the fault is typed and named by its ticket"); + require(out == 7 && after.load() == job_outcome::ran, "the job after two faults still runs"); + require(first.load() == job_outcome::run_faulted && second.load() == job_outcome::run_faulted, + "each fault is kept in its own owner's storage: none overwritten"); + require(module.stats().faulted == 2, "and counted"); // a cancel call that throws, during stop std::atomic release{false}; + std::atomic doomed_out{job_outcome::pending}; auto blocker = module.submit([&](job_state) { while (!release.load()) { std::this_thread::yield(); } }); - auto doomed = module.submit([](job_state s) { if (s == job_state::cancelled) throw std::logic_error("cancel failed"); }); + auto doomed = module.submit([](job_state s) { if (s == job_state::cancelled) throw std::logic_error("cancel failed"); }, &doomed_out); require(blocker.has_value() && doomed.has_value(), "queued"); std::thread stopper([&] { module.stop(); }); + while (!module.stopping()) std::this_thread::yield(); // the blocker still runs: `doomed` can only be cancelled release = true; stopper.join(); require(module.completed() >= *doomed, "no waiter hangs on a ticket whose cancel threw"); - require(module.stats().faulted == 2 && module.last_fault().during == job_state::cancelled, "a cancel fault is typed too"); + require(doomed_out.load() == job_outcome::cancel_faulted, "a cancel fault is typed too"); +} + +// what this catches (Codex on #135): an empty or moved-from job was accepted, then called through null ops +static void an_empty_job_is_refused_typed() { + adder module(4); + adder::job empty; + auto r = module.submit(std::move(empty)); + require(!r.has_value() && r.error() == module_refusal::empty, "an empty job is refused, never queued"); + adder::job real([](job_state) {}); + adder::job moved = std::move(real); + auto r2 = module.submit(std::move(real)); // NOLINT: deliberately the moved-from one + require(!r2.has_value() && r2.error() == module_refusal::empty, "a moved-from job is refused"); + auto r3 = module.submit(std::move(moved)); + require(r3.has_value(), "the moved-to job queues"); + module.wait(*r3); } // what this catches (Codex on #135): std::function required a copyable target; a job owning a move-only @@ -226,7 +245,8 @@ int main() { a_snapshot_never_waits_on_work(); a_stop_cancels_queued_jobs_and_no_waiter_hangs(); the_owners_capacity_bounds_the_ring(); - a_throwing_job_is_a_typed_fault_and_the_worker_lives(); + a_throwing_job_ends_typed_in_its_owners_storage(); + an_empty_job_is_refused_typed(); a_move_only_job_runs_once_and_releases_its_capture(); a_snapshot_read_is_never_torn(); std::cout << "test-server-module: ok\n"; diff --git a/tools/server/server-module.h b/tools/server/server-module.h index d78f58b6604c..6a12afeff032 100644 --- a/tools/server/server-module.h +++ b/tools/server/server-module.h @@ -13,7 +13,8 @@ // // A job is called exactly once: with `job_state::run` to do its work, or with `job_state::cancelled` // when a stop dropped it, so it can mark its owner's slot. A call that throws is contained: the fault is -// recorded typed against its ticket, the ticket still completes, and the worker lives on. Stop cancels: +// written as the job's typed terminal outcome into its owner's storage, the ticket still completes, and the +// worker lives on. Stop cancels: // the job in flight finishes, every queued job is called cancelled and destroyed (its captures released), // and the counter still advances past every ticket, so no waiter waits forever. The worker sleeps until // there is work or a stop: never a poll, never a timer. Jobs capture a pointer to their owner's storage, @@ -39,10 +40,11 @@ #include #include -// A value published by one writer and read by many, with no lock anywhere (Codex on #135: a mutex let a -// reader wait on a publication). A seqlock over atomic words: the writer never waits; a reader copies the -// words and retries only when a publish overlapped its copy. A snapshot is counters and ids, so it is -// trivially copyable, enforced. +// A value published by one writer and read by many, with no lock (Codex on #135: a mutex let a reader wait on +// a publication). A seqlock over atomic words: the writer never waits on readers; a reader copies the words +// and retries when a publish overlapped its copy, so a reader is NOT wait-free: a writer descheduled mid- +// publish stalls readers until it resumes (they yield, never spin hot). A snapshot is counters and ids, so it +// is trivially copyable, enforced. template class snapshot_cell { static_assert(std::is_trivially_copyable_v, "a snapshot is counters and ids, copied by value"); @@ -53,10 +55,13 @@ class snapshot_cell { T read() const { uint64_t buf[WORDS]; - while (true) { + for (uint32_t attempt = 0;; ++attempt) { + if (attempt >= 4) { + std::this_thread::yield(); // a publish keeps overlapping: let the writer finish + } const uint64_t before = seq_.load(std::memory_order_acquire); if (before & 1) { - continue; // a publish is mid-copy: read again, never wait on it + continue; // a publish is mid-copy } for (size_t i = 0; i < WORDS; ++i) { buf[i] = words_[i].load(std::memory_order_relaxed); @@ -160,6 +165,7 @@ class inplace_job { enum class module_refusal : uint8_t { stopping, // the module is shutting down: the job was not queued full, // the owner's capacity is reached: the job was not queued + empty, // the job holds no callable (default-constructed or moved-from): never queued, never called }; // How a job is called: once, either to run or because a stop dropped it. @@ -179,14 +185,28 @@ struct module_stats { uint64_t max_job_us = 0; // the longest single job since start }; -// The most recent call that threw (Codex on #135: a throwing job terminated the worker and left tickets -// unfinished). The worker survives; the fault is typed and named by its ticket. -struct module_fault { - job_ticket ticket = 0; // 0: none yet - job_state during = job_state::run; - std::string what; +// How a job ended, written by the module into storage its OWNER passed with the job (Codex on #135: one +// "last fault" slot lost earlier failures, and recording what() allocated a string inside the catch). Typed, +// one per job, no text: a name is rendered only at an export edge (job_outcome_name). +enum class job_outcome : uint8_t { + pending = 0, // not ended yet + ran = 1, + run_faulted = 2, // its run call threw: contained + cancelled = 3, + cancel_faulted = 4, // its cancel call threw: contained }; +inline const char * job_outcome_name(job_outcome o) { + switch (o) { + case job_outcome::pending: return "pending"; + case job_outcome::ran: return "ran"; + case job_outcome::run_faulted: return "run_faulted"; + case job_outcome::cancelled: return "cancelled"; + case job_outcome::cancel_faulted: return "cancel_faulted"; + } + return "unknown"; +} + // `JobBytes`: the inline capture size of every job of this module, fixed at compile time. template class engine_module { @@ -213,9 +233,15 @@ class engine_module { const std::string & name() const { return name_; } - // Queue `j`; its ticket is complete once completed() reaches it. - std::expected submit(job j) { + // Queue `j`; its ticket is complete once completed() reaches it. `outcome`, when given, is the owner's + // storage for how the job ended; it must outlive the ticket's completion. + std::expected submit(job j, std::atomic * outcome = nullptr) { job_ticket ticket; + if (!j) { + std::scoped_lock lock(mutex_); + stats_.refused++; + return std::unexpected(module_refusal::empty); + } { std::scoped_lock lock(mutex_); if (worker_.get_stop_token().stop_requested()) { @@ -227,7 +253,7 @@ class engine_module { return std::unexpected(module_refusal::full); } ticket = ++submitted_; - ring_[(head_ + count_) % ring_.size()] = slot{ std::move(j), ticket }; + ring_[(head_ + count_) % ring_.size()] = slot{ std::move(j), ticket, outcome }; count_++; stats_.queued = count_; } @@ -235,6 +261,9 @@ class engine_module { return ticket; } + // A stop was requested: no job is taken from here on. + bool stopping() const { return worker_.get_stop_token().stop_requested(); } + // How many jobs have finished (run or cancelled), in submission order. uint64_t completed() const { return completed_.load(std::memory_order_acquire); } @@ -250,12 +279,9 @@ class engine_module { module_stats stats() const { std::scoped_lock lock(mutex_); - return stats_; - } - - module_fault last_fault() const { - std::scoped_lock lock(mutex_); - return fault_; + module_stats out = stats_; + out.faulted = faulted_.load(std::memory_order_relaxed); + return out; } protected: @@ -278,8 +304,9 @@ class engine_module { private: struct slot { - job fn; - job_ticket ticket = 0; + job fn; + job_ticket ticket = 0; + std::atomic * outcome = nullptr; // the owner's storage, or none }; void finish_one() { @@ -287,21 +314,23 @@ class engine_module { completed_.notify_all(); } - // A job's call, contained: whatever it throws is recorded typed against its ticket; the worker lives on. - void call(job & j, job_state s, job_ticket ticket) { + // A job's call, contained: whatever it throws ends it as a typed fault in its owner's storage (nothing is + // allocated, nothing can throw here); the worker lives on. + void call(slot & s, job_state state) { + bool faulted = false; try { - j(s); - } catch (const std::exception & e) { - record_fault(ticket, s, e.what()); + s.fn(state); } catch (...) { - record_fault(ticket, s, "a non-standard exception"); + faulted = true; + } + if (faulted) { + faulted_.fetch_add(1, std::memory_order_relaxed); + } + if (s.outcome != nullptr) { + const job_outcome o = state == job_state::run ? (faulted ? job_outcome::run_faulted : job_outcome::ran) + : (faulted ? job_outcome::cancel_faulted : job_outcome::cancelled); + s.outcome->store(o, std::memory_order_release); } - } - - void record_fault(job_ticket ticket, job_state s, const char * what) { - std::scoped_lock lock(mutex_); - stats_.faulted++; - fault_ = module_fault{ ticket, s, what }; } void run(std::stop_token stop) { @@ -320,7 +349,7 @@ class engine_module { stats_.queued = count_; } const auto started = std::chrono::steady_clock::now(); - call(s.fn, job_state::run, s.ticket); + call(s, job_state::run); s.fn.reset(); // its captures are released before completion is announced const auto us = (uint64_t) std::chrono::duration_cast( std::chrono::steady_clock::now() - started).count(); @@ -350,7 +379,7 @@ class engine_module { count_--; stats_.cancelled++; } - call(s.fn, job_state::cancelled, s.ticket); + call(s, job_state::cancelled); s.fn.reset(); finish_one(); } @@ -366,6 +395,6 @@ class engine_module { job_ticket submitted_ = 0; std::atomic completed_{0}; module_stats stats_; - module_fault fault_; + std::atomic faulted_{0}; std::jthread worker_; // last: started after every member it uses exists }; From 076d825478e7454b2ae194192d26f447f91194b3 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 13:49:39 -0600 Subject: [PATCH 4/4] engine_module: C++20, submit returns its own typed result (module_submit), not the C++23 library type the grid lacks (Codex's CI read of #135) Ubuntu 22.04's libstdc++ has no (both ubuntu jobs failed at server-module.h). submit returns module_submit {ticket, refusal}: queued under a ticket (from 1), or refused (ticket 0) with the typed reason. No look-alike of the library type, no fallback: a plain struct this API owns. The test builds at C++20 (the server's standard). Also from the re-review: the outcome storage must stay valid until the owner observes the ticket's completion (said in submit's contract); the torn-read test starts the writer only once the reader runs, so it always overlaps; the faulting test jobs throw only on run (no noreturn warnings). Receipt (M5, Apple clang 21): cmake build 0 warnings, test-server-module ok; -std=c++20 -Wall -Wextra -Werror under -fsanitize=thread 3 of 3 ok and under -fsanitize=address,undefined 3 of 3 ok. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tests/CMakeLists.txt | 2 +- tests/test-server-module.cpp | 58 +++++++++++++++++++----------------- tools/server/server-module.h | 24 ++++++++++----- 3 files changed, 47 insertions(+), 37 deletions(-) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index e17215e0edf8..598cd0dfa87e 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -34,7 +34,7 @@ set_tests_properties(test-server-learn-ledger PROPERTIES LABELS "main") # Model-free engine-module validator: own thread, move-only jobs, typed refusals, snapshots that never wait. add_executable(test-server-module test-server-module.cpp) -target_compile_features(test-server-module PRIVATE cxx_std_23) +target_compile_features(test-server-module PRIVATE cxx_std_20) add_test(NAME test-server-module COMMAND test-server-module) set_tests_properties(test-server-module PROPERTIES LABELS "main") diff --git a/tests/test-server-module.cpp b/tests/test-server-module.cpp index 50ef0dcaa195..690bedb4507e 100644 --- a/tests/test-server-module.cpp +++ b/tests/test-server-module.cpp @@ -53,15 +53,15 @@ static void jobs_write_into_owner_storage_in_order() { adder module(128); std::thread::id worker{}; auto t = module.submit([&worker](job_state) { worker = std::this_thread::get_id(); }); - require(t.has_value(), "a running module takes a job"); - module.wait(*t); + require(t.queued(), "a running module takes a job"); + module.wait(t.ticket); require(worker != std::this_thread::get_id(), "the job ran on the module's own thread"); std::vector totals(100, 0); // the owner's storage, allocated once job_ticket last = 0; for (int64_t n = 1; n <= 100; ++n) { auto ticket = module.add(n, &totals[(size_t) n - 1]); - require(ticket.has_value(), "queued"); - last = *ticket; + require(ticket.queued(), "queued"); + last = ticket.ticket; } module.wait(last); // one wait covers every earlier ticket: completion is in order int64_t expected = 0; @@ -78,14 +78,14 @@ static void a_snapshot_never_waits_on_work() { adder module(4); std::atomic release{false}; auto blocker = module.submit([&](job_state) { while (!release.load()) { std::this_thread::yield(); } }); - require(blocker.has_value(), "queued"); + require(blocker.queued(), "queued"); const auto t0 = std::chrono::steady_clock::now(); for (int i = 0; i < 1000; ++i) { require(module.snapshot().total == 0, "a reader sees the last published state"); } require(std::chrono::steady_clock::now() - t0 < std::chrono::milliseconds(50), "1,000 snapshot reads during a long job never wait on it"); release = true; - module.wait(*blocker); + module.wait(blocker.ticket); } struct tracker { @@ -112,8 +112,8 @@ static void a_stop_cancels_queued_jobs_and_no_waiter_hangs() { for (int i = 0; i < 3; ++i) { auto held = std::make_shared(&alive); // a captured handle: released with its job auto t = module.submit([held, slot = &slots[(size_t) i]](job_state s) { *slot = s == job_state::run ? 1 : -1; }); - require(t.has_value(), "queued behind the running job"); - last = *t; + require(t.queued(), "queued behind the running job"); + last = t.ticket; } require(alive.load() == 3, "the queued jobs hold their captures"); std::thread waiter([&] { module.wait(last); }); // must return even though these never run @@ -121,12 +121,12 @@ static void a_stop_cancels_queued_jobs_and_no_waiter_hangs() { int probes = 0; while (true) { auto probe = module.submit([](job_state) {}); - if (!probe && probe.error() == module_refusal::full) { + if (!probe.queued() && probe.refusal == module_refusal::full) { std::this_thread::yield(); // the ring filled before the stop landed: the stop is coming continue; } - if (!probe) { - require(probe.error() == module_refusal::stopping, "a stopping module refuses typed"); + if (!probe.queued()) { + require(probe.refusal == module_refusal::stopping, "a stopping module refuses typed"); break; } ++probes; @@ -142,7 +142,7 @@ static void a_stop_cancels_queued_jobs_and_no_waiter_hangs() { require(module.stats().cancelled == (uint64_t) (3 + probes), "every cancelled job is counted"); require(module.stats().refused >= 1, "refusals are counted"); require(module.stats().done == 1, "nothing queued ran after the stop"); - require(module.completed() == *running + 3 + (uint64_t) probes, "the counter advanced past every ticket"); + require(module.completed() == running.ticket + 3 + (uint64_t) probes, "the counter advanced past every ticket"); } static void the_owners_capacity_bounds_the_ring() { @@ -151,12 +151,12 @@ static void the_owners_capacity_bounds_the_ring() { auto running = module.submit([&](job_state) { started = true; while (!release.load()) { std::this_thread::yield(); } }); while (!started.load()) { std::this_thread::yield(); } int64_t a = 0, b = 0, c = 0; - require(module.add(1, &a).has_value() && module.add(2, &b).has_value(), "two may wait"); + require(module.add(1, &a).queued() && module.add(2, &b).queued(), "two may wait"); auto third = module.add(3, &c); - require(!third && third.error() == module_refusal::full, "a full ring refuses typed, never grows"); + require(!third.queued() && third.refusal == module_refusal::full, "a full ring refuses typed, never grows"); require(module.stats().refused == 1, "the refusal is counted"); release = true; - module.wait(*running + 2); + module.wait(running.ticket + 2); require(a == 1 && b == 3 && c == 0, "the queued jobs ran; the refused one never did"); } @@ -166,12 +166,12 @@ static void the_owners_capacity_bounds_the_ring() { static void a_throwing_job_ends_typed_in_its_owners_storage() { adder module(8); std::atomic first{job_outcome::pending}, second{job_outcome::pending}, after{job_outcome::pending}; - auto bad1 = module.submit([](job_state) { throw std::runtime_error("job failed"); }, &first); - auto bad2 = module.submit([](job_state) { throw 7; }, &second); + auto bad1 = module.submit([](job_state s) { if (s == job_state::run) throw std::runtime_error("job failed"); }, &first); + auto bad2 = module.submit([](job_state s) { if (s == job_state::run) throw 7; }, &second); int64_t out = 0; auto good = module.submit([&out](job_state s) { if (s == job_state::run) out = 7; }, &after); - require(bad1.has_value() && bad2.has_value() && good.has_value(), "all queued"); - module.wait(*good); + require(bad1.queued() && bad2.queued() && good.queued(), "all queued"); + module.wait(good.ticket); require(out == 7 && after.load() == job_outcome::ran, "the job after two faults still runs"); require(first.load() == job_outcome::run_faulted && second.load() == job_outcome::run_faulted, "each fault is kept in its own owner's storage: none overwritten"); @@ -182,12 +182,12 @@ static void a_throwing_job_ends_typed_in_its_owners_storage() { std::atomic doomed_out{job_outcome::pending}; auto blocker = module.submit([&](job_state) { while (!release.load()) { std::this_thread::yield(); } }); auto doomed = module.submit([](job_state s) { if (s == job_state::cancelled) throw std::logic_error("cancel failed"); }, &doomed_out); - require(blocker.has_value() && doomed.has_value(), "queued"); + require(blocker.queued() && doomed.queued(), "queued"); std::thread stopper([&] { module.stop(); }); while (!module.stopping()) std::this_thread::yield(); // the blocker still runs: `doomed` can only be cancelled release = true; stopper.join(); - require(module.completed() >= *doomed, "no waiter hangs on a ticket whose cancel threw"); + require(module.completed() >= doomed.ticket, "no waiter hangs on a ticket whose cancel threw"); require(doomed_out.load() == job_outcome::cancel_faulted, "a cancel fault is typed too"); } @@ -196,14 +196,14 @@ static void an_empty_job_is_refused_typed() { adder module(4); adder::job empty; auto r = module.submit(std::move(empty)); - require(!r.has_value() && r.error() == module_refusal::empty, "an empty job is refused, never queued"); + require(!r.queued() && r.refusal == module_refusal::empty, "an empty job is refused, never queued"); adder::job real([](job_state) {}); adder::job moved = std::move(real); auto r2 = module.submit(std::move(real)); // NOLINT: deliberately the moved-from one - require(!r2.has_value() && r2.error() == module_refusal::empty, "a moved-from job is refused"); + require(!r2.queued() && r2.refusal == module_refusal::empty, "a moved-from job is refused"); auto r3 = module.submit(std::move(moved)); - require(r3.has_value(), "the moved-to job queues"); - module.wait(*r3); + require(r3.queued(), "the moved-to job queues"); + module.wait(r3.ticket); } // what this catches (Codex on #135): std::function required a copyable target; a job owning a move-only @@ -215,8 +215,8 @@ static void a_move_only_job_runs_once_and_releases_its_capture() { auto t = module.submit([h = std::move(handle), &value](job_state s) mutable { if (s == job_state::run) value = *h + 1; }); - require(t.has_value(), "a move-only capture queues"); - module.wait(*t); + require(t.queued(), "a move-only capture queues"); + module.wait(t.ticket); require(value == 42, "it ran once with its owned handle"); } @@ -225,12 +225,14 @@ static void a_move_only_job_runs_once_and_releases_its_capture() { struct pair_state { uint64_t a = 0, b = 0; }; static void a_snapshot_read_is_never_torn() { snapshot_cell cell(pair_state{}); - std::atomic stop{false}; + std::atomic stop{false}, reading{false}; std::thread writer([&] { + while (!reading.load()) std::this_thread::yield(); // the reader is running before the first publish for (uint64_t i = 1; i <= 200000; ++i) cell.publish(pair_state{ i, ~i }); stop = true; }); uint64_t reads = 0; + reading = true; while (!stop.load()) { const auto v = cell.read(); require(v.b == ~v.a || (v.a == 0 && v.b == 0), "a read is one whole published value"); diff --git a/tools/server/server-module.h b/tools/server/server-module.h index 6a12afeff032..35226574edbc 100644 --- a/tools/server/server-module.h +++ b/tools/server/server-module.h @@ -30,7 +30,6 @@ #include #include #include -#include #include #include #include @@ -171,9 +170,17 @@ enum class module_refusal : uint8_t { // How a job is called: once, either to run or because a stop dropped it. enum class job_state : uint8_t { run, cancelled }; -// A job's sequence number; it is complete once completed() >= its ticket. +// A job's sequence number, from 1; it is complete once completed() >= its ticket. using job_ticket = uint64_t; +// What submit() did: queued under `ticket` (never 0), or refused for `refusal` (ticket 0). A plain typed result: +// the C++23 library result type is missing from grid toolchains (Ubuntu 22.04's libstdc++). +struct module_submit { + job_ticket ticket = 0; + module_refusal refusal = module_refusal::stopping; // meaningful only when !queued() + bool queued() const { return ticket != 0; } +}; + // What every module measures about itself. struct module_stats { uint64_t queued = 0; // jobs waiting now @@ -234,23 +241,24 @@ class engine_module { const std::string & name() const { return name_; } // Queue `j`; its ticket is complete once completed() reaches it. `outcome`, when given, is the owner's - // storage for how the job ended; it must outlive the ticket's completion. - std::expected submit(job j, std::atomic * outcome = nullptr) { + // storage for how the job ended: the module writes it before the ticket completes, so it must stay valid + // (not moved, not freed) until the owner has observed that completion (completed() >= ticket, or wait()). + module_submit submit(job j, std::atomic * outcome = nullptr) { job_ticket ticket; if (!j) { std::scoped_lock lock(mutex_); stats_.refused++; - return std::unexpected(module_refusal::empty); + return module_submit{ 0, module_refusal::empty }; } { std::scoped_lock lock(mutex_); if (worker_.get_stop_token().stop_requested()) { stats_.refused++; - return std::unexpected(module_refusal::stopping); + return module_submit{ 0, module_refusal::stopping }; } if (count_ == ring_.size()) { stats_.refused++; - return std::unexpected(module_refusal::full); + return module_submit{ 0, module_refusal::full }; } ticket = ++submitted_; ring_[(head_ + count_) % ring_.size()] = slot{ std::move(j), ticket, outcome }; @@ -258,7 +266,7 @@ class engine_module { stats_.queued = count_; } wake_.notify_one(); - return ticket; + return module_submit{ ticket, module_refusal::stopping }; } // A stop was requested: no job is taken from here on.