pddl-validate 0.1.0

Independent PDDL plan validator: classical, numeric and temporal plans with precise diagnostics
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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
//! Temporal plans (level 3): durative actions, happenings, invariants, interference and
//! timed initial literals, after PDDL 2.1 and VAL.
//!
//! A durative action starting at `t` with duration `d` splits into a start event at `t`
//! and an end event at `t + d`. Instantaneous actions and timed initial literals are
//! events too. Events at the same time (within [`SAME_TIME`]) form a happening, and
//! happenings run in time order:
//!
//! ```mermaid
//! flowchart TD
//!     schedule["split steps into events, add timed literals"] --> next{"next happening?"}
//!     next -- yes --> interval["advance continuous change; check over all conditions"]
//!     interval --> conditions["check at start / at end conditions, preconditions, durations"]
//!     conditions --> collect["collect each event's effects in the state before"]
//!     collect --> mutex["reject interfering events less than epsilon apart"]
//!     mutex --> apply["apply all effects: deletes, adds, numeric updates"]
//!     apply --> next
//!     next -- no --> goal["check the goal and the metric"]
//! ```
//!
//! An untimed plan for a temporal task runs its steps at times 1, 2, 3, and so on. In a
//! metric, `total-time` is the makespan: the time of the last event of the plan. Timed
//! initial literals after the makespan do not happen.

mod continuous;
mod mutex;
mod pddl_plus;
mod timed;

use alloc::boxed::Box;
use alloc::collections::BTreeSet;
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use core::cell::RefCell;

use pddl::{
    ActionDefinition, AtomicFormula, DurativeActionDefinition, InitElement, Literal, Problem,
};

use super::{bind_parameters, finish, step_ref, stopped, Stop};
use crate::atom::{lower, Atom};
use crate::effects::Changes;
use crate::eval::{Evaluator, Observer, Scope};
use crate::model::Model;
use crate::plan::{Plan, PlanStep};
use crate::report::{Report, StepRef, StepTrace, ViolationKind};
use crate::state::State;
use continuous::{Flow, Interval, Rates};
use mutex::Footprint;
use pddl_plus::Dynamics;
use timed::{Collector, Memo, Moment};

pub use crate::model::SAME_TIME;

/// The rounding error that a difference of two times near `time` may carry.
///
/// Plan times are decimals rounded to `f64`, so the difference of two of them is off by
/// up to a few units in the last place of the larger one: about `1e-7` near `1e9`. The
/// slack is [`SAME_TIME`] for small times and grows with `time`, so a separation of
/// exactly epsilon as written in the plan passes at any magnitude.
fn rounding_slack(time: f64) -> f64 {
    SAME_TIME.max(time.abs() * 8.0 * f64::EPSILON)
}

/// Runs plans on the timeline of a temporal task.
pub struct Timeline<'v, 'a> {
    /// The indexed domain and problem.
    pub model: &'v Model<'a>,
    /// The problem, for its timed initial literals, goal and metric.
    pub problem: &'a Problem,
    /// The relative tolerance of numeric comparisons.
    pub tolerance: f64,
    /// The least time between interfering events.
    pub epsilon: f64,
    /// The absolute tolerance of duration constraints; see
    /// [`Validator::with_duration_tolerance`](crate::Validator::with_duration_tolerance).
    pub duration_tolerance: f64,
}

/// A durative action of the plan, between its start and its end.
struct Instance<'v> {
    /// The action.
    action: &'v DurativeActionDefinition,
    /// Its parameters, bound to the step's objects.
    scope: Scope,
    /// The duration, positive.
    duration: f64,
    /// The step that starts it.
    step: StepRef,
    /// The `at start` conditions of its `at end` conditional effects.
    memo: Memo,
    /// Its continuous effects, ground when it starts.
    flows: Vec<Flow<'v>>,
}

