Skip to main content

domainforge_core/policy/
quantifier.rs

1use super::expression::{AggregateFunction, BinaryOp, Expression, Quantifier};
2use crate::graph::Graph;
3use rust_decimal::prelude::ToPrimitive;
4use rust_decimal::Decimal;
5use std::convert::TryFrom;
6use std::str::FromStr;
7
8impl Expression {
9    pub fn expand(&self, graph: &Graph) -> Result<Expression, String> {
10        match self {
11            Expression::Quantifier {
12                quantifier,
13                variable,
14                collection,
15                condition,
16            } => {
17                let items = Self::get_collection(collection, graph)?;
18
19                match quantifier {
20                    Quantifier::ForAll => {
21                        if items.is_empty() {
22                            return Ok(Expression::literal(true));
23                        }
24
25                        let mut result = Expression::literal(true);
26                        for item in items {
27                            let substituted = condition.substitute(variable, &item)?;
28                            let expanded = substituted.expand(graph)?;
29                            result = Expression::binary(BinaryOp::And, result, expanded);
30                        }
31                        Ok(result)
32                    }
33                    Quantifier::Exists => {
34                        if items.is_empty() {
35                            return Ok(Expression::literal(false));
36                        }
37
38                        let mut result = Expression::literal(false);
39                        for item in items {
40                            let substituted = condition.substitute(variable, &item)?;
41                            let expanded = substituted.expand(graph)?;
42                            result = Expression::binary(BinaryOp::Or, result, expanded);
43                        }
44                        Ok(result)
45                    }
46                    Quantifier::ExistsUnique => {
47                        let mut count = 0;
48                        let mut saw_unknown = false;
49                        for item in items {
50                            let substituted = condition.substitute(variable, &item)?;
51                            let expanded = substituted.expand(graph)?;
52
53                            if Self::is_true_literal(&expanded) {
54                                count += 1;
55                            } else if matches!(&expanded,
56                                Expression::Literal(v) if v.as_bool().is_none())
57                            {
58                                // Unknown (NULL) item, as the three-valued evaluator
59                                // reads it (`from_option_bool(as_bool())`).
60                                saw_unknown = true;
61                            }
62                        }
63                        // Same counts as the three-valued handler in `Policy`:
64                        // 2+ true => false; otherwise any unknown => NULL;
65                        // else exactly one true. Boolean mode keeps the old
66                        // count-only result (its evaluator rejects NULL literals).
67                        if graph.use_three_valued_logic() {
68                            if count > 1 {
69                                return Ok(Expression::literal(false));
70                            }
71                            if saw_unknown {
72                                return Ok(Expression::Literal(serde_json::Value::Null));
73                            }
74                        }
75                        Ok(Expression::literal(count == 1))
76                    }
77                }
78            }
79            Expression::GroupBy {
80                variable,
81                collection,
82                filter,
83                key,
84                condition,
85            } => {
86                let items = Self::get_collection(collection, graph)?;
87
88                // Filter items if filter is present
89                let filtered_items = if let Some(filter_expr) = filter {
90                    let mut filtered = Vec::new();
91                    for item in items {
92                        let substituted = filter_expr.substitute(variable, &item)?;
93                        let expanded = substituted.expand(graph)?;
94                        if Self::is_true_literal(&expanded) {
95                            filtered.push(item);
96                        }
97                    }
98                    filtered
99                } else {
100                    items
101                };
102
103                // Group items
104                let mut groups: std::collections::HashMap<String, Vec<serde_json::Value>> =
105                    std::collections::HashMap::new();
106                for item in filtered_items {
107                    let substituted_key = key.substitute(variable, &item)?;
108                    let expanded_key = substituted_key.expand(graph)?;
109                    let key_str = match expanded_key {
110                        Expression::Literal(v) => match v {
111                            serde_json::Value::String(s) => s,
112                            serde_json::Value::Number(n) => n.to_string(),
113                            serde_json::Value::Bool(b) => b.to_string(),
114                            serde_json::Value::Null => "null".to_string(),
115                            other => {
116                                return Err(format!(
117                                "Group key must be a string, number, bool, or null literal, got {}",
118                                other
119                            ))
120                            }
121                        },
122                        _ => {
123                            return Err("Group key must evaluate to a literal".to_string());
124                        }
125                    };
126                    groups.entry(key_str).or_default().push(item);
127                }
128
129                // Evaluate condition for each group
130                for (_group_key, group_items) in groups {
131                    // Substitute the variable with the group collection (as a Literal Array)
132                    // This allows aggregations inside the condition to use the group items
133                    let substituted_condition =
134                        condition.substitute(variable, &serde_json::Value::Array(group_items))?;
135                    let expanded = substituted_condition.expand(graph)?;
136                    if !Self::is_true_literal(&expanded) {
137                        return Ok(Expression::literal(false));
138                    }
139                }
140                Ok(Expression::literal(true))
141            }
142            Expression::Binary { op, left, right } => {
143                let left_expanded = left.expand(graph)?;
144                let right_expanded = right.expand(graph)?;
145                Ok(Self::reduce_binary_expression(
146                    op,
147                    left_expanded,
148                    right_expanded,
149                )?)
150            }
151            Expression::Unary { op, operand } => {
152                Ok(Expression::unary(op.clone(), operand.expand(graph)?))
153            }
154            Expression::MemberAccess { .. } => Ok(self.clone()),
155            Expression::Aggregation {
156                function,
157                collection,
158                field,
159                filter,
160            } => {
161                // Evaluate the aggregation and return a literal
162                let result =
163                    Self::evaluate_aggregation(function, collection, field, filter, graph)?;
164                Ok(Expression::Literal(result))
165            }
166            Expression::AggregationComprehension {
167                function,
168                variable,
169                collection,
170                window,
171                predicate,
172                projection,
173                target_unit,
174            } => {
175                let result = Self::evaluate_aggregation_comprehension(
176                    function,
177                    variable,
178                    collection,
179                    window,
180                    predicate,
181                    projection,
182                    target_unit.as_deref(),
183                    graph,
184                )?;
185                Ok(Expression::Literal(result))
186            }
187            _ => Ok(self.clone()),
188        }
189    }
190
191    pub fn substitute(&self, var: &str, value: &serde_json::Value) -> Result<Expression, String> {
192        match self {
193            Expression::Variable(n) => {
194                if n == var {
195                    Ok(Expression::Literal(value.clone()))
196                } else if n.starts_with(&format!("{}.", var)) {
197                    let field = &n[var.len() + 1..];
198                    if let Some(field_value) = value.get(field) {
199                        Ok(Expression::Literal(field_value.clone()))
200                    } else {
201                        // For three-valued semantics, if a field is missing in a substituted
202                        // value, treat it as NULL/unknown rather than a fatal error. That way
203                        // quantifiers and nested expressions can evaluate to NULL when data
204                        // is optional.
205                        Ok(Expression::Literal(serde_json::Value::Null))
206                    }
207                } else {
208                    Ok(self.clone())
209                }
210            }
211            Expression::Binary { op, left, right } => Ok(Expression::binary(
212                op.clone(),
213                left.substitute(var, value)?,
214                right.substitute(var, value)?,
215            )),
216            Expression::Unary { op, operand } => Ok(Expression::unary(
217                op.clone(),
218                operand.substitute(var, value)?,
219            )),
220            Expression::Quantifier {
221                quantifier,
222                variable,
223                collection,
224                condition,
225            } => {
226                if var == variable {
227                    // Don't substitute into condition when var matches the bound variable
228                    // to avoid variable capture
229                    Ok(Expression::quantifier(
230                        quantifier.clone(),
231                        variable,
232                        collection.substitute(var, value)?,
233                        *condition.clone(),
234                    ))
235                } else {
236                    // Substitute into both collection and condition
237                    Ok(Expression::quantifier(
238                        quantifier.clone(),
239                        variable,
240                        collection.substitute(var, value)?,
241                        condition.substitute(var, value)?,
242                    ))
243                }
244            }
245            Expression::MemberAccess { object, member } => {
246                if object == var {
247                    if let Some(field_value) = value.get(member) {
248                        Ok(Expression::Literal(field_value.clone()))
249                    } else {
250                        Ok(Expression::Literal(serde_json::Value::Null))
251                    }
252                } else {
253                    Ok(self.clone())
254                }
255            }
256            Expression::Aggregation {
257                function,
258                collection,
259                field,
260                filter,
261            } => Ok(Expression::aggregation(
262                function.clone(),
263                collection.substitute(var, value)?,
264                field.clone(),
265                filter
266                    .as_ref()
267                    .map(|f| f.substitute(var, value))
268                    .transpose()?,
269            )),
270            Expression::AggregationComprehension {
271                function,
272                variable,
273                collection,
274                window,
275                predicate,
276                projection,
277                target_unit,
278            } => Ok(Expression::AggregationComprehension {
279                function: function.clone(),
280                variable: variable.clone(),
281                collection: Box::new(collection.substitute(var, value)?),
282                window: window.clone(),
283                predicate: Box::new(predicate.substitute(var, value)?),
284                projection: Box::new(projection.substitute(var, value)?),
285                target_unit: target_unit.clone(),
286            }),
287            Expression::GroupBy {
288                variable,
289                collection,
290                filter,
291                key,
292                condition,
293            } => {
294                // Similar to Quantifier, check if variable matches
295                if var == variable {
296                    Ok(Expression::GroupBy {
297                        variable: variable.clone(),
298                        collection: Box::new(collection.substitute(var, value)?),
299                        filter: filter.clone(),
300                        key: key.clone(),
301                        condition: condition.clone(),
302                    })
303                } else {
304                    Ok(Expression::GroupBy {
305                        variable: variable.clone(),
306                        collection: Box::new(collection.substitute(var, value)?),
307                        filter: filter
308                            .as_ref()
309                            .map(|f| f.substitute(var, value))
310                            .transpose()?
311                            .map(Box::new),
312                        key: Box::new(key.substitute(var, value)?),
313                        condition: Box::new(condition.substitute(var, value)?),
314                    })
315                }
316            }
317            _ => Ok(self.clone()),
318        }
319    }
320
321    pub(crate) fn get_collection(
322        expr: &Expression,
323        graph: &Graph,
324    ) -> Result<Vec<serde_json::Value>, String> {
325        match expr {
326            Expression::Variable(name) => {
327                if let Some(entity_type) = name.strip_prefix("entity_instances:") {
328                    return Ok(Self::collect_entity_instances(graph, Some(entity_type)));
329                }
330                Self::get_named_collection(name, graph)
331            }
332            Expression::Literal(serde_json::Value::Array(arr)) => Ok(arr.clone()),
333            _ => Err("Collection expression must be a variable or array literal".to_string()),
334        }
335    }
336
337    fn collect_entity_instances(
338        graph: &Graph,
339        entity_type_filter: Option<&str>,
340    ) -> Vec<serde_json::Value> {
341        graph
342            .all_entity_instances()
343            .iter()
344            .filter(|instance| {
345                entity_type_filter.is_none_or(|filter| instance.entity_type() == filter)
346            })
347            .map(|instance| {
348                let mut map = serde_json::Map::new();
349                map.insert(
350                    "id".to_string(),
351                    serde_json::json!(instance.id().to_string()),
352                );
353                map.insert("name".to_string(), serde_json::json!(instance.name()));
354                map.insert(
355                    "entity".to_string(),
356                    serde_json::json!(instance.entity_type()),
357                );
358                map.insert(
359                    "namespace".to_string(),
360                    serde_json::json!(instance.namespace()),
361                );
362
363                let mut fields: Vec<_> = instance.fields().iter().collect();
364                fields.sort_by(|left, right| left.0.cmp(right.0));
365                for (name, value) in fields {
366                    if matches!(name.as_str(), "id" | "name" | "entity" | "namespace") {
367                        continue;
368                    }
369                    map.insert(name.clone(), value.clone());
370                }
371                serde_json::Value::Object(map)
372            })
373            .collect()
374    }
375
376    fn get_named_collection(name: &str, graph: &Graph) -> Result<Vec<serde_json::Value>, String> {
377        match name {
378            "flows" => {
379                let flows: Result<Vec<serde_json::Value>, String> = graph
380                    .all_flows()
381                    .iter()
382                    .map(|f| {
383                        let quantity = f.quantity().to_f64().ok_or_else(|| {
384                            format!("Failed to convert flow quantity {} to f64", f.quantity())
385                        })?;
386
387                        let mut map = serde_json::Map::new();
388                        map.insert("id".to_string(), serde_json::json!(f.id().to_string()));
389                        map.insert(
390                            "from_entity".to_string(),
391                            serde_json::json!(f.from_id().to_string()),
392                        );
393                        map.insert(
394                            "to_entity".to_string(),
395                            serde_json::json!(f.to_id().to_string()),
396                        );
397                        map.insert(
398                            "resource".to_string(),
399                            serde_json::json!(f.resource_id().to_string()),
400                        );
401                        map.insert("quantity".to_string(), serde_json::json!(quantity));
402
403                        for (k, v) in f.attributes().iter() {
404                            if matches!(
405                                k.as_str(),
406                                "id" | "from_entity" | "to_entity" | "resource" | "quantity"
407                            ) || map.contains_key(k)
408                            {
409                                continue;
410                            }
411                            map.insert(k.clone(), v.clone());
412                        }
413                        Ok(serde_json::Value::Object(map))
414                    })
415                    .collect();
416                flows
417            }
418            "entities" => {
419                let entities: Vec<serde_json::Value> = graph
420                    .all_entities()
421                    .iter()
422                    .map(|e| {
423                        let mut map = serde_json::Map::new();
424                        map.insert("id".to_string(), serde_json::json!(e.id().to_string()));
425                        map.insert("name".to_string(), serde_json::json!(e.name()));
426                        map.insert("namespace".to_string(), serde_json::json!(e.namespace()));
427
428                        let roles = graph.role_names_for_entity(e.id());
429                        if !roles.is_empty() {
430                            map.insert("roles".to_string(), serde_json::json!(roles));
431                        }
432
433                        for (k, v) in e.attributes().iter() {
434                            if matches!(k.as_str(), "id" | "name" | "namespace")
435                                || map.contains_key(k)
436                            {
437                                continue;
438                            }
439                            map.insert(k.clone(), v.clone());
440                        }
441
442                        serde_json::Value::Object(map)
443                    })
444                    .collect();
445                Ok(entities)
446            }
447            "entity_instances" => Ok(Self::collect_entity_instances(graph, None)),
448            "relations" => {
449                let relations: Vec<serde_json::Value> = graph
450                    .all_relations()
451                    .iter()
452                    .map(|relation| {
453                        let mut map = serde_json::Map::new();
454                        map.insert(
455                            "id".to_string(),
456                            serde_json::json!(relation.id().to_string()),
457                        );
458                        map.insert("name".to_string(), serde_json::json!(relation.name()));
459                        map.insert(
460                            "predicate".to_string(),
461                            serde_json::json!(relation.predicate()),
462                        );
463
464                        if let Some(subject) = graph.get_role(relation.subject_role()) {
465                            map.insert(
466                                "subject_role".to_string(),
467                                serde_json::json!(subject.name()),
468                            );
469                        }
470
471                        if let Some(object) = graph.get_role(relation.object_role()) {
472                            map.insert("object_role".to_string(), serde_json::json!(object.name()));
473                        }
474
475                        if let Some(flow) = relation.via_flow() {
476                            map.insert("via".to_string(), serde_json::json!(flow.to_string()));
477                        }
478
479                        serde_json::Value::Object(map)
480                    })
481                    .collect();
482
483                Ok(relations)
484            }
485            "resources" => {
486                let resources: Vec<serde_json::Value> = graph
487                    .all_resources()
488                    .iter()
489                    .map(|r| {
490                        let mut map = serde_json::Map::new();
491                        map.insert("id".to_string(), serde_json::json!(r.id().to_string()));
492                        map.insert("name".to_string(), serde_json::json!(r.name()));
493                        map.insert("namespace".to_string(), serde_json::json!(r.namespace()));
494                        map.insert("unit".to_string(), serde_json::json!(r.unit()));
495                        for (k, v) in r.attributes().iter() {
496                            if matches!(k.as_str(), "id" | "name" | "namespace" | "unit")
497                                || map.contains_key(k)
498                            {
499                                continue;
500                            }
501                            map.insert(k.clone(), v.clone());
502                        }
503                        serde_json::Value::Object(map)
504                    })
505                    .collect();
506                Ok(resources)
507            }
508            "instances" => {
509                let instances: Vec<serde_json::Value> = graph
510                    .all_instances()
511                    .iter()
512                    .map(|i| {
513                        let mut map = serde_json::Map::new();
514                        map.insert("id".to_string(), serde_json::json!(i.id().to_string()));
515                        map.insert(
516                            "entity".to_string(),
517                            serde_json::json!(i.entity_id().to_string()),
518                        );
519                        map.insert(
520                            "resource".to_string(),
521                            serde_json::json!(i.resource_id().to_string()),
522                        );
523                        for (k, v) in i.attributes().iter() {
524                            if matches!(k.as_str(), "id" | "entity" | "resource")
525                                || map.contains_key(k)
526                            {
527                                continue;
528                            }
529                            map.insert(k.clone(), v.clone());
530                        }
531                        serde_json::Value::Object(map)
532                    })
533                    .collect();
534                Ok(instances)
535            }
536            _ => Err(format!("Unknown collection: {}", name)),
537        }
538    }
539
540    fn is_true_literal(expr: &Expression) -> bool {
541        matches!(expr, Expression::Literal(v) if v.as_bool() == Some(true))
542    }
543
544    pub(crate) fn evaluate_aggregation(
545        function: &AggregateFunction,
546        collection: &Expression,
547        field: &Option<String>,
548        filter: &Option<Box<Expression>>,
549        graph: &Graph,
550    ) -> Result<serde_json::Value, String> {
551        // Get the collection items
552        let items = Self::get_collection(collection, graph)?;
553
554        // Apply filter if present
555        let filtered_items = if let Some(filter_expr) = filter {
556            // Determine the variable name based on collection type
557            let variable_name = match collection {
558                Expression::Variable(name) if name.starts_with("entity_instances:") => {
559                    "entity_instance"
560                }
561                Expression::Variable(name) => match name.as_str() {
562                    "flows" => "flow",
563                    "entities" => "entity",
564                    "entity_instances" => "entity_instance",
565                    "resources" => "resource",
566                    "instances" => "instance",
567                    "relations" => "relation",
568                    _ => "item",
569                },
570                _ => "item",
571            };
572
573            let mut kept = Vec::new();
574            for item in items {
575                // Substitute collection-specific variables in the filter. A missing
576                // field yields NULL (three-valued semantics — see `substitute`), not
577                // an error, so this only fails for a genuinely malformed filter
578                // expression, and such failures must not be read as "row excluded".
579                let substituted = filter_expr.substitute(variable_name, &item)?;
580                let expanded = substituted.expand(graph)?;
581                if Self::is_true_literal(&expanded) {
582                    kept.push(item);
583                }
584            }
585            kept
586        } else {
587            items
588        };
589
590        // Apply aggregation function
591        match function {
592            AggregateFunction::Count => Ok(serde_json::json!(filtered_items.len())),
593
594            AggregateFunction::Sum => {
595                let field_name = field.as_ref().ok_or("Sum requires a field specification")?;
596
597                let sum: Decimal = filtered_items
598                    .iter()
599                    .filter_map(|item| {
600                        item.get(field_name).and_then(|v| {
601                            if let Some(num) = v.as_f64() {
602                                Decimal::from_str(&num.to_string()).ok()
603                            } else if let Some(s) = v.as_str() {
604                                Decimal::from_str(s).ok()
605                            } else {
606                                None
607                            }
608                        })
609                    })
610                    .sum();
611
612                // Convert Decimal to f64 and propagate parsing errors
613                let sum_f64 = sum
614                    .to_f64()
615                    .ok_or_else(|| format!("Failed to convert sum {} to f64", sum))?;
616
617                Ok(serde_json::json!(sum_f64))
618            }
619
620            AggregateFunction::Avg => {
621                let field_name = field.as_ref().ok_or("Avg requires a field specification")?;
622
623                let values: Vec<Decimal> = filtered_items
624                    .iter()
625                    .filter_map(|item| {
626                        item.get(field_name).and_then(|v| {
627                            if let Some(num) = v.as_f64() {
628                                Decimal::from_str(&num.to_string()).ok()
629                            } else if let Some(s) = v.as_str() {
630                                Decimal::from_str(s).ok()
631                            } else {
632                                None
633                            }
634                        })
635                    })
636                    .collect();
637
638                if values.is_empty() {
639                    return Ok(serde_json::json!(null));
640                }
641
642                let sum: Decimal = values.iter().copied().sum();
643                let avg = sum / Decimal::from(values.len());
644
645                // Convert Decimal to f64 and propagate parsing errors
646                let avg_f64 = avg
647                    .to_f64()
648                    .ok_or_else(|| format!("Failed to convert average {} to f64", avg))?;
649
650                Ok(serde_json::json!(avg_f64))
651            }
652
653            AggregateFunction::Min => {
654                let field_name = field.as_ref().ok_or("Min requires a field specification")?;
655
656                let min = filtered_items
657                    .iter()
658                    .filter_map(|item| {
659                        item.get(field_name).and_then(|v| {
660                            if let Some(num) = v.as_f64() {
661                                Decimal::from_str(&num.to_string()).ok()
662                            } else if let Some(s) = v.as_str() {
663                                Decimal::from_str(s).ok()
664                            } else {
665                                None
666                            }
667                        })
668                    })
669                    .min();
670
671                // Convert Decimal to f64 and propagate parsing errors
672                if let Some(min_val) = min {
673                    let min_f64 = min_val
674                        .to_f64()
675                        .ok_or_else(|| format!("Failed to convert min {} to f64", min_val))?;
676                    Ok(serde_json::json!(min_f64))
677                } else {
678                    Ok(serde_json::json!(null))
679                }
680            }
681
682            AggregateFunction::Max => {
683                let field_name = field.as_ref().ok_or("Max requires a field specification")?;
684
685                let max = filtered_items
686                    .iter()
687                    .filter_map(|item| {
688                        item.get(field_name).and_then(|v| {
689                            if let Some(num) = v.as_f64() {
690                                Decimal::from_str(&num.to_string()).ok()
691                            } else if let Some(s) = v.as_str() {
692                                Decimal::from_str(s).ok()
693                            } else {
694                                None
695                            }
696                        })
697                    })
698                    .max();
699
700                // Convert Decimal to f64 and propagate parsing errors
701                if let Some(max_val) = max {
702                    let max_f64 = max_val
703                        .to_f64()
704                        .ok_or_else(|| format!("Failed to convert max {} to f64", max_val))?;
705                    Ok(serde_json::json!(max_f64))
706                } else {
707                    Ok(serde_json::json!(null))
708                }
709            }
710        }
711    }
712
713    #[allow(clippy::too_many_arguments)]
714    pub(crate) fn evaluate_aggregation_comprehension(
715        function: &AggregateFunction,
716        variable: &str,
717        collection: &Expression,
718        window: &Option<crate::policy::WindowSpec>,
719        predicate: &Expression,
720        projection: &Expression,
721        target_unit: Option<&str>,
722        graph: &Graph,
723    ) -> Result<serde_json::Value, String> {
724        let items = Self::get_collection(collection, graph)?;
725
726        // Apply window filtering if present
727        let items = if let Some(w) = window {
728            let now = chrono::Utc::now();
729            let duration_span = i64::try_from(w.duration)
730                .map_err(|_| format!("Window duration {} exceeds supported range", w.duration))?;
731            let unit_lower = w.unit.to_lowercase();
732            let duration = match unit_lower.as_str() {
733                "hour" | "hours" => chrono::Duration::hours(duration_span),
734                "minute" | "minutes" => chrono::Duration::minutes(duration_span),
735                "day" | "days" => chrono::Duration::days(duration_span),
736                "second" | "seconds" => chrono::Duration::seconds(duration_span),
737                _ => {
738                    return Err(format!(
739                        "Invalid window unit '{}' in aggregation window",
740                        w.unit
741                    ))
742                }
743            };
744
745            items
746                .into_iter()
747                .filter(|item| {
748                    let ts_str = item
749                        .get("timestamp")
750                        .or_else(|| item.get("created_at"))
751                        .and_then(|v| v.as_str());
752                    if let Some(s) = ts_str {
753                        if let Ok(ts) = chrono::DateTime::parse_from_rfc3339(s) {
754                            let ts_utc: chrono::DateTime<chrono::Utc> = ts.into();
755                            return ts_utc >= now - duration;
756                        }
757                    }
758                    // If no timestamp, we can't filter, so maybe exclude? Or include?
759                    // Safer to exclude if windowing is requested but data is missing.
760                    false
761                })
762                .collect()
763        } else {
764            items
765        };
766
767        let mut projected_values = Vec::new();
768        for item in items {
769            let substituted_predicate = predicate.substitute(variable, &item)?;
770            let predicate_result = substituted_predicate.expand(graph)?;
771            if !Self::is_true_literal(&predicate_result) {
772                continue;
773            }
774
775            let substituted_projection = projection.substitute(variable, &item)?;
776            let projection_result = substituted_projection.expand(graph)?;
777            match projection_result {
778                Expression::Literal(value) => projected_values.push(value),
779                Expression::QuantityLiteral { value, unit } => {
780                    projected_values.push(serde_json::json!({
781                        "__quantity_value": value.to_string(),
782                        "__quantity_unit": unit,
783                    }));
784                }
785                _ => {
786                    return Err(
787                        "Projection in aggregation comprehension must reduce to a literal"
788                            .to_string(),
789                    );
790                }
791            }
792        }
793
794        match function {
795            AggregateFunction::Count => Ok(serde_json::json!(projected_values.len())),
796            AggregateFunction::Sum
797            | AggregateFunction::Avg
798            | AggregateFunction::Min
799            | AggregateFunction::Max => {
800                Self::fold_numeric(function, &projected_values, target_unit)
801            }
802        }
803    }
804
805    pub(crate) fn fold_numeric(
806        function: &AggregateFunction,
807        values: &[serde_json::Value],
808        target_unit: Option<&str>,
809    ) -> Result<serde_json::Value, String> {
810        use crate::units::UnitRegistry;
811
812        let mut decimals: Vec<Decimal> = Vec::new();
813        let mut source_unit: Option<String> = None;
814        for value in values {
815            if let Some(num) = value.as_f64() {
816                decimals.push(Decimal::from_str(&num.to_string()).map_err(|e| e.to_string())?);
817            } else if let Some(s) = value.as_str() {
818                decimals.push(Decimal::from_str(s).map_err(|e| e.to_string())?);
819            } else if value.is_object() {
820                let map = value
821                    .as_object()
822                    .ok_or_else(|| "Invalid quantity object".to_string())?;
823                if let Some(val) = map.get("__quantity_value") {
824                    let s = val
825                        .as_str()
826                        .ok_or_else(|| "Quantity value must be a string".to_string())?;
827                    decimals.push(Decimal::from_str(s).map_err(|e| e.to_string())?);
828                }
829                if let Some(unit) = map.get("__quantity_unit") {
830                    if source_unit.is_none() {
831                        if let Some(unit_str) = unit.as_str() {
832                            source_unit = Some(unit_str.to_string());
833                        }
834                    }
835                }
836            }
837        }
838
839        if decimals.is_empty() {
840            return Ok(serde_json::json!(null));
841        }
842
843        if let Some(target_unit) = target_unit {
844            if let Some(unit) = source_unit.clone() {
845                let registry = UnitRegistry::global();
846                let registry = registry
847                    .read()
848                    .map_err(|e| format!("Failed to lock unit registry: {}", e))?;
849                let from = registry
850                    .get_unit(&unit)
851                    .map_err(|e| format!("{}", e))?
852                    .clone();
853                let to = registry
854                    .get_unit(target_unit)
855                    .map_err(|e| format!("{}", e))?
856                    .clone();
857                decimals = decimals
858                    .into_iter()
859                    .map(|value| registry.convert(value, &from, &to))
860                    .collect::<Result<Vec<_>, _>>()
861                    .map_err(|e| format!("{}", e))?;
862            }
863        }
864
865        let result = match function {
866            AggregateFunction::Sum => decimals.iter().copied().sum(),
867            AggregateFunction::Avg => {
868                let sum: Decimal = decimals.iter().copied().sum();
869                sum / Decimal::from(decimals.len())
870            }
871            AggregateFunction::Min => decimals
872                .into_iter()
873                .min()
874                .ok_or_else(|| "No values available for min".to_string())?,
875            AggregateFunction::Max => decimals
876                .into_iter()
877                .max()
878                .ok_or_else(|| "No values available for max".to_string())?,
879            AggregateFunction::Count => Decimal::from(values.len() as i64),
880        };
881
882        let as_f64 = result
883            .to_f64()
884            .ok_or_else(|| format!("Failed to convert aggregated value {} to f64", result))?;
885
886        Ok(serde_json::json!(as_f64))
887    }
888
889    fn reduce_binary_expression(
890        op: &BinaryOp,
891        left: Expression,
892        right: Expression,
893    ) -> Result<Expression, String> {
894        match (&left, &right) {
895            (Expression::Literal(left_value), Expression::Literal(right_value)) => {
896                // Preserve tri-state semantics: if either operand is NULL, yield NULL.
897                if left_value.is_null() || right_value.is_null() {
898                    return Ok(Expression::Literal(serde_json::Value::Null));
899                }
900
901                let numeric_cmp = left_value.is_number() && right_value.is_number();
902                let reduced = match op {
903                    BinaryOp::Equal => {
904                        if numeric_cmp {
905                            let left_num = Self::value_to_f64(left_value)
906                                .ok_or_else(|| "Left operand is not numeric".to_string())?;
907                            let right_num = Self::value_to_f64(right_value)
908                                .ok_or_else(|| "Right operand is not numeric".to_string())?;
909                            serde_json::json!(left_num == right_num)
910                        } else {
911                            serde_json::json!(left_value == right_value)
912                        }
913                    }
914                    BinaryOp::NotEqual => {
915                        if numeric_cmp {
916                            let left_num = Self::value_to_f64(left_value)
917                                .ok_or_else(|| "Left operand is not numeric".to_string())?;
918                            let right_num = Self::value_to_f64(right_value)
919                                .ok_or_else(|| "Right operand is not numeric".to_string())?;
920                            serde_json::json!(left_num != right_num)
921                        } else {
922                            serde_json::json!(left_value != right_value)
923                        }
924                    }
925                    BinaryOp::GreaterThan
926                    | BinaryOp::LessThan
927                    | BinaryOp::GreaterThanOrEqual
928                    | BinaryOp::LessThanOrEqual => {
929                        let left_num = Self::value_to_f64(left_value)
930                            .ok_or_else(|| "Left operand is not numeric".to_string())?;
931                        let right_num = Self::value_to_f64(right_value)
932                            .ok_or_else(|| "Right operand is not numeric".to_string())?;
933                        match op {
934                            BinaryOp::GreaterThan => serde_json::json!(left_num > right_num),
935                            BinaryOp::LessThan => serde_json::json!(left_num < right_num),
936                            BinaryOp::GreaterThanOrEqual => {
937                                serde_json::json!(left_num >= right_num)
938                            }
939                            BinaryOp::LessThanOrEqual => serde_json::json!(left_num <= right_num),
940                            _ => unreachable!(),
941                        }
942                    }
943                    BinaryOp::And | BinaryOp::Or => {
944                        let left_bool = match left_value {
945                            serde_json::Value::Bool(b) => Some(*b),
946                            serde_json::Value::Null => None,
947                            _ => return Err("Left operand is not boolean".to_string()),
948                        };
949                        let right_bool = match right_value {
950                            serde_json::Value::Bool(b) => Some(*b),
951                            serde_json::Value::Null => None,
952                            _ => return Err("Right operand is not boolean".to_string()),
953                        };
954
955                        match op {
956                            BinaryOp::And => {
957                                if left_bool == Some(false) || right_bool == Some(false) {
958                                    serde_json::json!(false)
959                                } else if left_bool.is_none() || right_bool.is_none() {
960                                    serde_json::Value::Null
961                                } else {
962                                    serde_json::json!(left_bool.unwrap() && right_bool.unwrap())
963                                }
964                            }
965                            BinaryOp::Or => {
966                                if left_bool == Some(true) || right_bool == Some(true) {
967                                    serde_json::json!(true)
968                                } else if left_bool.is_none() || right_bool.is_none() {
969                                    serde_json::Value::Null
970                                } else {
971                                    serde_json::json!(left_bool.unwrap() || right_bool.unwrap())
972                                }
973                            }
974                            _ => unreachable!(),
975                        }
976                    }
977                    BinaryOp::Plus | BinaryOp::Minus | BinaryOp::Multiply | BinaryOp::Divide => {
978                        // Decimal, not f64: fold_numeric() above already
979                        // avoids float rounding for aggregation, and an
980                        // arithmetic `where` predicate comparing e.g.
981                        // `i.a + i.b != i.total` needs the same guarantee —
982                        // 0.1 + 0.2 != 0.3 is true under f64.
983                        let left_dec = Self::value_to_decimal(left_value)
984                            .ok_or_else(|| "Left operand is not numeric".to_string())?;
985                        let right_dec = Self::value_to_decimal(right_value)
986                            .ok_or_else(|| "Right operand is not numeric".to_string())?;
987                        let result = match op {
988                            BinaryOp::Plus => left_dec + right_dec,
989                            BinaryOp::Minus => left_dec - right_dec,
990                            BinaryOp::Multiply => left_dec * right_dec,
991                            BinaryOp::Divide => {
992                                if right_dec.is_zero() {
993                                    return Err("Division by zero".to_string());
994                                }
995                                left_dec / right_dec
996                            }
997                            _ => unreachable!(),
998                        };
999                        serde_json::json!(result.to_f64().ok_or_else(|| format!(
1000                            "Failed to convert arithmetic result {} to f64",
1001                            result
1002                        ))?)
1003                    }
1004                    BinaryOp::Contains | BinaryOp::StartsWith | BinaryOp::EndsWith => {
1005                        let left_str = left_value
1006                            .as_str()
1007                            .ok_or_else(|| "Left operand is not string".to_string())?;
1008                        let right_str = right_value
1009                            .as_str()
1010                            .ok_or_else(|| "Right operand is not string".to_string())?;
1011                        match op {
1012                            BinaryOp::Contains => serde_json::json!(left_str.contains(right_str)),
1013                            BinaryOp::StartsWith => {
1014                                serde_json::json!(left_str.starts_with(right_str))
1015                            }
1016                            BinaryOp::EndsWith => serde_json::json!(left_str.ends_with(right_str)),
1017                            _ => unreachable!(),
1018                        }
1019                    }
1020                    _ => return Ok(Expression::binary(op.clone(), left.clone(), right.clone())),
1021                };
1022                Ok(Expression::Literal(reduced))
1023            }
1024            _ => Ok(Expression::binary(op.clone(), left, right)),
1025        }
1026    }
1027
1028    fn value_to_f64(value: &serde_json::Value) -> Option<f64> {
1029        value
1030            .as_f64()
1031            .or_else(|| value.as_i64().map(|v| v as f64))
1032            .or_else(|| value.as_u64().map(|v| v as f64))
1033    }
1034
1035    /// Like [`Self::value_to_f64`], but keeps integers exact and routes
1036    /// floats through their shortest round-trip string form (matching
1037    /// [`Self::fold_numeric`]) instead of losing precision to binary
1038    /// floating point.
1039    fn value_to_decimal(value: &serde_json::Value) -> Option<Decimal> {
1040        if let Some(i) = value.as_i64() {
1041            return Some(Decimal::from(i));
1042        }
1043        if let Some(u) = value.as_u64() {
1044            return Some(Decimal::from(u));
1045        }
1046        value
1047            .as_f64()
1048            .and_then(|f| Decimal::from_str(&f.to_string()).ok())
1049    }
1050}