Skip to main content

temporal_control/
dispatch.rs

1//! Onboard dispatcher: executes a dispatchable network online, without allocation.
2//!
3//! A *dispatchable network* is a set of [`DispatchEdge`]s (`t_to - t_from <= weight`) and
4//! [`Wait`]s over executable and contingent time points. The ground side derives it from an
5//! [`Stn`](crate::Stn) or a dynamically controllable [`Stnu`](crate::Stnu); the onboard side only
6//! loads and executes it.
7//!
8//! # Execution semantics
9//!
10//! The dispatcher keeps, per time point, a window `[lb, ub]` (initially unbounded) and the
11//! number of precedence edges `x -> y` (defined below) whose head `y` has not happened yet. When a time point
12//! happens at `t` (executed by the agent or observed for a contingent point), the dispatcher
13//! propagates only along that point's own edges:
14//!
15//! - edge `x -> y` with weight `w` and `x` happened: `ub[y] = min(ub[y], t + w)`;
16//! - edge `y -> x` with weight `w` and `x` happened: `lb[y] = max(lb[y], t - w)`.
17//!
18//! An edge `x -> y` with weight `w < 0` is a *precedence* edge: `y` must happen strictly
19//! before `x`. A consistent network has no cycle of precedence edges. Zero-weight edges are
20//! not precedence edges; `x` may happen first and then caps `y`'s window at its own time.
21//!
22//! An executable point `x` may execute at `now` iff it has not happened, every precedence edge
23//! `x -> y` has `y` happened, `lb[x] <= now <= ub[x]`, and every wait `(x, c, d)` is satisfied:
24//! `c` has been observed, or its activation point happened at `a` and `now >= a + d`.
25//!
26//! **Reaction time.** Within one tick, observations are processed first, so a point may execute
27//! in the same tick in which a contingent point it waits for was observed (instantaneous
28//! reaction at tick granularity). [`Dispatcher::step`] follows that order.
29//!
30//! ```mermaid
31//! stateDiagram-v2
32//!     [*] --> Waiting
33//!     Waiting --> Enabled: all negative-edge heads happened
34//!     Enabled --> Executable: lb <= now, waits satisfied
35//!     Executable --> Happened: execute(now)
36//!     Executable --> Missed: now > ub
37//!     Happened --> [*]
38//! ```
39//!
40//! # Memory
41//!
42//! [`Dispatcher`] has fixed capacities: `N` time points and `E` adjacency entries. Every edge
43//! takes two entries (one per endpoint) and every wait one. Work per event is `O(degree)`;
44//! [`Dispatcher::step`] is `O(N * degree)` per executed point. Internal handles are stored in
45//! an [`Index`] type (`usize` by default, or `u16`/`u32`).
46
47pub mod encoding;
48mod index;
49#[cfg(feature = "alloc")]
50mod network;
51#[cfg(any(test, kani))]
52mod proofs;
53mod source;
54
55use core::fmt;
56
57use crate::{Ticks, TimePoint};
58use source::{Slices, Source};
59
60pub use encoding::{DecodeError, EncodeError};
61pub use index::Index;
62#[cfg(feature = "alloc")]
63pub use network::DispatchableNetwork;
64
65/// What kind of time point a dispatcher node is.
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
67pub enum PointKind {
68    /// The agent decides when this point happens.
69    Executable,
70    /// Nature decides: once `activation` happened at `a`, this point happens in `[a + lo, a + hi]`.
71    Contingent {
72        /// The time point that starts the contingent duration.
73        activation: TimePoint,
74        /// Shortest duration. Positive.
75        lo: Ticks,
76        /// Longest duration. At least `lo`.
77        hi: Ticks,
78    },
79}
80
81/// A dispatchable edge `t_to - t_from <= weight`.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
83pub struct DispatchEdge {
84    /// Tail of the distance-graph edge.
85    pub from: TimePoint,
86    /// Head of the distance-graph edge.
87    pub to: TimePoint,
88    /// Maximum of `t_to - t_from`.
89    pub weight: Ticks,
90}
91
92/// A wait: `waiter` must not execute before `activation(contingent) + delay`, unless
93/// `contingent` has been observed first.
94///
95/// Waits are the upper-case edges of an extended STNU (Morris, Muscettola and Vidal 2001).
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
97pub struct Wait {
98    /// The executable point that waits.
99    pub waiter: TimePoint,
100    /// The contingent point being waited for.
101    pub contingent: TimePoint,
102    /// Wait length after the contingent point's activation.
103    pub delay: Ticks,
104}
105
106/// Reasons a dispatcher call failed or detected a problem.
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
108#[non_exhaustive]
109pub enum DispatchError {
110    /// The network needs more than `N` points or `E` entries.
111    CapacityExceeded,
112    /// The network has more points or entries than the dispatcher's [`Index`] type can
113    /// address.
114    IndexTypeTooSmall,
115    /// The network is malformed: a bad index, a contingent link with `lo <= 0` or `lo > hi`, a
116    /// cyclic activation chain, a negative self-loop, or a wait on a non-contingent point.
117    InvalidNetwork,
118    /// The handle is not part of this dispatcher, or has the wrong kind for the call.
119    UnknownTimePoint,
120    /// `now` is earlier than a time passed to an earlier call.
121    TimeWentBackwards,
122    /// [`Dispatcher::execute`] was asked to execute a point that may not execute now. Nothing
123    /// changed.
124    NotExecutable(TimePoint),
125    /// The point already happened.
126    AlreadyHappened(TimePoint),
127    /// An executable point's window closed before it executed.
128    DeadlineMissed(TimePoint),
129    /// A contingent point was observed outside, or failed to occur within, its declared bounds.
130    /// The network's assumptions do not hold; its guarantees are void.
131    ContingentOutOfBounds(TimePoint),
132    /// A constraint of the network is violated, or the window of the point became empty.
133    ConstraintViolated(TimePoint),
134    /// The output buffer passed to [`Dispatcher::step`] is full.
135    OutputFull,
136    /// Tick arithmetic overflowed.
137    Overflow,
138}
139
140impl fmt::Display for DispatchError {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        match self {
143            Self::CapacityExceeded => f.write_str("dispatcher capacity exceeded"),
144            Self::IndexTypeTooSmall => f.write_str("network too large for the index type"),
145            Self::InvalidNetwork => f.write_str("malformed dispatchable network"),
146            Self::UnknownTimePoint => f.write_str("unknown time point or wrong kind"),
147            Self::TimeWentBackwards => f.write_str("time went backwards"),
148            Self::NotExecutable(tp) => write!(f, "time point {} may not execute now", tp.0),
149            Self::AlreadyHappened(tp) => write!(f, "time point {} already happened", tp.0),
150            Self::DeadlineMissed(tp) => write!(f, "deadline of time point {} missed", tp.0),
151            Self::ContingentOutOfBounds(tp) => {
152                write!(f, "contingent time point {} outside its bounds", tp.0)
153            }
154            Self::ConstraintViolated(tp) => write!(f, "constraint on time point {} violated", tp.0),
155            Self::OutputFull => f.write_str("output buffer full"),
156            Self::Overflow => f.write_str("tick arithmetic overflowed"),
157        }
158    }
159}
160
161impl core::error::Error for DispatchError {}
162
163/// Kind of a loaded point, with the activation stored as an [`Index`].
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165enum Kind<I> {
166    /// See [`PointKind::Executable`].
167    Executable,
168    /// See [`PointKind::Contingent`].
169    Contingent {
170        /// The time point that starts the contingent duration.
171        activation: I,
172        /// Shortest duration.
173        lo: Ticks,
174        /// Longest duration.
175        hi: Ticks,
176    },
177}
178
179impl<I: Index> Kind<I> {
180    /// Narrows a validated [`PointKind`].
181    ///
182    /// # Errors
183    ///
184    /// [`DispatchError::IndexTypeTooSmall`] if the activation does not fit `I`.
185    fn narrow(kind: PointKind) -> Result<Self, DispatchError> {
186        Ok(match kind {
187            PointKind::Executable => Self::Executable,
188            PointKind::Contingent { activation, lo, hi } => Self::Contingent {
189                activation: index(activation.0)?,
190                lo,
191                hi,
192            },
193        })
194    }
195
196    /// Widens back to the public [`PointKind`].
197    fn widen(self) -> PointKind {
198        match self {
199            Self::Executable => PointKind::Executable,
200            Self::Contingent { activation, lo, hi } => PointKind::Contingent {
201                activation: TimePoint(activation.to_usize()),
202                lo,
203                hi,
204            },
205        }
206    }
207
208    /// Whether this is an executable point.
209    const fn is_executable(self) -> bool {
210        matches!(self, Self::Executable)
211    }
212}
213
214/// One adjacency entry, owned by one time point.
215#[derive(Debug, Clone, Copy, PartialEq, Eq)]
216enum Entry<I> {
217    /// Unused slot.
218    Empty,
219    /// When the owner happens at `t`: `ub[target] <= t + weight`.
220    Upper {
221        /// The point whose upper bound tightens.
222        target: I,
223        /// Edge weight.
224        weight: Ticks,
225    },
226    /// When the owner happens at `t`: `lb[target] >= t - weight`.
227    Lower {
228        /// The point whose lower bound tightens.
229        target: I,
230        /// Weight of the edge `target -> owner`.
231        weight: Ticks,
232    },
233    /// The owner waits for `contingent` until `activation + delay`.
234    Wait {
235        /// The contingent point waited for.
236        contingent: I,
237        /// Wait length after activation.
238        delay: Ticks,
239    },
240}
241
242/// Fixed-capacity online dispatcher for up to `N` time points and `E` adjacency entries,
243/// storing internal handles as `I` (see [`Index`]).
244///
245/// # Examples
246///
247/// ```
248/// use temporal_control::{DispatchEdge, Dispatcher, PointKind, Ticks, TimePoint};
249///
250/// // 5 <= t_1 - t_0 <= 15
251/// let points = [PointKind::Executable; 2];
252/// let edges = [
253///     DispatchEdge { from: TimePoint(0), to: TimePoint(1), weight: Ticks(15) },
254///     DispatchEdge { from: TimePoint(1), to: TimePoint(0), weight: Ticks(-5) },
255/// ];
256/// let mut d = Dispatcher::<2, 4>::new(&points, &edges, &[]).expect("fits");
257/// let mut out = [TimePoint(0); 2];
258///
259/// assert_eq!(d.step(Ticks(0), &[], &mut out), Ok(1)); // t_0 = 0
260/// assert_eq!(d.step(Ticks(4), &[], &mut out), Ok(0)); // too early for t_1
261/// assert_eq!(d.step(Ticks(5), &[], &mut out), Ok(1)); // t_1 = 5
262/// assert!(d.is_complete());
263/// ```
264#[derive(Debug, Clone)]
265pub struct Dispatcher<const N: usize, const E: usize, I: Index = usize> {
266    /// Number of time points in use.
267    n: usize,
268    /// Kind of each point.
269    kinds: [Kind<I>; N],
270    /// Lower window bound per point; `None` is `-infinity`.
271    lb: [Option<Ticks>; N],
272    /// Upper window bound per point; `None` is `+infinity`.
273    ub: [Option<Ticks>; N],
274    /// Time each point happened, `None` until it happens.
275    time: [Option<Ticks>; N],
276    /// Per point: outgoing precedence edges whose head has not happened yet.
277    pending: [I; N],
278    /// Start of each point's entries in `entries`; the end is the next point's start.
279    start: [I; N],
280    /// Number of entries in use.
281    m: usize,
282    /// Adjacency entries grouped by owner.
283    entries: [Entry<I>; E],
284    /// Latest time passed to any call; `None` before the first call.
285    now: Option<Ticks>,
286}
287
288impl<const N: usize, const E: usize, I: Index> Dispatcher<N, E, I> {
289    /// A dispatcher with no network loaded, usable in `const` and `static` initialisers.
290    ///
291    /// Flight software typically places the dispatcher in statically allocated memory once
292    /// and then calls [`Self::load`] for every new plan, so the (possibly large) structure is
293    /// never built on the stack and returned by value. With no network loaded the dispatcher
294    /// has no points, [`Self::is_complete`] is true and every point handle is unknown.
295    ///
296    /// # Examples
297    ///
298    /// ```
299    /// use temporal_control::{DispatchEdge, Dispatcher, PointKind, Ticks, TimePoint};
300    ///
301    /// // Built at compile time; a flight build would put this behind its own cell type.
302    /// static IDLE: Dispatcher<8, 32> = Dispatcher::EMPTY;
303    /// assert!(IDLE.is_complete());
304    ///
305    /// let mut d = Dispatcher::<8, 32>::EMPTY;
306    /// let edges = [DispatchEdge { from: TimePoint(0), to: TimePoint(1), weight: Ticks(10) }];
307    /// d.load(&[PointKind::Executable; 2], &edges, &[]).expect("fits");
308    /// assert!(!d.is_complete());
309    /// ```
310    pub const EMPTY: Self = Self {
311        n: 0,
312        kinds: [Kind::Executable; N],
313        lb: [None; N],
314        ub: [None; N],
315        time: [None; N],
316        pending: [I::ZERO; N],
317        start: [I::ZERO; N],
318        m: 0,
319        entries: [Entry::Empty; E],
320        now: None,
321    };
322
323    /// Validates a dispatchable network and loads it into a new dispatcher.
324    ///
325    /// Shorthand for [`Self::EMPTY`] followed by [`Self::load`]. The dispatcher is returned by
326    /// value; for large capacities on a small stack prefer [`Self::load`] on a dispatcher in
327    /// static memory.
328    ///
329    /// # Errors
330    ///
331    /// As for [`Self::load`].
332    pub fn new(
333        points: &[PointKind],
334        edges: &[DispatchEdge],
335        waits: &[Wait],
336    ) -> Result<Self, DispatchError> {
337        let mut d = Self::EMPTY;
338        d.load(points, edges, waits)?;
339        Ok(d)
340    }
341
342    /// Validates a dispatchable network and loads it in place, replacing any earlier network
343    /// and execution state.
344    ///
345    /// This is the onboard trust boundary: every index, bound and capacity is checked, and
346    /// nothing is assumed about how the network was produced. Validation completes before the
347    /// first write, so a rejected network leaves the dispatcher exactly as it was (still
348    /// executing the previous plan, if any). Loading needs no stack memory proportional to
349    /// `N` or `E`.
350    ///
351    /// # Errors
352    ///
353    /// - [`DispatchError::CapacityExceeded`] if `points.len() > N` or
354    ///   `2 * edges.len() + waits.len() > E`.
355    /// - [`DispatchError::IndexTypeTooSmall`] if the point or entry count exceeds the maximum
356    ///   of `I` (see [`Index`]).
357    /// - [`DispatchError::InvalidNetwork`] for any malformed input (see its docs).
358    pub fn load(
359        &mut self,
360        points: &[PointKind],
361        edges: &[DispatchEdge],
362        waits: &[Wait],
363    ) -> Result<(), DispatchError> {
364        self.load_from(&Slices {
365            points,
366            edges,
367            waits,
368        })
369    }
370
371    /// Validates an encoded dispatchable network and loads it in place, without copying it
372    /// anywhere first.
373    ///
374    /// `bytes` must be exactly one encoding as written by [`encoding::encode_into`] (see
375    /// [`encoding`] for the format). Header, length and CRC-32 are checked first, then every
376    /// record, then the network as in [`Self::load`]. As there, a rejected encoding leaves the
377    /// dispatcher exactly as it was. Never panics on any input.
378    ///
379    /// # Examples
380    ///
381    /// ```
382    /// use temporal_control::dispatch::encoding;
383    /// use temporal_control::{DecodeError, DispatchEdge, Dispatcher, PointKind, Ticks, TimePoint};
384    ///
385    /// let points = [PointKind::Executable; 2];
386    /// let edges = [DispatchEdge { from: TimePoint(0), to: TimePoint(1), weight: Ticks(10) }];
387    /// let mut buf = [0u8; 128];
388    /// let len = encoding::encode_into(&points, &edges, &[], &mut buf).expect("fits");
389    ///
390    /// let mut d = Dispatcher::<4, 8>::EMPTY;
391    /// d.load_encoded(&buf[..len]).expect("valid");
392    /// assert_eq!(d.window(TimePoint(1)), Some((None, None)));
393    ///
394    /// buf[30] ^= 0x10;
395    /// assert_eq!(d.load_encoded(&buf[..len]), Err(DecodeError::ChecksumMismatch));
396    /// ```
397    ///
398    /// # Errors
399    ///
400    /// Any [`DecodeError`]; [`DecodeError::Network`] wraps the errors of [`Self::load`].
401    pub fn load_encoded(&mut self, bytes: &[u8]) -> Result<(), DecodeError> {
402        let encoded = encoding::Encoded::parse(bytes)?;
403        self.load_from(&encoded).map_err(DecodeError::Network)
404    }
405
406    /// Validates `net` and loads it in place; see [`Self::load`].
407    ///
408    /// # Errors
409    ///
410    /// As for [`Self::load`].
411    fn load_from(&mut self, net: &impl Source) -> Result<(), DispatchError> {
412        source::validate::<I>(net, N, E)?;
413
414        self.clear();
415        let filled = self.fill(net);
416
417        if filled.is_err() {
418            self.clear();
419        }
420
421        filled
422    }
423
424    /// Records that contingent point `tp` was observed at `now`.
425    ///
426    /// The observation is recorded and propagated even when it violates an assumption, so that
427    /// monitoring continues; the violation is then reported as an error.
428    ///
429    /// # Errors
430    ///
431    /// - [`DispatchError::UnknownTimePoint`] if `tp` is not a contingent point of this network.
432    /// - [`DispatchError::AlreadyHappened`] if `tp` was already observed.
433    /// - [`DispatchError::TimeWentBackwards`] if `now` precedes an earlier call.
434    /// - [`DispatchError::ContingentOutOfBounds`] if the activation has not happened or `now`
435    ///   is outside `[a + lo, a + hi]`.
436    /// - [`DispatchError::ConstraintViolated`] if a constraint with an already happened point is
437    ///   violated or a window became empty.
438    /// - [`DispatchError::Overflow`] on tick overflow.
439    pub fn observe(&mut self, tp: TimePoint, now: Ticks) -> Result<(), DispatchError> {
440        let PointKind::Contingent {
441            activation, lo, hi, ..
442        } = self.kind(tp)?
443        else {
444            return Err(DispatchError::UnknownTimePoint);
445        };
446
447        self.ensure_unhappened(tp)?;
448        self.advance_clock(now)?;
449
450        let in_bounds = self.time[activation.0].is_some_and(|a| {
451            a.checked_add(lo).is_some_and(|l| l <= now)
452                && a.checked_add(hi).is_none_or(|h| now <= h)
453        });
454        let in_window = self.in_window(tp.0, now);
455        self.happen(tp.0, now)?;
456
457        if !in_bounds {
458            return Err(DispatchError::ContingentOutOfBounds(tp));
459        }
460
461        if !in_window {
462            return Err(DispatchError::ConstraintViolated(tp));
463        }
464
465        Ok(())
466    }
467
468    /// Whether executable point `tp` may execute at `now`.
469    #[must_use]
470    pub fn can_execute(&self, tp: TimePoint, now: Ticks) -> bool {
471        tp.0 < self.n
472            && self.kinds[tp.0].is_executable()
473            && self.time[tp.0].is_none()
474            && self.now.is_none_or(|t| t <= now)
475            && self.pending[tp.0] == I::ZERO
476            && self.in_window(tp.0, now)
477            && self.waits_satisfied(tp.0, now)
478    }
479
480    /// Executes `tp` at `now` and propagates to its neighbors.
481    ///
482    /// # Errors
483    ///
484    /// - [`DispatchError::NotExecutable`] if [`Self::can_execute`] is false; nothing changes.
485    /// - [`DispatchError::ConstraintViolated`] if propagation empties a window. The point is
486    ///   executed regardless; this means the network was not dispatchable.
487    /// - [`DispatchError::Overflow`] on tick overflow.
488    pub fn execute(&mut self, tp: TimePoint, now: Ticks) -> Result<(), DispatchError> {
489        if !self.can_execute(tp, now) {
490            return Err(DispatchError::NotExecutable(tp));
491        }
492
493        self.now = Some(now);
494        self.happen(tp.0, now)
495    }
496
497    /// Advances the clock to `now` and reports deadlines that have passed.
498    ///
499    /// # Errors
500    ///
501    /// - [`DispatchError::TimeWentBackwards`] if `now` precedes an earlier call.
502    /// - [`DispatchError::DeadlineMissed`] for the first executable point with `ub < now`.
503    /// - [`DispatchError::ContingentOutOfBounds`] for the first contingent point that has not
504    ///   been observed although `now > a + hi`.
505    pub fn check_deadlines(&mut self, now: Ticks) -> Result<(), DispatchError> {
506        self.advance_clock(now)?;
507
508        for p in 0..self.n {
509            if self.time[p].is_some() {
510                continue;
511            }
512
513            let deadline = match self.kinds[p] {
514                Kind::Executable => self.ub[p],
515                Kind::Contingent { activation, hi, .. } => {
516                    self.time[activation.to_usize()].and_then(|a| a.checked_add(hi))
517                }
518            };
519
520            if deadline.is_some_and(|d| d < now) {
521                return Err(match self.kinds[p] {
522                    Kind::Executable => DispatchError::DeadlineMissed(TimePoint(p)),
523                    Kind::Contingent { .. } => DispatchError::ContingentOutOfBounds(TimePoint(p)),
524                });
525            }
526        }
527
528        Ok(())
529    }
530
531    /// Runs one tick with the as-soon-as-possible policy.
532    ///
533    /// Order: record every point in `observed` at `now`, check deadlines, then execute every
534    /// point that may execute at `now`, repeating until none is left. Executed points are
535    /// written to `out`; the return value is their number.
536    ///
537    /// # Errors
538    ///
539    /// Any error of [`Self::observe`] or [`Self::check_deadlines`], which stops the tick, and
540    /// [`DispatchError::OutputFull`] if `out` cannot hold the next executed point (that point
541    /// is not executed). A buffer of `N` entries never fills up.
542    pub fn step(
543        &mut self,
544        now: Ticks,
545        observed: &[TimePoint],
546        out: &mut [TimePoint],
547    ) -> Result<usize, DispatchError> {
548        for &c in observed {
549            self.observe(c, now)?;
550        }
551
552        self.check_deadlines(now)?;
553
554        let mut count = 0;
555
556        while let Some(tp) = self.next_executable(now) {
557            let slot = out.get_mut(count).ok_or(DispatchError::OutputFull)?;
558            *slot = tp;
559            count += 1;
560            self.execute(tp, now)?;
561        }
562
563        Ok(count)
564    }
565
566    /// Earliest time at or after the latest call at which some executable point could execute
567    /// without new observations, or `None` if none can.
568    ///
569    /// An executive may sleep until then unless an observation arrives first.
570    #[must_use]
571    pub fn next_wakeup(&self) -> Option<Ticks> {
572        let floor = self.now.unwrap_or(Ticks(i64::MIN));
573
574        (0..self.n)
575            .filter(|&p| self.kinds[p].is_executable() && self.time[p].is_none())
576            .filter(|&p| self.pending[p] == I::ZERO)
577            .filter_map(|p| self.earliest_start(p, floor))
578            .min()
579    }
580
581    /// Time at which `tp` happened, or `None` if it has not (or is unknown).
582    #[must_use]
583    pub fn time(&self, tp: TimePoint) -> Option<Ticks> {
584        self.time.get(..self.n)?.get(tp.0).copied().flatten()
585    }
586
587    /// Current window `(lb, ub)` of `tp`; `None` bounds are infinite. `None` for unknown handles.
588    #[must_use]
589    pub fn window(&self, tp: TimePoint) -> Option<(Option<Ticks>, Option<Ticks>)> {
590        (tp.0 < self.n).then(|| (self.lb[tp.0], self.ub[tp.0]))
591    }
592
593    /// Whether every time point has happened.
594    #[must_use]
595    pub fn is_complete(&self) -> bool {
596        self.time[..self.n].iter().all(Option::is_some)
597    }
598
599    /// Looks up the kind of `tp`.
600    ///
601    /// # Errors
602    ///
603    /// [`DispatchError::UnknownTimePoint`] if `tp` is out of range.
604    fn kind(&self, tp: TimePoint) -> Result<PointKind, DispatchError> {
605        self.kinds[..self.n]
606            .get(tp.0)
607            .map(|k| k.widen())
608            .ok_or(DispatchError::UnknownTimePoint)
609    }
610
611    /// Fails if `tp` already happened.
612    ///
613    /// # Errors
614    ///
615    /// [`DispatchError::AlreadyHappened`].
616    fn ensure_unhappened(&self, tp: TimePoint) -> Result<(), DispatchError> {
617        if self.time[tp.0].is_some() {
618            return Err(DispatchError::AlreadyHappened(tp));
619        }
620
621        Ok(())
622    }
623
624    /// Moves the clock to `now`.
625    ///
626    /// # Errors
627    ///
628    /// [`DispatchError::TimeWentBackwards`] if `now` precedes the clock.
629    fn advance_clock(&mut self, now: Ticks) -> Result<(), DispatchError> {
630        if self.now.is_some_and(|t| now < t) {
631            return Err(DispatchError::TimeWentBackwards);
632        }
633
634        self.now = Some(now);
635        Ok(())
636    }
637
638    /// Whether `now` lies in the window of point `p`.
639    fn in_window(&self, p: usize, now: Ticks) -> bool {
640        self.lb[p].is_none_or(|l| l <= now) && self.ub[p].is_none_or(|u| now <= u)
641    }
642
643    /// Index range in `entries` of the entries owned by point `p`.
644    fn range_of(&self, p: usize) -> core::ops::Range<usize> {
645        let end = if p + 1 < self.n {
646            self.start[p + 1].to_usize()
647        } else {
648            self.m
649        };
650
651        self.start[p].to_usize()..end
652    }
653
654    /// Entries owned by point `p`.
655    fn entries_of(&self, p: usize) -> &[Entry<I>] {
656        &self.entries[self.range_of(p)]
657    }
658
659    /// Whether every wait of `p` is satisfied at `now`.
660    fn waits_satisfied(&self, p: usize, now: Ticks) -> bool {
661        self.entries_of(p).iter().all(|e| match *e {
662            Entry::Wait { contingent, delay } => {
663                self.wait_released(contingent.to_usize(), delay, now)
664            }
665            _ => true,
666        })
667    }
668
669    /// Whether a wait for `contingent` with `delay` is over at `now`.
670    fn wait_released(&self, contingent: usize, delay: Ticks, now: Ticks) -> bool {
671        self.wait_release_time(contingent, delay)
672            .is_some_and(|r| r <= now)
673    }
674
675    /// Time at which a wait for `contingent` with `delay` ends: already (`i64::MIN`) if the
676    /// contingent point happened, `a + delay` once its activation happened, else `None`.
677    fn wait_release_time(&self, contingent: usize, delay: Ticks) -> Option<Ticks> {
678        if self.time[contingent].is_some() {
679            return Some(Ticks(i64::MIN));
680        }
681
682        let Kind::Contingent { activation, .. } = self.kinds[contingent] else {
683            return None;
684        };
685
686        self.time[activation.to_usize()].and_then(|a| a.checked_add(delay))
687    }
688
689    /// Earliest time `>= floor` at which enabled point `p` could execute, if its window allows.
690    fn earliest_start(&self, p: usize, floor: Ticks) -> Option<Ticks> {
691        let mut t = self.lb[p].map_or(floor, |l| l.max(floor));
692
693        for e in self.entries_of(p) {
694            if let Entry::Wait { contingent, delay } = *e {
695                t = t.max(self.wait_release_time(contingent.to_usize(), delay)?);
696            }
697        }
698
699        self.ub[p].is_none_or(|u| t <= u).then_some(t)
700    }
701
702    /// First point that may execute at `now`, in index order.
703    fn next_executable(&self, now: Ticks) -> Option<TimePoint> {
704        (0..self.n)
705            .map(TimePoint)
706            .find(|&tp| self.can_execute(tp, now))
707    }
708
709    /// Marks `p` as happened at `t` and propagates along its entries.
710    ///
711    /// Propagation always completes; the first problem found is returned afterwards.
712    ///
713    /// # Errors
714    ///
715    /// [`DispatchError::ConstraintViolated`] or [`DispatchError::Overflow`].
716    fn happen(&mut self, p: usize, t: Ticks) -> Result<(), DispatchError> {
717        self.time[p] = Some(t);
718        let mut result = Ok(());
719
720        for i in self.range_of(p) {
721            let outcome = match self.entries[i] {
722                Entry::Upper { target, weight } => self.tighten_upper(target.to_usize(), t, weight),
723                Entry::Lower { target, weight } => {
724                    self.tighten_lower(p, target.to_usize(), t, weight)
725                }
726                Entry::Wait { .. } | Entry::Empty => Ok(()),
727            };
728
729            if result.is_ok() {
730                result = outcome;
731            }
732        }
733
734        result
735    }
736
737    /// Applies `t_target <= t + weight`.
738    ///
739    /// # Errors
740    ///
741    /// [`DispatchError::ConstraintViolated`] if `target` happened later than allowed or its
742    /// window becomes empty; [`DispatchError::Overflow`] if the bound underflows.
743    fn tighten_upper(
744        &mut self,
745        target: usize,
746        t: Ticks,
747        weight: Ticks,
748    ) -> Result<(), DispatchError> {
749        let Some(bound) = t.checked_add(weight) else {
750            // Overflow upwards means no bound; downwards means an unmeetable one.
751            return if weight.0 > 0 {
752                Ok(())
753            } else {
754                Err(DispatchError::Overflow)
755            };
756        };
757
758        if let Some(s) = self.time[target] {
759            return ok_or_violated(s <= bound, target);
760        }
761
762        if self.ub[target].is_none_or(|u| bound < u) {
763            self.ub[target] = Some(bound);
764        }
765
766        ok_or_violated(self.window_nonempty(target), target)
767    }
768
769    /// Applies `t_target >= t - weight`, where `owner` happened at `t`, and releases the
770    /// precedence edge `target -> owner` if it is one.
771    ///
772    /// # Errors
773    ///
774    /// As for [`Self::tighten_upper`].
775    fn tighten_lower(
776        &mut self,
777        owner: usize,
778        target: usize,
779        t: Ticks,
780        weight: Ticks,
781    ) -> Result<(), DispatchError> {
782        if is_precedence(target, owner, weight) && self.time[target].is_none() {
783            self.pending[target] = self.pending[target].saturating_dec();
784        }
785
786        let Some(bound) = weight.checked_neg().and_then(|w| t.checked_add(w)) else {
787            return if weight.0 > 0 {
788                Ok(())
789            } else {
790                Err(DispatchError::Overflow)
791            };
792        };
793
794        if let Some(s) = self.time[target] {
795            return ok_or_violated(bound <= s, target);
796        }
797
798        if self.lb[target].is_none_or(|l| bound > l) {
799            self.lb[target] = Some(bound);
800        }
801
802        ok_or_violated(self.window_nonempty(target), target)
803    }
804
805    /// Whether `lb[p] <= ub[p]`.
806    fn window_nonempty(&self, p: usize) -> bool {
807        match (self.lb[p], self.ub[p]) {
808            (Some(l), Some(u)) => l <= u,
809            _ => true,
810        }
811    }
812
813    /// Resets every field to the state of [`Self::EMPTY`], in place.
814    fn clear(&mut self) {
815        self.n = 0;
816        self.kinds.fill(Kind::Executable);
817        self.lb.fill(None);
818        self.ub.fill(None);
819        self.time.fill(None);
820        self.pending.fill(I::ZERO);
821        self.start.fill(I::ZERO);
822        self.m = 0;
823        self.entries.fill(Entry::Empty);
824        self.now = None;
825    }
826
827    /// Fills a cleared dispatcher from a validated network.
828    ///
829    /// # Errors
830    ///
831    /// [`DispatchError::IndexTypeTooSmall`] if a value does not fit `I`, or
832    /// [`DispatchError::InvalidNetwork`] if a record cannot be read. Validation already rules
833    /// both out; the errors replace what would otherwise be panic paths, and the caller clears
834    /// the half-filled state.
835    fn fill(&mut self, net: &impl Source) -> Result<(), DispatchError> {
836        for (p, slot) in self.kinds.iter_mut().take(net.point_count()).enumerate() {
837            *slot = Kind::narrow(record(net.point(p))?)?;
838        }
839
840        self.n = net.point_count();
841        self.count_entries(net)?;
842        self.fill_entries(net)
843    }
844
845    /// Sets `start[p]` to the end of `p`'s entry range, `m` to the entry count, and `pending`
846    /// to the number of precedence edges per point.
847    ///
848    /// # Errors
849    ///
850    /// As for [`Self::fill`].
851    fn count_entries(&mut self, net: &impl Source) -> Result<(), DispatchError> {
852        for i in 0..net.edge_count() {
853            let e = record(net.edge(i))?;
854            increment(&mut self.start[e.from.0])?;
855            increment(&mut self.start[e.to.0])?;
856
857            if is_precedence(e.from.0, e.to.0, e.weight) {
858                increment(&mut self.pending[e.from.0])?;
859            }
860        }
861
862        for i in 0..net.wait_count() {
863            increment(&mut self.start[record(net.wait(i))?.waiter.0])?;
864        }
865
866        let mut end = 0usize;
867
868        for p in 0..self.n {
869            end += self.start[p].to_usize();
870            self.start[p] = index(end)?;
871        }
872
873        self.m = end;
874        Ok(())
875    }
876
877    /// Writes the owner-grouped adjacency, moving each `start[p]` from the end to the
878    /// beginning of `p`'s range.
879    ///
880    /// Together with [`Self::count_entries`] this is a counting sort that works inside `start`
881    /// instead of on temporary arrays. Iterating the input in reverse keeps each owner's
882    /// entries in input order (its edge entries in edge order, then its waits), which decides
883    /// which violation [`Self::happen`] reports first.
884    ///
885    /// # Errors
886    ///
887    /// As for [`Self::fill`].
888    fn fill_entries(&mut self, net: &impl Source) -> Result<(), DispatchError> {
889        for i in (0..net.wait_count()).rev() {
890            let w = record(net.wait(i))?;
891            let entry = Entry::Wait {
892                contingent: index(w.contingent.0)?,
893                delay: w.delay,
894            };
895            self.push_back(w.waiter.0, entry);
896        }
897
898        for i in (0..net.edge_count()).rev() {
899            let e = record(net.edge(i))?;
900            let (u, v) = (e.from.0, e.to.0);
901            let lower = Entry::Lower {
902                target: index(u)?,
903                weight: e.weight,
904            };
905            let upper = Entry::Upper {
906                target: index(v)?,
907                weight: e.weight,
908            };
909            self.push_back(v, lower);
910            self.push_back(u, upper);
911        }
912
913        Ok(())
914    }
915
916    /// Writes `entry` just before the current `start[owner]` and moves `start[owner]` there.
917    fn push_back(&mut self, owner: usize, entry: Entry<I>) {
918        let slot = self.start[owner].saturating_dec();
919        self.start[owner] = slot;
920        self.entries[slot.to_usize()] = entry;
921    }
922}
923
924/// Unwraps a record read from a validated [`Source`].
925///
926/// # Errors
927///
928/// [`DispatchError::InvalidNetwork`] if it could not be read.
929fn record<T>(value: Option<T>) -> Result<T, DispatchError> {
930    value.ok_or(DispatchError::InvalidNetwork)
931}
932
933/// Converts `value` to the index type.
934///
935/// # Errors
936///
937/// [`DispatchError::IndexTypeTooSmall`] if it does not fit.
938fn index<I: Index>(value: usize) -> Result<I, DispatchError> {
939    I::from_usize(value).ok_or(DispatchError::IndexTypeTooSmall)
940}
941
942/// Adds one to `counter`.
943///
944/// # Errors
945///
946/// [`DispatchError::IndexTypeTooSmall`] if the result does not fit.
947fn increment<I: Index>(counter: &mut I) -> Result<(), DispatchError> {
948    *counter = index(counter.to_usize().saturating_add(1))?;
949    Ok(())
950}
951
952/// Whether edge `from -> to` with `weight` makes `from` wait for `to` (see the module docs).
953fn is_precedence(from: usize, to: usize, weight: Ticks) -> bool {
954    weight < Ticks::ZERO && from != to
955}
956
957/// `Ok(())` if `ok`, else [`DispatchError::ConstraintViolated`] for point `p`.
958///
959/// # Errors
960///
961/// [`DispatchError::ConstraintViolated`] when `ok` is false.
962fn ok_or_violated(ok: bool, p: usize) -> Result<(), DispatchError> {
963    if ok {
964        Ok(())
965    } else {
966        Err(DispatchError::ConstraintViolated(TimePoint(p)))
967    }
968}