/// When a durative step of the plan runs, to reject a ground action overlapping itself.
struct Span {
    /// The step; its `action` text names the ground action.
    step: StepRef,
    /// The start time.
    start: f64,
    /// The end time, later than `start`.
    end: f64,
}

impl Span {
    /// The number of a step in `earlier` that runs the same ground action while this one
    /// runs, if any. Spans that only touch, one ending where the other starts, do not
    /// overlap; the interference check judges their shared happening.
    fn overlapping(&self, earlier: &[Span]) -> Option<usize> {
        earlier
            .iter()
            .find(|other| {
                other.step.action.eq_ignore_ascii_case(&self.step.action)
                    && self.start < other.end - SAME_TIME
                    && other.start < self.end - SAME_TIME
            })
            .map(|other| other.step.number)
    }
}

/// What happens at an event.
enum Kind<'v> {
    /// An instantaneous action, with its parameters bound.
    Instant(&'v ActionDefinition, Scope),
    /// The start of an [`Instance`], by index.
    Start(usize),
    /// The end of an [`Instance`], by index.
    End(usize),
    /// A timed initial literal: the atom, and `true` to add it or `false` to delete it.
    Literal(Atom, bool),
}

/// Something that happens at one time.
struct Event<'v> {
    /// When.
    time: f64,
    /// What.
    kind: Kind<'v>,
    /// The plan step it belongs to; `None` for a timed initial literal.
    step: Option<StepRef>,
    /// What it is called in traces and diagnostics.
    label: String,
}

/// An event that already happened, kept while it may interfere with later ones.
struct Past {
    /// When it happened.
    time: f64,
    /// What it is called.
    label: String,
    /// What it read and wrote.
    footprint: Footprint,
    /// The durative instance it starts or ends, if any. An action's own start and end
    /// never interfere: the domain orders them.
    owner: Option<usize>,
}

/// Why the timeline stopped, and at which step.
type Failure = Box<(Option<StepRef>, Stop)>;

/// Builds a [`Failure`].
fn failure(step: Option<StepRef>, reason: Stop) -> Failure {
    Box::new((step, reason))
}

