Logo AND Algorithmique Numérique Distribuée

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