Logo AND Algorithmique Numérique Distribuée

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