resource-timeline 0.1.0

Resource timelines for onboard scheduling: energy, memory, thermal and communication budgets with explained violations, envelopes and allocation-free storage
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! The sweep that finds the first bound violation of a timeline.
//!
//! The sweep walks the sorted change points once, as a sequence of linear [`Segment`]s.
//! Within a segment the first out-of-bounds tick is either its first tick or the tick at which
//! the line crosses a bound, which integer division finds directly; end-state targets inside
//! the segment are evaluated on the line.
//!
//! ```mermaid
//! graph LR
//!     points["change points: profile merged with candidates"] --> groups["net changes per tick"]
//!     groups --> scan["segment by segment: level at the point, crossing inside"]
//!     scan --> explain["net impacts per activity at the violating tick"]
//! ```

use super::Bounds;
use super::profile::Point;
use crate::plan::Offsets;
use crate::storage::{Seq, Storage};
use crate::{ActivityId, Bound, Container, Error, Impact, Level, Target, Tick, Violation};

/// The first out-of-bounds tick of a timeline, before it is explained.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Breach {
    /// The earliest tick at which the level is out of bounds.
    pub(crate) at: Tick,
    /// The level at that tick.
    pub(crate) level: i128,
    /// The broken bound.
    pub(crate) bound: Bound,
}

/// The fixed parameters of a sweep: where it starts, from which level, against which bounds.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Frame<'a> {
    /// The first tick of the timeline.
    pub(crate) start: Tick,
    /// The level at `start` before changes at `start` apply.
    pub(crate) initial: Level,
    /// The range the level must stay in.
    pub(crate) bounds: Bounds,
    /// The end-state targets, sorted by [`Target::key`], none before `start`.
    pub(crate) targets: &'a [Target],
}

/// One linear piece of the level: from a change point up to the next one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Segment {
    /// The first tick of the piece. All changes at this tick are applied.
    pub(crate) at: Tick,
    /// The level at `at`.
    pub(crate) level: i128,
    /// The level change per tick after `at`, until `next`.
    pub(crate) slope: i128,
    /// The tick of the next change point, or `None` for the last piece, which lasts forever
    /// with slope zero (every rate ends).
    pub(crate) next: Option<Tick>,
}

impl Segment {
    /// The level at `t`, which must lie in the piece.
    ///
    /// # Errors
    ///
    /// [`Error::Overflow`] if the level exceeds `i128`.
    pub(crate) fn level_at(&self, t: Tick) -> Result<i128, Error> {
        if self.slope == 0 {
            return Ok(self.level);
        }

        let elapsed = i128::from(t) - i128::from(self.at);
        self.slope
            .checked_mul(elapsed)
            .and_then(|change| self.level.checked_add(change))
            .ok_or(Error::Overflow)
    }

    /// The first tick strictly inside the piece at which the line crosses a bound.
    ///
    /// The level at `at` is in bounds. The line is checked up to the tick before `next`; the
    /// level at `next` includes the changes there and belongs to the next piece.
    fn crossing(&self, bounds: Bounds) -> Result<Option<Breach>, Error> {
        if self.slope == 0 {
            return Ok(None);
        }

        let Some(next) = self.next else {
            debug_assert_eq!(self.slope, 0, "the last piece has a slope");
            return Ok(None);
        };

        let last = i128::from(next) - 1 - i128::from(self.at);
        if self.slope == 0 || last < 1 {
            return Ok(None);
        }

        let (room, bound) = if self.slope < 0 {
            (
                self.level - i128::from(bounds.min),
                Bound::BelowMin(bounds.min),
            )
        } else {
            (
                i128::from(bounds.max) - self.level,
                Bound::AboveMax(bounds.max),
            )
        };

        // The first k with room - |slope| * k < 0, that is k = room / |slope| + 1.
        let steps = room / self.slope.abs() + 1;
        if steps > last {
            return Ok(None);
        }

        let at = Tick::try_from(i128::from(self.at) + steps).map_err(|_| Error::Overflow)?;
        let level = self.level + self.slope * steps;
        Ok(Some(Breach { at, level, bound }))
    }

