Skip to main content

resource_timeline/
envelope.rs

1//! Level envelopes for activities whose start lies in a window.
2//!
3//! A flexible schedule fixes each activity's start only to a [`Window`], for example the
4//! windows a simple temporal network allows. The envelope bounds the level over *every*
5//! schedule the windows admit: at each tick, the lower envelope is the lowest level any
6//! schedule can reach there and the upper envelope the highest. If the lower envelope never
7//! falls below the minimum and the upper never exceeds the maximum, every schedule is safe and
8//! the dispatcher may pick any start in the windows without re-checking resources.
9//!
10//! This is the resource-envelope idea from Muscettola's work on flexible schedules. In its
11//! simplest form the windows are independent: the activities' starts may be chosen
12//! separately, so the extreme level at a tick is the sum of each activity's own extreme
13//! contribution there, and the envelope computed here is exactly the tightest one for
14//! independent windows. Three refinements build on it:
15//!
16//! - **Uncertain durations** ([`Envelope::with_contingent`]): a [`Contingent`] activity has a
17//!   start window and a duration range, and its impacts are [`Uncertain`]: anchored at the
18//!   start or at the (uncertain) end. Claims held until the end on a claimable timeline and
19//!   rates that run until the end are covered for every start and every duration, exactly.
20//! - **Precedences** ([`Envelope::with_precedences`]): [`Precedence`] constraints between the
21//!   starts and ends of activities tighten windows and durations by propagation and couple the
22//!   linked activities exactly (a maximum-weight closure for stepwise ones, a discretised
23//!   minimum cut with rates or uncertain durations); see the `precedence` module.
24//! - **States** ([`StateEnvelope`]): the same question for a state timeline, with
25//!   requirements and conflicting sets instead of bounds; exact for independent windows.
26//!
27//! # Bridge to `temporal-control`
28//!
29//! The crates do not depend on each other. Integration code builds the windows from
30//! `temporal-control`: before execution from the minimal network, `MinimalNetwork::lower` and
31//! `upper` between the origin and each activity's start time point; during execution from
32//! `Dispatcher::window`, which narrows as events are observed. Unbounded sides must be clamped
33//! to a mission horizon. Re-running [`Envelope::check`] on the narrowed windows after each
34//! observation keeps the resource guarantee in step with the temporal one. Contingent link
35//! bounds `[l, u]` of an STNU become the [`Contingent::duration`], and the network's
36//! requirement links between starts become [`Precedence`]s.
37//!
38//! ```mermaid
39//! graph LR
40//!     stn["temporal-control: start windows"] --> flexible["Flexible activities"]
41//!     fixed["Timeline: fixed impacts"] --> envelope["Envelope: lower and upper level per tick"]
42//!     contingent["Contingent activities: start window, duration range"] --> envelope
43//!     precedences["Precedences between starts"] --> envelope
44//!     flexible --> envelope
45//!     envelope --> verdict["Verdict: Safe, Possible or Certain"]
46//! ```
47
48mod closure;
49mod contingent;
50mod cut;
51mod member;
52mod precedence;
53mod state;
54
55use alloc::vec::Vec;
56
57pub use contingent::{Anchor, Contingent, Uncertain};
58use member::{Extreme, Member, Shape};
59use precedence::Network;
60pub use precedence::{Endpoint, Precedence};
61pub use state::{FlexibleState, StateEnvelope, StateEnvelopeViolation, StateVerdict};
62
63use crate::storage::{Heap, Storage};
64
65/// The default node budget of the exact coupled cut, see [`Envelope::with_cut_budget`].
66const DEFAULT_CUT_BUDGET: usize = 4096;
67use crate::{ActivityId, Bound, Error, Impact, Level, Tick, Timeline, Window};
68
69/// An activity whose start is only known to lie in a window.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
71pub struct Flexible<'a> {
72    /// The activity, reported back in explanations.
73    pub activity: ActivityId,
74    /// The allowed starts.
75    pub window: Window,
76    /// The effects of the activity on the timeline, with ticks relative to its start.
77    pub impacts: &'a [Impact],
78}
79
80/// The outcome of an envelope check.
81#[derive(Debug, Clone, PartialEq, Eq, Hash)]
82pub enum Verdict {
83    /// Every schedule the windows admit keeps the level within bounds at every tick.
84    Safe,
85    /// Some schedule may leave the bounds at the reported tick, but the envelopes do not show
86    /// that every schedule leaves them at that same tick. This does not imply that a safe
87    /// schedule exists: every schedule may still violate, each at a different tick. The
88    /// envelopes are exact, so some schedule does leave the bounds there, unless precedences
89    /// link activities with rates or uncertain durations whose domains exceed the cut budget
90    /// ([`Envelope::with_cut_budget`]); then it may be a false alarm.
91    Possible(EnvelopeViolation),
92    /// Every schedule the windows admit leaves the bounds at the reported tick.
93    Certain(EnvelopeViolation),
94}
95
96/// A tick at which the envelope breaks a bound, and the activities that can push it there.
97#[derive(Debug, Clone, PartialEq, Eq, Hash)]
98pub struct EnvelopeViolation {
99    /// The tick at which the envelope breaks the bound.
100    pub at: Tick,
101    /// The envelope value that breaks the bound: for [`Bound::BelowMin`] the lower envelope of
102    /// a possible violation or the upper envelope of a certain one, mirrored for
103    /// [`Bound::AboveMax`].
104    pub level: Level,
105    /// The broken bound.
106    pub bound: Bound,
107    /// The activities, fixed or flexible, that can push the level towards the bound at `at`:
108    /// a fixed activity whose net effect there points towards the bound, or a flexible
109    /// activity for which some start in its window does. Sorted ascending, without duplicates.
110    pub contributors: Vec<ActivityId>,
111}
112
113/// The lower and upper level envelopes of a timeline with additional flexible activities.
114///
115/// The timeline's own impacts count as fixed. Create it with [`Envelope::new`].
116///
117/// # Examples
118///
119/// ```
120/// use resource_timeline::envelope::{Envelope, Flexible, Verdict};
121/// use resource_timeline::{ActivityId, Bounds, Impact, Timeline, Window};
122///
123/// // A battery at 10 units, reserve 0, charged by 6 units at tick 10.
124/// let mut battery = Timeline::depletable(0, 10, Bounds::new(0, 100)?, 8)?;
125/// battery.add(ActivityId(0), Impact::Step { at: 10, delta: 6 })?;
126///
127/// // Two heaters, each drawing 6 units, may start anywhere in [0, 20].
128/// let heat = [Impact::Step { at: 0, delta: -6 }];
129/// let window = Window::new(0, 20)?;
130/// let flexible = [
131///     Flexible { activity: ActivityId(1), window, impacts: &heat },
132///     Flexible { activity: ActivityId(2), window, impacts: &heat },
133/// ];
134///
135/// let envelope = Envelope::new(&battery, &flexible)?;
136/// assert_eq!(envelope.lower_at(0)?, -2); // both heaters start before the charge
137/// assert_eq!(envelope.upper_at(0)?, 10); // neither has started yet
138/// match envelope.check()? {
139///     Verdict::Possible(violation) => assert_eq!(violation.at, 0),
140///     verdict => panic!("unexpected {verdict:?}"),
141/// }
142///
143/// // With the second heater held back until after the charge, every schedule is safe.
144/// let late = Window::new(10, 20)?;
145/// let flexible = [flexible[0], Flexible { window: late, ..flexible[1] }];
146/// assert_eq!(Envelope::new(&battery, &flexible)?.check()?, Verdict::Safe);
147/// # Ok::<(), resource_timeline::Error>(())
148/// ```
149#[derive(Debug, Clone)]
150pub struct Envelope<'a, S: Storage = Heap> {
151    /// The timeline with the fixed impacts, start, initial level, bounds and targets.
152    timeline: &'a Timeline<S>,
153    /// The flexible and contingent activities, validated against the timeline.
154    members: Vec<Member<'a>>,
155    /// The start window of each member, tightened by the precedences.
156    windows: Vec<Window>,
157    /// The duration range of each member, tightened by the precedences (`[0, 0]` for fixed
158    /// impacts).
159    durations: Vec<Window>,
160    /// The largest graph the exact coupled cut may build, in nodes.
161    cut_budget: usize,
162    /// The precedences between members, as given.
163    precedences: Vec<Precedence>,
164    /// The temporal network of the precedences, `None` without precedences.
165    network: Option<Network>,
166}
167
168impl<'a, S: Storage> Envelope<'a, S> {
169    /// Combines the fixed impacts of `timeline` with the `flexible` activities.
170    ///
171    /// The windows are independent until [`with_precedences`](Self::with_precedences) couples
172    /// them; [`with_contingent`](Self::with_contingent) adds activities with uncertain
173    /// durations.
174    ///
175    /// # Errors
176    ///
177    /// - The validation errors of [`Timeline::add`] for any flexible impact at the earliest or
178    ///   latest start of its window, including [`Error::BeforeStart`] when the earliest start
179    ///   would place an impact before the timeline start.
180    /// - [`Error::Overflow`] if a shifted tick does not fit a [`Tick`].
181    /// - [`Error::OutOfMemory`] if the activity list cannot be allocated.
182    pub fn new(timeline: &'a Timeline<S>, flexible: &'a [Flexible<'a>]) -> Result<Self, Error> {
183        for activity in flexible {
184            for impact in activity.impacts {
185                for start in [activity.window.earliest(), activity.window.latest()] {
186                    timeline.validate(impact.shifted(start).ok_or(Error::Overflow)?)?;
187                }
188            }
189        }
190
191        let mut envelope = Self {
192            timeline,
193            members: Vec::new(),
194            windows: Vec::new(),
195            durations: Vec::new(),
196            cut_budget: DEFAULT_CUT_BUDGET,
197            precedences: Vec::new(),
198            network: None,
199        };
200        envelope.extend(flexible.iter().map(|activity| Member {
201            activity: activity.activity,
202            window: activity.window,
203            shape: Shape::Fixed(activity.impacts),
204        }))?;
205        Ok(envelope)
206    }
207
208    /// Adds activities whose durations are uncertain.
209    ///
210    /// The envelope then covers every start in each window combined with every duration in
211    /// each duration range. Claims and rates that last as long as the activity are anchored at
212    /// its end, see [`Uncertain`]. Such a member's extreme at a tick is found by evaluating its
213    /// profile at the vertices of the (start, duration) box, see the `member` module.
214    ///
215    /// # Errors
216    ///
217    /// - [`Error::NegativeDuration`] if a duration range starts below zero.
218    /// - [`Error::EmptyInterval`] if a claim or rate interval is inverted for some duration
219    ///   (an empty interval at the shortest duration is allowed).
220    /// - The other validation errors of [`Timeline::add`] for any impact at the corners of the
221    ///   start window and the duration range.
222    /// - The errors of [`with_precedences`](Self::with_precedences) if precedences were
223    ///   given before.
224    /// - [`Error::Overflow`] if a tick does not fit a [`Tick`].
225    ///
226    /// # Examples
227    ///
228    /// ```
229    /// use resource_timeline::envelope::{Anchor, Contingent, Envelope, Uncertain, Verdict};
230    /// use resource_timeline::{ActivityId, Bounds, Impact, Timeline, Window};
231    ///
232    /// // A battery at 30 units; a heater draws 2 units per tick while it runs, 5 to 15 ticks.
233    /// let battery = Timeline::depletable(0, 30, Bounds::new(0, 100)?, 8)?;
234    /// let heat = [Uncertain::Rate { start: Anchor::Start(0), end: Anchor::End(0), per_tick: -2 }];
235    /// let heater = [Contingent {
236    ///     activity: ActivityId(1),
237    ///     window: Window::new(0, 10)?,
238    ///     duration: Window::new(5, 15)?,
239    ///     impacts: &heat,
240    /// }];
241    ///
242    /// let envelope = Envelope::new(&battery, &[])?.with_contingent(&heater)?;
243    /// assert_eq!(envelope.lower_at(25)?, 0); // the longest run has drawn 30
244    /// assert_eq!(envelope.upper_at(25)?, 20); // the shortest run has drawn 10
245    /// assert_eq!(envelope.check()?, Verdict::Safe);
246    ///
247    /// // A 16-tick run would drain the battery: possible, not certain.
248    /// let longer = [Contingent { duration: Window::new(5, 16)?, ..heater[0] }];
249    /// let envelope = Envelope::new(&battery, &[])?.with_contingent(&longer)?;
250    /// assert!(matches!(envelope.check()?, Verdict::Possible(_)));
251    /// # Ok::<(), resource_timeline::Error>(())
252    /// ```
253    pub fn with_contingent(mut self, contingent: &'a [Contingent<'a>]) -> Result<Self, Error> {
254        for activity in contingent {
255            self.validate_contingent(activity)?;
256        }
257
258        self.extend(contingent.iter().map(|activity| Member {
259            activity: activity.activity,
260            window: activity.window,
261            shape: Shape::Uncertain {
262                duration: activity.duration,
263                impacts: activity.impacts,
264            },
265        }))?;
266        self.couple()?;
267        Ok(self)
268    }
269
270    /// Restricts the schedules to those that respect `precedences` between the activities.
271    ///
272    /// Start windows and contingent duration ranges are tightened by propagation, and the
273    /// activities that take part in a precedence get a joint, exact extreme: by
274    /// maximum-weight closure if all are stepwise, by a discretised minimum cut if some have
275    /// rates or uncertain durations and their domains fit the cut budget; see the `precedence`
276    /// module. Above the budget the latter keep separate extremes over their tightened ranges,
277    /// which may add up to a level no single schedule reaches, so [`Verdict::Possible`] may
278    /// then be a false alarm (never [`Verdict::Safe`] a false all-clear). The envelopes are
279    /// never looser than without precedences. With the cut, every tick a coupled time point
280    /// can take becomes an evaluation tick, so [`check`](Self::check) costs grow with those
281    /// windows.
282    ///
283    /// # Errors
284    ///
285    /// - [`Error::UnknownActivity`] if a precedence names an activity that is not part of the
286    ///   envelope. Add contingent activities with [`with_contingent`](Self::with_contingent)
287    ///   first; precedences given earlier are re-applied when activities are added later.
288    /// - [`Error::InconsistentPrecedences`] if no schedule satisfies the windows and the
289    ///   precedences together.
290    /// - [`Error::OutOfMemory`] if the network cannot be allocated.
291    ///
292    /// # Examples
293    ///
294    /// ```
295    /// use resource_timeline::envelope::{Envelope, Flexible, Precedence, Verdict};
296    /// use resource_timeline::{ActivityId, Bounds, Impact, Timeline, Window};
297    ///
298    /// // One transmitter; two downlinks of 10 ticks, each anywhere in [0, 20].
299    /// let transmitter = Timeline::claimable(0, 1, 8)?;
300    /// let downlink = [Impact::Claim { start: 0, end: 10, amount: 1 }];
301    /// let window = Window::new(0, 20)?;
302    /// let flexible = [
303    ///     Flexible { activity: ActivityId(1), window, impacts: &downlink },
304    ///     Flexible { activity: ActivityId(2), window, impacts: &downlink },
305    /// ];
306    ///
307    /// // Independent windows let the downlinks overlap.
308    /// let independent = Envelope::new(&transmitter, &flexible)?;
309    /// assert!(matches!(independent.check()?, Verdict::Possible(_)));
310    ///
311    /// // "2 starts after 1 has ended" rules every overlap out.
312    /// let ordered = independent.with_precedences(&[Precedence::after_end(
313    ///     ActivityId(1),
314    ///     ActivityId(2),
315    ///     0,
316    /// )])?;
317    /// assert_eq!(ordered.check()?, Verdict::Safe);
318    /// assert_eq!(ordered.window(ActivityId(1)), Some(Window::new(0, 10)?));
319    /// # Ok::<(), resource_timeline::Error>(())
320    /// ```
321    pub fn with_precedences(mut self, precedences: &[Precedence]) -> Result<Self, Error> {
322        self.precedences
323            .try_reserve(precedences.len())
324            .map_err(|_| Error::OutOfMemory)?;
325        self.precedences.extend_from_slice(precedences);
326        self.couple()?;
327        Ok(self)
328    }
329
330    /// Sets the largest graph, in nodes, that the exact coupled extreme of precedence-linked
331    /// activities with rates or uncertain durations may build per tick (one node per tick of
332    /// each coupled start and end domain). Above it those activities get separate, sound
333    /// extremes. The default is 4096.
334    ///
335    /// # Errors
336    ///
337    /// The errors of [`with_precedences`](Self::with_precedences), re-run with the new budget.
338    pub fn with_cut_budget(mut self, nodes: usize) -> Result<Self, Error> {
339        self.cut_budget = nodes;
340        self.couple()?;
341        Ok(self)
342    }
343
344    /// The duration range of the first activity with id `activity`, tightened by the
345    /// precedences (`[0, 0]` for a flexible activity), or `None` if there is no such activity.
346    #[must_use]
347    pub fn duration(&self, activity: ActivityId) -> Option<Window> {
348        self.members
349            .iter()
350            .position(|member| member.activity == activity)
351            .map(|index| self.durations[index])
352    }
353
354    /// The start window of the first activity with id `activity`, tightened by the
355    /// precedences, or `None` if there is no such activity.
356    #[must_use]
357    pub fn window(&self, activity: ActivityId) -> Option<Window> {
358        self.members
359            .iter()
360            .position(|member| member.activity == activity)
361            .map(|index| self.windows[index])
362    }
363
364    /// The lowest level any admitted schedule has at tick `t`.
365    ///
366    /// Costs `O(n + f k^2)` for `n` fixed impacts and `f` independent activities with `k`
367    /// impacts each, plus a minimum cut over the pending events of coupled activities.
368    ///
369    /// # Errors
370    ///
371    /// - [`Error::BeforeStart`] if `t` precedes the timeline start.
372    /// - [`Error::Overflow`] if the value does not fit a [`Level`].
373    /// - [`Error::OutOfMemory`] if the event graph of coupled activities cannot be allocated.
374    pub fn lower_at(&self, t: Tick) -> Result<Level, Error> {
375        self.level_at(t, Extreme::Lower)
376    }
377
378    /// The highest level any admitted schedule has at tick `t`.
379    ///
380    /// # Errors
381    ///
382    /// As for [`lower_at`](Self::lower_at).
383    pub fn upper_at(&self, t: Tick) -> Result<Level, Error> {
384        self.level_at(t, Extreme::Upper)
385    }
386
387    /// Checks the envelopes against the timeline's bounds and end-state targets.
388    ///
389    /// The envelopes are evaluated at every tick where their shape can change and at the tick
390    /// before. Without rates they are constant in between, so the reported tick is the
391    /// earliest one with a possible (or certain) violation. With rates the upper envelope is
392    /// convex and the lower one concave between those ticks, so [`Verdict::Safe`] is still
393    /// exact, but a reported tick may lie after the first one, and a certain violation that
394    /// exists only strictly between evaluation ticks is reported as possible. A certain
395    /// violation anywhere takes precedence over possible ones.
396    ///
397    /// # Errors
398    ///
399    /// - [`Error::Overflow`] if an envelope value does not fit a [`Level`].
400    /// - [`Error::OutOfMemory`] if the evaluation ticks cannot be allocated.
401    pub fn check(&self) -> Result<Verdict, Error> {
402        let mut possible = None;
403        for t in self.evaluation_ticks()? {
404            let (lower, upper) = (self.lower_at(t)?, self.upper_at(t)?);
405            for (min, max, target) in self.limits_at(t) {
406                if let Some((level, bound)) = certain_breach(lower, upper, min, max, target) {
407                    return Ok(Verdict::Certain(self.explain(t, level, bound)?));
408                }
409
410                if possible.is_none() {
411                    if let Some((level, bound)) = possible_breach(lower, upper, min, max, target) {
412                        possible = Some(self.explain(t, level, bound)?);
413                    }
414                }
415            }
416        }
417
418        Ok(possible.map_or(Verdict::Safe, Verdict::Possible))
419    }
420
421    /// Appends members with their windows as given.
422    fn extend(&mut self, members: impl ExactSizeIterator<Item = Member<'a>>) -> Result<(), Error> {
423        let extra = members.len();
424        self.members
425            .try_reserve(extra)
426            .map_err(|_| Error::OutOfMemory)?;
427        self.windows
428            .try_reserve(extra)
429            .map_err(|_| Error::OutOfMemory)?;
430        self.durations
431            .try_reserve(extra)
432            .map_err(|_| Error::OutOfMemory)?;
433        for member in members {
434            self.windows.push(member.window);
435            self.durations.push(member.duration());
436            self.members.push(member);
437        }
438
439        Ok(())
440    }
441
442    /// Recomputes the tightened windows and the network from the precedences.
443    fn couple(&mut self) -> Result<(), Error> {
444        if self.precedences.is_empty() {
445            return Ok(());
446        }
447
448        let (tightened, network) =
449            Network::propagate(&self.members, &self.precedences, self.cut_budget)?;
450        self.windows = tightened.windows;
451        self.durations = tightened.durations;
452        self.network = Some(network);
453        Ok(())
454    }
455
456    /// Checks a contingent activity's impacts at every corner of its start window and
457    /// duration range.
458    fn validate_contingent(&self, activity: &Contingent<'_>) -> Result<(), Error> {
459        let duration = activity.duration;
460        if duration.earliest() < 0 {
461            return Err(Error::NegativeDuration {
462                shortest: duration.earliest(),
463            });
464        }
465
466        for impact in activity.impacts {
467            for length in [duration.earliest(), duration.latest()] {
468                let relative = impact.resolve(length).ok_or(Error::Overflow)?;
469                let relative = contingent::widened(relative)?;
470                for start in [activity.window.earliest(), activity.window.latest()] {
471                    let shifted = relative.shifted(start).ok_or(Error::Overflow)?;
472                    self.timeline.validate(shifted)?;
473                }
474            }
475        }
476
477        Ok(())
478    }
479
480    /// The limits in force at `t`: the bounds, then each target at `t`, as
481    /// `(min, max, is_target)`.
482    fn limits_at(&self, t: Tick) -> impl Iterator<Item = (Level, Level, bool)> + '_ {
483        let bounds = self.timeline.bounds();
484        let targets = self
485            .timeline
486            .targets()
487            .iter()
488            .filter(move |target| target.at == t)
489            .map(|target| (target.min, Level::MAX, true));
490        core::iter::once((bounds.min(), bounds.max(), false)).chain(targets)
491    }
492
493    /// The fixed level plus the extreme contributions of the members at `t`: coupled members
494    /// jointly, the others one by one.
495    fn level_at(&self, t: Tick, extreme: Extreme) -> Result<Level, Error> {
496        let mut level = i128::from(self.timeline.level_at(t)?);
497        for (index, member) in self.members.iter().enumerate() {
498            if self
499                .network
500                .as_ref()
501                .is_some_and(|network| network.is_coupled(index))
502            {
503                continue;
504            }
505
506            let (window, duration) = (self.windows[index], self.durations[index]);
507            let contribution = member.extreme_at(window, duration, t, extreme)?;
508            level = level.checked_add(contribution).ok_or(Error::Overflow)?;
509        }
510
511        if let Some(network) = &self.network {
512            let coupled = network.coupled_extreme(&self.members, t, extreme)?;
513            level = level.checked_add(coupled).ok_or(Error::Overflow)?;
514        }
515
516        Level::try_from(level).map_err(|_| Error::Overflow)
517    }
518
519    /// Every tick from the start on at which an envelope can change shape, and the tick
520    /// before each, sorted and without duplicates.
521    fn evaluation_ticks(&self) -> Result<Vec<Tick>, Error> {
522        let start = self.timeline.start();
523        let mut ticks = Vec::new();
524        let mut push = |tick: i128| -> Result<(), Error> {
525            for tick in [tick - 1, tick] {
526                if let Ok(tick) = Tick::try_from(tick) {
527                    if tick >= start {
528                        ticks.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
529                        ticks.push(tick);
530                    }
531                }
532            }
533
534            Ok(())
535        };
536
537        push(i128::from(start))?;
538        for tick in self.timeline.change_ticks() {
539            push(i128::from(tick))?;
540        }
541
542        for ((member, window), duration) in
543            self.members.iter().zip(&self.windows).zip(&self.durations)
544        {
545            for offset in member.offsets(*duration) {
546                for start in [window.earliest(), window.latest()] {
547                    push(offset + i128::from(start))?;
548                }
549            }
550        }
551
552        // The exact coupled cut over rates or durations may change shape at any tick a coupled
553        // time point can take; its graph is within the node budget, so are these ranges.
554        if let Some(network) = &self.network {
555            for (lo, hi) in network.dense_ranges(&self.members) {
556                for tick in lo..=hi {
557                    push(tick)?;
558                }
559            }
560        }
561
562        ticks.sort_unstable();
563        ticks.dedup();
564        Ok(ticks)
565    }
566
567    /// The violation at `t` with the activities that can push towards `bound` there.
568    fn explain(&self, t: Tick, level: Level, bound: Bound) -> Result<EnvelopeViolation, Error> {
569        let towards = if bound.is_lower() {
570            Extreme::Lower
571        } else {
572            Extreme::Upper
573        };
574
575        let mut contributors = Vec::new();
576        let fixed = self.timeline.contributors_at(t, bound)?;
577        contributors
578            .try_reserve_exact(fixed.len() + self.members.len())
579            .map_err(|_| Error::OutOfMemory)?;
580        contributors.extend_from_slice(&fixed);
581        let ranges = self.members.iter().zip(&self.windows).zip(&self.durations);
582        for ((member, window), duration) in ranges {
583            if bound.is_pushed_by(member.extreme_at(*window, *duration, t, towards)?) {
584                contributors.push(member.activity);
585            }
586        }
587
588        contributors.sort_unstable();
589        contributors.dedup();
590        Ok(EnvelopeViolation {
591            at: t,
592            level,
593            bound,
594            contributors,
595        })
596    }
597}
598
599/// The broken lower bound: [`Bound::BelowTarget`] for a target, [`Bound::BelowMin`] otherwise.
600const fn lower_bound(min: Level, target: bool) -> Bound {
601    if target {
602        Bound::BelowTarget(min)
603    } else {
604        Bound::BelowMin(min)
605    }
606}
607
608/// The level and bound of a violation every schedule has, if the envelopes `[lower, upper]`
609/// lie entirely outside `[min, max]`.
610const fn certain_breach(
611    lower: Level,
612    upper: Level,
613    min: Level,
614    max: Level,
615    target: bool,
616) -> Option<(Level, Bound)> {
617    if upper < min {
618        Some((upper, lower_bound(min, target)))
619    } else if lower > max {
620        Some((lower, Bound::AboveMax(max)))
621    } else {
622        None
623    }
624}
625
626/// The level and bound of a violation some schedule may have, if the envelopes `[lower, upper]`
627/// reach outside `[min, max]`.
628const fn possible_breach(
629    lower: Level,
630    upper: Level,
631    min: Level,
632    max: Level,
633    target: bool,
634) -> Option<(Level, Bound)> {
635    if lower < min {
636        Some((lower, lower_bound(min, target)))
637    } else if upper > max {
638        Some((upper, Bound::AboveMax(max)))
639    } else {
640        None
641    }
642}