Logo AND Algorithmique Numérique Distribuée

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