temporal-control 0.1.0

Simple temporal networks with uncertainty: dynamic controllability checking, dispatchable networks and a no_std, no-alloc onboard dispatcher
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//! Dynamic controllability in `O(n^3)` by Morris's backpropagation (Morris 2014).
//!
//! # Graph
//!
//! The labelled distance graph has one ordinary edge per requirement bound, and per contingent
//! link `(A, l, u, C)` the lower-case edge `A -> C: c:l` and the upper-case edge `C -> A: C:-u`.
//! The link's ordinary edges `A -> C: u` and `C -> A: -l`, which Morris (CPAIOR 2014, section
//! 3) also lists, are left out, as in the graph of Cairo, Hunsberger and Rizzi (2018, section
//! 2.2) and Hunsberger and Posenato (2023, section 2), and as in CSTNU-Tool's `Morris2014`
//! ("Morris considers only the labeled value for contingent links"). Each labelled edge is at
//! least as tight as the ordinary edge it shadows (`l <= u`, `-u <= -l`); the brute-force
//! oracle tests confirm that leaving the ordinary ones out changes no verdict.
//!
//! **Normal form and separated activation nodes.** Backpropagation from a node needs its
//! negative incoming edges to be either all ordinary or a single upper-case edge, so that one
//! propagation with one label is exact (see *Unsuitable edges*). Morris (CPAIOR 2014) gets
//! there in two steps: the normal form (section 3: `A => C` in `[x, y]` becomes
//! `A -> A' [x, x]` and `A' => C` in `[0, y - x]`), and a modification before Fig. 1 that
//! gives every link an activation node of its own, apart from other links' activation and
//! contingent points and from the targets of ordinary negative edges (an extra `[0, 0]` link).
//! Both steps are done at once here, as in CSTNU-Tool's `STNU::applyNormalForm`: each link `i`
//! gets its own activation node `A'_i = A_i + l_i`, tied to `A_i` by the ordinary edges
//! `A_i -> A'_i: l_i` and `A'_i -> A_i: -l_i`, and the link becomes `A'_i => C_i` in
//! `[0, u_i - l_i]`. All other edges stay on `A_i`. Afterwards `A'_i` has exactly one negative
//! incoming edge (the upper-case one; the tie into it weighs `l_i > 0`), and every other node
//! has only ordinary negative incoming edges, because derived edges are never negative. Under
//! instantaneous reaction the result is DC iff the original is: `A'_i` executes `l_i` ticks
//! after `A_i`, also when `A_i` is contingent. With `l_i = u_i` (which Morris excludes) the
//! upper-case edge weighs `0` and is treated as ordinary, which is the normal-form label
//! removal rule (`B:x` with `x >= 0` becomes `x`).
//!
//! # Algorithm
//!
//! This is `DCbackprop` of Morris (CPAIOR 2014, Fig. 1). A *negative node* has a negative
//! incoming edge. `backprop(s)` runs Dijkstra backwards from `s`, seeded with its negative
//! incoming edges and extending only through non-negative edges. Fig. 1 seeds every incoming
//! edge by assignment (lines 08-11); here only the negative ones are seeded, keeping the
//! smallest weight per tail. A non-negative seed would only re-add its own edge, and with
//! parallel edges an assignment could replace a negative seed by a larger one. When a node
//! `u` is settled at distance `d`:
//!
//! - `d >= 0`: the path `u ~> s` reduces to a new ordinary edge `u -> s` of weight `d` (by the
//!   no-case and lower-case rules, or for an upper-case seed by the upper-case, cross-case and
//!   label-removal rules, since `d >= 0 > -l`). It is recorded and not extended.
//! - `d < 0` and `u` is a negative node: `backprop(u)` runs first, so that the edges bypassing
//!   `u`'s negative edges exist before the search extends through `u`.
//! - meeting a node whose `backprop` is still on the call stack closes a cycle of negative
//!   reducible paths: a semi-reducible negative cycle, so the network is not DC.
//!
//! **Unsuitable edges.** In a propagation seeded with the upper-case edge of link `c`, the
//! lower-case edge of `c` is skipped: the cross-case rule needs distinct labels, because the
//! same link cannot take its minimum and its maximum duration. Thanks to the normal form the
//! label is a property of the source (one upper-case seed, or none), so the test is exact with
//! one distance per node. It is the same test as CSTNU-Tool's: a lower-case edge is unsuitable
//! iff it leaves the source.
//!
//! The network is DC iff every negative node's `backprop` completes.
//!
//! # Cost
//!
//! Let `n' = n + k` (at most `2n`) be the node count in normal form and `m` the number
//! of requirement bounds.
//!
//! 1. Each node runs at most one propagation: a finished `backprop` returns at once, and an
//!    active one ends the check.
//! 2. A propagation settles each node at most once. Extract-min is a linear scan, `O(n')` per
//!    settled node, so `O(n'^2)` per propagation, without a log factor.
//! 3. Each propagation of source `s` adds at most one derived edge per settled node, all into
//!    `s`, so at most `n'^2` derived edges exist in total, and at most `n'` into any node.
//! 4. A settled node `u` with `d < 0` scans `u`'s incoming edges once. Derived edges into `u`
//!    are only added by `backprop(u)` itself, which has finished before the scan, so every
//!    list is scanned at its final length at most once per propagation: `O(m + n'^2)`.
//!
//! So each propagation costs `O(m + n'^2)` and the check `O(n' (m + n'^2)) = O(n m + n^3)`,
//! which is Morris's `O(n^3)` whenever `m = O(n^2)`, i.e. without many parallel constraints
//! on the same pair. Morris's own count (section 4: at most `N` non-trivial calls of `O(N^2)`
//! each with a Fibonacci heap, at most `O(N^2)` added edges) presumes the same: a Dijkstra
//! call costs `O(E + N log N)`, which is `O(N^2)` only if `E = O(N^2)`. The linear scan gives
//! the same `O(N^2)` per call without a heap. Memory: the derived edges and the finished shortest-path trees kept for
//! explanations take `O(m + n'^2)`, the up to `n'` nested searches `O(n'^2)`.
//!
//! # Explanation
//!
//! The cycle consists of one negative path per nested call, from the node that interrupted it
//! to its source. It is collected while the calls unwind, as in the conflict extraction of
//! Bhargava, Vaquero and Williams (IJCAI 2017, Algorithms 1 and 2), then put into compact form
//! instead of their full expansion of derived ("novel") edges: every
//! derived edge on it becomes a [`DerivedEdge`] listed once, whose steps come from the stored
//! shortest-path tree of the propagation that created it, recursively. Normal-form edges are
//! mapped back: `A'_i` is `A_i`, the two tie edges are dropped, and the labelled edges get
//! their original weights `l_i` and `-u_i`. A cycle's total is unchanged, because a cycle
//! enters `A'_i` by the tie (`+l_i`) or the upper-case edge (`l_i - u_i`) and leaves it by the
//! tie (`-l_i`) or the lower-case edge (`0`); each of the four combinations weighs the same
//! before and after the mapping. A derived edge's weight is the sum over its mapped path.
//!
//! There are at most `n'^2` derived edges, each a path of at most `n'` steps, so building the
//! compact form costs `O(n'^3)` steps; expanding it ([`SemiReducibleCycle::edges`]) can yield
//! `3 * 2^k - 2` edges (Hunsberger's magic loops).

