Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
63765f80cfe4e86a3d898d2f33569b3ea6bba110
[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 <memory>
26 #include <string>
27 #include <vector>
28
29 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_dfs, mc, "DFS exploration algorithm of the model-checker");
30
31 namespace simgrid::mc {
32
33 xbt::signal<void(RemoteApp&)> DFSExplorer::on_exploration_start_signal;
34 xbt::signal<void(RemoteApp&)> DFSExplorer::on_backtracking_signal;
35
36 xbt::signal<void(State*, RemoteApp&)> DFSExplorer::on_state_creation_signal;
37
38 xbt::signal<void(State*, RemoteApp&)> DFSExplorer::on_restore_system_state_signal;
39 xbt::signal<void(RemoteApp&)> DFSExplorer::on_restore_initial_state_signal;
40 xbt::signal<void(Transition*, RemoteApp&)> DFSExplorer::on_transition_replay_signal;
41 xbt::signal<void(Transition*, RemoteApp&)> DFSExplorer::on_transition_execute_signal;
42
43 xbt::signal<void(RemoteApp&)> DFSExplorer::on_log_state_signal;
44
45 void DFSExplorer::check_non_termination(const State* current_state)
46 {
47 #if SIMGRID_HAVE_STATEFUL_MC
48   for (auto const& state : stack_) {
49     if (state->get_system_state()->equals_to(*current_state->get_system_state(),
50                                              *get_remote_app().get_remote_process_memory())) {
51       XBT_INFO("Non-progressive cycle: state %ld -> state %ld", state->get_num(), current_state->get_num());
52       XBT_INFO("******************************************");
53       XBT_INFO("*** NON-PROGRESSIVE CYCLE DETECTED ***");
54       XBT_INFO("******************************************");
55       XBT_INFO("Counter-example execution trace:");
56       for (auto const& s : get_textual_trace())
57         XBT_INFO("  %s", s.c_str());
58       XBT_INFO("You can debug the problem (and see the whole details) by rerunning out of simgrid-mc with "
59                "--cfg=model-check/replay:'%s'",
60                get_record_trace().to_string().c_str());
61       log_state();
62
63       throw McError(ExitStatus::NON_TERMINATION);
64     }
65   }
66 #endif
67 }
68
69 RecordTrace DFSExplorer::get_record_trace() // override
70 {
71   RecordTrace res;
72   for (auto const& transition : stack_.back()->get_recipe())
73     res.push_back(transition);
74   if (const auto trans = stack_.back()->get_transition_out(); trans != nullptr)
75     res.push_back(stack_.back()->get_transition_out().get());
76   return res;
77 }
78
79 void DFSExplorer::restore_stack(std::shared_ptr<State> state)
80 {
81   stack_.clear();
82   auto current_state = state;
83   stack_.emplace_front(current_state);
84   // condition corresponds to reaching initial state
85   while (current_state->get_parent_state() != nullptr) {
86     current_state = current_state->get_parent_state();
87     stack_.emplace_front(current_state);
88   }
89   XBT_DEBUG("Replaced stack by %s", get_record_trace().to_string().c_str());
90 }
91
92 void DFSExplorer::log_state() // override
93 {
94   on_log_state_signal(get_remote_app());
95   XBT_INFO("DFS exploration ended. %ld unique states visited; %lu backtracks (%lu transition replays, %lu states "
96            "visited overall)",
97            State::get_expanded_states(), backtrack_count_, visited_states_count_,
98            Transition::get_replayed_transitions());
99   Exploration::log_state();
100 }
101
102 void DFSExplorer::run()
103 {
104   on_exploration_start_signal(get_remote_app());
105   /* This function runs the DFS algorithm the state space.
106    * We do so iteratively instead of recursively, dealing with the call stack manually.
107    * This allows one to explore the call stack at will. */
108
109   while (not stack_.empty()) {
110     /* Get current state */
111     auto state = stack_.back();
112
113     XBT_DEBUG("**************************************************");
114     XBT_DEBUG("Exploration depth=%zu (state:#%ld; %zu interleaves todo)", stack_.size(), state->get_num(),
115               state->count_todo());
116
117     visited_states_count_++;
118
119     // Backtrack if we reached the maximum depth
120     if (stack_.size() > (std::size_t)_sg_mc_max_depth) {
121       if (reduction_mode_ == ReductionMode::dpor) {
122         XBT_ERROR("/!\\ Max depth of %d reached! THIS WILL PROBABLY BREAK the dpor reduction /!\\",
123                   _sg_mc_max_depth.get());
124         XBT_ERROR("/!\\ If bad things happen, disable dpor with --cfg=model-check/reduction:none /!\\");
125       } else
126         XBT_WARN("/!\\ Max depth reached ! /!\\ ");
127       this->backtrack();
128       continue;
129     }
130
131 #if SIMGRID_HAVE_STATEFUL_MC
132     // Backtrack if we are revisiting a state we saw previously while applying state-equality reduction
133     if (visited_state_ != nullptr) {
134       XBT_DEBUG("State already visited (equal to state %ld), exploration stopped on this path.",
135                 visited_state_->original_num_ == -1 ? visited_state_->num_ : visited_state_->original_num_);
136
137       visited_state_ = nullptr;
138       this->backtrack();
139       continue;
140     }
141 #endif
142
143     // Search for the next transition
144     // next_transition returns a pair<aid_t, int> in case we want to consider multiple state (eg. during backtrack)
145     auto [next, _] = state->next_transition_guided();
146
147     if (next < 0) { // If there is no more transition in the current state, backtrack.
148       XBT_VERB("%lu actors remain, but none of them need to be interleaved (depth %zu).", state->get_actor_count(),
149                stack_.size() + 1);
150
151       if (state->get_actor_count() == 0) {
152         get_remote_app().finalize_app();
153         XBT_VERB("Execution came to an end at %s (state: %ld, depth: %zu)", get_record_trace().to_string().c_str(),
154                  state->get_num(), stack_.size());
155       }
156
157       this->backtrack();
158       continue;
159     }
160
161     if (_sg_mc_sleep_set && XBT_LOG_ISENABLED(mc_dfs, xbt_log_priority_verbose)) {
162       XBT_VERB("Sleep set actually containing:");
163       for (auto& [aid, transition] : state->get_sleep_set())
164         XBT_VERB("  <%ld,%s>", aid, transition.to_string().c_str());
165     }
166
167     /* Actually answer the request: let's execute the selected request (MCed does one step) */
168     state->execute_next(next, get_remote_app());
169     on_transition_execute_signal(state->get_transition_out().get(), get_remote_app());
170
171     // If there are processes to interleave and the maximum depth has not been
172     // reached then perform one step of the exploration algorithm.
173     XBT_VERB("Execute %ld: %.60s (stack depth: %zu, state: %ld, %zu interleaves)", state->get_transition_out()->aid_,
174              state->get_transition_out()->to_string().c_str(), stack_.size(), state->get_num(), state->count_todo());
175
176     /* Create the new expanded state (copy the state of MCed into our MCer data) */
177     auto next_state = std::make_shared<State>(get_remote_app(), state);
178     on_state_creation_signal(next_state.get(), get_remote_app());
179
180     /* Sleep set procedure:
181      * adding the taken transition to the sleep set of the original state.
182      * <!> Since the parent sleep set is used to compute the child sleep set, this need to be
183      * done after next_state creation */
184     XBT_DEBUG("Marking Transition >>%s<< of process %ld done and adding it to the sleep set",
185               state->get_transition_out()->to_string().c_str(), state->get_transition_out()->aid_);
186     state->add_sleep_set(state->get_transition_out()); // Actors are marked done when they are considerd in ActorState
187
188     /* DPOR persistent set procedure:
189      * for each new transition considered, check if it depends on any other previous transition executed before it
190      * on another process. If there exists one, find the more recent, and add its process to the interleave set.
191      * If the process is not enabled at this  point, then add every enabled process to the interleave */
192     if (reduction_mode_ == ReductionMode::dpor) {
193       aid_t issuer_id   = state->get_transition_out()->aid_;
194       stack_t tmp_stack = stack_;
195       while (not tmp_stack.empty()) {
196         if (const State* prev_state = tmp_stack.back().get();
197             state->get_transition_out()->aid_ == prev_state->get_transition_out()->aid_) {
198           XBT_DEBUG("Simcall >>%s<< and >>%s<< with same issuer %ld", state->get_transition_out()->to_string().c_str(),
199                     prev_state->get_transition_out()->to_string().c_str(), issuer_id);
200           tmp_stack.pop_back();
201           continue;
202         } else if (prev_state->get_transition_out()->depends(state->get_transition_out().get())) {
203           XBT_VERB("Dependent Transitions:");
204           XBT_VERB("  %s (state=%ld)", prev_state->get_transition_out()->to_string().c_str(), prev_state->get_num());
205           XBT_VERB("  %s (state=%ld)", state->get_transition_out()->to_string().c_str(), state->get_num());
206
207           if (prev_state->is_actor_enabled(issuer_id)) {
208             if (not prev_state->is_actor_done(issuer_id)) {
209               prev_state->consider_one(issuer_id);
210               opened_states_.emplace_back(tmp_stack.back());
211             } else
212               XBT_DEBUG("Actor %ld is already in done set: no need to explore it again", issuer_id);
213           } else {
214             XBT_DEBUG("Actor %ld is not enabled: DPOR may be failing. To stay sound, we are marking every enabled "
215                       "transition as todo",
216                       issuer_id);
217             // If we ended up marking at least a transition, explore it at some point
218             if (prev_state->consider_all() > 0)
219               opened_states_.emplace_back(tmp_stack.back());
220           }
221           break;
222         } else {
223           XBT_VERB("INDEPENDENT Transitions:");
224           XBT_VERB("  %s (state=%ld)", prev_state->get_transition_out()->to_string().c_str(), prev_state->get_num());
225           XBT_VERB("  %s (state=%ld)", state->get_transition_out()->to_string().c_str(), state->get_num());
226         }
227         tmp_stack.pop_back();
228       }
229     }
230
231     // Before leaving that state, if the transition we just took can be taken multiple times, we
232     // need to give it to the opened states
233     if (stack_.back()->count_todo_multiples() > 0)
234       opened_states_.emplace_back(stack_.back());
235
236     if (_sg_mc_termination)
237       this->check_non_termination(next_state.get());
238
239 #if SIMGRID_HAVE_STATEFUL_MC
240     /* Check whether we already explored next_state in the past (but only if interested in state-equality reduction) */
241     if (_sg_mc_max_visited_states > 0)
242       visited_state_ = visited_states_.addVisitedState(next_state->get_num(), next_state.get(), get_remote_app());
243 #endif
244
245     stack_.emplace_back(std::move(next_state));
246
247     /* If this is a new state (or if we don't care about state-equality reduction) */
248     if (visited_state_ == nullptr) {
249       /* Get an enabled process and insert it in the interleave set of the next state */
250       if (reduction_mode_ == ReductionMode::dpor)
251         stack_.back()->consider_best(); // Take only one transition if DPOR: others may be considered later if required
252       else {
253         stack_.back()->consider_all();
254       }
255
256       dot_output("\"%ld\" -> \"%ld\" [%s];\n", state->get_num(), stack_.back()->get_num(),
257                  state->get_transition_out()->dot_string().c_str());
258 #if SIMGRID_HAVE_STATEFUL_MC
259     } else {
260       dot_output("\"%ld\" -> \"%ld\" [%s];\n", state->get_num(),
261                  visited_state_->original_num_ == -1 ? visited_state_->num_ : visited_state_->original_num_,
262                  state->get_transition_out()->dot_string().c_str());
263 #endif
264     }
265   }
266   log_state();
267 }
268
269 std::shared_ptr<State> DFSExplorer::best_opened_state()
270 {
271   int best_prio = 0; // cache the value for the best priority found so far (initialized to silence gcc)
272   auto best     = end(opened_states_);   // iterator to the state to explore having the best priority
273   auto valid    = begin(opened_states_); // iterator marking the limit between states still to explore, and already
274                                          // explored ones
275
276   // Keep only still non-explored states (aid != -1), and record the one with the best (greater) priority.
277   for (auto current = begin(opened_states_); current != end(opened_states_); ++current) {
278     auto [aid, prio] = (*current)->next_transition_guided();
279     if (aid == -1)
280       continue;
281     if (valid != current)
282       *valid = std::move(*current);
283     if (best == end(opened_states_) || prio > best_prio) {
284       best_prio = prio;
285       best      = valid;
286     }
287     ++valid;
288   }
289
290   std::shared_ptr<State> best_state;
291   if (best < valid) {
292     // There are non-explored states, and one of them has the best priority.  Remove it from opened_states_ before
293     // returning.
294     best_state = std::move(*best);
295     --valid;
296     if (best != valid)
297       *best = std::move(*valid);
298   }
299   opened_states_.erase(valid, end(opened_states_));
300
301   return best_state;
302 }
303
304 void DFSExplorer::backtrack()
305 {
306   XBT_VERB("Backtracking from %s", get_record_trace().to_string().c_str());
307   XBT_DEBUG("%lu alternatives are yet to be explored:", opened_states_.size());
308
309   on_backtracking_signal(get_remote_app());
310   get_remote_app().check_deadlock();
311
312   // Take the point with smallest distance
313   auto backtracking_point = best_opened_state();
314
315   // if no backtracking point, then set the stack_ to empty so we can end the exploration
316   if (not backtracking_point) {
317     XBT_DEBUG("No more opened point of exploration, the search will end");
318     stack_.clear();
319     return;
320   }
321
322   // We found a backtracking point, let's go to it
323   backtrack_count_++;
324   XBT_DEBUG("Backtracking to state#%ld", backtracking_point->get_num());
325
326 #if SIMGRID_HAVE_STATEFUL_MC
327   /* If asked to rollback on a state that has a snapshot, restore it */
328   if (const auto* system_state = backtracking_point->get_system_state()) {
329     system_state->restore(*get_remote_app().get_remote_process_memory());
330     on_restore_system_state_signal(backtracking_point.get(), get_remote_app());
331     this->restore_stack(backtracking_point);
332     return;
333   }
334 #endif
335
336   /* if no snapshot, we need to restore the initial state and replay the transitions */
337   get_remote_app().restore_initial_state();
338   on_restore_initial_state_signal(get_remote_app());
339   /* Traverse the stack from the state at position start and re-execute the transitions */
340   for (auto& state : backtracking_point->get_recipe()) {
341     state->replay(get_remote_app());
342     on_transition_replay_signal(state, get_remote_app());
343     visited_states_count_++;
344   }
345   this->restore_stack(backtracking_point);
346 }
347
348 DFSExplorer::DFSExplorer(const std::vector<char*>& args, bool with_dpor, bool need_memory_info)
349     : Exploration(args, need_memory_info || _sg_mc_termination)
350 {
351   if (with_dpor)
352     reduction_mode_ = ReductionMode::dpor;
353   else
354     reduction_mode_ = ReductionMode::none;
355
356   if (_sg_mc_termination) {
357     if (with_dpor) {
358       XBT_INFO("Check non progressive cycles (turning DPOR off)");
359       reduction_mode_ = ReductionMode::none;
360     } else {
361       XBT_INFO("Check non progressive cycles");
362     }
363   } else
364     XBT_INFO("Start a DFS exploration. Reduction is: %s.", to_c_str(reduction_mode_));
365
366   auto initial_state = std::make_shared<State>(get_remote_app());
367
368   XBT_DEBUG("**************************************************");
369
370   stack_.emplace_back(std::move(initial_state));
371
372   /* Get an enabled actor and insert it in the interleave set of the initial state */
373   XBT_DEBUG("Initial state. %lu actors to consider", stack_.back()->get_actor_count());
374   if (reduction_mode_ == ReductionMode::dpor)
375     stack_.back()->consider_best();
376   else {
377     stack_.back()->consider_all();
378   }
379   if (stack_.back()->count_todo_multiples() > 1)
380     opened_states_.emplace_back(stack_.back());
381 }
382
383 Exploration* create_dfs_exploration(const std::vector<char*>& args, bool with_dpor)
384 {
385   return new DFSExplorer(args, with_dpor);
386 }
387
388 } // namespace simgrid::mc