temporal-control 0.1.1

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
//! Dispatchable STNs: equivalence of the filtered network and simulated dispatch.

use std::sync::Mutex;

use proptest::prelude::*;
use temporal_control::{
    Budget, DispatchEdge, DispatchError, DispatchableNetwork, Dispatcher, PointKind, Stn, Ticks,
    TimePoint, Verdict, Wait,
};

use crate::generators::any_stn;
use crate::sim::{self, Agent, Nature, Rng};

/// Builds an [`Stn`] from the edges of a dispatchable network.
fn stn_of(net: &DispatchableNetwork) -> Stn {
    let mut stn = Stn::new();

    for _ in net.points() {
        stn.add_time_point().unwrap();
    }

    for e in net.edges() {
        stn.add_constraint(e.from, e.to, None, Some(e.weight))
            .unwrap();
    }

    stn
}

/// The dispatchable network of a consistent STN, or `None`.
fn dispatchable(stn: &Stn) -> Option<DispatchableNetwork> {
    match stn.dispatchable(&Budget::UNLIMITED).unwrap() {
        Verdict::Consistent(net) => Some(net),
        Verdict::Inconsistent(_) => None,
    }
}

/// A rigid pair whose lower index is the later point, plus a third point.
///
/// `t_0 = t_1 + 3`, `t_2 - t_1` in `[1, 10]`, and `t_2 = t_3` (zero-weight edges).
fn rigid_example() -> Stn {
    let mut stn = Stn::new();
    let p: Vec<TimePoint> = (0..4).map(|_| stn.add_time_point().unwrap()).collect();
    stn.add_constraint(p[1], p[0], Some(Ticks(3)), Some(Ticks(3)))
        .unwrap();
    stn.add_constraint(p[1], p[2], Some(Ticks(1)), Some(Ticks(10)))
        .unwrap();
    stn.add_constraint(p[2], p[3], Some(Ticks(0)), Some(Ticks(0)))
        .unwrap();
    stn
}

/// The earliest member leads a rigid component even if it has the higher index.
#[test]
fn rigid_component_led_by_earliest_member() {
    let stn = rigid_example();
    let net = dispatchable(&stn).unwrap();

    assert!(net.edges().contains(&DispatchEdge {
        from: TimePoint(1),
        to: TimePoint(0),
        weight: Ticks(3),
    }));
    assert!(net.edges().iter().all(|e| e.from.0 != 0 || e.to.0 == 1));

    for agent in [Agent::Asap, Agent::Latest, Agent::Random] {
        for nature in [Nature::Min, Nature::Max] {
            let times = sim::run(&net, agent, nature, &mut Rng(7));
            sim::assert_satisfies(&stn, &times);
        }
    }
}

/// Filtering removes edges implied by others: a chain keeps only its links.
#[test]
fn chain_is_filtered_to_its_links() {
    let mut stn = Stn::new();
    let p: Vec<TimePoint> = (0..4).map(|_| stn.add_time_point().unwrap()).collect();

    for w in p.windows(2) {
        stn.add_constraint(w[0], w[1], Some(Ticks(2)), Some(Ticks(5)))
            .unwrap();
    }

    let net = dispatchable(&stn).unwrap();
    assert_eq!(net.edges().len(), 6);
}

/// The dispatcher refuses early execution, reports missed deadlines and rejects bad input.
#[test]
fn dispatcher_reports_errors() {
    let points = [PointKind::Executable; 2];
    let edges = [
        DispatchEdge {
            from: TimePoint(0),
            to: TimePoint(1),
            weight: Ticks(10),
        },
        DispatchEdge {
            from: TimePoint(1),
            to: TimePoint(0),
            weight: Ticks(-5),
        },
    ];
    let mut d = Dispatcher::<2, 4>::new(&points, &edges, &[]).unwrap();

    assert_eq!(
        d.execute(TimePoint(1), Ticks(0)),
        Err(DispatchError::NotExecutable(TimePoint(1)))
    );
    d.execute(TimePoint(0), Ticks(0)).unwrap();
    assert_eq!(
        d.window(TimePoint(1)),
        Some((Some(Ticks(5)), Some(Ticks(10))))
    );
    assert_eq!(d.next_wakeup(), Some(Ticks(5)));
    assert_eq!(
        d.check_deadlines(Ticks(11)),
        Err(DispatchError::DeadlineMissed(TimePoint(1)))
    );
    assert_eq!(
        d.check_deadlines(Ticks(3)),
        Err(DispatchError::TimeWentBackwards)
    );

    assert_eq!(
        Dispatcher::<1, 4>::new(&points, &edges, &[]).err(),
        Some(DispatchError::CapacityExceeded)
    );
    let bad = [DispatchEdge {
        from: TimePoint(0),
        to: TimePoint(5),
        weight: Ticks(1),
    }];
    assert_eq!(
        Dispatcher::<2, 4>::new(&points, &bad, &[]).err(),
        Some(DispatchError::InvalidNetwork)
    );
}