use alloc::collections::BTreeMap;
use alloc::vec;
use alloc::vec::Vec;

use super::{
    ContingentId, Controllability, CycleStep, DerivedEdge, LabelledEdge, SemiReducibleCycle, Stnu,
};
use crate::budget::Meter;
use crate::stn::{Bound, ConstraintId, CycleEdge, steps};
use crate::{Budget, Error, Ticks, TimePoint};

/// Where an edge of the normal-form graph comes from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Origin {
    /// An edge of the labelled distance graph; in normal form, so labelled edges of link `i`
    /// attach to its own activation node and weigh `0` and `l_i - u_i`.
    Original(LabelledEdge),
    /// One of the two normal-form tie edges `A_i -> A'_i: l_i` and `A'_i -> A_i: -l_i`.
    Tie,
    /// A non-negative bypass edge `u -> s` found by `backprop(s)`; expands through `s`'s tree.
    Derived,
}

/// An edge `from -> owner`, stored in the owner's incoming list.
#[derive(Debug, Clone, Copy)]
struct InEdge {
    /// Tail of the edge.
    from: usize,
    /// Edge weight.
    weight: Ticks,
    /// What supplied the edge.
    origin: Origin,
}

/// A reference to an edge: `(head, index into the head's incoming list)`.
///
/// Stable because incoming lists only grow at the end.
type EdgeRef = (usize, usize);

