Logo AND Algorithmique Numérique Distribuée

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