proptest! {
    /// The filtered network has the same minimal network as the original.
    #[test]
    fn filtered_network_is_equivalent(spec in any_stn()) {
        let stn = spec.build().unwrap();
        let Some(net) = dispatchable(&stn) else {
            return Ok(());
        };

        let original = stn.minimal_network(&Budget::UNLIMITED).unwrap();
        let filtered = stn_of(&net).minimal_network(&Budget::UNLIMITED).unwrap();
        prop_assert_eq!(original, filtered);
        prop_assert!(net.edges().iter().all(|e| e.from != e.to));
    }

    /// Any agent policy completes without a dispatch error and satisfies every constraint.
    #[test]
    fn dispatch_never_violates(spec in any_stn(), seed in 1u64..) {
        let stn = spec.build().unwrap();
        let Some(net) = dispatchable(&stn) else {
            return Ok(());
        };

        let mut rng = Rng(seed);

        for agent in [Agent::Asap, Agent::Latest, Agent::Random] {
            let times = sim::run(&net, agent, Nature::Random, &mut rng);
            sim::assert_satisfies(&stn, &times);
        }
    }

    /// Under any budget, filtering either reports exhaustion or matches the unlimited result.
    #[test]
    fn dispatchable_budget_never_changes_result(spec in any_stn(), max_steps in 0u64..600) {
        let stn = spec.build().unwrap();
        let budget = Budget { max_steps, max_cells: usize::MAX };
        let limited = stn.dispatchable(&budget);
        prop_assert!(limited == Err(temporal_control::Error::BudgetExhausted)
            || limited == stn.dispatchable(&Budget::UNLIMITED));
    }
}

/// Upper dominance through a zero-weight edge: `t_0`'s deadline reaches it only through `t_1`.
///
/// Regression: with zero-weight edges counted as precedence, `t_1` waited for `t_0`, which had
/// no deadline of its own, and `t_1` missed its deadline.
#[test]
fn zero_weight_dominance_does_not_deadlock() {
    let mut stn = Stn::new();
    let p: Vec<TimePoint> = (0..6).map(|_| stn.add_time_point().unwrap()).collect();
    stn.add_constraint(p[0], p[1], Some(Ticks(0)), None)
        .unwrap();
    stn.add_constraint(p[5], p[0], Some(Ticks(54)), None)
        .unwrap();
    stn.add_constraint(p[1], p[2], Some(Ticks(-49)), None)
        .unwrap();
    let net = dispatchable(&stn).unwrap();

    for seed in 1..200 {
        let times = sim::run(&net, Agent::Random, Nature::Random, &mut Rng(seed));
        sim::assert_satisfies(&stn, &times);
    }
}

/// A contingent point with the given activation and bounds.
fn contingent(activation: usize, lo: i64, hi: i64) -> PointKind {
    PointKind::Contingent {
        activation: TimePoint(activation),
        lo: Ticks(lo),
        hi: Ticks(hi),
    }
}

/// Every malformed-network branch of the validator is rejected.
#[test]
fn validator_rejects_malformed_networks() {
    let exec = PointKind::Executable;
    let edge = |from, to, weight| DispatchEdge {
        from: TimePoint(from),
        to: TimePoint(to),
        weight: Ticks(weight),
    };
    let wait = |waiter, contingent| Wait {
        waiter: TimePoint(waiter),
        contingent: TimePoint(contingent),
        delay: Ticks(1),
    };
    let cases: [(&[PointKind], &[DispatchEdge], &[Wait]); 7] = [
        (&[exec, contingent(0, 0, 3)], &[], &[]),
        (&[exec, contingent(0, 4, 3)], &[], &[]),
        (&[contingent(1, 1, 3), contingent(0, 1, 3)], &[], &[]),
        (&[exec, contingent(7, 1, 3)], &[], &[]),
        (&[exec, exec], &[edge(1, 1, -1)], &[]),
        (&[exec, contingent(0, 1, 3)], &[], &[wait(1, 1)]),
        (&[exec, exec], &[], &[wait(0, 1)]),
    ];

    for (points, edges, waits) in cases {
        assert_eq!(
            Dispatcher::<4, 8>::new(points, edges, waits).err(),
            Some(DispatchError::InvalidNetwork),
            "{points:?} {edges:?} {waits:?}"
        );
    }
}

