-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsystematic_testing.h
3028 lines (2593 loc) · 117 KB
/
systematic_testing.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#ifndef SYSTEMATIC_TESTING_H
#define SYSTEMATIC_TESTING_H
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <optional>
#include <set>
#include <sstream>
#include <string>
#include <thread>
#include <tuple>
#include <vector>
#ifdef __linux__
# ifdef SYSTEST_EXPORT
# define SYSTEST_API __attribute__((visibility("default")))
# else
# define SYSTEST_API
# endif
#elif _WIN32
# ifdef SYSTEST_EXPORT
# define SYSTEST_API __declspec(dllexport)
# else
# define SYSTEST_API __declspec(dllimport)
# endif
#else
# ifdef SYSTEST_EXPORT
# define SYSTEST_API
# else
# define SYSTEST_API
# endif
#endif
namespace SystematicTesting
{
class TestEngine;
// Used to convert microseconds to ticks.
static const size_t TICKS_PER_MICROSECOND = 10;
// The verbosity level used by the scheduler.
enum class VerbosityLevel
{
None = 0,
Error,
Warning,
Info,
Debug,
Exhaustive
};
class Logger
{
public:
Logger(VerbosityLevel verbosity_level) noexcept :
m_verbosity_level(verbosity_level)
{
}
template<class... Args>
void log_error(const Args&... args) const
{
if (m_verbosity_level >= VerbosityLevel::Error)
{
(std::cout << ... << args) << std::endl;
}
}
template<class... Args>
void log_warning(const Args&... args) const
{
if (m_verbosity_level >= VerbosityLevel::Warning)
{
(std::cout << ... << args) << std::endl;
}
}
template<class... Args>
void log_info(const Args&... args) const
{
if (m_verbosity_level >= VerbosityLevel::Info)
{
(std::cout << ... << args) << std::endl;
}
}
template<class... Args>
void log_debug(const Args&... args) const
{
if (m_verbosity_level >= VerbosityLevel::Debug)
{
(std::cout << ... << args) << std::endl;
}
}
template<class... Args>
void log_exhaustive(const Args&... args) const
{
if (m_verbosity_level >= VerbosityLevel::Exhaustive)
{
(std::cout << ... << args) << std::endl;
}
}
template<class... Args>
static std::string format(const Args&... args)
{
std::ostringstream result;
(result << ... << args);
return result.str();
}
// Returns the defined verbosity level.
VerbosityLevel verbosity_level() const noexcept
{
return m_verbosity_level;
}
private:
// The defined verbosity level.
const VerbosityLevel m_verbosity_level;
};
// The type of the exploration strategy to use.
enum class StrategyType
{
Random = 0,
Prioritization,
Replay
};
// The systematic test engine settings.
class Settings
{
public:
Settings() noexcept :
m_strategy_type(StrategyType::Random),
m_strategy_bound(100),
m_seed_state(0),
m_replay_trace(),
m_is_resource_race_checking_enabled(false),
m_is_partially_controlled_concurrency_allowed(true),
m_partially_controlled_concurrency_resolution_interval(100),
m_verbosity_level(VerbosityLevel::None)
{
}
// Configures the engine to use the random exploration strategy with the specified
// probability of deviating from the currently scheduled enabled operation.
void with_random_strategy(size_t probability = 100)
{
size_t max_probability = 100;
if (probability > max_probability)
{
throw std::runtime_error(Logger::format("cannot assign probability greater than ", max_probability));
}
m_strategy_type = StrategyType::Random;
m_strategy_bound = probability;
}
// Configures the engine to use the prioritized exploration strategy with the specified
// bound of priority change points that allow deviation from the currently scheduled
// enabled operation.
void with_prioritization_strategy(size_t priority_change_bound = 10)
{
m_strategy_type = StrategyType::Prioritization;
m_strategy_bound = priority_change_bound;
}
// Configures the engine to use the replay exploration strategy with the specified random generator
// seed and trace (sequence of nondeterministic choices) to reproduce an execution.
void with_replay_strategy(const std::string& trace)
{
m_strategy_type = StrategyType::Replay;
m_replay_trace = trace;
}
// Configures the engine to enable race checking for synchronization resources, which introduces
// extra scheduling points when an operation accesses a resource.
void with_resource_race_checking_enabled(bool is_enabled) noexcept
{
m_is_resource_race_checking_enabled = is_enabled;
}
// Configures the engine to allow executions with uncontrolled concurrency and
// enables heuristics to try resolve such instances while maintaining as high
// coverage as possible.
void with_partially_controlled_concurrency_allowed(bool is_allowed = true) noexcept
{
m_is_partially_controlled_concurrency_allowed = is_allowed;
}
// Configures the time interval (in microseconds) to wait before checking
// if uncontrolled concurrency has resolved.
void with_partially_controlled_concurrency_resolution_interval(size_t interval) noexcept
{
m_partially_controlled_concurrency_resolution_interval = interval;
}
// Configures the engine to use the specified initial random generator seed.
// Each new test iteration increments this seed by 1 to assign a unique seed
// per iteration.
void with_random_generator_seed(size_t seed) noexcept
{
m_seed_state = seed;
}
// Configures the engine to use the defined verbosity level.
void with_verbosity_level(VerbosityLevel verbosity_level) noexcept
{
m_verbosity_level = verbosity_level;
}
// Returns the type of the installed exploration strategy.
StrategyType exploration_strategy() const noexcept
{
return m_strategy_type;
}
// Returns an exploration strategy specific bound.
size_t exploration_strategy_bound() const noexcept
{
return m_strategy_bound;
}
// Checks if race checking for synchronization resources is enabled.
bool is_resource_race_checking_enabled() const noexcept
{
return m_is_resource_race_checking_enabled;
}
// Checks if partially controlled concurrency is allowed.
bool is_partially_controlled_concurrency_allowed() const noexcept
{
return m_is_partially_controlled_concurrency_allowed;
}
// Returns the time interval (in microseconds) to wait before checking
// if uncontrolled concurrency has resolved.
size_t partially_controlled_concurrency_resolution_interval() const noexcept
{
return m_partially_controlled_concurrency_resolution_interval;
}
// Returns the seed used by randomized strategies.
size_t random_seed() const noexcept
{
return m_seed_state;
}
// Returns the trace used by the replay strategy to reproduce an execution.
const std::string& replay_trace() const noexcept
{
return m_replay_trace;
}
// Returns the defined verbosity level.
VerbosityLevel verbosity_level() const noexcept
{
return m_verbosity_level;
}
private:
// The execution exploration strategy.
StrategyType m_strategy_type;
// A strategy-specific bound.
size_t m_strategy_bound;
// The seed used by randomized strategies.
size_t m_seed_state;
// The trace used by the replay strategy to reproduce an execution.
std::string m_replay_trace;
// True if race checking for resources is enabled.
bool m_is_resource_race_checking_enabled;
// True if partially controlled concurrency is allowed.
bool m_is_partially_controlled_concurrency_allowed;
// The time interval (in microseconds) to wait before checking
// if uncontrolled concurrency has resolved.
size_t m_partially_controlled_concurrency_resolution_interval;
// The defined verbosity level.
VerbosityLevel m_verbosity_level;
};
// Report with exploration statistics and coverage information.
class TestReport
{
private:
// Give private access to the test engine.
friend class SystematicTesting::TestEngine;
public:
// Returns the number of iterations performed.
size_t iterations() const noexcept
{
return m_iterations;
}
// Returns the number of bugs found during testing.
size_t bugs_found() const noexcept
{
return m_bugs_found;
}
// Returns the number of unique execution paths explored during testing.
size_t explored_execution_paths() const noexcept
{
return m_explored_paths.size();
}
// Returns the number of unique states visited during testing.
size_t visited_states() const noexcept
{
return m_visited_states.size();
}
// Returns the total number of scheduling decisions.
size_t total_scheduling_decisions() const noexcept
{
return m_scheduling_decisions;
}
// Returns the average number of scheduling decisions per iteration.
size_t avg_scheduling_decisions() const noexcept
{
return m_iterations > 0 ? (size_t) std::round(m_scheduling_decisions / m_iterations) : 0;
}
// Returns the total number of controlled operations.
size_t total_controlled_operations() const noexcept
{
return m_operations;
}
// Returns the average number of controlled operations per iteration.
size_t avg_controlled_operations() const noexcept
{
return m_iterations > 0 ? (size_t) std::round(m_operations / m_iterations) : 0;
}
// Returns the number of unique controlled operation creation sequences.
size_t controlled_operation_creation_sequences() const noexcept
{
return m_op_creation_sequences;
}
// Returns the max number of controlled operations that were enabled for scheduling
// at the same time during testing.
size_t max_concurrency_degree() const noexcept
{
return m_concurrency_degree;
}
// Returns the total number of controlled resources.
size_t total_controlled_resources() const noexcept
{
return m_resources;
}
// Returns the average number of controlled resources per iteration.
size_t avg_controlled_resources() const noexcept
{
return m_iterations > 0 ? (size_t) std::round(m_resources / m_iterations) : 0;
}
// Returns the max number of synchronization resources that were controlled
// at the same time during testing.
size_t max_synchronization_degree() const noexcept
{
return m_synchronization_degree;
}
// Returns the total number of uncontrolled threads.
size_t total_uncontrolled_threads() const noexcept
{
return m_uncontrolled_threads;
}
// Returns the average number of uncontrolled threads per iteration.
size_t avg_uncontrolled_threads() const noexcept
{
return m_iterations > 0 ? (size_t) std::round(m_uncontrolled_threads / m_iterations) : 0;
}
// Returns the total number of detached threads.
size_t total_detached_threads() const noexcept
{
return m_detached_threads + m_global_detached_threads;
}
// Returns the seed used in the last test iteration.
size_t last_seed() const noexcept
{
return m_last_seed;
}
// Returns the sequence of choices made in the last test iteration, which can be used
// to replay the same test iteration if configured in the test engine settings.
const std::string& last_trace() const noexcept
{
return m_last_trace;
}
// Returns the total test duration in milliseconds across all iterations.
size_t elapsed_time() const noexcept
{
return m_elapsed_test_time;
}
// Returns the average test duration in milliseconds per iteration.
size_t avg_elapsed_time() const noexcept
{
return m_iterations > 0 ? (size_t) std::round(m_elapsed_test_time / m_iterations) : 0;
}
// Returns the total unattached duration in milliseconds across all iterations.
size_t elapsed_unattached_time() const noexcept
{
return m_elapsed_unattached_time;
}
// Returns the average unattached duration in milliseconds per iteration.
size_t avg_elapsed_unattached_time() const noexcept
{
return m_iterations > 0 ? (size_t) std::round(m_elapsed_unattached_time / m_iterations) : 0;
}
// Returns a string containing exploration statistics and coverage metrics.
std::string to_string() const
{
std::ostringstream report;
report << "========================================================" << std::endl;
report << "===== exploration information and coverage metrics =====" << std::endl;
report << "========================================================" << std::endl;
report << "|_ used the '" << m_strategy << "' exploration strategy." << std::endl;
report << "|_ ran '" << m_iterations << "' test iteration" << (m_iterations == 1 ? "" : "s") << "." << std::endl;
if (m_iterations > 0)
{
report << "| |_ found '" << m_bugs_found << "' bug" << (m_bugs_found == 1 ? "" : "s") << "." << std::endl;
report << "| |_ explored '" << m_explored_paths.size() << "' unique path" <<
(m_explored_paths.size() == 1 ? "" : "s") << "." << std::endl;
report << "| |_ visited '" << m_visited_states.size() << "' unique state" <<
(m_visited_states.size() == 1 ? "" : "s") << "." << std::endl;
report << "| |_ last iteration used the '" << m_last_seed << "' seed." << std::endl;
if (m_scheduling_decisions > 0)
{
report << "|_ scheduling decisions:" << std::endl;
report << "| |_ '" << m_scheduling_decisions << "' decisions ('" << avg_scheduling_decisions() <<
"' per iteration)." << std::endl;
}
if (m_operations > 0)
{
report << "|_ controlled operations (i.e., tasks and threads):" << std::endl;
report << "| |_ '" << m_operations << "' operations ('" << avg_controlled_operations() <<
"' per iteration)." << std::endl;
report << "| |_ '" << m_op_creation_sequences << "' unique creation sequences." << std::endl;
report << "| |_ '" << m_concurrency_degree << "' max degree of concurrency." << std::endl;
}
if (m_resources > 0)
{
report << "|_ controlled resources (i.e., locks):" << std::endl;
report << "| |_ '" << m_resources << "' resources ('" << avg_controlled_resources() <<
"' per iteration)." << std::endl;
report << "| |_ '" << m_synchronization_degree << "' max degree of synchronization." << std::endl;
}
auto detached_threads = m_detached_threads + m_global_detached_threads;
if (m_uncontrolled_threads > 0 || detached_threads > 0)
{
report << "|_ uncontrolled concurrency:" << std::endl;
if (m_uncontrolled_threads > 0)
{
report << "| |_ detected '" << m_uncontrolled_threads << "' uncontrolled threads ('" <<
avg_uncontrolled_threads() << "' per iteration)." << std::endl;
}
if (detached_threads > 0)
{
report << "| |_ detected '" << detached_threads << "' detached threads." << std::endl;
}
}
report << "|_ elapsed time in milliseconds:" << std::endl;
report << "| |_ '" << m_elapsed_test_time << "ms' ('" << avg_elapsed_time() <<
"ms' per iteration)." << std::endl;
report << "| |_ '" << m_elapsed_unattached_time << "ms' while unattached ('" <<
avg_elapsed_unattached_time() << "ms' per iteration)." << std::endl;
}
report << "========================================================";
return report.str();
}
private:
// The exploration strategy used during testing.
const std::string m_strategy;
// Number of test iterations completed.
size_t m_iterations;
// Number of bugs found during testing.
size_t m_bugs_found;
// Set of unique execution paths that were explored during testing.
std::set<std::string> m_explored_paths;
// Set of unique states that were visited during testing.
std::set<size_t> m_visited_states;
// Number of scheduling decisions taken during testing.
size_t m_scheduling_decisions;
// The total number of operations that were controlled during testing.
size_t m_operations;
// Number of unique controlled operation creation sequences during testing.
size_t m_op_creation_sequences;
// The max number of controlled operations that were enabled for scheduling
// at the same time during testing.
size_t m_concurrency_degree;
// The total number of resources that were controlled during testing.
size_t m_resources;
// The max number of synchronization resources that were controlled
// at the same time during testing.
size_t m_synchronization_degree;
// The total number of known uncontrolled threads during testing.
size_t m_uncontrolled_threads;
// The total number of known detached threads during testing.
size_t m_detached_threads;
// The total number of known detached threads during testing.
size_t m_global_detached_threads;
// The seed used by the last test iteration.
size_t m_last_seed;
// The sequence of nondeterministic choices made in the last test iteration.
std::string m_last_trace;
// The test duration in milliseconds across all iterations.
size_t m_elapsed_test_time;
// The unattached duration in milliseconds across all iterations.
size_t m_elapsed_unattached_time;
TestReport(const std::string& strategy) noexcept :
m_strategy(strategy),
m_iterations(0),
m_bugs_found(0),
m_explored_paths(),
m_visited_states(),
m_scheduling_decisions(0),
m_operations(0),
m_op_creation_sequences(0),
m_concurrency_degree(0),
m_resources(0),
m_synchronization_degree(0),
m_uncontrolled_threads(0),
m_detached_threads(0),
m_global_detached_threads(0),
m_last_seed(0),
m_last_trace(),
m_elapsed_test_time(0),
m_elapsed_unattached_time(0)
{
}
};
namespace Exceptions
{
class TestEngineNotInitializedError : public std::runtime_error
{
public:
TestEngineNotInitializedError() : std::runtime_error("test engine is not initialized") {}
};
class TestEngineAlreadyInitializedError : public std::runtime_error
{
public:
TestEngineAlreadyInitializedError() : std::runtime_error("test engine is already initialized") {}
};
class TestEngineDetachedError : public std::runtime_error
{
public:
TestEngineDetachedError() : std::runtime_error("test engine is detached") {}
};
class OperationAlreadyExistsError : public std::runtime_error
{
public:
OperationAlreadyExistsError(size_t op_id)
: std::runtime_error(Logger::format("operation '", op_id, "' already exists"))
{}
};
class OperationNotFoundError : public std::runtime_error
{
public:
OperationNotFoundError(size_t op_id)
: std::runtime_error(Logger::format("operation '", op_id, "' does not exist"))
{}
};
class ResourceAlreadyExistsError : public std::runtime_error
{
public:
ResourceAlreadyExistsError(size_t resource_id)
: std::runtime_error(Logger::format("resource '", resource_id, "' already exists"))
{}
};
class ResourceNotFoundError : public std::runtime_error
{
public:
ResourceNotFoundError(size_t resource_id)
: std::runtime_error(Logger::format("resource '", resource_id, "' does not exist"))
{}
};
class UncontrolledInvocationError : public std::runtime_error
{
public:
UncontrolledInvocationError() : std::runtime_error("uncontrolled invocation") {}
};
class DeadlockError : public std::runtime_error
{
public:
DeadlockError() : std::runtime_error("deadlock detected") {}
};
class InstrumentationError : public std::runtime_error
{
public:
InstrumentationError(std::string error) : std::runtime_error(Logger::format("instrumentation error(", error, ")")) {}
};
} // namespace SystematicTesting::Exceptions
namespace Runtime
{
// The status of a controlled operation.
enum class OperationStatus
{
None = 0,
Enabled,
BlockedOnWaitAll,
BlockedOnWaitAny,
BlockedOnResource,
Completed
};
// Models a concurrent operation that is controlled by the test engine.
class Operation
{
private:
// Give private access to the test engine.
friend class SystematicTesting::TestEngine;
// The creation sequence vector of this operation.
std::vector<size_t> m_creation_seq;
public:
// The unique id of this operation.
const size_t id;
// The creation sequence id of this operation.
const size_t seq_id;
// The test iteration associated with this operation.
const size_t iteration;
Operation(size_t op_id, Operation* const parent_op, size_t iteration) noexcept :
m_creation_seq(get_next_creation_seq(op_id, parent_op)),
id(op_id),
seq_id(get_seq_hash()),
iteration(iteration),
m_status(OperationStatus::None),
m_cv(),
m_is_scheduled(false),
m_dependencies(),
m_dependent_resource_id(std::nullopt),
m_child_op_count(0)
{
}
Operation(Operation&& op) = delete;
Operation(Operation const&) = delete;
Operation& operator=(Operation&& op) = delete;
Operation& operator=(Operation const&) = delete;
// Returns the id of the thread currently executing this operation.
std::thread::id thread_id() const noexcept
{
return m_thread_id;
}
// Returns the current status of this operation.
OperationStatus status() const noexcept
{
return m_status;
}
// Returns true if this operation is currently scheduled, else false.
bool is_scheduled() const noexcept
{
return m_is_scheduled;
}
private:
// The id of the thread currently executing this operation.
std::thread::id m_thread_id;
// The current status of this operation.
OperationStatus m_status;
// Conditional variable that can be used to pause the execution of this operation.
std::condition_variable m_cv;
// True if this operation is currently scheduled, else false.
bool m_is_scheduled;
// Set of dependencies that must get satisfied before this operation can resume executing.
std::vector<std::function<bool()>> m_dependencies;
// The id of the resource that this operation is waiting for, if any.
std::optional<size_t> m_dependent_resource_id;
// The count of child operations created by this operation.
size_t m_child_op_count;
// Sets a callback that returns true when a dependency has been satisfied.
void set_dependency_callback(std::function<bool()> callback)
{
m_dependencies.push_back(callback);
}
// Unblocks the operation if its dependencies have been satisfied.
bool try_unblock()
{
size_t num_satisfied = 0;
for (size_t index = 0; index < m_dependencies.size(); ++index)
{
bool is_satisfied = m_dependencies[index]();
if (is_satisfied)
{
num_satisfied++;
if (m_status == OperationStatus::BlockedOnWaitAny)
{
break;
}
}
}
if ((num_satisfied > 0 && m_status == OperationStatus::BlockedOnWaitAny) ||
(num_satisfied == m_dependencies.size() && m_status == OperationStatus::BlockedOnWaitAll))
{
m_dependencies.clear();
m_status = OperationStatus::Enabled;
return true;
}
return false;
}
// Returns the next creation sequence vector of the specified parent operation.
std::vector<size_t> get_next_creation_seq(size_t op_id, Operation* const parent_op)
{
std::vector<size_t> creation_seq;
if (op_id == 0)
{
// If this is the root operation, then the creation sequence only contains
// the root operation itself.
creation_seq.push_back(0);
}
else
{
creation_seq.assign(parent_op->m_creation_seq.begin(), parent_op->m_creation_seq.end());
creation_seq.push_back(parent_op->m_child_op_count);
parent_op->m_child_op_count++;
}
return creation_seq;
}
// Returns the hash of the creation sequence vector.
size_t get_seq_hash() const noexcept
{
// Iterate the creation sequence vector and create a low collision rate hash.
size_t hash = m_creation_seq.size();
for(auto seq : m_creation_seq) {
seq = ((seq >> 16) ^ seq) * 0x45d9f3b;
seq = ((seq >> 16) ^ seq) * 0x45d9f3b;
seq = (seq >> 16) ^ seq;
hash ^= seq + 0x9e3779b9 + (hash << 6) + (hash >> 2);
}
return hash;
}
};
// Data structure that maintains a set of controlled operations and splits them into
// an enabled and a disabled sub-set that is used when taking scheduling decisions.
class Operations
{
public:
Operations(const Logger& logger) noexcept :
m_enabled_operations_size(0),
m_disabled_operations_size(0),
m_logger(logger)
{
}
Operations(Operations&& op) = delete;
Operations(Operations const&) = delete;
Operations& operator=(Operations&& op) = delete;
Operations& operator=(Operations const&) = delete;
const Operation* operator[](size_t index) const
{
return m_operations[index];
}
void insert(const Operation* op)
{
m_logger.log_debug("[st::engine] inserting operation '", op->id, "'.");
log_debug("pre-insert");
m_operations.push_back(op);
m_enabled_operations_size++;
if (m_operations.size() != m_enabled_operations_size)
{
swap(m_operations.size() - 1, m_enabled_operations_size - 1);
}
log_debug("post-insert");
}
void remove(size_t op_id)
{
m_logger.log_debug("[st::engine] removing operation '", op_id, "'.");
log_debug("pre-remove");
bool found = false;
size_t index;
if (find_index(op_id, 0, m_enabled_operations_size, index))
{
m_enabled_operations_size--;
found = true;
}
else if (find_index(op_id, m_enabled_operations_size, m_operations.size(), index))
{
m_disabled_operations_size--;
found = true;
}
if (found)
{
log_debug_swap("remove", index);
swap(index, m_enabled_operations_size);
swap(m_enabled_operations_size, m_operations.size() - 1);
m_operations.pop_back();
}
log_debug("post-remove");
}
void enable(size_t op_id)
{
m_logger.log_debug("[st::engine] enabling operation '", op_id, "'.");
log_debug("pre-enable");
size_t index;
if (find_index(op_id, m_enabled_operations_size, m_operations.size(), index))
{
log_debug_swap("enable", index);
swap(index, m_enabled_operations_size);
m_enabled_operations_size++;
m_disabled_operations_size--;
}
log_debug("post-enable");
}
void disable(size_t op_id)
{
m_logger.log_debug("[st::engine] disabling operation '", op_id, "'.");
log_debug("pre-disable");
size_t index;
if (find_index(op_id, 0, m_enabled_operations_size, index))
{
m_enabled_operations_size--;
m_disabled_operations_size++;
log_debug_swap("disable", index);
swap(index, m_enabled_operations_size);
}
log_debug("post-disable");
}
bool is_enabled(size_t op_id) const
{
size_t index;
return find_index(op_id, 0, m_enabled_operations_size, index);
}
const Operation* get_if_enabled(size_t op_id) const
{
size_t index;
if (find_index(op_id, 0, m_enabled_operations_size, index))
{
return m_operations[index];
}
return nullptr;
}
size_t size(bool is_enabled = true) const noexcept
{
return is_enabled ? m_enabled_operations_size : m_disabled_operations_size;
}
void clear()
{
m_operations.clear();
m_enabled_operations_size = 0;
m_disabled_operations_size = 0;
}
private:
std::vector<const Operation*> m_operations;
size_t m_enabled_operations_size;
size_t m_disabled_operations_size;
// The logger used by the engine to log messages.
const Logger& m_logger;
bool find_index(size_t op_id, size_t start, size_t end, size_t& index) const
{
for (index = start; index < end; ++index)
{
if (m_operations[index]->id == op_id)
{
return true;
}
}
return false;
}
void swap(size_t left, size_t right)
{
if (left != right)
{
auto temp = m_operations[left];
m_operations[left] = m_operations[right];
m_operations[right] = temp;
}
}
void log_debug(std::string action_type) const
{
if (m_logger.verbosity_level() == VerbosityLevel::Debug)
{
m_logger.log_debug("[st::engine] ", action_type, " total/enabled/disabled: ", m_operations.size(),
"/", m_enabled_operations_size, "/", m_disabled_operations_size, ".");
std::cout << "[st::engine] enabled: ";
for (size_t index = 0; index < m_enabled_operations_size; ++index)
{
if (index == 0)