Logo AND Algorithmique Numérique Distribuée

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