/// Progress of `backprop` for one node.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Status {
    /// Never started.
    Unvisited,
    /// On the current call stack.
    Active,
    /// Finished without finding a cycle.
    Done,
}

/// A semi-reducible negative cycle being collected while `backprop` calls unwind.
struct Trace {
    /// The node whose re-entry closed the cycle; collection stops at its own frame.
    closes_at: usize,
    /// Edges in traversal order, starting at `closes_at`.
    edges: Vec<EdgeRef>,
    /// Whether the frame of `closes_at` has added its path.
    complete: bool,
}

/// Graph and bookkeeping for one check.
struct Graph<'m> {
    /// Incoming edges per node; grows as derived edges are added.
    incoming: Vec<Vec<InEdge>>,
    /// Whether each node has a negative incoming edge. Fixed: derived edges are non-negative.
    negative: Vec<bool>,
    /// `backprop` progress per node.
    status: Vec<Status>,
    /// Shortest-path tree of each finished propagation: `trees[s][u]` is the first edge of the
    /// path `u ~> s`. Empty until `backprop(s)` finishes.
    trees: Vec<Vec<Option<EdgeRef>>>,
    /// Step meter shared by all propagations.
    meter: &'m mut Meter,
}

/// State of one backward Dijkstra.
struct Search {
    /// The node propagated from.
    source: usize,
    /// Link of the source's upper-case seed edge, if it is one; its lower-case edge is
    /// unsuitable.
    label: Option<usize>,
    /// Tentative distance `u ~> source`; `None` is `+infinity`.
    dist: Vec<Option<Ticks>>,
    /// Whether each node is settled.
    settled: Vec<bool>,
    /// First edge of the best path found so far from each node.
    pred: Vec<Option<EdgeRef>>,
}

/// Checks dynamic controllability with Morris's `O(n^3)` backpropagation.
///
/// # Errors
///
/// See [`Stnu::check_controllability`].
pub(super) fn run(stnu: &Stnu, budget: &Budget) -> Result<Controllability<()>, Error> {
    let mut meter = budget.meter();
    let mut g = Graph::new(stnu, budget, &mut meter)?;

    for s in 0..g.incoming.len() {
        if !g.negative[s] {
            continue;
        }

        if let Some(trace) = g.backprop(s)? {
            return g.explain(stnu, &trace).map(Controllability::Uncontrollable);
        }
    }

    Ok(Controllability::Controllable(()))
}

/// The explanation for a network another checker found not DC.
///
/// # Errors
///
/// [`Error::Internal`] if this checker finds the network DC; otherwise as for [`run`].
pub(super) fn explain(stnu: &Stnu, budget: &Budget) -> Result<SemiReducibleCycle, Error> {
    match run(stnu, budget)? {
        Controllability::Uncontrollable(cycle) => Ok(cycle),
        Controllability::Controllable(()) => Err(Error::Internal),
    }
}

