Logo AND Algorithmique Numérique Distribuée

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