Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Try to fix the MC build on 32 bits
[simgrid.git] / src / mc / checker / CommunicationDeterminismChecker.cpp
1 /* Copyright (c) 2008-2022. 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/checker/CommunicationDeterminismChecker.hpp"
7 #include "src/kernel/activity/MailboxImpl.hpp"
8 #include "src/mc/Session.hpp"
9 #include "src/mc/api/TransitionComm.hpp"
10 #include "src/mc/mc_config.hpp"
11 #include "src/mc/mc_exit.hpp"
12 #include "src/mc/mc_private.hpp"
13
14 #include <cstdint>
15
16 using api = simgrid::mc::Api;
17
18 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_comm_determinism, mc, "Logging specific to MC communication determinism detection");
19
20 namespace simgrid {
21 namespace mc {
22
23 enum class CallType { NONE, SEND, RECV, WAIT, WAITANY };
24 enum class CommPatternDifference { NONE, TYPE, MBOX, TAG, SRC_PROC, DST_PROC, DATA_SIZE };
25 enum class PatternCommunicationType {
26   none    = 0,
27   send    = 1,
28   receive = 2,
29 };
30
31 class PatternCommunication {
32 public:
33   int num = 0;
34   uintptr_t comm_addr           = 0;
35   PatternCommunicationType type = PatternCommunicationType::send;
36   unsigned long src_proc        = 0;
37   unsigned long dst_proc        = 0;
38   unsigned mbox                 = 0;
39   unsigned size                 = 0;
40   int tag   = 0;
41   int index = 0;
42
43   PatternCommunication dup() const
44   {
45     simgrid::mc::PatternCommunication res;
46     // num?
47     res.comm_addr = this->comm_addr;
48     res.type      = this->type;
49     // src_proc?
50     // dst_proc?
51     res.dst_proc = this->dst_proc;
52     res.mbox     = this->mbox;
53     // tag?
54     res.index = this->index;
55     return res;
56   }
57 };
58
59 struct PatternCommunicationList {
60   unsigned int index_comm = 0;
61   std::vector<std::unique_ptr<simgrid::mc::PatternCommunication>> list;
62 };
63
64 /********** Checker extension **********/
65
66 struct CommDetExtension {
67   static simgrid::xbt::Extension<simgrid::mc::Checker, CommDetExtension> EXTENSION_ID;
68
69   CommDetExtension()
70   {
71     const unsigned long maxpid = api::get().get_maxpid();
72
73     initial_communications_pattern.resize(maxpid);
74     incomplete_communications_pattern.resize(maxpid);
75   }
76
77   std::vector<simgrid::mc::PatternCommunicationList> initial_communications_pattern;
78   std::vector<std::vector<simgrid::mc::PatternCommunication*>> incomplete_communications_pattern;
79
80   bool initial_communications_pattern_done = false;
81   bool recv_deterministic                  = true;
82   bool send_deterministic                  = true;
83   std::string send_diff;
84   std::string recv_diff;
85
86   void restore_communications_pattern(const simgrid::mc::State* state);
87   void deterministic_comm_pattern(aid_t process, const PatternCommunication* comm, bool backtracking);
88   void get_comm_pattern(const Transition* transition, bool backtracking);
89   void complete_comm_pattern(const CommWaitTransition* transition, bool backtracking);
90   void handle_comm_pattern(const Transition* transition, bool backtracking);
91 };
92 simgrid::xbt::Extension<simgrid::mc::Checker, CommDetExtension> CommDetExtension::EXTENSION_ID;
93 /********** State Extension ***********/
94
95 class StateCommDet {
96   CommDetExtension* checker_;
97
98 public:
99   std::vector<std::vector<simgrid::mc::PatternCommunication>> incomplete_comm_pattern_;
100   std::vector<unsigned> communication_indices_;
101
102   static simgrid::xbt::Extension<simgrid::mc::State, StateCommDet> EXTENSION_ID;
103   explicit StateCommDet(CommDetExtension* checker) : checker_(checker)
104   {
105     copy_incomplete_comm_pattern();
106     copy_index_comm_pattern();
107   }
108
109   void copy_incomplete_comm_pattern()
110   {
111     incomplete_comm_pattern_.clear();
112     const unsigned long maxpid = api::get().get_maxpid();
113     for (unsigned long i = 0; i < maxpid; i++) {
114       std::vector<simgrid::mc::PatternCommunication> res;
115       for (auto const& comm : checker_->incomplete_communications_pattern[i])
116         res.push_back(comm->dup());
117       incomplete_comm_pattern_.push_back(std::move(res));
118     }
119   }
120
121   void copy_index_comm_pattern()
122   {
123     communication_indices_.clear();
124     for (auto const& list_process_comm : checker_->initial_communications_pattern)
125       this->communication_indices_.push_back(list_process_comm.index_comm);
126   }
127 };
128 simgrid::xbt::Extension<simgrid::mc::State, StateCommDet> StateCommDet::EXTENSION_ID;
129
130 static simgrid::mc::CommPatternDifference compare_comm_pattern(const simgrid::mc::PatternCommunication* comm1,
131                                                                const simgrid::mc::PatternCommunication* comm2)
132 {
133   using simgrid::mc::CommPatternDifference;
134   if (comm1->type != comm2->type)
135     return CommPatternDifference::TYPE;
136   if (comm1->mbox != comm2->mbox)
137     return CommPatternDifference::MBOX;
138   if (comm1->src_proc != comm2->src_proc)
139     return CommPatternDifference::SRC_PROC;
140   if (comm1->dst_proc != comm2->dst_proc)
141     return CommPatternDifference::DST_PROC;
142   if (comm1->tag != comm2->tag)
143     return CommPatternDifference::TAG;
144   if (comm1->size != comm2->size)
145     return CommPatternDifference::DATA_SIZE;
146   return CommPatternDifference::NONE;
147 }
148
149 void CommDetExtension::restore_communications_pattern(const simgrid::mc::State* state)
150 {
151   for (size_t i = 0; i < initial_communications_pattern.size(); i++)
152     initial_communications_pattern[i].index_comm =
153         state->extension<simgrid::mc::StateCommDet>()->communication_indices_[i];
154
155   const unsigned long maxpid = api::get().get_maxpid();
156   for (unsigned long i = 0; i < maxpid; i++) {
157     incomplete_communications_pattern[i].clear();
158     for (simgrid::mc::PatternCommunication const& comm :
159          state->extension<simgrid::mc::StateCommDet>()->incomplete_comm_pattern_[i])
160       incomplete_communications_pattern[i].push_back(new simgrid::mc::PatternCommunication(comm.dup()));
161   }
162 }
163
164 static std::string print_determinism_result(simgrid::mc::CommPatternDifference diff, aid_t process,
165                                             const simgrid::mc::PatternCommunication* comm, unsigned int cursor)
166 {
167   std::string type;
168   std::string res;
169
170   if (comm->type == simgrid::mc::PatternCommunicationType::send)
171     type = xbt::string_printf("The send communications pattern of the process %ld is different!", process - 1);
172   else
173     type = xbt::string_printf("The recv communications pattern of the process %ld is different!", process - 1);
174
175   using simgrid::mc::CommPatternDifference;
176   switch (diff) {
177     case CommPatternDifference::TYPE:
178       res = xbt::string_printf("%s Different type for communication #%u", type.c_str(), cursor);
179       break;
180     case CommPatternDifference::MBOX:
181       res = xbt::string_printf("%s Different mailbox for communication #%u", type.c_str(), cursor);
182       break;
183     case CommPatternDifference::TAG:
184       res = xbt::string_printf("%s Different tag for communication #%u", type.c_str(), cursor);
185       break;
186     case CommPatternDifference::SRC_PROC:
187       res = xbt::string_printf("%s Different source for communication #%u", type.c_str(), cursor);
188       break;
189     case CommPatternDifference::DST_PROC:
190       res = xbt::string_printf("%s Different destination for communication #%u", type.c_str(), cursor);
191       break;
192     case CommPatternDifference::DATA_SIZE:
193       res = xbt::string_printf("%s Different data size for communication #%u", type.c_str(), cursor);
194       break;
195     default:
196       res = "";
197       break;
198   }
199
200   return res;
201 }
202
203 void CommDetExtension::deterministic_comm_pattern(aid_t actor, const PatternCommunication* comm, bool backtracking)
204 {
205   if (not backtracking) {
206     PatternCommunicationList& list = initial_communications_pattern[actor];
207     CommPatternDifference diff     = compare_comm_pattern(list.list[list.index_comm].get(), comm);
208
209     if (diff != CommPatternDifference::NONE) {
210       if (comm->type == PatternCommunicationType::send) {
211         send_deterministic = false;
212         send_diff          = print_determinism_result(diff, actor, comm, list.index_comm + 1);
213       } else {
214         recv_deterministic = false;
215         recv_diff          = print_determinism_result(diff, actor, comm, list.index_comm + 1);
216       }
217       if (_sg_mc_send_determinism && not send_deterministic) {
218         XBT_INFO("*********************************************************");
219         XBT_INFO("***** Non-send-deterministic communications pattern *****");
220         XBT_INFO("*********************************************************");
221         XBT_INFO("%s", send_diff.c_str());
222         api::get().log_state();
223         api::get().mc_exit(SIMGRID_MC_EXIT_NON_DETERMINISM);
224       } else if (_sg_mc_comms_determinism && (not send_deterministic && not recv_deterministic)) {
225         XBT_INFO("****************************************************");
226         XBT_INFO("***** Non-deterministic communications pattern *****");
227         XBT_INFO("****************************************************");
228         if (not send_diff.empty())
229           XBT_INFO("%s", send_diff.c_str());
230         if (not recv_diff.empty())
231           XBT_INFO("%s", recv_diff.c_str());
232         api::get().log_state();
233         api::get().mc_exit(SIMGRID_MC_EXIT_NON_DETERMINISM);
234       }
235     }
236   }
237 }
238
239 /********** Non Static functions ***********/
240
241 void CommDetExtension::get_comm_pattern(const Transition* transition, bool backtracking)
242 {
243   const mc::PatternCommunicationList& initial_pattern          = initial_communications_pattern[transition->aid_];
244   const std::vector<PatternCommunication*>& incomplete_pattern = incomplete_communications_pattern[transition->aid_];
245
246   auto pattern   = std::make_unique<PatternCommunication>();
247   pattern->index = initial_pattern.index_comm + incomplete_pattern.size();
248
249   if (transition->type_ == Transition::Type::COMM_SEND) {
250     auto* send = dynamic_cast<const CommSendTransition*>(transition);
251     /* Create comm pattern */
252     pattern->type      = PatternCommunicationType::send;
253     pattern->comm_addr = send->get_comm();
254     pattern->mbox      = send->get_mailbox();
255     pattern->src_proc  = send->aid_;
256
257 #if HAVE_SMPI
258     pattern->tag = 0; // FIXME: replace it by the real tag from the observer
259 #endif
260
261 #if HAVE_SMPI
262     // auto send_detached = api::get().check_send_request_detached(request);
263     if (false) { // send_detached) {
264       if (initial_communications_pattern_done) {
265         /* Evaluate comm determinism */
266         deterministic_comm_pattern(pattern->src_proc, pattern.get(), backtracking);
267         initial_communications_pattern[pattern->src_proc].index_comm++;
268       } else {
269         /* Store comm pattern */
270         initial_communications_pattern[pattern->src_proc].list.push_back(std::move(pattern));
271       }
272       return;
273     }
274 #endif
275   } else if (transition->type_ == Transition::Type::COMM_RECV) {
276     auto* recv = static_cast<const CommRecvTransition*>(transition);
277
278     pattern->type = PatternCommunicationType::receive;
279     pattern->comm_addr = recv->get_comm();
280
281 #if HAVE_SMPI
282     pattern->tag = 0; // FIXME: replace it by the real tag from the observer
283 #endif
284     pattern->mbox     = recv->get_mailbox();
285     pattern->dst_proc = recv->aid_;
286   }
287
288   XBT_DEBUG("Insert incomplete comm pattern %p type:%d for process %ld (comm: %" PRIxPTR ")", pattern.get(),
289             (int)pattern->type, transition->aid_, pattern->comm_addr);
290   incomplete_communications_pattern[transition->aid_].push_back(pattern.release());
291 }
292
293 void CommDetExtension::complete_comm_pattern(const CommWaitTransition* transition, bool backtracking)
294 {
295   /* Complete comm pattern */
296   std::vector<PatternCommunication*>& incomplete_pattern = incomplete_communications_pattern[transition->aid_];
297   uintptr_t comm_addr                                    = transition->get_comm();
298   auto current_comm_pattern =
299       std::find_if(begin(incomplete_pattern), end(incomplete_pattern),
300                    [&comm_addr](const PatternCommunication* comm) { return (comm->comm_addr == comm_addr); });
301   xbt_assert(current_comm_pattern != std::end(incomplete_pattern), "Corresponding communication not found!");
302   std::unique_ptr<PatternCommunication> comm_pattern(*current_comm_pattern);
303
304   comm_pattern->src_proc = transition->get_sender();
305   comm_pattern->dst_proc = transition->get_receiver();
306
307   XBT_DEBUG("Remove incomplete comm pattern for actor %ld at cursor %zd", transition->aid_,
308             std::distance(begin(incomplete_pattern), current_comm_pattern));
309   incomplete_pattern.erase(current_comm_pattern);
310
311   if (initial_communications_pattern_done) {
312     /* Evaluate comm determinism */
313     deterministic_comm_pattern(transition->aid_, comm_pattern.get(), backtracking);
314     initial_communications_pattern[transition->aid_].index_comm++;
315   } else {
316     /* Store comm pattern */
317     initial_communications_pattern[transition->aid_].list.push_back(std::move(comm_pattern));
318   }
319 }
320
321 CommunicationDeterminismChecker::CommunicationDeterminismChecker(Session* session) : Checker(session)
322 {
323   CommDetExtension::EXTENSION_ID = simgrid::mc::Checker::extension_create<CommDetExtension>();
324   StateCommDet::EXTENSION_ID = simgrid::mc::State::extension_create<StateCommDet>();
325 }
326
327 CommunicationDeterminismChecker::~CommunicationDeterminismChecker() = default;
328
329 RecordTrace CommunicationDeterminismChecker::get_record_trace() // override
330 {
331   RecordTrace res;
332   for (auto const& state : stack_)
333     res.push_back(state->get_transition());
334   return res;
335 }
336
337 std::vector<std::string> CommunicationDeterminismChecker::get_textual_trace() // override
338 {
339   std::vector<std::string> trace;
340   for (auto const& state : stack_)
341     trace.push_back(state->get_transition()->to_string());
342   return trace;
343 }
344
345 void CommunicationDeterminismChecker::log_state() // override
346 {
347   if (_sg_mc_comms_determinism) {
348     if (extension<CommDetExtension>()->send_deterministic && not extension<CommDetExtension>()->recv_deterministic) {
349       XBT_INFO("*******************************************************");
350       XBT_INFO("**** Only-send-deterministic communication pattern ****");
351       XBT_INFO("*******************************************************");
352       XBT_INFO("%s", extension<CommDetExtension>()->recv_diff.c_str());
353     }
354     if (not extension<CommDetExtension>()->send_deterministic && extension<CommDetExtension>()->recv_deterministic) {
355       XBT_INFO("*******************************************************");
356       XBT_INFO("**** Only-recv-deterministic communication pattern ****");
357       XBT_INFO("*******************************************************");
358       XBT_INFO("%s", extension<CommDetExtension>()->send_diff.c_str());
359     }
360   }
361   XBT_INFO("Expanded states = %ld", State::get_expanded_states());
362   XBT_INFO("Visited states = %lu", api::get().mc_get_visited_states());
363   XBT_INFO("Executed transitions = %lu", Transition::get_executed_transitions());
364   XBT_INFO("Send-deterministic : %s", extension<CommDetExtension>()->send_deterministic ? "Yes" : "No");
365   if (_sg_mc_comms_determinism)
366     XBT_INFO("Recv-deterministic : %s", extension<CommDetExtension>()->recv_deterministic ? "Yes" : "No");
367 }
368
369 void CommunicationDeterminismChecker::prepare()
370 {
371   auto initial_state = std::make_unique<State>();
372   extension_set(new CommDetExtension());
373   initial_state->extension_set(new StateCommDet(extension<CommDetExtension>()));
374
375   XBT_DEBUG("********* Start communication determinism verification *********");
376
377   /* Add all enabled actors to the interleave set of the initial state */
378   for (auto& act : api::get().get_actors()) {
379     auto actor = act.copy.get_buffer();
380     if (get_session().actor_is_enabled(actor->get_pid()))
381       initial_state->mark_todo(actor->get_pid());
382   }
383
384   stack_.push_back(std::move(initial_state));
385 }
386
387 void CommunicationDeterminismChecker::restoreState()
388 {
389   auto extension = this->extension<CommDetExtension>();
390
391   /* If asked to rollback on a state that has a snapshot, restore it */
392   State* last_state = stack_.back().get();
393   if (last_state->system_state_) {
394     api::get().restore_state(last_state->system_state_);
395     extension->restore_communications_pattern(last_state);
396     return;
397   }
398
399   /* if no snapshot, we need to restore the initial state and replay the transitions */
400   get_session().restore_initial_state();
401
402   const unsigned long maxpid = api::get().get_maxpid();
403   assert(maxpid == extension->incomplete_communications_pattern.size());
404   assert(maxpid == extension->initial_communications_pattern.size());
405   for (unsigned long j = 0; j < maxpid; j++) {
406     extension->incomplete_communications_pattern[j].clear();
407     extension->initial_communications_pattern[j].index_comm = 0;
408   }
409
410   /* Traverse the stack from the state at position start and re-execute the transitions */
411   for (std::unique_ptr<simgrid::mc::State> const& state : stack_) {
412     if (state == stack_.back())
413       break;
414
415     auto* transition = state->get_transition();
416     transition->replay();
417     extension->handle_comm_pattern(transition, true);
418
419     /* Update statistics */
420     api::get().mc_inc_visited_states();
421   }
422 }
423
424 void CommDetExtension::handle_comm_pattern(const Transition* transition, bool backtracking)
425 {
426   if (not _sg_mc_comms_determinism && not _sg_mc_send_determinism)
427     return;
428
429   switch (transition->type_) {
430     case Transition::Type::COMM_SEND:
431       get_comm_pattern(transition, backtracking);
432       break;
433     case Transition::Type::COMM_RECV:
434       get_comm_pattern(transition, backtracking);
435       break;
436     case Transition::Type::COMM_WAIT: {
437       complete_comm_pattern(static_cast<const CommWaitTransition*>(transition), backtracking);
438       break;
439     }
440     case Transition::Type::WAITANY: {
441       auto const* t    = static_cast<const WaitAnyTransition*>(transition)->get_current_transition();
442       auto const* wait = dynamic_cast<const CommWaitTransition*>(t);
443       if (wait != nullptr) // Ignore wait on non-comm
444         complete_comm_pattern(wait, backtracking);
445     } break;
446     default: /* Ignore unhandled transition types */
447       break;
448   }
449 }
450
451 void CommunicationDeterminismChecker::real_run()
452 {
453   auto extension = this->extension<CommDetExtension>();
454
455   std::unique_ptr<VisitedState> visited_state = nullptr;
456   const unsigned long maxpid                  = api::get().get_maxpid();
457
458   while (not stack_.empty()) {
459     /* Get current state */
460     State* cur_state = stack_.back().get();
461
462     XBT_DEBUG("**************************************************");
463     XBT_DEBUG("Exploration depth = %zu (state = %ld, interleaved processes = %zu)", stack_.size(), cur_state->num_,
464               cur_state->count_todo());
465
466     /* Update statistics */
467     api::get().mc_inc_visited_states();
468
469     int next_transition = -1;
470     if (stack_.size() <= (std::size_t)_sg_mc_max_depth)
471       next_transition = cur_state->next_transition();
472
473     if (next_transition >= 0 && visited_state == nullptr) {
474       cur_state->execute_next(next_transition);
475
476       auto* transition  = cur_state->get_transition();
477       XBT_DEBUG("Execute: %s", transition->to_string().c_str());
478
479       std::string req_str;
480       if (dot_output != nullptr)
481         req_str = api::get().request_get_dot_output(transition);
482
483       extension->handle_comm_pattern(transition, false);
484
485       /* Create the new expanded state */
486       auto next_state = std::make_unique<State>();
487       next_state->extension_set(new StateCommDet(extension));
488
489       bool all_communications_are_finished = true;
490       for (size_t current_actor = 1; all_communications_are_finished && current_actor < maxpid; current_actor++) {
491         if (not extension->incomplete_communications_pattern[current_actor].empty()) {
492           XBT_DEBUG("Some communications are not finished, cannot stop the exploration! State not visited.");
493           all_communications_are_finished = false;
494         }
495       }
496
497       /* If comm determinism verification, we cannot stop the exploration if some communications are not finished (at
498        * least, data are transferred). These communications  are incomplete and they cannot be analyzed and compared
499        * with the initial pattern. */
500       bool compare_snapshots = extension->initial_communications_pattern_done && all_communications_are_finished;
501
502       if (_sg_mc_max_visited_states != 0)
503         visited_state = visited_states_.addVisitedState(next_state->num_, next_state.get(), compare_snapshots);
504       else
505         visited_state = nullptr;
506
507       if (visited_state == nullptr) {
508         /* Add all enabled actors to the interleave set of the next state */
509         for (auto& act : api::get().get_actors()) {
510           auto actor = act.copy.get_buffer();
511           if (get_session().actor_is_enabled(actor->get_pid()))
512             next_state->mark_todo(actor->get_pid());
513         }
514
515         if (dot_output != nullptr)
516           fprintf(dot_output, "\"%ld\" -> \"%ld\" [%s];\n", cur_state->num_, next_state->num_, req_str.c_str());
517
518       } else if (dot_output != nullptr)
519         fprintf(dot_output, "\"%ld\" -> \"%ld\" [%s];\n", cur_state->num_,
520                 visited_state->original_num == -1 ? visited_state->num : visited_state->original_num, req_str.c_str());
521
522       stack_.push_back(std::move(next_state));
523     } else {
524       if (stack_.size() > (std::size_t)_sg_mc_max_depth)
525         XBT_WARN("/!\\ Max depth reached! /!\\ ");
526       else if (visited_state != nullptr)
527         XBT_DEBUG("State already visited (equal to state %ld), exploration stopped on this path.",
528                   visited_state->original_num == -1 ? visited_state->num : visited_state->original_num);
529       else
530         XBT_DEBUG("There are no more processes to interleave. (depth %zu)", stack_.size());
531
532       extension->initial_communications_pattern_done = true;
533
534       /* Trash the current state, no longer needed */
535       XBT_DEBUG("Delete state %ld at depth %zu", cur_state->num_, stack_.size());
536       stack_.pop_back();
537
538       visited_state = nullptr;
539
540       api::get().mc_check_deadlock();
541
542       while (not stack_.empty()) {
543         std::unique_ptr<State> state(std::move(stack_.back()));
544         stack_.pop_back();
545         if (state->count_todo() && stack_.size() < (std::size_t)_sg_mc_max_depth) {
546           /* We found a back-tracking point, let's loop */
547           XBT_DEBUG("Back-tracking to state %ld at depth %zu", state->num_, stack_.size() + 1);
548           stack_.push_back(std::move(state));
549
550           this->restoreState();
551
552           XBT_DEBUG("Back-tracking to state %ld at depth %zu done", stack_.back()->num_, stack_.size());
553
554           break;
555         } else {
556           XBT_DEBUG("Delete state %ld at depth %zu", state->num_, stack_.size() + 1);
557         }
558       }
559     }
560   }
561
562   api::get().log_state();
563 }
564
565 void CommunicationDeterminismChecker::run()
566 {
567   XBT_INFO("Check communication determinism");
568   get_session().take_initial_snapshot();
569
570   this->prepare();
571   this->real_run();
572 }
573
574 Checker* create_communication_determinism_checker(Session* session)
575 {
576   return new CommunicationDeterminismChecker(session);
577 }
578
579 } // namespace mc
580 } // namespace simgrid