3#include <condition_variable>
19#include "hegel/core.h"
165 : name_(std::move(params.
name)), groups_(std::move(params.
groups)),
166 weight_(params.
weight), step_(std::move(params.
step)) {}
173 const std::string&
name()
const {
return name_; }
180 const std::vector<std::string>&
groups()
const {
return groups_; }
187 double weight()
const {
return weight_; }
198 std::vector<std::string> groups_;
338 std::vector<Invariant<Derived>>
invariants()
const {
return {}; }
397 template <
typename T>
class Pool {
412 void add(
const T& element) {
413 int64_t var_id = pool_handle_.add(tc_);
415 if (pool_.find(var_id) != pool_.end()) {
416 throw std::runtime_error(
"unexpected variable id in map");
419 pool_.emplace(var_id, element);
428 int64_t var_id = pool_handle_.add(tc_);
430 if (pool_.find(var_id) != pool_.end()) {
431 throw std::runtime_error(
"unexpected variable id in map");
434 pool_.emplace(var_id, std::move(element));
442 std::size_t
size()
const {
return pool_.size(); }
448 hegel::internal::PoolHandle pool_handle_;
449 std::map<int64_t, T> pool_;
457 class TakenVariables {
460 hegel::internal::PoolHandle& pool)
461 : tc_(tc), pool_(pool) {}
462 TakenVariables(
const TakenVariables&) =
delete;
463 TakenVariables& operator=(
const TakenVariables&) =
delete;
465 for (int64_t variable : variables_) {
466 pool_.restore_unchecked(tc_, variable);
470 void add(int64_t variable) { variables_.push_back(variable); }
472 void keep_last() { variables_.pop_back(); }
475 while (!variables_.empty()) {
476 pool_.restore(tc_, variables_.back());
477 variables_.pop_back();
483 hegel::internal::PoolHandle& pool_;
484 std::vector<int64_t> variables_;
493 template <
typename T>
495 draw_filtered_consumed(
const TestCase& tc,
496 hegel::internal::PoolHandle& pool,
497 std::map<int64_t, T>& values, uint64_t label,
498 const std::function<
bool(
const T&)>& predicate) {
499 namespace hi = hegel::internal;
500 uint64_t attempt = hi::label(hi::LabelName::FilterAttempt);
501 TakenVariables taken(tc, pool);
502 std::optional<T> accepted;
503 for (
int i = 0; i < hi::filter_attempts && !accepted; ++i) {
504 hi::start_span(tc, attempt);
505 hi::start_span(tc, label);
506 int64_t variable = pool.draw_variable(tc,
true);
509 T& value = values.at(variable);
510 if (predicate(value)) {
513 accepted = std::move(value);
514 values.erase(variable);
516 hi::stop_span(tc,
true);
523 return std::move(*accepted);
531 template <
typename T>
533 :
public generators::detail::value_base_t<T, is_representable_v<T>> {
535 explicit VariablesGenerator(Pool<T>& p,
bool consume)
536 : p_(p), consume_(consume) {}
538 T do_draw(
const TestCase& tc)
const override {
539 int64_t variable = p_.pool_handle_.draw_variable(tc, consume_);
541 auto it = p_.pool_.find(variable);
543 if (it == p_.pool_.end()) {
544 throw std::runtime_error(
545 "Pool state diverged between the engine and the "
546 "client, or a bug in the pool bookkeeping.");
550 auto val = std::move(it->second);
557 uint64_t label()
const override {
558 return hegel::internal::label(
559 consume_ ? hegel::internal::LabelName::PoolValuesConsumed
560 : hegel::internal::LabelName::PoolValuesReusable);
565 const std::function<
bool(
const T&)>& predicate)
const override {
569 return detail::draw_filtered_consumed(tc, p_.pool_handle_, p_.pool_,
570 this->label(), predicate);
614 return generators::detail::handle_t<is_representable_v<T>, T>(
615 std::make_shared<VariablesGenerator<T>>(p,
true));
646 return generators::detail::handle_t<is_representable_v<T>, T>(
647 std::make_shared<VariablesGenerator<T>>(p,
false));
651 template <
typename T>
class ConcurrentVariablesGenerator;
686 std::lock_guard<std::mutex> lock(mutex_);
687 int64_t variable = pool_handle_.add(tc);
688 values_.emplace(variable, std::move(value));
697 std::lock_guard<std::mutex> lock(mutex_);
698 return values_.empty();
707 std::lock_guard<std::mutex> lock(mutex_);
708 return values_.size();
715 internal::PoolHandle pool_handle_;
716 mutable std::mutex mutex_;
717 std::map<int64_t, T> values_;
719 friend class ConcurrentVariablesGenerator<T>;
723 template <
typename T>
724 class ConcurrentVariablesGenerator
725 :
public generators::detail::value_base_t<T, is_representable_v<T>> {
727 ConcurrentVariablesGenerator(ConcurrentPool<T>& pool,
bool consume)
728 : pool_(pool), consume_(consume) {}
730 T do_draw(
const TestCase& tc)
const override {
731 std::lock_guard<std::mutex> lock(pool_.mutex_);
732 int64_t variable = pool_.pool_handle_.draw_variable(tc, consume_);
734 T result = std::move(pool_.values_.at(variable));
735 pool_.values_.erase(variable);
738 return pool_.values_.at(variable);
742 uint64_t label()
const override {
743 return hegel::internal::label(
744 consume_ ? hegel::internal::LabelName::PoolValuesConsumed
745 : hegel::internal::LabelName::PoolValuesReusable);
750 const std::function<
bool(
const T&)>& predicate)
const override {
754 std::lock_guard<std::mutex> lock(pool_.mutex_);
755 return detail::draw_filtered_consumed(tc, pool_.pool_handle_,
756 pool_.values_, this->label(),
761 ConcurrentPool<T>& pool_;
778 return generators::detail::handle_t<is_representable_v<T>, T>(
779 std::make_shared<ConcurrentVariablesGenerator<T>>(pool,
true));
793 return generators::detail::handle_t<is_representable_v<T>, T>(
794 std::make_shared<ConcurrentVariablesGenerator<T>>(pool,
false));
831 template <
typename T>
class Rule {
862 : name_(std::move(params.
name)), weight_(params.
weight),
863 step_(std::move(params.
step)) {}
870 const std::string&
name()
const {
return name_; }
876 const std::function<void(
TestCase&, T&)>&
step()
const {
return step_; }
883 double weight()
const {
return weight_; }
888 std::function<void(
TestCase&, T&)> step_;
970 : name_(std::move(params.
name)),
980 const std::string&
name()
const {
return name_; }
987 const std::function<void(
const T&)>&
invariant()
const {
1008 std::function<void(
const T&)> invariant_;
1071 :
state(std::move(params.initial_state)) {}
1100 template <
typename T>
1101 void check_invariants(
1104 std::optional<std::reference_wrapper<internal::StateMachineHandle>>
1105 machine_handle = std::nullopt) {
1106 for (std::size_t index = 0; index < invariants.size(); ++index) {
1107 if (machine_handle.has_value() &&
1108 !machine_handle->get().should_check_invariant(
1109 tc,
static_cast<int64_t
>(index))) {
1114 internal::PauseFaultsScope pause(tc, inv.
pause_faults());
1117 tc.
note(
"Invariant " + inv.
name() +
" failed:");
1123 inline void check_step_count(
const RunParams& params) {
1124 if (params.step_count < 1) {
1125 throw std::invalid_argument(
1126 "RunParams::step_count must be at least 1");
1165 template <
typename M>
1167 int64_t max_concurrency,
const RunParams& params = {}) {
1168 static_assert(std::is_base_of<ConcurrentStateMachine<M>, M>::value,
1169 "run_concurrent() requires a machine deriving from "
1170 "ConcurrentStateMachine<M>.");
1171 if (min_concurrency < 1 || min_concurrency > max_concurrency) {
1172 throw std::invalid_argument(
1173 "concurrency bounds must satisfy 1 <= min <= max");
1175 check_step_count(params);
1177 std::vector<ConcurrentRule<M>> rules = machine.rules();
1178 std::vector<Invariant<M>> invariants = machine.invariants();
1179 if (rules.empty()) {
1180 throw std::invalid_argument(
1181 "Cannot run a concurrent state machine with no rules.");
1184 std::vector<internal::RuleSpec> rule_specs;
1185 std::vector<internal::InvariantSpec> invariant_specs;
1186 std::vector<std::string> group_names;
1187 std::map<std::string, int64_t> group_ids;
1188 rule_specs.reserve(rules.size());
1190 std::vector<int64_t> ids;
1191 ids.reserve(rule.groups().size());
1192 for (
const std::string& group_name : rule.groups()) {
1193 auto [group, inserted] = group_ids.emplace(
1194 group_name,
static_cast<int64_t
>(group_ids.size()));
1196 group_names.push_back(group_name);
1198 ids.push_back(group->second);
1200 rule_specs.push_back({rule.name(), std::move(ids), rule.weight()});
1202 invariant_specs.reserve(invariants.size());
1204 invariant_specs.push_back(
1205 {invariant.name(), invariant.always_check()});
1208 internal::StateMachineHandle machine_handle(
1209 tc, rule_specs, invariant_specs, min_concurrency, max_concurrency,
1211 if (!invariants.empty()) {
1212 tc.
note(
"Checking invariants on the initial state.");
1214 check_invariants(tc, machine, invariants);
1216 enum class EventKind { RoundDone, Invalid, Overrun, Control, Panicked };
1218 EventKind kind = EventKind::RoundDone;
1219 std::optional<internal::CapturedException> exception;
1223 std::condition_variable start;
1224 std::condition_variable done;
1225 uint64_t round_number = 0;
1227 std::size_t num_workers_completed = 0;
1228 std::vector<Event> events;
1230 std::vector<std::optional<TestCase>> cases;
1233 auto classify = [] {
1235 event.exception = internal::capture_current_exception();
1237 std::rethrow_exception(event.exception->exception);
1238 }
catch (
const internal::HegelStopTest&) {
1239 event.kind = EventKind::Overrun;
1240 }
catch (
const internal::HegelLoopDone&) {
1241 event.kind = EventKind::Control;
1242 }
catch (
const internal::HegelReject&) {
1246 event.kind = EventKind::Invalid;
1247 }
catch (
const std::invalid_argument&) {
1248 event.kind = EventKind::Control;
1250 event.kind = EventKind::Panicked;
1255 auto run_round = [&](std::size_t worker, TestCase& worker_tc) {
1258 int64_t rule_index = machine_handle.next_rule(
1259 worker_tc,
static_cast<int64_t
>(worker));
1260 if (rule_index == internal::state_machine_done) {
1263 if (rule_index < 0 ||
1264 static_cast<std::size_t
>(rule_index) >= rules.size()) {
1266 throw std::runtime_error(
1267 "state_machine_next_rule returned out-of-range "
1268 "rule index. Please report this as a bug.");
1273 rules[
static_cast<std::size_t
>(rule_index)];
1274 worker_tc.note(
"Rule: " + rule.name() +
" {");
1276 TestCase rule_tc = internal::block(worker_tc, 2);
1277 rule.step()(rule_tc, machine);
1278 }
catch (
const internal::HegelReject&) {
1279 machine_handle.rule_rejected(
1280 worker_tc,
static_cast<int64_t
>(worker));
1281 internal::block(worker_tc, 2)
1282 .note(
"Rule stopped early due to violated "
1285 worker_tc.note(
"}");
1286 Event
event = classify();
1287 if (event.kind == EventKind::Panicked) {
1288 worker_tc.note(
"Rule " + rule.name() +
" failed:");
1292 worker_tc.note(
"}");
1299 std::size_t worker_count =
1300 static_cast<std::size_t
>(machine_handle.concurrency());
1302 state.events.resize(worker_count);
1303 state.cases.resize(worker_count);
1304 std::vector<std::thread> workers;
1305 workers.reserve(worker_count);
1306 for (std::size_t worker = 0; worker < worker_count; ++worker) {
1307 workers.emplace_back([&, worker]() {
1308 uint64_t observed_round_number = 0;
1310 std::optional<TestCase> worker_tc;
1312 std::unique_lock<std::mutex> lock(state.mutex);
1313 state.start.wait(lock, [&] {
1314 return state.stop ||
1315 state.round_number !=
1316 observed_round_number;
1323 observed_round_number = state.round_number;
1324 worker_tc = std::move(state.cases[worker]);
1325 state.cases[worker].reset();
1329 Event
event = run_round(worker, *worker_tc);
1330 std::lock_guard<std::mutex> lock(state.mutex);
1331 state.events[worker] = std::move(event);
1332 ++state.num_workers_completed;
1334 state.done.notify_one();
1339 auto stop_workers = [&] {
1341 std::lock_guard<std::mutex> lock(state.mutex);
1344 state.start.notify_all();
1345 for (std::thread& worker : workers) {
1351 std::optional<int64_t> noted_concurrency;
1353 int64_t group = machine_handle.next_group(tc);
1354 if (group == internal::state_machine_done) {
1358 static_cast<std::size_t
>(group) >= group_names.size()) {
1360 throw std::runtime_error(
1361 "state_machine_next_group returned an unknown group "
1362 "index. Please report this as a bug.");
1365 if (noted_concurrency != machine_handle.round_concurrency()) {
1366 noted_concurrency = machine_handle.round_concurrency();
1367 tc.
note(
"Concurrency level: " +
1368 std::to_string(*noted_concurrency));
1371 std::lock_guard<std::mutex> lock(state.mutex);
1372 tc.
note(
"---------------- Round " +
1373 std::to_string(state.round_number + 1) +
1375 group_names[
static_cast<std::size_t
>(group)] +
1376 "\" ----------------");
1379 for (std::size_t worker = 0; worker < worker_count;
1381 state.cases[worker] = tc.
clone();
1382 state.cases[worker]->set_worker(worker);
1384 state.num_workers_completed = 0;
1385 ++state.round_number;
1387 state.start.notify_all();
1389 std::unique_lock<std::mutex> lock(state.mutex);
1390 state.done.wait(lock, [&] {
1391 return state.num_workers_completed == worker_count;
1395 std::optional<std::size_t> control;
1396 bool saw_overrun =
false;
1397 bool saw_invalid =
false;
1398 std::optional<std::size_t> panic;
1401 for (std::size_t worker = 0; worker < worker_count; ++worker) {
1402 switch (state.events[worker].kind) {
1403 case EventKind::RoundDone:
1406 case EventKind::Invalid:
1410 case EventKind::Control:
1411 if (!control.has_value()) {
1415 case EventKind::Overrun:
1418 case EventKind::Panicked:
1419 if (!panic.has_value()) {
1425 if (control.has_value()) {
1426 state.events[*control].exception->rethrow();
1429 throw internal::HegelStopTest();
1432 throw internal::HegelReject();
1434 if (panic.has_value()) {
1435 state.events[*panic].exception->rethrow();
1437 check_invariants(tc, machine, invariants,
1438 std::ref(machine_handle));
1441 if (!invariants.empty()) {
1442 tc.
note(
"Checking invariants on the final state.");
1444 check_invariants(tc, machine, invariants);
1482 template <
typename M>
1485 std::is_base_of<StateMachine<M, typename M::state_type>, M>::value,
1486 "run() requires a machine deriving from "
1487 "StateMachine<M, State>.");
1488 check_step_count(params);
1489 std::vector<Rule<M>> rules = machine.rules();
1490 std::vector<Invariant<M>> invariants = machine.invariants();
1491 if (rules.empty()) {
1492 throw std::invalid_argument(
1493 "Cannot run a state machine with no rules.");
1495 std::vector<internal::RuleSpec> rule_specs;
1496 rule_specs.reserve(rules.size());
1497 for (
const Rule<M>& rule : rules) {
1498 rule_specs.push_back({rule.name(), {0}, rule.weight()});
1501 std::vector<internal::InvariantSpec> invariant_specs;
1502 invariant_specs.reserve(invariants.size());
1504 invariant_specs.push_back(
1505 {invariant.name(), invariant.always_check()});
1508 internal::StateMachineHandle machine_handle(
1509 tc, rule_specs, invariant_specs, 1, 1, params.step_count);
1510 if (!invariants.empty()) {
1511 tc.
note(
"Checking invariants on the initial state.");
1513 check_invariants(tc, machine, invariants);
1514 int64_t steps_run = 0;
1518 while (machine_handle.next_group(tc) != internal::state_machine_done) {
1520 int64_t next_rule_idx = machine_handle.next_rule(tc, 0);
1521 if (next_rule_idx == internal::state_machine_done) {
1525 if (next_rule_idx < 0 ||
1526 static_cast<size_t>(next_rule_idx) >= rules.size()) {
1527 throw std::runtime_error(
1528 "state_machine_next_rule returned out-of-range "
1529 "rule index. Please report this as a bug.");
1532 internal::start_span(
1533 tc, internal::label(internal::LabelName::StatefulRule));
1535 const Rule<M>& rule = rules[
static_cast<size_t>(next_rule_idx)];
1536 tc.
note(
"Step " + std::to_string(steps_run) +
": " +
1537 rule.name() +
" {");
1542 TestCase step_tc = internal::block(tc, 2);
1543 rule.step()(step_tc, machine);
1546 internal::stop_span(tc);
1547 }
catch (
const internal::HegelReject&) {
1548 machine_handle.rule_rejected(tc, 0);
1549 internal::block(tc, 2).note(
1550 "Rule stopped early due to violated assumption.");
1552 internal::stop_span(tc,
true);
1553 }
catch (
const internal::HegelStopTest&) {
1555 internal::stop_span(tc);
1557 }
catch (
const internal::HegelLoopDone&) {
1559 internal::stop_span(tc);
1563 tc.
note(
"Rule " + rule.name() +
" failed:");
1564 internal::stop_span(tc);
1568 check_invariants(tc, machine, invariants, std::ref(machine_handle));
1571 if (!invariants.empty()) {
1572 tc.
note(
"Checking invariants on the final state.");
1574 check_invariants(tc, machine, invariants);
Handle to the currently-executing test case.
Definition test_case.h:46
TestCase clone() const
Creates a clone of this test case with an independent choice sequence forked from this test case.
void note(std::string_view message) const
Record a message that will be printed on the final replay of a failing test case.
A printable generator: TestCase::draw() accepts it.
Definition core.h:470
The interface of a generator that draws without printing.
Definition core.h:51
A pool of values that concurrent workers can share.
Definition stateful.h:668
ConcurrentPool(const TestCase &tc)
Creates an empty pool.
Definition stateful.h:675
bool empty() const
Returns true if the pool contains no values.
Definition stateful.h:696
std::size_t size() const
Returns the number of values in the pool.
Definition stateful.h:706
void add(const TestCase &tc, T value)
Adds a value to the pool.
Definition stateful.h:685
An action that a worker can apply to a concurrent state machine.
Definition stateful.h:117
std::function< void(TestCase &, M &)> Step
The function the rule applies.
Definition stateful.h:120
ConcurrentRule(std::string name, std::vector< std::string > groups, double weight, Step step)
Creates a rule in the specified groups with a weight.
Definition stateful.h:153
const std::vector< std::string > & groups() const
Returns the concurrency groups of the rule.
Definition stateful.h:180
ConcurrentRule(ConcurrentRuleParams< M > params)
Creates a rule from named arguments.
Definition stateful.h:164
ConcurrentRule(std::string name, std::vector< std::string > groups, Step step)
Creates a rule in the specified groups.
Definition stateful.h:140
ConcurrentRule(std::string name, Step step)
Creates a rule in anonymous_group.
Definition stateful.h:128
const std::string & name() const
Returns the name of the rule.
Definition stateful.h:173
const Step & step() const
Returns the function the rule applies.
Definition stateful.h:194
double weight() const
Returns the weight of the rule.
Definition stateful.h:187
Base class for a concurrent state machine.
Definition stateful.h:328
std::vector< Invariant< Derived > > invariants() const
Returns the invariants of the machine.
Definition stateful.h:338
virtual T do_draw_filtered(const TestCase &tc, const std::function< bool(const T &)> &predicate) const
Draw a value that predicate accepts, for filter().
Definition core.h:91
An invariant is a predicate that must hold at any point in the stateful test. They are evaluated in f...
Definition stateful.h:939
Invariant(std::string name, std::function< void(const T &)> invariant)
Declare a new invariant.
Definition stateful.h:947
bool pause_faults() const
Returns true if fault injection is paused while this invariant is checked.
Definition stateful.h:996
bool always_check() const
Returns whether the invariant is checked after every step or round instead of sampled.
Definition stateful.h:1004
Invariant(InvariantParams< T > params)
Declare a new invariant from named arguments.
Definition stateful.h:969
const std::string & name() const
Returns the name of the invariant.
Definition stateful.h:980
Invariant(std::string name, bool always_check, std::function< void(const T &)> invariant)
Declare a new invariant that can skip sampling.
Definition stateful.h:958
const std::function< void(const T &)> & invariant() const
Returns the function representing the predicate of the invariant.
Definition stateful.h:987
A pool of previously generated values. A pool lets data flow from one rule to another,...
Definition stateful.h:397
std::size_t size() const
Returns the number of variables in the pool.
Definition stateful.h:442
Pool(const TestCase &tc)
Creates an empty pool. Pools are tied to a test case. Do not reuse one across test cases.
Definition stateful.h:405
void add(T &&element)
Adds element to the pool. Overload for moving rvalues.
Definition stateful.h:427
void add(const T &element)
Adds element to the pool. Overload for copying lvalues.
Definition stateful.h:412
A rule is one possible action in a stateful test.
Definition stateful.h:831
Rule(std::string name, std::function< void(TestCase &, T &)> step)
Declares a new Rule.
Definition stateful.h:842
double weight() const
Returns the weight of the rule.
Definition stateful.h:883
Rule(RuleParams< T > params)
Declares a new Rule from named arguments.
Definition stateful.h:861
const std::function< void(TestCase &, T &)> & step() const
Returns the underlying step function of the rule.
Definition stateful.h:876
const std::string & name() const
Returns the name of the rule.
Definition stateful.h:870
Rule(std::string name, double weight, std::function< void(TestCase &, T &)> step)
Declares a new Rule with a weight.
Definition stateful.h:852
Base class for a state machine. Holds the state and declares the rules and the invariants that act on...
Definition stateful.h:1057
std::vector< Invariant< Derived > > invariants()
Invariants checked in full before the first step and after the final step, and sampled between steps....
Definition stateful.h:1083
State state
The state the rules act on. Rules mutate it in place.
Definition stateful.h:1074
State state_type
The type of the state the rules act on.
Definition stateful.h:1060
StateMachine(StateMachineParams< State > params)
Builds a machine holding the given initial state.
Definition stateful.h:1070
Stateful (model-based) property testing.
Definition stateful.h:66
auto values_consumed(Pool< T > &p)
Returns a value from the pool and removes it.
Definition stateful.h:613
void run_concurrent(M &machine, TestCase &tc, int64_t min_concurrency, int64_t max_concurrency, const RunParams ¶ms={})
Executes a concurrent stateful test with rules from machine.
Definition stateful.h:1166
auto values_reusable(Pool< T > &p)
Returns a value from the pool without removing it.
Definition stateful.h:645
constexpr const char * anonymous_group
The group name for rules that do not specify a group.
Definition stateful.h:75
void run(M &machine, TestCase &tc, const RunParams ¶ms={})
Executes a stateful test by repeatedly applying randomly chosen rules from machine to it....
Definition stateful.h:1483
Arguments for the ConcurrentRule constructor.
Definition stateful.h:90
std::function< void(TestCase &, M &)> step
The function the rule applies.
Definition stateful.h:100
std::string name
The name of the rule.
Definition stateful.h:92
std::vector< std::string > groups
The concurrency groups of the rule.
Definition stateful.h:94
double weight
Definition stateful.h:98
Arguments for the Invariant constructor.
Definition stateful.h:903
bool pause_faults
Definition stateful.h:911
std::string name
The name of the invariant.
Definition stateful.h:905
bool always_check
Definition stateful.h:908
std::function< void(const T &)> invariant
The predicate. It throws when the invariant is violated.
Definition stateful.h:913
Arguments for the Rule constructor.
Definition stateful.h:809
std::function< void(TestCase &, T &)> step
The function the rule applies. See Rule.
Definition stateful.h:816
std::string name
The name of the rule.
Definition stateful.h:811
double weight
Definition stateful.h:814
Options for run and run_concurrent.
Definition stateful.h:1092
int64_t step_count
Definition stateful.h:1096
Arguments for the StateMachine constructor.
Definition stateful.h:1018
State initial_state
The state the first rule acts on.
Definition stateful.h:1020