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