picteach 0.1.0

Explainable acceptance policies, tolerance rules, and composable decisions
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
//! Explainable rules for deciding what is acceptable.
//!
//! `picteach` treats acceptance as a named policy rather than a bare boolean.
//! A policy returns a decision tree that records which rules accepted or
//! rejected a value. Policies can be combined with all, any, and not.
//!
//! # Example
//!
//! ```
//! use picteach::Policy;
//!
//! let temperature = Policy::inclusive_range("comfortable", 18.0, 26.0)?;
//! let near_target = Policy::absolute_tolerance("near 22°C", 22.0, 0.5)?;
//! let acceptable = Policy::any("room temperature", [temperature, near_target])?;
//!
//! let decision = acceptable.evaluate(&25.0);
//! assert!(decision.is_accepted());
//! assert_eq!(decision.children().len(), 2);
//! # Ok::<(), picteach::Error>(())
//! ```

#![forbid(unsafe_code)]
#![warn(missing_docs)]

use std::error::Error as StdError;
use std::fmt;
use std::sync::Arc;

/// Whether a policy accepted or rejected a value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Status {
    /// The value satisfied the policy.
    Accepted,
    /// The value did not satisfy the policy.
    Rejected,
}

impl Status {
    /// Returns `true` for [`Status::Accepted`].
    pub const fn is_accepted(self) -> bool {
        matches!(self, Self::Accepted)
    }
}

/// An explainable policy result, optionally containing child results.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Decision {
    policy: String,
    status: Status,
    explanation: String,
    children: Vec<Decision>,
}

impl Decision {
    /// Creates a leaf decision.
    pub fn leaf(policy: impl Into<String>, status: Status, explanation: impl Into<String>) -> Self {
        Self {
            policy: policy.into(),
            status,
            explanation: explanation.into(),
            children: Vec::new(),
        }
    }

    fn composite(
        policy: String,
        status: Status,
        explanation: impl Into<String>,
        children: Vec<Self>,
    ) -> Self {
        Self {
            policy,
            status,
            explanation: explanation.into(),
            children,
        }
    }

    /// Returns the policy name.
    pub fn policy(&self) -> &str {
        &self.policy
    }

    /// Returns the accepted/rejected status.
    pub const fn status(&self) -> Status {
        self.status
    }

    /// Returns whether the decision was accepted.
    pub const fn is_accepted(&self) -> bool {
        self.status.is_accepted()
    }

    /// Returns a human-readable reason.
    pub fn explanation(&self) -> &str {
        &self.explanation
    }

    /// Returns evaluated child policies in declaration order.
    pub fn children(&self) -> &[Self] {
        &self.children
    }

    /// Visits this decision and all descendants in pre-order.
    pub fn walk(&self) -> impl Iterator<Item = &Self> {
        DecisionWalk { stack: vec![self] }
    }
}

struct DecisionWalk<'a> {
    stack: Vec<&'a Decision>,
}

impl<'a> Iterator for DecisionWalk<'a> {
    type Item = &'a Decision;

    fn next(&mut self) -> Option<Self::Item> {
        let current = self.stack.pop()?;
        self.stack.extend(current.children.iter().rev());
        Some(current)
    }
}

type Evaluator<T> = dyn Fn(&T) -> Decision + Send + Sync + 'static;

/// A cloneable, thread-safe acceptance rule for values of type `T`.
pub struct Policy<T> {
    name: String,
    evaluator: Arc<Evaluator<T>>,
}

impl<T> Clone for Policy<T> {
    fn clone(&self) -> Self {
        Self {
            name: self.name.clone(),
            evaluator: Arc::clone(&self.evaluator),
        }
    }
}

impl<T> fmt::Debug for Policy<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Policy").field("name", &self.name).finish()
    }
}

