1 /* Copyright (c) 2016-2023. The SimGrid Team. All rights reserved. */
3 /* This program is free software; you can redistribute it and/or modify it
4 * under the terms of the license (GNU LGPL) which comes with this package. */
6 #include "src/mc/explo/DFSExplorer.hpp"
7 #include "src/mc/mc_config.hpp"
8 #include "src/mc/mc_exit.hpp"
9 #include "src/mc/mc_private.hpp"
10 #include "src/mc/mc_record.hpp"
11 #include "src/mc/transition/Transition.hpp"
14 #include "xbt/string.hpp"
15 #include "xbt/sysdep.h"
23 #include <unordered_set>
26 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_dfs, mc, "DFS exploration algorithm of the model-checker");
28 namespace simgrid::mc {
30 xbt::signal<void(RemoteApp&)> DFSExplorer::on_exploration_start_signal;
31 xbt::signal<void(RemoteApp&)> DFSExplorer::on_backtracking_signal;
33 xbt::signal<void(State*, RemoteApp&)> DFSExplorer::on_state_creation_signal;
35 xbt::signal<void(State*, RemoteApp&)> DFSExplorer::on_restore_system_state_signal;
36 xbt::signal<void(RemoteApp&)> DFSExplorer::on_restore_initial_state_signal;
37 xbt::signal<void(Transition*, RemoteApp&)> DFSExplorer::on_transition_replay_signal;
38 xbt::signal<void(Transition*, RemoteApp&)> DFSExplorer::on_transition_execute_signal;
40 xbt::signal<void(RemoteApp&)> DFSExplorer::on_log_state_signal;
42 RecordTrace DFSExplorer::get_record_trace() // override
46 if (const auto trans = stack_.back()->get_transition_out(); trans != nullptr)
47 res.push_back(trans.get());
48 for (const auto* state = stack_.back().get(); state != nullptr; state = state->get_parent_state().get())
49 if (state->get_transition_in() != nullptr)
50 res.push_front(state->get_transition_in().get());
55 void DFSExplorer::restore_stack(std::shared_ptr<State> state)
58 execution_seq_ = odpor::Execution();
59 auto current_state = state;
60 stack_.emplace_front(current_state);
61 // condition corresponds to reaching initial state
62 while (current_state->get_parent_state() != nullptr) {
63 current_state = current_state->get_parent_state();
64 stack_.emplace_front(current_state);
66 XBT_DEBUG("Replaced stack by %s", get_record_trace().to_string().c_str());
67 if (reduction_mode_ == ReductionMode::sdpor || reduction_mode_ == ReductionMode::odpor) {
68 // NOTE: The outgoing transition for the top-most
69 // state of the stack refers to that which was taken
70 // as part of the last trace explored by the algorithm.
71 // Thus, only the sequence of transitions leading up to,
72 // but not including, the last state must be included
73 // when reconstructing the Exploration for SDPOR.
74 for (auto iter = std::next(stack_.begin()); iter != stack_.end(); ++iter) {
75 execution_seq_.push_transition((*iter)->get_transition_in());
77 XBT_DEBUG("Replaced SDPOR/ODPOR execution to reflect the new stack");
81 void DFSExplorer::log_state() // override
83 on_log_state_signal(get_remote_app());
84 XBT_INFO("DFS exploration ended. %ld unique states visited; %lu backtracks (%lu transition replays, %lu states "
86 State::get_expanded_states(), backtrack_count_, Transition::get_replayed_transitions(),
87 visited_states_count_);
88 Exploration::log_state();
91 void DFSExplorer::run()
93 on_exploration_start_signal(get_remote_app());
94 /* This function runs the DFS algorithm the state space.
95 * We do so iteratively instead of recursively, dealing with the call stack manually.
96 * This allows one to explore the call stack at will. */
98 while (not stack_.empty()) {
99 /* Get current state */
100 auto state = stack_.back();
102 XBT_DEBUG("**************************************************");
103 XBT_DEBUG("Exploration depth=%zu (state:#%ld; %zu interleaves todo)", stack_.size(), state->get_num(),
104 state->count_todo());
106 visited_states_count_++;
108 // Backtrack if we reached the maximum depth
109 if (stack_.size() > (std::size_t)_sg_mc_max_depth) {
110 if (reduction_mode_ == ReductionMode::dpor) {
111 XBT_ERROR("/!\\ Max depth of %d reached! THIS WILL PROBABLY BREAK the dpor reduction /!\\",
112 _sg_mc_max_depth.get());
113 XBT_ERROR("/!\\ If bad things happen, disable dpor with --cfg=model-check/reduction:none /!\\");
114 } else if (reduction_mode_ == ReductionMode::sdpor || reduction_mode_ == ReductionMode::odpor) {
115 XBT_ERROR("/!\\ Max depth of %d reached! THIS **WILL** BREAK the reduction, which is not sound "
116 "when stopping at a fixed depth /!\\",
117 _sg_mc_max_depth.get());
118 XBT_ERROR("/!\\ If bad things happen, disable the reduction with --cfg=model-check/reduction:none /!\\");
120 XBT_WARN("/!\\ Max depth reached ! /!\\ ");
126 if (reduction_mode_ == ReductionMode::odpor) {
127 // In the case of ODPOR, the wakeup tree for this
128 // state may be empty if we're exploring new territory
129 // (rather than following the partial execution of a
130 // wakeup tree). This corresponds to lines 9 to 13 of
131 // the ODPOR pseudocode
133 // INVARIANT: The execution sequence should be consistent
134 // with the state when seeding the tree. If the sequence
135 // gets out of sync with the state, selection will not
137 state->seed_wakeup_tree_if_needed(execution_seq_);
140 // Search for the next transition
141 // next_transition returns a pair<aid_t, int>
142 // in case we want to consider multiple states (eg. during backtrack)
143 const aid_t next = reduction_mode_ == ReductionMode::odpor ? state->next_odpor_transition()
144 : std::get<0>(state->next_transition_guided());
146 if (next < 0) { // If there is no more transition in the current state, backtrack.
147 XBT_VERB("%lu actors remain, but none of them need to be interleaved (depth %zu).", state->get_actor_count(),
150 if (state->get_actor_count() == 0) {
151 get_remote_app().finalize_app();
152 XBT_VERB("Execution came to an end at %s (state: %ld, depth: %zu)", get_record_trace().to_string().c_str(),
153 state->get_num(), stack_.size());
160 if (XBT_LOG_ISENABLED(mc_dfs, xbt_log_priority_verbose)) {
161 XBT_VERB("Sleep set actually containing:");
162 for (const auto& [aid, transition] : state->get_sleep_set())
163 XBT_VERB(" <%ld,%s>", aid, transition->to_string().c_str());
166 /* Actually answer the request: let's execute the selected request (MCed does one step) */
167 auto executed_transition = state->execute_next(next, get_remote_app());
168 on_transition_execute_signal(state->get_transition_out().get(), get_remote_app());
170 // If there are processes to interleave and the maximum depth has not been
171 // reached then perform one step of the exploration algorithm.
172 XBT_VERB("Execute %ld: %.60s (stack depth: %zu, state: %ld, %zu interleaves)", state->get_transition_out()->aid_,
173 state->get_transition_out()->to_string().c_str(), stack_.size(), state->get_num(), state->count_todo());
175 /* Create the new expanded state (copy the state of MCed into our MCer data) */
176 auto next_state = std::make_shared<State>(get_remote_app(), state);
177 on_state_creation_signal(next_state.get(), get_remote_app());
179 if (reduction_mode_ == ReductionMode::odpor) {
180 // With ODPOR, after taking a step forward, we must
181 // assign a copy of that subtree to the next state.
183 // NOTE: We only add actions to the sleep set AFTER
184 // we've regenerated states. We must perform the search
185 // fully down a single path before we consider adding
186 // any elements to the sleep set according to the pseudocode
187 next_state->sprout_tree_from_parent_state();
189 /* Sleep set procedure:
190 * adding the taken transition to the sleep set of the original state.
191 * <!> Since the parent sleep set is used to compute the child sleep set, this need to be
192 * done after next_state creation */
193 XBT_DEBUG("Marking Transition >>%s<< of process %ld done and adding it to the sleep set",
194 state->get_transition_out()->to_string().c_str(), state->get_transition_out()->aid_);
195 state->add_sleep_set(
196 state->get_transition_out()); // Actors are marked done when they are considered in ActorState
199 /* DPOR persistent set procedure:
200 * for each new transition considered, check if it depends on any other previous transition executed before it
201 * on another process. If there exists one, find the more recent, and add its process to the interleave set.
202 * If the process is not enabled at this point, then add every enabled process to the interleave */
203 if (reduction_mode_ == ReductionMode::dpor) {
204 aid_t issuer_id = state->get_transition_out()->aid_;
205 stack_t tmp_stack = stack_;
206 while (not tmp_stack.empty()) {
207 if (const State* prev_state = tmp_stack.back().get();
208 state->get_transition_out()->aid_ == prev_state->get_transition_out()->aid_) {
209 XBT_DEBUG("Simcall >>%s<< and >>%s<< with same issuer %ld", state->get_transition_out()->to_string().c_str(),
210 prev_state->get_transition_out()->to_string().c_str(), issuer_id);
211 tmp_stack.pop_back();
213 } else if (prev_state->get_transition_out()->depends(state->get_transition_out().get())) {
214 XBT_VERB("Dependent Transitions:");
215 XBT_VERB(" #%ld %s (state=%ld)", prev_state->get_transition_out()->aid_,
216 prev_state->get_transition_out()->to_string().c_str(), prev_state->get_num());
217 XBT_VERB(" #%ld %s (state=%ld)", state->get_transition_out()->aid_,
218 state->get_transition_out()->to_string().c_str(), state->get_num());
220 if (prev_state->is_actor_enabled(issuer_id)) {
221 if (not prev_state->is_actor_done(issuer_id)) {
222 prev_state->consider_one(issuer_id);
223 opened_states_.emplace_back(tmp_stack.back());
225 XBT_DEBUG("Actor %ld is already in done set: no need to explore it again", issuer_id);
227 XBT_DEBUG("Actor %ld is not enabled: DPOR may be failing. To stay sound, we are marking every enabled "
228 "transition as todo",
230 // If we ended up marking at least a transition, explore it at some point
231 if (prev_state->consider_all() > 0)
232 opened_states_.emplace_back(tmp_stack.back());
236 XBT_VERB("INDEPENDENT Transitions:");
237 XBT_VERB(" #%ld %s (state=%ld)", prev_state->get_transition_out()->aid_,
238 prev_state->get_transition_out()->to_string().c_str(), prev_state->get_num());
239 XBT_VERB(" #%ld %s (state=%ld)", state->get_transition_out()->aid_,
240 state->get_transition_out()->to_string().c_str(), state->get_num());
242 tmp_stack.pop_back();
244 } else if (reduction_mode_ == ReductionMode::sdpor) {
246 * SDPOR Source Set Procedure:
248 * Find "reversible races" in the current execution `E` with respect
249 * to the latest action `p`. For each such race, determine one thread
250 * not contained in the backtrack set at the "race point" `r` which
251 * "represents" the trace formed by first executing everything after
252 * `r` that doesn't depend on it (`v := notdep(r, E)`) and then `p` to
255 * The intuition is that some subsequence of `v` may enable `p`, so
256 * we want to be sure that search "in that direction"
258 execution_seq_.push_transition(std::move(executed_transition));
259 xbt_assert(execution_seq_.get_latest_event_handle().has_value(), "No events are contained in the SDPOR execution "
260 "even though one was just added");
262 const auto next_E_p = execution_seq_.get_latest_event_handle().value();
263 for (const auto e_race : execution_seq_.get_reversible_races_of(next_E_p)) {
264 State* prev_state = stack_[e_race].get();
265 const auto choices = execution_seq_.get_missing_source_set_actors_from(e_race, prev_state->get_backtrack_set());
266 if (not choices.empty()) {
267 // NOTE: To incorporate the idea of attempting to select the "best"
268 // backtrack point into SDPOR, instead of selecting the `first` initial,
269 // we should instead compute all choices and decide which is best
271 // Here, we choose the actor with the lowest ID to ensure
272 // we get deterministic results
274 std::min_element(choices.begin(), choices.end(), [](const aid_t a1, const aid_t a2) { return a1 < a2; });
275 prev_state->consider_one(*q);
276 opened_states_.emplace_back(std::move(prev_state));
279 } else if (reduction_mode_ == ReductionMode::odpor) {
280 // In the case of ODPOR, we simply observe the transition that was executed
281 // until we've reached a maximal trace
282 execution_seq_.push_transition(std::move(executed_transition));
285 // Before leaving that state, if the transition we just took can be taken multiple times, we
286 // need to give it to the opened states
287 if (stack_.back()->count_todo_multiples() > 0)
288 opened_states_.emplace_back(stack_.back());
290 stack_.emplace_back(std::move(next_state));
292 /* If this is a new state (or if we don't care about state-equality reduction) */
293 /* Get an enabled process and insert it in the interleave set of the next state */
294 if (reduction_mode_ == ReductionMode::dpor)
295 stack_.back()->consider_best(); // Take only one transition if DPOR: others may be considered later if required
297 stack_.back()->consider_all();
300 dot_output("\"%ld\" -> \"%ld\" [%s];\n", state->get_num(), stack_.back()->get_num(),
301 state->get_transition_out()->dot_string().c_str());
306 std::shared_ptr<State> DFSExplorer::best_opened_state()
308 int best_prio = 0; // cache the value for the best priority found so far (initialized to silence gcc)
309 auto best = end(opened_states_); // iterator to the state to explore having the best priority
310 auto valid = begin(opened_states_); // iterator marking the limit between states still to explore, and already
313 // Keep only still non-explored states (aid != -1), and record the one with the best (greater) priority.
314 for (auto current = begin(opened_states_); current != end(opened_states_); ++current) {
315 auto [aid, prio] = (*current)->next_transition_guided();
318 if (valid != current)
319 *valid = std::move(*current);
320 if (best == end(opened_states_) || prio < best_prio) {
327 std::shared_ptr<State> best_state;
329 // There are non-explored states, and one of them has the best priority. Remove it from opened_states_ before
331 best_state = std::move(*best);
334 *best = std::move(*valid);
336 opened_states_.erase(valid, end(opened_states_));
341 std::shared_ptr<State> DFSExplorer::next_odpor_state()
343 for (auto iter = stack_.rbegin(); iter != stack_.rend(); ++iter) {
344 const auto& state = *iter;
345 state->do_odpor_unwind();
346 XBT_DEBUG("\tPerformed ODPOR 'clean-up'. Sleep set has:");
347 for (const auto& [aid, transition] : state->get_sleep_set())
348 XBT_DEBUG("\t <%ld,%s>", aid, transition->to_string().c_str());
349 if (not state->has_empty_tree()) {
356 void DFSExplorer::backtrack()
358 if (const auto last_event = execution_seq_.get_latest_event_handle();
359 reduction_mode_ == ReductionMode::odpor and last_event.has_value()) {
361 * ODPOR Race Detection Procedure:
363 * For each reversible race in the current execution, we
364 * note if there are any continuations `C` equivalent to that which
365 * would reverse the race that have already either a) been searched by ODPOR or
366 * b) been *noted* to be searched by the wakeup tree at the
367 * appropriate reversal point, either as `C` directly or
368 * an as equivalent to `C` ("eventually looks like C", viz. the `~_E`
371 for (auto e_prime = static_cast<odpor::Execution::EventHandle>(0); e_prime <= last_event.value(); ++e_prime) {
372 for (const auto e : execution_seq_.get_reversible_races_of(e_prime)) {
373 XBT_DEBUG("ODPOR: Reversible race detected between events `%u` and `%u`", e, e_prime);
374 State& prev_state = *stack_[e];
375 if (const auto v = execution_seq_.get_odpor_extension_from(e, e_prime, prev_state); v.has_value()) {
376 switch (prev_state.insert_into_wakeup_tree(v.value(), execution_seq_.get_prefix_before(e))) {
377 case odpor::WakeupTree::InsertionResult::root: {
378 XBT_DEBUG("ODPOR: Reversible race with `%u` unaccounted for in the wakeup tree for "
379 "the execution prior to event `%u`:",
383 case odpor::WakeupTree::InsertionResult::interior_node: {
384 XBT_DEBUG("ODPOR: Reversible race with `%u` partially accounted for in the wakeup tree for "
385 "the execution prior to event `%u`:",
389 case odpor::WakeupTree::InsertionResult::leaf: {
390 XBT_DEBUG("ODPOR: Reversible race with `%u` accounted for in the wakeup tree for "
391 "the execution prior to event `%u`:",
396 for (const auto& seq : simgrid::mc::odpor::get_textual_trace(v.value())) {
397 XBT_DEBUG(" %s", seq.c_str());
400 XBT_DEBUG("ODPOR: Ignoring race: `sleep(E')` intersects `WI_[E'](v := notdep(%u, E))`", e);
401 XBT_DEBUG("Sleep set contains:");
402 for (const auto& [aid, transition] : prev_state.get_sleep_set())
403 XBT_DEBUG(" <%ld,%s>", aid, transition->to_string().c_str());
409 XBT_VERB("Backtracking from %s", get_record_trace().to_string().c_str());
410 XBT_DEBUG("%lu alternatives are yet to be explored:", opened_states_.size());
412 on_backtracking_signal(get_remote_app());
413 get_remote_app().check_deadlock();
415 // Take the point with smallest distance
416 auto backtracking_point = reduction_mode_ == ReductionMode::odpor ? next_odpor_state() : best_opened_state();
418 // if no backtracking point, then set the stack_ to empty so we can end the exploration
419 if (not backtracking_point) {
420 XBT_DEBUG("No more opened point of exploration, the search will end");
425 // We found a backtracking point, let's go to it
427 XBT_DEBUG("Backtracking to state#%ld", backtracking_point->get_num());
429 // Search how to restore the backtracking point
430 std::deque<Transition*> replay_recipe;
431 for (auto* s = backtracking_point.get(); s != nullptr; s = s->get_parent_state().get()) {
432 if (s->get_transition_in() != nullptr) // The root has no transition_in
433 replay_recipe.push_front(s->get_transition_in().get());
436 // Restore the initial state if no intermediate state was found
437 get_remote_app().restore_initial_state();
438 on_restore_initial_state_signal(get_remote_app());
440 /* if no snapshot, we need to restore the initial state and replay the transitions */
441 /* Traverse the stack from the state at position start and re-execute the transitions */
442 for (auto& transition : replay_recipe) {
443 transition->replay(get_remote_app());
444 on_transition_replay_signal(transition, get_remote_app());
445 visited_states_count_++;
447 this->restore_stack(backtracking_point);
450 DFSExplorer::DFSExplorer(const std::vector<char*>& args, ReductionMode mode) : Exploration(args), reduction_mode_(mode)
452 XBT_INFO("Start a DFS exploration. Reduction is: %s.", to_c_str(reduction_mode_));
454 auto initial_state = std::make_shared<State>(get_remote_app());
456 XBT_DEBUG("**************************************************");
458 stack_.emplace_back(std::move(initial_state));
460 /* Get an enabled actor and insert it in the interleave set of the initial state */
461 XBT_DEBUG("Initial state. %lu actors to consider", stack_.back()->get_actor_count());
462 if (reduction_mode_ == ReductionMode::dpor)
463 stack_.back()->consider_best();
465 stack_.back()->consider_all();
467 if (stack_.back()->count_todo_multiples() > 1)
468 opened_states_.emplace_back(stack_.back());
471 Exploration* create_dfs_exploration(const std::vector<char*>& args, ReductionMode mode)
473 return new DFSExplorer(args, mode);
476 } // namespace simgrid::mc