impl<'v> Timeline<'v, '_> {
    /// Runs `plan` from `initial` and checks the goal at the end.
    pub fn run(&self, initial: &State, plan: &Plan) -> Report {
        let (mut instances, mut events) = match self.schedule(plan) {
            Ok(scheduled) => scheduled,
            Err(failed) => {
                let (step, reason) = *failed;
                return stopped(reason, step, String::from("plan"), Vec::new());
            }
        };

        let makespan = events.iter().map(|event| event.time).fold(0.0, f64::max);
        events.extend(self.timed_literals(makespan));
        events.sort_by(|a, b| a.time.total_cmp(&b.time));

        let dynamics = Dynamics::new(&self.evaluator(initial, None));
        match self.happenings(initial, &mut instances, &events, &dynamics) {
            Ok((state, trace)) => {
                let evaluator = self.evaluator(&state, None);
                finish(&evaluator, self.problem, makespan, trace)
            }
            Err((failed, trace)) => {
                let (step, reason) = *failed;
                let location = step.as_ref().map_or_else(
                    || String::from("timeline"),
                    |s| format!("step {}", s.number),
                );
                stopped(reason, step, location, trace)
            }
        }
    }

    /// Builds an evaluator for `state`.
    const fn evaluator<'s>(
        &'s self,
        state: &'s State,
        observer: Option<&'s RefCell<Observer>>,
    ) -> Evaluator<'s, 'v> {
        Evaluator {
            model: self.model,
            state,
            tolerance: self.tolerance,
            observer,
        }
    }

    /// Splits the plan's steps into events and durative instances.
    fn schedule(&self, plan: &Plan) -> Result<(Vec<Instance<'v>>, Vec<Event<'v>>), Failure> {
        let timed = plan.steps().iter().any(|step| step.time().is_some());
        let mut instances = Vec::new();
        let mut events = Vec::new();
        let mut spans: Vec<Span> = Vec::new();
        for (index, step) in plan.steps().iter().enumerate() {
            let at = step_ref(index, step);
            let fail = |kind| Err(failure(Some(at.clone()), Stop::Invalid(kind)));
            let time = match step.time() {
                Some(time) if !(time.is_finite() && time >= 0.0) => {
                    return fail(ViolationKind::InvalidTime(time));
                }
                Some(time) => time,
                None if timed => return fail(ViolationKind::MissingTimestamp),
                #[expect(
                    clippy::cast_precision_loss,
                    reason = "plans of more than 2^53 steps do not fit in memory"
                )]
                None => (index + 1) as f64,
            };

            if let Some(action) = self.model.durative.get(step.action()) {
                let instance = self.instance(action, step, &at)?;
                let label = at.action.clone();
                let end = time + instance.duration;
                if !end.is_finite() {
                    return fail(ViolationKind::InvalidTime(end));
                }

                // At a huge start time the duration can round away, merging start and end
                // into one happening that skips the over all conditions.
                if end - time <= SAME_TIME {
                    return fail(ViolationKind::NonPositiveDuration(end - time));
                }

                let span = Span {
                    step: at.clone(),
                    start: time,
                    end,
                };
                if let Some(other) = span.overlapping(&spans) {
                    return fail(ViolationKind::SelfOverlap { other });
                }

                spans.push(span);
                let number = instances.len();
                events.push(event(
                    time,
                    Kind::Start(number),
                    &at,
                    format!("start {label}"),
                ));
                events.push(event(end, Kind::End(number), &at, format!("end {label}")));
                instances.push(instance);
            } else {
                let (action, scope) =
                    super::bind(self.model, step).map_err(|s| failure(Some(at.clone()), s))?;
                if step.duration().is_some() {
                    return fail(ViolationKind::UnexpectedDuration);
                }

                let label = at.action.clone();
                events.push(event(time, Kind::Instant(action, scope), &at, label));
            }
        }

        Ok((instances, events))
    }

    /// Binds a durative action of `step` and checks its duration.
    fn instance(
        &self,
        action: &'v DurativeActionDefinition,
        step: &PlanStep,
        at: &StepRef,
    ) -> Result<Instance<'v>, Failure> {
        let fail = |kind| Err(failure(Some(at.clone()), Stop::Invalid(kind)));
        let scope = bind_parameters(self.model, action.parameters(), step)
            .map_err(|reason| failure(Some(at.clone()), reason))?;
        let Some(duration) = step.duration() else {
            return fail(ViolationKind::MissingDuration);
        };

        // A duration within SAME_TIME would put start and end in one happening and skip
        // the over all conditions, so it counts as zero; NaN fails the test too.
        if !(duration > SAME_TIME && duration.is_finite()) {
            return fail(ViolationKind::NonPositiveDuration(duration));
        }

        Ok(Instance {
            action,
            scope,
            duration,
            step: at.clone(),
            memo: Memo::new(),
            flows: Vec::new(),
        })
    }

    /// Returns the timed initial literals up to `makespan` as events.
    fn timed_literals(&self, makespan: f64) -> Vec<Event<'v>> {
        let mut events = Vec::new();
        for element in self.problem.init().iter() {
            let InitElement::At(time, literal) = element else {
                continue;
            };

            let (formula, positive) = match literal {
                Literal::AtomicFormula(formula) => (formula, true),
                Literal::NotAtomicFormula(formula) => (formula, false),
            };
            // The static check rejects timed equalities.
            let AtomicFormula::Predicate(predicate) = formula else {
                continue;
            };

            let time = **time;
            if time > makespan + SAME_TIME {
                continue;
            }

            let arguments = predicate.values().iter().map(|name| lower(name)).collect();
            let atom = Atom::lowered(lower(predicate.predicate()), arguments);
            let label = if positive {
                format!("timed literal {atom} at {time}")
            } else {
                format!("timed literal (not {atom}) at {time}")
            };
            events.push(Event {
                time,
                kind: Kind::Literal(atom, positive),
                step: None,
                label,
            });
        }

        events
    }

    /// Runs the happenings of the sorted `events`. Returns the final state and the trace,
    /// or the failure with the trace so far.
    fn happenings(
        &self,
        initial: &State,
        instances: &mut [Instance<'v>],
        events: &[Event<'v>],
        dynamics: &Dynamics<'v>,
    ) -> Result<(State, Vec<StepTrace>), (Failure, Vec<StepTrace>)> {
        let mut state = initial.clone();
        let mut trace = Vec::new();
        if let Err(failure) = self.cascade(dynamics, &mut state, 0.0, &mut trace) {
            return Err((failure, trace));
        }

        let mut active = BTreeSet::new();
        let mut recent: Vec<Past> = Vec::new();
        let mut clock = 0.0;
        let mut rest = events;
        while let Some(first) = rest.first() {
            // At least one event, so the loop ends whatever the times.
            let size = rest
                .iter()
                .take_while(|event| event.time - first.time <= SAME_TIME)
                .count()
                .max(1);
            let (happening, later) = rest.split_at(size);
            rest = later;

            if first.time - clock > SAME_TIME {
                let next = self.interval(
                    dynamics,
                    &state,
                    (instances, &active, &ends(happening)),
                    (clock, first.time),
                    &mut trace,
                );
                state = match next {
                    Ok(next) => next,
                    Err(failure) => return Err((failure, trace)),
                };
                clock = first.time;
            }

            // Events exactly epsilon apart are far enough, despite rounding.
            let slack = rounding_slack(first.time);
            recent.retain(|past| first.time - past.time < self.epsilon - slack);
            match self.happen(&mut state, instances, happening, &mut recent) {
                Ok(step) => trace.push(step),
                Err(failure) => return Err((failure, trace)),
            }

            if let Err(failure) = self.cascade(dynamics, &mut state, first.time, &mut trace) {
                return Err((failure, trace));
            }

            for event in happening {
                match event.kind {
                    Kind::Start(index) => {
                        active.insert(index);
                    }
                    Kind::End(index) => {
                        active.remove(&index);
                    }
                    Kind::Instant(..) | Kind::Literal(..) => {}
                }
            }
        }

        Ok((state, trace))
    }

    /// Advances continuous change from `start` to `end`, with processes and events if
    /// the task has any, and checks the `over all` conditions of the `active` actions
    /// throughout. Returns the state at `end`.
    ///
    /// The happening at `end` lies inside the open interval of every active action that
    /// does not end there, so their conditions must also hold at `end`, in the state
    /// before the happening; the actions in `ending` are exempt.
    fn interval(
        &self,
        dynamics: &Dynamics<'v>,
        state: &State,
        (instances, active, ending): (&[Instance<'v>], &BTreeSet<usize>, &BTreeSet<usize>),
        (start, end): (f64, f64),
        trace: &mut Vec<StepTrace>,
    ) -> Result<State, Failure> {
        let running: Vec<&Instance<'v>> = active.iter().filter_map(|&i| instances.get(i)).collect();
        let through: Vec<&Instance<'v>> = active
            .difference(ending)
            .filter_map(|&i| instances.get(i))
            .collect();
        if !dynamics.is_empty() {
            let running = (running.as_slice(), through.as_slice());
            return self.hybrid_interval(dynamics, state, running, start, end, trace);
        }

        let Some(first) = running.first() else {
            return Ok(state.clone());
        };

        let flows: Vec<&Flow<'v>> = running.iter().flat_map(|i| &i.flows).collect();
        let stop = |error| failure(Some(first.step.clone()), Stop::from(error));
        let rates = continuous::rates(&self.evaluator(state, None), &flows).map_err(stop)?;
        self.check_invariants(&running, state, &rates, start, end)?;
        let next = continuous::advance(state, &rates, end - start).map_err(stop)?;
        self.check_invariants_at(&through, &next, end)?;

        Ok(next)
    }

    /// Checks the `over all` conditions of the `running` actions on the open interval
    /// from `start` to `end`, with `state` at `start` and constant `rates`.
    fn check_invariants(
        &self,
        running: &[&Instance<'v>],
        state: &State,
        rates: &Rates,
        start: f64,
        end: f64,
    ) -> Result<(), Failure> {
        let interval = Interval {
            start,
            end,
            state,
            rates,
        };
        for instance in running {
            let Some(invariant) = instance.action.condition() else {
                continue;
            };

            let at = || Some(instance.step.clone());
            let mut scope = instance.scope.clone();
            match interval.check(self.model, self.tolerance, invariant, &mut scope) {
                Ok(None) => {}
                Ok(Some((time, unmet))) => {
                    let kind = ViolationKind::InvariantViolated { time, unmet };
                    return Err(failure(at(), Stop::Invalid(kind)));
                }
                Err(error) => return Err(failure(at(), Stop::from(error))),
            }
        }

        Ok(())
    }

    /// Checks the `over all` conditions of the `running` durative actions in `state`
    /// at the single point `time`.
    fn check_invariants_at(
        &self,
        running: &[&Instance<'v>],
        state: &State,
        time: f64,
    ) -> Result<(), Failure> {
        let evaluator = self.evaluator(state, None);
        for instance in running {
            let Some(invariant) = instance.action.condition() else {
                continue;
            };

            let at = || Some(instance.step.clone());
            let mut scope = instance.scope.clone();
            match timed::condition(&evaluator, invariant, &mut scope, Moment::Over) {
                Ok(None) => {}
                Ok(Some(unmet)) => {
                    let kind = ViolationKind::InvariantViolated { time, unmet };
                    return Err(failure(at(), Stop::Invalid(kind)));
                }
                Err(error) => return Err(failure(at(), Stop::from(error))),
            }
        }

        Ok(())
    }

    /// Runs one happening on `state`: checks every event's conditions in the state
    /// before it, rejects interference, and applies all effects at once.
    fn happen(
        &self,
        state: &mut State,
        instances: &mut [Instance<'v>],
        happening: &[Event<'v>],
        recent: &mut Vec<Past>,
    ) -> Result<StepTrace, Failure> {
        let mut merged = Changes::default();
        let mut current: Vec<Past> = Vec::new();
        for event in happening {
            let fail = |reason| failure(event.step.clone(), reason);
            let observer = RefCell::new(Observer::default());
            let evaluator = self.evaluator(state, Some(&observer));
            // A failed condition still records what it read, and interference is the
            // better diagnostic: the condition may fail only because of the order.
            let result = run_event(&evaluator, event, instances, self.duration_tolerance);
            let footprint = Footprint::new(
                &observer.borrow(),
                result.as_ref().unwrap_or(&Changes::default()),
            );
            let clash = recent.iter().chain(&current).find(|past| {
                (past.owner.is_none() || past.owner != owner(event))
                    && past.footprint.interferes(&footprint)
            });
            if let Some(past) = clash {
                let kind = ViolationKind::Interference {
                    event: event.label.clone(),
                    other: past.label.clone(),
                    time: event.time,
                    separation: event.time - past.time,
                };
                return Err(fail(Stop::Invalid(kind)));
            }

            merged.merge(result.map_err(fail)?);
            current.push(Past {
                time: event.time,
                label: event.label.clone(),
                footprint,
                owner: owner(event),
            });
        }

        let first_step = happening.first().and_then(|event| event.step.clone());
        let mut step = merged
            .apply(state)
            .map_err(|error| failure(first_step, Stop::from(error)))?;
        step.time = happening.first().map(|event| event.time);
        step.events = happening.iter().map(|event| event.label.clone()).collect();
        recent.extend(current);

        Ok(step)
    }
}

/// Returns the durative instances that end in `happening`.
fn ends(happening: &[Event<'_>]) -> BTreeSet<usize> {
    happening
        .iter()
        .filter_map(|event| match event.kind {
            Kind::End(index) => Some(index),
            Kind::Start(_) | Kind::Instant(..) | Kind::Literal(..) => None,
        })
        .collect()
}

/// Returns the durative instance an event starts or ends.
const fn owner(event: &Event<'_>) -> Option<usize> {
    match event.kind {
        Kind::Start(index) | Kind::End(index) => Some(index),
        Kind::Instant(..) | Kind::Literal(..) => None,
    }
}

/// Builds a plan event.
fn event<'v>(time: f64, kind: Kind<'v>, step: &StepRef, label: String) -> Event<'v> {
    Event {
        time,
        kind,
        step: Some(step.clone()),
        label,
    }
}

/// Checks the conditions of one event and collects its effects; durations compare
/// within `duration_tolerance`.
fn run_event<'v>(
    evaluator: &Evaluator<'_, '_>,
    event: &Event<'v>,
    instances: &mut [Instance<'v>],
    duration_tolerance: f64,
) -> Result<Changes, Stop> {
    let mut changes = Changes::default();
    match &event.kind {
        Kind::Instant(action, scope) => {
            let mut scope = scope.clone();
            if let Some(unmet) = evaluator.preconditions(action.precondition(), &mut scope)? {
                return Err(Stop::Invalid(ViolationKind::PreconditionUnsatisfied(unmet)));
            }

            if let Some(effects) = action.effect() {
                changes.collect(evaluator, effects, &mut scope)?;
            }
        }
        Kind::Start(index) | Kind::End(index) => {
            let moment = if matches!(event.kind, Kind::Start(_)) {
                Moment::Start
            } else {
                Moment::End
            };
            if let Some(instance) = instances.get_mut(*index) {
                durative_event(
                    evaluator,
                    instance,
                    moment,
                    duration_tolerance,
                    &mut changes,
                )?;
            }
        }
        Kind::Literal(atom, true) => {
            changes.add.insert(atom.clone());
        }
        Kind::Literal(atom, false) => {
            changes.delete.insert(atom.clone());
        }
    }

    Ok(changes)
}

/// Checks the duration and the conditions of a durative action at `moment` and
/// collects its effects then; at the start, also grounds its continuous effects. The
/// duration compares within `duration_tolerance`.
fn durative_event(
    evaluator: &Evaluator<'_, '_>,
    instance: &mut Instance<'_>,
    moment: Moment,
    duration_tolerance: f64,
    changes: &mut Changes,
) -> Result<(), Stop> {
    let action = instance.action;
    let mut scope = instance.scope.clone();
    if let Some(constraint) = action.duration() {
        let unmet = timed::duration(
            evaluator,
            constraint,
            &scope,
            instance.duration,
            duration_tolerance,
            moment,
        )?;
        if let Some(unmet) = unmet {
            return Err(Stop::Invalid(ViolationKind::DurationConstraint(unmet)));
        }
    }

    if let Some(condition) = action.condition() {
        if let Some(unmet) = timed::condition(evaluator, condition, &mut scope, moment)? {
            let kind = match moment {
                Moment::End => ViolationKind::EndConditionUnsatisfied(unmet),
                Moment::Start | Moment::Over => ViolationKind::StartConditionUnsatisfied(unmet),
            };
            return Err(Stop::Invalid(kind));
        }
    }

    let Some(effect) = action.effect() else {
        return Ok(());
    };

    let collector = Collector {
        evaluator,
        moment,
        duration: instance.duration,
    };
    collector.collect(effect, &mut scope, &mut instance.memo, changes)?;
    if moment == Moment::Start {
        continuous::flows(evaluator, effect, &mut scope, &mut instance.flows)?;
    }

    Ok(())
}