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                    if let Some(kind) = sources.clock_invention(variable) {
95                        // A clock may produce a fresh value at each firing,
96                        // even without data arguments. Every positive body
97                        // atom controls whether this firing occurs.
98                        for body in &sources.atoms {
99                            for slot in 0..body.atom.arity() {
100                                self.edge(
101                                    &body.position(head.rule, slot),
102                                    &to,
103                                    Some(wrapper.unwrap_or(kind)),
104                                );
105                            }
106                        }
107                    }
108                    for source in sources.of(variable) {
109                        self.edge(&source.position, &to, wrapper.or(source.invention));
110                    }
111                });
112                if existential {
113                    for variable in head.frontier() {
114                        for source in sources.of(&variable) {
115                            self.edge(&source.position, &to, Some(InventionKind::Existential));
116                        }
117                    }
118                }
119            }
120        }
121    }
122
123    /// Ordinary edges from a head slot to the same slot of every positive
124    /// body atom, in any rule, whose pattern can match the head's facts.
125    fn add_flows(&mut self, head: &HeadOccurrences<'_>, scopes: &[VariableSources<'_>]) {
126        for (path, atom) in head.head.atoms() {
127            for (consumer, scope) in scopes.iter().enumerate() {
128                for body in scope.atoms.iter().filter(|body| overlaps(atom, body.atom)) {
129                    for slot in 0..atom.arity() {
130                        let from = head.position(path, atom, slot);
131                        let to = body.position(RuleIndex::new(consumer), slot);
132                        self.edge(&from, &to, None);
133                    }
134                }
135            }
136        }
137    }
138
139    fn component_of(&self, sccs: &[BTreeSet<usize>]) -> Vec<usize> {
140        // bounded: one component id per position of the finite program.
141        let mut component = vec![0; self.positions.len()];
142        for (index, members) in sccs.iter().enumerate() {
143            for &node in members {
144                component[node] = index;
145            }
146        }
147        component
148    }
149
150    fn violation(
151        &self,
152        sccs: &[BTreeSet<usize>],
153        component: &[usize],
154    ) -> Option<TerminationViolation> {
155        let edge = self
156            .special
157            .iter()
158            .filter(|edge| component[self.ids[&edge.from]] == component[self.ids[&edge.to]])
159            .min()?;
160        let members = &sccs[component[self.ids[&edge.from]]];
161        let positions = members
162            .iter()
163            .map(|&id| self.positions[id].clone())
164            .collect();
165        Some(TerminationViolation::new(
166            TerminationCriterion::WeaklyAcyclic,
167            edge.clone(),
168            positions,
169        ))
170    }
171
172    /// Longest special-edge count over the acyclic condensation. Tarjan
173    /// emits sinks first, so walking components in reverse settles every
174    /// predecessor before its successors.
175    fn certificate(&self, sccs: &[BTreeSet<usize>], component: &[usize]) -> WeakAcyclicity {
176        let mut rank = vec![0_usize; sccs.len()];
177        for index in (0..sccs.len()).rev() {
178            for &node in &sccs[index] {
179                for &(target, special) in &self.successors[node] {
180                    let target = component[target];
181                    if target != index {
182                        rank[target] = rank[target].max(rank[index] + usize::from(special));
183                    }
184                }
185            }
186        }
187        let skolem_depth = rank.iter().copied().max().unwrap_or(0);
188        let deepest = (skolem_depth > 0)
189            .then(|| {
190                self.ids
191                    .iter()
192                    .find(|&(_, &id)| rank[component[id]] == skolem_depth)
193                    .map(|(position, _)| position.clone())
194            })
195            .flatten();
196        WeakAcyclicity {
197            law_version: TerminationCriterion::WeaklyAcyclic.law_version(),
198            positions: self.positions.len(),
199            special_edges: self.special.len(),
200            skolem_depth,
201            deepest,
202        }
203    }
204}
205
206/// The head of one rule, whose atom slots are graph nodes.
207struct HeadOccurrences<'a> {
208    rule: RuleIndex,
209    head: &'a RuleHead,
210}
211
212impl<'a> HeadOccurrences<'a> {
213    fn new(rule: RuleIndex, head: &'a RuleHead) -> Self {
214        Self { rule, head }
215    }
216
217    fn position(&self, path: HeadAtomPath, atom: &Atom, slot: usize) -> ArgumentPosition {
218        ArgumentPosition::new(
219            atom.predicate.clone(),
220            AtomSlot::new(slot),
221            self.rule,
222            RuleSite::Head(path),
223        )
224    }
225
226    /// Head variables that are not existential: the values a witness
227    /// depends on.
228    fn frontier(&self) -> impl Iterator<Item = VariableSymbol> + '_ {
229        self.head
230            .variables()
231            .into_iter()
232            .filter(|variable| !self.head.is_existential(variable))
233    }
234}
235
236impl SuccessorGraph for PositionGraph {
237    fn node_count(&self) -> usize {
238        self.positions.len()
239    }
240
241    fn successor(&self, node: usize, nth: usize) -> Option<usize> {
242        self.successors[node].get(nth).map(|&(target, _)| target)
243    }
244}
245
246impl Program {
247    /// Check [`TerminationCriterion::WeaklyAcyclic`] on the position graph.
248    ///
249    /// Nodes are argument slots of atom occurrences. Inside a rule, a head
250    /// variable copied directly from a body slot adds an ordinary edge; a
251    /// head value built by a Skolem term, a triple term, a `BIND` or an
252    /// aggregate adds a special edge from each body slot feeding it. A
253    /// clock-dependent value also receives special edges from every positive
254    /// body slot controlling its firing, including later body atoms. A head
255    /// slot holding an existential variable is treated like a Skolem term over
256    /// the frontier: a special edge arrives from every body slot binding a
257    /// non-existential head variable. Every atom of a conjunctive,
258    /// existential or disjunctive head is its own occurrence. Across
259    /// rules, a head slot feeds the same slot of every positive body atom
260    /// whose complete pattern can match the head, so constants that keep two
261    /// patterns apart break the cycle. The program is weakly acyclic when no
262    /// special edge lies on a cycle, which bounds the nesting of invented
263    /// values and so the number of derivable facts.
264    ///
265    /// The analysis reads only the program: its time and memory are bounded
266    /// by program size, never by data. A program without value invention is
267    /// always weakly acyclic.
268    ///
269    /// # Errors
270    ///
271    /// Returns the first cyclic special edge in canonical order, with the
272    /// positions of its component.
273    pub fn check_weak_acyclicity(&self) -> Result<WeakAcyclicity, TerminationViolation> {
274        let graph = PositionGraph::build(self);
275        let sccs = graph.strongly_connected_components();
276        let component = graph.component_of(&sccs);
277        match graph.violation(&sccs, &component) {
278            Some(violation) => Err(violation),
279            None => Ok(graph.certificate(&sccs, &component)),
280        }
281    }
282}