Skip to main content

datalog_structural_model/termination/
graph.rs

1//! The position graph and [`Program::check_weak_acyclicity`].
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use super::criterion::TerminationCriterion;
6use super::edge::{ArgumentPosition, InventionKind, SpecialEdge};
7use super::sources::VariableSources;
8use super::verdict::WeakAcyclicity;
9use super::violation::TerminationViolation;
10use crate::EqualityMode;
11use crate::ir::{Atom, Program, RuleHead, Term, VariableSymbol};
12use crate::position::{AtomSlot, HeadAtomPath, RuleIndex, RuleSite};
13use crate::scc::SuccessorGraph;
14use crate::stratify::overlaps;
15
16/// Nodes are predicate positions; an edge carries a value from a body
17/// position to a head position, specially when the head invents a value.
18#[derive(Debug, Default)]
19struct PositionGraph {
20    equality_mode: EqualityMode,
21    // bounded: one node per distinct position of the finite program.
22    ids: BTreeMap<ArgumentPosition, usize>,
23    positions: Vec<ArgumentPosition>,
24    // bounded: edges are pairs of authored occurrences, never facts.
25    successors: Vec<Vec<(usize, bool)>>,
26    special: Vec<SpecialEdge>,
27}
28
29impl PositionGraph {
30    fn build(program: &Program, equality_mode: EqualityMode) -> Self {
31        let mut graph = Self {
32            equality_mode,
33            ..Self::default()
34        };
35        // bounded: one scope per rule of the finite program.
36        let scopes: Vec<_> = program
37            .rules
38            .iter()
39            .enumerate()
40            .map(|(index, rule)| VariableSources::of_body(RuleIndex::new(index), &rule.body))
41            .collect();
42        for (index, (rule, sources)) in program.rules.iter().zip(&scopes).enumerate() {
43            let head = HeadOccurrences::new(RuleIndex::new(index), &rule.head);
44            graph.add_head(&head, sources);
45        }
46        for (producer, rule) in program.rules.iter().enumerate() {
47            let head = HeadOccurrences::new(RuleIndex::new(producer), &rule.head);
48            graph.add_flows(&head, &scopes);
49        }
50        graph
51    }
52
53    fn node(&mut self, position: &ArgumentPosition) -> usize {
54        if let Some(&id) = self.ids.get(position) {
55            return id;
56        }
57        let id = self.positions.len();
58        self.ids.insert(position.clone(), id);
59        self.positions.push(position.clone());
60        self.successors.push(Vec::new());
61        id
62    }
63
64    fn edge(
65        &mut self,
66        from: &ArgumentPosition,
67        to: &ArgumentPosition,
68        kind: Option<InventionKind>,
69    ) {
70        let source = self.node(from);
71        let target = self.node(to);
72        self.successors[source].push((target, kind.is_some()));
73        if let Some(kind) = kind {
74            self.special.push(SpecialEdge {
75                from: from.clone(),
76                to: to.clone(),
77                kind,
78            });
79        }
80    }
81
82    /// Edges inside one rule, from the body positions binding each head
83    /// variable to the head slot holding it. An existential variable has no
84    /// body source; like a Skolem term over the frontier, it gets a special
85    /// edge from every body position binding a frontier variable.
86    fn add_head(&mut self, head: &HeadOccurrences<'_>, sources: &VariableSources<'_>) {
87        for (path, atom) in head.head.atoms() {
88            for (slot, term) in atom.terms.iter().enumerate() {
89                let to = head.position(path, atom, slot);
90                self.node(&to);
91                let wrapper = match term {
92                    Term::Variable(_) | Term::Constant(_) => None,
93                    Term::TripleTerm(_) => Some(InventionKind::TripleTerm),
94                    Term::Skolem { .. } => Some(InventionKind::Skolem),
95                };
96                let mut existential = false;
97                term.visit_variables(&mut |variable| {
98                    existential |= head.head.is_existential(variable);
99                    if let Some(kind) = sources.clock_invention(variable) {
100                        // A clock may produce a fresh value at each firing,
101                        // even without data arguments. Every positive body
102                        // atom controls whether this firing occurs.
103                        for body in &sources.atoms {
104                            for slot in 0..body.atom.arity() {
105                                self.edge(
106                                    &body.position(head.rule, slot),
107                                    &to,
108                                    Some(wrapper.unwrap_or(kind)),
109                                );
110                            }
111                        }
112                    }
113                    for source in sources.of(variable) {
114                        self.edge(&source.position, &to, wrapper.or(source.invention));
115                    }
116                });
117                if existential {
118                    for variable in head.frontier() {
119                        for source in sources.of(&variable) {
120                            self.edge(&source.position, &to, Some(InventionKind::Existential));
121                        }
122                    }
123                }
124            }
125        }
126    }
127
128    /// Ordinary edges from a head slot to the same slot of every positive
129    /// body atom, in any rule, whose pattern can match the head's facts.
130    fn add_flows(&mut self, head: &HeadOccurrences<'_>, scopes: &[VariableSources<'_>]) {
131        let mode = self.equality_mode;
132        for (path, atom) in head.head.atoms() {
133            for (consumer, scope) in scopes.iter().enumerate() {
134                for body in scope.atoms.iter().filter(|body| match mode {
135                    EqualityMode::Default => overlaps(atom, body.atom),
136                    EqualityMode::SameAs => {
137                        atom.predicate == body.atom.predicate && atom.arity() == body.atom.arity()
138                    }
139                }) {
140                    for slot in 0..atom.arity() {
141                        let from = head.position(path, atom, slot);
142                        let to = body.position(RuleIndex::new(consumer), slot);
143                        self.edge(&from, &to, None);
144                    }
145                }
146            }
147        }
148    }
149
150    fn component_of(&self, sccs: &[BTreeSet<usize>]) -> Vec<usize> {
151        // bounded: one component id per position of the finite program.
152        let mut component = vec![0; self.positions.len()];
153        for (index, members) in sccs.iter().enumerate() {
154            for &node in members {
155                component[node] = index;
156            }
157        }
158        component
159    }
160
161    fn violation(
162        &self,
163        sccs: &[BTreeSet<usize>],
164        component: &[usize],
165    ) -> Option<TerminationViolation> {
166        let edge = self
167            .special
168            .iter()
169            .filter(|edge| component[self.ids[&edge.from]] == component[self.ids[&edge.to]])
170            .min()?;
171        let members = &sccs[component[self.ids[&edge.from]]];
172        let positions = members
173            .iter()
174            .map(|&id| self.positions[id].clone())
175            .collect();
176        Some(TerminationViolation::new(
177            TerminationCriterion::WeaklyAcyclic,
178            self.equality_mode,
179            edge.clone(),
180            positions,
181        ))
182    }
183
184    /// Longest special-edge count over the acyclic condensation. Tarjan
185    /// emits sinks first, so walking components in reverse settles every
186    /// predecessor before its successors.
187    fn certificate(&self, sccs: &[BTreeSet<usize>], component: &[usize]) -> WeakAcyclicity {
188        let mut rank = vec![0_usize; sccs.len()];
189        for index in (0..sccs.len()).rev() {
190            for &node in &sccs[index] {
191                for &(target, special) in &self.successors[node] {
192                    let target = component[target];
193                    if target != index {
194                        rank[target] = rank[target].max(rank[index] + usize::from(special));
195                    }
196                }
197            }
198        }
199        let skolem_depth = rank.iter().copied().max().unwrap_or(0);
200        let deepest = (skolem_depth > 0)
201            .then(|| {
202                self.ids
203                    .iter()
204                    .find(|&(_, &id)| rank[component[id]] == skolem_depth)
205                    .map(|(position, _)| position.clone())
206            })
207            .flatten();
208        WeakAcyclicity {
209            law_version: TerminationCriterion::WeaklyAcyclic.law_version(),
210            equality_mode: self.equality_mode,
211            positions: self.positions.len(),
212            special_edges: self.special.len(),
213            skolem_depth,
214            deepest,
215        }
216    }
217}
218
219/// The head of one rule, whose atom slots are graph nodes.
220struct HeadOccurrences<'a> {
221    rule: RuleIndex,
222    head: &'a RuleHead,
223}
224
225impl<'a> HeadOccurrences<'a> {
226    fn new(rule: RuleIndex, head: &'a RuleHead) -> Self {
227        Self { rule, head }
228    }
229
230    fn position(&self, path: HeadAtomPath, atom: &Atom, slot: usize) -> ArgumentPosition {
231        ArgumentPosition::new(
232            atom.predicate.clone(),
233            AtomSlot::new(slot),
234            self.rule,
235            RuleSite::Head(path),
236        )
237    }
238
239    /// Head variables that are not existential: the values a witness
240    /// depends on.
241    fn frontier(&self) -> impl Iterator<Item = VariableSymbol> + '_ {
242        self.head
243            .variables()
244            .into_iter()
245            .filter(|variable| !self.head.is_existential(variable))
246    }
247}
248
249impl SuccessorGraph for PositionGraph {
250    fn node_count(&self) -> usize {
251        self.positions.len()
252    }
253
254    fn successor(&self, node: usize, nth: usize) -> Option<usize> {
255        self.successors[node].get(nth).map(|&(target, _)| target)
256    }
257}
258
259impl Program {
260    /// Check [`TerminationCriterion::WeaklyAcyclic`] on the position graph.
261    ///
262    /// Nodes are argument slots of atom occurrences. Inside a rule, a head
263    /// variable copied directly from a body slot adds an ordinary edge; a
264    /// head value built by a Skolem term, a triple term, a `BIND` or an
265    /// aggregate adds a special edge from each body slot feeding it. A
266    /// clock-dependent value also receives special edges from every positive
267    /// body slot controlling its firing, including later body atoms. A head
268    /// slot holding an existential variable is treated like a Skolem term over
269    /// the frontier: a special edge arrives from every body slot binding a
270    /// non-existential head variable. Every atom of a conjunctive,
271    /// existential or disjunctive head is its own occurrence. Across
272    /// rules, a head slot feeds the same slot of every positive body atom
273    /// whose complete pattern can match the head, so constants that keep two
274    /// patterns apart break the cycle. The program is weakly acyclic when no
275    /// special edge lies on a cycle, which bounds the nesting of invented
276    /// values and so the number of derivable facts.
277    ///
278    /// The analysis reads only the program: its time and memory are bounded
279    /// by program size, never by data. A program without value invention is
280    /// always weakly acyclic.
281    ///
282    /// # Errors
283    ///
284    /// Returns the first cyclic special edge in canonical order, with the
285    /// positions of its component.
286    pub fn check_weak_acyclicity(&self) -> Result<WeakAcyclicity, TerminationViolation> {
287        self.check_weak_acyclicity_with_equality_mode(EqualityMode::Default)
288    }
289
290    /// Check termination under the selected term-equality regime.
291    ///
292    /// Default matching retains complete-pattern unification. Under
293    /// [`EqualityMode::SameAs`], any argument terms may become equal, so
294    /// flows connect every occurrence of the same relation and arity.
295    /// Relation symbols remain distinct from the terms equality rewrites.
296    /// Evidence records the equality mode. Structural safety and equality
297    /// compatibility are checked by [`Self::validate_with_equality_mode`].
298    ///
299    /// # Errors
300    ///
301    /// Returns the first cyclic special edge under this equality mode.
302    pub fn check_weak_acyclicity_with_equality_mode(
303        &self,
304        equality_mode: EqualityMode,
305    ) -> Result<WeakAcyclicity, TerminationViolation> {
306        let graph = PositionGraph::build(self, equality_mode);
307        let sccs = graph.strongly_connected_components();
308        let component = graph.component_of(&sccs);
309        match graph.violation(&sccs, &component) {
310            Some(violation) => Err(violation),
311            None => Ok(graph.certificate(&sccs, &component)),
312        }
313    }
314}