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