impl<'m> Graph<'m> {
    /// Builds the labelled distance graph of `stnu` in normal form.
    ///
    /// # Errors
    ///
    /// [`Error::MemoryBudgetExceeded`] if `n'^2` cells exceed the budget (the worst case of
    /// derived edges and trees), [`Error::BudgetExhausted`] or [`Error::Overflow`].
    fn new(stnu: &Stnu, budget: &Budget, meter: &'m mut Meter) -> Result<Self, Error> {
        let n = stnu.time_point_count();
        let nodes = n.checked_add(stnu.links.len()).ok_or(Error::Overflow)?;
        budget.check_cells(
            nodes
                .checked_mul(nodes)
                .ok_or(Error::MemoryBudgetExceeded)?,
        )?;

        let mut incoming = vec![Vec::new(); nodes];
        let mut add = |from: usize, to: usize, weight: Ticks, origin: Origin| {
            incoming[to].push(InEdge {
                from,
                weight,
                origin,
            });
        };

        for (i, c) in stnu.requirements.constraints().iter().enumerate() {
            let id = ConstraintId(i);

            if let Some(hi) = c.hi {
                let edge = LabelledEdge::Requirement(CycleEdge::new(id, Bound::Upper));
                add(c.from.0, c.to.0, hi, Origin::Original(edge));
            }

            if let Some(lo) = c.lo {
                let edge = LabelledEdge::Requirement(CycleEdge::new(id, Bound::Lower));
                let w = lo.checked_neg().ok_or(Error::Overflow)?;
                add(c.to.0, c.from.0, w, Origin::Original(edge));
            }
        }

        for (i, link) in stnu.links.iter().enumerate() {
            let (a, own, x) = (link.activation.0, n + i, link.contingent.0);
            // Normal form: `own = A + l` rigidly, and the link `own => C` lasts `[0, u - l]`.
            let neg_lo = link.lo.checked_neg().ok_or(Error::Overflow)?;
            let span = link.hi.checked_sub(link.lo).ok_or(Error::Overflow)?;
            add(a, own, link.lo, Origin::Tie);
            add(own, a, neg_lo, Origin::Tie);
            let lower = LabelledEdge::LowerCase(ContingentId(i));
            add(own, x, Ticks::ZERO, Origin::Original(lower));
            let upper = LabelledEdge::UpperCase(ContingentId(i));
            let neg_span = span.checked_neg().ok_or(Error::Overflow)?;
            add(x, own, neg_span, Origin::Original(upper));
        }

        meter.spend(steps(nodes)?)?;
        let negative = incoming
            .iter()
            .map(|edges| edges.iter().any(|e| e.weight < Ticks::ZERO))
            .collect();

        Ok(Self {
            incoming,
            negative,
            status: vec![Status::Unvisited; nodes],
            trees: vec![Vec::new(); nodes],
            meter,
        })
    }

    /// Runs `backprop(source)`; returns the partial or complete cycle if one was found.
    ///
    /// # Errors
    ///
    /// [`Error::BudgetExhausted`], [`Error::Overflow`] or [`Error::Internal`].
    fn backprop(&mut self, source: usize) -> Result<Option<Trace>, Error> {
        match self.status[source] {
            Status::Active => {
                return Ok(Some(Trace {
                    closes_at: source,
                    edges: Vec::new(),
                    complete: false,
                }));
            }
            Status::Done => return Ok(None),
            Status::Unvisited => {}
        }

        self.status[source] = Status::Active;
        let mut search = self.seed(source)?;

        while let Some((u, d)) = search.pop(self.meter)? {
            if d >= Ticks::ZERO {
                self.add_derived(u, source, d);
                continue;
            }

            if self.negative[u] {
                if let Some(trace) = self.backprop(u)? {
                    return search.extend_trace(trace, u).map(Some);
                }
            }

            self.extend(&mut search, u, d)?;
        }

        self.status[source] = Status::Done;
        self.trees[source] = search.pred;
        Ok(None)
    }