    /// The first missed target in the piece, consuming the targets before `next` from the
    /// front of `targets`.
    fn missed_target(&self, targets: &mut &[Target]) -> Result<Option<Breach>, Error> {
        if targets
            .first()
            .is_none_or(|first| self.next.is_some_and(|next| first.at >= next))
        {
            return Ok(None);
        }

        let inside = targets
            .iter()
            .take_while(|target| self.next.is_none_or(|next| target.at < next))
            .count();
        let (now, rest) = targets.split_at(inside);
        *targets = rest;

        for target in now {
            let level = self.level_at(target.at)?;
            if level < i128::from(target.min) {
                return Ok(Some(Breach {
                    at: target.at,
                    level,
                    bound: Bound::BelowTarget(target.min),
                }));
            }
        }

        Ok(None)
    }
}

/// The pieces of the level built from a frame and two sorted point slices, in time order.
///
/// The first piece starts at the frame start with the changes there applied.
pub(crate) struct Segments<'a> {
    /// The merged change points not yet reached.
    groups: core::iter::Peekable<Grouped<'a>>,
    /// The piece to yield next, `None` once the last piece was yielded.
    current: Option<Segment>,
}

impl<'a> Segments<'a> {
    /// The pieces of the level that starts at `frame` and changes at `base` and `extra`.
    ///
    /// Both slices must be sorted by tick and must not contain ticks before `frame.start`.
    /// The level at the start cannot overflow: a point's step is below `2^124` in magnitude
    /// (see the profile module), and the initial level is an `i64`.
    pub(crate) fn new(frame: &Frame<'_>, base: &'a [Point], extra: &'a [Point]) -> Self {
        let mut groups = Grouped { base, extra }.peekable();
        let mut first = Segment {
            at: frame.start,
            level: i128::from(frame.initial),
            slope: 0,
            next: None,
        };
        if let Some(point) = groups.next_if(|point| point.at == frame.start) {
            first.level += point.step;
            first.slope = point.slope;
        }

        first.next = groups.peek().map(|point| point.at);
        Self {
            groups,
            current: Some(first),
        }
    }

    /// The piece after `segment`, which starts at the next change point.
    fn successor(&mut self, segment: &Segment) -> Result<Option<Segment>, Error> {
        let Some(point) = self.groups.next() else {
            return Ok(None);
        };

        let level = segment
            .level_at(point.at)?
            .checked_add(point.step)
            .ok_or(Error::Overflow)?;
        let slope = segment
            .slope
            .checked_add(point.slope)
            .ok_or(Error::Overflow)?;
        Ok(Some(Segment {
            at: point.at,
            level,
            slope,
            next: self.groups.peek().map(|point| point.at),
        }))
    }
}

impl Iterator for Segments<'_> {
    type Item = Result<Segment, Error>;

    fn next(&mut self) -> Option<Self::Item> {
        let segment = self.current.take()?;
        match self.successor(&segment) {
            Ok(next) => self.current = next,
            Err(error) => return Some(Err(error)),
        }

        Some(Ok(segment))
    }
}

/// Finds the first tick at which the level built from `base` and `extra` leaves
/// `frame.bounds` or misses a target.
///
/// Both slices must be sorted by tick and must not contain ticks before `frame.start`. `base`
/// is the timeline profile, `extra` holds the points of tentatively added impacts; points of
/// both at the same tick are netted. At the same tick a broken bound is reported before a
/// missed target.
///
/// # Errors
///
/// [`Error::Overflow`] if a level along a rate segment exceeds `i128`.
pub(crate) fn first_breach(
    frame: &Frame<'_>,
    base: &[Point],
    extra: &[Point],
) -> Result<Option<Breach>, Error> {
    // A hand-rolled walk instead of `Segments`: this is the hot path of every check and search,
    // and consuming each point as it comes avoids the look-ahead the iterator needs.
    let mut targets = frame.targets;
    let mut groups = Grouped { base, extra }.peekable();
    let mut segment = Segment {
        at: frame.start,
        level: i128::from(frame.initial),
        slope: 0,
        next: None,
    };
    if let Some(point) = groups.next_if(|point| point.at == frame.start) {
        segment.level += point.step;
        segment.slope = point.slope;
    }

    for point in groups {
        segment.next = Some(point.at);
        let flat_and_inside = segment.slope == 0
            && targets.is_empty()
            && broken_bound(frame.bounds, segment.level).is_none();
        if !flat_and_inside {
            if let Some(breach) = segment.first_breach(frame.bounds, &mut targets)? {
                return Ok(Some(breach));
            }
        }

        segment.level = segment
            .level_at(point.at)?
            .checked_add(point.step)
            .ok_or(Error::Overflow)?;
        segment.slope = segment
            .slope
            .checked_add(point.slope)
            .ok_or(Error::Overflow)?;
        segment.at = point.at;
    }

    segment.next = None;
    segment.first_breach(frame.bounds, &mut targets)
}

