Skip to main content

pddl_validate/
validator.rs

1//! The validator: checks a domain and problem once, then runs plans against them.
2//!
3//! ```mermaid
4//! flowchart TD
5//!     new["Validator::new"] --> names["check names, arities, types"]
6//!     names --> scan["find unsupported constructs"]
7//!     scan --> strata["stratify derived predicates"]
8//!     strata --> init["build the initial state"]
9//!     init --> step{"next step?"}
10//!     step -- yes --> ground["ground: action, arity, objects, types"]
11//!     ground --> pre["check the precondition"]
12//!     pre --> eff["collect effects, delete, add"]
13//!     eff --> close["recompute derived atoms"]
14//!     close --> step
15//!     step -- no --> goal["check the goal"]
16//! ```
17
18mod temporal;
19
20use alloc::format;
21use alloc::string::String;
22use alloc::vec::Vec;
23
24use pddl::{AtomicFormula, Domain, InitElement, Literal, Problem};
25
26use crate::atom::{lower, Atom};
27use crate::derived;
28use crate::effects::Changes;
29use crate::error::ModelError;
30use crate::eval::{EvalError, Evaluator, Scope};
31use crate::model::check::{self, Issue};
32use crate::model::universe::type_text;
33use crate::model::{self as model, Model};
34use crate::plan::{Plan, PlanStep};
35use crate::report::{
36    Construct, Metric, Outcome, Report, StepRef, StepTrace, Unsupported, Violation, ViolationKind,
37};
38use crate::state::State;
39
40/// Validates plans for one domain and problem.
41///
42/// Construction checks the domain and problem once; [`Validator::validate`] can then run
43/// any number of plans. Validation never panics, whatever the plan.
44///
45/// # Examples
46///
47/// ```
48/// use pddl::{Domain, Parser, Problem};
49/// use pddl_validate::{ValidationStatus, Validator};
50///
51/// let domain = Domain::from_str(
52///     "(define (domain switch) (:predicates (on))
53///        (:action flip :parameters () :precondition (not (on)) :effect (on)))",
54/// ).unwrap();
55/// let problem = Problem::from_str(
56///     "(define (problem light) (:domain switch) (:init) (:goal (on)))",
57/// ).unwrap();
58/// let validator = Validator::new(&domain, &problem).unwrap();
59///
60/// assert_eq!(validator.validate_text("(flip)").status(), ValidationStatus::Valid);
61///
62/// let report = validator.validate_text("(flip)\n(flip)");
63/// assert_eq!(report.status(), ValidationStatus::Invalid);
64/// assert_eq!(report.violation().unwrap().to_string(),
65///     "step 2 (flip): unsatisfied precondition: (not (on))");
66/// ```
67#[derive(Debug)]
68pub struct Validator<'a> {
69    /// The checked task, or why the validator cannot interpret it.
70    inner: Inner<'a>,
71    /// The relative tolerance of numeric comparisons; see [`Validator::with_tolerance`].
72    tolerance: f64,
73    /// The least time between interfering events; see [`Validator::with_epsilon`].
74    epsilon: f64,
75    /// The absolute tolerance of duration constraints; see
76    /// [`Validator::with_duration_tolerance`].
77    duration_tolerance: f64,
78}
79
80/// The default relative tolerance of numeric comparisons, `1e-12`.
81///
82/// Two values `a` and `b` count as equal when `|a - b| <= 1e-12 * max(1, |a|, |b|)`.
83/// Near zero that absorbs differences up to `1e-12`; elsewhere it absorbs the rounding
84/// of summing many decimal costs such as `0.1`. Integers below `1e12` differ by at least
85/// 1, more than the tolerance, so they compare exactly.
86/// [`Validator::with_tolerance(0.0)`](Validator::with_tolerance) compares exactly.
87pub const DEFAULT_TOLERANCE: f64 = 1e-12;
88
89/// The default least time between interfering events of a temporal plan, VAL's default.
90pub const DEFAULT_EPSILON: f64 = 0.01;
91
92/// The default absolute tolerance of duration constraints, `0.0005`.
93///
94/// Planners print durations with three decimals: `(= ?duration (/ (dist) 3))` with
95/// `(dist)` 10 comes out as `[3.333]`, 0.00033 below the exact value. Rounding to three
96/// decimals is off by at most 0.0005, so a duration within 0.0005 of the bound satisfies
97/// `=`, `<=` and `>=`; it also accepts a duration up to 0.0005 beyond a `<=` or `>=`
98/// bound. Shorter durations need a smaller tolerance:
99/// [`Validator::with_duration_tolerance(0.0)`](Validator::with_duration_tolerance) leaves
100/// only the relative numeric tolerance.
101pub const DEFAULT_DURATION_TOLERANCE: f64 = 0.0005;
102
103/// What [`Validator::new`] found.
104#[derive(Debug)]
105#[expect(
106    clippy::large_enum_variant,
107    reason = "one per validator, built once; boxing buys nothing"
108)]
109enum Inner<'a> {
110    /// A task the validator interprets.
111    Ready {
112        /// The indexed domain and problem.
113        model: Model<'a>,
114        /// The problem, for its goal.
115        problem: &'a Problem,
116        /// The initial state, derived atoms not yet computed.
117        initial: State,
118    },
119    /// A task that uses a construct the validator does not interpret.
120    Unsupported(Unsupported),
121}
122
123/// Why a step stops the plan.
124enum Stop {
125    /// The step is invalid.
126    Invalid(ViolationKind),
127    /// The step meets a construct the validator does not interpret.
128    Unsupported(Construct),
129}
130
131impl From<EvalError> for Stop {
132    fn from(error: EvalError) -> Self {
133        match error {
134            EvalError::Unsupported(construct) => Self::Unsupported(construct),
135            EvalError::Undefined(fluent) => Self::Invalid(ViolationKind::Undefined(fluent)),
136            EvalError::DivisionByZero(exp) => Self::Invalid(ViolationKind::DivisionByZero(exp)),
137            EvalError::NonFinite(exp) => Self::Invalid(ViolationKind::NonFinite(exp)),
138            EvalError::ConflictingUpdates(fluent) => {
139                Self::Invalid(ViolationKind::ConflictingUpdates(fluent))
140            }
141        }
142    }
143}
144
145impl<'a> Validator<'a> {
146    /// Checks `domain` and `problem` and prepares the initial state.
147    ///
148    /// A task that uses a construct the validator does not interpret yet, such as
149    /// preferences, still builds a validator, whose every report is
150    /// [`ValidationStatus::Unsupported`](crate::ValidationStatus::Unsupported).
151    ///
152    /// # Errors
153    ///
154    /// A [`ModelError`] if the problem is for another domain, or if a formula uses an
155    /// undeclared type, predicate, function, object or variable, applies a symbol to the
156    /// wrong number of arguments, or sets a derived predicate or `=`; also for two actions
157    /// of one name.
158    pub fn new(domain: &'a Domain, problem: &'a Problem) -> Result<Self, ModelError> {
159        model::check_domain_name(domain, problem)?;
160        if let Some(unsupported) = model::unsupported_sections(domain, problem) {
161            return Ok(Self::unsupported(unsupported));
162        }
163
164        let mut model = Model::new(domain, problem)?;
165        let checked =
166            check::check_function_types(domain).and_then(|()| check::check(&model, problem));
167        match checked {
168            Err(Issue::Model(error)) => return Err(error),
169            Err(Issue::Unsupported(unsupported)) => return Ok(Self::unsupported(unsupported)),
170            Ok(()) => {}
171        }
172
173        if let Err(unsupported) = derived::stratify(&mut model) {
174            return Ok(Self::unsupported(unsupported));
175        }
176
177        let initial = initial_state(&model, problem);
178
179        Ok(Self {
180            inner: Inner::Ready {
181                model,
182                problem,
183                initial,
184            },
185            tolerance: DEFAULT_TOLERANCE,
186            epsilon: DEFAULT_EPSILON,
187            duration_tolerance: DEFAULT_DURATION_TOLERANCE,
188        })
189    }
190
191    /// Builds a validator that reports `unsupported` for every plan.
192    const fn unsupported(unsupported: Unsupported) -> Self {
193        Self {
194            inner: Inner::Unsupported(unsupported),
195            tolerance: DEFAULT_TOLERANCE,
196            epsilon: DEFAULT_EPSILON,
197            duration_tolerance: DEFAULT_DURATION_TOLERANCE,
198        }
199    }
200
201    /// Sets the relative tolerance of numeric comparisons, [`DEFAULT_TOLERANCE`] unless
202    /// set.
203    ///
204    /// Two values `a` and `b` are equal if `|a - b| <= tolerance * max(1, |a|, |b|)`;
205    /// otherwise they compare as numbers. So `(= (x) 0.3)` holds after `(x)` was set to
206    /// 0.1 and increased by 0.2, and exactly one of `<`, `=` and `>` holds for any pair.
207    /// A tolerance of 0 compares exactly; a negative or NaN tolerance counts as 0.
208    ///
209    /// # Examples
210    ///
211    /// ```
212    /// use pddl::{Domain, Parser, Problem};
213    /// use pddl_validate::{ValidationStatus, Validator};
214    ///
215    /// let domain = Domain::from_str("(define (domain d) (:predicates (done)) (:functions (x))
216    ///     (:action add :parameters () :effect (increase (x) 0.2))
217    ///     (:action check :parameters () :precondition (= (x) 0.3) :effect (done)))").unwrap();
218    /// let problem = Problem::from_str("(define (problem p) (:domain d)
219    ///     (:init (= (x) 0.1)) (:goal (done)))").unwrap();
220    /// let validator = Validator::new(&domain, &problem).unwrap();
221    /// assert_eq!(validator.validate_text("(add) (check)").status(), ValidationStatus::Valid);
222    ///
223    /// let exact = validator.with_tolerance(0.0);
224    /// assert_eq!(exact.validate_text("(add) (check)").status(), ValidationStatus::Invalid);
225    /// ```
226    #[must_use]
227    pub fn with_tolerance(mut self, tolerance: f64) -> Self {
228        self.tolerance = if tolerance > 0.0 { tolerance } else { 0.0 };
229        self
230    }
231
232    /// Sets the least time between two interfering events of a temporal plan,
233    /// [`DEFAULT_EPSILON`] (VAL's default) unless set.
234    ///
235    /// Two events interfere (PDDL 2.1 mutex) when one changes an atom or fluent the other
236    /// reads or changes, except two `increase`/`decrease` updates of one fluent. Such
237    /// events must be at least `epsilon` apart; at the same time or closer, the plan is
238    /// invalid with [`ViolationKind::Interference`]. A negative or NaN epsilon counts
239    /// as 0, which forbids only simultaneous interference.
240    #[must_use]
241    pub fn with_epsilon(mut self, epsilon: f64) -> Self {
242        self.epsilon = if epsilon > 0.0 { epsilon } else { 0.0 };
243        self
244    }
245
246    /// Sets the absolute tolerance of a temporal plan's durations against the actions'
247    /// `:duration` constraints, [`DEFAULT_DURATION_TOLERANCE`] unless set.
248    ///
249    /// A duration `d` satisfies a constraint with bound `b` when `|d - b| <= tolerance`,
250    /// and otherwise compares as a number under [`Validator::with_tolerance`]. A negative
251    /// or NaN tolerance counts as 0.
252    #[must_use]
253    pub fn with_duration_tolerance(mut self, tolerance: f64) -> Self {
254        self.duration_tolerance = if tolerance > 0.0 { tolerance } else { 0.0 };
255        self
256    }
257
258    /// Parses `text` as a plan file and validates it.
259    ///
260    /// A plan file that cannot be read is [`ValidationStatus::Invalid`](crate::ValidationStatus::Invalid)
261    /// with [`ViolationKind::PlanSyntax`].
262    #[must_use]
263    pub fn validate_text(&self, text: &str) -> Report {
264        match text.parse::<Plan>() {
265            Ok(plan) => self.validate(&plan),
266            Err(error) => {
267                let violation = Violation {
268                    step: None,
269                    kind: ViolationKind::PlanSyntax(error),
270                };
271                Report::new(Outcome::Invalid(violation), Vec::new())
272            }
273        }
274    }
275
276    /// Runs `plan` from the initial state and checks the goal in the final state.
277    ///
278    /// Validation stops at the first violation, which the report names together with the
279    /// step, the failing condition and a repair hint.
280    #[must_use]
281    pub fn validate(&self, plan: &Plan) -> Report {
282        let (model, problem, initial) = match &self.inner {
283            Inner::Ready {
284                model,
285                problem,
286                initial,
287            } => (model, problem, initial),
288            Inner::Unsupported(unsupported) => {
289                return Report::new(Outcome::Unsupported(unsupported.clone()), Vec::new());
290            }
291        };
292
293        let tolerance = self.tolerance;
294        let timed = plan.steps().iter().any(|step| step.time().is_some());
295        if timed || model.is_temporal(problem) {
296            if !model.rules.is_empty() {
297                let construct = Construct::DerivedPredicatesInTemporalPlans;
298                let unsupported = Unsupported::new(construct, "domain");
299                return Report::new(Outcome::Unsupported(unsupported), Vec::new());
300            }
301
302            let timeline = temporal::Timeline {
303                model,
304                problem,
305                tolerance,
306                epsilon: self.epsilon,
307                duration_tolerance: self.duration_tolerance,
308            };
309            return timeline.run(initial, plan);
310        }
311
312        let mut state = initial.clone();
313        let mut trace = Vec::new();
314        if let Err(error) = derived::close(model, &mut state, tolerance) {
315            return stopped(Stop::from(error), None, String::from("init"), trace);
316        }
317
318        for (index, step) in plan.steps().iter().enumerate() {
319            let at = step_ref(index, step);
320            match run_step(model, &mut state, step, tolerance) {
321                Ok(mut changes) => {
322                    changes.step = Some(at);
323                    trace.push(changes);
324                }
325                Err(stop) => {
326                    let location = format!("step {}", at.number);
327                    return stopped(stop, Some(at), location, trace);
328                }
329            }
330        }
331
332        #[expect(
333            clippy::cast_precision_loss,
334            reason = "plans of more than 2^53 steps do not fit in memory"
335        )]
336        let total_time = plan.len() as f64;
337        let evaluator = Evaluator {
338            model,
339            state: &state,
340            tolerance,
341            observer: None,
342        };
343
344        finish(&evaluator, problem, total_time, trace)
345    }
346}
347
348/// Checks the goal in the final state and evaluates the metric, with `total-time` set
349/// to `total_time`. A metric whose value is undefined leaves the plan valid, without a
350/// metric value.
351fn finish(
352    evaluator: &Evaluator<'_, '_>,
353    problem: &Problem,
354    total_time: f64,
355    trace: Vec<StepTrace>,
356) -> Report {
357    match evaluator.preconditions(problem.goals(), &mut Scope::new()) {
358        Ok(None) => {}
359        Ok(Some(unmet)) => {
360            let kind = ViolationKind::GoalUnsatisfied(unmet);
361            return stopped(Stop::Invalid(kind), None, String::from("goal"), trace);
362        }
363        Err(error) => return stopped(Stop::from(error), None, String::from("goal"), trace),
364    }
365
366    let Some(spec) = problem.metric_spec() else {
367        return Report::new(Outcome::Valid, trace);
368    };
369
370    match evaluator.metric(spec.expression(), total_time) {
371        Ok(value) => Report::new(Outcome::Valid, trace).with_metric(Metric {
372            optimization: spec.optimization(),
373            value,
374        }),
375        Err(error) if error.is_unknown() => Report::new(Outcome::Valid, trace),
376        Err(error) => stopped(Stop::from(error), None, String::from("metric"), trace),
377    }
378}
379
380/// Names step `index` (from 0) for diagnostics.
381fn step_ref(index: usize, step: &PlanStep) -> StepRef {
382    StepRef {
383        number: index + 1,
384        line: step.line(),
385        action: alloc::string::ToString::to_string(step),
386        time: step.time(),
387    }
388}
389
390/// Builds the report of a plan that stopped at `step` (or at the goal, for `None`).
391fn stopped(reason: Stop, step: Option<StepRef>, location: String, trace: Vec<StepTrace>) -> Report {
392    match reason {
393        Stop::Invalid(kind) => Report::new(Outcome::Invalid(Violation { step, kind }), trace),
394        Stop::Unsupported(construct) => {
395            let unsupported = Unsupported::new(construct, location);
396            Report::new(Outcome::Unsupported(unsupported), Vec::new())
397        }
398    }
399}
400
401/// Applies one step to `state` and returns what it changed.
402fn run_step(
403    model: &Model<'_>,
404    state: &mut State,
405    step: &PlanStep,
406    tolerance: f64,
407) -> Result<StepTrace, Stop> {
408    let (action, mut scope) = bind(model, step)?;
409    if step.duration().is_some() {
410        return Err(Stop::Invalid(ViolationKind::UnexpectedDuration));
411    }
412
413    let evaluator = Evaluator {
414        model,
415        state: &*state,
416        tolerance,
417        observer: None,
418    };
419    if let Some(unmet) = evaluator.preconditions(action.precondition(), &mut scope)? {
420        return Err(Stop::Invalid(ViolationKind::PreconditionUnsatisfied(unmet)));
421    }
422
423    let mut changes = Changes::default();
424    if let Some(effects) = action.effect() {
425        changes.collect(&evaluator, effects, &mut scope)?;
426    }
427
428    let trace = changes.apply(state)?;
429    derived::close(model, state, tolerance)?;
430
431    Ok(trace)
432}
433
434/// Looks up the action of `step` and binds its parameters to the step's objects.
435fn bind<'m>(
436    model: &'m Model<'_>,
437    step: &PlanStep,
438) -> Result<(&'m pddl::ActionDefinition, Scope), Stop> {
439    let Some(action) = model.actions.get(step.action()) else {
440        let kind = ViolationKind::UnknownAction(String::from(step.action()));
441        return Err(Stop::Invalid(kind));
442    };
443
444    Ok((action, bind_parameters(model, action.parameters(), step)?))
445}
446
447/// Binds `parameters` to the objects of `step`, checking arity, objects and types.
448fn bind_parameters(
449    model: &Model<'_>,
450    parameters: &pddl::TypedVariables,
451    step: &PlanStep,
452) -> Result<Scope, Stop> {
453    let invalid = |kind| Err(Stop::Invalid(kind));
454    if parameters.len() != step.arguments().len() {
455        return invalid(ViolationKind::Arity {
456            expected: parameters.len(),
457            found: step.arguments().len(),
458        });
459    }
460
461    let mut scope = Scope::new();
462    for (parameter, object) in parameters.iter().zip(step.arguments()) {
463        let name = lower(parameter.value());
464        if !model.universe.contains(object) {
465            return invalid(ViolationKind::UnknownObject {
466                parameter: name,
467                object: object.clone(),
468            });
469        }
470
471        if !model.universe.is_of(object, parameter.type_()) {
472            return invalid(ViolationKind::TypeMismatch {
473                parameter: name,
474                object: object.clone(),
475                expected: type_text(parameter.type_()),
476            });
477        }
478
479        scope.push((name, object.clone()));
480    }
481
482    Ok(scope)
483}
484
485/// Builds the initial state from the problem's `:init`.
486///
487/// Negative literals are skipped: under the closed-world assumption they hold anyway.
488/// A nullary `total-cost` function that `:init` gives no value starts at 0, as Fast
489/// Downward assumes. The static check has rejected every element this validator cannot
490/// interpret.
491fn initial_state(model: &Model<'_>, problem: &Problem) -> State {
492    let mut state = State::default();
493    if model.functions.get(TOTAL_COST) == Some(&0) {
494        let total_cost = Atom::lowered(String::from(TOTAL_COST), Vec::new());
495        state.fluents.insert(total_cost, 0.0);
496    }
497
498    for element in problem.init().iter() {
499        match element {
500            InitElement::Literal(Literal::AtomicFormula(AtomicFormula::Predicate(atom))) => {
501                let arguments = atom.values().iter().map(|name| lower(name)).collect();
502                let atom = Atom::lowered(lower(atom.predicate()), arguments);
503                state.facts.insert(atom);
504            }
505            InitElement::IsValue(term, value) => {
506                let arguments = term.names().iter().map(|name| lower(name)).collect();
507                let fluent = Atom::lowered(lower(term.symbol()), arguments);
508                state.fluents.insert(fluent, **value);
509            }
510            InitElement::Literal(_) | InitElement::At(..) | InitElement::IsObject(..) => {}
511        }
512    }
513
514    state
515}
516
517/// The function that action costs accumulate in.
518const TOTAL_COST: &str = "total-cost";