impl<T: 'static> Policy<T> {
    /// Creates a leaf policy from a predicate and a fixed expectation message.
    pub fn allow_if(
        name: impl Into<String>,
        expectation: impl Into<String>,
        predicate: impl Fn(&T) -> bool + Send + Sync + 'static,
    ) -> Result<Self, Error> {
        let name = valid_name(name.into())?;
        let expectation = expectation.into();
        let decision_name = name.clone();
        let evaluator = move |value: &T| {
            let status = if predicate(value) {
                Status::Accepted
            } else {
                Status::Rejected
            };
            Decision::leaf(decision_name.clone(), status, expectation.clone())
        };
        Ok(Self {
            name,
            evaluator: Arc::new(evaluator),
        })
    }

    /// Creates a leaf policy whose predicate also explains each result.
    pub fn explain_with(
        name: impl Into<String>,
        evaluator: impl Fn(&T) -> (bool, String) + Send + Sync + 'static,
    ) -> Result<Self, Error> {
        let name = valid_name(name.into())?;
        let decision_name = name.clone();
        Ok(Self {
            name,
            evaluator: Arc::new(move |value| {
                let (accepted, explanation) = evaluator(value);
                let status = if accepted {
                    Status::Accepted
                } else {
                    Status::Rejected
                };
                Decision::leaf(decision_name.clone(), status, explanation)
            }),
        })
    }

    /// Creates a policy that accepts only when every child accepts.
    ///
    /// All children are evaluated so the returned tree contains a complete
    /// explanation rather than stopping at the first rejection.
    pub fn all(
        name: impl Into<String>,
        policies: impl IntoIterator<Item = Self>,
    ) -> Result<Self, Error> {
        Self::combine(name.into(), policies, Composite::All)
    }

    /// Creates a policy that accepts when at least one child accepts.
    /// All children are evaluated for a complete explanation.
    pub fn any(
        name: impl Into<String>,
        policies: impl IntoIterator<Item = Self>,
    ) -> Result<Self, Error> {
        Self::combine(name.into(), policies, Composite::Any)
    }

    fn combine(
        name: String,
        policies: impl IntoIterator<Item = Self>,
        mode: Composite,
    ) -> Result<Self, Error> {
        let name = valid_name(name)?;
        let policies: Vec<Self> = policies.into_iter().collect();
        if policies.is_empty() {
            return Err(Error::EmptyComposite);
        }
        let decision_name = name.clone();
        Ok(Self {
            name,
            evaluator: Arc::new(move |value| {
                let children: Vec<_> = policies.iter().map(|rule| rule.evaluate(value)).collect();
                let accepted = match mode {
                    Composite::All => children.iter().all(Decision::is_accepted),
                    Composite::Any => children.iter().any(Decision::is_accepted),
                };
                let (status, explanation) = match (mode, accepted) {
                    (Composite::All, true) => (Status::Accepted, "all child policies accepted"),
                    (Composite::All, false) => {
                        (Status::Rejected, "one or more child policies rejected")
                    }
                    (Composite::Any, true) => {
                        (Status::Accepted, "one or more child policies accepted")
                    }
                    (Composite::Any, false) => (Status::Rejected, "all child policies rejected"),
                };
                Decision::composite(decision_name.clone(), status, explanation, children)
            }),
        })
    }

    /// Creates a policy with the opposite result of this policy.
    pub fn not(self, name: impl Into<String>) -> Result<Self, Error> {
        let name = valid_name(name.into())?;
        let decision_name = name.clone();
        Ok(Self {
            name,
            evaluator: Arc::new(move |value| {
                let child = self.evaluate(value);
                let status = if child.is_accepted() {
                    Status::Rejected
                } else {
                    Status::Accepted
                };
                Decision::composite(
                    decision_name.clone(),
                    status,
                    "child policy result was inverted",
                    vec![child],
                )
            }),
        })
    }

    /// Evaluates a value and returns an explainable decision tree.
    pub fn evaluate(&self, value: &T) -> Decision {
        (self.evaluator)(value)
    }

    /// Returns the policy name.
    pub fn name(&self) -> &str {
        &self.name
    }
}

