Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add reversible race calculator
[simgrid.git] / src / mc / explo / DFSExplorer.cpp
1 /* Copyright (c) 2016-2023. The SimGrid Team. All rights reserved.          */
2
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. */
5
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"
12
13 #if SIMGRID_HAVE_STATEFUL_MC
14 #include "src/mc/VisitedState.hpp"
15 #endif
16
17 #include "src/xbt/mmalloc/mmprivate.h"
18 #include "xbt/log.h"
19 #include "xbt/string.hpp"
20 #include "xbt/sysdep.h"
21
22 #include <cassert>
23 #include <cstdio>
24
25 #include <algorithm>
26 #include <memory>
27 #include <string>
28 #include <unordered_set>
29 #include <vector>
30
31 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_dfs, mc, "DFS exploration algorithm of the model-checker");
32
33 namespace simgrid::mc {
34
35 xbt::signal<void(RemoteApp&)> DFSExplorer::on_exploration_start_signal;
36 xbt::signal<void(RemoteApp&)> DFSExplorer::on_backtracking_signal;
37
38 xbt::signal<void(State*, RemoteApp&)> DFSExplorer::on_state_creation_signal;
39
40 xbt::signal<void(State*, RemoteApp&)> DFSExplorer::on_restore_system_state_signal;
41 xbt::signal<void(RemoteApp&)> DFSExplorer::on_restore_initial_state_signal;
42 xbt::signal<void(Transition*, RemoteApp&)> DFSExplorer::on_transition_replay_signal;
43 xbt::signal<void(Transition*, RemoteApp&)> DFSExplorer::on_transition_execute_signal;
44
45 xbt::signal<void(RemoteApp&)> DFSExplorer::on_log_state_signal;
46
47 void DFSExplorer::check_non_termination(const State* current_state)
48 {
49 #if SIMGRID_HAVE_STATEFUL_MC
50   for (auto const& state : stack_) {
51     if (state->get_system_state()->equals_to(*current_state->get_system_state(),
52                                              *get_remote_app().get_remote_process_memory())) {
53       XBT_INFO("Non-progressive cycle: state %ld -> state %ld", state->get_num(), current_state->get_num());
54       XBT_INFO("******************************************");
55       XBT_INFO("*** NON-PROGRESSIVE CYCLE DETECTED ***");
56       XBT_INFO("******************************************");
57       XBT_INFO("Counter-example execution trace:");
58       for (auto const& s : get_textual_trace())
59         XBT_INFO("  %s", s.c_str());
60       XBT_INFO("You can debug the problem (and see the whole details) by rerunning out of simgrid-mc with "
61                "--cfg=model-check/replay:'%s'",
62                get_record_trace().to_string().c_str());
63       log_state();
64
65       throw McError(ExitStatus::NON_TERMINATION);
66     }
67   }
68 #endif
69 }
70
71 RecordTrace DFSExplorer::get_record_trace() // override
72 {
73   RecordTrace res;
74
75   if (const auto trans = stack_.back()->get_transition_out(); trans != nullptr)
76     res.push_back(trans.get());
77   for (const auto* state = stack_.back().get(); state != nullptr; state = state->get_parent_state().get())
78     if (state->get_transition_in() != nullptr)
79       res.push_front(state->get_transition_in().get());
80
81   return res;
82 }
83
84 void DFSExplorer::restore_stack(std::shared_ptr<State> state)
85 {
86   stack_.clear();
87   auto current_state = state;
88   stack_.emplace_front(current_state);
89   // condition corresponds to reaching initial state
90   while (current_state->get_parent_state() != nullptr) {
91     current_state = current_state->get_parent_state();
92     stack_.emplace_front(current_state);
93   }
94   XBT_DEBUG("Replaced stack by %s", get_record_trace().to_string().c_str());
95
96   if (reduction_mode_ == ReductionMode::sdpor || reduction_mode_ == ReductionMode::odpor) {
97     execution_seq_ = odpor::Execution();
98
99     // NOTE: The outgoing transition for the top-most
100     // state of the  stack refers to that which was taken
101     // as part of the last trace explored by the algorithm.
102     // Thus, only the sequence of transitions leading up to,
103     // but not including, the last state must be included
104     // when reconstructing the Exploration for SDPOR.
105     for (auto iter = stack_.begin(); iter != stack_.end() - 1 and iter != stack_.end(); ++iter) {
106       const auto& state = *(iter);
107       execution_seq_.push_transition(state->get_transition_out());
108     }
109   }
110   XBT_DEBUG("Additionally replaced corresponding SDPOR execution stack");
111 }
112
113 void DFSExplorer::log_state() // override
114 {
115   on_log_state_signal(get_remote_app());
116   XBT_INFO("DFS exploration ended. %ld unique states visited; %lu backtracks (%lu transition replays, %lu states "
117            "visited overall)",
118            State::get_expanded_states(), backtrack_count_, visited_states_count_,
119            Transition::get_replayed_transitions());
120   Exploration::log_state();
121 }
122
123 void DFSExplorer::run()
124 {
125   on_exploration_start_signal(get_remote_app());
126   /* This function runs the DFS algorithm the state space.
127    * We do so iteratively instead of recursively, dealing with the call stack manually.
128    * This allows one to explore the call stack at will. */
129
130   while (not stack_.empty()) {
131     /* Get current state */
132     auto state = stack_.back();
133
134     XBT_DEBUG("**************************************************");
135     XBT_DEBUG("Exploration depth=%zu (state:#%ld; %zu interleaves todo)", stack_.size(), state->get_num(),
136               state->count_todo());
137
138     visited_states_count_++;
139
140     // Backtrack if we reached the maximum depth
141     if (stack_.size() > (std::size_t)_sg_mc_max_depth) {
142       if (reduction_mode_ == ReductionMode::dpor) {
143         XBT_ERROR("/!\\ Max depth of %d reached! THIS WILL PROBABLY BREAK the dpor reduction /!\\",
144                   _sg_mc_max_depth.get());
145         XBT_ERROR("/!\\ If bad things happen, disable dpor with --cfg=model-check/reduction:none /!\\");
146       } else if (reduction_mode_ == ReductionMode::sdpor || reduction_mode_ == ReductionMode::odpor) {
147         XBT_ERROR("/!\\ Max depth of %d reached! THIS **WILL** BREAK the reduction, which is not sound "
148                   "when stopping at a fixed depth /!\\",
149                   _sg_mc_max_depth.get());
150         XBT_ERROR("/!\\ If bad things happen, disable dpor with --cfg=model-check/reduction:none /!\\");
151       } else {
152         XBT_WARN("/!\\ Max depth reached ! /!\\ ");
153       }
154       this->backtrack();
155       continue;
156     }
157
158 #if SIMGRID_HAVE_STATEFUL_MC
159     // Backtrack if we are revisiting a state we saw previously while applying state-equality reduction
160     if (visited_state_ != nullptr) {
161       XBT_DEBUG("State already visited (equal to state %ld), exploration stopped on this path.",
162                 visited_state_->original_num_ == -1 ? visited_state_->num_ : visited_state_->original_num_);
163
164       visited_state_ = nullptr;
165       this->backtrack();
166       continue;
167     }
168 #endif
169
170     if (reduction_mode_ == ReductionMode::odpor) {
171       // In the case of ODPOR, the wakeup tree for this
172       // state may be empty if we're exploring new territory
173       // (rather than following the partial execution of a
174       // wakeup tree). This corresponds to lines 9 to 13 of
175       // the ODPOR pseudocode
176       //
177       // INVARIANT: The execution sequence should be consistent
178       // with the state when seeding the tree. If the sequence
179       // gets out of sync with the state, selection will not
180       // work as we intend
181       state->seed_wakeup_tree_if_needed(execution_seq_);
182     }
183
184     // Search for the next transition
185     // next_transition returns a pair<aid_t, int>
186     // in case we want to consider multiple states (eg. during backtrack)
187     const aid_t next = reduction_mode_ == ReductionMode::odpor ? state->next_odpor_transition()
188                                                                : std::get<0>(state->next_transition_guided());
189
190     if (next < 0) { // If there is no more transition in the current state, backtrack.
191       XBT_VERB("%lu actors remain, but none of them need to be interleaved (depth %zu).", state->get_actor_count(),
192                stack_.size() + 1);
193
194       if (state->get_actor_count() == 0) {
195         get_remote_app().finalize_app();
196         XBT_VERB("Execution came to an end at %s (state: %ld, depth: %zu)", get_record_trace().to_string().c_str(),
197                  state->get_num(), stack_.size());
198       }
199
200       this->backtrack();
201       continue;
202     }
203
204     if (_sg_mc_sleep_set && XBT_LOG_ISENABLED(mc_dfs, xbt_log_priority_verbose)) {
205       XBT_VERB("Sleep set actually containing:");
206       for (auto& [aid, transition] : state->get_sleep_set())
207         XBT_VERB("  <%ld,%s>", aid, transition.to_string().c_str());
208     }
209
210     /* Actually answer the request: let's execute the selected request (MCed does one step) */
211     const auto executed_transition = state->execute_next(next, get_remote_app());
212     on_transition_execute_signal(state->get_transition_out().get(), get_remote_app());
213
214     // If there are processes to interleave and the maximum depth has not been
215     // reached then perform one step of the exploration algorithm.
216     XBT_VERB("Execute %ld: %.60s (stack depth: %zu, state: %ld, %zu interleaves)", state->get_transition_out()->aid_,
217              state->get_transition_out()->to_string().c_str(), stack_.size(), state->get_num(), state->count_todo());
218
219     /* Create the new expanded state (copy the state of MCed into our MCer data) */
220     auto next_state = std::make_shared<State>(get_remote_app(), state);
221     on_state_creation_signal(next_state.get(), get_remote_app());
222
223     if (reduction_mode_ == ReductionMode::odpor) {
224       // With ODPOR, after taking a step forward, we must
225       // assign a copy of that subtree to the next state.
226       //
227       // NOTE: We only add actions to the sleep set AFTER
228       // we've regenerated states. We must perform the search
229       // fully down a single path before we consider adding
230       // any elements to the sleep set according to the pseudocode
231       next_state->sprout_tree_from_parent_state();
232     } else {
233       /* Sleep set procedure:
234        * adding the taken transition to the sleep set of the original state.
235        * <!> Since the parent sleep set is used to compute the child sleep set, this need to be
236        * done after next_state creation */
237       XBT_DEBUG("Marking Transition >>%s<< of process %ld done and adding it to the sleep set",
238                 state->get_transition_out()->to_string().c_str(), state->get_transition_out()->aid_);
239       state->add_sleep_set(
240           state->get_transition_out()); // Actors are marked done when they are considered in ActorState
241     }
242
243     /* DPOR persistent set procedure:
244      * for each new transition considered, check if it depends on any other previous transition executed before it
245      * on another process. If there exists one, find the more recent, and add its process to the interleave set.
246      * If the process is not enabled at this  point, then add every enabled process to the interleave */
247     if (reduction_mode_ == ReductionMode::dpor) {
248       aid_t issuer_id   = state->get_transition_out()->aid_;
249       stack_t tmp_stack = stack_;
250       while (not tmp_stack.empty()) {
251         if (const State* prev_state = tmp_stack.back().get();
252             state->get_transition_out()->aid_ == prev_state->get_transition_out()->aid_) {
253           XBT_DEBUG("Simcall >>%s<< and >>%s<< with same issuer %ld", state->get_transition_out()->to_string().c_str(),
254                     prev_state->get_transition_out()->to_string().c_str(), issuer_id);
255           tmp_stack.pop_back();
256           continue;
257         } else if (prev_state->get_transition_out()->depends(state->get_transition_out().get())) {
258           XBT_VERB("Dependent Transitions:");
259           XBT_VERB("  %s (state=%ld)", prev_state->get_transition_out()->to_string().c_str(), prev_state->get_num());
260           XBT_VERB("  %s (state=%ld)", state->get_transition_out()->to_string().c_str(), state->get_num());
261
262           if (prev_state->is_actor_enabled(issuer_id)) {
263             if (not prev_state->is_actor_done(issuer_id)) {
264               prev_state->consider_one(issuer_id);
265               opened_states_.emplace_back(tmp_stack.back());
266             } else
267               XBT_DEBUG("Actor %ld is already in done set: no need to explore it again", issuer_id);
268           } else {
269             XBT_DEBUG("Actor %ld is not enabled: DPOR may be failing. To stay sound, we are marking every enabled "
270                       "transition as todo",
271                       issuer_id);
272             // If we ended up marking at least a transition, explore it at some point
273             if (prev_state->consider_all() > 0)
274               opened_states_.emplace_back(tmp_stack.back());
275           }
276           break;
277         } else {
278           XBT_VERB("INDEPENDENT Transitions:");
279           XBT_VERB("  %s (state=%ld)", prev_state->get_transition_out()->to_string().c_str(), prev_state->get_num());
280           XBT_VERB("  %s (state=%ld)", state->get_transition_out()->to_string().c_str(), state->get_num());
281         }
282         tmp_stack.pop_back();
283       }
284     } else if (reduction_mode_ == ReductionMode::sdpor) {
285       /**
286        * SDPOR Source Set Procedure:
287        *
288        * Find "reversible races" in the current execution `E` with respect
289        * to the latest action `p`. For each such race, determine one thread
290        * not contained in the backtrack set at the "race point" `r` which
291        * "represents" the trace formed by first executing everything after
292        * `r` that doesn't depend on it (`v := notdep(r, E)`) and then `p` to
293        * flip the race.
294        *
295        * The intuition is that some subsequence of `v` may enable `p`, so
296        * we want to be sure that search "in that direction"
297        */
298       execution_seq_.push_transition(std::move(executed_transition));
299       xbt_assert(execution_seq_.get_latest_event_handle().has_value(),
300                  "No events are contained in the SDPOR/OPDPOR execution "
301                  "even though one was just added");
302
303       const auto next_E_p = execution_seq_.get_latest_event_handle().value();
304       for (const auto racing_event_handle : execution_seq_.get_reversible_races_of(next_E_p)) {
305         const std::shared_ptr<State> prev_state = stack_[racing_event_handle];
306         // NOTE: To incorporate the idea of attempting to select the "best"
307         // backtrack point into SDPOR, instead of selecting the `first` initial,
308         // we should instead compute all choices and decide which is best
309         if (const auto q =
310                 execution_seq_.get_first_sdpor_initial_from(racing_event_handle, prev_state->get_backtrack_set());
311             q.has_value()) {
312           prev_state->consider_one(q.value());
313           opened_states_.emplace_back(std::move(prev_state));
314         }
315       }
316     } else if (reduction_mode_ == ReductionMode::odpor) {
317       // In the case of ODPOR, we simply observe the transition that was executed
318       // until we've reached a maximal trace
319       execution_seq_.push_transition(std::move(executed_transition));
320     }
321
322     // Before leaving that state, if the transition we just took can be taken multiple times, we
323     // need to give it to the opened states
324     if (stack_.back()->count_todo_multiples() > 0)
325       opened_states_.emplace_back(stack_.back());
326
327     if (_sg_mc_termination)
328       this->check_non_termination(next_state.get());
329
330 #if SIMGRID_HAVE_STATEFUL_MC
331     /* Check whether we already explored next_state in the past (but only if interested in state-equality reduction)
332      */
333     if (_sg_mc_max_visited_states > 0)
334       visited_state_ = visited_states_.addVisitedState(next_state->get_num(), next_state.get(), get_remote_app());
335 #endif
336
337     stack_.emplace_back(std::move(next_state));
338
339     /* If this is a new state (or if we don't care about state-equality reduction) */
340     if (visited_state_ == nullptr) {
341       /* Get an enabled process and insert it in the interleave set of the next state */
342       if (reduction_mode_ == ReductionMode::dpor)
343         stack_.back()->consider_best(); // Take only one transition if DPOR: others may be considered later if required
344       else {
345         stack_.back()->consider_all();
346       }
347
348       dot_output("\"%ld\" -> \"%ld\" [%s];\n", state->get_num(), stack_.back()->get_num(),
349                  state->get_transition_out()->dot_string().c_str());
350 #if SIMGRID_HAVE_STATEFUL_MC
351     } else {
352       dot_output("\"%ld\" -> \"%ld\" [%s];\n", state->get_num(),
353                  visited_state_->original_num_ == -1 ? visited_state_->num_ : visited_state_->original_num_,
354                  state->get_transition_out()->dot_string().c_str());
355 #endif
356     }
357   }
358   log_state();
359 }
360
361 std::shared_ptr<State> DFSExplorer::best_opened_state()
362 {
363   int best_prio = 0; // cache the value for the best priority found so far (initialized to silence gcc)
364   auto best     = end(opened_states_);   // iterator to the state to explore having the best priority
365   auto valid    = begin(opened_states_); // iterator marking the limit between states still to explore, and already
366                                          // explored ones
367
368   // Keep only still non-explored states (aid != -1), and record the one with the best (greater) priority.
369   for (auto current = begin(opened_states_); current != end(opened_states_); ++current) {
370     auto [aid, prio] = (*current)->next_transition_guided();
371     if (aid == -1)
372       continue;
373     if (valid != current)
374       *valid = std::move(*current);
375     if (best == end(opened_states_) || prio > best_prio) {
376       best_prio = prio;
377       best      = valid;
378     }
379     ++valid;
380   }
381
382   std::shared_ptr<State> best_state;
383   if (best < valid) {
384     // There are non-explored states, and one of them has the best priority.  Remove it from opened_states_ before
385     // returning.
386     best_state = std::move(*best);
387     --valid;
388     if (best != valid)
389       *best = std::move(*valid);
390   }
391   opened_states_.erase(valid, end(opened_states_));
392
393   return best_state;
394 }
395
396 std::shared_ptr<State> DFSExplorer::next_odpor_state()
397 {
398   for (auto iter = stack_.rbegin(); iter != stack_.rend(); ++iter) {
399     const auto& state = *iter;
400     state->do_odpor_backtrack_cleanup();
401     if (!state->has_empty_tree()) {
402       return state;
403     }
404   }
405   xbt_die("There are no more states for ODPOR");
406   return nullptr;
407 }
408
409 void DFSExplorer::backtrack()
410 {
411   if (const auto last_event = execution_seq_.get_latest_event_handle();
412       reduction_mode_ == ReductionMode::odpor and last_event.has_value()) {
413     /**
414      * ODPOR Race Detection Procedure:
415      *
416      * For each reversible race in the current execution, we
417      * note if there are any continuations `C` equivalent to that which
418      * would reverse the race that have already either a) been searched by ODPOR or
419      * b) been *noted* to be searched by the wakeup tree at the
420      * appropriate reversal point, either as `C` directly or
421      * an as equivalent to `C` ("eventually looks like C", viz. the `~_E`
422      * relation)
423      */
424     for (auto e_prime = static_cast<odpor::Execution::EventHandle>(0); e_prime <= last_event.value(); ++e_prime) {
425       for (const auto e : execution_seq_.get_reversible_races_of(e_prime)) {
426         XBT_DEBUG("ODPOR: Reversible race detected between events `%u` and `%u`", e, e_prime);
427         State& prev_state = *stack_[e];
428         if (const auto v = execution_seq_.get_odpor_extension_from(e, e_prime, prev_state); v.has_value()) {
429           XBT_DEBUG("ODPOR: Reversible race unaccounted for in the wakeup tree for "
430                     "the execution prior to event `%u`, inserting a sequence",
431                     e);
432           prev_state.mark_path_interesting_for_odpor(v.value(), execution_seq_.get_prefix_before(e));
433         }
434       }
435     }
436   }
437
438   XBT_VERB("Backtracking from %s", get_record_trace().to_string().c_str());
439   XBT_DEBUG("%lu alternatives are yet to be explored:", opened_states_.size());
440
441   on_backtracking_signal(get_remote_app());
442   get_remote_app().check_deadlock();
443
444   // Take the point with smallest distance
445   auto backtracking_point = reduction_mode_ == ReductionMode::odpor ? next_odpor_state() : best_opened_state();
446
447   // if no backtracking point, then set the stack_ to empty so we can end the exploration
448   if (not backtracking_point) {
449     XBT_DEBUG("No more opened point of exploration, the search will end");
450     stack_.clear();
451     return;
452   }
453
454   // We found a backtracking point, let's go to it
455   backtrack_count_++;
456   XBT_DEBUG("Backtracking to state#%ld", backtracking_point->get_num());
457
458 #if SIMGRID_HAVE_STATEFUL_MC
459   /* If asked to rollback on a state that has a snapshot, restore it */
460   if (const auto* system_state = backtracking_point->get_system_state()) {
461     system_state->restore(*get_remote_app().get_remote_process_memory());
462     on_restore_system_state_signal(backtracking_point.get(), get_remote_app());
463     this->restore_stack(backtracking_point);
464     return;
465   }
466 #endif
467
468   // Search how to restore the backtracking point
469   State* init_state = nullptr;
470   std::deque<Transition*> replay_recipe;
471   for (auto* s = backtracking_point.get(); s != nullptr; s = s->get_parent_state().get()) {
472 #if SIMGRID_HAVE_STATEFUL_MC
473     if (s->get_system_state() != nullptr) { // Found a state that I can restore
474       init_state = s;
475       break;
476     }
477 #endif
478     if (s->get_transition_in() != nullptr) // The root has no transition_in
479       replay_recipe.push_front(s->get_transition_in().get());
480   }
481
482   // Restore the init_state, if any
483   if (init_state != nullptr) {
484 #if SIMGRID_HAVE_STATEFUL_MC
485     const auto* system_state = init_state->get_system_state();
486     system_state->restore(*get_remote_app().get_remote_process_memory());
487     on_restore_system_state_signal(init_state, get_remote_app());
488 #endif
489   } else { // Restore the initial state if no intermediate state was found
490     get_remote_app().restore_initial_state();
491     on_restore_initial_state_signal(get_remote_app());
492   }
493
494   /* if no snapshot, we need to restore the initial state and replay the transitions */
495   /* Traverse the stack from the state at position start and re-execute the transitions */
496   for (auto& transition : replay_recipe) {
497     transition->replay(get_remote_app());
498     on_transition_replay_signal(transition, get_remote_app());
499     visited_states_count_++;
500   }
501   this->restore_stack(backtracking_point);
502 }
503
504 DFSExplorer::DFSExplorer(const std::vector<char*>& args, ReductionMode mode, bool need_memory_info)
505     : Exploration(args, need_memory_info || _sg_mc_termination
506 #if SIMGRID_HAVE_STATEFUL_MC
507                             || _sg_mc_checkpoint > 0
508 #endif
509                   )
510     , reduction_mode_(mode)
511 {
512   if (_sg_mc_termination) {
513     if (mode != ReductionMode::none) {
514       XBT_INFO("Check non progressive cycles (turning DPOR off)");
515       reduction_mode_ = ReductionMode::none;
516     } else {
517       XBT_INFO("Check non progressive cycles");
518     }
519   } else
520     XBT_INFO("Start a DFS exploration. Reduction is: %s.", to_c_str(reduction_mode_));
521
522   auto initial_state = std::make_shared<State>(get_remote_app());
523
524   XBT_DEBUG("**************************************************");
525
526   stack_.emplace_back(std::move(initial_state));
527
528   /* Get an enabled actor and insert it in the interleave set of the initial state */
529   XBT_DEBUG("Initial state. %lu actors to consider", stack_.back()->get_actor_count());
530   if (reduction_mode_ == ReductionMode::dpor)
531     stack_.back()->consider_best();
532   else {
533     stack_.back()->consider_all();
534   }
535   if (stack_.back()->count_todo_multiples() > 1)
536     opened_states_.emplace_back(stack_.back());
537 }
538
539 Exploration* create_dfs_exploration(const std::vector<char*>& args, ReductionMode mode)
540 {
541   return new DFSExplorer(args, mode);
542 }
543
544 } // namespace simgrid::mc