impl Segment {
    /// The first breach in this piece: at its first tick, on the line, or at a target.
    ///
    /// At the same tick a broken bound wins over a missed target.
    fn first_breach(
        &self,
        bounds: Bounds,
        targets: &mut &[Target],
    ) -> Result<Option<Breach>, Error> {
        if let Some(bound) = broken_bound(bounds, self.level) {
            return Ok(Some(Breach {
                at: self.at,
                level: self.level,
                bound,
            }));
        }

        let crossing = self.crossing(bounds)?;
        let target = self.missed_target(targets)?;
        Ok(match (crossing, target) {
            (Some(crossing), Some(target)) if target.at < crossing.at => Some(target),
            (Some(crossing), _) => Some(crossing),
            (None, target) => target,
        })
    }
}

/// Narrows `offsets` to the start offsets at which the level built from `base` and the
/// tentative points stays valid, from the lines at offset 0 (`tentative[0]`) and 1
/// (`tentative[1]`).
///
/// Each evaluated level (segment start, tick before the segment end, target) is affine in the
/// offset; its value and coefficient are read off the two lines.
///
/// # Errors
///
/// [`Error::Overflow`] if a level exceeds `i128`.
pub(crate) fn narrow(
    frame: &Frame<'_>,
    base: &[Point],
    tentative: [&[Point]; 2],
    offsets: &mut Offsets,
) -> Result<(), Error> {
    let (min, max) = (i128::from(frame.bounds.min), i128::from(frame.bounds.max));
    let mut targets = frame.targets;
    let first = Segments::new(frame, base, tentative[0]);
    let second = Segments::new(frame, base, tentative[1]);
    for (a, b) in first.zip(second) {
        let (a, b) = (a?, b?);
        debug_assert_eq!(
            a.next.is_some(),
            b.next.is_some(),
            "segment structures differ"
        );
        offsets.keep(a.level, b.level - a.level, min, Some(max))?;
        if let (Some(end_a), Some(end_b)) = (a.next, b.next) {
            let (last_a, last_b) = (a.level_at(end_a - 1)?, b.level_at(end_b - 1)?);
            offsets.keep(last_a, last_b - last_a, min, Some(max))?;
        }

        let inside = targets
            .iter()
            .take_while(|target| a.next.is_none_or(|next| target.at < next))
            .count();
        let (now, rest) = targets.split_at(inside);
        targets = rest;
        for target in now {
            let (at_a, at_b) = (a.level_at(target.at)?, b.level_at(target.at)?);
            offsets.keep(at_a, at_b - at_a, i128::from(target.min), None)?;
        }

        if offsets.is_empty() {
            return Ok(());
        }
    }

    Ok(())
}

/// Merges two sorted point slices into one sorted sequence with one point per tick.
struct Grouped<'a> {
    /// Remaining points of the first input.
    base: &'a [Point],
    /// Remaining points of the second input.
    extra: &'a [Point],
}

impl Iterator for Grouped<'_> {
    type Item = Point;

    fn next(&mut self) -> Option<Point> {
        let at = match (self.base.first(), self.extra.first()) {
            (Some(a), Some(b)) => a.at.min(b.at),
            (Some(a), None) => a.at,
            (None, Some(b)) => b.at,
            (None, None) => return None,
        };

        let mut net = Point::loose(at, 0, 0);
        take_tick(&mut self.base, &mut net);
        take_tick(&mut self.extra, &mut net);
        Some(net)
    }
}