impl<T> Policy<T>
where
    T: PartialOrd + fmt::Display + Send + Sync + Copy + 'static,
{
    /// Accepts values in the inclusive interval `[minimum, maximum]`.
    pub fn inclusive_range(name: impl Into<String>, minimum: T, maximum: T) -> Result<Self, Error> {
        if minimum > maximum {
            return Err(Error::ReversedRange);
        }
        Self::explain_with(name, move |value| {
            (
                *value >= minimum && *value <= maximum,
                format!("expected {minimum} <= value <= {maximum}; observed {value}"),
            )
        })
    }

    /// Accepts values in the exclusive interval `(minimum, maximum)`.
    pub fn exclusive_range(name: impl Into<String>, minimum: T, maximum: T) -> Result<Self, Error> {
        if minimum >= maximum {
            return Err(Error::ReversedRange);
        }
        Self::explain_with(name, move |value| {
            (
                *value > minimum && *value < maximum,
                format!("expected {minimum} < value < {maximum}; observed {value}"),
            )
        })
    }
}

impl Policy<f64> {
    /// Accepts finite values within an absolute distance of a finite target.
    pub fn absolute_tolerance(
        name: impl Into<String>,
        target: f64,
        tolerance: f64,
    ) -> Result<Self, Error> {
        validate_float_rule(target, tolerance)?;
        Self::explain_with(name, move |value| {
            let distance = (*value - target).abs();
            let accepted = value.is_finite() && distance <= tolerance;
            (
                accepted,
                format!(
                    "absolute distance {distance} must be <= {tolerance} around target {target}"
                ),
            )
        })
    }

    /// Accepts finite values within a fraction of a finite target.
    ///
    /// `absolute_floor` prevents a zero or tiny target from creating an
    /// unusably small tolerance. The effective tolerance is the greater of
    /// `abs(target) * fraction` and `absolute_floor`.
    pub fn relative_tolerance(
        name: impl Into<String>,
        target: f64,
        fraction: f64,
        absolute_floor: f64,
    ) -> Result<Self, Error> {
        validate_float_rule(target, fraction)?;
        if !absolute_floor.is_finite() || absolute_floor < 0.0 {
            return Err(Error::InvalidTolerance(absolute_floor));
        }
        let tolerance = (target.abs() * fraction).max(absolute_floor);
        if !tolerance.is_finite() {
            return Err(Error::InvalidTolerance(tolerance));
        }
        Self::explain_with(name, move |value| {
            let distance = (*value - target).abs();
            (
                value.is_finite() && distance <= tolerance,
                format!(
                    "relative distance {distance} must be <= {tolerance} around target {target}"
                ),
            )
        })
    }
}

#[derive(Debug, Clone, Copy)]
enum Composite {
    All,
    Any,
}

/// Errors raised while constructing an acceptance policy.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Error {
    /// A policy name contained only whitespace.
    EmptyName,
    /// An `all` or `any` policy was created without children.
    EmptyComposite,
    /// Range boundaries were reversed, or an exclusive range was empty.
    ReversedRange,
    /// A tolerance was negative or non-finite.
    InvalidTolerance(f64),
    /// A numeric target was non-finite.
    NonFiniteTarget(f64),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyName => f.write_str("policy name cannot be empty"),
            Self::EmptyComposite => f.write_str("composite policy needs at least one child"),
            Self::ReversedRange => f.write_str("range boundaries are reversed or empty"),
            Self::InvalidTolerance(value) => write!(f, "invalid tolerance: {value}"),
            Self::NonFiniteTarget(value) => write!(f, "target must be finite: {value}"),
        }
    }
}

impl StdError for Error {}

fn valid_name(name: String) -> Result<String, Error> {
    if name.trim().is_empty() {
        Err(Error::EmptyName)
    } else {
        Ok(name)
    }
}