    /// Starts a search from `source` with its negative incoming edges.
    ///
    /// # Errors
    ///
    /// [`Error::Internal`] if the normal-form invariant (all ordinary, or one upper-case
    /// edge) does not hold.
    fn seed(&self, source: usize) -> Result<Search, Error> {
        let nodes = self.incoming.len();
        let mut search = Search {
            source,
            label: None,
            dist: vec![None; nodes],
            settled: vec![false; nodes],
            pred: vec![None; nodes],
        };
        let mut ordinary = false;

        for (i, e) in self.incoming[source].iter().enumerate() {
            if e.weight >= Ticks::ZERO {
                continue;
            }

            if ordinary || search.label.is_some() {
                // Mixed or repeated upper-case seeds would make one label inexact.
                let upper = matches!(e.origin, Origin::Original(LabelledEdge::UpperCase(_)));

                if upper || search.label.is_some() {
                    return Err(Error::Internal);
                }
            }

            match e.origin {
                Origin::Original(LabelledEdge::UpperCase(c)) => search.label = Some(c.0),
                _ => ordinary = true,
            }

            search.relax(e.from, e.weight, (source, i));
        }

        Ok(search)
    }

    /// Relaxes every suitable non-negative edge into `u`, which is settled at `d < 0`.
    ///
    /// # Errors
    ///
    /// [`Error::BudgetExhausted`] or [`Error::Overflow`].
    fn extend(&mut self, search: &mut Search, u: usize, d: Ticks) -> Result<(), Error> {
        self.meter.spend(steps(self.incoming[u].len())?)?;

        for (i, e) in self.incoming[u].iter().enumerate() {
            let unsuitable = matches!(
                (e.origin, search.label),
                (Origin::Original(LabelledEdge::LowerCase(c)), Some(l)) if c.0 == l
            );

            if e.weight < Ticks::ZERO || unsuitable {
                continue;
            }

            let candidate = d.checked_add(e.weight).ok_or(Error::Overflow)?;
            search.relax(e.from, candidate, (u, i));
        }

        Ok(())
    }

    /// Records the derived ordinary edge `from -> to` with non-negative `weight`.
    fn add_derived(&mut self, from: usize, to: usize, weight: Ticks) {
        if from != to {
            self.incoming[to].push(InEdge {
                from,
                weight,
                origin: Origin::Derived,
            });
        }
    }

    /// Turns a complete trace into a compact cycle and checks that it is negative.
    ///
    /// # Errors
    ///
    /// [`Error::BudgetExhausted`], [`Error::Overflow`], or [`Error::Internal`] if the trace
    /// is incomplete, empty or not negative.
    fn explain(&mut self, stnu: &Stnu, trace: &Trace) -> Result<SemiReducibleCycle, Error> {
        if !trace.complete {
            return Err(Error::Internal);
        }

        let mut compact = Compact {
            stnu,
            ids: BTreeMap::new(),
            derived: Vec::new(),
        };
        let (steps, weight) = compact.steps(self, &trace.edges)?;

        if steps.is_empty() || weight >= Ticks::ZERO {
            return Err(Error::Internal);
        }

        Ok(SemiReducibleCycle::new(steps, compact.derived, weight))
    }
}

/// Builder of the compact form of a cycle: each derived edge is listed once.
struct Compact<'s> {
    /// The network, for original weights and activation points.
    stnu: &'s Stnu,
    /// Index in `derived` of each derived edge already listed.
    ids: BTreeMap<EdgeRef, usize>,
    /// Derived edges, inner ones first.
    derived: Vec<DerivedEdge>,
}

