Logo AND Algorithmique Numérique Distribuée

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