/// Moves all leading points of `points` at `net.at` into `net`.
fn take_tick(points: &mut &[Point], net: &mut Point) {
    while let Some((point, rest)) = points.split_first() {
        if point.at != net.at {
            break;
        }

        net.step += point.step;
        net.slope += point.slope;
        *points = rest;
    }
}

/// The bound that `level` breaks, if any.
fn broken_bound(bounds: Bounds, level: i128) -> Option<Bound> {
    if level < i128::from(bounds.min) {
        Some(Bound::BelowMin(bounds.min))
    } else if level > i128::from(bounds.max) {
        Some(Bound::AboveMax(bounds.max))
    } else {
        None
    }
}

/// Explains `breach` with the activities in `impacts` that push towards the broken bound.
///
/// # Errors
///
/// - [`Error::Overflow`] if the level does not fit a [`Level`], or a contribution overflows.
/// - [`Error::OutOfMemory`] or [`Error::CapacityExceeded`] if the working memory cannot be
///   allocated.
pub(crate) fn explain<S: Storage>(
    impacts: &[(ActivityId, Impact)],
    breach: Breach,
) -> Result<Violation<S>, Error> {
    let level = Level::try_from(breach.level).map_err(|_| Error::Overflow)?;
    let contributors = contributors::<S>(impacts, breach.at, breach.bound)?;

    Ok(Violation {
        at: breach.at,
        level,
        bound: breach.bound,
        contributors,
    })
}

/// The activities whose net effect in force at tick `at` pushes towards `bound`.
///
/// Sorted ascending, without duplicates. `impacts` must fit an `S` impact list, which the
/// impacts of a timeline with storage `S` do.
///
/// # Errors
///
/// - [`Error::Overflow`] if a contribution overflows.
/// - [`Error::OutOfMemory`] or [`Error::CapacityExceeded`] if the working memory cannot be
///   allocated.
pub(crate) fn contributors<S: Storage>(
    impacts: &[(ActivityId, Impact)],
    at: Tick,
    bound: Bound,
) -> Result<S::List<ActivityId>, Error> {
    let net = net_per_activity::<S>(impacts, at)?;

    let mut activities = <S::List<ActivityId> as Seq<_>>::EMPTY;
    activities.try_reserve(net.len(), Container::Contributors)?;
    for &(activity, effect) in net.iter() {
        if bound.is_pushed_by(effect) {
            activities.try_push(activity, Container::Contributors)?;
        }
    }

    Ok(activities)
}

/// The summed effect of each activity's impacts in force at tick `at`, sorted by activity.
fn net_per_activity<S: Storage>(
    impacts: &[(ActivityId, Impact)],
    at: Tick,
) -> Result<S::List<(ActivityId, i128)>, Error> {
    let mut effects = <S::List<(ActivityId, i128)> as Seq<_>>::EMPTY;
    effects.try_reserve(impacts.len(), Container::Scratch)?;
    for &(activity, impact) in impacts {
        let effect = impact.contribution_at(at).ok_or(Error::Overflow)?;
        effects.try_push((activity, effect), Container::Scratch)?;
    }

    effects.sort_unstable_by_key(|&(activity, _)| activity);
    merge_adjacent(&mut effects)?;
    Ok(effects)
}

/// Sums the effects of adjacent entries with the same activity, in place.
fn merge_adjacent(effects: &mut impl Seq<(ActivityId, i128)>) -> Result<(), Error> {
    let mut merged: usize = 0;
    for read in 0..effects.len() {
        let (activity, effect) = effects[read];
        match merged.checked_sub(1).map(|last| &mut effects[last]) {
            Some((last, sum)) if *last == activity => {
                *sum = sum.checked_add(effect).ok_or(Error::Overflow)?;
            }
            _ => {
                effects[merged] = (activity, effect);
                merged += 1;
            }
        }
    }

    effects.truncate(merged);
    Ok(())
}