Skip to main content

uqa_execution/aggregation/
accumulator.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Streaming aggregate state and registered aggregate adapters.
8
9use super::state::{with_cleanup, RegisteredAggregateState};
10use super::{
11    value_as_f64, AggregateValueBuffer, Arc, DecimalValue, DistinctTracker,
12    RegisteredAggregateBuffer, SQLAggregateFactory, SQLAggregateState, SQLError, Value,
13};
14use uqa_core::TemporalInfinity;
15use uqa_sql::expr::enums::{EnumComparisonState, EnumLabelCatalog};
16use uqa_sql::expr::IntervalFields;
17
18pub struct AggregateAccumulator {
19    pub(super) registered: Option<Arc<dyn SQLAggregateFactory>>,
20    pub(super) registered_state: RegisteredAggregateState,
21    pub(super) registered_ordered: RegisteredAggregateBuffer,
22    pub(super) count: u64,
23    pub(super) sum: f64,
24    pub(super) integer_sum: i128,
25    pub(super) decimal_sum: Option<DecimalValue>,
26    /// The finite `sumX` of `sum(interval)` and `avg(interval)`; infinite inputs are counted separately.
27    pub(super) interval_sum: Option<IntervalFields>,
28    pub(super) interval_positive_infinity: u64,
29    pub(super) interval_negative_infinity: u64,
30    pub(super) numeric_inputs: NumericInputKind,
31    pub(super) min: Option<Value>,
32    pub(super) max: Option<Value>,
33    /// MIN/MAX's transition support function belongs to the call, across groups and frame restarts.
34    pub(super) enum_comparison: Option<Arc<EnumComparisonState>>,
35    /// DISTINCT arguments are sorted with their SQL comparison operators before finalization.
36    pub(super) distinct: DistinctTracker,
37    /// Only collection, ordered-set, and statistical aggregates need
38    /// their complete input. Streaming aggregates keep constant-size
39    /// state and must not spill values that their finalizer never reads.
40    pub(super) state_plan: AggregateStatePlan,
41    pub(super) values: AggregateValueBuffer,
42    /// Shape of the first `array_agg(anyarray)` input observed in transition order.
43    pub(super) array_inputs: super::array_inputs::ArrayInputShape,
44    /// Boolean folds for `BOOL_AND` / `BOOL_OR`. Stay `None` until the
45    /// first observation so an empty input set returns `NULL` (matches
46    /// `PostgreSQL`).
47    pub(super) bool_and: Option<bool>,
48    pub(super) bool_or: Option<bool>,
49    /// Welford state for variance/stddev. This avoids retaining the complete group for statistical aggregates.
50    pub(super) statistics_count: u64,
51    pub(super) statistics_mean: f64,
52    pub(super) statistics_m2: f64,
53    pub(super) statistics_moments_valid: bool,
54    pub(super) statistics_has_float: bool,
55    pub(super) statistics_nonzero_deviation: bool,
56    pub(super) statistics_origin: Option<DecimalValue>,
57    pub(super) statistics_sum: Option<DecimalValue>,
58    pub(super) statistics_sum_squares: Option<DecimalValue>,
59}
60
61#[derive(Clone, Copy, Default)]
62pub enum NumericInputKind {
63    #[default]
64    Integers,
65    Decimals,
66    Floats,
67    DecimalsAndFloats,
68}
69
70impl NumericInputKind {
71    pub(super) fn observe_decimal(&mut self) {
72        *self = match self {
73            Self::Integers | Self::Decimals => Self::Decimals,
74            Self::Floats | Self::DecimalsAndFloats => Self::DecimalsAndFloats,
75        };
76    }
77
78    pub(super) fn observe_float(&mut self) {
79        *self = match self {
80            Self::Integers | Self::Floats => Self::Floats,
81            Self::Decimals | Self::DecimalsAndFloats => Self::DecimalsAndFloats,
82        };
83    }
84
85    pub(super) fn all_integers(self) -> bool {
86        matches!(self, Self::Integers)
87    }
88
89    pub(super) fn decimal_without_float(self) -> bool {
90        matches!(self, Self::Decimals)
91    }
92
93    pub(super) fn has_decimal(self) -> bool {
94        matches!(self, Self::Decimals | Self::DecimalsAndFloats)
95    }
96
97    pub(super) fn has_float(self) -> bool {
98        matches!(self, Self::Floats | Self::DecimalsAndFloats)
99    }
100}
101
102#[derive(Clone, Copy)]
103pub enum AggregateStatePlan {
104    /// Conservative fallback for an aggregate whose state requirements
105    /// are not known here.
106    Generic,
107    Count,
108    Sum,
109    SumReal,
110    Min,
111    Max,
112    BoolAnd,
113    BoolOr,
114    /// Retains non-NULL inputs: `string_agg`, the ordered-set aggregates and the JSON object aggregates, whose pairs are never NULL.
115    Buffered,
116    /// Retains every input including NULL, as `array_agg` over non-array input, `json_agg` and `jsonb_agg` do.
117    BufferedWithNulls,
118    /// `array_agg` over array input, whose transition rejects NULL, empty and differently shaped arrays.
119    BufferedArrays,
120    Statistics,
121}
122
123impl AggregateStatePlan {
124    pub(super) fn builtin_with_input_type(
125        name: &str,
126        input_type: Option<&uqa_sql::ast::ColumnType>,
127    ) -> Self {
128        use uqa_sql::ast::ColumnType;
129        let name = uqa_sql::semantics::builtin_aggregate_dispatch_name(name);
130        if let Some(ColumnType::Domain { base, .. }) = input_type {
131            return Self::builtin_with_input_type(name, Some(base));
132        }
133        if name.eq_ignore_ascii_case("sum") && matches!(input_type, Some(ColumnType::Real)) {
134            Self::SumReal
135        } else if name.eq_ignore_ascii_case("array_agg")
136            && matches!(input_type, Some(ColumnType::Array(_)))
137        {
138            Self::BufferedArrays
139        } else {
140            Self::builtin(name)
141        }
142    }
143
144    pub(super) fn builtin(name: &str) -> Self {
145        let name = uqa_sql::semantics::builtin_aggregate_dispatch_name(name);
146        match name.to_ascii_lowercase().as_str() {
147            "count" => Self::Count,
148            "sum" | "avg" => Self::Sum,
149            "min" => Self::Min,
150            "max" => Self::Max,
151            "bool_and" => Self::BoolAnd,
152            "bool_or" => Self::BoolOr,
153            "stddev" | "stddev_samp" | "stddev_pop" | "variance" | "var_samp" | "var_pop" => {
154                Self::Statistics
155            }
156            "array_agg" | "json_agg" | "jsonb_agg" => Self::BufferedWithNulls,
157            "string_agg" | "json_object_agg" | "jsonb_object_agg" | "percentile_cont"
158            | "percentile_disc" | "mode" => Self::Buffered,
159            _ => Self::Generic,
160        }
161    }
162
163    pub(super) fn retains_values(self) -> bool {
164        matches!(
165            self,
166            Self::Generic | Self::Buffered | Self::BufferedWithNulls | Self::BufferedArrays
167        )
168    }
169}
170
171impl Default for AggregateAccumulator {
172    fn default() -> Self {
173        Self {
174            registered: None,
175            registered_state: RegisteredAggregateState::default(),
176            registered_ordered: RegisteredAggregateBuffer::default(),
177            count: 0,
178            sum: 0.0,
179            integer_sum: 0,
180            decimal_sum: None,
181            interval_sum: None,
182            interval_positive_infinity: 0,
183            interval_negative_infinity: 0,
184            numeric_inputs: NumericInputKind::default(),
185            min: None,
186            max: None,
187            enum_comparison: None,
188            distinct: DistinctTracker::default(),
189            state_plan: AggregateStatePlan::Generic,
190            values: AggregateValueBuffer::default(),
191            array_inputs: super::array_inputs::ArrayInputShape::default(),
192            bool_and: None,
193            bool_or: None,
194            statistics_count: 0,
195            statistics_mean: 0.0,
196            statistics_m2: 0.0,
197            statistics_moments_valid: true,
198            statistics_has_float: false,
199            statistics_nonzero_deviation: false,
200            statistics_origin: None,
201            statistics_sum: None,
202            statistics_sum_squares: None,
203        }
204    }
205}
206
207impl AggregateAccumulator {
208    pub(super) fn with_budget(budget_bytes: usize) -> Self {
209        let component_budget = (budget_bytes / 2).max(1);
210        Self {
211            registered: None,
212            registered_state: RegisteredAggregateState::default(),
213            registered_ordered: RegisteredAggregateBuffer::new(component_budget),
214            count: 0,
215            sum: 0.0,
216            integer_sum: 0,
217            decimal_sum: None,
218            interval_sum: None,
219            interval_positive_infinity: 0,
220            interval_negative_infinity: 0,
221            numeric_inputs: NumericInputKind::default(),
222            min: None,
223            max: None,
224            enum_comparison: None,
225            distinct: DistinctTracker::new(component_budget),
226            state_plan: AggregateStatePlan::Generic,
227            values: AggregateValueBuffer::new(component_budget),
228            array_inputs: super::array_inputs::ArrayInputShape::default(),
229            bool_and: None,
230            bool_or: None,
231            statistics_count: 0,
232            statistics_mean: 0.0,
233            statistics_m2: 0.0,
234            statistics_moments_valid: true,
235            statistics_has_float: false,
236            statistics_nonzero_deviation: false,
237            statistics_origin: None,
238            statistics_sum: None,
239            statistics_sum_squares: None,
240        }
241    }
242
243    pub fn builtin(name: &str) -> Self {
244        Self {
245            state_plan: AggregateStatePlan::builtin(name),
246            ..Self::default()
247        }
248    }
249
250    pub fn builtin_with_input_type(
251        name: &str,
252        input_type: Option<&uqa_sql::ast::ColumnType>,
253    ) -> Self {
254        let mut accumulator = Self::builtin(name);
255        accumulator.state_plan = AggregateStatePlan::builtin_with_input_type(name, input_type);
256        accumulator.enum_comparison = super::template::enum_extrema_state(name, input_type);
257        accumulator
258    }
259
260    pub(super) fn builtin_with_budget(name: &str, budget_bytes: usize) -> Self {
261        Self::from_plan_with_budget(AggregateStatePlan::builtin(name), budget_bytes)
262    }
263
264    pub(super) fn from_plan_with_budget(
265        state_plan: AggregateStatePlan,
266        budget_bytes: usize,
267    ) -> Self {
268        let mut accumulator = Self::with_budget(budget_bytes);
269        accumulator.state_plan = state_plan;
270        accumulator
271    }
272
273    pub(super) fn registered_with_budget(
274        function: Arc<dyn SQLAggregateFactory>,
275        budget_bytes: usize,
276    ) -> Result<Self, SQLError> {
277        let state = RegisteredAggregateState::new(function.try_create_state()?);
278        Ok(Self::with_registered_state(function, state, budget_bytes))
279    }
280
281    fn with_registered_state(
282        function: Arc<dyn SQLAggregateFactory>,
283        state: RegisteredAggregateState,
284        budget_bytes: usize,
285    ) -> Self {
286        let mut accumulator = Self::with_budget(budget_bytes);
287        accumulator.registered = Some(function);
288        accumulator.registered_state = state;
289        accumulator
290    }
291
292    pub(super) fn replay_with_budget(&self, budget_bytes: usize) -> Result<Self, SQLError> {
293        match &self.registered {
294            Some(function) => Ok(Self::with_registered_state(
295                Arc::clone(function),
296                self.registered_state.replay(function.as_ref())?,
297                budget_bytes,
298            )),
299            None => Ok(Self::from_plan_with_budget(self.state_plan, budget_bytes)),
300        }
301    }
302
303    pub fn observe(&mut self, value: &Value) -> Result<(), SQLError> {
304        self.observe_with_enum_catalog(value, None)
305    }
306
307    pub fn observe_with_enum_catalog(
308        &mut self,
309        value: &Value,
310        enums: Option<&dyn EnumLabelCatalog>,
311    ) -> Result<(), SQLError> {
312        if let AggregateStatePlan::BufferedArrays = self.state_plan {
313            self.array_inputs.accept(value)?;
314        }
315        if matches!(value, Value::Null) {
316            return self.observe_null(Vec::new(), enums);
317        }
318        self.observe_state(value, enums)?;
319        if self.state_plan.retains_values() {
320            self.values.push(value.clone(), Vec::new(), enums)?;
321        }
322        Ok(())
323    }
324
325    pub(super) fn observe_projected(
326        &mut self,
327        value: &Value,
328        enums: Option<&dyn EnumLabelCatalog>,
329    ) -> Result<(), SQLError> {
330        match value {
331            Value::Int(value) => self.observe_projected_integer(*value),
332            _ => self.observe_with_enum_catalog(value, enums),
333        }
334    }
335
336    pub(super) fn observe_projected_integer(&mut self, value: i64) -> Result<(), SQLError> {
337        match self.state_plan {
338            AggregateStatePlan::Count => {
339                self.count = self
340                    .count
341                    .checked_add(1)
342                    .ok_or_else(|| SQLError::TypeMismatch("aggregate count overflow".into()))?;
343                Ok(())
344            }
345            AggregateStatePlan::Sum | AggregateStatePlan::SumReal => {
346                self.count = self
347                    .count
348                    .checked_add(1)
349                    .ok_or_else(|| SQLError::TypeMismatch("aggregate count overflow".into()))?;
350                self.integer_sum = self
351                    .integer_sum
352                    .checked_add(i128::from(value))
353                    .ok_or_else(|| SQLError::TypeMismatch("integer aggregate overflow".into()))?;
354                if self.numeric_inputs.has_decimal() {
355                    let next = DecimalValue::from_i64(value);
356                    self.decimal_sum = Some(
357                        self.decimal_sum
358                            .as_ref()
359                            .and_then(|sum| sum.checked_add(&next))
360                            .ok_or_else(|| {
361                                SQLError::TypeMismatch("decimal aggregate overflow".into())
362                            })?,
363                    );
364                }
365                if self.numeric_inputs.has_float() {
366                    self.sum += value as f64;
367                }
368                Ok(())
369            }
370            _ => self.observe(&Value::Int(value)),
371        }
372    }
373
374    pub(super) fn observe_state(
375        &mut self,
376        value: &Value,
377        enums: Option<&dyn EnumLabelCatalog>,
378    ) -> Result<(), SQLError> {
379        // Only transitions that inspect scalar payloads decode them. COUNT and
380        // collection transitions retain lazy inputs; MIN/MAX use SQL comparison.
381        let decoded;
382        let value = if matches!(value, Value::Datum(_)) {
383            if matches!(
384                self.state_plan,
385                AggregateStatePlan::Generic
386                    | AggregateStatePlan::Sum
387                    | AggregateStatePlan::SumReal
388                    | AggregateStatePlan::BoolAnd
389                    | AggregateStatePlan::BoolOr
390                    | AggregateStatePlan::Statistics
391            ) {
392                decoded = super::observation::read(value, enums)?;
393                &*decoded
394            } else {
395                value
396            }
397        } else {
398            value
399        };
400        match self.state_plan {
401            AggregateStatePlan::Generic => {
402                self.count = self
403                    .count
404                    .checked_add(1)
405                    .ok_or_else(|| SQLError::TypeMismatch("aggregate count overflow".into()))?;
406                if matches!(value, Value::Int(_) | Value::Float(_) | Value::Decimal(_)) {
407                    self.observe_sum(value)?;
408                }
409                self.observe_min(value, enums)?;
410                self.observe_max(value, enums)?;
411                if matches!(value, Value::Bool(_)) {
412                    self.observe_bool_and(value)?;
413                    self.observe_bool_or(value)?;
414                }
415            }
416            AggregateStatePlan::Count => {
417                self.count = self
418                    .count
419                    .checked_add(1)
420                    .ok_or_else(|| SQLError::TypeMismatch("aggregate count overflow".into()))?;
421            }
422            AggregateStatePlan::Sum | AggregateStatePlan::SumReal => {
423                self.count = self
424                    .count
425                    .checked_add(1)
426                    .ok_or_else(|| SQLError::TypeMismatch("aggregate count overflow".into()))?;
427                self.observe_sum(value)?;
428            }
429            AggregateStatePlan::Min => self.observe_min(value, enums)?,
430            AggregateStatePlan::Max => self.observe_max(value, enums)?,
431            AggregateStatePlan::BoolAnd => self.observe_bool_and(value)?,
432            AggregateStatePlan::BoolOr => self.observe_bool_or(value)?,
433            AggregateStatePlan::Buffered
434            | AggregateStatePlan::BufferedWithNulls
435            | AggregateStatePlan::BufferedArrays => {}
436            AggregateStatePlan::Statistics => self.observe_statistics(value)?,
437        }
438        Ok(())
439    }
440
441    fn observe_statistics(&mut self, value: &Value) -> Result<(), SQLError> {
442        let previous_count = self.statistics_count;
443        let next_count = previous_count
444            .checked_add(1)
445            .ok_or_else(|| SQLError::TypeMismatch("statistical aggregate count overflow".into()))?;
446        if matches!(value, Value::Float(_)) {
447            if !self.statistics_moments_valid {
448                return Err(SQLError::TypeMismatch(
449                    "numeric statistical state does not fit double precision".into(),
450                ));
451            }
452            self.statistics_has_float = true;
453            self.observe_float_statistic(value_as_f64(value)?, next_count);
454        } else {
455            let decimal = match value {
456                Value::Int(value) => DecimalValue::from_i64(*value),
457                Value::Decimal(value) => value.clone(),
458                other => {
459                    return Err(SQLError::TypeMismatch(format!(
460                        "statistical aggregate requires a numeric value, got {other:?}"
461                    )))
462                }
463            };
464            if self.statistics_moments_valid {
465                if let Some(float) = decimal.to_f64() {
466                    self.observe_float_statistic(float, next_count);
467                } else {
468                    self.statistics_moments_valid = false;
469                    if self.statistics_has_float {
470                        return Err(SQLError::TypeMismatch(
471                            "numeric statistical input does not fit double precision".into(),
472                        ));
473                    }
474                }
475            }
476            if decimal.is_nan() || decimal.is_infinite() {
477                let nan = decimal.checked_sub(&decimal).ok_or_else(|| {
478                    SQLError::Internal("numeric special value did not produce NaN".into())
479                })?;
480                self.statistics_origin
481                    .get_or_insert_with(|| DecimalValue::from_i64(0));
482                self.statistics_sum = Some(nan.clone());
483                self.statistics_sum_squares = Some(nan);
484                self.statistics_nonzero_deviation = true;
485                self.statistics_count = next_count;
486                return Ok(());
487            }
488            if self
489                .statistics_sum_squares
490                .as_ref()
491                .is_some_and(DecimalValue::is_nan)
492            {
493                self.statistics_count = next_count;
494                return Ok(());
495            }
496            let origin = if let Some(origin) = &self.statistics_origin {
497                origin.clone()
498            } else {
499                let origin = decimal.clone();
500                self.statistics_origin = Some(origin.clone());
501                origin
502            };
503            let deviation = decimal.checked_sub(&origin).ok_or_else(|| {
504                SQLError::TypeMismatch("numeric statistical deviation overflow".into())
505            })?;
506            self.statistics_nonzero_deviation |= !deviation.is_zero();
507            let square = deviation.checked_mul(&deviation).ok_or_else(|| {
508                SQLError::TypeMismatch("numeric statistical deviation square overflow".into())
509            })?;
510            self.statistics_sum = Some(match self.statistics_sum.take() {
511                Some(sum) => sum.checked_add(&deviation).ok_or_else(|| {
512                    SQLError::TypeMismatch("numeric statistical deviation sum overflow".into())
513                })?,
514                None => deviation,
515            });
516            self.statistics_sum_squares = Some(match self.statistics_sum_squares.take() {
517                Some(sum) => sum.checked_add(&square).ok_or_else(|| {
518                    SQLError::TypeMismatch(
519                        "numeric statistical deviation square sum overflow".into(),
520                    )
521                })?,
522                None => square,
523            });
524        }
525        self.statistics_count = next_count;
526        Ok(())
527    }
528
529    fn observe_float_statistic(&mut self, value: f64, count: u64) {
530        let delta = value - self.statistics_mean;
531        self.statistics_mean += delta / count as f64;
532        let delta_after = value - self.statistics_mean;
533        self.statistics_m2 += delta * delta_after;
534    }
535
536    pub(super) fn observe_sum(&mut self, value: &Value) -> Result<(), SQLError> {
537        if let Value::Temporal(temporal) = value {
538            let interval = IntervalFields::of(temporal).ok_or_else(|| {
539                SQLError::TypeMismatch(format!(
540                    "SUM/AVG requires a numeric or interval value, got {value:?}"
541                ))
542            })?;
543            if let Some(infinity) = temporal.infinity() {
544                let count = match infinity {
545                    TemporalInfinity::Positive => &mut self.interval_positive_infinity,
546                    TemporalInfinity::Negative => &mut self.interval_negative_infinity,
547                };
548                *count = count
549                    .checked_add(1)
550                    .ok_or_else(|| SQLError::TypeMismatch("aggregate count overflow".into()))?;
551                return Ok(());
552            }
553            self.interval_sum = Some(
554                self.interval_sum
555                    .unwrap_or(IntervalFields::ZERO)
556                    .plus(interval)?,
557            );
558            return Ok(());
559        }
560        if !matches!(value, Value::Int(_) | Value::Float(_) | Value::Decimal(_)) {
561            return Err(SQLError::TypeMismatch(format!(
562                "SUM/AVG requires a numeric or interval value, got {value:?}"
563            )));
564        }
565        match value {
566            Value::Int(n) => {
567                self.integer_sum = self
568                    .integer_sum
569                    .checked_add(i128::from(*n))
570                    .ok_or_else(|| SQLError::TypeMismatch("integer aggregate overflow".into()))?;
571                if self.numeric_inputs.has_decimal() {
572                    let next = DecimalValue::from_i64(*n);
573                    self.decimal_sum = Some(
574                        self.decimal_sum
575                            .as_ref()
576                            .and_then(|sum| sum.checked_add(&next))
577                            .ok_or_else(|| {
578                                SQLError::TypeMismatch("decimal aggregate overflow".into())
579                            })?,
580                    );
581                }
582                if self.numeric_inputs.has_float() {
583                    self.sum += *n as f64;
584                }
585            }
586            Value::Decimal(d) => {
587                let next = match &self.decimal_sum {
588                    Some(sum) => sum.checked_add(d),
589                    None if self.integer_sum == 0 => Some(d.clone()),
590                    None => {
591                        DecimalValue::from_i128(self.integer_sum).and_then(|sum| sum.checked_add(d))
592                    }
593                }
594                .ok_or_else(|| SQLError::TypeMismatch("decimal aggregate overflow".into()))?;
595                self.decimal_sum = Some(next);
596                if self.numeric_inputs.has_float() {
597                    self.sum += d.to_f64().ok_or_else(|| {
598                        SQLError::TypeMismatch("decimal aggregate does not fit float".into())
599                    })?;
600                }
601                self.numeric_inputs.observe_decimal();
602            }
603            Value::Float(value) => {
604                if !self.numeric_inputs.has_float() {
605                    // Exact integer/decimal aggregates do not maintain a shadow
606                    // floating total. Convert the accumulated total only if a
607                    // floating input actually makes it necessary.
608                    self.sum = if self.numeric_inputs.has_decimal() {
609                        self.decimal_sum
610                            .as_ref()
611                            .and_then(DecimalValue::to_f64)
612                            .ok_or_else(|| {
613                                SQLError::TypeMismatch(
614                                    "decimal aggregate does not fit float".into(),
615                                )
616                            })?
617                    } else {
618                        self.integer_sum as f64
619                    };
620                }
621                self.sum = if self.count == 1 {
622                    *value
623                } else {
624                    self.combine_float_sum(self.sum, *value)?
625                };
626                self.numeric_inputs.observe_float();
627            }
628            _ => {
629                return Err(SQLError::TypeMismatch(format!(
630                    "SUM/AVG requires a numeric or interval value, got {value:?}"
631                )))
632            }
633        }
634        Ok(())
635    }
636
637    /// Select the interval result after all transitions, preserving finite overflow and later input errors even when both signs of infinity have been seen.
638    pub(super) fn interval_result(&self) -> Result<Option<IntervalFields>, SQLError> {
639        let infinity = match (
640            self.interval_positive_infinity != 0,
641            self.interval_negative_infinity != 0,
642        ) {
643            (true, true) => {
644                return Err(SQLError::Routine {
645                    sqlstate: "22008".into(),
646                    message: "interval out of range".into(),
647                })
648            }
649            (true, false) => Some(TemporalInfinity::Positive),
650            (false, true) => Some(TemporalInfinity::Negative),
651            (false, false) => None,
652        };
653        Ok(infinity.map_or(self.interval_sum, |value| {
654            IntervalFields::of(&value.interval())
655        }))
656    }
657
658    pub(super) fn combine_float_sum(&self, left: f64, right: f64) -> Result<f64, SQLError> {
659        use uqa_sql::expr::{eval_float_arithmetic, FloatWidth};
660        let width = if matches!(self.state_plan, AggregateStatePlan::SumReal) {
661            FloatWidth::Real
662        } else {
663            FloatWidth::DoublePrecision
664        };
665        match eval_float_arithmetic(
666            uqa_sql::ast::BinaryOp::Add,
667            &Value::Float(left),
668            &Value::Float(right),
669            width,
670        )? {
671            Value::Float(value) => Ok(value),
672            _ => Err(SQLError::Internal(
673                "floating sum lost its numeric carrier".into(),
674            )),
675        }
676    }
677
678    pub(super) fn observe_min(
679        &mut self,
680        value: &Value,
681        enums: Option<&dyn EnumLabelCatalog>,
682    ) -> Result<(), SQLError> {
683        match &self.min {
684            Some(cur)
685                if !super::ordering::compare_extrema_with_catalog(
686                    cur,
687                    value,
688                    enums,
689                    self.enum_comparison.as_deref(),
690                )?
691                .is_gt() => {}
692            _ => self.min = Some(value.clone()),
693        }
694        Ok(())
695    }
696
697    pub(super) fn observe_max(
698        &mut self,
699        value: &Value,
700        enums: Option<&dyn EnumLabelCatalog>,
701    ) -> Result<(), SQLError> {
702        match &self.max {
703            Some(cur)
704                if !super::ordering::compare_extrema_with_catalog(
705                    cur,
706                    value,
707                    enums,
708                    self.enum_comparison.as_deref(),
709                )?
710                .is_lt() => {}
711            _ => self.max = Some(value.clone()),
712        }
713        Ok(())
714    }
715
716    pub(super) fn observe_bool_and(&mut self, value: &Value) -> Result<(), SQLError> {
717        let Value::Bool(value) = value else {
718            return Err(SQLError::TypeMismatch(format!(
719                "BOOL_AND requires a boolean value, got {value:?}"
720            )));
721        };
722        self.bool_and = Some(self.bool_and.unwrap_or(true) && *value);
723        Ok(())
724    }
725
726    pub(super) fn observe_bool_or(&mut self, value: &Value) -> Result<(), SQLError> {
727        let Value::Bool(value) = value else {
728            return Err(SQLError::TypeMismatch(format!(
729                "BOOL_OR requires a boolean value, got {value:?}"
730            )));
731        };
732        self.bool_or = Some(self.bool_or.unwrap_or(false) || *value);
733        Ok(())
734    }
735
736    /// Ordered inputs reach the transition only after sorting, so array inputs are checked when the aggregate finishes.
737    pub(super) fn observe_with_sort_keys(
738        &mut self,
739        value: &Value,
740        keys: Vec<super::ordering::AggregateSortKey>,
741        enums: Option<&dyn EnumLabelCatalog>,
742    ) -> Result<(), SQLError> {
743        if matches!(value, Value::Null) {
744            return match self.state_plan {
745                AggregateStatePlan::BufferedArrays => self.values.push(Value::Null, keys, enums),
746                _ => self.observe_null(keys, enums),
747            };
748        }
749        if self.state_plan.retains_values() {
750            self.observe_state(value, enums)?;
751        }
752        self.values.push(value.clone(), keys, enums)?;
753        Ok(())
754    }
755
756    /// A NULL input is part of the aggregate's input only for aggregates that retain NULLs.
757    fn observe_null(
758        &mut self,
759        keys: Vec<super::ordering::AggregateSortKey>,
760        enums: Option<&dyn EnumLabelCatalog>,
761    ) -> Result<(), SQLError> {
762        match self.state_plan {
763            AggregateStatePlan::BufferedWithNulls => self.values.push(Value::Null, keys, enums),
764            _ => Ok(()),
765        }
766    }
767
768    /// Whether DISTINCT keeps a NULL input. Array accumulation rejects it when the transition sees it.
769    pub(super) fn admits_null_input(&self) -> bool {
770        matches!(
771            self.state_plan,
772            AggregateStatePlan::BufferedWithNulls | AggregateStatePlan::BufferedArrays
773        )
774    }
775
776    pub(super) fn observe_registered(
777        &mut self,
778        values: Vec<Value>,
779        sort_keys: Vec<super::ordering::AggregateSortKey>,
780        enums: Option<&dyn EnumLabelCatalog>,
781    ) -> Result<(), SQLError> {
782        if sort_keys.is_empty() {
783            self.registered_state.observe(&values)?;
784            return Ok(());
785        }
786        self.registered_ordered.push(values, sort_keys, enums)
787    }
788
789    pub(super) fn registered_value(
790        &self,
791        enums: Option<&dyn EnumLabelCatalog>,
792    ) -> Option<Result<Value, SQLError>> {
793        let function = self.registered.as_ref()?;
794        if self.registered_ordered.is_empty() {
795            return Some(self.registered_state.finish());
796        }
797        Some((|| {
798            let mut state = self.registered_state.replay(function.as_ref())?;
799            let result = self
800                .registered_ordered
801                .observe_ordered_into(&mut state, enums)
802                .and_then(|()| state.finish());
803            with_cleanup(result, state.close())
804        })())
805    }
806
807    /// Release registered host state before reporting completion or failure.
808    /// Repeated calls do not invoke host cleanup again. Abandoned accumulators
809    /// still release their state through best-effort `Drop` cleanup.
810    pub fn close(&mut self) -> Result<(), SQLError> {
811        self.registered_state.close()
812    }
813}