datalog_structural_model/ir/aggregate.rs
1//! Aggregation IR for extension.
2//!
3//! Datalog with aggregation extends pure Datalog by allowing a
4//! body literal that folds a set of inner bindings into a single
5//! aggregate value, optionally grouped by a chosen set of
6//! variables. The aggregate result is bound to a fresh variable
7//! that downstream body literals (and the rule head) can consume.
8//!
9//! This module defines the IR data types only:
10//! [`Aggregator`] (the SQL/SPARQL aggregator vocabulary) and
11//! [`AggregateBody`] (an aggregation sub-query). The
12//! corresponding body-literal variant is
13//! [`Literal::Aggregate`],
14//! and rule-level safety analysis is in
15//! [`Rule::unsafe_aggregate_variables`](super::rule::Rule::unsafe_aggregate_variables).
16//!
17//! **Stratification**: an aggregation depends on the *complete*
18//! extension of its inner predicates, so each predicate referenced
19//! from the aggregate's inner body forms a polarity-bearing
20//! dependency edge analogous to a negative literal — those
21//! predicates must sit in a strictly lower stratum than the
22//! rule's head predicate.
23
24use std::collections::BTreeSet;
25
26use super::literal::Literal;
27use super::symbols::VariableSymbol;
28
29/// SQL/SPARQL aggregator vocabulary supported in rule bodies.
30///
31/// Mirrors the subset called out in the extension deliverable
32/// (the rule validation specification):
33/// MIN, MAX, SUM, COUNT, AVG. SPARQL's `SAMPLE` and
34/// `GROUP_CONCAT` are not in scope for extension — they map onto
35/// SPARQL's `Group` operator rather than a Datalog rule body.
36#[derive(
37 Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize,
38)]
39#[serde(deny_unknown_fields)]
40pub enum Aggregator {
41 /// `COUNT(?expr)` — number of distinct `?expr` values that
42 /// appear in the inner result set.
43 Count,
44 /// `SUM(?expr)` — numeric sum of `?expr` values.
45 Sum,
46 /// `MIN(?expr)` — minimum `?expr` value under SPARQL's
47 /// ordering (numeric / lexicographic per term kind).
48 Min,
49 /// `MAX(?expr)` — maximum `?expr` value under the same
50 /// ordering as [`Self::Min`].
51 Max,
52 /// `AVG(?expr)` — numeric mean of `?expr` values. Undefined
53 /// for an empty input.
54 Avg,
55}
56
57impl Aggregator {
58 /// Render the aggregator as its canonical uppercase name.
59 /// Used by diagnostics and rule-name maps.
60 #[must_use]
61 pub fn name(self) -> &'static str {
62 match self {
63 Self::Count => "COUNT",
64 Self::Sum => "SUM",
65 Self::Min => "MIN",
66 Self::Max => "MAX",
67 Self::Avg => "AVG",
68 }
69 }
70}
71
72/// An aggregation sub-query inside a rule body.
73///
74/// Semantically equivalent to a SPARQL `Group { ... } over { ... }`
75/// projection: evaluate `inner_body` as a sub-query, group the
76/// results by `group_by`, fold each group's `input_var` values
77/// with `aggregator`, and bind the per-group result to
78/// `result_var`. The aggregate then participates in the outer
79/// rule body as if `result_var` were produced by a positive
80/// atom that ranges over the per-group results.
81///
82/// # Variable scoping
83///
84/// `inner_body` is its own scope: positive atoms and `BIND`
85/// outputs inside the inner body bind variables that are visible
86/// only within the aggregation. Only `group_by` and the computed
87/// `result_var` are exported to the outer rule. The input value
88/// remains local unless `input_var` is also a grouping key. Concretely:
89///
90/// - `group_by` and `input_var` MUST be bound by some positive atom or `BIND`
91/// inside `inner_body`.
92/// - `result_var` MUST be fresh relative to outer positive-atom variables,
93/// outer `BIND` outputs, and earlier aggregate exports. It may appear in the
94/// head and in literals that consume the aggregate result.
95///
96/// # Inner-body literal kinds
97///
98/// `inner_body` accepts the same four literal kinds the outer
99/// rule body accepts — [`Literal::Positive`], [`Literal::Negative`],
100/// [`Literal::Filter`], and [`Literal::Bind`] — under the usual
101/// safety rules (negated atoms and filter expressions reference
102/// only inner-body-bound variables; `BIND` expressions reference
103/// inner-positive variables anywhere in the inner body or earlier inner
104/// `BIND` outputs, and bind a fresh variable).
105/// Nested aggregates inside an aggregate's inner body are rejected
106/// at validation time as
107/// [`super::error::ProgramValidationError::NestedAggregateInInnerBody`].
108#[derive(Clone, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize)]
109#[serde(deny_unknown_fields)]
110pub struct AggregateBody {
111 /// The variable that receives the per-group aggregate
112 /// result.
113 pub result_var: VariableSymbol,
114 /// Which aggregator to apply.
115 pub aggregator: Aggregator,
116 /// The variable whose values are folded into the aggregate
117 /// (the "input expression" in SPARQL terms).
118 pub input_var: VariableSymbol,
119 /// Group-by keys. The aggregator runs once per distinct
120 /// tuple of `group_by` values; an empty `group_by`
121 /// collapses every inner-body binding into a single group.
122 pub group_by: Vec<VariableSymbol>,
123 /// Literals forming the aggregation's inner sub-query.
124 /// Accepts [`Literal::Positive`], [`Literal::Negative`],
125 /// [`Literal::Filter`], and [`Literal::Bind`] under the
126 /// per-kind safety rules. Nested
127 /// [`Literal::Aggregate`] is rejected at validation time.
128 pub inner_body: Vec<Literal>,
129}
130
131impl AggregateBody {
132 /// Variables bound by the inner body — every variable a
133 /// positive inner atom binds, plus every `BIND`'s output
134 /// variable. Used by safety analysis to verify that
135 /// `input_var` and `group_by` are sourced from the inner
136 /// body and that inner negation / filter / bind references
137 /// stay within the inner scope.
138 #[must_use]
139 pub fn inner_bound_variables(&self) -> BTreeSet<VariableSymbol> {
140 let mut out = BTreeSet::new();
141 for lit in &self.inner_body {
142 match lit {
143 Literal::Positive(atom) => out.extend(atom.variables()),
144 Literal::Bind { var, .. } => {
145 out.insert(var.clone());
146 }
147 Literal::Negative(_) | Literal::Filter(_) | Literal::Aggregate(_) => {}
148 }
149 }
150 out
151 }
152
153 /// Variables this aggregate exposes to the outer rule body:
154 /// the freshly-bound `result_var` plus every key the
155 /// outer rule groups by. The outer-scope view of an
156 /// aggregate body literal.
157 #[must_use]
158 pub fn exported_variables(&self) -> BTreeSet<VariableSymbol> {
159 let mut out: BTreeSet<VariableSymbol> = self.group_by.iter().cloned().collect();
160 out.insert(self.result_var.clone());
161 out
162 }
163
164 /// Returns `true` when the inner body contains a nested
165 /// `Literal::Aggregate`. Nested aggregates are rejected as
166 /// [`super::error::ProgramValidationError::NestedAggregateInInnerBody`].
167 #[must_use]
168 pub fn contains_nested_aggregate(&self) -> bool {
169 self.inner_body
170 .iter()
171 .any(|lit| matches!(lit, Literal::Aggregate(_)))
172 }
173}