494 lines
15 KiB
C++
494 lines
15 KiB
C++
#pragma once
|
|
|
|
#include <Void/Time/Clock.hpp>
|
|
|
|
#include <algorithm>
|
|
#include <chrono>
|
|
#include <concepts>
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <deque>
|
|
#include <expected>
|
|
#include <functional>
|
|
#include <limits>
|
|
#include <optional>
|
|
#include <random>
|
|
#include <string>
|
|
#include <type_traits>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
namespace Void::Testing
|
|
{
|
|
|
|
struct ReplayToken {
|
|
std::uint64_t seed{0x9E3779B97F4A7C15ULL};
|
|
std::uint32_t generator_version{1};
|
|
std::uint64_t case_index{0};
|
|
|
|
[[nodiscard]] constexpr bool operator==(const ReplayToken&) const noexcept = default;
|
|
};
|
|
|
|
// Frozen version-1 deterministic PRNG backed by SplitMix64 seeding + mt19937_64
|
|
// with standard-library-independent unbiased rejection sampling.
|
|
class DeterministicRng
|
|
{
|
|
public:
|
|
explicit DeterministicRng(ReplayToken token) noexcept
|
|
: token_(token)
|
|
, engine_(mix_seed_v1(token.seed, token.case_index))
|
|
{
|
|
}
|
|
|
|
[[nodiscard]] static constexpr std::uint64_t mix_seed_v1(
|
|
std::uint64_t seed, std::uint64_t case_index) noexcept
|
|
{
|
|
std::uint64_t z = seed ^ (case_index * 0x9E3779B97F4A7C15ULL);
|
|
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
|
|
z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
|
|
return z ^ (z >> 31);
|
|
}
|
|
|
|
[[nodiscard]] const ReplayToken& token() const noexcept { return token_; }
|
|
|
|
[[nodiscard]] std::uint64_t next_u64() noexcept
|
|
{
|
|
return engine_();
|
|
}
|
|
|
|
// Returns uniform integer in [0, bound - 1] via rejection sampling.
|
|
[[nodiscard]] std::uint64_t next_bounded(std::uint64_t bound) noexcept
|
|
{
|
|
if (bound <= 1) {
|
|
return 0;
|
|
}
|
|
const std::uint64_t threshold = (0ULL - bound) % bound;
|
|
for (;;) {
|
|
const std::uint64_t r = next_u64();
|
|
if (r >= threshold) {
|
|
return r % bound;
|
|
}
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] std::int64_t next_int(std::int64_t lo, std::int64_t hi) noexcept
|
|
{
|
|
if (lo >= hi) {
|
|
return lo;
|
|
}
|
|
const std::uint64_t ulo = static_cast<std::uint64_t>(lo);
|
|
const std::uint64_t uhi = static_cast<std::uint64_t>(hi);
|
|
const std::uint64_t span = uhi - ulo;
|
|
if (span == std::numeric_limits<std::uint64_t>::max()) {
|
|
return static_cast<std::int64_t>(next_u64());
|
|
}
|
|
const std::uint64_t pick = next_bounded(span + 1ULL);
|
|
return static_cast<std::int64_t>(ulo + pick);
|
|
}
|
|
|
|
[[nodiscard]] bool next_bool() noexcept
|
|
{
|
|
return (next_u64() & 1ULL) != 0ULL;
|
|
}
|
|
|
|
[[nodiscard]] std::vector<std::byte> next_bytes(std::size_t max_len)
|
|
{
|
|
const std::size_t len =
|
|
static_cast<std::size_t>(next_bounded(max_len + 1ULL));
|
|
std::vector<std::byte> out(len);
|
|
for (std::size_t i = 0; i < len; ++i) {
|
|
out[i] = static_cast<std::byte>(next_u64() & 0xFFULL);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
[[nodiscard]] std::vector<int> next_ints(
|
|
std::size_t max_len, int lo, int hi)
|
|
{
|
|
const std::size_t len =
|
|
static_cast<std::size_t>(next_bounded(max_len + 1ULL));
|
|
std::vector<int> out;
|
|
out.reserve(len);
|
|
for (std::size_t i = 0; i < len; ++i) {
|
|
out.push_back(static_cast<int>(next_int(lo, hi)));
|
|
}
|
|
return out;
|
|
}
|
|
|
|
private:
|
|
ReplayToken token_{};
|
|
std::mt19937_64 engine_;
|
|
};
|
|
|
|
enum class PropertyStatus {
|
|
passed,
|
|
failed,
|
|
inconclusive
|
|
};
|
|
|
|
struct PropertyOptions {
|
|
unsigned cases{256};
|
|
unsigned max_size{64};
|
|
unsigned max_shrinks{1000};
|
|
unsigned max_steps{10000};
|
|
unsigned max_discard_factor{10};
|
|
std::chrono::nanoseconds time_budget{std::chrono::seconds{5}};
|
|
};
|
|
|
|
template <typename T>
|
|
struct PropertyResult {
|
|
PropertyStatus status{PropertyStatus::passed};
|
|
ReplayToken replay{};
|
|
unsigned cases_executed{0};
|
|
unsigned discards{0};
|
|
unsigned shrink_steps{0};
|
|
std::optional<T> original_failure{};
|
|
std::optional<T> minimal_failure{};
|
|
std::vector<T> shrink_path{};
|
|
std::string message{};
|
|
};
|
|
|
|
namespace Detail
|
|
{
|
|
template <typename T>
|
|
struct UnwrapOptional {
|
|
using type = T;
|
|
static constexpr bool is_optional = false;
|
|
};
|
|
|
|
template <typename U>
|
|
struct UnwrapOptional<std::optional<U>> {
|
|
using type = U;
|
|
static constexpr bool is_optional = true;
|
|
};
|
|
|
|
[[nodiscard]] inline std::chrono::nanoseconds elapsed_since(
|
|
const Void::Time::MonotonicClock& clock,
|
|
Void::Time::MonotonicClock::time_point start) noexcept
|
|
{
|
|
const auto now = clock.now();
|
|
return (now > start)
|
|
? std::chrono::duration_cast<std::chrono::nanoseconds>(now - start)
|
|
: std::chrono::nanoseconds{0};
|
|
}
|
|
} // namespace Detail
|
|
|
|
template <typename GeneratorFn, typename PredicateFn, typename ShrinkFn>
|
|
requires std::invocable<
|
|
ShrinkFn,
|
|
const typename Detail::UnwrapOptional<
|
|
std::remove_cvref_t<std::invoke_result_t<GeneratorFn, DeterministicRng&>>>::type&>
|
|
[[nodiscard]] auto check_property(
|
|
GeneratorFn&& gen,
|
|
PredicateFn&& pred,
|
|
ShrinkFn&& shrink,
|
|
const PropertyOptions& opts = {},
|
|
ReplayToken base_token = {},
|
|
const Void::Time::MonotonicClock* clock = nullptr)
|
|
{
|
|
using GenRaw = std::remove_cvref_t<std::invoke_result_t<GeneratorFn, DeterministicRng&>>;
|
|
using T = typename Detail::UnwrapOptional<GenRaw>::type;
|
|
|
|
PropertyResult<T> result;
|
|
result.replay = base_token;
|
|
|
|
if (base_token.generator_version != 1) {
|
|
result.status = PropertyStatus::inconclusive;
|
|
result.message = "Unsupported ReplayToken generator_version";
|
|
return result;
|
|
}
|
|
|
|
const Void::Time::MonotonicClock& clk =
|
|
clock ? *clock : Void::Time::SystemMonotonicClock::instance();
|
|
const auto start_tp = clk.now();
|
|
unsigned total_steps = 0;
|
|
const unsigned max_discards =
|
|
(opts.cases == 0 || opts.max_discard_factor == 0)
|
|
? 0
|
|
: (opts.cases <= std::numeric_limits<unsigned>::max() / opts.max_discard_factor
|
|
? opts.cases * opts.max_discard_factor
|
|
: std::numeric_limits<unsigned>::max());
|
|
|
|
for (unsigned case_idx = 0;
|
|
result.cases_executed < opts.cases;
|
|
++case_idx) {
|
|
if (total_steps >= opts.max_steps ||
|
|
Detail::elapsed_since(clk, start_tp) >= opts.time_budget) {
|
|
result.status = PropertyStatus::inconclusive;
|
|
result.message = "Property step or time budget exhausted";
|
|
return result;
|
|
}
|
|
++total_steps;
|
|
|
|
ReplayToken case_tok{base_token.seed, base_token.generator_version, case_idx};
|
|
DeterministicRng rng{case_tok};
|
|
std::optional<T> value_opt;
|
|
if constexpr (Detail::UnwrapOptional<GenRaw>::is_optional) {
|
|
value_opt = std::forward<GeneratorFn>(gen)(rng);
|
|
} else {
|
|
value_opt.emplace(std::forward<GeneratorFn>(gen)(rng));
|
|
}
|
|
|
|
if (!value_opt.has_value()) {
|
|
++result.discards;
|
|
if (result.discards > max_discards) {
|
|
result.status = PropertyStatus::inconclusive;
|
|
result.message = "Property generator discard budget exceeded";
|
|
return result;
|
|
}
|
|
continue;
|
|
}
|
|
|
|
using PredRaw = std::remove_cvref_t<std::invoke_result_t<PredicateFn, const T&>>;
|
|
std::optional<bool> ok;
|
|
if constexpr (Detail::UnwrapOptional<PredRaw>::is_optional) {
|
|
ok = std::forward<PredicateFn>(pred)(*value_opt);
|
|
} else {
|
|
ok = static_cast<bool>(std::forward<PredicateFn>(pred)(*value_opt));
|
|
}
|
|
|
|
if (!ok.has_value()) {
|
|
++result.discards;
|
|
if (result.discards > max_discards) {
|
|
result.status = PropertyStatus::inconclusive;
|
|
result.message = "Property precondition discard budget exceeded";
|
|
return result;
|
|
}
|
|
continue;
|
|
}
|
|
|
|
++result.cases_executed;
|
|
if (*ok) {
|
|
continue;
|
|
}
|
|
|
|
result.status = PropertyStatus::failed;
|
|
result.replay = case_tok;
|
|
result.original_failure = *value_opt;
|
|
result.minimal_failure = std::move(*value_opt);
|
|
result.message = "Property falsified";
|
|
|
|
// Deterministic shrinking up to max_shrinks / max_steps / time_budget.
|
|
while (result.shrink_steps < opts.max_shrinks &&
|
|
total_steps < opts.max_steps &&
|
|
Detail::elapsed_since(clk, start_tp) < opts.time_budget) {
|
|
const auto candidates = shrink(*result.minimal_failure);
|
|
bool shrunk_once = false;
|
|
for (const auto& cand : candidates) {
|
|
if (total_steps >= opts.max_steps ||
|
|
Detail::elapsed_since(clk, start_tp) >= opts.time_budget) {
|
|
break;
|
|
}
|
|
++total_steps;
|
|
std::optional<bool> cand_ok;
|
|
if constexpr (Detail::UnwrapOptional<PredRaw>::is_optional) {
|
|
cand_ok = pred(cand);
|
|
} else {
|
|
cand_ok = static_cast<bool>(pred(cand));
|
|
}
|
|
if (cand_ok.has_value() && !(*cand_ok)) {
|
|
result.minimal_failure = cand;
|
|
result.shrink_path.push_back(cand);
|
|
++result.shrink_steps;
|
|
shrunk_once = true;
|
|
break;
|
|
}
|
|
}
|
|
if (!shrunk_once) {
|
|
break;
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
result.status = PropertyStatus::passed;
|
|
return result;
|
|
}
|
|
|
|
template <typename GeneratorFn, typename PredicateFn>
|
|
[[nodiscard]] auto check_property(
|
|
GeneratorFn&& gen,
|
|
PredicateFn&& pred,
|
|
const PropertyOptions& opts = {},
|
|
ReplayToken base_token = {},
|
|
const Void::Time::MonotonicClock* clock = nullptr)
|
|
{
|
|
using GenRaw = std::remove_cvref_t<std::invoke_result_t<GeneratorFn, DeterministicRng&>>;
|
|
using T = typename Detail::UnwrapOptional<GenRaw>::type;
|
|
auto no_shrink = [](const T&) -> std::vector<T> { return {}; };
|
|
return check_property(
|
|
std::forward<GeneratorFn>(gen),
|
|
std::forward<PredicateFn>(pred),
|
|
no_shrink,
|
|
opts,
|
|
base_token,
|
|
clock);
|
|
}
|
|
|
|
template <typename GeneratorFn, typename PredicateFn>
|
|
[[nodiscard]] bool replay_property_case(
|
|
GeneratorFn&& gen,
|
|
PredicateFn&& pred,
|
|
ReplayToken token)
|
|
{
|
|
DeterministicRng rng{token};
|
|
auto val = std::forward<GeneratorFn>(gen)(rng);
|
|
return static_cast<bool>(std::forward<PredicateFn>(pred)(val));
|
|
}
|
|
|
|
struct ScheduleEvent {
|
|
std::uint64_t step{0};
|
|
std::uint64_t action_id{0};
|
|
std::string label{};
|
|
std::int64_t clock_ns{0};
|
|
std::size_t choice_index{0};
|
|
std::size_t ready_count{0};
|
|
};
|
|
|
|
// Deterministic single-step action & timer harness using Void::Time::ManualClock.
|
|
class DeterministicRun
|
|
{
|
|
public:
|
|
explicit DeterministicRun(Void::Time::ManualClock::time_point initial = {}) noexcept
|
|
: clock_(initial)
|
|
{
|
|
}
|
|
|
|
[[nodiscard]] const Void::Time::ManualClock& clock() const noexcept { return clock_; }
|
|
[[nodiscard]] Void::Time::ManualClock& clock() noexcept { return clock_; }
|
|
|
|
std::uint64_t schedule(std::string label, std::function<void()> fn)
|
|
{
|
|
const std::uint64_t id = next_id_++;
|
|
ready_.push_back(Action{id, std::move(label), std::move(fn)});
|
|
return id;
|
|
}
|
|
|
|
std::uint64_t schedule_after(
|
|
std::chrono::nanoseconds delay,
|
|
std::string label,
|
|
std::function<void()> fn)
|
|
{
|
|
const std::uint64_t id = next_id_++;
|
|
const auto fire_at =
|
|
(delay.count() <= 0) ? clock_.now() : (clock_.now() + delay);
|
|
if (fire_at <= clock_.now()) {
|
|
ready_.push_back(Action{id, std::move(label), std::move(fn)});
|
|
return id;
|
|
}
|
|
timers_.push_back(Timer{fire_at, id, std::move(label), std::move(fn)});
|
|
return id;
|
|
}
|
|
|
|
std::size_t advance_clock(std::chrono::nanoseconds delta)
|
|
{
|
|
(void)clock_.advance(delta);
|
|
return promote_due_timers();
|
|
}
|
|
|
|
bool step()
|
|
{
|
|
return step_choice(0);
|
|
}
|
|
|
|
bool step_choice(std::size_t ready_index)
|
|
{
|
|
(void)promote_due_timers();
|
|
if (ready_.empty() || ready_index >= ready_.size()) {
|
|
return false;
|
|
}
|
|
const std::size_t rc = ready_.size();
|
|
Action act = std::move(ready_[ready_index]);
|
|
ready_.erase(ready_.begin() + static_cast<std::ptrdiff_t>(ready_index));
|
|
|
|
const std::int64_t now_ns =
|
|
std::chrono::duration_cast<std::chrono::nanoseconds>(
|
|
clock_.now().time_since_epoch())
|
|
.count();
|
|
trace_.push_back(ScheduleEvent{
|
|
.step = next_step_++,
|
|
.action_id = act.id,
|
|
.label = act.label,
|
|
.clock_ns = now_ns,
|
|
.choice_index = ready_index,
|
|
.ready_count = rc,
|
|
});
|
|
if (act.fn) {
|
|
act.fn();
|
|
}
|
|
return true;
|
|
}
|
|
|
|
[[nodiscard]] std::expected<std::size_t, std::string>
|
|
run_until_idle(std::size_t max_steps = 10000)
|
|
{
|
|
std::size_t ran = 0;
|
|
for (;;) {
|
|
(void)promote_due_timers();
|
|
if (ready_.empty()) {
|
|
return ran;
|
|
}
|
|
if (ran >= max_steps) {
|
|
return std::unexpected{
|
|
"DeterministicRun exceeded max_steps limit"};
|
|
}
|
|
if (!step()) {
|
|
return ran;
|
|
}
|
|
++ran;
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] std::size_t ready_count() const noexcept { return ready_.size(); }
|
|
[[nodiscard]] std::size_t timer_count() const noexcept { return timers_.size(); }
|
|
[[nodiscard]] const std::vector<ScheduleEvent>& trace() const noexcept { return trace_; }
|
|
|
|
private:
|
|
struct Action {
|
|
std::uint64_t id{0};
|
|
std::string label{};
|
|
std::function<void()> fn{};
|
|
};
|
|
|
|
struct Timer {
|
|
Void::Time::ManualClock::time_point fire_at{};
|
|
std::uint64_t id{0};
|
|
std::string label{};
|
|
std::function<void()> fn{};
|
|
};
|
|
|
|
std::size_t promote_due_timers()
|
|
{
|
|
const auto now = clock_.now();
|
|
std::vector<Timer> due;
|
|
std::vector<Timer> remaining;
|
|
remaining.reserve(timers_.size());
|
|
for (auto& t : timers_) {
|
|
if (t.fire_at <= now) {
|
|
due.push_back(std::move(t));
|
|
} else {
|
|
remaining.push_back(std::move(t));
|
|
}
|
|
}
|
|
timers_ = std::move(remaining);
|
|
std::sort(due.begin(), due.end(), [](const Timer& a, const Timer& b) {
|
|
if (a.fire_at != b.fire_at) {
|
|
return a.fire_at < b.fire_at;
|
|
}
|
|
return a.id < b.id;
|
|
});
|
|
for (auto& t : due) {
|
|
ready_.push_back(Action{t.id, std::move(t.label), std::move(t.fn)});
|
|
}
|
|
return due.size();
|
|
}
|
|
|
|
Void::Time::ManualClock clock_;
|
|
std::uint64_t next_id_{1};
|
|
std::uint64_t next_step_{0};
|
|
std::deque<Action> ready_{};
|
|
std::vector<Timer> timers_{};
|
|
std::vector<ScheduleEvent> trace_{};
|
|
};
|
|
|
|
} // namespace Void::Testing
|