/// One arbitrary dispatcher call.
#[derive(Debug, Clone)]
enum Call {
    /// [`Dispatcher::observe`].
    Observe(usize, i64),
    /// [`Dispatcher::execute`].
    Execute(usize, i64),
    /// [`Dispatcher::step`] with one observation.
    Step(usize, i64),
    /// [`Dispatcher::check_deadlines`].
    Deadlines(i64),
}

/// Extreme and small tick values.
fn any_tick() -> impl Strategy<Value = i64> {
    prop_oneof![
        Just(i64::MIN),
        Just(i64::MAX),
        Just(i64::MIN + 1),
        Just(i64::MAX - 1),
        -20i64..=20,
    ]
}

proptest! {
    /// Arbitrary, possibly malformed networks and call sequences never panic.
    #[test]
    fn dispatcher_never_panics(
        kinds in proptest::collection::vec((any::<bool>(), 0usize..6, any_tick(), any_tick()), 0..6),
        edges in proptest::collection::vec((0usize..7, 0usize..7, any_tick()), 0..10),
        waits in proptest::collection::vec((0usize..7, 0usize..7, any_tick()), 0..4),
        calls in proptest::collection::vec(
            prop_oneof![
                (0usize..7, any_tick()).prop_map(|(p, t)| Call::Observe(p, t)),
                (0usize..7, any_tick()).prop_map(|(p, t)| Call::Execute(p, t)),
                (0usize..7, any_tick()).prop_map(|(p, t)| Call::Step(p, t)),
                any_tick().prop_map(Call::Deadlines),
            ],
            0..20,
        ),
    ) {
        let points: Vec<PointKind> = kinds
            .iter()
            .map(|&(exec, a, lo, hi)| {
                if exec {
                    PointKind::Executable
                } else {
                    PointKind::Contingent { activation: TimePoint(a), lo: Ticks(lo), hi: Ticks(hi) }
                }
            })
            .collect();
        let edges: Vec<DispatchEdge> = edges
            .iter()
            .map(|&(f, t, w)| DispatchEdge { from: TimePoint(f), to: TimePoint(t), weight: Ticks(w) })
            .collect();
        let waits: Vec<Wait> = waits
            .iter()
            .map(|&(x, c, d)| Wait { waiter: TimePoint(x), contingent: TimePoint(c), delay: Ticks(d) })
            .collect();

        let Ok(mut d) = Dispatcher::<6, 24>::new(&points, &edges, &waits) else {
            return Ok(());
        };

        let mut out = [TimePoint(0); 6];

        for call in calls {
            let _ = match call {
                Call::Observe(p, t) => d.observe(TimePoint(p), Ticks(t)),
                Call::Execute(p, t) => d.execute(TimePoint(p), Ticks(t)),
                Call::Step(p, t) => d.step(Ticks(t), &[TimePoint(p)], &mut out).map(|_| ()),
                Call::Deadlines(t) => d.check_deadlines(Ticks(t)),
            };
            let _ = (d.next_wakeup(), d.is_complete(), d.window(TimePoint(0)), d.time(TimePoint(0)));
        }
    }
}

/// Two executable points with `5 <= t_1 - t_0 <= 10`.
fn two_point_edges() -> [DispatchEdge; 2] {
    [
        DispatchEdge {
            from: TimePoint(0),
            to: TimePoint(1),
            weight: Ticks(10),
        },
        DispatchEdge {
            from: TimePoint(1),
            to: TimePoint(0),
            weight: Ticks(-5),
        },
    ]
}

/// Dispatcher in static-friendly storage: loaded in place, reloaded, and unchanged by a
/// rejected load.
#[test]
fn load_in_place_replaces_or_keeps_state() {
    let points = [PointKind::Executable; 2];
    let edges = two_point_edges();
    let mut d = Dispatcher::<4, 8>::EMPTY;
    assert!(d.is_complete());
    assert_eq!(d.window(TimePoint(0)), None);

    d.load(&points, &edges, &[]).unwrap();
    d.execute(TimePoint(0), Ticks(3)).unwrap();
    let before = format!("{d:?}");

    let bad = [DispatchEdge {
        from: TimePoint(0),
        to: TimePoint(9),
        weight: Ticks(1),
    }];
    assert_eq!(
        d.load(&points, &bad, &[]),
        Err(DispatchError::InvalidNetwork)
    );
    assert_eq!(
        d.load(&[PointKind::Executable; 5], &[], &[]),
        Err(DispatchError::CapacityExceeded)
    );
    assert_eq!(format!("{d:?}"), before);

    d.load(&points, &edges, &[]).unwrap();
    assert_eq!(d.time(TimePoint(0)), None);
    assert_eq!(d.window(TimePoint(1)), Some((None, None)));
    assert_eq!(
        format!("{d:?}"),
        format!(
            "{:?}",
            Dispatcher::<4, 8>::new(&points, &edges, &[]).unwrap()
        )
    );
}

