Deterministic completion-order helpers (#15) #31

Merged
faumaray merged 2 commits from issue/15-completion-observer into main 2026-12-03 08:08:35 +00:00
2 changed files with 277 additions and 0 deletions

No files matched your search

+140
View File
@@ -0,0 +1,140 @@
#pragma once
#include <chrono>
#include <concepts>
#include <condition_variable>
#include <cstddef>
#include <functional>
#include <mutex>
#include <type_traits>
#include <utility>
namespace Void::Testing
{
/// Small synchronization gate for deterministic completion-order tests.
///
/// Participants call `arrive()` after a computation returned and can then
/// block in `wait_release()`. The test thread can wait for a number of
/// arrivals (`wait_for`) and release blocked participants explicitly, on
/// failure, or after a timeout. All waits are bounded.
class CompletionGate
{
public:
using Clock = std::chrono::steady_clock;
CompletionGate() = default;
CompletionGate(const CompletionGate&) = delete;
CompletionGate& operator=(const CompletionGate&) = delete;
/// Record one completed invocation and wake `wait_for` waiters.
void arrive() noexcept
{
std::lock_guard lock{mutex_};
++arrivals_;
condition_.notify_all();
}
[[nodiscard]] std::size_t arrivals() const noexcept
{
std::lock_guard lock{mutex_};
return arrivals_;
}
/// Wait until at least `count` invocations arrived. Returns false on
/// timeout.
[[nodiscard]] bool wait_for(std::size_t count,
std::chrono::milliseconds timeout)
{
std::unique_lock lock{mutex_};
return condition_.wait_for(
lock, timeout, [&] { return arrivals_ >= count; });
}
/// Unblock every current and future `wait_release` caller.
void release() noexcept
{
std::lock_guard lock{mutex_};
released_ = true;
condition_.notify_all();
}
[[nodiscard]] bool released() const noexcept
{
std::lock_guard lock{mutex_};
return released_;
}
/// Block until `release()`; returns false on timeout so a failing test
/// can still finish.
[[nodiscard]] bool wait_release(std::chrono::milliseconds timeout)
{
std::unique_lock lock{mutex_};
return condition_.wait_for(lock, timeout,
[&] { return released_; });
}
private:
mutable std::mutex mutex_;
std::condition_variable condition_;
std::size_t arrivals_{0};
bool released_{false};
};
/// Callable adapter that runs an observer exactly once after a successful
/// invocation returns, and before the enclosing future is fulfilled.
///
/// The observer is *not* called when the callable throws; the exception is
/// forwarded unchanged. Void, value, reference and move-only results are
/// preserved. The observer itself must not throw; an exception from it
/// propagates instead of the result.
template <typename Fn, typename Observer> class ObservedCallable
{
public:
template <typename F, typename O>
ObservedCallable(F&& fn, O&& observer)
: fn_(std::forward<F>(fn))
, observer_(std::forward<O>(observer))
{
}
template <typename... Args>
requires std::invocable<Fn&, Args...>
decltype(auto) operator()(Args&&... args)
{
using Result = std::invoke_result_t<Fn&, Args...>;
if constexpr (std::is_void_v<Result>) {
std::invoke(fn_, std::forward<Args>(args)...);
std::invoke(observer_);
return;
} else if constexpr (std::is_reference_v<Result>) {
Result result =
std::invoke(fn_, std::forward<Args>(args)...);
std::invoke(observer_);
return std::forward<Result>(result);
} else {
Result result =
std::invoke(fn_, std::forward<Args>(args)...);
std::invoke(observer_);
return result;
}
}
private:
Fn fn_;
Observer observer_;
};
template <typename Fn, typename Observer>
[[nodiscard]] auto observe_completion(Fn&& fn, Observer&& observer)
{
return ObservedCallable<std::decay_t<Fn>, std::decay_t<Observer>>(
std::forward<Fn>(fn), std::forward<Observer>(observer));
}
} // namespace Void::Testing
@@ -0,0 +1,137 @@
#include <Void/Testing/CompletionObserver.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <chrono>
#include <future>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <utility>
#include <vector>
namespace
{
using namespace std::chrono_literals;
[[nodiscard]] std::vector<char> completion_order(char first, char second)
{
Void::Testing::CompletionGate gate;
std::mutex mutex;
std::vector<char> order;
const auto task = [&](char id) {
return Void::Testing::observe_completion(
[id] { return id; },
[&, id] {
{
std::lock_guard lock{mutex};
order.push_back(id);
}
gate.arrive();
(void)gate.wait_release(5s);
});
};
auto a = task(first);
auto b = task(second);
auto first_future = std::async(std::launch::async, std::move(a));
if (!gate.wait_for(1, 5s)) {
return {};
}
auto second_future = std::async(std::launch::async, std::move(b));
const bool both = gate.wait_for(2, 5s);
gate.release();
Void::Testing::expect_eq(first_future.get(), first);
Void::Testing::expect_eq(second_future.get(), second);
if (!both) {
return {};
}
std::lock_guard lock{mutex};
return order;
}
} // namespace
Void::Testing::Test completion_observer_runs_before_future_ready()
{
Void::Testing::CompletionGate gate;
std::promise<void> observed;
auto wrapped = Void::Testing::observe_completion(
[] { return 42; },
[&] {
observed.set_value();
(void)gate.wait_release(5s);
});
auto future = std::async(std::launch::async, std::move(wrapped));
observed.get_future().wait();
// The observer already ran, but the callable has not returned yet.
Void::Testing::expect(future.wait_for(0ms) ==
std::future_status::timeout);
gate.release();
Void::Testing::expect_eq(future.get(), 42);
}
Void::Testing::Test completion_observer_preserves_result_categories()
{
int observed = 0;
auto void_callable =
Void::Testing::observe_completion([] {}, [&] { ++observed; });
void_callable();
Void::Testing::expect_eq(observed, 1);
auto move_only = Void::Testing::observe_completion(
[] { return std::make_unique<int>(7); },
[&] { ++observed; });
auto value = move_only();
Void::Testing::require(value != nullptr);
Void::Testing::expect_eq(*value, 7);
Void::Testing::expect_eq(observed, 2);
int storage = 5;
auto reference = Void::Testing::observe_completion(
[&]() -> int& { return storage; }, [] {});
int& ref = reference();
ref = 9;
Void::Testing::expect_eq(storage, 9);
}
Void::Testing::Test completion_observer_forwards_exceptions()
{
int observed = 0;
auto throwing = Void::Testing::observe_completion(
[]() -> int { throw std::runtime_error{"boom"}; },
[&] { ++observed; });
bool caught = false;
try {
(void)throwing();
} catch (const std::runtime_error&) {
caught = true;
}
Void::Testing::expect(caught);
Void::Testing::expect_eq(observed, 0);
}
Void::Testing::Test completion_gate_release_and_timeout()
{
Void::Testing::CompletionGate gate;
Void::Testing::expect(!gate.wait_release(5ms));
gate.arrive();
Void::Testing::expect(gate.wait_for(1, 5ms));
Void::Testing::expect(!gate.wait_for(2, 5ms));
gate.release();
Void::Testing::expect(gate.wait_release(5ms));
}
Void::Testing::Test completion_order_is_deterministic()
{
Void::Testing::expect(completion_order('A', 'B') ==
std::vector<char>{'A', 'B'});
Void::Testing::expect(completion_order('B', 'A') ==
std::vector<char>{'B', 'A'});
}