Hegel 0.18.3
Property-based testing for C++
Loading...
Searching...
No Matches
stateful.h
1#pragma once
2
3#include <condition_variable>
4#include <cstddef>
5#include <cstdint>
6#include <exception>
7#include <functional>
8#include <map>
9#include <memory>
10#include <mutex>
11#include <optional>
12#include <stdexcept>
13#include <string>
14#include <thread>
15#include <type_traits>
16#include <utility>
17#include <vector>
18
19#include "hegel/core.h"
20
66namespace hegel::stateful {
67
70
71 template <typename T> class VariablesGenerator;
72 template <typename T> class Invariant;
73
75 inline constexpr const char* anonymous_group = "<anonymous>";
76
90 template <typename M> struct ConcurrentRuleParams {
92 std::string name;
94 std::vector<std::string> groups = {anonymous_group};
98 double weight = 1.0;
100 std::function<void(TestCase&, M&)> step;
101 };
102
117 template <typename M> class ConcurrentRule {
118 public:
120 using Step = std::function<void(TestCase&, M&)>;
121
129 : ConcurrentRule(std::move(name),
130 std::vector<std::string>{anonymous_group},
131 std::move(step)) {}
132
140 ConcurrentRule(std::string name, std::vector<std::string> groups,
141 Step step)
142 : ConcurrentRule(std::move(name), std::move(groups), 1.0,
143 std::move(step)) {}
144
153 ConcurrentRule(std::string name, std::vector<std::string> groups,
154 double weight, Step step)
156 std::move(groups), weight,
157 std::move(step)}) {}
158
165 : name_(std::move(params.name)), groups_(std::move(params.groups)),
166 weight_(params.weight), step_(std::move(params.step)) {}
167
173 const std::string& name() const { return name_; }
174
180 const std::vector<std::string>& groups() const { return groups_; }
181
187 double weight() const { return weight_; }
188
194 const Step& step() const { return step_; }
195
196 private:
197 std::string name_;
198 std::vector<std::string> groups_;
199 double weight_;
200 Step step_;
201 };
202
328 template <typename Derived> class ConcurrentStateMachine {
329 public:
338 std::vector<Invariant<Derived>> invariants() const { return {}; }
339 };
340
397 template <typename T> class Pool {
398 public:
405 explicit Pool(const TestCase& tc) : tc_(tc), pool_handle_(tc) {}
406
412 void add(const T& element) {
413 int64_t var_id = pool_handle_.add(tc_);
414 // GCOVR_EXCL_START
415 if (pool_.find(var_id) != pool_.end()) {
416 throw std::runtime_error("unexpected variable id in map");
417 }
418 // GCOVR_EXCL_STOP
419 pool_.emplace(var_id, element);
420 }
421
427 void add(T&& element) {
428 int64_t var_id = pool_handle_.add(tc_);
429 // GCOVR_EXCL_START
430 if (pool_.find(var_id) != pool_.end()) {
431 throw std::runtime_error("unexpected variable id in map");
432 }
433 // GCOVR_EXCL_STOP
434 pool_.emplace(var_id, std::move(element));
435 }
436
442 std::size_t size() const { return pool_.size(); }
443
444 Pool(const Pool&) = delete;
445
446 private:
447 const TestCase& tc_;
448 hegel::internal::PoolHandle pool_handle_;
449 std::map<int64_t, T> pool_;
450
451 friend class VariablesGenerator<T>;
452 };
453
455 namespace detail {
456
457 class TakenVariables {
458 public:
459 TakenVariables(const TestCase& tc,
460 hegel::internal::PoolHandle& pool)
461 : tc_(tc), pool_(pool) {}
462 TakenVariables(const TakenVariables&) = delete;
463 TakenVariables& operator=(const TakenVariables&) = delete;
464 ~TakenVariables() {
465 for (int64_t variable : variables_) {
466 pool_.restore_unchecked(tc_, variable);
467 }
468 }
469
470 void add(int64_t variable) { variables_.push_back(variable); }
471
472 void keep_last() { variables_.pop_back(); }
473
474 void restore() {
475 while (!variables_.empty()) {
476 pool_.restore(tc_, variables_.back());
477 variables_.pop_back();
478 }
479 }
480
481 private:
482 const TestCase& tc_;
483 hegel::internal::PoolHandle& pool_;
484 std::vector<int64_t> variables_;
485 };
486
487 // A filtered consuming draw from a pool whose values `values` holds
488 // by variable id. Each attempt consumes a variable the engine
489 // chooses, in a span that is discarded when `predicate` rejects its
490 // value. A rejected variable stays consumed until the attempts are
491 // over, so no later attempt draws it again, and is then put back.
492 // Only the accepted value leaves the pool.
493 template <typename T>
494 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);
507 taken.add(variable);
508 hi::stop_span(tc);
509 T& value = values.at(variable);
510 if (predicate(value)) {
511 hi::stop_span(tc);
512 taken.keep_last();
513 accepted = std::move(value);
514 values.erase(variable);
515 } else {
516 hi::stop_span(tc, true);
517 }
518 }
519 taken.restore();
520 if (!accepted) {
521 tc.reject();
522 }
523 return std::move(*accepted);
524 }
525
526 } // namespace detail
528
530 // Concrete IGenerator for variables.
531 template <typename T>
533 : public generators::detail::value_base_t<T, is_representable_v<T>> {
534 public:
535 explicit VariablesGenerator(Pool<T>& p, bool consume)
536 : p_(p), consume_(consume) {}
537
538 T do_draw(const TestCase& tc) const override {
539 int64_t variable = p_.pool_handle_.draw_variable(tc, consume_);
540
541 auto it = p_.pool_.find(variable);
542 // GCOVR_EXCL_START
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.");
547 }
548 // GCOVR_EXCL_STOP
549 if (consume_) {
550 auto val = std::move(it->second);
551 p_.pool_.erase(it);
552 return val;
553 }
554 return it->second;
555 }
556
557 uint64_t label() const override {
558 return hegel::internal::label(
559 consume_ ? hegel::internal::LabelName::PoolValuesConsumed
560 : hegel::internal::LabelName::PoolValuesReusable);
561 }
562
563 T do_draw_filtered(
564 const TestCase& tc,
565 const std::function<bool(const T&)>& predicate) const override {
566 if (!consume_) {
567 return IGenerator<T>::do_draw_filtered(tc, predicate);
568 }
569 return detail::draw_filtered_consumed(tc, p_.pool_handle_, p_.pool_,
570 this->label(), predicate);
571 }
572
573 private:
574 Pool<T>& p_;
575 bool consume_;
576 };
578
581
613 template <typename T> auto values_consumed(Pool<T>& p) {
614 return generators::detail::handle_t<is_representable_v<T>, T>(
615 std::make_shared<VariablesGenerator<T>>(p, true));
616 }
617
645 template <typename T> auto values_reusable(Pool<T>& p) {
646 return generators::detail::handle_t<is_representable_v<T>, T>(
647 std::make_shared<VariablesGenerator<T>>(p, false));
648 }
649
651 template <typename T> class ConcurrentVariablesGenerator;
653
668 template <typename T> class ConcurrentPool {
669 public:
675 explicit ConcurrentPool(const TestCase& tc) : pool_handle_(tc) {}
676
685 void add(const TestCase& tc, T value) {
686 std::lock_guard<std::mutex> lock(mutex_);
687 int64_t variable = pool_handle_.add(tc);
688 values_.emplace(variable, std::move(value));
689 }
690
696 bool empty() const {
697 std::lock_guard<std::mutex> lock(mutex_);
698 return values_.empty();
699 }
700
706 std::size_t size() const {
707 std::lock_guard<std::mutex> lock(mutex_);
708 return values_.size();
709 }
710
711 ConcurrentPool(const ConcurrentPool&) = delete;
712 ConcurrentPool& operator=(const ConcurrentPool&) = delete;
713
714 private:
715 internal::PoolHandle pool_handle_;
716 mutable std::mutex mutex_;
717 std::map<int64_t, T> values_;
718
719 friend class ConcurrentVariablesGenerator<T>;
720 };
721
723 template <typename T>
724 class ConcurrentVariablesGenerator
725 : public generators::detail::value_base_t<T, is_representable_v<T>> {
726 public:
727 ConcurrentVariablesGenerator(ConcurrentPool<T>& pool, bool consume)
728 : pool_(pool), consume_(consume) {}
729
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_);
733 if (consume_) {
734 T result = std::move(pool_.values_.at(variable));
735 pool_.values_.erase(variable);
736 return result;
737 } else {
738 return pool_.values_.at(variable);
739 }
740 }
741
742 uint64_t label() const override {
743 return hegel::internal::label(
744 consume_ ? hegel::internal::LabelName::PoolValuesConsumed
745 : hegel::internal::LabelName::PoolValuesReusable);
746 }
747
748 T do_draw_filtered(
749 const TestCase& tc,
750 const std::function<bool(const T&)>& predicate) const override {
751 if (!consume_) {
752 return IGenerator<T>::do_draw_filtered(tc, predicate);
753 }
754 std::lock_guard<std::mutex> lock(pool_.mutex_);
755 return detail::draw_filtered_consumed(tc, pool_.pool_handle_,
756 pool_.values_, this->label(),
757 predicate);
758 }
759
760 private:
761 ConcurrentPool<T>& pool_;
762 bool consume_;
763 };
765
777 template <typename T> auto values_consumed(ConcurrentPool<T>& pool) {
778 return generators::detail::handle_t<is_representable_v<T>, T>(
779 std::make_shared<ConcurrentVariablesGenerator<T>>(pool, true));
780 }
781
792 template <typename T> auto values_reusable(ConcurrentPool<T>& pool) {
793 return generators::detail::handle_t<is_representable_v<T>, T>(
794 std::make_shared<ConcurrentVariablesGenerator<T>>(pool, false));
795 }
796
809 template <typename T> struct RuleParams {
811 std::string name;
814 double weight = 1.0;
816 std::function<void(TestCase&, T&)> step;
817 };
818
831 template <typename T> class Rule {
832 public:
842 explicit Rule(std::string name, std::function<void(TestCase&, T&)> step)
843 : Rule(std::move(name), 1.0, std::move(step)) {}
844
852 Rule(std::string name, double weight,
853 std::function<void(TestCase&, T&)> step)
854 : Rule(RuleParams<T>{std::move(name), weight, std::move(step)}) {}
855
861 explicit Rule(RuleParams<T> params)
862 : name_(std::move(params.name)), weight_(params.weight),
863 step_(std::move(params.step)) {}
864
870 const std::string& name() const { return name_; }
876 const std::function<void(TestCase&, T&)>& step() const { return step_; }
877
883 double weight() const { return weight_; }
884
885 private:
886 std::string name_;
887 double weight_;
888 std::function<void(TestCase&, T&)> step_;
889 };
890
903 template <typename T> struct InvariantParams {
905 std::string name;
908 bool always_check = false;
911 bool pause_faults = false;
913 std::function<void(const T&)> invariant;
914 };
915
939 template <typename T> class Invariant {
940 public:
947 explicit Invariant(std::string name,
948 std::function<void(const T&)> invariant)
949 : Invariant(std::move(name), false, std::move(invariant)) {}
950
958 Invariant(std::string name, bool always_check,
959 std::function<void(const T&)> invariant)
960 : Invariant(InvariantParams<T>{std::move(name), always_check, false,
961 std::move(invariant)}) {}
962
970 : name_(std::move(params.name)),
971 invariant_(std::move(params.invariant)),
972 always_check_(params.always_check),
973 pause_faults_(params.pause_faults) {}
974
980 const std::string& name() const { return name_; }
987 const std::function<void(const T&)>& invariant() const {
988 return invariant_;
989 }
990
996 bool pause_faults() const { return pause_faults_; }
997
1004 bool always_check() const { return always_check_; }
1005
1006 private:
1007 std::string name_;
1008 std::function<void(const T&)> invariant_;
1009 bool always_check_;
1010 bool pause_faults_;
1011 };
1012
1018 template <typename State> struct StateMachineParams {
1021 };
1022
1057 template <typename Derived, typename State> class StateMachine {
1058 public:
1060 using state_type = State;
1071 : state(std::move(params.initial_state)) {}
1072
1074 State state;
1075
1083 std::vector<Invariant<Derived>> invariants() { return {}; }
1084
1085 protected:
1086 ~StateMachine() = default;
1087 };
1088
1092 struct RunParams {
1096 int64_t step_count = 50;
1097 };
1098
1100 template <typename T>
1101 void check_invariants(
1102 TestCase& tc, const T& state,
1103 const std::vector<Invariant<T>>& 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))) {
1110 continue;
1111 }
1112 const Invariant<T>& inv = invariants[index];
1113 try {
1114 internal::PauseFaultsScope pause(tc, inv.pause_faults());
1115 inv.invariant()(state);
1116 } catch (...) {
1117 tc.note("Invariant " + inv.name() + " failed:");
1118 throw;
1119 }
1120 }
1121 }
1122
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");
1127 }
1128 }
1130
1165 template <typename M>
1166 void run_concurrent(M& machine, TestCase& tc, int64_t min_concurrency,
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");
1174 }
1175 check_step_count(params);
1176
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.");
1182 }
1183
1184 std::vector<internal::RuleSpec> rule_specs;
1185 std::vector<internal::InvariantSpec> invariant_specs;
1186 std::vector<std::string> group_names; // maps group ID to name
1187 std::map<std::string, int64_t> group_ids; // maps group name to ID
1188 rule_specs.reserve(rules.size());
1189 for (const ConcurrentRule<M>& rule : rules) {
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()));
1195 if (inserted) {
1196 group_names.push_back(group_name);
1197 }
1198 ids.push_back(group->second);
1199 }
1200 rule_specs.push_back({rule.name(), std::move(ids), rule.weight()});
1201 }
1202 invariant_specs.reserve(invariants.size());
1203 for (const Invariant<M>& invariant : invariants) {
1204 invariant_specs.push_back(
1205 {invariant.name(), invariant.always_check()});
1206 }
1207
1208 internal::StateMachineHandle machine_handle(
1209 tc, rule_specs, invariant_specs, min_concurrency, max_concurrency,
1210 params.step_count);
1211 if (!invariants.empty()) {
1212 tc.note("Checking invariants on the initial state.");
1213 }
1214 check_invariants(tc, machine, invariants);
1215
1216 enum class EventKind { RoundDone, Invalid, Overrun, Control, Panicked };
1217 struct Event {
1218 EventKind kind = EventKind::RoundDone;
1219 std::optional<internal::CapturedException> exception;
1220 };
1221 struct RoundState {
1222 std::mutex mutex;
1223 std::condition_variable start;
1224 std::condition_variable done;
1225 uint64_t round_number = 0;
1226 bool stop = false;
1227 std::size_t num_workers_completed = 0;
1228 std::vector<Event> events;
1229 // The test case each worker draws from in the current round.
1230 std::vector<std::optional<TestCase>> cases;
1231 };
1232
1233 auto classify = [] {
1234 Event event;
1235 event.exception = internal::capture_current_exception();
1236 try {
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&) {
1243 // not the same as rule rejection - entire test case is rejected
1244 // requires some worker race on cloned test cases with same
1245 // parent
1246 event.kind = EventKind::Invalid; // GCOVR_EXCL_LINE
1247 } catch (const std::invalid_argument&) {
1248 event.kind = EventKind::Control;
1249 } catch (...) {
1250 event.kind = EventKind::Panicked;
1251 }
1252 return event;
1253 };
1254
1255 auto run_round = [&](std::size_t worker, TestCase& worker_tc) {
1256 try {
1257 while (true) {
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) {
1261 return Event{};
1262 }
1263 if (rule_index < 0 ||
1264 static_cast<std::size_t>(rule_index) >= rules.size()) {
1265 // GCOVR_EXCL_START
1266 throw std::runtime_error(
1267 "state_machine_next_rule returned out-of-range "
1268 "rule index. Please report this as a bug.");
1269 // GCOVR_EXCL_STOP
1270 }
1271
1272 const ConcurrentRule<M>& rule =
1273 rules[static_cast<std::size_t>(rule_index)];
1274 worker_tc.note("Rule: " + rule.name() + " {");
1275 try {
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 "
1283 "assumption.");
1284 } catch (...) {
1285 worker_tc.note("}");
1286 Event event = classify();
1287 if (event.kind == EventKind::Panicked) {
1288 worker_tc.note("Rule " + rule.name() + " failed:");
1289 }
1290 return event;
1291 }
1292 worker_tc.note("}");
1293 }
1294 } catch (...) {
1295 return classify();
1296 }
1297 };
1298
1299 std::size_t worker_count =
1300 static_cast<std::size_t>(machine_handle.concurrency());
1301 RoundState state;
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;
1309 while (true) {
1310 std::optional<TestCase> worker_tc;
1311 {
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; // main thread
1317 // started a
1318 // new round
1319 });
1320 if (state.stop) {
1321 return;
1322 }
1323 observed_round_number = state.round_number;
1324 worker_tc = std::move(state.cases[worker]);
1325 state.cases[worker].reset();
1326 }
1327
1328 {
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;
1333 }
1334 state.done.notify_one();
1335 }
1336 });
1337 }
1338
1339 auto stop_workers = [&] {
1340 {
1341 std::lock_guard<std::mutex> lock(state.mutex);
1342 state.stop = true;
1343 }
1344 state.start.notify_all();
1345 for (std::thread& worker : workers) {
1346 worker.join();
1347 }
1348 };
1349
1350 try {
1351 std::optional<int64_t> noted_concurrency;
1352 while (true) {
1353 int64_t group = machine_handle.next_group(tc);
1354 if (group == internal::state_machine_done) {
1355 break;
1356 }
1357 if (group < 0 ||
1358 static_cast<std::size_t>(group) >= group_names.size()) {
1359 // GCOVR_EXCL_START
1360 throw std::runtime_error(
1361 "state_machine_next_group returned an unknown group "
1362 "index. Please report this as a bug.");
1363 // GCOVR_EXCL_STOP
1364 }
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));
1369 }
1370 {
1371 std::lock_guard<std::mutex> lock(state.mutex);
1372 tc.note("---------------- Round " +
1373 std::to_string(state.round_number + 1) +
1374 ": group \"" +
1375 group_names[static_cast<std::size_t>(group)] +
1376 "\" ----------------");
1377 // Each worker prints into a clone made after the round's
1378 // header, so its lines appear under that header.
1379 for (std::size_t worker = 0; worker < worker_count;
1380 ++worker) {
1381 state.cases[worker] = tc.clone();
1382 state.cases[worker]->set_worker(worker);
1383 }
1384 state.num_workers_completed = 0;
1385 ++state.round_number;
1386 }
1387 state.start.notify_all();
1388 {
1389 std::unique_lock<std::mutex> lock(state.mutex);
1390 state.done.wait(lock, [&] {
1391 return state.num_workers_completed == worker_count;
1392 });
1393 }
1394
1395 std::optional<std::size_t> control;
1396 bool saw_overrun = false;
1397 bool saw_invalid = false;
1398 std::optional<std::size_t> panic;
1399 // need to collect every event because the precedence is
1400 // control > overrun > invalid > panic > round complete
1401 for (std::size_t worker = 0; worker < worker_count; ++worker) {
1402 switch (state.events[worker].kind) {
1403 case EventKind::RoundDone:
1404 break;
1405 // GCOVR_EXCL_START
1406 case EventKind::Invalid:
1407 saw_invalid = true;
1408 break;
1409 // GCOVR_EXCL_STOP
1410 case EventKind::Control:
1411 if (!control.has_value()) {
1412 control = worker;
1413 }
1414 break;
1415 case EventKind::Overrun:
1416 saw_overrun = true;
1417 break;
1418 case EventKind::Panicked:
1419 if (!panic.has_value()) {
1420 panic = worker;
1421 }
1422 break;
1423 }
1424 }
1425 if (control.has_value()) {
1426 state.events[*control].exception->rethrow();
1427 }
1428 if (saw_overrun) {
1429 throw internal::HegelStopTest();
1430 }
1431 if (saw_invalid) {
1432 throw internal::HegelReject(); // GCOVR_EXCL_LINE
1433 }
1434 if (panic.has_value()) {
1435 state.events[*panic].exception->rethrow();
1436 }
1437 check_invariants(tc, machine, invariants,
1438 std::ref(machine_handle));
1439 }
1440
1441 if (!invariants.empty()) {
1442 tc.note("Checking invariants on the final state.");
1443 }
1444 check_invariants(tc, machine, invariants);
1445 } catch (...) {
1446 stop_workers();
1447 throw;
1448 }
1449 stop_workers();
1450 }
1451
1482 template <typename M>
1483 void run(M& machine, TestCase& tc, const RunParams& params = {}) {
1484 static_assert(
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.");
1494 }
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()});
1499 }
1500
1501 std::vector<internal::InvariantSpec> invariant_specs;
1502 invariant_specs.reserve(invariants.size());
1503 for (const Invariant<M>& invariant : invariants) {
1504 invariant_specs.push_back(
1505 {invariant.name(), invariant.always_check()});
1506 }
1507
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.");
1512 }
1513 check_invariants(tc, machine, invariants);
1514 int64_t steps_run = 0;
1515
1516 // Sequential stateful testing is modeled as a concurrent stateful test
1517 // with one group and one worker.
1518 while (machine_handle.next_group(tc) != internal::state_machine_done) {
1519 while (true) {
1520 int64_t next_rule_idx = machine_handle.next_rule(tc, 0);
1521 if (next_rule_idx == internal::state_machine_done) {
1522 break;
1523 }
1524 // GCOVR_EXCL_START
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.");
1530 }
1531 // GCOVR_EXCL_STOP
1532 internal::start_span(
1533 tc, internal::label(internal::LabelName::StatefulRule));
1534 steps_run++;
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() + " {");
1538
1539 try {
1540 // nest the draws the step makes under its "Step N" header.
1541 {
1542 TestCase step_tc = internal::block(tc, 2);
1543 rule.step()(step_tc, machine);
1544 }
1545 tc.note("}");
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.");
1551 tc.note("}");
1552 internal::stop_span(tc, true);
1553 } catch (const internal::HegelStopTest&) {
1554 tc.note("}");
1555 internal::stop_span(tc);
1556 throw;
1557 } catch (const internal::HegelLoopDone&) {
1558 tc.note("}");
1559 internal::stop_span(tc);
1560 throw;
1561 } catch (...) {
1562 tc.note("}");
1563 tc.note("Rule " + rule.name() + " failed:");
1564 internal::stop_span(tc);
1565 throw;
1566 }
1567 }
1568 check_invariants(tc, machine, invariants, std::ref(machine_handle));
1569 }
1570
1571 if (!invariants.empty()) {
1572 tc.note("Checking invariants on the final state.");
1573 }
1574 check_invariants(tc, machine, invariants);
1575 }
1576
1577
1578} // namespace hegel::stateful
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
Definition stateful.h:71
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 &params={})
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 &params={})
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