impl Compact<'_> {
    /// The compact steps of a path of normal-form edges and their total original weight.
    ///
    /// # Errors
    ///
    /// [`Error::BudgetExhausted`], [`Error::Overflow`] or [`Error::Internal`].
    fn steps(
        &mut self,
        g: &mut Graph<'_>,
        path: &[EdgeRef],
    ) -> Result<(Vec<CycleStep>, Ticks), Error> {
        let mut steps = Vec::new();
        let mut weight = Ticks::ZERO;

        for &(head, i) in path {
            g.meter.spend(1)?;
            let e = g.incoming[head][i];
            let (step, w) = match e.origin {
                Origin::Original(edge) => (CycleStep::Edge(edge), edge.resolve(self.stnu)?.2),
                Origin::Tie => continue,
                Origin::Derived => {
                    let id = self.derived_id(g, (head, i))?;
                    (CycleStep::Derived(id), self.derived[id].weight)
                }
            };

            weight = weight.checked_add(w).ok_or(Error::Overflow)?;
            steps.push(step);
        }

        Ok((steps, weight))
    }

    /// The index of the derived edge `edge`, listing it (and its inner edges) first if new.
    ///
    /// # Errors
    ///
    /// [`Error::BudgetExhausted`], [`Error::Overflow`] or [`Error::Internal`].
    fn derived_id(&mut self, g: &mut Graph<'_>, edge: EdgeRef) -> Result<usize, Error> {
        if let Some(&id) = self.ids.get(&edge) {
            return Ok(id);
        }

        let (head, i) = edge;
        let from = g.incoming[head][i].from;
        let path = walk(&g.trees[head], from, head)?;
        let (steps, weight) = self.steps(g, &path)?;
        let id = self.derived.len();
        self.derived.push(DerivedEdge {
            from: self.point(from),
            to: self.point(head),
            weight,
            steps,
        });
        self.ids.insert(edge, id);
        Ok(id)
    }

    /// The time point a normal-form node stands for: a link's own activation node is its
    /// activation point.
    fn point(&self, node: usize) -> TimePoint {
        let n = self.stnu.time_point_count();
        match node.checked_sub(n) {
            Some(i) => self.stnu.links[i].activation,
            None => TimePoint(node),
        }
    }
}

impl Search {
    /// Settles the closest unsettled node and returns it with its distance.
    ///
    /// A linear scan, `O(n')` steps; ties go to the lowest index, so results are
    /// deterministic.
    ///
    /// # Errors
    ///
    /// [`Error::BudgetExhausted`] or [`Error::Overflow`].
    fn pop(&mut self, meter: &mut Meter) -> Result<Option<(usize, Ticks)>, Error> {
        meter.spend(steps(self.dist.len())?)?;
        let mut best: Option<(usize, Ticks)> = None;

        let open = self.dist.iter().zip(&self.settled).enumerate();

        for (u, (d, settled)) in open {
            if let (Some(d), false) = (*d, *settled) {
                if best.is_none_or(|(_, b)| d < b) {
                    best = Some((u, d));
                }
            }
        }

        if let Some((u, _)) = best {
            self.settled[u] = true;
        }

        Ok(best)
    }

    /// Lowers the distance of `v` to `d` via `edge` if that is an improvement.
    fn relax(&mut self, v: usize, d: Ticks, edge: EdgeRef) {
        if !self.settled[v] && self.dist[v].is_none_or(|old| d < old) {
            self.dist[v] = Some(d);
            self.pred[v] = Some(edge);
        }
    }

    /// Appends this search's path from `u` (where a nested call found a cycle) to the source,
    /// unless the trace is already complete.
    ///
    /// # Errors
    ///
    /// [`Error::Internal`] if the path is broken.
    fn extend_trace(&self, mut trace: Trace, u: usize) -> Result<Trace, Error> {
        if trace.complete {
            return Ok(trace);
        }

        trace.edges.extend(walk(&self.pred, u, self.source)?);
        trace.complete = self.source == trace.closes_at;
        Ok(trace)
    }
}

/// The edges of the path `from ~> target` in a shortest-path tree, in traversal order.
///
/// # Errors
///
/// [`Error::Internal`] if the tree has no such path.
fn walk(tree: &[Option<EdgeRef>], from: usize, target: usize) -> Result<Vec<EdgeRef>, Error> {
    let mut path = Vec::new();
    let mut at = from;

    while path.len() < tree.len() {
        let (head, i) = tree.get(at).copied().flatten().ok_or(Error::Internal)?;
        path.push((head, i));

        if head == target {
            return Ok(path);
        }

        at = head;
    }

    Err(Error::Internal)
}