/// Runs `check` on a thread with a stack large enough for dispatchers of `u16::MAX` capacity.
fn with_big_stack(check: impl FnOnce() + Send + 'static) {
    std::thread::Builder::new()
        .stack_size(256 << 20)
        .spawn(check)
        .unwrap()
        .join()
        .unwrap();
}

/// A `u16` dispatcher accepts exactly the networks whose point and entry counts are at most
/// `u16::MAX`, even when its capacities are larger.
#[test]
fn index_type_bounds_network_size() {
    with_big_stack(|| {
        const CAP: usize = 1 << 16;
        let mut d = Dispatcher::<CAP, CAP, u16>::EMPTY;
        let max = usize::from(u16::MAX);

        assert_eq!(d.load(&vec![PointKind::Executable; max], &[], &[]), Ok(()));
        assert_eq!(
            d.load(&vec![PointKind::Executable; max + 1], &[], &[]),
            Err(DispatchError::IndexTypeTooSmall)
        );

        let points = [PointKind::Executable, contingent(0, 1, 2)];
        let edge = DispatchEdge {
            from: TimePoint(0),
            to: TimePoint(1),
            weight: Ticks(5),
        };
        let wait = Wait {
            waiter: TimePoint(0),
            contingent: TimePoint(1),
            delay: Ticks(1),
        };
        let edges = vec![edge; max / 2];
        assert_eq!(d.load(&points, &edges, &[wait]), Ok(()));
        assert_eq!(
            d.load(&points, &edges, &[wait, wait]),
            Err(DispatchError::IndexTypeTooSmall)
        );
        assert_eq!(
            d.load(&points, &vec![edge; max / 2 + 1], &[]),
            Err(DispatchError::IndexTypeTooSmall)
        );
    });
}

proptest! {
    /// `u16` and `u32` dispatchers make exactly the decisions of the default `usize` one.
    #[test]
    fn index_types_dispatch_identically(spec in any_stn(), seed in 1u64..) {
        let stn = spec.build().unwrap();
        let Some(net) = dispatchable(&stn) else {
            return Ok(());
        };

        for agent in [Agent::Asap, Agent::Random] {
            let expected = sim::run(&net, agent, Nature::Random, &mut Rng(seed));
            let mut narrow: Dispatcher<{ sim::N }, { sim::E }, u16> = net.dispatcher().unwrap();
            let mut mid: Dispatcher<{ sim::N }, { sim::E }, u32> = net.dispatcher().unwrap();
            prop_assert_eq!(&sim::run_on(&mut narrow, &net, agent, Nature::Random, &mut Rng(seed)), &expected);
            prop_assert_eq!(&sim::run_on(&mut mid, &net, agent, Nature::Random, &mut Rng(seed)), &expected);
        }
    }
}

/// A dispatcher of about 1 MB capacity in a `static`, initialised at compile time.
static BIG: Mutex<Dispatcher<8192, 8192>> = Mutex::new(Dispatcher::EMPTY);

/// `load`, a rejected `load` and `load_encoded` work in place: on a 256 KiB stack, any
/// temporary of the dispatcher's size would overflow it.
#[test]
fn loading_needs_no_capacity_sized_stack() {
    let points = [PointKind::Executable; 2];
    let edges = two_point_edges();

    std::thread::Builder::new()
        .stack_size(256 << 10)
        .spawn(move || {
            let mut d = BIG.lock().unwrap();
            d.load(&points, &edges, &[]).unwrap();
            assert_eq!(
                d.load(&vec![PointKind::Executable; 8193], &[], &[]),
                Err(DispatchError::CapacityExceeded)
            );

            let mut buf = [0u8; 128];
            let len =
                temporal_control::dispatch::encoding::encode_into(&points, &edges, &[], &mut buf)
                    .unwrap();
            d.load_encoded(&buf[..len]).unwrap();
            d.execute(TimePoint(0), Ticks(0)).unwrap();
            assert_eq!(d.next_wakeup(), Some(Ticks(5)));
        })
        .unwrap()
        .join()
        .unwrap();
}