Skip to main content

oxirs_rule/
truth_maintenance.rs

1/// Truth Maintenance System (TMS) for belief revision.
2///
3/// A classical JTMS (Justification-based Truth Maintenance System) that tracks
4/// beliefs (nodes) and their justifications. Retracting an axiom propagates
5/// the "unsupported" status to all transitively dependent nodes.
6use std::collections::{HashMap, HashSet};
7
8// ---------------------------------------------------------------------------
9// Public types
10// ---------------------------------------------------------------------------
11
12/// How a TMS node is justified.
13#[derive(Debug, Clone, PartialEq)]
14pub enum Justification {
15    /// The node is an axiom — always supported unless explicitly retracted.
16    Axiom,
17    /// The node is derived from one or more other nodes.
18    Derived {
19        /// Indices of nodes this node depends on.
20        from: Vec<usize>,
21    },
22}
23
24/// A single belief node in the TMS.
25#[derive(Debug, Clone)]
26pub struct TmsNode {
27    /// Unique identifier.
28    pub id: usize,
29    /// The statement this node represents (e.g. a fact, rule conclusion).
30    pub statement: String,
31    /// Whether this node is currently supported (believed).
32    pub supported: bool,
33    /// How this node is justified.
34    pub justification: Justification,
35}
36
37/// Justification-based Truth Maintenance System.
38///
39/// Nodes can be axioms (always-on unless retracted) or derived (supported
40/// only when all antecedent nodes are supported).
41#[derive(Debug, Default)]
42pub struct TruthMaintenanceSystem {
43    nodes: Vec<TmsNode>,
44    /// Set of node IDs that have been explicitly retracted.
45    assumptions: HashSet<usize>,
46}
47
48impl TruthMaintenanceSystem {
49    /// Create an empty TMS.
50    pub fn new() -> Self {
51        Self {
52            nodes: Vec::new(),
53            assumptions: HashSet::new(),
54        }
55    }
56
57    /// Add an axiom node.  Axiom nodes are always supported until retracted.
58    ///
59    /// Returns the new node's `id`.
60    pub fn add_axiom(&mut self, statement: impl Into<String>) -> usize {
61        let id = self.nodes.len();
62        self.nodes.push(TmsNode {
63            id,
64            statement: statement.into(),
65            supported: true,
66            justification: Justification::Axiom,
67        });
68        id
69    }
70
71    /// Add a derived node that is supported exactly when all nodes in `from`
72    /// are supported.
73    ///
74    /// Returns the new node's `id`.
75    pub fn add_derived(&mut self, statement: impl Into<String>, from: Vec<usize>) -> usize {
76        let id = self.nodes.len();
77        let supported = from
78            .iter()
79            .all(|&dep| self.nodes.get(dep).map(|n| n.supported).unwrap_or(false));
80        self.nodes.push(TmsNode {
81            id,
82            statement: statement.into(),
83            supported,
84            justification: Justification::Derived { from },
85        });
86        id
87    }
88
89    /// Retract (un-support) a node and propagate unsupport to all dependents.
90    pub fn retract(&mut self, node_id: usize) {
91        if node_id >= self.nodes.len() {
92            return;
93        }
94        self.assumptions.insert(node_id);
95        self.nodes[node_id].supported = false;
96        // Propagate transitively to all reachable dependents
97        let affected = self.reachable(node_id);
98        for dep_id in affected {
99            self.nodes[dep_id].supported = false;
100        }
101    }
102
103    /// Attempt to re-support a node that was previously retracted.
104    ///
105    /// For an axiom: re-supports unless still in the retraction set (but we
106    /// remove it from the set here).  For a derived node: re-supports only
107    /// when all antecedents are supported.
108    pub fn restore(&mut self, node_id: usize) {
109        if node_id >= self.nodes.len() {
110            return;
111        }
112        self.assumptions.remove(&node_id);
113        let supported = self.compute_supported(node_id);
114        self.nodes[node_id].supported = supported;
115        // Re-evaluate downstream nodes transitively
116        let downstream = self.reachable(node_id);
117        for dep_id in downstream {
118            let s = self.compute_supported(dep_id);
119            self.nodes[dep_id].supported = s;
120        }
121    }
122
123    /// Return whether node `node_id` is currently supported.
124    pub fn is_supported(&self, node_id: usize) -> bool {
125        self.nodes
126            .get(node_id)
127            .map(|n| n.supported)
128            .unwrap_or(false)
129    }
130
131    /// Count supported nodes.
132    pub fn supported_count(&self) -> usize {
133        self.nodes.iter().filter(|n| n.supported).count()
134    }
135
136    /// Count unsupported nodes.
137    pub fn unsupported_count(&self) -> usize {
138        self.nodes.iter().filter(|n| !n.supported).count()
139    }
140
141    /// Return all node IDs that **directly** depend on `node_id`.
142    pub fn dependents(&self, node_id: usize) -> Vec<usize> {
143        self.nodes
144            .iter()
145            .filter(|n| match &n.justification {
146                Justification::Derived { from } => from.contains(&node_id),
147                _ => false,
148            })
149            .map(|n| n.id)
150            .collect()
151    }
152
153    /// Return a slice of all nodes.
154    pub fn all_nodes(&self) -> &[TmsNode] {
155        &self.nodes
156    }
157
158    /// Return all node IDs transitively reachable from `root_id` via the
159    /// "depended-upon-by" relation (i.e. nodes that would be invalidated if
160    /// `root_id` were retracted).
161    pub fn reachable(&self, root_id: usize) -> Vec<usize> {
162        let mut visited = HashSet::new();
163        let mut stack = vec![root_id];
164        while let Some(current) = stack.pop() {
165            for dep in self.dependents(current) {
166                if visited.insert(dep) {
167                    stack.push(dep);
168                }
169            }
170        }
171        let mut result: Vec<usize> = visited.into_iter().collect();
172        result.sort_unstable();
173        result
174    }
175
176    // -----------------------------------------------------------------------
177    // Private helpers
178    // -----------------------------------------------------------------------
179
180    /// Recompute whether node `id` should be supported given current state.
181    fn compute_supported(&self, id: usize) -> bool {
182        if self.assumptions.contains(&id) {
183            return false;
184        }
185        match self.nodes.get(id) {
186            None => false,
187            Some(node) => match &node.justification {
188                Justification::Axiom => true,
189                Justification::Derived { from } => from.iter().all(|&dep| self.is_supported(dep)),
190            },
191        }
192    }
193
194    /// Build an index of node_id → indices of nodes that depend on it.
195    #[allow(dead_code)]
196    fn build_dependent_index(&self) -> HashMap<usize, Vec<usize>> {
197        let mut index: HashMap<usize, Vec<usize>> = HashMap::new();
198        for node in &self.nodes {
199            if let Justification::Derived { from } = &node.justification {
200                for &dep in from {
201                    index.entry(dep).or_default().push(node.id);
202                }
203            }
204        }
205        index
206    }
207}
208
209// ===========================================================================
210// Tests
211// ===========================================================================
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    // --- Basic construction ---
218    #[test]
219    fn test_new_tms_is_empty() {
220        let tms = TruthMaintenanceSystem::new();
221        assert_eq!(tms.all_nodes().len(), 0);
222        assert_eq!(tms.supported_count(), 0);
223        assert_eq!(tms.unsupported_count(), 0);
224    }
225
226    #[test]
227    fn test_add_axiom_returns_id() {
228        let mut tms = TruthMaintenanceSystem::new();
229        let id = tms.add_axiom("A");
230        assert_eq!(id, 0);
231    }
232
233    #[test]
234    fn test_axiom_is_supported() {
235        let mut tms = TruthMaintenanceSystem::new();
236        let id = tms.add_axiom("A");
237        assert!(tms.is_supported(id));
238    }
239
240    #[test]
241    fn test_multiple_axioms_ids_sequential() {
242        let mut tms = TruthMaintenanceSystem::new();
243        let a = tms.add_axiom("A");
244        let b = tms.add_axiom("B");
245        assert_eq!(a, 0);
246        assert_eq!(b, 1);
247    }
248
249    // --- Derived nodes ---
250    #[test]
251    fn test_derived_node_supported_when_deps_supported() {
252        let mut tms = TruthMaintenanceSystem::new();
253        let a = tms.add_axiom("A");
254        let b = tms.add_axiom("B");
255        let c = tms.add_derived("C", vec![a, b]);
256        assert!(tms.is_supported(c));
257    }
258
259    #[test]
260    fn test_derived_node_unsupported_when_dep_unsupported() {
261        let mut tms = TruthMaintenanceSystem::new();
262        let a = tms.add_axiom("A");
263        let b = tms.add_derived("B", vec![a]);
264        tms.retract(a);
265        assert!(!tms.is_supported(b));
266    }
267
268    #[test]
269    fn test_derived_node_with_no_deps_is_supported() {
270        let mut tms = TruthMaintenanceSystem::new();
271        let c = tms.add_derived("C", vec![]);
272        assert!(tms.is_supported(c));
273    }
274
275    // --- Retraction ---
276    #[test]
277    fn test_retract_axiom() {
278        let mut tms = TruthMaintenanceSystem::new();
279        let id = tms.add_axiom("A");
280        tms.retract(id);
281        assert!(!tms.is_supported(id));
282    }
283
284    #[test]
285    fn test_retract_propagates_one_level() {
286        let mut tms = TruthMaintenanceSystem::new();
287        let a = tms.add_axiom("A");
288        let b = tms.add_derived("B <- A", vec![a]);
289        tms.retract(a);
290        assert!(!tms.is_supported(a));
291        assert!(!tms.is_supported(b));
292    }
293
294    #[test]
295    fn test_retract_propagates_two_levels() {
296        let mut tms = TruthMaintenanceSystem::new();
297        let a = tms.add_axiom("A");
298        let b = tms.add_derived("B <- A", vec![a]);
299        let c = tms.add_derived("C <- B", vec![b]);
300        tms.retract(a);
301        assert!(!tms.is_supported(b));
302        assert!(!tms.is_supported(c));
303    }
304
305    #[test]
306    fn test_retract_does_not_affect_unrelated() {
307        let mut tms = TruthMaintenanceSystem::new();
308        let a = tms.add_axiom("A");
309        let b = tms.add_axiom("B");
310        tms.retract(a);
311        assert!(!tms.is_supported(a));
312        assert!(tms.is_supported(b));
313    }
314
315    #[test]
316    fn test_retract_invalid_id_is_noop() {
317        let mut tms = TruthMaintenanceSystem::new();
318        tms.retract(999); // Should not panic
319    }
320
321    // --- Restore ---
322    #[test]
323    fn test_restore_axiom() {
324        let mut tms = TruthMaintenanceSystem::new();
325        let a = tms.add_axiom("A");
326        tms.retract(a);
327        tms.restore(a);
328        assert!(tms.is_supported(a));
329    }
330
331    #[test]
332    fn test_restore_propagates_to_derived() {
333        let mut tms = TruthMaintenanceSystem::new();
334        let a = tms.add_axiom("A");
335        let b = tms.add_derived("B <- A", vec![a]);
336        tms.retract(a);
337        assert!(!tms.is_supported(b));
338        tms.restore(a);
339        assert!(tms.is_supported(a));
340        assert!(tms.is_supported(b));
341    }
342
343    #[test]
344    fn test_restore_does_not_restore_if_other_dep_still_retracted() {
345        let mut tms = TruthMaintenanceSystem::new();
346        let a = tms.add_axiom("A");
347        let b = tms.add_axiom("B");
348        let c = tms.add_derived("C <- A, B", vec![a, b]);
349        tms.retract(a);
350        tms.retract(b);
351        tms.restore(a);
352        // c still depends on b which is retracted
353        assert!(!tms.is_supported(c));
354    }
355
356    // --- supported_count / unsupported_count ---
357    #[test]
358    fn test_counts_after_retract() {
359        let mut tms = TruthMaintenanceSystem::new();
360        let a = tms.add_axiom("A");
361        let _b = tms.add_axiom("B");
362        let _c = tms.add_derived("C <- A", vec![a]);
363        tms.retract(a);
364        assert_eq!(tms.supported_count(), 1); // only B
365        assert_eq!(tms.unsupported_count(), 2); // A and C
366    }
367
368    #[test]
369    fn test_counts_all_supported() {
370        let mut tms = TruthMaintenanceSystem::new();
371        let _a = tms.add_axiom("A");
372        let _b = tms.add_axiom("B");
373        assert_eq!(tms.supported_count(), 2);
374        assert_eq!(tms.unsupported_count(), 0);
375    }
376
377    // --- dependents ---
378    #[test]
379    fn test_dependents_empty_when_none() {
380        let mut tms = TruthMaintenanceSystem::new();
381        let a = tms.add_axiom("A");
382        assert!(tms.dependents(a).is_empty());
383    }
384
385    #[test]
386    fn test_dependents_returns_derived_nodes() {
387        let mut tms = TruthMaintenanceSystem::new();
388        let a = tms.add_axiom("A");
389        let b = tms.add_derived("B <- A", vec![a]);
390        let c = tms.add_derived("C <- A", vec![a]);
391        let mut deps = tms.dependents(a);
392        deps.sort_unstable();
393        assert_eq!(deps, vec![b, c]);
394    }
395
396    // --- reachable ---
397    #[test]
398    fn test_reachable_empty() {
399        let mut tms = TruthMaintenanceSystem::new();
400        let a = tms.add_axiom("A");
401        assert!(tms.reachable(a).is_empty());
402    }
403
404    #[test]
405    fn test_reachable_chain() {
406        let mut tms = TruthMaintenanceSystem::new();
407        let a = tms.add_axiom("A");
408        let b = tms.add_derived("B <- A", vec![a]);
409        let c = tms.add_derived("C <- B", vec![b]);
410        let reachable = tms.reachable(a);
411        assert!(reachable.contains(&b));
412        assert!(reachable.contains(&c));
413    }
414
415    #[test]
416    fn test_reachable_diamond() {
417        let mut tms = TruthMaintenanceSystem::new();
418        let a = tms.add_axiom("A");
419        let b = tms.add_derived("B <- A", vec![a]);
420        let c = tms.add_derived("C <- A", vec![a]);
421        let d = tms.add_derived("D <- B, C", vec![b, c]);
422        let reachable = tms.reachable(a);
423        assert!(reachable.contains(&b));
424        assert!(reachable.contains(&c));
425        assert!(reachable.contains(&d));
426        assert_eq!(reachable.len(), 3);
427    }
428
429    // --- all_nodes ---
430    #[test]
431    fn test_all_nodes_returns_correct_slice() {
432        let mut tms = TruthMaintenanceSystem::new();
433        tms.add_axiom("A");
434        tms.add_axiom("B");
435        let nodes = tms.all_nodes();
436        assert_eq!(nodes.len(), 2);
437        assert_eq!(nodes[0].statement, "A");
438        assert_eq!(nodes[1].statement, "B");
439    }
440
441    // --- justification content ---
442    #[test]
443    fn test_axiom_justification() {
444        let mut tms = TruthMaintenanceSystem::new();
445        let a = tms.add_axiom("A");
446        assert_eq!(tms.all_nodes()[a].justification, Justification::Axiom);
447    }
448
449    #[test]
450    fn test_derived_justification_from_ids() {
451        let mut tms = TruthMaintenanceSystem::new();
452        let a = tms.add_axiom("A");
453        let b = tms.add_derived("B", vec![a]);
454        assert_eq!(
455            tms.all_nodes()[b].justification,
456            Justification::Derived { from: vec![a] }
457        );
458    }
459
460    // --- is_supported for out-of-range id ---
461    #[test]
462    fn test_is_supported_out_of_range() {
463        let tms = TruthMaintenanceSystem::new();
464        assert!(!tms.is_supported(999));
465    }
466
467    // --- Double retract is safe ---
468    #[test]
469    fn test_double_retract_is_idempotent() {
470        let mut tms = TruthMaintenanceSystem::new();
471        let a = tms.add_axiom("A");
472        tms.retract(a);
473        tms.retract(a);
474        assert!(!tms.is_supported(a));
475    }
476
477    // --- Restore then retract ---
478    #[test]
479    fn test_restore_then_retract() {
480        let mut tms = TruthMaintenanceSystem::new();
481        let a = tms.add_axiom("A");
482        tms.retract(a);
483        tms.restore(a);
484        assert!(tms.is_supported(a));
485        tms.retract(a);
486        assert!(!tms.is_supported(a));
487    }
488}