diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index ee695dd04b09..598cd0dfa87e 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_20) +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..690bedb4507e --- /dev/null +++ b/tests/test-server-module.cpp @@ -0,0 +1,256 @@ +// 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 +#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.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.queued(), "queued"); + last = ticket.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.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.ticket); +} + +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.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 + std::thread stopper([&] { module.stop(); }); + int probes = 0; + while (true) { + auto probe = module.submit([](job_state) {}); + 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.queued()) { + require(probe.refusal == 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.ticket + 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).queued() && module.add(2, &b).queued(), "two may wait"); + auto third = module.add(3, &c); + 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.ticket + 2); + 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), 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); + std::atomic first{job_outcome::pending}, second{job_outcome::pending}, after{job_outcome::pending}; + 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.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"); + 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"); }, &doomed_out); + 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.ticket, "no waiter hangs on a ticket whose cancel threw"); + 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.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.queued() && r2.refusal == module_refusal::empty, "a moved-from job is refused"); + auto r3 = module.submit(std::move(moved)); + 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 +// 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.queued(), "a move-only capture queues"); + module.wait(t.ticket); + 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}, 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"); + 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_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"; + return 0; +} diff --git a/tools/server/server-module.h b/tools/server/server-module.h new file mode 100644 index 000000000000..35226574edbc --- /dev/null +++ b/tools/server/server-module.h @@ -0,0 +1,408 @@ +#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 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. A call that throws is contained: the fault is +// 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, +// 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 + +// 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"); + static constexpr size_t WORDS = (sizeof(T) + sizeof(uint64_t) - 1) / sizeof(uint64_t); + +public: + explicit snapshot_cell(const T & initial) { publish(initial); } + + T read() const { + uint64_t buf[WORDS]; + 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 + } + 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; + } + } + } + + // 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: + 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. +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. +enum class job_state : uint8_t { run, cancelled }; + +// 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 + 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 +}; + +// 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 { +public: + 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, 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; + 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. `outcome`, when given, is the owner's + // 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 module_submit{ 0, module_refusal::empty }; + } + { + std::scoped_lock lock(mutex_); + if (worker_.get_stop_token().stop_requested()) { + stats_.refused++; + return module_submit{ 0, module_refusal::stopping }; + } + if (count_ == ring_.size()) { + stats_.refused++; + return module_submit{ 0, module_refusal::full }; + } + ticket = ++submitted_; + ring_[(head_ + count_) % ring_.size()] = slot{ std::move(j), ticket, outcome }; + count_++; + stats_.queued = count_; + } + wake_.notify_one(); + return module_submit{ ticket, module_refusal::stopping }; + } + + // 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); } + + // 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); + } + } + + // The last published state, copied with no lock. + Snapshot snapshot() const { return snapshot_.read(); } + + module_stats stats() const { + std::scoped_lock lock(mutex_); + module_stats out = stats_; + out.faulted = faulted_.load(std::memory_order_relaxed); + return out; + } + +protected: + 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 + // 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: + struct slot { + job fn; + job_ticket ticket = 0; + std::atomic * outcome = nullptr; // the owner's storage, or none + }; + + void finish_one() { + completed_.fetch_add(1, std::memory_order_release); + completed_.notify_all(); + } + + // 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 { + s.fn(state); + } catch (...) { + 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 run(std::stop_token stop) { + while (true) { + slot s; + { + 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; + } + s = std::move(ring_[head_]); + head_ = (head_ + 1) % ring_.size(); + count_--; + stats_.queued = count_; + } + const auto started = std::chrono::steady_clock::now(); + 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(); + { + 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, 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() { + 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++; + } + call(s, job_state::cancelled); + s.fn.reset(); + 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::atomic faulted_{0}; + std::jthread worker_; // last: started after every member it uses exists +};