fn validate_float_rule(target: f64, tolerance: f64) -> Result<(), Error> {
    if !target.is_finite() {
        return Err(Error::NonFiniteTarget(target));
    }
    if !tolerance.is_finite() || tolerance < 0.0 {
        return Err(Error::InvalidTolerance(tolerance));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn absolute_tolerance_includes_boundary_and_rejects_nan() {
        let policy = Policy::absolute_tolerance("sensor", 10.0, 0.25).unwrap();
        assert!(policy.evaluate(&10.25).is_accepted());
        assert!(!policy.evaluate(&10.251).is_accepted());
        assert!(!policy.evaluate(&f64::NAN).is_accepted());
    }

    #[test]
    fn relative_tolerance_uses_absolute_floor_near_zero() {
        let policy = Policy::relative_tolerance("zero", 0.0, 0.05, 0.01).unwrap();
        assert!(policy.evaluate(&0.009).is_accepted());
        assert!(!policy.evaluate(&0.011).is_accepted());
    }

    #[test]
    fn inclusive_and_exclusive_ranges_have_clear_boundaries() {
        let inclusive = Policy::inclusive_range("inclusive", 1, 3).unwrap();
        let exclusive = Policy::exclusive_range("exclusive", 1, 3).unwrap();
        assert!(inclusive.evaluate(&1).is_accepted());
        assert!(!exclusive.evaluate(&1).is_accepted());
        assert!(exclusive.evaluate(&2).is_accepted());
    }

    #[test]
    fn all_evaluates_every_child_for_explanation() {
        let positive = Policy::allow_if("positive", "must be positive", |v: &i32| *v > 0).unwrap();
        let even = Policy::allow_if("even", "must be even", |v: &i32| *v % 2 == 0).unwrap();
        let policy = Policy::all("valid number", [positive, even]).unwrap();
        let result = policy.evaluate(&-3);
        assert!(!result.is_accepted());
        assert_eq!(result.children().len(), 2);
        assert!(result.children().iter().all(|child| !child.is_accepted()));
    }

    #[test]
    fn any_accepts_one_matching_child() {
        let small = Policy::inclusive_range("small", 0, 10).unwrap();
        let large = Policy::inclusive_range("large", 90, 100).unwrap();
        let policy = Policy::any("edge", [small, large]).unwrap();
        assert!(policy.evaluate(&95).is_accepted());
        assert!(!policy.evaluate(&50).is_accepted());
    }

    #[test]
    fn not_inverts_and_preserves_child_result() {
        let empty = Policy::allow_if("empty", "must be empty", String::is_empty).unwrap();
        let non_empty = empty.not("non-empty").unwrap();
        let result = non_empty.evaluate(&"hello".to_owned());
        assert!(result.is_accepted());
        assert_eq!(result.children()[0].policy(), "empty");
    }

    #[test]
    fn decision_walk_is_preorder() {
        let a = Policy::allow_if("a", "a", |_: &()| true).unwrap();
        let b = Policy::allow_if("b", "b", |_: &()| true).unwrap();
        let root = Policy::all("root", [a, b]).unwrap().evaluate(&());
        let names: Vec<_> = root.walk().map(Decision::policy).collect();
        assert_eq!(names, ["root", "a", "b"]);
    }

    #[test]
    fn invalid_policy_definitions_are_rejected() {
        assert!(matches!(
            Policy::<i32>::all("empty", []),
            Err(Error::EmptyComposite)
        ));
        assert!(matches!(
            Policy::absolute_tolerance("bad", 1.0, -1.0),
            Err(Error::InvalidTolerance(_))
        ));
        assert!(matches!(
            Policy::relative_tolerance("overflow", f64::MAX, 2.0, 0.0),
            Err(Error::InvalidTolerance(_))
        ));
        assert!(matches!(
            Policy::inclusive_range("backwards", 3, 1),
            Err(Error::ReversedRange)
        ));
    }
}