Logo AND Algorithmique Numérique Distribuée

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