Skip to main content

resource_timeline/plan/
search.rs

1//! Tentative checks and the earliest-start search of a plan.
2//!
3//! # Why the candidate starts suffice without rates
4//!
5//! Without rates every level is a step function. Whether an activity starting at `s` fits
6//! depends only on how each of its shifted ticks `s + o` compares (less, equal, greater) with
7//! each change tick `p` of the touched timeline. These comparisons change only at `s = p - o`
8//! (from less to equal) and `s = p - o + 1` (from equal to greater), so the answer is constant
9//! between consecutive candidates, and the earliest fitting start is the window start or one of
10//! them.
11//!
12//! # Closed form per piece with rates
13//!
14//! With rates a level also depends on the distance between ticks, so the answer may change
15//! inside a piece `[c_i, c_{i+1})` between consecutive candidates. The order of all ticks is
16//! still fixed there, so the merged level line has the same segments for every start `s` in the
17//! piece, and the level at each segment start, at the tick before each segment end and at each
18//! target is affine in `s` with an integer coefficient: a shifted point moves along a fixed
19//! line, a shifted rate changes its contribution to a fixed tick by its rate per tick. The
20//! activity fits at `s` if every such affine value lies within its bounds; the extremes of a
21//! linear segment are at its ends, so these values cover every tick. The search evaluates the
22//! line at `c_i` and `c_i + 1`, reads each value and its coefficient off the pair, and solves
23//! the inequalities for the earliest `s` in closed form, without checking `s` tick by tick.
24
25use super::{Demand, Plan};
26use crate::state::{Requirement, SetPoint};
27use crate::storage::{PlanStorage, Seq, Storage};
28use crate::timeline::profile::Point;
29use crate::{Container, Error, Impact, StateImpact, Tick, Timeline, Window};
30
31/// The scratch list types of a probe on plan storage `P`.
32type Line<P> = <P as PlanStorage>::Line;
33
34/// Working memory of [`Plan::fits`](super::Plan::fits) and
35/// [`Plan::earliest_start`](super::Plan::earliest_start), for callers that keep it outside the
36/// stack.
37///
38/// With [`Fixed<N>`](crate::storage::Fixed) storage it holds two change-point lists of `2 N`
39/// points and a set and a requirement list of `N` entries, `216 N + 128` bytes on 64-bit
40/// targets: 58 KiB for `N = 256`. `fits` and `earliest_start` put it on the stack;
41/// [`Plan::fits_with`](super::Plan::fits_with) and
42/// [`Plan::earliest_start_with`](super::Plan::earliest_start_with) borrow one instead, for
43/// example from a `static` or a task's own memory. Measured on x86-64 (release, frame sizes
44/// from `-Z emit-stack-sizes`, confirmed by running in threads of shrinking stack): a search
45/// over a `FixedPlan<2, 1, 256>` needs about 60 KiB of stack with the internal scratch and
46/// fits in a 16 KiB thread stack with a borrowed one; its largest frame is the 2.4 KiB of the
47/// change-point sort. Explaining a violation (`first_violation`) keeps its own per-activity
48/// working list of `32 N` bytes on the stack, about 16 KiB for `N = 256`.
49///
50/// # Examples
51///
52/// ```
53/// use resource_timeline::storage::{Fixed, FixedPlan};
54/// use resource_timeline::{ActivityId, Demand, Impact, Plan, SearchScratch, Timeline, Window};
55///
56/// let mut plan = Plan::<FixedPlan<1, 0, 64>>::new_in();
57/// let transmitter = plan.add_timeline(Timeline::claimable_in(0, 1, 64)?)?;
58/// let downlink = [Demand::Level {
59///     timeline: transmitter,
60///     impact: Impact::Claim { start: 0, end: 8, amount: 1 },
61/// }];
62/// plan.place(ActivityId(1), 5, &downlink)?;
63///
64/// let mut scratch = SearchScratch::<Fixed<64>>::new();
65/// let window = Window::new(0, 100)?;
66/// assert_eq!(plan.earliest_start_with(&downlink, window, 1_000, &mut scratch)?, Some(13));
67/// # Ok::<(), resource_timeline::Error>(())
68/// ```
69#[derive(Debug, Clone)]
70pub struct SearchScratch<S: Storage> {
71    /// Change points of the shifted demands on the numeric timeline being checked.
72    points: S::DoubleList<Point>,
73    /// The same change points for a start one tick later, for the closed-form solve.
74    points_next: S::DoubleList<Point>,
75    /// Sets of the shifted demands on the state timeline being checked.
76    sets: S::List<SetPoint>,
77    /// Requirements of the shifted demands on the state timeline being checked.
78    requires: S::List<Requirement>,
79}
80
81impl<S: Storage> SearchScratch<S> {
82    /// Empty working memory.
83    #[must_use]
84    pub const fn new() -> Self {
85        Self {
86            points: <S::DoubleList<Point> as Seq<_>>::EMPTY,
87            points_next: <S::DoubleList<Point> as Seq<_>>::EMPTY,
88            sets: <S::List<SetPoint> as Seq<_>>::EMPTY,
89            requires: <S::List<Requirement> as Seq<_>>::EMPTY,
90        }
91    }
92}
93
94impl<S: Storage> Default for SearchScratch<S> {
95    fn default() -> Self {
96        Self::new()
97    }
98}
99
100/// Checks one activity at many candidate starts, with borrowed working memory.
101pub(super) struct Probe<'a, P: PlanStorage> {
102    /// The plan the activity is checked against.
103    plan: &'a Plan<P>,
104    /// The demands of the activity, relative to its start.
105    demands: &'a [Demand],
106    /// The working memory.
107    scratch: &'a mut SearchScratch<Line<P>>,
108}
109
110impl<'a, P: PlanStorage> Probe<'a, P> {
111    /// Prepares scratch space for `demands`.
112    ///
113    /// Reserves room for the largest number of demands on any one timeline, so that
114    /// [`fits`](Self::fits) never allocates.
115    ///
116    /// # Errors
117    ///
118    /// - [`Error::UnknownResource`] if a demand names a timeline outside `plan`.
119    /// - [`Error::OutOfMemory`] or [`Error::CapacityExceeded`] if the scratch buffers cannot
120    ///   be allocated.
121    pub(super) fn new(
122        plan: &'a Plan<P>,
123        demands: &'a [Demand],
124        scratch: &'a mut SearchScratch<Line<P>>,
125    ) -> Result<Self, Error> {
126        for demand in demands {
127            let known = match *demand {
128                Demand::Level { timeline, .. } => plan.timeline(timeline).is_some(),
129                Demand::State { timeline, .. } => plan.state(timeline).is_some(),
130            };
131            if !known {
132                return Err(Error::UnknownResource);
133            }
134        }
135
136        let most = most_on_one_timeline(demands);
137        for points in [&mut scratch.points, &mut scratch.points_next] {
138            points.clear();
139            points.try_reserve(most.saturating_mul(2), Container::Scratch)?;
140        }
141
142        scratch.sets.clear();
143        scratch.requires.clear();
144        scratch.sets.try_reserve(most, Container::Scratch)?;
145        scratch.requires.try_reserve(most, Container::Scratch)?;
146        Ok(Self {
147            plan,
148            demands,
149            scratch,
150        })
151    }
152
153    /// Whether the activity fits when it starts at `start`. Never allocates.
154    ///
155    /// # Errors
156    ///
157    /// See [`Plan::fits`].
158    pub(super) fn fits(&mut self, start: Tick) -> Result<bool, Error> {
159        for index in self.representatives() {
160            if !self.timeline_fits(&self.demands[index], start)? {
161                return Ok(false);
162            }
163        }
164
165        Ok(true)
166    }
167
168    /// The earliest start in `[lo, hi]` at which the activity fits, solved in closed form.
169    ///
170    /// Every start in `[lo, hi]` must be admissible and see the same order of demand ticks and
171    /// change ticks (a piece between consecutive search candidates); see the module docs. Never
172    /// allocates.
173    ///
174    /// # Errors
175    ///
176    /// See [`Plan::fits`].
177    fn earliest_in(&mut self, lo: Tick, hi: Tick) -> Result<Option<Tick>, Error> {
178        if lo == hi {
179            return Ok(self.fits(lo)?.then_some(lo));
180        }
181
182        let mut offsets = Offsets {
183            lo: 0,
184            hi: i128::from(hi) - i128::from(lo),
185        };
186        for index in self.representatives() {
187            let representative = self.demands[index];
188            let Demand::Level { timeline, .. } = representative else {
189                // The order of ticks fixes every state comparison, so one start decides.
190                if !self.timeline_fits(&representative, lo)? {
191                    return Ok(None);
192                }
193
194                continue;
195            };
196
197            let timeline = &self.plan.timelines[timeline.0];
198            let first = collect_points(
199                timeline,
200                self.demands,
201                &representative,
202                lo,
203                &mut self.scratch.points,
204            )?;
205            let second = collect_points(
206                timeline,
207                self.demands,
208                &representative,
209                lo + 1,
210                &mut self.scratch.points_next,
211            )?;
212            if !(first && second) {
213                return Ok(None);
214            }
215
216            timeline.narrow(
217                &self.scratch.points,
218                &self.scratch.points_next,
219                &mut offsets,
220            )?;
221            if offsets.is_empty() {
222                return Ok(None);
223            }
224        }
225
226        let start = i128::from(lo) + offsets.lo;
227        Ok(Some(Tick::try_from(start).map_err(|_| Error::Overflow)?))
228    }
229
230    /// The indices of the first demand on each touched timeline.
231    fn representatives(&self) -> impl Iterator<Item = usize> + 'a {
232        let demands = self.demands;
233        (0..demands.len()).filter(move |&index| {
234            !demands[..index]
235                .iter()
236                .any(|earlier| earlier.same_timeline(&demands[index]))
237        })
238    }
239
240    /// Whether the timeline of `representative` stays valid with all demands on it added.
241    fn timeline_fits(&mut self, representative: &Demand, start: Tick) -> Result<bool, Error> {
242        match *representative {
243            Demand::Level { timeline, .. } => {
244                let timeline = &self.plan.timelines[timeline.0];
245                if !collect_points(
246                    timeline,
247                    self.demands,
248                    representative,
249                    start,
250                    &mut self.scratch.points,
251                )? {
252                    return Ok(false);
253                }
254
255                Ok(timeline.breach_with(&self.scratch.points)?.is_none())
256            }
257            Demand::State { timeline, .. } => {
258                let timeline = &self.plan.states[timeline.0];
259                if !self.collect_states(representative, start)? {
260                    return Ok(false);
261                }
262
263                Ok(!timeline.is_violated_with(&self.scratch.sets, &self.scratch.requires))
264            }
265        }
266    }
267
268    /// Fills `sets` and `requires` with the shifted state demands on the timeline of
269    /// `representative`. Returns `false` if one of them would precede the timeline start.
270    fn collect_states(&mut self, representative: &Demand, start: Tick) -> Result<bool, Error> {
271        self.scratch.sets.clear();
272        self.scratch.requires.clear();
273        for demand in self.demands {
274            let Demand::State { timeline, impact } = *demand else {
275                continue;
276            };
277            if !demand.same_timeline(representative) {
278                continue;
279            }
280
281            let shifted = impact.shifted(start).ok_or(Error::Overflow)?;
282            match self.plan.states[timeline.0].validate(shifted) {
283                Ok(()) => {}
284                Err(Error::BeforeStart { .. }) => return Ok(false),
285                Err(error) => return Err(error),
286            }
287
288            self.push_state(shifted)?;
289        }
290
291        self.scratch.sets.sort_unstable_by_key(SetPoint::key);
292        Ok(true)
293    }
294
295    /// Stores one shifted, validated state impact in the scratch lists.
296    ///
297    /// # Errors
298    ///
299    /// None in practice: [`new`](Self::new) reserved the room.
300    fn push_state(&mut self, impact: StateImpact) -> Result<(), Error> {
301        // The probe's own activity id is irrelevant for the yes/no answer; any fixed id works.
302        let activity = crate::ActivityId(u32::MAX);
303        match impact {
304            StateImpact::Set { at, value } => {
305                let set = SetPoint {
306                    at,
307                    activity,
308                    value,
309                };
310                self.scratch.sets.try_push(set, Container::Scratch)
311            }
312            StateImpact::Require { start, end, value } => {
313                let requirement = Requirement {
314                    activity,
315                    start,
316                    end,
317                    value,
318                };
319                self.scratch
320                    .requires
321                    .try_push(requirement, Container::Scratch)
322            }
323        }
324    }
325}
326
327/// Fills `points` with the shifted changes of all numeric demands of `demands` on the timeline
328/// of `representative`, which is `timeline`, sorted by tick. Returns `false` if one of them
329/// would precede the timeline start.
330///
331/// # Errors
332///
333/// [`Error::Overflow`] if a shifted tick does not fit, the validation errors of
334/// [`Timeline::add`] other than [`Error::BeforeStart`], and capacity errors if `points` was not
335/// reserved.
336fn collect_points<S: Storage>(
337    timeline: &Timeline<S>,
338    demands: &[Demand],
339    representative: &Demand,
340    start: Tick,
341    points: &mut impl Seq<Point>,
342) -> Result<bool, Error> {
343    points.clear();
344    for demand in demands {
345        let Demand::Level { impact, .. } = *demand else {
346            continue;
347        };
348        if !demand.same_timeline(representative) {
349            continue;
350        }
351
352        let Some(impact) = admissible(timeline, impact, start)? else {
353            return Ok(false);
354        };
355        for (at, step, slope) in impact.changes().into_iter().flatten() {
356            points.try_push(Point::loose(at, step, slope), Container::Scratch)?;
357        }
358    }
359
360    points.sort_unstable_by_key(|point| point.at);
361    Ok(true)
362}
363
364/// The largest number of demands that address the same timeline.
365fn most_on_one_timeline(demands: &[Demand]) -> usize {
366    demands
367        .iter()
368        .map(|demand| {
369            demands
370                .iter()
371                .filter(|other| other.same_timeline(demand))
372                .count()
373        })
374        .max()
375        .unwrap_or(0)
376}
377
378/// `impact` shifted to `start` if the timeline accepts it there, `None` if it would precede
379/// the timeline start.
380fn admissible<S: Storage>(
381    timeline: &Timeline<S>,
382    impact: Impact,
383    start: Tick,
384) -> Result<Option<Impact>, Error> {
385    let shifted = impact.shifted(start).ok_or(Error::Overflow)?;
386    match timeline.validate(shifted) {
387        Ok(()) => Ok(Some(shifted)),
388        Err(Error::BeforeStart { .. }) => Ok(None),
389        Err(error) => Err(error),
390    }
391}
392
393/// Finds the earliest start in `window` at which `demands` fit, checking at most `max_checks`
394/// pieces between consecutive candidates.
395pub(super) fn earliest_start<P: PlanStorage>(
396    plan: &Plan<P>,
397    demands: &[Demand],
398    window: Window,
399    max_checks: usize,
400    scratch: &mut SearchScratch<Line<P>>,
401) -> Result<Option<Tick>, Error> {
402    let mut probe = Probe::new(plan, demands, scratch)?;
403    let Some(window) = admissible_window(plan, demands, window) else {
404        return Ok(None);
405    };
406
407    let rates = involves_rates(plan, demands);
408    let mut checks = 0_usize;
409    let mut piece = Some(window.earliest());
410    while let Some(lo) = piece {
411        if checks == max_checks {
412            return Err(Error::SearchExhausted { checks: max_checks });
413        }
414
415        checks += 1;
416        let next = next_candidate(plan, demands, lo, window);
417        let found = if rates {
418            let hi = next.map_or(window.latest(), |next| next - 1);
419            probe.earliest_in(lo, hi)?
420        } else {
421            probe.fits(lo)?.then_some(lo)
422        };
423        if found.is_some() {
424            return Ok(found);
425        }
426
427        piece = next;
428    }
429
430    Ok(None)
431}
432
433/// A range `[lo, hi]` of start offsets from the first start of a piece. Empty if `lo > hi`.
434#[derive(Debug, Clone, Copy, PartialEq, Eq)]
435pub(crate) struct Offsets {
436    /// The smallest offset left.
437    pub(crate) lo: i128,
438    /// The largest offset left.
439    pub(crate) hi: i128,
440}
441
442impl Offsets {
443    /// Whether no offset is left.
444    pub(crate) const fn is_empty(&self) -> bool {
445        self.lo > self.hi
446    }
447
448    /// Keeps the offsets `k` with `min <= value + slope * k <= max` (no upper limit for
449    /// `max == None`).
450    ///
451    /// # Errors
452    ///
453    /// [`Error::Overflow`] if a difference of levels exceeds `i128`.
454    pub(crate) fn keep(
455        &mut self,
456        value: i128,
457        slope: i128,
458        min: i128,
459        max: Option<i128>,
460    ) -> Result<(), Error> {
461        let below_min = value < min;
462        let above_max = max.is_some_and(|max| value > max);
463        if slope == 0 {
464            if below_min || above_max {
465                self.hi = self.lo - 1;
466            }
467
468            return Ok(());
469        }
470
471        let room_min = min.checked_sub(value).ok_or(Error::Overflow)?;
472        let room_max = max
473            .map(|max| max.checked_sub(value).ok_or(Error::Overflow))
474            .transpose()?;
475        if slope > 0 {
476            self.lo = self.lo.max(ceil_div(room_min, slope));
477            if let Some(room) = room_max {
478                self.hi = self.hi.min(floor_div(room, slope));
479            }
480        } else {
481            self.hi = self.hi.min(floor_div(room_min, slope));
482            if let Some(room) = room_max {
483                self.lo = self.lo.max(ceil_div(room, slope));
484            }
485        }
486
487        Ok(())
488    }
489}
490
491/// `a / b` rounded towards negative infinity. `b` must not be zero.
492const fn floor_div(a: i128, b: i128) -> i128 {
493    let quotient = a / b;
494    if a % b != 0 && ((a < 0) != (b < 0)) {
495        quotient - 1
496    } else {
497        quotient
498    }
499}
500
501/// `a / b` rounded towards positive infinity. `b` must not be zero.
502const fn ceil_div(a: i128, b: i128) -> i128 {
503    let quotient = a / b;
504    if a % b != 0 && ((a < 0) == (b < 0)) {
505        quotient + 1
506    } else {
507        quotient
508    }
509}
510
511/// `window` without the starts at which a demand would precede its timeline's start, or
512/// `None` if no start is left.
513fn admissible_window<P: PlanStorage>(
514    plan: &Plan<P>,
515    demands: &[Demand],
516    window: Window,
517) -> Option<Window> {
518    let mut earliest = i128::from(window.earliest());
519    for demand in demands {
520        let timeline_start = match *demand {
521            Demand::Level { timeline, .. } => plan.timelines[timeline.0].start(),
522            Demand::State { timeline, .. } => plan.states[timeline.0].start(),
523        };
524        let first_offset = demand.offsets()[0];
525        earliest = earliest.max(i128::from(timeline_start) - i128::from(first_offset));
526    }
527
528    Window::new(Tick::try_from(earliest).ok()?, window.latest()).ok()
529}
530
531/// Whether a demand or a touched numeric timeline has a rate.
532fn involves_rates<P: PlanStorage>(plan: &Plan<P>, demands: &[Demand]) -> bool {
533    demands.iter().any(|demand| match *demand {
534        Demand::Level { timeline, impact } => {
535            impact.is_rate() || plan.timelines[timeline.0].has_rates()
536        }
537        Demand::State { .. } => false,
538    })
539}
540
541/// The smallest start in `window` after `after` where a demand tick meets a change tick of
542/// its timeline, or the tick after one, so that the comparison of the two changes.
543///
544/// Enumerating candidates one at a time this way needs no memory. For a demand offset `o` the
545/// next meeting start is `p - o` for the first change tick `p >= after + o + 1`, and the next
546/// passing start `p - o + 1` for the first `p >= after + o`; sorted change ticks make each a
547/// binary search, so a call costs `O(k log n)` for `k` demands (plus the unsorted requirements
548/// of touched state timelines).
549fn next_candidate<P: PlanStorage>(
550    plan: &Plan<P>,
551    demands: &[Demand],
552    after: Tick,
553    window: Window,
554) -> Option<Tick> {
555    let mut next: Option<i128> = None;
556    for demand in demands {
557        for offset in demand.offsets() {
558            let threshold = i128::from(after) + i128::from(offset);
559            let first_from = |x: i128| match *demand {
560                Demand::Level { timeline, .. } => plan.timelines[timeline.0].first_change_from(x),
561                Demand::State { timeline, .. } => plan.states[timeline.0].first_change_from(x),
562            };
563            let meet = first_from(threshold + 1).map(|p| i128::from(p) - i128::from(offset));
564            let pass = first_from(threshold).map(|p| i128::from(p) - i128::from(offset) + 1);
565            for start in [meet, pass].into_iter().flatten() {
566                if next.is_none_or(|next| start < next) {
567                    next = Some(start);
568                }
569            }
570        }
571    }
572
573    let next = Tick::try_from(next?).ok()?;
574    window.contains(next).then_some(next)
575}
576
577#[cfg(test)]
578mod tests {
579    //! Brute-force checks of the closed-form helpers.
580
581    use super::{Offsets, ceil_div, floor_div};
582
583    /// Rounding division agrees with exact rational comparison for all small operands.
584    #[test]
585    fn rounding_division() {
586        for a in -20_i128..=20 {
587            for b in (-6_i128..=6).filter(|&b| b != 0) {
588                let floor = floor_div(a, b);
589                let ceil = ceil_div(a, b);
590                // floor * b <= a < (floor + 1) * b for b > 0, mirrored for b < 0.
591                if b > 0 {
592                    assert!(floor * b <= a && a < (floor + 1) * b, "floor {a}/{b}");
593                    assert!((ceil - 1) * b < a && a <= ceil * b, "ceil {a}/{b}");
594                } else {
595                    assert!(floor * b >= a && a > (floor + 1) * b, "floor {a}/{b}");
596                    assert!((ceil - 1) * b > a && a >= ceil * b, "ceil {a}/{b}");
597                }
598            }
599        }
600    }
601
602    /// `keep` leaves exactly the offsets whose affine value lies in the range.
603    #[test]
604    fn keep_matches_enumeration() {
605        for value in -8_i128..=8 {
606            for slope in -3_i128..=3 {
607                for max in [None, Some(2_i128), Some(5)] {
608                    let mut offsets = Offsets { lo: 0, hi: 6 };
609                    offsets.keep(value, slope, -1, max).expect("small");
610                    let expected = (0..=6).filter(|k| {
611                        let level = value + slope * k;
612                        level >= -1 && max.is_none_or(|max| level <= max)
613                    });
614                    assert!(
615                        (offsets.lo..=offsets.hi).eq(expected),
616                        "value {value} slope {slope} max {max:?}"
617                    );
618                }
619            }
620        }
621    }
622}