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) => match name.as_str() {
308                "flows" => {
309                    let flows: Result<Vec<serde_json::Value>, String> = graph
310                        .all_flows()
311                        .iter()
312                        .map(|f| {
313                            let quantity = f.quantity().to_f64().ok_or_else(|| {
314                                format!("Failed to convert flow quantity {} to f64", f.quantity())
315                            })?;
316
317                            let mut map = serde_json::Map::new();
318                            map.insert("id".to_string(), serde_json::json!(f.id().to_string()));
319                            map.insert(
320                                "from_entity".to_string(),
321                                serde_json::json!(f.from_id().to_string()),
322                            );
323                            map.insert(
324                                "to_entity".to_string(),
325                                serde_json::json!(f.to_id().to_string()),
326                            );
327                            map.insert(
328                                "resource".to_string(),
329                                serde_json::json!(f.resource_id().to_string()),
330                            );
331                            map.insert("quantity".to_string(), serde_json::json!(quantity));
332
333                            for (k, v) in f.attributes().iter() {
334                                if matches!(
335                                    k.as_str(),
336                                    "id" | "from_entity" | "to_entity" | "resource" | "quantity"
337                                ) || map.contains_key(k)
338                                {
339                                    continue;
340                                }
341                                map.insert(k.clone(), v.clone());
342                            }
343                            Ok(serde_json::Value::Object(map))
344                        })
345                        .collect();
346                    flows
347                }
348                "entities" => {
349                    let entities: Vec<serde_json::Value> = graph
350                        .all_entities()
351                        .iter()
352                        .map(|e| {
353                            let mut map = serde_json::Map::new();
354                            map.insert("id".to_string(), serde_json::json!(e.id().to_string()));
355                            map.insert("name".to_string(), serde_json::json!(e.name()));
356                            map.insert("namespace".to_string(), serde_json::json!(e.namespace()));
357
358                            let roles = graph.role_names_for_entity(e.id());
359                            if !roles.is_empty() {
360                                map.insert("roles".to_string(), serde_json::json!(roles));
361                            }
362
363                            for (k, v) in e.attributes().iter() {
364                                if matches!(k.as_str(), "id" | "name" | "namespace")
365                                    || map.contains_key(k)
366                                {
367                                    continue;
368                                }
369                                map.insert(k.clone(), v.clone());
370                            }
371
372                            serde_json::Value::Object(map)
373                        })
374                        .collect();
375                    Ok(entities)
376                }
377                "entity_instances" => {
378                    let instances = graph
379                        .all_entity_instances()
380                        .iter()
381                        .map(|instance| {
382                            let mut map = serde_json::Map::new();
383                            map.insert(
384                                "id".to_string(),
385                                serde_json::json!(instance.id().to_string()),
386                            );
387                            map.insert("name".to_string(), serde_json::json!(instance.name()));
388                            map.insert(
389                                "entity".to_string(),
390                                serde_json::json!(instance.entity_type()),
391                            );
392                            map.insert(
393                                "namespace".to_string(),
394                                serde_json::json!(instance.namespace()),
395                            );
396
397                            let mut fields: Vec<_> = instance.fields().iter().collect();
398                            fields.sort_by(|left, right| left.0.cmp(right.0));
399                            for (name, value) in fields {
400                                if matches!(name.as_str(), "id" | "name" | "entity" | "namespace") {
401                                    continue;
402                                }
403                                map.insert(name.clone(), value.clone());
404                            }
405                            serde_json::Value::Object(map)
406                        })
407                        .collect();
408                    Ok(instances)
409                }
410                "relations" => {
411                    let relations: Vec<serde_json::Value> = graph
412                        .all_relations()
413                        .iter()
414                        .map(|relation| {
415                            let mut map = serde_json::Map::new();
416                            map.insert(
417                                "id".to_string(),
418                                serde_json::json!(relation.id().to_string()),
419                            );
420                            map.insert("name".to_string(), serde_json::json!(relation.name()));
421                            map.insert(
422                                "predicate".to_string(),
423                                serde_json::json!(relation.predicate()),
424                            );
425
426                            if let Some(subject) = graph.get_role(relation.subject_role()) {
427                                map.insert(
428                                    "subject_role".to_string(),
429                                    serde_json::json!(subject.name()),
430                                );
431                            }
432
433                            if let Some(object) = graph.get_role(relation.object_role()) {
434                                map.insert(
435                                    "object_role".to_string(),
436                                    serde_json::json!(object.name()),
437                                );
438                            }
439
440                            if let Some(flow) = relation.via_flow() {
441                                map.insert("via".to_string(), serde_json::json!(flow.to_string()));
442                            }
443
444                            serde_json::Value::Object(map)
445                        })
446                        .collect();
447
448                    Ok(relations)
449                }
450                "resources" => {
451                    let resources: Vec<serde_json::Value> = graph
452                        .all_resources()
453                        .iter()
454                        .map(|r| {
455                            let mut map = serde_json::Map::new();
456                            map.insert("id".to_string(), serde_json::json!(r.id().to_string()));
457                            map.insert("name".to_string(), serde_json::json!(r.name()));
458                            map.insert("namespace".to_string(), serde_json::json!(r.namespace()));
459                            map.insert("unit".to_string(), serde_json::json!(r.unit()));
460                            for (k, v) in r.attributes().iter() {
461                                if matches!(k.as_str(), "id" | "name" | "namespace" | "unit")
462                                    || map.contains_key(k)
463                                {
464                                    continue;
465                                }
466                                map.insert(k.clone(), v.clone());
467                            }
468                            serde_json::Value::Object(map)
469                        })
470                        .collect();
471                    Ok(resources)
472                }
473                "instances" => {
474                    let instances: Vec<serde_json::Value> = graph
475                        .all_instances()
476                        .iter()
477                        .map(|i| {
478                            let mut map = serde_json::Map::new();
479                            map.insert("id".to_string(), serde_json::json!(i.id().to_string()));
480                            map.insert(
481                                "entity".to_string(),
482                                serde_json::json!(i.entity_id().to_string()),
483                            );
484                            map.insert(
485                                "resource".to_string(),
486                                serde_json::json!(i.resource_id().to_string()),
487                            );
488                            for (k, v) in i.attributes().iter() {
489                                if matches!(k.as_str(), "id" | "entity" | "resource")
490                                    || map.contains_key(k)
491                                {
492                                    continue;
493                                }
494                                map.insert(k.clone(), v.clone());
495                            }
496                            serde_json::Value::Object(map)
497                        })
498                        .collect();
499                    Ok(instances)
500                }
501                _ => Err(format!("Unknown collection: {}", name)),
502            },
503            Expression::Literal(serde_json::Value::Array(arr)) => Ok(arr.clone()),
504            _ => Err("Collection expression must be a variable or array literal".to_string()),
505        }
506    }
507
508    fn is_true_literal(expr: &Expression) -> bool {
509        matches!(expr, Expression::Literal(v) if v.as_bool() == Some(true))
510    }
511
512    pub(crate) fn evaluate_aggregation(
513        function: &AggregateFunction,
514        collection: &Expression,
515        field: &Option<String>,
516        filter: &Option<Box<Expression>>,
517        graph: &Graph,
518    ) -> Result<serde_json::Value, String> {
519        // Get the collection items
520        let items = Self::get_collection(collection, graph)?;
521
522        // Apply filter if present
523        let filtered_items = if let Some(filter_expr) = filter {
524            // Determine the variable name based on collection type
525            let variable_name = match collection {
526                Expression::Variable(name) => match name.as_str() {
527                    "flows" => "flow",
528                    "entities" => "entity",
529                    "entity_instances" => "entity_instance",
530                    "resources" => "resource",
531                    "instances" => "instance",
532                    "relations" => "relation",
533                    _ => "item",
534                },
535                _ => "item",
536            };
537
538            items
539                .into_iter()
540                .filter(|item| {
541                    // Substitute collection-specific variables in the filter
542                    let substituted = filter_expr
543                        .substitute(variable_name, item)
544                        .unwrap_or_else(|_| filter_expr.as_ref().clone());
545                    // Expand and check if true
546                    if let Ok(expanded) = substituted.expand(graph) {
547                        Self::is_true_literal(&expanded)
548                    } else {
549                        false
550                    }
551                })
552                .collect::<Vec<_>>()
553        } else {
554            items
555        };
556
557        // Apply aggregation function
558        match function {
559            AggregateFunction::Count => Ok(serde_json::json!(filtered_items.len())),
560
561            AggregateFunction::Sum => {
562                let field_name = field.as_ref().ok_or("Sum requires a field specification")?;
563
564                let sum: Decimal = filtered_items
565                    .iter()
566                    .filter_map(|item| {
567                        item.get(field_name).and_then(|v| {
568                            if let Some(num) = v.as_f64() {
569                                Decimal::from_str(&num.to_string()).ok()
570                            } else if let Some(s) = v.as_str() {
571                                Decimal::from_str(s).ok()
572                            } else {
573                                None
574                            }
575                        })
576                    })
577                    .sum();
578
579                // Convert Decimal to f64 and propagate parsing errors
580                let sum_f64 = sum
581                    .to_f64()
582                    .ok_or_else(|| format!("Failed to convert sum {} to f64", sum))?;
583
584                Ok(serde_json::json!(sum_f64))
585            }
586
587            AggregateFunction::Avg => {
588                let field_name = field.as_ref().ok_or("Avg requires a field specification")?;
589
590                let values: Vec<Decimal> = filtered_items
591                    .iter()
592                    .filter_map(|item| {
593                        item.get(field_name).and_then(|v| {
594                            if let Some(num) = v.as_f64() {
595                                Decimal::from_str(&num.to_string()).ok()
596                            } else if let Some(s) = v.as_str() {
597                                Decimal::from_str(s).ok()
598                            } else {
599                                None
600                            }
601                        })
602                    })
603                    .collect();
604
605                if values.is_empty() {
606                    return Ok(serde_json::json!(null));
607                }
608
609                let sum: Decimal = values.iter().copied().sum();
610                let avg = sum / Decimal::from(values.len());
611
612                // Convert Decimal to f64 and propagate parsing errors
613                let avg_f64 = avg
614                    .to_f64()
615                    .ok_or_else(|| format!("Failed to convert average {} to f64", avg))?;
616
617                Ok(serde_json::json!(avg_f64))
618            }
619
620            AggregateFunction::Min => {
621                let field_name = field.as_ref().ok_or("Min requires a field specification")?;
622
623                let min = 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                    .min();
637
638                // Convert Decimal to f64 and propagate parsing errors
639                if let Some(min_val) = min {
640                    let min_f64 = min_val
641                        .to_f64()
642                        .ok_or_else(|| format!("Failed to convert min {} to f64", min_val))?;
643                    Ok(serde_json::json!(min_f64))
644                } else {
645                    Ok(serde_json::json!(null))
646                }
647            }
648
649            AggregateFunction::Max => {
650                let field_name = field.as_ref().ok_or("Max requires a field specification")?;
651
652                let max = filtered_items
653                    .iter()
654                    .filter_map(|item| {
655                        item.get(field_name).and_then(|v| {
656                            if let Some(num) = v.as_f64() {
657                                Decimal::from_str(&num.to_string()).ok()
658                            } else if let Some(s) = v.as_str() {
659                                Decimal::from_str(s).ok()
660                            } else {
661                                None
662                            }
663                        })
664                    })
665                    .max();
666
667                // Convert Decimal to f64 and propagate parsing errors
668                if let Some(max_val) = max {
669                    let max_f64 = max_val
670                        .to_f64()
671                        .ok_or_else(|| format!("Failed to convert max {} to f64", max_val))?;
672                    Ok(serde_json::json!(max_f64))
673                } else {
674                    Ok(serde_json::json!(null))
675                }
676            }
677        }
678    }
679
680    #[allow(clippy::too_many_arguments)]
681    pub(crate) fn evaluate_aggregation_comprehension(
682        function: &AggregateFunction,
683        variable: &str,
684        collection: &Expression,
685        window: &Option<crate::policy::WindowSpec>,
686        predicate: &Expression,
687        projection: &Expression,
688        target_unit: Option<&str>,
689        graph: &Graph,
690    ) -> Result<serde_json::Value, String> {
691        let items = Self::get_collection(collection, graph)?;
692
693        // Apply window filtering if present
694        let items = if let Some(w) = window {
695            let now = chrono::Utc::now();
696            let duration_span = i64::try_from(w.duration)
697                .map_err(|_| format!("Window duration {} exceeds supported range", w.duration))?;
698            let unit_lower = w.unit.to_lowercase();
699            let duration = match unit_lower.as_str() {
700                "hour" | "hours" => chrono::Duration::hours(duration_span),
701                "minute" | "minutes" => chrono::Duration::minutes(duration_span),
702                "day" | "days" => chrono::Duration::days(duration_span),
703                "second" | "seconds" => chrono::Duration::seconds(duration_span),
704                _ => {
705                    return Err(format!(
706                        "Invalid window unit '{}' in aggregation window",
707                        w.unit
708                    ))
709                }
710            };
711
712            items
713                .into_iter()
714                .filter(|item| {
715                    let ts_str = item
716                        .get("timestamp")
717                        .or_else(|| item.get("created_at"))
718                        .and_then(|v| v.as_str());
719                    if let Some(s) = ts_str {
720                        if let Ok(ts) = chrono::DateTime::parse_from_rfc3339(s) {
721                            let ts_utc: chrono::DateTime<chrono::Utc> = ts.into();
722                            return ts_utc >= now - duration;
723                        }
724                    }
725                    // If no timestamp, we can't filter, so maybe exclude? Or include?
726                    // Safer to exclude if windowing is requested but data is missing.
727                    false
728                })
729                .collect()
730        } else {
731            items
732        };
733
734        let mut projected_values = Vec::new();
735        for item in items {
736            let substituted_predicate = predicate.substitute(variable, &item)?;
737            let predicate_result = substituted_predicate.expand(graph)?;
738            if !Self::is_true_literal(&predicate_result) {
739                continue;
740            }
741
742            let substituted_projection = projection.substitute(variable, &item)?;
743            let projection_result = substituted_projection.expand(graph)?;
744            match projection_result {
745                Expression::Literal(value) => projected_values.push(value),
746                Expression::QuantityLiteral { value, unit } => {
747                    projected_values.push(serde_json::json!({
748                        "__quantity_value": value.to_string(),
749                        "__quantity_unit": unit,
750                    }));
751                }
752                _ => {
753                    return Err(
754                        "Projection in aggregation comprehension must reduce to a literal"
755                            .to_string(),
756                    );
757                }
758            }
759        }
760
761        match function {
762            AggregateFunction::Count => Ok(serde_json::json!(projected_values.len())),
763            AggregateFunction::Sum
764            | AggregateFunction::Avg
765            | AggregateFunction::Min
766            | AggregateFunction::Max => {
767                Self::fold_numeric(function, &projected_values, target_unit)
768            }
769        }
770    }
771
772    pub(crate) fn fold_numeric(
773        function: &AggregateFunction,
774        values: &[serde_json::Value],
775        target_unit: Option<&str>,
776    ) -> Result<serde_json::Value, String> {
777        use crate::units::UnitRegistry;
778
779        let mut decimals: Vec<Decimal> = Vec::new();
780        let mut source_unit: Option<String> = None;
781        for value in values {
782            if let Some(num) = value.as_f64() {
783                decimals.push(Decimal::from_str(&num.to_string()).map_err(|e| e.to_string())?);
784            } else if let Some(s) = value.as_str() {
785                decimals.push(Decimal::from_str(s).map_err(|e| e.to_string())?);
786            } else if value.is_object() {
787                let map = value
788                    .as_object()
789                    .ok_or_else(|| "Invalid quantity object".to_string())?;
790                if let Some(val) = map.get("__quantity_value") {
791                    let s = val
792                        .as_str()
793                        .ok_or_else(|| "Quantity value must be a string".to_string())?;
794                    decimals.push(Decimal::from_str(s).map_err(|e| e.to_string())?);
795                }
796                if let Some(unit) = map.get("__quantity_unit") {
797                    if source_unit.is_none() {
798                        if let Some(unit_str) = unit.as_str() {
799                            source_unit = Some(unit_str.to_string());
800                        }
801                    }
802                }
803            }
804        }
805
806        if decimals.is_empty() {
807            return Ok(serde_json::json!(null));
808        }
809
810        if let Some(target_unit) = target_unit {
811            if let Some(unit) = source_unit.clone() {
812                let registry = UnitRegistry::global();
813                let registry = registry
814                    .read()
815                    .map_err(|e| format!("Failed to lock unit registry: {}", e))?;
816                let from = registry
817                    .get_unit(&unit)
818                    .map_err(|e| format!("{}", e))?
819                    .clone();
820                let to = registry
821                    .get_unit(target_unit)
822                    .map_err(|e| format!("{}", e))?
823                    .clone();
824                decimals = decimals
825                    .into_iter()
826                    .map(|value| registry.convert(value, &from, &to))
827                    .collect::<Result<Vec<_>, _>>()
828                    .map_err(|e| format!("{}", e))?;
829            }
830        }
831
832        let result = match function {
833            AggregateFunction::Sum => decimals.iter().copied().sum(),
834            AggregateFunction::Avg => {
835                let sum: Decimal = decimals.iter().copied().sum();
836                sum / Decimal::from(decimals.len())
837            }
838            AggregateFunction::Min => decimals
839                .into_iter()
840                .min()
841                .ok_or_else(|| "No values available for min".to_string())?,
842            AggregateFunction::Max => decimals
843                .into_iter()
844                .max()
845                .ok_or_else(|| "No values available for max".to_string())?,
846            AggregateFunction::Count => Decimal::from(values.len() as i64),
847        };
848
849        let as_f64 = result
850            .to_f64()
851            .ok_or_else(|| format!("Failed to convert aggregated value {} to f64", result))?;
852
853        Ok(serde_json::json!(as_f64))
854    }
855
856    fn reduce_binary_expression(
857        op: &BinaryOp,
858        left: Expression,
859        right: Expression,
860    ) -> Result<Expression, String> {
861        match (&left, &right) {
862            (Expression::Literal(left_value), Expression::Literal(right_value)) => {
863                // Preserve tri-state semantics: if either operand is NULL, yield NULL.
864                if left_value.is_null() || right_value.is_null() {
865                    return Ok(Expression::Literal(serde_json::Value::Null));
866                }
867
868                let numeric_cmp = left_value.is_number() && right_value.is_number();
869                let reduced = match op {
870                    BinaryOp::Equal => {
871                        if numeric_cmp {
872                            let left_num = Self::value_to_f64(left_value)
873                                .ok_or_else(|| "Left operand is not numeric".to_string())?;
874                            let right_num = Self::value_to_f64(right_value)
875                                .ok_or_else(|| "Right operand is not numeric".to_string())?;
876                            serde_json::json!(left_num == right_num)
877                        } else {
878                            serde_json::json!(left_value == right_value)
879                        }
880                    }
881                    BinaryOp::NotEqual => {
882                        if numeric_cmp {
883                            let left_num = Self::value_to_f64(left_value)
884                                .ok_or_else(|| "Left operand is not numeric".to_string())?;
885                            let right_num = Self::value_to_f64(right_value)
886                                .ok_or_else(|| "Right operand is not numeric".to_string())?;
887                            serde_json::json!(left_num != right_num)
888                        } else {
889                            serde_json::json!(left_value != right_value)
890                        }
891                    }
892                    BinaryOp::GreaterThan
893                    | BinaryOp::LessThan
894                    | BinaryOp::GreaterThanOrEqual
895                    | BinaryOp::LessThanOrEqual => {
896                        let left_num = Self::value_to_f64(left_value)
897                            .ok_or_else(|| "Left operand is not numeric".to_string())?;
898                        let right_num = Self::value_to_f64(right_value)
899                            .ok_or_else(|| "Right operand is not numeric".to_string())?;
900                        match op {
901                            BinaryOp::GreaterThan => serde_json::json!(left_num > right_num),
902                            BinaryOp::LessThan => serde_json::json!(left_num < right_num),
903                            BinaryOp::GreaterThanOrEqual => {
904                                serde_json::json!(left_num >= right_num)
905                            }
906                            BinaryOp::LessThanOrEqual => serde_json::json!(left_num <= right_num),
907                            _ => unreachable!(),
908                        }
909                    }
910                    BinaryOp::And | BinaryOp::Or => {
911                        let left_bool = match left_value {
912                            serde_json::Value::Bool(b) => Some(*b),
913                            serde_json::Value::Null => None,
914                            _ => return Err("Left operand is not boolean".to_string()),
915                        };
916                        let right_bool = match right_value {
917                            serde_json::Value::Bool(b) => Some(*b),
918                            serde_json::Value::Null => None,
919                            _ => return Err("Right operand is not boolean".to_string()),
920                        };
921
922                        match op {
923                            BinaryOp::And => {
924                                if left_bool == Some(false) || right_bool == Some(false) {
925                                    serde_json::json!(false)
926                                } else if left_bool.is_none() || right_bool.is_none() {
927                                    serde_json::Value::Null
928                                } else {
929                                    serde_json::json!(left_bool.unwrap() && right_bool.unwrap())
930                                }
931                            }
932                            BinaryOp::Or => {
933                                if left_bool == Some(true) || right_bool == Some(true) {
934                                    serde_json::json!(true)
935                                } else if left_bool.is_none() || right_bool.is_none() {
936                                    serde_json::Value::Null
937                                } else {
938                                    serde_json::json!(left_bool.unwrap() || right_bool.unwrap())
939                                }
940                            }
941                            _ => unreachable!(),
942                        }
943                    }
944                    BinaryOp::Contains | BinaryOp::StartsWith | BinaryOp::EndsWith => {
945                        let left_str = left_value
946                            .as_str()
947                            .ok_or_else(|| "Left operand is not string".to_string())?;
948                        let right_str = right_value
949                            .as_str()
950                            .ok_or_else(|| "Right operand is not string".to_string())?;
951                        match op {
952                            BinaryOp::Contains => serde_json::json!(left_str.contains(right_str)),
953                            BinaryOp::StartsWith => {
954                                serde_json::json!(left_str.starts_with(right_str))
955                            }
956                            BinaryOp::EndsWith => serde_json::json!(left_str.ends_with(right_str)),
957                            _ => unreachable!(),
958                        }
959                    }
960                    _ => return Ok(Expression::binary(op.clone(), left.clone(), right.clone())),
961                };
962                Ok(Expression::Literal(reduced))
963            }
964            _ => Ok(Expression::binary(op.clone(), left, right)),
965        }
966    }
967
968    fn value_to_f64(value: &serde_json::Value) -> Option<f64> {
969        value
970            .as_f64()
971            .or_else(|| value.as_i64().map(|v| v as f64))
972            .or_else(|| value.as_u64().map(|v| v as f64))
973    }
974}