Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
42ff35ec8632eb48dcd968370c0919823df20a85
[simgrid.git] / src / mc / explo / odpor / Execution.cpp
1 /* Copyright (c) 2008-2023. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include "src/mc/explo/odpor/Execution.hpp"
7 #include "src/mc/api/State.hpp"
8 #include "src/mc/explo/odpor/ReversibleRaceCalculator.hpp"
9 #include "xbt/asserts.h"
10 #include "xbt/string.hpp"
11 #include <algorithm>
12 #include <limits>
13 #include <vector>
14
15 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_odpor_execution, mc_dfs, "ODPOR exploration algorithm of the model-checker");
16
17 namespace simgrid::mc::odpor {
18
19 std::vector<std::string> get_textual_trace(const PartialExecution& w)
20 {
21   std::vector<std::string> trace;
22   for (const auto& t : w) {
23     auto a = xbt::string_printf("Actor %ld: %s", t->aid_, t->to_string(true).c_str());
24     trace.emplace_back(std::move(a));
25   }
26   return trace;
27 }
28
29 Execution::Execution(const PartialExecution& w)
30 {
31   push_partial_execution(w);
32 }
33
34 void Execution::push_transition(std::shared_ptr<Transition> t)
35 {
36   if (t == nullptr) {
37     throw std::invalid_argument("Unexpectedly received `nullptr`");
38   }
39   ClockVector max_clock_vector;
40   for (const Event& e : this->contents_) {
41     if (e.get_transition()->depends(t.get())) {
42       max_clock_vector = ClockVector::max(max_clock_vector, e.get_clock_vector());
43     }
44   }
45   max_clock_vector[t->aid_] = this->size();
46   contents_.push_back(Event({std::move(t), max_clock_vector}));
47 }
48
49 void Execution::push_partial_execution(const PartialExecution& w)
50 {
51   for (const auto& t : w) {
52     push_transition(t);
53   }
54 }
55
56 std::vector<std::string> Execution::get_textual_trace() const
57 {
58   std::vector<std::string> trace;
59   for (const auto& t : this->contents_) {
60     auto a = xbt::string_printf("Actor %ld: %s", t.get_transition()->aid_, t.get_transition()->to_string(true).c_str());
61     trace.emplace_back(std::move(a));
62   }
63   return trace;
64 }
65
66 std::unordered_set<Execution::EventHandle> Execution::get_racing_events_of(Execution::EventHandle target) const
67 {
68   std::unordered_set<Execution::EventHandle> racing_events;
69   // This keep tracks of events that happens-before the target
70   std::unordered_set<Execution::EventHandle> disqualified_events;
71
72   // For each event of the execution
73   for (auto e_i = target; e_i != std::numeric_limits<Execution::EventHandle>::max(); e_i--) {
74     // We need `e_i -->_E target` as a necessary condition
75     if (not happens_before(e_i, target)) {
76       XBT_DEBUG("ODPOR_RACING_EVENTS with `%u` : `%u` discarded because `%u` --\\-->_E `%u`", target, e_i, e_i, target);
77       continue;
78     }
79
80     // Further, `proc(e_i) != proc(target)`
81     if (get_actor_with_handle(e_i) == get_actor_with_handle(target)) {
82       disqualified_events.insert(e_i);
83       XBT_DEBUG("ODPOR_RACING_EVENTS with `%u` : `%u` disqualified because proc(`%u`)=proc(`%u`)", target, e_i, e_i,
84                 target);
85       continue;
86     }
87
88     // There could an event that "happens-between" the two events which would discount `e_i` as a race
89     for (auto e_j = e_i; e_j < target; e_j++) {
90       // If both:
91       // 1. e_i --->_E e_j; and
92       // 2. disqualified_events.count(e_j) > 0
93       // then e_i --->_E target indirectly (either through
94       // e_j directly, or transitively through e_j)
95       if (disqualified_events.count(e_j) > 0 && happens_before(e_i, e_j)) {
96         XBT_DEBUG("ODPOR_RACING_EVENTS with `%u` : `%u` disqualified because `%u` happens-between `%u`-->`%u`-->`%u`)",
97                   target, e_i, e_j, e_i, e_j, target);
98         disqualified_events.insert(e_i);
99         break;
100       }
101     }
102
103     // If `e_i` wasn't disqualified in the last round,
104     // it's in a race with `target`. After marking it
105     // as such, we ensure no other event `e` can happen-before
106     // it (since this would transitively make it the event
107     // which "happens-between" `target` and `e`)
108     if (disqualified_events.count(e_i) == 0) {
109       XBT_DEBUG("ODPOR_RACING_EVENTS with `%u` : `%u` is a valid racing event", target, e_i);
110       racing_events.insert(e_i);
111       disqualified_events.insert(e_i);
112     }
113   }
114
115   return racing_events;
116 }
117
118 std::unordered_set<Execution::EventHandle> Execution::get_reversible_races_of(EventHandle handle) const
119 {
120   std::unordered_set<EventHandle> reversible_races;
121   for (EventHandle race : get_racing_events_of(handle)) {
122     if (ReversibleRaceCalculator::is_race_reversible(*this, race, handle)) {
123       reversible_races.insert(race);
124     }
125   }
126   return reversible_races;
127 }
128
129 Execution Execution::get_prefix_before(Execution::EventHandle handle) const
130 {
131   return Execution(std::vector<Event>{contents_.begin(), contents_.begin() + handle});
132 }
133
134 std::unordered_set<aid_t>
135 Execution::get_missing_source_set_actors_from(EventHandle e, const std::unordered_set<aid_t>& backtrack_set) const
136 {
137   // If this execution is empty, there are no initials
138   // relative to the last transition added to the execution
139   // since such a transition does not exist
140   if (empty()) {
141     return std::unordered_set<aid_t>{};
142   }
143
144   // To actually compute `I_[E'](v) ∩ backtrack(E')`, we must
145   // first compute `E'` and "move" in the direction of `v`.
146   // We perform a scan over `E` (this execution) and make
147   // note of any events which occur after `e` but don't
148   // "happen-after" `e` by pushing them onto `E'`. Note that
149   // correctness is still preserved in computing `v` "on-the-fly"
150   // to determine if an event `e` by actor `q` is an initial for `E'`
151   // after `v`: only those events that "occur-before" `e` in `v` could
152   // "happen-before" `ve for any valid "happens-before" relation
153   // (see property 1 in the ODPOR paper, viz. "is included in <_E")
154
155   // First, grab `E' := pre(e, E)` and determine what actor `p` is
156   const auto next_E_p = get_latest_event_handle().value();
157   xbt_assert(e != next_E_p,
158              "This method assumes that the event `e` (%u) and `next_[E](p)` (%u)"
159              "are in a reversible race, yet we claim to have such a race between the"
160              "same event. This indicates the the SDPOR pseudocode implementation is broken "
161              "as it supplies these values.",
162              e, next_E_p);
163   Execution E_prime_v = get_prefix_before(e);
164   std::vector<sdpor::Execution::EventHandle> v;
165   std::unordered_set<aid_t> I_E_prime_v;
166   std::unordered_set<aid_t> disqualified_actors;
167
168   // Note `e + 1` here: `notdep(e, E)` is defined as the
169   // set of events that *occur-after* but don't *happen-after* `e`
170   for (auto e_prime = e + 1; e_prime <= next_E_p; ++e_prime) {
171     // Any event `e*` which occurs after `e` but which does not
172     // happen after `e` is a member of `v`. In addition to marking
173     // the event in `v`, we also "simulate" running the action `v`
174     // from E'
175     if (not happens_before(e, e_prime) || e_prime == next_E_p) {
176       // First, push the transition onto the hypothetical execution
177       E_prime_v.push_transition(get_event_with_handle(e_prime).get_transition());
178       const EventHandle e_prime_in_E_prime_v = E_prime_v.get_latest_event_handle().value();
179
180       // When checking whether any event in `dom_[E'](v)` happens before
181       // `next_[E'](q)` below for thread `q`, we must consider that the
182       // events relative to `E` (this execution) are different than those
183       // relative to `E'.v`. Thus e.g. event `7` in `E` may be event `4`
184       // in `E'.v`. Since we are asking about "happens-before"
185       // `-->_[E'.v]` about `E'.v`, we must build `v` relative to `E'`.
186       //
187       // Note that we add `q` to v regardless of whether `q` itself has been
188       // disqualified since  we've determined that `e_prime` "occurs-after" but
189       // does not "happen-after" `e`
190       v.push_back(e_prime_in_E_prime_v);
191
192       const aid_t q = E_prime_v.get_actor_with_handle(e_prime_in_E_prime_v);
193       if (disqualified_actors.count(q) > 0) { // Did we already note that `q` is not an initial?
194         continue;
195       }
196       const bool is_initial = std::none_of(v.begin(), v.end(), [&](const auto& e_star) {
197         return E_prime_v.happens_before(e_star, e_prime_in_E_prime_v);
198       });
199       if (is_initial) {
200         // If the backtrack set already contains `q`, we're done:
201         // they've made note to search for (or have already searched for)
202         // this initial
203         if (backtrack_set.count(q) > 0) {
204           return std::unordered_set<aid_t>{};
205         } else {
206           I_E_prime_v.insert(q);
207         }
208       } else {
209         // If `q` is disqualified as a candidate, clearly
210         // no event occurring after `e_prime` in `E` executed
211         // by actor `q` will qualify since any (valid) happens-before
212         // relation orders actions taken by each actor
213         disqualified_actors.insert(q);
214       }
215     }
216   }
217   xbt_assert(not I_E_prime_v.empty(),
218              "For any non-empty execution, we know that "
219              "at minimum one actor is an initial since "
220              "some execution is possible with respect to a "
221              "prefix before event `%u`, yet we didn't find anyone. "
222              "This implies the implementation of this function is broken.",
223              e);
224   return I_E_prime_v;
225 }
226
227 std::optional<PartialExecution> Execution::get_odpor_extension_from(EventHandle e, EventHandle e_prime,
228                                                                     const State& state_at_e) const
229 {
230   // `e` is assumed to be in a reversible race with `e_prime`.
231   // If `e > e_prime`, then `e` occurs-after `e_prime` which means
232   // `e` could not race with if
233   if (e > e_prime) {
234     throw std::invalid_argument("ODPOR extensions can only be computed for "
235                                 "events in a reversible race, which is claimed, "
236                                 "yet the racing event 'occurs-after' the target");
237   }
238
239   if (empty()) {
240     return std::nullopt;
241   }
242
243   PartialExecution v;
244   std::vector<Execution::EventHandle> v_handles;
245   std::unordered_set<aid_t> WI_E_prime_v;
246   std::unordered_set<aid_t> disqualified_actors;
247   Execution E_prime_v                           = get_prefix_before(e);
248   const std::unordered_set<aid_t> sleep_E_prime = state_at_e.get_sleeping_actors();
249
250   // Note `e + 1` here: `notdep(e, E)` is defined as the
251   // set of events that *occur-after* but don't *happen-after* `e`
252   //
253   // SUBTLE NOTE: ODPOR requires us to compute `notdep(e, E)` EVEN THOUGH
254   // the race is between `e` and `e'`; that is, events occurring in `E`
255   // that "occur-after" `e'` may end up in the partial execution `v`.
256   //
257   // Observe that `notdep(e, E).proc(e')` will contain all transitions
258   // that don't happen-after `e` in the order they appear FOLLOWED BY
259   // THE **TRANSITION** ASSOCIATED WITH **`e'`**!!
260   //
261   // SUBTLE NOTE: Observe that any event that "happens-after" `e'`
262   // must necessarily "happen-after" `e` as well, since `e` and
263   // `e'` are presumed to be in a reversible race. Hence, we know that
264   // all events `e_star` such that `e` "happens-before" `e_star` cannot affect
265   // the enabledness of `e'`; furthermore, `e'` cannot affect the enabledness
266   // of any event independent with `e` that "occurs-after" `e'`
267   for (auto e_star = e + 1; e_star <= get_latest_event_handle().value(); ++e_star) {
268     // Any event `e*` which occurs after `e` but which does not
269     // happen after `e` is a member of `v`. In addition to marking
270     // the event in `v`, we also "simulate" running the action `v` from E'
271     // to be able to compute `--->[E'.v]`
272     if (not happens_before(e, e_star)) {
273       xbt_assert(e_star != e_prime,
274                  "Invariant Violation: We claimed events %u and %u were in a reversible race, yet we also "
275                  "claim that they do not happen-before one another. This is impossible: "
276                  "are you sure that the two events are in a reversible race?",
277                  e, e_prime);
278       E_prime_v.push_transition(get_event_with_handle(e_star).get_transition());
279       v.push_back(get_event_with_handle(e_star).get_transition());
280
281       XBT_DEBUG("Added Event `%u` (%ld:%s) to the construction of v", e_star, get_actor_with_handle(e_star),
282                 get_event_with_handle(e_star).get_transition()->to_string().c_str());
283
284       const EventHandle e_star_in_E_prime_v = E_prime_v.get_latest_event_handle().value();
285
286       // When checking whether any event in `dom_[E'](v)` happens before
287       // `next_[E'](q)` below for thread `q`, we must consider that the
288       // events relative to `E` (this execution) are different than those
289       // relative to `E'.v`. Thus e.g. event `7` in `E` may be event `4`
290       // in `E'.v`. Since we are asking about "happens-before"
291       // `-->_[E'.v]` about `E'.v`, we must build `v` relative to `E'`
292       v_handles.push_back(e_star_in_E_prime_v);
293
294       // Note that we add `q` to v regardless of whether `q` itself has been
295       // disqualified since `q` may itself disqualify other actors
296       // (i.e. even if `q` is disqualified from being an initial, it
297       // is still contained in the sequence `v`)
298       const aid_t q = E_prime_v.get_actor_with_handle(e_star_in_E_prime_v);
299       if (disqualified_actors.count(q) > 0) { // Did we already note that `q` is not an initial?
300         continue;
301       }
302       const bool is_initial = std::none_of(v_handles.begin(), v_handles.end(), [&](const auto& handle) {
303         return E_prime_v.happens_before(handle, e_star_in_E_prime_v);
304       });
305       if (is_initial) {
306         // If the sleep set already contains `q`, we're done:
307         // we've found an initial contained in the sleep set and
308         // so the intersection is non-empty
309         if (sleep_E_prime.count(q) > 0) {
310           return std::nullopt;
311         } else {
312           WI_E_prime_v.insert(q);
313         }
314       } else {
315         // If `q` is disqualified as a candidate, clearly
316         // no event occurring after `e_prime` in `E` executed
317         // by actor `q` will qualify since any (valid) happens-before
318         // relation orders actions taken by each actor
319         disqualified_actors.insert(q);
320       }
321     } else {
322       XBT_DEBUG("Event `%u` (%ld:%s) dismissed from the construction of v", e_star, get_actor_with_handle(e_star),
323                 get_event_with_handle(e_star).get_transition()->to_string().c_str());
324     }
325   }
326
327   // Now we add `e_prime := <q, i>` to `E'.v` and repeat the same work
328   // It's possible `proc(e_prime)` is an initial
329   //
330   // Note the form of `v` in the pseudocode:
331   //  `v := notdep(e, E).e'^
332   E_prime_v.push_transition(get_event_with_handle(e_prime).get_transition());
333   v.push_back(get_event_with_handle(e_prime).get_transition());
334
335   const EventHandle e_prime_in_E_prime_v = E_prime_v.get_latest_event_handle().value();
336   v_handles.push_back(e_prime_in_E_prime_v);
337
338   const bool is_initial = std::none_of(v_handles.begin(), v_handles.end(), [&](const auto& handle) {
339     return E_prime_v.happens_before(handle, e_prime_in_E_prime_v);
340   });
341   if (is_initial) {
342     if (const aid_t q = E_prime_v.get_actor_with_handle(e_prime_in_E_prime_v); sleep_E_prime.count(q) > 0) {
343       return std::nullopt;
344     } else {
345       WI_E_prime_v.insert(q);
346     }
347   }
348
349   const Execution pre_E_e    = get_prefix_before(e);
350   const auto sleeping_actors = state_at_e.get_sleeping_actors();
351
352   // Check if any enabled actor that is independent with
353   // this execution after `v` is contained in the sleep set
354   for (const auto& [aid, astate] : state_at_e.get_actors_list()) {
355     const bool is_in_WI_E =
356         astate.is_enabled() and pre_E_e.is_independent_with_execution_of(v, astate.get_transition());
357     const bool is_in_sleep_set = sleeping_actors.count(aid) > 0;
358
359     // `action(aid)` is in `WI_[E](v)` but also is contained in the sleep set.
360     // This implies that the intersection between the two is non-empty
361     if (is_in_WI_E && is_in_sleep_set)
362       return std::nullopt;
363   }
364
365   return v;
366 }
367
368 bool Execution::is_initial_after_execution_of(const PartialExecution& w, aid_t p) const
369 {
370   auto E_w = *this;
371   std::vector<EventHandle> w_handles;
372   for (const auto& w_i : w) {
373     // Take one step in the direction of `w`
374     E_w.push_transition(w_i);
375
376     // If that step happened to be executed by `p`,
377     // great: we know that `p` is contained in `w`.
378     // We now need to verify that it doens't "happen-after"
379     // any events which occur before it
380     if (w_i->aid_ == p) {
381       const auto p_handle = E_w.get_latest_event_handle().value();
382       return std::none_of(w_handles.begin(), w_handles.end(),
383                           [&](const auto handle) { return E_w.happens_before(handle, p_handle); });
384     } else {
385       w_handles.push_back(E_w.get_latest_event_handle().value());
386     }
387   }
388   return false;
389 }
390
391 bool Execution::is_independent_with_execution_of(const PartialExecution& w, std::shared_ptr<Transition> next_E_p) const
392 {
393   // INVARIANT: Here, we assume that for any process `p_i` of `w`,
394   // the events of this execution followed by the execution of all
395   // actors occurring before `p_i` in `v` (`p_j`, `0 <= j < i`)
396   // are sufficient to enable `p_i`. This is fortunately the case
397   // with what ODPOR requires of us, viz. to ask the question about
398   // `v := notdep(e, E)` for some execution `E` and event `e` of
399   // that execution.
400   auto E_p_w = *this;
401   E_p_w.push_transition(std::move(next_E_p));
402   const auto p_handle = E_p_w.get_latest_event_handle().value();
403
404   // As we add events to `w`, verify that none
405   // of them "happen-after" the event associated with
406   // the step `next_E_p` (viz. p_handle)
407   for (const auto& w_i : w) {
408     E_p_w.push_transition(w_i);
409     const auto w_i_handle = E_p_w.get_latest_event_handle().value();
410     if (E_p_w.happens_before(p_handle, w_i_handle)) {
411       return false;
412     }
413   }
414   return true;
415 }
416
417 std::optional<PartialExecution> Execution::get_shortest_odpor_sq_subset_insertion(const PartialExecution& v,
418                                                                                   const PartialExecution& w) const
419 {
420   // See section 4 of Abdulla. et al.'s 2017 ODPOR paper for details (specifically
421   // where the [iterative] computation of `v ~_[E] w` is described)
422   auto E_v   = *this;
423   auto w_now = w;
424
425   for (const auto& next_E_p : v) {
426     // Is `p in `I_[E](w)`?
427     if (const aid_t p = next_E_p->aid_; E_v.is_initial_after_execution_of(w_now, p)) {
428       // Remove `p` from w and continue
429
430       // INVARIANT: If `p` occurs in `w`, it had better refer to the same
431       // transition referenced by `v`. Unfortunately, we have two
432       // sources of truth here which can be manipulated at the same
433       // time as arguments to the function. If ODPOR works correctly,
434       // they should always refer to the same value; but as a sanity check,
435       // we have an assert that tests that at least the types are the same.
436       const auto action_by_p_in_w =
437           std::find_if(w_now.begin(), w_now.end(), [=](const auto& action) { return action->aid_ == p; });
438       xbt_assert(action_by_p_in_w != w_now.end(), "Invariant violated: actor `p` "
439                                                   "is claimed to be an initial after `w` but is "
440                                                   "not actually contained in `w`. This indicates that there "
441                                                   "is a bug computing initials");
442       const auto& w_action = *action_by_p_in_w;
443       xbt_assert(w_action->type_ == next_E_p->type_,
444                  "Invariant violated: `v` claims that actor `%ld` executes '%s' while "
445                  "`w` claims that it executes '%s'. These two partial executions both "
446                  "refer to `next_[E](p)`, which should be the same",
447                  p, next_E_p->to_string(false).c_str(), w_action->to_string(false).c_str());
448       w_now.erase(action_by_p_in_w);
449     }
450     // Is `E ⊢ p ◇ w`?
451     else if (E_v.is_independent_with_execution_of(w_now, next_E_p)) {
452       // INVARIANT: Note that it is impossible for `p` to be
453       // excluded from the set `I_[E](w)` BUT ALSO be contained in
454       // `w` itself if `E ⊢ p ◇ w` (intuitively, the fact that `E ⊢ p ◇ w`
455       // means that are able to move `p` anywhere in `w` IF it occurred, so
456       // if it really does occur we know it must then be an initial).
457       // We assert this is the case here
458       const auto action_by_p_in_w =
459           std::find_if(w_now.begin(), w_now.end(), [=](const auto& action) { return action->aid_ == p; });
460       xbt_assert(action_by_p_in_w == w_now.end(),
461                  "Invariant violated: We claimed that actor `%ld` is not an initial "
462                  "after `w`, yet it's independent with all actions of `w` AND occurs in `w`."
463                  "This indicates that there is a bug computing initials",
464                  p);
465     } else {
466       // Neither of the two above conditions hold, so the relation fails
467       return std::nullopt;
468     }
469
470     // Move one step forward in the direction of `v` and repeat
471     E_v.push_transition(next_E_p);
472   }
473   return std::optional<PartialExecution>{std::move(w_now)};
474 }
475
476 bool Execution::happens_before(Execution::EventHandle e1_handle, Execution::EventHandle e2_handle) const
477 {
478   // 1. "happens-before" (-->_E) is a subset of "occurs before" (<_E)
479   // and is an irreflexive relation
480   if (e1_handle >= e2_handle) {
481     return false;
482   }
483
484   // Each execution maintains a stack of clock vectors which are updated
485   // according to the procedure outlined in section 4 of the original DPOR paper
486   const Event& e2     = get_event_with_handle(e2_handle);
487   const aid_t proc_e1 = get_actor_with_handle(e1_handle);
488
489   if (const auto e1_in_e2_clock = e2.get_clock_vector().get(proc_e1); e1_in_e2_clock.has_value()) {
490     return e1_handle <= e1_in_e2_clock.value();
491   }
492   // If `e1` does not appear in e2's clock vector, this implies
493   // not only that the transitions associated with `e1` and `e2
494   // are independent, but further that there are no transitive
495   // dependencies between e1 and e2
496   return false;
497 }
498
499 } // namespace simgrid::mc::odpor