Skip to main content

mz_compute/render/
reduce.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Reduction dataflow construction.
11//!
12//! Consult [ReducePlan] documentation for details.
13
14use std::collections::BTreeMap;
15
16use columnar::Columnar;
17use columnation::{Columnation, CopyRegion};
18use differential_dataflow::Diff as _;
19use differential_dataflow::collection::AsCollection;
20use differential_dataflow::columnar::layout::Coltainer;
21use differential_dataflow::consolidation::ConsolidatingContainerBuilder;
22use differential_dataflow::difference::{IsZero, Multiply, Semigroup};
23use differential_dataflow::hashable::Hashable;
24use differential_dataflow::operators::arrange::{Arranged, TraceAgent};
25use differential_dataflow::trace::cursor::{BatchCursor, BatchDiff, BatchValOwn};
26use differential_dataflow::trace::implementations::BatchContainer;
27use differential_dataflow::trace::{Builder, Cursor, Navigable, Trace};
28use differential_dataflow::{Data, VecCollection};
29use itertools::Itertools;
30use mz_compute_types::dyncfgs::{ENABLE_COLUMNAR_ACCUMULABLE_DIFF, TEMPORAL_BUCKETING_SUMMARY};
31use mz_compute_types::plan::ArrangementStrategy;
32use mz_compute_types::plan::reduce::{
33    AccumulablePlan, BasicPlan, BucketedPlan, HierarchicalPlan, KeyValPlan, LirAggregateExpr,
34    MonotonicPlan, ReducePlan, ReductionType, SingleBasicPlan, reduction_type,
35};
36use mz_compute_types::plan::scalar::LirScalarExpr;
37use mz_expr::{AggregateFunc, EvalError, SafeMfpPlan};
38use mz_ore::cast::CastLossy;
39use mz_repr::adt::interval::Interval;
40use mz_repr::adt::numeric::{self, Numeric, NumericAgg, OrderedNumericAgg};
41use mz_repr::fixed_length::ExtendDatums;
42use mz_repr::{Datum, DatumVec, Diff, Row, RowArena, SharedRow};
43use mz_row_spine::{
44    DatumContainer, DatumSeq, RowBatcher, RowBuilder, RowRowBatcher, RowRowBuilder, RowValBatcher,
45    RowValBuilder,
46};
47use mz_timely_util::operator::CollectionExt;
48use num_traits::Float;
49use serde::{Deserialize, Serialize};
50use timely::Container;
51use timely::container::{CapacityContainerBuilder, PushInto};
52use tracing::warn;
53
54use crate::extensions::arrange::{ArrangementSize, KeyCollection, MzArrange};
55use crate::extensions::reduce::{ClearContainer, MzReduce};
56use crate::render::context::{CollectionBundle, Context};
57use crate::render::errors::DataflowErrorSer;
58use crate::render::errors::MaybeValidatingRow;
59use crate::render::reduce::monoids::{ReductionMonoid, get_monoid};
60use crate::render::{ArrangementFlavor, Pairer, RenderTimestamp};
61use crate::typedefs::ConsolidateBatcher;
62use crate::typedefs::{
63    ErrBatcher, RowAgent, RowErrBuilder, RowErrSpine, RowRowAgent, RowRowArrangement, RowRowSpine,
64    RowSpine, RowValSpine,
65};
66
67/// Key container of trace `Tr`'s batch cursor.
68type BatchKeyContainer<Tr> = <BatchCursor<Tr> as Cursor>::KeyContainer;
69
70impl<'scope, T: RenderTimestamp> Context<'scope, T> {
71    /// Renders a `MirRelationExpr::Reduce` using various non-obvious techniques to
72    /// minimize worst-case incremental update times and memory footprint.
73    pub fn render_reduce(
74        &self,
75        input_key: Option<Vec<LirScalarExpr>>,
76        input: CollectionBundle<'scope, T>,
77        key_val_plan: KeyValPlan,
78        reduce_plan: ReducePlan,
79        mfp_after: Option<SafeMfpPlan<LirScalarExpr>>,
80        temporal_bucketing_strategy: ArrangementStrategy,
81    ) -> CollectionBundle<'scope, T>
82    where
83        T: crate::render::MaybeBucketByTime,
84    {
85        input.scope().region_named("Reduce", |inner| {
86            let KeyValPlan {
87                mut key_plan,
88                mut val_plan,
89            } = key_val_plan;
90            let key_arity = key_plan.projection.len();
91            let mut datums = DatumVec::new();
92
93            // Determine the columns we'll need from the row.
94            let mut demand = Vec::new();
95            demand.extend(key_plan.demand());
96            demand.extend(val_plan.demand());
97            demand.sort();
98            demand.dedup();
99
100            // remap column references to the subset we use.
101            let mut demand_map = BTreeMap::new();
102            for column in demand.iter() {
103                demand_map.insert(*column, demand_map.len());
104            }
105            let demand_map_len = demand_map.len();
106            key_plan.permute_fn(|c| demand_map[&c], demand_map_len);
107            val_plan.permute_fn(|c| demand_map[&c], demand_map_len);
108            let max_demand = demand.iter().max().map(|x| *x + 1).unwrap_or(0);
109            let skips = mz_compute_types::plan::reduce::convert_indexes_to_skips(demand);
110
111            let (key_val_input, err) = input
112                .enter_region(inner)
113                .flat_map::<ConsolidatingContainerBuilder<Vec<((Row, Row), T, Diff)>>, _>(
114                    input_key.map(|k| (k, None)),
115                    max_demand,
116                    move |row_datums, time, diff, ok_session, err_session| {
117                        let mut row_builder = SharedRow::get();
118                        let temp_storage = RowArena::new();
119
120                        let mut row_iter = row_datums.drain(..);
121                        let mut datums_local = datums.borrow();
122                        // Unpack only the demanded columns.
123                        for skip in skips.iter() {
124                            datums_local.push(row_iter.nth(*skip).unwrap());
125                        }
126
127                        // Evaluate the key expressions.
128                        let key = key_plan.evaluate_into(
129                            &mut datums_local,
130                            &temp_storage,
131                            &mut row_builder,
132                        );
133                        let key = match key {
134                            Err(e) => {
135                                err_session.give((e.into(), time, diff));
136                                return 1;
137                            }
138                            Ok(Some(key)) => key.clone(),
139                            Ok(None) => panic!("Row expected as no predicate was used"),
140                        };
141
142                        // Evaluate the value expressions.
143                        // The prior evaluation may have left additional columns we should delete.
144                        datums_local.truncate(skips.len());
145                        let val = val_plan.evaluate_into(
146                            &mut datums_local,
147                            &temp_storage,
148                            &mut row_builder,
149                        );
150                        let val = match val {
151                            Err(e) => {
152                                err_session.give((e.into(), time, diff));
153                                return 1;
154                            }
155                            Ok(Some(val)) => val.clone(),
156                            Ok(None) => panic!("Row expected as no predicate was used"),
157                        };
158
159                        ok_session.give(((key, val), time, diff));
160                        1
161                    },
162                );
163
164            // Bucket the keyed `(key, val)` stream when lowering chose `TemporalBucketing`.
165            // `Reduce` builds its own arrangement via `KeyValPlan`, bypassing
166            // `ensure_collections`, so the strategy is plumbed through `PlanNode::Reduce`
167            // rather than inferred at the arrangement site. No-op for `Direct`.
168            let key_val_collection = key_val_input.as_collection();
169            let key_val_collection = if matches!(
170                temporal_bucketing_strategy,
171                ArrangementStrategy::TemporalBucketing
172            ) {
173                let summary: mz_repr::Timestamp = TEMPORAL_BUCKETING_SUMMARY
174                    .get(&self.config_set)
175                    .try_into()
176                    .expect("must fit");
177                T::maybe_apply_temporal_bucketing_vec(
178                    key_val_collection.inner,
179                    self.as_of_frontier.clone(),
180                    summary,
181                )
182            } else {
183                key_val_collection
184            };
185
186            // Render the reduce plan
187            self.render_reduce_plan(reduce_plan, key_val_collection, err, key_arity, mfp_after)
188                .leave_region(self.scope)
189        })
190    }
191
192    /// Render a dataflow based on the provided plan.
193    ///
194    /// The output will be an arrangements that looks the same as if
195    /// we just had a single reduce operator computing everything together, and
196    /// this arrangement can also be re-used.
197    fn render_reduce_plan<'s>(
198        &self,
199        plan: ReducePlan,
200        collection: VecCollection<'s, T, (Row, Row), Diff>,
201        err_input: VecCollection<'s, T, DataflowErrorSer, Diff>,
202        key_arity: usize,
203        mfp_after: Option<SafeMfpPlan<LirScalarExpr>>,
204    ) -> CollectionBundle<'s, T> {
205        let mut errors = Default::default();
206        let arrangement =
207            self.render_reduce_plan_inner(plan, collection, &mut errors, key_arity, mfp_after);
208        let errs: KeyCollection<_, _, _> = err_input.concatenate(errors).into();
209        CollectionBundle::from_columns(
210            0..key_arity,
211            ArrangementFlavor::Local(
212                arrangement,
213                errs.mz_arrange::<ErrBatcher<_, _>, _>("Arrange bundle err"),
214            ),
215        )
216    }
217
218    fn render_reduce_plan_inner<'s>(
219        &self,
220        plan: ReducePlan,
221        collection: VecCollection<'s, T, (Row, Row), Diff>,
222        errors: &mut Vec<VecCollection<'s, T, DataflowErrorSer, Diff>>,
223        key_arity: usize,
224        mfp_after: Option<SafeMfpPlan<LirScalarExpr>>,
225    ) -> Arranged<'s, RowRowAgent<T, Diff>> {
226        // TODO(vmarcos): Arrangement specialization here could eventually be extended to keys,
227        // not only values (database-issues#6658).
228        let arrangement = match plan {
229            // If we have no aggregations or just a single type of reduction, we
230            // can go ahead and render them directly.
231            ReducePlan::Distinct => {
232                let (arranged_output, errs) = self.build_distinct(collection, mfp_after);
233                errors.push(errs);
234                arranged_output
235            }
236            ReducePlan::Accumulable(expr) => {
237                let (arranged_output, errs) =
238                    self.build_accumulable(collection, expr, key_arity, mfp_after);
239                errors.push(errs);
240                arranged_output
241            }
242            ReducePlan::Hierarchical(HierarchicalPlan::Monotonic(expr)) => {
243                let (output, errs) = self.build_monotonic(collection, expr, mfp_after);
244                errors.push(errs);
245                output
246            }
247            ReducePlan::Hierarchical(HierarchicalPlan::Bucketed(expr)) => {
248                let (output, errs) = self.build_bucketed(collection, expr, key_arity, mfp_after);
249                errors.push(errs);
250                output
251            }
252            ReducePlan::Basic(BasicPlan::Single(SingleBasicPlan {
253                expr,
254                fused_unnest_list,
255            })) => {
256                // Note that we skip validating for negative diffs when we have a fused unnest list,
257                // because this is already a CPU-intensive situation due to the non-incrementalness
258                // of window functions.
259                let validating = !fused_unnest_list;
260                let (output, errs) = self.build_basic_aggregate(
261                    collection,
262                    0,
263                    &expr,
264                    validating,
265                    key_arity,
266                    mfp_after,
267                    fused_unnest_list,
268                );
269                errors.extend(errs);
270                output
271            }
272            ReducePlan::Basic(BasicPlan::Multiple(aggrs)) => {
273                let (output, errs) =
274                    self.build_basic_aggregates(collection, aggrs, key_arity, mfp_after);
275                errors.push(errs);
276                output
277            }
278        };
279        arrangement
280    }
281
282    /// Build the dataflow to compute the set of distinct keys.
283    fn build_distinct<'s>(
284        &self,
285        collection: VecCollection<'s, T, (Row, Row), Diff>,
286        mfp_after: Option<SafeMfpPlan<LirScalarExpr>>,
287    ) -> (
288        Arranged<'s, TraceAgent<RowRowSpine<T, Diff>>>,
289        VecCollection<'s, T, DataflowErrorSer, Diff>,
290    ) {
291        let error_logger = self.error_logger();
292
293        // Allocations for the two closures.
294        let mut datums1 = DatumVec::new();
295        let mut datums2 = DatumVec::new();
296        let mfp_after1 = mfp_after.clone();
297        let mfp_after2 = mfp_after.filter(|mfp| mfp.could_error());
298
299        let arranged =
300            collection.mz_arrange::<RowRowBatcher<_, _>, RowRowSpine<_, _>>("Arranged DistinctBy");
301        let output = arranged
302            .clone()
303            .mz_reduce_abelian::<_, RowRowBuilder<_, _>, RowRowSpine<_, _>, _>(
304                "DistinctBy",
305                move |key, _input, output| {
306                    let temp_storage = RowArena::new();
307                    let mut datums_local = datums1.borrow();
308                    key.extend_datums(&temp_storage, &mut datums_local, None);
309
310                    // Note that the key contains all the columns in a `Distinct` and that `mfp_after` is
311                    // required to preserve the key. Therefore, if `mfp_after` maps, then it must project
312                    // back to the key. As a consequence, we can treat `mfp_after` as a filter here.
313                    if mfp_after1
314                        .as_ref()
315                        .map(|mfp| mfp.evaluate_inner(&mut datums_local, &temp_storage))
316                        .unwrap_or(Ok(true))
317                        == Ok(true)
318                    {
319                        // We're pushing a unit value here because the key is implicitly added by the
320                        // arrangement, and the permutation logic takes care of using the key part of the
321                        // output.
322                        output.push((Row::default(), Diff::ONE));
323                    }
324                },
325            );
326        let errors = arranged.mz_reduce_abelian::<_, RowErrBuilder<_, _>, RowErrSpine<_, _>, _>(
327            "DistinctByErrorCheck",
328            move |key, input: &[(_, Diff)], output: &mut Vec<(DataflowErrorSer, _)>| {
329                for (_, count) in input.iter() {
330                    if count.is_positive() {
331                        continue;
332                    }
333                    let message = "Non-positive multiplicity in DistinctBy";
334                    error_logger.log(message, &format!("row={key:?}, count={count}"));
335                    output.push((EvalError::Internal(message.into()).into(), Diff::ONE));
336                    return;
337                }
338                // If `mfp_after` can error, then evaluate it here.
339                let Some(mfp) = &mfp_after2 else { return };
340                let temp_storage = RowArena::new();
341                let mut datums_local = datums2.borrow();
342                key.extend_datums(&temp_storage, &mut datums_local, None);
343
344                if let Err(e) = mfp.evaluate_inner(&mut datums_local, &temp_storage) {
345                    output.push((e.into(), Diff::ONE));
346                }
347            },
348        );
349        (output, errors.as_collection(|_k, v| v.clone()))
350    }
351
352    /// Build the dataflow to compute and arrange multiple non-accumulable,
353    /// non-hierarchical aggregations on `input`.
354    ///
355    /// This function assumes that we are explicitly rendering multiple basic aggregations.
356    /// For each aggregate, we render a different reduce operator, and then fuse
357    /// results together into a final arrangement that presents all the results
358    /// in the order specified by `aggrs`.
359    fn build_basic_aggregates<'s>(
360        &self,
361        input: VecCollection<'s, T, (Row, Row), Diff>,
362        aggrs: Vec<LirAggregateExpr>,
363        key_arity: usize,
364        mfp_after: Option<SafeMfpPlan<LirScalarExpr>>,
365    ) -> (
366        RowRowArrangement<'s, T>,
367        VecCollection<'s, T, DataflowErrorSer, Diff>,
368    ) {
369        // We are only using this function to render multiple basic aggregates and
370        // stitch them together. If that's not true we should complain.
371        if aggrs.len() <= 1 {
372            self.error_logger().soft_panic_or_log(
373                "Too few aggregations when building basic aggregates",
374                &format!("len={}", aggrs.len()),
375            )
376        }
377        let mut err_output = None;
378        let mut to_collect = Vec::new();
379        for (index, aggr) in aggrs.into_iter().enumerate() {
380            let (result, errs) = self.build_basic_aggregate(
381                input.clone(),
382                index,
383                &aggr,
384                err_output.is_none(),
385                key_arity,
386                None,
387                false,
388            );
389            if errs.is_some() {
390                err_output = errs
391            }
392            to_collect
393                .push(result.as_collection(move |key, val| (key.to_row(), (index, val.to_row()))));
394        }
395
396        // Allocations for the two closures.
397        let mut datums1 = DatumVec::new();
398        let mut datums2 = DatumVec::new();
399        let mfp_after1 = mfp_after.clone();
400        let mfp_after2 = mfp_after.filter(|mfp| mfp.could_error());
401
402        let arranged = differential_dataflow::collection::concatenate(input.scope(), to_collect)
403            .mz_arrange::<RowValBatcher<_, _, _>, RowValSpine<_, _, _>>(
404            "Arranged ReduceFuseBasic input",
405        );
406
407        let output = arranged
408            .clone()
409            .mz_reduce_abelian::<_, RowRowBuilder<_, _>, RowRowSpine<_, _>, _>(
410                "ReduceFuseBasic",
411                {
412                    move |key, input, output| {
413                        let temp_storage = RowArena::new();
414                        let mut datums_local = datums1.borrow();
415                        key.extend_datums(&temp_storage, &mut datums_local, None);
416                        let key_len = datums_local.len();
417
418                        for ((_, row), _) in input.iter() {
419                            datums_local.push(row.unpack_first());
420                        }
421
422                        if let Some(row) = evaluate_mfp_after(
423                            &mfp_after1,
424                            &mut datums_local,
425                            &temp_storage,
426                            key_len,
427                        ) {
428                            output.push((row, Diff::ONE));
429                        }
430                    }
431                },
432            );
433        // If `mfp_after` can error, then we need to render a paired reduction
434        // to scan for these potential errors. Note that we cannot directly use
435        // `mz_timely_util::reduce::ReduceExt::reduce_pair` here because we only
436        // conditionally render the second component of the reduction pair.
437        let validation_errs = err_output.expect("expected to validate in at least one aggregate");
438        if let Some(mfp) = mfp_after2 {
439            let mfp_errs = arranged
440                .mz_reduce_abelian::<_, RowErrBuilder<_, _>, RowErrSpine<_, _>, _>(
441                    "ReduceFuseBasic Error Check",
442                    move |key, input, output| {
443                        // Since negative accumulations are checked in at least one component
444                        // aggregate, we only need to look for MFP errors here.
445                        let temp_storage = RowArena::new();
446                        let mut datums_local = datums2.borrow();
447                        key.extend_datums(&temp_storage, &mut datums_local, None);
448
449                        for ((_, row), _) in input.iter() {
450                            datums_local.push(row.unpack_first());
451                        }
452
453                        if let Err(e) = mfp.evaluate_inner(&mut datums_local, &temp_storage) {
454                            output.push((e.into(), Diff::ONE));
455                        }
456                    },
457                )
458                .as_collection(|_, v| v.clone());
459            (output, validation_errs.concat(mfp_errs))
460        } else {
461            (output, validation_errs)
462        }
463    }
464
465    /// Build the dataflow to compute a single basic aggregation.
466    ///
467    /// This method also applies distinctness if required.
468    ///
469    /// The returned errors are the validation errors, if `validating`, and the errors of
470    /// `mfp_after`, if it can error. They are `None` only when there are neither.
471    fn build_basic_aggregate<'s>(
472        &self,
473        input: VecCollection<'s, T, (Row, Row), Diff>,
474        index: usize,
475        aggr: &LirAggregateExpr,
476        validating: bool,
477        key_arity: usize,
478        mfp_after: Option<SafeMfpPlan<LirScalarExpr>>,
479        fused_unnest_list: bool,
480    ) -> (
481        RowRowArrangement<'s, T>,
482        Option<VecCollection<'s, T, DataflowErrorSer, Diff>>,
483    ) {
484        let LirAggregateExpr {
485            func,
486            expr: _,
487            distinct,
488        } = aggr.clone();
489
490        // Extract the value we were asked to aggregate over.
491        let mut partial = input.map(move |(key, row)| {
492            let mut row_builder = SharedRow::get();
493            let value = row.iter().nth(index).unwrap();
494            row_builder.packer().push(value);
495            (key, row_builder.clone())
496        });
497
498        let mut err_output = None;
499
500        // If `distinct` is set, we restrict ourselves to the distinct `(key, val)`.
501        if distinct {
502            // We map `(Row, Row)` to `Row` to take advantage of `Row*Spine` types.
503            let pairer = Pairer::new(key_arity);
504            let keyed = partial.map(move |(key, val)| pairer.merge(&key, &val));
505            if validating {
506                let (oks, errs) = self
507                    .build_reduce_inaccumulable_distinct::<
508                        RowValBuilder<Result<(), String>, _, _>,
509                        RowValSpine<Result<(), String>, _, _>,
510                    >(keyed, None)
511                    .as_collection(|k, v| {
512                        (
513                            k.to_row(),
514                            v.as_ref()
515                                .map(|&()| ())
516                                .map_err(|m| m.as_str().into()),
517                        )
518                    })
519                    .map_fallible::<
520                        CapacityContainerBuilder<_>,
521                        CapacityContainerBuilder<_>,
522                        _,
523                        _,
524                        _,
525                    >(
526                        "Demux Errors",
527                        move |(key_val, result)| match result {
528                            Ok(()) => Ok(pairer.split(&key_val)),
529                            Err(m) => {
530                                Err(EvalError::Internal(m).into())
531                            }
532                        },
533                    );
534                err_output = Some(errs);
535                partial = oks;
536            } else {
537                partial = self
538                    .build_reduce_inaccumulable_distinct::<RowBuilder<_, _>, RowSpine<_, _>>(
539                        keyed,
540                        Some(" [val: empty]"),
541                    )
542                    .as_collection(move |key_val_iter, _| pairer.split(key_val_iter));
543            }
544        }
545
546        // Allocations for the two closures.
547        let mut datums1 = DatumVec::new();
548        let mut datums2 = DatumVec::new();
549        let mut datums_key_1 = DatumVec::new();
550        let mut datums_key_2 = DatumVec::new();
551        // Scratch buffers for decoding each input value's (single) datum into the
552        // arena, so the aggregates iterate arena-resident datums rather than the
553        // packed value bytes — a prerequisite for compressed value representations.
554        let mut vals1 = DatumVec::new();
555        let mut vals2 = DatumVec::new();
556        let mut vals_key_1 = DatumVec::new();
557        let mut vals_key_2 = DatumVec::new();
558        let mfp_after1 = mfp_after.clone();
559        let func2 = func.clone();
560
561        let name = if !fused_unnest_list {
562            "ReduceInaccumulable"
563        } else {
564            "FusedReduceUnnestList"
565        };
566        let arranged = partial
567            .mz_arrange::<RowRowBatcher<_, _>, RowRowSpine<_, _>>(&format!("Arranged {name}"));
568        let oks = if !fused_unnest_list {
569            arranged
570                .clone()
571                .mz_reduce_abelian::<_, RowRowBuilder<_, _>, RowRowSpine<_, _>, _>(name, {
572                    move |key, source, target| {
573                        let temp_storage = RowArena::new();
574                        // Decode each input value's single datum into the arena, reusing one
575                        // scratch buffer; the datum is `Copy` and is copied out before the
576                        // buffer is overwritten on the next row. We pass the multiplicity
577                        // through (unlike in hierarchical aggregation) because we don't know
578                        // that the aggregation method is not sensitive to the number of
579                        // records. The aggregate decides how to consume it.
580                        let mut val_scratch = vals1.borrow();
581                        let iter = source.iter().map(|(v, w)| {
582                            val_scratch.clear();
583                            v.extend_datums(&temp_storage, &mut val_scratch, Some(1));
584                            (val_scratch[0], *w)
585                        });
586
587                        let mut datums_local = datums1.borrow();
588                        key.extend_datums(&temp_storage, &mut datums_local, None);
589                        let key_len = datums_local.len();
590                        datums_local.push(
591                        // Note that this is not necessarily a window aggregation, in which case
592                        // `eval_with_fast_window_agg` delegates to the normal `eval`.
593                        func.eval_with_fast_window_agg::<_, window_agg_helpers::OneByOneAggrImpls>(
594                            iter,
595                            &temp_storage,
596                        ),
597                    );
598
599                        if let Some(row) = evaluate_mfp_after(
600                            &mfp_after1,
601                            &mut datums_local,
602                            &temp_storage,
603                            key_len,
604                        ) {
605                            target.push((row, Diff::ONE));
606                        }
607                    }
608                })
609        } else {
610            arranged
611                .clone()
612                .mz_reduce_abelian::<_, RowRowBuilder<_, _>, RowRowSpine<_, _>, _>(name, {
613                    move |key, source, target| {
614                        // This part is the same as in the `!fused_unnest_list` if branch above.
615                        let temp_storage = RowArena::new();
616                        let mut val_scratch = vals_key_1.borrow();
617                        let iter = source.iter().map(|(v, w)| {
618                            val_scratch.clear();
619                            v.extend_datums(&temp_storage, &mut val_scratch, Some(1));
620                            (val_scratch[0], *w)
621                        });
622
623                        // This is the part that is specific to the `fused_unnest_list` branch.
624                        let mut datums_local = datums_key_1.borrow();
625                        key.extend_datums(&temp_storage, &mut datums_local, None);
626                        let key_len = datums_local.len();
627                        for datum in func
628                            .eval_with_unnest_list::<_, window_agg_helpers::OneByOneAggrImpls>(
629                                iter,
630                                &temp_storage,
631                            )
632                        {
633                            datums_local.truncate(key_len);
634                            datums_local.push(datum);
635                            if let Some(row) = evaluate_mfp_after(
636                                &mfp_after1,
637                                &mut datums_local,
638                                &temp_storage,
639                                key_len,
640                            ) {
641                                target.push((row, Diff::ONE));
642                            }
643                        }
644                    }
645                })
646        };
647
648        // Note that we would prefer to use `mz_timely_util::reduce::ReduceExt::reduce_pair` here, but
649        // we then wouldn't be able to do this error check conditionally.  See its documentation for the
650        // rationale around using a second reduction here.
651        let must_validate = validating && err_output.is_none();
652        let mfp_after2 = mfp_after.filter(|mfp| mfp.could_error());
653        if must_validate || mfp_after2.is_some() {
654            let error_logger = self.error_logger();
655
656            let errs = if !fused_unnest_list {
657                arranged
658                    .mz_reduce_abelian::<_, RowErrBuilder<_, _>, RowErrSpine<_, _>, _>(
659                        &format!("{name} Error Check"),
660                        move |key, source, target| {
661                            // Negative counts would be surprising, but until we are 100% certain we won't
662                            // see them, we should report when we do. We may want to bake even more info
663                            // in here in the future.
664                            if must_validate {
665                                for (value, count) in source.iter() {
666                                    if count.is_positive() {
667                                        continue;
668                                    }
669                                    let value = value.to_row();
670                                    let message =
671                                        "Non-positive accumulation in ReduceInaccumulable";
672                                    error_logger
673                                        .log(message, &format!("value={value:?}, count={count}"));
674                                    let err = EvalError::Internal(message.into());
675                                    target.push((err.into(), Diff::ONE));
676                                    return;
677                                }
678                            }
679
680                            // We know that `mfp_after` can error if it exists, so try to evaluate it here.
681                            let Some(mfp) = &mfp_after2 else { return };
682                            let temp_storage = RowArena::new();
683                            let mut val_scratch = vals2.borrow();
684                            let iter = source.iter().map(|(v, w)| {
685                                val_scratch.clear();
686                                v.extend_datums(&temp_storage, &mut val_scratch, Some(1));
687                                (val_scratch[0], *w)
688                            });
689
690                            let mut datums_local = datums2.borrow();
691                            key.extend_datums(&temp_storage, &mut datums_local, None);
692                            datums_local.push(
693                                func2.eval_with_fast_window_agg::<
694                                    _,
695                                    window_agg_helpers::OneByOneAggrImpls,
696                                >(
697                                    iter, &temp_storage
698                                ),
699                            );
700                            if let Err(e) = mfp.evaluate_inner(&mut datums_local, &temp_storage) {
701                                target.push((e.into(), Diff::ONE));
702                            }
703                        },
704                    )
705                    .as_collection(|_, v| v.clone())
706            } else {
707                // `render_reduce_plan_inner` doesn't request validation when `fused_unnest_list`.
708                assert!(!must_validate);
709                // We couldn't have got into this if branch due to `must_validate`, so it must be
710                // because of the `mfp_after2.is_some()`.
711                let Some(mfp) = mfp_after2 else {
712                    unreachable!()
713                };
714                arranged
715                    .mz_reduce_abelian::<_, RowErrBuilder<_, _>, RowErrSpine<_, _>, _>(
716                        &format!("{name} Error Check"),
717                        move |key, source, target| {
718                            let temp_storage = RowArena::new();
719                            let mut val_scratch = vals_key_2.borrow();
720                            let iter = source.iter().map(|(v, w)| {
721                                val_scratch.clear();
722                                v.extend_datums(&temp_storage, &mut val_scratch, Some(1));
723                                (val_scratch[0], *w)
724                            });
725
726                            let mut datums_local = datums_key_2.borrow();
727                            key.extend_datums(&temp_storage, &mut datums_local, None);
728                            let key_len = datums_local.len();
729                            for datum in func2
730                                .eval_with_unnest_list::<_, window_agg_helpers::OneByOneAggrImpls>(
731                                    iter,
732                                    &temp_storage,
733                                )
734                            {
735                                datums_local.truncate(key_len);
736                                datums_local.push(datum);
737                                // We know that `mfp` can error (because of the `could_error` call
738                                // above), so try to evaluate it here.
739                                if let Err(e) = mfp.evaluate_inner(&mut datums_local, &temp_storage)
740                                {
741                                    target.push((e.into(), Diff::ONE));
742                                }
743                            }
744                        },
745                    )
746                    .as_collection(|_, v| v.clone())
747            };
748
749            if let Some(e) = err_output {
750                err_output = Some(e.concat(errs));
751            } else {
752                err_output = Some(errs);
753            }
754        }
755        (oks, err_output)
756    }
757
758    fn build_reduce_inaccumulable_distinct<'s, Bu, Tr>(
759        &self,
760        input: VecCollection<'s, T, Row, Diff>,
761        name_tag: Option<&str>,
762    ) -> Arranged<'s, TraceAgent<Tr>>
763    where
764        Tr: Trace<Batch: Navigable, Time = T> + 'static,
765        for<'a> BatchCursor<Tr>: Cursor<
766                Key<'a> = DatumSeq<'a>,
767                KeyContainer = DatumContainer,
768                Time = T,
769                Diff = Diff,
770                ValOwn: Data + MaybeValidatingRow<(), String>,
771            >,
772        Bu: Builder<
773                Time = T,
774                Input: Container
775                           + ClearContainer
776                           + PushInto<((Row, BatchValOwn<Tr>), Tr::Time, BatchDiff<Tr>)>,
777                Output = Tr::Batch,
778            > + 'static,
779        Arranged<'s, TraceAgent<Tr>>: ArrangementSize,
780    {
781        let error_logger = self.error_logger();
782
783        let output_name = format!(
784            "ReduceInaccumulable Distinct{}",
785            name_tag.unwrap_or_default()
786        );
787
788        let input: KeyCollection<_, _, _> = input.into();
789        let arranged = input.mz_arrange::<RowBatcher<_, _>, RowSpine<_, _>>(
790            "Arranged ReduceInaccumulable Distinct [val: empty]",
791        );
792        arranged.mz_reduce_abelian::<_, Bu, Tr, _>(&output_name, move |_, source, t| {
793            if let Some(err) = BatchValOwn::<Tr>::into_error() {
794                for (value, count) in source.iter() {
795                    if count.is_positive() {
796                        continue;
797                    }
798
799                    let message = "Non-positive accumulation in ReduceInaccumulable DISTINCT";
800                    error_logger.log(message, &format!("value={value:?}, count={count}"));
801                    t.push((err(message.to_string()), Diff::ONE));
802                    return;
803                }
804            }
805            t.push((BatchValOwn::<Tr>::ok(()), Diff::ONE))
806        })
807    }
808
809    /// Build the dataflow to compute and arrange multiple hierarchical aggregations
810    /// on non-monotonic inputs.
811    ///
812    /// This function renders a single reduction tree that computes aggregations with
813    /// a priority queue implemented with a series of reduce operators that partition
814    /// the input into buckets, and compute the aggregation over very small buckets
815    /// and feed the results up to larger buckets.
816    ///
817    /// Note that this implementation currently ignores the distinct bit because we
818    /// currently only perform min / max hierarchically and the reduction tree
819    /// efficiently suppresses non-distinct updates.
820    ///
821    /// `buckets` indicates the number of buckets in this stage. We do some non-obvious
822    /// trickery here to limit the memory usage per layer by internally
823    /// holding only the elements that were rejected by this stage. However, the
824    /// output collection maintains the `((key, bucket), (passing value)` for this
825    /// stage.
826    fn build_bucketed<'s>(
827        &self,
828        input: VecCollection<'s, T, (Row, Row), Diff>,
829        BucketedPlan {
830            aggr_funcs,
831            buckets,
832        }: BucketedPlan,
833        key_arity: usize,
834        mfp_after: Option<SafeMfpPlan<LirScalarExpr>>,
835    ) -> (
836        RowRowArrangement<'s, T>,
837        VecCollection<'s, T, DataflowErrorSer, Diff>,
838    ) {
839        let mut err_output: Option<VecCollection<'s, T, _, _>> = None;
840        let outer_scope = input.scope();
841        let arranged_output = outer_scope
842            .clone()
843            .region_named("ReduceHierarchical", |inner| {
844                let input = input.enter(inner);
845
846                // The first mod to apply to the hash.
847                let first_mod = buckets.get(0).copied().unwrap_or(1);
848                let aggregations = aggr_funcs.len();
849
850                // Gather the relevant keys with their hashes along with values ordered by aggregation_index.
851                let mut stage = input.map(move |(key, row)| {
852                    let mut row_builder = SharedRow::get();
853                    let mut row_packer = row_builder.packer();
854                    row_packer.extend(row.iter().take(aggregations));
855                    let values = row_builder.clone();
856
857                    // Apply the initial mod here.
858                    let hash = values.hashed() % first_mod;
859                    let hash_key =
860                        row_builder.pack_using(std::iter::once(Datum::from(hash)).chain(&key));
861                    (hash_key, values)
862                });
863
864                // Repeatedly apply hierarchical reduction with a progressively coarser key.
865                for (index, b) in buckets.into_iter().enumerate() {
866                    // Apply subsequent bucket mods for all but the first round.
867                    let input = if index == 0 {
868                        stage
869                    } else {
870                        stage.map(move |(hash_key, values)| {
871                            let mut hash_key_iter = hash_key.iter();
872                            let hash = hash_key_iter.next().unwrap().unwrap_uint64() % b;
873                            // TODO: Convert the `chain(hash_key_iter...)` into a memcpy.
874                            let hash_key = SharedRow::pack(
875                                std::iter::once(Datum::from(hash))
876                                    .chain(hash_key_iter.take(key_arity)),
877                            );
878                            (hash_key, values)
879                        })
880                    };
881
882                    // We only want the first stage to perform validation of whether invalid accumulations
883                    // were observed in the input. Subsequently, we will either produce an error in the error
884                    // stream or produce correct data in the output stream.
885                    let validating = err_output.is_none();
886
887                    let (oks, errs) = self.build_bucketed_stage(&aggr_funcs, input, validating);
888                    if let Some(errs) = errs {
889                        err_output = Some(errs.leave_region(outer_scope));
890                    }
891                    stage = oks
892                }
893
894                // Discard the hash from the key and return to the format of the input data.
895                let partial = stage.map(move |(hash_key, values)| {
896                    let mut hash_key_iter = hash_key.iter();
897                    let _hash = hash_key_iter.next();
898                    (SharedRow::pack(hash_key_iter.take(key_arity)), values)
899                });
900
901                // Allocations for the two closures.
902                let mut datums1 = DatumVec::new();
903                let mut datums2 = DatumVec::new();
904                // Scratch buffers for decoding the input values (one column per aggregate)
905                // into the arena, so the aggregates iterate arena-resident datums rather
906                // than the packed value bytes.
907                let mut vals1 = DatumVec::new();
908                let mut vals2 = DatumVec::new();
909                let mfp_after1 = mfp_after.clone();
910                let mfp_after2 = mfp_after.filter(|mfp| mfp.could_error());
911                let aggr_funcs2 = aggr_funcs.clone();
912
913                // Build a series of stages for the reduction
914                // Arrange the final result into (key, Row)
915                let error_logger = self.error_logger();
916                // NOTE(vmarcos): The input operator name below is used in the tuning advice built-in
917                // view mz_introspection.mz_expected_group_size_advice.
918                let arranged = partial.mz_arrange::<RowRowBatcher<_, _>, RowRowSpine<_, _>>(
919                    "Arrange ReduceMinsMaxes",
920                );
921                // Note that we would prefer to use `mz_timely_util::reduce::ReduceExt::reduce_pair` here,
922                // but we then wouldn't be able to do this error check conditionally.  See its documentation
923                // for the rationale around using a second reduction here.
924                let must_validate = err_output.is_none();
925                if must_validate || mfp_after2.is_some() {
926                    let errs = arranged
927                        .clone()
928                        .mz_reduce_abelian::<_, RowErrBuilder<_, _>, RowErrSpine<_, _>, _>(
929                            "ReduceMinsMaxes Error Check",
930                            move |key, source, target| {
931                                // Negative counts would be surprising, but until we are 100% certain we wont
932                                // see them, we should report when we do. We may want to bake even more info
933                                // in here in the future.
934                                if must_validate {
935                                    for (val, count) in source.iter() {
936                                        if count.is_positive() {
937                                            continue;
938                                        }
939                                        let val = val.to_row();
940                                        let message =
941                                            "Non-positive accumulation in ReduceMinsMaxes";
942                                        error_logger
943                                            .log(message, &format!("val={val:?}, count={count}"));
944                                        target.push((
945                                            EvalError::Internal(message.into()).into(),
946                                            Diff::ONE,
947                                        ));
948                                        return;
949                                    }
950                                }
951
952                                // We know that `mfp_after` can error if it exists, so try to evaluate it here.
953                                let Some(mfp) = &mfp_after2 else { return };
954                                let temp_storage = RowArena::new();
955                                let mut datums_local = datums2.borrow();
956                                key.extend_datums(&temp_storage, &mut datums_local, None);
957
958                                // Decode every value row's datums into the arena, one column
959                                // per aggregate, then iterate them column-major below. Min/max
960                                // hierarchical aggregates are multiplicity-insensitive, so each
961                                // row contributes once (`Diff::ONE`) regardless of `_cnt`.
962                                let arity = aggr_funcs2.len();
963                                let mut decoded = vals2.borrow();
964                                for (values, _cnt) in source.iter() {
965                                    values.extend_datums(&temp_storage, &mut decoded, None);
966                                }
967                                assert_eq!(decoded.len(), source.len() * arity);
968                                for (col, func) in aggr_funcs2.iter().enumerate() {
969                                    let column_iter = (0..source.len())
970                                        .map(|r| (decoded[r * arity + col], Diff::ONE));
971                                    datums_local.push(func.eval(column_iter, &temp_storage));
972                                }
973                                if let Result::Err(e) =
974                                    mfp.evaluate_inner(&mut datums_local, &temp_storage)
975                                {
976                                    target.push((e.into(), Diff::ONE));
977                                }
978                            },
979                        )
980                        .as_collection(|_, v| v.clone())
981                        .leave_region(outer_scope);
982                    if let Some(e) = err_output.take() {
983                        err_output = Some(e.concat(errs));
984                    } else {
985                        err_output = Some(errs);
986                    }
987                }
988                arranged
989                    .mz_reduce_abelian::<_, RowRowBuilder<_, _>, RowRowSpine<_, _>, _>(
990                        "ReduceMinsMaxes",
991                        move |key, source, target| {
992                            let temp_storage = RowArena::new();
993                            let mut datums_local = datums1.borrow();
994                            key.extend_datums(&temp_storage, &mut datums_local, None);
995                            let key_len = datums_local.len();
996
997                            // Decode every value row's datums into the arena, one column
998                            // per aggregate, then iterate them column-major below. Min/max
999                            // hierarchical aggregates are multiplicity-insensitive, so each
1000                            // row contributes once (`Diff::ONE`) regardless of `_cnt`.
1001                            let arity = aggr_funcs.len();
1002                            let mut decoded = vals1.borrow();
1003                            for (values, _cnt) in source.iter() {
1004                                values.extend_datums(&temp_storage, &mut decoded, None);
1005                            }
1006                            assert_eq!(decoded.len(), source.len() * arity);
1007                            for (col, func) in aggr_funcs.iter().enumerate() {
1008                                let column_iter = (0..source.len())
1009                                    .map(|r| (decoded[r * arity + col], Diff::ONE));
1010                                datums_local.push(func.eval(column_iter, &temp_storage));
1011                            }
1012
1013                            if let Some(row) = evaluate_mfp_after(
1014                                &mfp_after1,
1015                                &mut datums_local,
1016                                &temp_storage,
1017                                key_len,
1018                            ) {
1019                                target.push((row, Diff::ONE));
1020                            }
1021                        },
1022                    )
1023                    .leave_region(outer_scope)
1024            });
1025        (
1026            arranged_output,
1027            err_output.expect("expected to validate in one level of the hierarchy"),
1028        )
1029    }
1030
1031    /// Build a bucketed stage fragment that wraps [`Self::build_bucketed_negated_output`], and
1032    /// adds validation if `validating` is true. It returns the consolidated inputs concatenated
1033    /// with the reduction's output, which is the winner of each key.
1034    /// `validating` indicates whether we want this stage to perform error detection
1035    /// for invalid accumulations. Once a stage is clean of such errors, subsequent
1036    /// stages can skip validation.
1037    fn build_bucketed_stage<'s>(
1038        &self,
1039        aggr_funcs: &Vec<AggregateFunc>,
1040        input: VecCollection<'s, T, (Row, Row), Diff>,
1041        validating: bool,
1042    ) -> (
1043        VecCollection<'s, T, (Row, Row), Diff>,
1044        Option<VecCollection<'s, T, DataflowErrorSer, Diff>>,
1045    ) {
1046        let (input, negated_output, errs) = if validating {
1047            let (input, reduced) = self
1048                .build_bucketed_negated_output::<
1049                    RowValBuilder<_, _, _>,
1050                    RowValSpine<Result<Row, Row>, _, _>,
1051                >(
1052                    input.clone(),
1053                    aggr_funcs.clone(),
1054                );
1055            let (oks, errs) = reduced
1056                .as_collection(|k, v| (k.to_row(), v.clone()))
1057                .map_fallible::<CapacityContainerBuilder<_>, CapacityContainerBuilder<_>, _, _, _>(
1058                "Checked Invalid Accumulations",
1059                |(hash_key, result)| match result {
1060                    Err(hash_key) => {
1061                        let mut hash_key_iter = hash_key.iter();
1062                        let _hash = hash_key_iter.next();
1063                        let key = SharedRow::pack(hash_key_iter);
1064                        let message = format!(
1065                            "Invalid data in source, saw non-positive accumulation \
1066                                         for key {key:?} in hierarchical mins-maxes aggregate"
1067                        );
1068                        Err(EvalError::Internal(message.into()).into())
1069                    }
1070                    Ok(values) => Ok((hash_key, values)),
1071                },
1072            );
1073            (input, oks, Some(errs))
1074        } else {
1075            let (input, reduced) = self
1076                .build_bucketed_negated_output::<RowRowBuilder<_, _>, RowRowSpine<_, _>>(
1077                    input,
1078                    aggr_funcs.clone(),
1079                );
1080            // TODO: Here is a good moment where we could apply the next `mod` calculation. Note
1081            // that we need to apply the mod on both input and oks.
1082            let oks = reduced.as_collection(|k, v| (k.to_row(), v.to_row()));
1083            (input, oks, None)
1084        };
1085
1086        let input = input.as_collection(|k, v| (k.to_row(), v.to_row()));
1087        let oks = negated_output.concat(input);
1088        (oks, errs)
1089    }
1090
1091    /// Build a dataflow fragment for one stage of a reduction tree for multiple hierarchical
1092    /// aggregates to arrange and reduce the inputs. Returns the arranged input and the reduction,
1093    /// whose output for each key is the key's winner minus its input.
1094    fn build_bucketed_negated_output<'s, Bu, Tr>(
1095        &self,
1096        input: VecCollection<'s, T, (Row, Row), Diff>,
1097        aggrs: Vec<AggregateFunc>,
1098    ) -> (
1099        Arranged<'s, TraceAgent<RowRowSpine<T, Diff>>>,
1100        Arranged<'s, TraceAgent<Tr>>,
1101    )
1102    where
1103        Tr: Trace<Batch: Navigable, Time = T> + 'static,
1104        for<'a> BatchCursor<Tr>: Cursor<
1105                Key<'a> = DatumSeq<'a>,
1106                KeyContainer = DatumContainer,
1107                ValOwn: Data + MaybeValidatingRow<Row, Row>,
1108                Time = T,
1109                Diff = Diff,
1110            >,
1111        Bu: Builder<
1112                Time = T,
1113                Input: Container
1114                           + ClearContainer
1115                           + PushInto<((Row, BatchValOwn<Tr>), Tr::Time, BatchDiff<Tr>)>,
1116                Output = Tr::Batch,
1117            > + 'static,
1118        Arranged<'s, TraceAgent<Tr>>: ArrangementSize,
1119    {
1120        let error_logger = self.error_logger();
1121        // NOTE(vmarcos): The input operator name below is used in the tuning advice built-in
1122        // view mz_introspection.mz_expected_group_size_advice.
1123        let arranged_input = input.mz_arrange::<RowRowBatcher<_, _>, RowRowSpine<_, _>>(
1124            "Arranged MinsMaxesHierarchical input",
1125        );
1126
1127        // Scratch buffer for decoding the input values (one column per aggregate) into the
1128        // arena, so the aggregates iterate arena-resident datums rather than the packed bytes.
1129        let mut value_datums = DatumVec::new();
1130        let reduced = arranged_input.clone().mz_reduce_abelian::<_, Bu, Tr, _>(
1131            "Reduced Fallibly MinsMaxesHierarchical",
1132            move |key, source, target| {
1133                if let Some(err) = BatchValOwn::<Tr>::into_error() {
1134                    // Should negative accumulations reach us, we should loudly complain.
1135                    for (value, count) in source.iter() {
1136                        if count.is_positive() {
1137                            continue;
1138                        }
1139                        error_logger.log(
1140                            "Non-positive accumulation in MinsMaxesHierarchical",
1141                            &format!("key={key:?}, value={value:?}, count={count}"),
1142                        );
1143                        // After complaining, output an error here so that we can eventually
1144                        // report it in an error stream.
1145                        let key = <BatchKeyContainer<Tr> as BatchContainer>::into_owned(key);
1146                        target.push((err(key), Diff::ONE));
1147                        return;
1148                    }
1149                }
1150
1151                // Decode every value row's datums into the arena, one column per aggregate,
1152                // then iterate them column-major below.
1153                let temp_storage = RowArena::new();
1154                let arity = aggrs.len();
1155                let mut decoded = value_datums.borrow();
1156                for (values, _cnt) in source.iter() {
1157                    values.extend_datums(&temp_storage, &mut decoded, None);
1158                }
1159                assert_eq!(decoded.len(), source.len() * arity);
1160
1161                let mut row_builder = SharedRow::get();
1162                let mut row_packer = row_builder.packer();
1163                for (col, func) in aggrs.iter().enumerate() {
1164                    // Min/max hierarchical aggregates are multiplicity-insensitive, so each
1165                    // row contributes once (`Diff::ONE`) regardless of `_cnt`.
1166                    let column_iter =
1167                        (0..source.len()).map(|r| (decoded[r * arity + col], Diff::ONE));
1168                    row_packer.push(func.eval(column_iter, &temp_storage));
1169                }
1170                // We only want to arrange the parts of the input that are not part of the output.
1171                // The reduction emits the winner with a positive diff and every input with its diff
1172                // negated, so `negated_output.concat(input)` in the caller holds one copy of the
1173                // winner, regardless of its multiplicity in the input. The winner cancels against an
1174                // input row only if it equals one, which holds for a single aggregate but not in
1175                // general for several aggregates whose results come from different rows.
1176                target.reserve(source.len().saturating_add(1));
1177                target.push((BatchValOwn::<Tr>::ok(row_builder.clone()), Diff::ONE));
1178                target.extend(source.iter().map(|(values, cnt)| {
1179                    let mut cnt = *cnt;
1180                    cnt.negate();
1181                    (BatchValOwn::<Tr>::ok(values.to_row()), cnt)
1182                }));
1183            },
1184        );
1185        (arranged_input, reduced)
1186    }
1187
1188    /// Build the dataflow to compute and arrange multiple hierarchical aggregations
1189    /// on monotonic inputs.
1190    fn build_monotonic<'s>(
1191        &self,
1192        collection: VecCollection<'s, T, (Row, Row), Diff>,
1193        MonotonicPlan {
1194            aggr_funcs,
1195            must_consolidate,
1196        }: MonotonicPlan,
1197        mfp_after: Option<SafeMfpPlan<LirScalarExpr>>,
1198    ) -> (
1199        RowRowArrangement<'s, T>,
1200        VecCollection<'s, T, DataflowErrorSer, Diff>,
1201    ) {
1202        let aggregations = aggr_funcs.len();
1203        // Gather the relevant values into a vec of rows ordered by aggregation_index
1204        let collection = collection
1205            .map(move |(key, row)| {
1206                let mut row_builder = SharedRow::get();
1207                let mut values = Vec::with_capacity(aggregations);
1208                values.extend(
1209                    row.iter()
1210                        .take(aggregations)
1211                        .map(|v| row_builder.pack_using(std::iter::once(v))),
1212                );
1213
1214                (key, values)
1215            })
1216            .consolidate_named_if::<ConsolidateBatcher<_, _, _>>(
1217                must_consolidate,
1218                "Consolidated ReduceMonotonic input",
1219            );
1220
1221        // It should be now possible to ensure that we have a monotonic collection.
1222        let error_logger = self.error_logger();
1223        let (partial, validation_errs) = collection.ensure_monotonic(move |data, diff| {
1224            error_logger.log(
1225                "Non-monotonic input to ReduceMonotonic",
1226                &format!("data={data:?}, diff={diff}"),
1227            );
1228            let m = "tried to build a monotonic reduction on non-monotonic input".into();
1229            (EvalError::Internal(m).into(), Diff::ONE)
1230        });
1231        // We can place our rows directly into the diff field, and
1232        // only keep the relevant one corresponding to evaluating our
1233        // aggregate, instead of having to do a hierarchical reduction.
1234        let partial = partial.explode_one(move |(key, values)| {
1235            let mut output = Vec::new();
1236            for (row, func) in values.into_iter().zip_eq(aggr_funcs.iter()) {
1237                output.push(monoids::get_monoid(row, func).expect(
1238                    "hierarchical aggregations are expected to have monoid implementations",
1239                ));
1240            }
1241            (key, output)
1242        });
1243
1244        // Allocations for the two closures.
1245        let mut datums1 = DatumVec::new();
1246        let mut datums2 = DatumVec::new();
1247        let mfp_after1 = mfp_after.clone();
1248        let mfp_after2 = mfp_after.filter(|mfp| mfp.could_error());
1249
1250        let partial: KeyCollection<_, _, _> = partial.into();
1251        type MonoidSpine<T> = RowSpine<T, Vec<ReductionMonoid>>;
1252        let arranged =
1253            partial.mz_arrange::<RowBatcher<_, _>, MonoidSpine<_>>("ArrangeMonotonic [val: empty]");
1254        let output = arranged
1255            .clone()
1256            .mz_reduce_abelian::<_, RowRowBuilder<_, _>, RowRowSpine<_, _>, _>(
1257                "ReduceMonotonic",
1258                {
1259                    move |key, input, output| {
1260                        let temp_storage = RowArena::new();
1261                        let mut datums_local = datums1.borrow();
1262                        key.extend_datums(&temp_storage, &mut datums_local, None);
1263                        let key_len = datums_local.len();
1264                        let accum = &input[0].1;
1265                        for monoid in accum.iter() {
1266                            datums_local.extend(monoid.finalize().iter());
1267                        }
1268
1269                        if let Some(row) = evaluate_mfp_after(
1270                            &mfp_after1,
1271                            &mut datums_local,
1272                            &temp_storage,
1273                            key_len,
1274                        ) {
1275                            output.push((row, Diff::ONE));
1276                        }
1277                    }
1278                },
1279            );
1280
1281        // If `mfp_after` can error, then we need to render a paired reduction
1282        // to scan for these potential errors. Note that we cannot directly use
1283        // `mz_timely_util::reduce::ReduceExt::reduce_pair` here because we only
1284        // conditionally render the second component of the reduction pair.
1285        if let Some(mfp) = mfp_after2 {
1286            let mfp_errs = arranged
1287                .mz_reduce_abelian::<_, RowErrBuilder<_, _>, RowErrSpine<_, _>, _>(
1288                    "ReduceMonotonic Error Check",
1289                    move |key, input, output| {
1290                        let temp_storage = RowArena::new();
1291                        let mut datums_local = datums2.borrow();
1292                        key.extend_datums(&temp_storage, &mut datums_local, None);
1293                        let accum = &input[0].1;
1294                        for monoid in accum.iter() {
1295                            datums_local.extend(monoid.finalize().iter());
1296                        }
1297                        if let Result::Err(e) = mfp.evaluate_inner(&mut datums_local, &temp_storage)
1298                        {
1299                            output.push((e.into(), Diff::ONE));
1300                        }
1301                    },
1302                )
1303                .as_collection(|_k, v| v.clone());
1304            (output, validation_errs.concat(mfp_errs))
1305        } else {
1306            (output, validation_errs)
1307        }
1308    }
1309
1310    /// Build the dataflow to compute and arrange multiple accumulable aggregations.
1311    ///
1312    /// The incoming values are moved to the update's "difference" field, at which point
1313    /// they can be accumulated in place. The `count` operator promotes the accumulated
1314    /// values to data, at which point a final map applies operator-specific logic to
1315    /// yield the final aggregate.
1316    fn build_accumulable<'s>(
1317        &self,
1318        collection: VecCollection<'s, T, (Row, Row), Diff>,
1319        AccumulablePlan {
1320            full_aggrs,
1321            simple_aggrs,
1322            distinct_aggrs,
1323        }: AccumulablePlan,
1324        key_arity: usize,
1325        mfp_after: Option<SafeMfpPlan<LirScalarExpr>>,
1326    ) -> (
1327        RowRowArrangement<'s, T>,
1328        VecCollection<'s, T, DataflowErrorSer, Diff>,
1329    ) {
1330        let collection_scope = collection.scope();
1331
1332        // we must have called this function with something to reduce
1333        if full_aggrs.len() == 0 || simple_aggrs.len() + distinct_aggrs.len() != full_aggrs.len() {
1334            self.error_logger().soft_panic_or_log(
1335                "Incorrect numbers of aggregates in accummulable reduction rendering",
1336                &format!(
1337                    "full_aggrs={}, simple_aggrs={}, distinct_aggrs={}",
1338                    full_aggrs.len(),
1339                    simple_aggrs.len(),
1340                    distinct_aggrs.len(),
1341                ),
1342            );
1343        }
1344
1345        // Some of the aggregations may have the `distinct` bit set, which means that they'll
1346        // need to be extracted from `collection` and be subjected to `distinct` with `key`.
1347        // Other aggregations can be directly moved in to the `diff` field.
1348        //
1349        // In each case, the resulting collection should have `data` shaped as `(key, ())`
1350        // and a `diff` that is a vector with length `3 * aggrs.len()`. The three values are
1351        // generally the count, and then two aggregation-specific values. The size could be
1352        // reduced if we want to specialize for the aggregations.
1353
1354        // Instantiate a default vector for diffs with the correct types at each
1355        // position.
1356        let zero_diffs: (Vec<_>, Diff) = (
1357            full_aggrs
1358                .iter()
1359                .map(|f| accumulable_zero(&f.func))
1360                .collect(),
1361            Diff::ZERO,
1362        );
1363
1364        let mut to_aggregate = Vec::new();
1365        if simple_aggrs.len() > 0 {
1366            // First, collect all non-distinct aggregations in one pass.
1367            let collection = collection.clone();
1368            let easy_cases = collection.explode_one({
1369                let zero_diffs = zero_diffs.clone();
1370                move |(key, row)| {
1371                    let mut diffs = zero_diffs.clone();
1372                    // Try to unpack only the datums we need. Unfortunately, since we
1373                    // can't random access into a Row, we have to iterate through one by one.
1374                    // TODO: Even though we don't have random access, we could still avoid unpacking
1375                    // everything that we don't care about, and it might be worth it to extend the
1376                    // Row API to do that.
1377                    let mut row_iter = row.iter().enumerate();
1378                    for (datum_index, aggr) in simple_aggrs.iter() {
1379                        let mut datum = row_iter.next().unwrap();
1380                        while datum_index != &datum.0 {
1381                            datum = row_iter.next().unwrap();
1382                        }
1383                        let datum = datum.1;
1384                        diffs.0[*datum_index] = datum_to_accumulator(&aggr.func, datum);
1385                        diffs.1 = Diff::ONE;
1386                    }
1387                    ((key, ()), diffs)
1388                }
1389            });
1390            to_aggregate.push(easy_cases);
1391        }
1392
1393        // Next, collect all aggregations that require distinctness.
1394        for (datum_index, aggr) in distinct_aggrs.into_iter() {
1395            let pairer = Pairer::new(key_arity);
1396            let collection = collection
1397                .clone()
1398                .map(move |(key, row)| {
1399                    let value = row.iter().nth(datum_index).unwrap();
1400                    (pairer.merge(&key, std::iter::once(value)), ())
1401                })
1402                .mz_arrange::<RowBatcher<_, _>, RowSpine<_, _>>(
1403                    "Arranged Accumulable Distinct [val: empty]",
1404                )
1405                .mz_reduce_abelian::<_, RowBuilder<_, _>, RowSpine<_, _>, _>(
1406                    "Reduced Accumulable Distinct [val: empty]",
1407                    move |_k, _s, t| t.push(((), Diff::ONE)),
1408                )
1409                .as_collection(move |key_val_iter, _| pairer.split(key_val_iter))
1410                .explode_one({
1411                    let zero_diffs = zero_diffs.clone();
1412                    move |(key, row)| {
1413                        let datum = row.iter().next().unwrap();
1414                        let mut diffs = zero_diffs.clone();
1415                        diffs.0[datum_index] = datum_to_accumulator(&aggr.func, datum);
1416                        diffs.1 = Diff::ONE;
1417                        ((key, ()), diffs)
1418                    }
1419                });
1420            to_aggregate.push(collection);
1421        }
1422
1423        // now concatenate, if necessary, multiple aggregations
1424        let collection = if to_aggregate.len() == 1 {
1425            to_aggregate.remove(0)
1426        } else {
1427            differential_dataflow::collection::concatenate(collection_scope, to_aggregate)
1428        };
1429
1430        // The accumulators travel in the arrangement's diffs. A columnar diff container
1431        // lays each `Accum` out by variant, so it occupies only its own variant's
1432        // columns rather than the footprint of the largest variant. Both layouts feed
1433        // the same reduce operators.
1434        if ENABLE_COLUMNAR_ACCUMULABLE_DIFF.get(&self.config_set) {
1435            let arranged = collection.mz_arrange::<
1436                RowBatcher<_, _, Coltainer<_>>,
1437                RowSpine<_, (Vec<Accum>, Diff), Coltainer<_>>,
1438            >("ArrangeAccumulable [val: empty]");
1439            self.reduce_accumulable(arranged, full_aggrs, mfp_after)
1440        } else {
1441            let arranged = collection
1442                .mz_arrange::<RowBatcher<_, _>, RowSpine<_, (Vec<Accum>, Diff)>>(
1443                    "ArrangeAccumulable [val: empty]",
1444                );
1445            self.reduce_accumulable(arranged, full_aggrs, mfp_after)
1446        }
1447    }
1448
1449    /// Reduces arranged accumulators to output rows, and to the errors the accumulated
1450    /// values can reveal. Generic over the container holding the diffs, so both diff
1451    /// layouts share one rendering of the reduce operators.
1452    fn reduce_accumulable<'s, DC>(
1453        &self,
1454        arranged: Arranged<'s, RowAgent<T, (Vec<Accum>, Diff), DC>>,
1455        full_aggrs: Vec<LirAggregateExpr>,
1456        mfp_after: Option<SafeMfpPlan<LirScalarExpr>>,
1457    ) -> (
1458        RowRowArrangement<'s, T>,
1459        VecCollection<'s, T, DataflowErrorSer, Diff>,
1460    )
1461    where
1462        DC: BatchContainer<Owned = (Vec<Accum>, Diff)>,
1463    {
1464        // Allocations for the two closures.
1465        let mut datums1 = DatumVec::new();
1466        let mut datums2 = DatumVec::new();
1467        let mfp_after1 = mfp_after.clone();
1468        let mfp_after2 = mfp_after.filter(|mfp| mfp.could_error());
1469        let full_aggrs2 = full_aggrs.clone();
1470
1471        let error_logger = self.error_logger();
1472        let err_full_aggrs = full_aggrs.clone();
1473        let arranged_output = arranged
1474            .clone()
1475            .mz_reduce_abelian::<_, RowRowBuilder<_, _>, RowRowSpine<_, _>, _>(
1476                "ReduceAccumulable",
1477                {
1478                    move |key, input, output| {
1479                        let (ref accums, total) = input[0].1;
1480
1481                        let temp_storage = RowArena::new();
1482                        let mut datums_local = datums1.borrow();
1483                        key.extend_datums(&temp_storage, &mut datums_local, None);
1484                        let key_len = datums_local.len();
1485                        for (aggr, accum) in full_aggrs.iter().zip_eq(accums) {
1486                            datums_local.push(finalize_accum(&aggr.func, accum, total));
1487                        }
1488
1489                        if let Some(row) = evaluate_mfp_after(
1490                            &mfp_after1,
1491                            &mut datums_local,
1492                            &temp_storage,
1493                            key_len,
1494                        ) {
1495                            output.push((row, Diff::ONE));
1496                        }
1497                    }
1498                },
1499            );
1500        let arranged_errs = arranged
1501            .mz_reduce_abelian::<_, RowErrBuilder<_, _>, RowErrSpine<_, _>, _>(
1502                "AccumulableErrorCheck",
1503                move |key, input, output| {
1504                    let (ref accums, total) = input[0].1;
1505                    for (aggr, accum) in err_full_aggrs.iter().zip_eq(accums) {
1506                        // We first test here if inputs without net-positive records are present,
1507                        // producing an error to the logs and to the query output if that is the case.
1508                        if total == Diff::ZERO && !accum.is_zero() {
1509                            error_logger.log(
1510                                "Net-zero records with non-zero accumulation in ReduceAccumulable",
1511                                &format!("aggr={aggr:?}, accum={accum:?}"),
1512                            );
1513                            let key = key.to_row();
1514                            let message = format!(
1515                                "Invalid data in source, saw net-zero records for key {key} \
1516                                 with non-zero accumulation in accumulable aggregate"
1517                            );
1518                            output.push((EvalError::Internal(message.into()).into(), Diff::ONE));
1519                        }
1520                        match (&aggr.func, &accum) {
1521                            (AggregateFunc::SumUInt16, Accum::SimpleNumber { accum, .. })
1522                            | (AggregateFunc::SumUInt32, Accum::SimpleNumber { accum, .. })
1523                            | (AggregateFunc::SumUInt64, Accum::SimpleNumber { accum, .. }) => {
1524                                if accum.is_negative() {
1525                                    error_logger.log(
1526                                    "Invalid negative unsigned aggregation in ReduceAccumulable",
1527                                    &format!("aggr={aggr:?}, accum={accum:?}"),
1528                                );
1529                                    let key = key.to_row();
1530                                    let message = format!(
1531                                        "Invalid data in source, saw negative accumulation with \
1532                                         unsigned type for key {key}"
1533                                    );
1534                                    let err = EvalError::Internal(message.into());
1535                                    output.push((err.into(), Diff::ONE));
1536                                }
1537                            }
1538                            (
1539                                AggregateFunc::SumInterval,
1540                                Accum::Interval {
1541                                    months,
1542                                    days,
1543                                    micros,
1544                                    ..
1545                                },
1546                            ) => {
1547                                // PostgreSQL reports a sum that leaves the
1548                                // `Interval` field widths as `interval out of
1549                                // range`. So do we.
1550                                if Interval::try_new(
1551                                    months.into_inner(),
1552                                    days.into_inner(),
1553                                    micros.into_inner(),
1554                                )
1555                                .is_none()
1556                                {
1557                                    let err = EvalError::IntervalOutOfRange(
1558                                        format!(
1559                                            "{months} months {days} days {micros} microseconds"
1560                                        )
1561                                        .into(),
1562                                    );
1563                                    output.push((err.into(), Diff::ONE));
1564                                }
1565                            }
1566                            _ => (), // no more errors to check for at this point!
1567                        }
1568                    }
1569
1570                    // If `mfp_after` can error, then evaluate it here.
1571                    let Some(mfp) = &mfp_after2 else { return };
1572                    let temp_storage = RowArena::new();
1573                    let mut datums_local = datums2.borrow();
1574                    key.extend_datums(&temp_storage, &mut datums_local, None);
1575                    for (aggr, accum) in full_aggrs2.iter().zip_eq(accums) {
1576                        datums_local.push(finalize_accum(&aggr.func, accum, total));
1577                    }
1578
1579                    if let Result::Err(e) = mfp.evaluate_inner(&mut datums_local, &temp_storage) {
1580                        output.push((e.into(), Diff::ONE));
1581                    }
1582                },
1583            );
1584        (
1585            arranged_output,
1586            arranged_errs.as_collection(|_key, error| error.clone()),
1587        )
1588    }
1589}
1590
1591/// Evaluates the fused MFP, if one exists, on a reconstructed `DatumVecBorrow`
1592/// containing key and aggregate values, then returns a result `Row` or `None`
1593/// if the MFP filters the result out.
1594fn evaluate_mfp_after<'a, 'b>(
1595    mfp_after: &'a Option<SafeMfpPlan<LirScalarExpr>>,
1596    datums_local: &'b mut mz_repr::DatumVecBorrow<'a>,
1597    temp_storage: &'a RowArena,
1598    key_len: usize,
1599) -> Option<Row> {
1600    let mut row_builder = SharedRow::get();
1601    // Apply MFP if it exists and pack a Row of
1602    // aggregate values from `datums_local`.
1603    if let Some(mfp) = mfp_after {
1604        // It must ignore errors here, but they are scanned
1605        // for elsewhere if the MFP can error.
1606        if let Ok(Some(iter)) = mfp.evaluate_iter(datums_local, temp_storage) {
1607            // The `mfp_after` must preserve the key columns,
1608            // so we can skip them to form aggregation results.
1609            Some(row_builder.pack_using(iter.skip(key_len)))
1610        } else {
1611            None
1612        }
1613    } else {
1614        Some(row_builder.pack_using(&datums_local[key_len..]))
1615    }
1616}
1617
1618fn accumulable_zero(aggr_func: &AggregateFunc) -> Accum {
1619    match aggr_func {
1620        AggregateFunc::Any | AggregateFunc::All => Accum::Bool {
1621            trues: Diff::ZERO,
1622            falses: Diff::ZERO,
1623        },
1624        AggregateFunc::SumFloat32 | AggregateFunc::SumFloat64 => Accum::Float {
1625            accum: AccumCount::ZERO,
1626            pos_infs: Diff::ZERO,
1627            neg_infs: Diff::ZERO,
1628            nans: Diff::ZERO,
1629            non_nulls: Diff::ZERO,
1630        },
1631        AggregateFunc::SumNumeric => Accum::Numeric {
1632            accum: OrderedNumericAgg(NumericAgg::zero()),
1633            pos_infs: Diff::ZERO,
1634            neg_infs: Diff::ZERO,
1635            nans: Diff::ZERO,
1636            non_nulls: Diff::ZERO,
1637        },
1638        AggregateFunc::SumInterval => Accum::Interval {
1639            months: AccumCount::ZERO,
1640            days: AccumCount::ZERO,
1641            micros: AccumCount::ZERO,
1642            non_nulls: Diff::ZERO,
1643        },
1644        _ => Accum::SimpleNumber {
1645            accum: AccumCount::ZERO,
1646            non_nulls: Diff::ZERO,
1647        },
1648    }
1649}
1650
1651/// The number of fractional bits of binary precision retained by the
1652/// fixed-point representation used to accumulate float sums. The fixed-point
1653/// scale is `FLOAT_SCALE == 2^FLOAT_SCALE_EXP`.
1654const FLOAT_SCALE_EXP: u32 = 24;
1655
1656/// The fixed-point scale applied to float sums, i.e. `2^FLOAT_SCALE_EXP`.
1657#[allow(clippy::as_conversions)] // Integer-to-float cast, exact and const-evaluable.
1658const FLOAT_SCALE: f64 = (1_u64 << FLOAT_SCALE_EXP) as f64;
1659
1660/// Maps a finite `f64` onto the fixed-point `i128` domain used to accumulate
1661/// float sums, i.e. computes `trunc(n * FLOAT_SCALE)` reduced modulo `2^128`.
1662///
1663/// Conceptually this multiplies `n` by `FLOAT_SCALE` and truncates towards zero,
1664/// but it does so using *wrapping* (modulo `2^128`) rather than *saturating*
1665/// semantics, and it never forms the intermediate product `n * FLOAT_SCALE` as
1666/// an `f64` (which could itself overflow to infinity for very large `n`).
1667///
1668/// Wrapping is what makes this conversion a group homomorphism into the additive
1669/// group of `i128` (mod `2^128`), matching the wrapping arithmetic used when
1670/// accumulators are combined and retracted. As a result, a set of large finite
1671/// values whose *sum* is representable produces the correct result even when the
1672/// individual values fall outside the representable fixed-point range. Saturating
1673/// instead breaks this: e.g. `1.1e31` and `-1.1e31` both overflow the domain and
1674/// would saturate to `i128::MAX` and `i128::MIN`, which sum to `-1` rather than
1675/// `0` (see database-issues#11265).
1676fn float_to_fixed_point(n: f64) -> i128 {
1677    mz_ore::soft_assert_no_log!(n.is_finite());
1678
1679    // Decompose `n` into integer parts such that `n == sign * mantissa *
1680    // 2^exponent`. Folding in the `* 2^FLOAT_SCALE_EXP` scaling then amounts to
1681    // shifting `mantissa` left by `exponent + FLOAT_SCALE_EXP` bits.
1682    let (mantissa, exponent, sign) = Float::integer_decode(n);
1683    let significand = u128::from(mantissa);
1684    let exp = i64::from(exponent) + i64::from(FLOAT_SCALE_EXP);
1685
1686    let magnitude: u128 = if exp >= 0 {
1687        // Left shifts of 128 or more bits leave nothing within the 128-bit
1688        // window; smaller shifts keep only the low 128 bits (i.e. mod `2^128`).
1689        match u32::try_from(exp) {
1690            Ok(shift) if shift < 128 => significand << shift,
1691            _ => 0,
1692        }
1693    } else {
1694        // Right shift truncates the fractional part towards zero. Subnormals
1695        // (and zero) shift entirely out of the window and become zero.
1696        match u32::try_from(-exp) {
1697            Ok(shift) if shift < 128 => significand >> shift,
1698            _ => 0,
1699        }
1700    };
1701
1702    // Reinterpret the magnitude as a signed `i128` (wrapping into the signed
1703    // domain) and apply the sign of `n`.
1704    let magnitude = magnitude.cast_signed();
1705    if sign < 0 {
1706        magnitude.wrapping_neg()
1707    } else {
1708        magnitude
1709    }
1710}
1711
1712fn datum_to_accumulator(aggregate_func: &AggregateFunc, datum: Datum) -> Accum {
1713    match aggregate_func {
1714        AggregateFunc::Count => Accum::SimpleNumber {
1715            accum: AccumCount::ZERO, // unused for AggregateFunc::Count
1716            non_nulls: if datum.is_null() {
1717                Diff::ZERO
1718            } else {
1719                Diff::ONE
1720            },
1721        },
1722        AggregateFunc::Any | AggregateFunc::All => match datum {
1723            Datum::True => Accum::Bool {
1724                trues: Diff::ONE,
1725                falses: Diff::ZERO,
1726            },
1727            Datum::Null => Accum::Bool {
1728                trues: Diff::ZERO,
1729                falses: Diff::ZERO,
1730            },
1731            Datum::False => Accum::Bool {
1732                trues: Diff::ZERO,
1733                falses: Diff::ONE,
1734            },
1735            x => panic!("Invalid argument to AggregateFunc::Any: {x:?}"),
1736        },
1737        AggregateFunc::Dummy => match datum {
1738            Datum::Dummy => Accum::SimpleNumber {
1739                accum: AccumCount::ZERO,
1740                non_nulls: Diff::ZERO,
1741            },
1742            x => panic!("Invalid argument to AggregateFunc::Dummy: {x:?}"),
1743        },
1744        AggregateFunc::SumFloat32 | AggregateFunc::SumFloat64 => {
1745            let n = match datum {
1746                Datum::Float32(n) => f64::from(*n),
1747                Datum::Float64(n) => *n,
1748                Datum::Null => 0f64,
1749                x => panic!("Invalid argument to AggregateFunc::{aggregate_func:?}: {x:?}"),
1750            };
1751
1752            let nans = Diff::from(n.is_nan());
1753            let pos_infs = Diff::from(n == f64::INFINITY);
1754            let neg_infs = Diff::from(n == f64::NEG_INFINITY);
1755            let non_nulls = Diff::from(datum != Datum::Null);
1756
1757            // Map the floating point value onto a fixed precision domain
1758            // All special values should map to zero, since they are tracked separately
1759            let accum = if nans.is_positive() || pos_infs.is_positive() || neg_infs.is_positive() {
1760                AccumCount::ZERO
1761            } else {
1762                // Wrap (rather than saturate) on overflow, so that the mapping is
1763                // a group homomorphism and large finite values whose sum is in
1764                // range still produce correct results (database-issues#11265).
1765                float_to_fixed_point(n).into()
1766            };
1767
1768            Accum::Float {
1769                accum,
1770                pos_infs,
1771                neg_infs,
1772                nans,
1773                non_nulls,
1774            }
1775        }
1776        AggregateFunc::SumNumeric => match datum {
1777            Datum::Numeric(n) => {
1778                let (accum, pos_infs, neg_infs, nans) = if n.0.is_infinite() {
1779                    if n.0.is_negative() {
1780                        (NumericAgg::zero(), Diff::ZERO, Diff::ONE, Diff::ZERO)
1781                    } else {
1782                        (NumericAgg::zero(), Diff::ONE, Diff::ZERO, Diff::ZERO)
1783                    }
1784                } else if n.0.is_nan() {
1785                    (NumericAgg::zero(), Diff::ZERO, Diff::ZERO, Diff::ONE)
1786                } else {
1787                    // Take a narrow decimal (datum) into a wide decimal
1788                    // (aggregator).
1789                    let mut cx_agg = numeric::cx_agg();
1790                    (cx_agg.to_width(n.0), Diff::ZERO, Diff::ZERO, Diff::ZERO)
1791                };
1792
1793                Accum::Numeric {
1794                    accum: OrderedNumericAgg(accum),
1795                    pos_infs,
1796                    neg_infs,
1797                    nans,
1798                    non_nulls: Diff::ONE,
1799                }
1800            }
1801            Datum::Null => Accum::Numeric {
1802                accum: OrderedNumericAgg(NumericAgg::zero()),
1803                pos_infs: Diff::ZERO,
1804                neg_infs: Diff::ZERO,
1805                nans: Diff::ZERO,
1806                non_nulls: Diff::ZERO,
1807            },
1808            x => panic!("Invalid argument to AggregateFunc::SumNumeric: {x:?}"),
1809        },
1810        AggregateFunc::SumInterval => match datum {
1811            Datum::Interval(i) => Accum::Interval {
1812                months: i.months.into(),
1813                days: i.days.into(),
1814                micros: i.micros.into(),
1815                non_nulls: Diff::ONE,
1816            },
1817            Datum::Null => Accum::Interval {
1818                months: AccumCount::ZERO,
1819                days: AccumCount::ZERO,
1820                micros: AccumCount::ZERO,
1821                non_nulls: Diff::ZERO,
1822            },
1823            x => panic!("Invalid argument to AggregateFunc::SumInterval: {x:?}"),
1824        },
1825        _ => {
1826            // Other accumulations need to disentangle the accumulable
1827            // value from its NULL-ness, which is not quite as easily
1828            // accumulated.
1829            match datum {
1830                Datum::Int16(i) => Accum::SimpleNumber {
1831                    accum: i.into(),
1832                    non_nulls: Diff::ONE,
1833                },
1834                Datum::Int32(i) => Accum::SimpleNumber {
1835                    accum: i.into(),
1836                    non_nulls: Diff::ONE,
1837                },
1838                Datum::Int64(i) => Accum::SimpleNumber {
1839                    accum: i.into(),
1840                    non_nulls: Diff::ONE,
1841                },
1842                Datum::UInt16(u) => Accum::SimpleNumber {
1843                    accum: u.into(),
1844                    non_nulls: Diff::ONE,
1845                },
1846                Datum::UInt32(u) => Accum::SimpleNumber {
1847                    accum: u.into(),
1848                    non_nulls: Diff::ONE,
1849                },
1850                Datum::UInt64(u) => Accum::SimpleNumber {
1851                    accum: u.into(),
1852                    non_nulls: Diff::ONE,
1853                },
1854                Datum::MzTimestamp(t) => Accum::SimpleNumber {
1855                    accum: u64::from(t).into(),
1856                    non_nulls: Diff::ONE,
1857                },
1858                Datum::Null => Accum::SimpleNumber {
1859                    accum: AccumCount::ZERO,
1860                    non_nulls: Diff::ZERO,
1861                },
1862                x => panic!("Accumulating non-integer data: {x:?}"),
1863            }
1864        }
1865    }
1866}
1867
1868fn finalize_accum<'a>(aggr_func: &'a AggregateFunc, accum: &'a Accum, total: Diff) -> Datum<'a> {
1869    // The finished value depends on the aggregation function in a variety of ways.
1870    // For all aggregates but count, if only null values were
1871    // accumulated, then the output is null.
1872    if total.is_positive() && accum.is_zero() && *aggr_func != AggregateFunc::Count {
1873        Datum::Null
1874    } else {
1875        match (&aggr_func, &accum) {
1876            (AggregateFunc::Count, Accum::SimpleNumber { non_nulls, .. }) => {
1877                Datum::Int64(non_nulls.into_inner())
1878            }
1879            (AggregateFunc::All, Accum::Bool { falses, trues }) => {
1880                // If any false, else if all true, else must be no false and some nulls.
1881                if falses.is_positive() {
1882                    Datum::False
1883                } else if *trues == total {
1884                    Datum::True
1885                } else {
1886                    Datum::Null
1887                }
1888            }
1889            (AggregateFunc::Any, Accum::Bool { falses, trues }) => {
1890                // If any true, else if all false, else must be no true and some nulls.
1891                if trues.is_positive() {
1892                    Datum::True
1893                } else if *falses == total {
1894                    Datum::False
1895                } else {
1896                    Datum::Null
1897                }
1898            }
1899            (AggregateFunc::Dummy, _) => Datum::Dummy,
1900            // If any non-nulls, just report the aggregate.
1901            (AggregateFunc::SumInt16, Accum::SimpleNumber { accum, .. })
1902            | (AggregateFunc::SumInt32, Accum::SimpleNumber { accum, .. }) => {
1903                // This conversion is safe, as long as we have less than 2^32
1904                // summands.
1905                // TODO(benesch): are we guaranteed to have less than 2^32 summands?
1906                // If so, rewrite to avoid `as`.
1907                #[allow(clippy::as_conversions)]
1908                Datum::Int64(accum.into_inner() as i64)
1909            }
1910            (AggregateFunc::SumInt64, Accum::SimpleNumber { accum, .. }) => Datum::from(*accum),
1911            (AggregateFunc::SumUInt16, Accum::SimpleNumber { accum, .. })
1912            | (AggregateFunc::SumUInt32, Accum::SimpleNumber { accum, .. }) => {
1913                if !accum.is_negative() {
1914                    // Our semantics of overflow are not clearly articulated wrt.
1915                    // unsigned vs. signed types (database-issues#5172). We adopt an
1916                    // unsigned wrapping behavior to match what we do above for
1917                    // signed types.
1918                    // TODO(vmarcos): remove potentially dangerous usage of `as`.
1919                    #[allow(clippy::as_conversions)]
1920                    Datum::UInt64(accum.into_inner() as u64)
1921                } else {
1922                    // Note that we return a value here, but an error in the other
1923                    // operator of the reduce_pair. Therefore, we expect that this
1924                    // value will never be exposed as an output.
1925                    Datum::Null
1926                }
1927            }
1928            (AggregateFunc::SumUInt64, Accum::SimpleNumber { accum, .. }) => {
1929                if !accum.is_negative() {
1930                    Datum::from(*accum)
1931                } else {
1932                    // Note that we return a value here, but an error in the other
1933                    // operator of the reduce_pair. Therefore, we expect that this
1934                    // value will never be exposed as an output.
1935                    Datum::Null
1936                }
1937            }
1938            (
1939                AggregateFunc::SumFloat32,
1940                Accum::Float {
1941                    accum,
1942                    pos_infs,
1943                    neg_infs,
1944                    nans,
1945                    non_nulls: _,
1946                },
1947            ) => {
1948                if nans.is_positive() || (pos_infs.is_positive() && neg_infs.is_positive()) {
1949                    // NaNs are NaNs and cases where we've seen a
1950                    // mixture of positive and negative infinities.
1951                    Datum::from(f32::NAN)
1952                } else if pos_infs.is_positive() {
1953                    Datum::from(f32::INFINITY)
1954                } else if neg_infs.is_positive() {
1955                    Datum::from(f32::NEG_INFINITY)
1956                } else {
1957                    let sum = f64::cast_lossy(accum.into_inner()) / FLOAT_SCALE;
1958                    Datum::from(f32::cast_lossy(sum))
1959                }
1960            }
1961            (
1962                AggregateFunc::SumFloat64,
1963                Accum::Float {
1964                    accum,
1965                    pos_infs,
1966                    neg_infs,
1967                    nans,
1968                    non_nulls: _,
1969                },
1970            ) => {
1971                if nans.is_positive() || (pos_infs.is_positive() && neg_infs.is_positive()) {
1972                    // NaNs are NaNs and cases where we've seen a
1973                    // mixture of positive and negative infinities.
1974                    Datum::from(f64::NAN)
1975                } else if pos_infs.is_positive() {
1976                    Datum::from(f64::INFINITY)
1977                } else if neg_infs.is_positive() {
1978                    Datum::from(f64::NEG_INFINITY)
1979                } else {
1980                    Datum::from(f64::cast_lossy(accum.into_inner()) / FLOAT_SCALE)
1981                }
1982            }
1983            (
1984                AggregateFunc::SumNumeric,
1985                Accum::Numeric {
1986                    accum,
1987                    pos_infs,
1988                    neg_infs,
1989                    nans,
1990                    non_nulls: _,
1991                },
1992            ) => {
1993                let mut cx_datum = numeric::cx_datum();
1994                let d = cx_datum.to_width(accum.0);
1995                // Take a wide decimal (aggregator) into a
1996                // narrow decimal (datum). If this operation
1997                // overflows the datum, this new value will be
1998                // +/- infinity. However, the aggregator tracks
1999                // the amount of overflow, making it invertible.
2000                let inf_d = d.is_infinite();
2001                let neg_d = d.is_negative();
2002                let pos_inf = pos_infs.is_positive() || (inf_d && !neg_d);
2003                let neg_inf = neg_infs.is_positive() || (inf_d && neg_d);
2004                if nans.is_positive() || (pos_inf && neg_inf) {
2005                    // NaNs are NaNs and cases where we've seen a
2006                    // mixture of positive and negative infinities.
2007                    Datum::from(Numeric::nan())
2008                } else if pos_inf {
2009                    Datum::from(Numeric::infinity())
2010                } else if neg_inf {
2011                    let mut cx = numeric::cx_datum();
2012                    let mut d = Numeric::infinity();
2013                    cx.neg(&mut d);
2014                    Datum::from(d)
2015                } else {
2016                    Datum::from(d)
2017                }
2018            }
2019            (
2020                AggregateFunc::SumInterval,
2021                Accum::Interval {
2022                    months,
2023                    days,
2024                    micros,
2025                    non_nulls: _,
2026                },
2027            ) => {
2028                match Interval::try_new(months.into_inner(), days.into_inner(), micros.into_inner())
2029                {
2030                    Some(interval) => Datum::Interval(interval),
2031                    // The sum overflows an `Interval`. In the accumulable
2032                    // reduce pair the sibling operator raises the error, so
2033                    // this value is never exposed. `AccumulableOneByOneAggr`
2034                    // has no sibling, so a window aggregate does surface this
2035                    // NULL. See `mz_expr::sum_interval_counted`.
2036                    None => Datum::Null,
2037                }
2038            }
2039            _ => panic!(
2040                "Unexpected accumulation (aggr={:?}, accum={accum:?})",
2041                aggr_func
2042            ),
2043        }
2044    }
2045}
2046
2047/// The type for accumulator counting. Set to [`Overflowing<u128>`](mz_ore::Overflowing).
2048type AccumCount = mz_ore::Overflowing<i128>;
2049
2050/// Accumulates values for the various types of accumulable aggregations.
2051///
2052/// We assume that there are not more than 2^32 elements for the aggregation.
2053/// Thus we can perform a summation over i32 in an i64 accumulator
2054/// and not worry about exceeding its bounds.
2055///
2056/// The float accumulator performs accumulation in fixed point arithmetic. The fixed
2057/// point representation has less precision than a double. It is entirely possible
2058/// that the values of the accumulator overflow, thus we have to use wrapping arithmetic
2059/// to preserve group guarantees.
2060#[derive(
2061    Debug,
2062    Clone,
2063    Copy,
2064    PartialEq,
2065    Eq,
2066    PartialOrd,
2067    Ord,
2068    Serialize,
2069    Deserialize,
2070    Columnar
2071)]
2072// The columnar container orders references with this derived `Ord`, which must agree with
2073// the owned `Ord`. It does because every field's reference type is its owned type.
2074#[columnar(derive(PartialEq, Eq, PartialOrd, Ord))]
2075enum Accum {
2076    /// Accumulates boolean values.
2077    Bool {
2078        /// The number of `true` values observed.
2079        trues: Diff,
2080        /// The number of `false` values observed.
2081        falses: Diff,
2082    },
2083    /// Accumulates simple numeric values.
2084    SimpleNumber {
2085        /// The accumulation of all non-NULL values observed.
2086        accum: AccumCount,
2087        /// The number of non-NULL values observed.
2088        non_nulls: Diff,
2089    },
2090    /// Accumulates float values.
2091    Float {
2092        /// Accumulates non-special float values, mapped to a fixed precision i128 domain to
2093        /// preserve associativity and commutativity
2094        accum: AccumCount,
2095        /// Counts +inf
2096        pos_infs: Diff,
2097        /// Counts -inf
2098        neg_infs: Diff,
2099        /// Counts NaNs
2100        nans: Diff,
2101        /// Counts non-NULL values
2102        non_nulls: Diff,
2103    },
2104    /// Accumulates intervals as three independent component sums, matching
2105    /// PostgreSQL's interval addition: nothing is carried from a coarser
2106    /// component into a finer one. Each component accumulates in the same
2107    /// `AccumCount` the other variants use, so a sum that overflows an
2108    /// `Interval` field still consolidates and retracts correctly, and the
2109    /// narrowing at finalization is the single place that decides whether the
2110    /// result is representable.
2111    Interval {
2112        /// The accumulation of all non-NULL month counts observed.
2113        months: AccumCount,
2114        /// The accumulation of all non-NULL day counts observed.
2115        days: AccumCount,
2116        /// The accumulation of all non-NULL microsecond counts observed.
2117        micros: AccumCount,
2118        /// The number of non-NULL values observed.
2119        non_nulls: Diff,
2120    },
2121    /// Accumulates arbitrary precision decimals.
2122    Numeric {
2123        /// Accumulates non-special values
2124        accum: OrderedNumericAgg,
2125        /// Counts +inf
2126        pos_infs: Diff,
2127        /// Counts -inf
2128        neg_infs: Diff,
2129        /// Counts NaNs
2130        nans: Diff,
2131        /// Counts non-NULL values
2132        non_nulls: Diff,
2133    },
2134}
2135
2136impl IsZero for Accum {
2137    fn is_zero(&self) -> bool {
2138        match self {
2139            Accum::Bool { trues, falses } => trues.is_zero() && falses.is_zero(),
2140            Accum::SimpleNumber { accum, non_nulls } => accum.is_zero() && non_nulls.is_zero(),
2141            Accum::Float {
2142                accum,
2143                pos_infs,
2144                neg_infs,
2145                nans,
2146                non_nulls,
2147            } => {
2148                accum.is_zero()
2149                    && pos_infs.is_zero()
2150                    && neg_infs.is_zero()
2151                    && nans.is_zero()
2152                    && non_nulls.is_zero()
2153            }
2154            Accum::Interval {
2155                months,
2156                days,
2157                micros,
2158                non_nulls,
2159            } => months.is_zero() && days.is_zero() && micros.is_zero() && non_nulls.is_zero(),
2160            Accum::Numeric {
2161                accum,
2162                pos_infs,
2163                neg_infs,
2164                nans,
2165                non_nulls,
2166            } => {
2167                accum.0.is_zero()
2168                    && pos_infs.is_zero()
2169                    && neg_infs.is_zero()
2170                    && nans.is_zero()
2171                    && non_nulls.is_zero()
2172            }
2173        }
2174    }
2175}
2176
2177impl Semigroup for Accum {
2178    fn plus_equals(&mut self, other: &Accum) {
2179        match (&mut *self, other) {
2180            (
2181                Accum::Bool { trues, falses },
2182                Accum::Bool {
2183                    trues: other_trues,
2184                    falses: other_falses,
2185                },
2186            ) => {
2187                *trues += other_trues;
2188                *falses += other_falses;
2189            }
2190            (
2191                Accum::SimpleNumber { accum, non_nulls },
2192                Accum::SimpleNumber {
2193                    accum: other_accum,
2194                    non_nulls: other_non_nulls,
2195                },
2196            ) => {
2197                *accum += other_accum;
2198                *non_nulls += other_non_nulls;
2199            }
2200            (
2201                Accum::Float {
2202                    accum,
2203                    pos_infs,
2204                    neg_infs,
2205                    nans,
2206                    non_nulls,
2207                },
2208                Accum::Float {
2209                    accum: other_accum,
2210                    pos_infs: other_pos_infs,
2211                    neg_infs: other_neg_infs,
2212                    nans: other_nans,
2213                    non_nulls: other_non_nulls,
2214                },
2215            ) => {
2216                *accum = accum.checked_add(*other_accum).unwrap_or_else(|| {
2217                    warn!("Float accumulator overflow. Incorrect results possible");
2218                    accum.wrapping_add(*other_accum)
2219                });
2220                *pos_infs += other_pos_infs;
2221                *neg_infs += other_neg_infs;
2222                *nans += other_nans;
2223                *non_nulls += other_non_nulls;
2224            }
2225            (
2226                Accum::Interval {
2227                    months,
2228                    days,
2229                    micros,
2230                    non_nulls,
2231                },
2232                Accum::Interval {
2233                    months: other_months,
2234                    days: other_days,
2235                    micros: other_micros,
2236                    non_nulls: other_non_nulls,
2237                },
2238            ) => {
2239                *months += other_months;
2240                *days += other_days;
2241                *micros += other_micros;
2242                *non_nulls += other_non_nulls;
2243            }
2244            (
2245                Accum::Numeric {
2246                    accum,
2247                    pos_infs,
2248                    neg_infs,
2249                    nans,
2250                    non_nulls,
2251                },
2252                Accum::Numeric {
2253                    accum: other_accum,
2254                    pos_infs: other_pos_infs,
2255                    neg_infs: other_neg_infs,
2256                    nans: other_nans,
2257                    non_nulls: other_non_nulls,
2258                },
2259            ) => {
2260                let mut cx_agg = numeric::cx_agg();
2261                cx_agg.add(&mut accum.0, &other_accum.0);
2262                // `rounded` signals we have exceeded the aggregator's max
2263                // precision, which means we've lost commutativity and
2264                // associativity; nothing to be done here, so panic. For more
2265                // context, see the DEC_Rounded definition at
2266                // http://speleotrove.com/decimal/dncont.html
2267                assert!(!cx_agg.status().rounded(), "Accum::Numeric overflow");
2268                // Reduce to reclaim unused decimal precision. Note that this
2269                // reduction must happen somewhere to make the following
2270                // invertible:
2271                // ```
2272                // CREATE TABLE a (a numeric);
2273                // CREATE MATERIALIZED VIEW t as SELECT sum(a) FROM a;
2274                // INSERT INTO a VALUES ('9e39'), ('9e-39');
2275                // ```
2276                // This will now return infinity. However, we can retract the
2277                // value that blew up its precision:
2278                // ```
2279                // INSERT INTO a VALUES ('-9e-39');
2280                // ```
2281                // This leaves `t`'s aggregator with a value of 9e39. However,
2282                // without doing a reduction, `libdecnum` will store the value
2283                // as 9e39+0e-39, which still exceeds the narrower context's
2284                // precision. By doing the reduction, we can "reclaim" the 39
2285                // digits of precision.
2286                cx_agg.reduce(&mut accum.0);
2287                *pos_infs += other_pos_infs;
2288                *neg_infs += other_neg_infs;
2289                *nans += other_nans;
2290                *non_nulls += other_non_nulls;
2291            }
2292            (l, r) => unreachable!(
2293                "Accumulator::plus_equals called with non-matching variants: {l:?} vs {r:?}"
2294            ),
2295        }
2296    }
2297}
2298
2299impl Multiply<Diff> for Accum {
2300    type Output = Accum;
2301
2302    fn multiply(self, factor: &Diff) -> Accum {
2303        let factor = *factor;
2304        match self {
2305            Accum::Bool { trues, falses } => Accum::Bool {
2306                trues: trues * factor,
2307                falses: falses * factor,
2308            },
2309            Accum::SimpleNumber { accum, non_nulls } => Accum::SimpleNumber {
2310                accum: accum * AccumCount::from(factor),
2311                non_nulls: non_nulls * factor,
2312            },
2313            Accum::Float {
2314                accum,
2315                pos_infs,
2316                neg_infs,
2317                nans,
2318                non_nulls,
2319            } => Accum::Float {
2320                accum: accum
2321                    .checked_mul(AccumCount::from(factor))
2322                    .unwrap_or_else(|| {
2323                        warn!("Float accumulator overflow. Incorrect results possible");
2324                        accum.wrapping_mul(AccumCount::from(factor))
2325                    }),
2326                pos_infs: pos_infs * factor,
2327                neg_infs: neg_infs * factor,
2328                nans: nans * factor,
2329                non_nulls: non_nulls * factor,
2330            },
2331            Accum::Interval {
2332                months,
2333                days,
2334                micros,
2335                non_nulls,
2336            } => Accum::Interval {
2337                months: months * AccumCount::from(factor),
2338                days: days * AccumCount::from(factor),
2339                micros: micros * AccumCount::from(factor),
2340                non_nulls: non_nulls * factor,
2341            },
2342            Accum::Numeric {
2343                accum,
2344                pos_infs,
2345                neg_infs,
2346                nans,
2347                non_nulls,
2348            } => {
2349                let mut cx = numeric::cx_agg();
2350                let mut f = NumericAgg::from(factor.into_inner());
2351                // Unlike `plus_equals`, not necessary to reduce after this operation because `f` will
2352                // always be an integer, i.e. we are never increasing the
2353                // values' scale.
2354                cx.mul(&mut f, &accum.0);
2355                // `rounded` signals we have exceeded the aggregator's max
2356                // precision, which means we've lost commutativity and
2357                // associativity; nothing to be done here, so panic. For more
2358                // context, see the DEC_Rounded definition at
2359                // http://speleotrove.com/decimal/dncont.html
2360                assert!(!cx.status().rounded(), "Accum::Numeric multiply overflow");
2361                Accum::Numeric {
2362                    accum: OrderedNumericAgg(f),
2363                    pos_infs: pos_infs * factor,
2364                    neg_infs: neg_infs * factor,
2365                    nans: nans * factor,
2366                    non_nulls: non_nulls * factor,
2367                }
2368            }
2369        }
2370    }
2371}
2372
2373// The batcher stages updates in columnation chunks before they reach the arrangement,
2374// which stores `Accum` in its columnar form.
2375impl Columnation for Accum {
2376    type InnerRegion = CopyRegion<Self>;
2377}
2378
2379/// Monoids for in-place compaction of monotonic streams.
2380mod monoids {
2381
2382    // We can improve the performance of some aggregations through the use of algebra.
2383    // In particular, we can move some of the aggregations in to the `diff` field of
2384    // updates, by changing `diff` from integers to a different algebraic structure.
2385    //
2386    // The one we use is called a "semigroup", and it means that the structure has a
2387    // symmetric addition operator. The trait we use also allows the semigroup elements
2388    // to present as "zero", meaning they always act as the identity under +. Here,
2389    // `Datum::Null` acts as the identity under +, _but_ we don't want to make this
2390    // known to DD by the `is_zero` method, see comment there. So, from the point of view
2391    // of DD, this Semigroup should _not_ have a zero.
2392    //
2393    // WARNING: `Datum::Null` should continue to act as the identity of our + (even if we
2394    // add a new enum variant here), because other code (e.g., `HierarchicalOneByOneAggr`)
2395    // assumes this.
2396
2397    use columnation::{Columnation, Region};
2398    use differential_dataflow::difference::{IsZero, Multiply, Semigroup};
2399    use mz_expr::AggregateFunc;
2400    use mz_ore::soft_panic_or_log;
2401    use mz_repr::{Datum, Diff, Row};
2402    use serde::{Deserialize, Serialize};
2403
2404    /// A monoid containing a single-datum row.
2405    #[derive(Ord, PartialOrd, Eq, PartialEq, Debug, Serialize, Deserialize, Hash)]
2406    pub enum ReductionMonoid {
2407        Min(Row),
2408        Max(Row),
2409    }
2410
2411    impl ReductionMonoid {
2412        pub fn finalize(&self) -> &Row {
2413            use ReductionMonoid::*;
2414            match self {
2415                Min(row) | Max(row) => row,
2416            }
2417        }
2418    }
2419
2420    impl Clone for ReductionMonoid {
2421        fn clone(&self) -> Self {
2422            use ReductionMonoid::*;
2423            match self {
2424                Min(row) => Min(row.clone()),
2425                Max(row) => Max(row.clone()),
2426            }
2427        }
2428
2429        fn clone_from(&mut self, source: &Self) {
2430            use ReductionMonoid::*;
2431
2432            let mut row = std::mem::take(match self {
2433                Min(row) | Max(row) => row,
2434            });
2435
2436            let source_row = match source {
2437                Min(row) | Max(row) => row,
2438            };
2439
2440            row.clone_from(source_row);
2441
2442            match source {
2443                Min(_) => *self = Min(row),
2444                Max(_) => *self = Max(row),
2445            }
2446        }
2447    }
2448
2449    impl Multiply<Diff> for ReductionMonoid {
2450        type Output = Self;
2451
2452        fn multiply(self, factor: &Diff) -> Self {
2453            // Multiplication in ReductionMonoid is idempotent, and
2454            // its users must ascertain its monotonicity beforehand
2455            // (typically with ensure_monotonic) since it has no zero
2456            // value for us to use here.
2457            assert!(factor.is_positive());
2458            self
2459        }
2460    }
2461
2462    impl Semigroup for ReductionMonoid {
2463        fn plus_equals(&mut self, rhs: &Self) {
2464            match (self, rhs) {
2465                (ReductionMonoid::Min(lhs), ReductionMonoid::Min(rhs)) => {
2466                    let swap = {
2467                        let lhs_val = lhs.unpack_first();
2468                        let rhs_val = rhs.unpack_first();
2469                        // Datum::Null is the identity, not a small element.
2470                        match (lhs_val, rhs_val) {
2471                            (_, Datum::Null) => false,
2472                            (Datum::Null, _) => true,
2473                            (lhs, rhs) => rhs < lhs,
2474                        }
2475                    };
2476                    if swap {
2477                        lhs.clone_from(rhs);
2478                    }
2479                }
2480                (ReductionMonoid::Max(lhs), ReductionMonoid::Max(rhs)) => {
2481                    let swap = {
2482                        let lhs_val = lhs.unpack_first();
2483                        let rhs_val = rhs.unpack_first();
2484                        // Datum::Null is the identity, not a large element.
2485                        match (lhs_val, rhs_val) {
2486                            (_, Datum::Null) => false,
2487                            (Datum::Null, _) => true,
2488                            (lhs, rhs) => rhs > lhs,
2489                        }
2490                    };
2491                    if swap {
2492                        lhs.clone_from(rhs);
2493                    }
2494                }
2495                (lhs, rhs) => {
2496                    soft_panic_or_log!(
2497                        "Mismatched monoid variants in reduction! lhs: {lhs:?} rhs: {rhs:?}"
2498                    );
2499                }
2500            }
2501        }
2502    }
2503
2504    impl IsZero for ReductionMonoid {
2505        fn is_zero(&self) -> bool {
2506            // It totally looks like we could return true here for `Datum::Null`, but don't do this!
2507            // DD uses true results of this method to make stuff disappear. This makes sense when
2508            // diffs mean really just diffs, but for `ReductionMonoid` diffs hold reduction results.
2509            // We don't want funny stuff, like disappearing, happening to reduction results even
2510            // when they are null. (This would confuse, e.g., `ReduceCollation` for null inputs.)
2511            false
2512        }
2513    }
2514
2515    impl Columnation for ReductionMonoid {
2516        type InnerRegion = ReductionMonoidRegion;
2517    }
2518
2519    /// Region for [`ReductionMonoid`]. This region is special in that it stores both enum variants
2520    /// in the same backing region. Alternatively, it could store it in two regions, but we select
2521    /// the former for simplicity reasons.
2522    #[derive(Default)]
2523    pub struct ReductionMonoidRegion {
2524        inner: <Row as Columnation>::InnerRegion,
2525    }
2526
2527    impl Region for ReductionMonoidRegion {
2528        type Item = ReductionMonoid;
2529
2530        unsafe fn copy(&mut self, item: &Self::Item) -> Self::Item {
2531            use ReductionMonoid::*;
2532            match item {
2533                Min(row) => Min(unsafe { self.inner.copy(row) }),
2534                Max(row) => Max(unsafe { self.inner.copy(row) }),
2535            }
2536        }
2537
2538        fn clear(&mut self) {
2539            self.inner.clear();
2540        }
2541
2542        fn reserve_items<'a, I>(&mut self, items: I)
2543        where
2544            Self: 'a,
2545            I: Iterator<Item = &'a Self::Item> + Clone,
2546        {
2547            self.inner
2548                .reserve_items(items.map(ReductionMonoid::finalize));
2549        }
2550
2551        fn reserve_regions<'a, I>(&mut self, regions: I)
2552        where
2553            Self: 'a,
2554            I: Iterator<Item = &'a Self> + Clone,
2555        {
2556            self.inner.reserve_regions(regions.map(|r| &r.inner));
2557        }
2558
2559        fn heap_size(&self, callback: impl FnMut(usize, usize)) {
2560            self.inner.heap_size(callback);
2561        }
2562    }
2563
2564    /// Get the correct monoid implementation for a given aggregation function. Note that
2565    /// all hierarchical aggregation functions need to supply a monoid implementation.
2566    pub fn get_monoid(row: Row, func: &AggregateFunc) -> Option<ReductionMonoid> {
2567        match func {
2568            AggregateFunc::MaxNumeric
2569            | AggregateFunc::MaxInt16
2570            | AggregateFunc::MaxInt32
2571            | AggregateFunc::MaxInt64
2572            | AggregateFunc::MaxUInt16
2573            | AggregateFunc::MaxUInt32
2574            | AggregateFunc::MaxUInt64
2575            | AggregateFunc::MaxMzTimestamp
2576            | AggregateFunc::MaxFloat32
2577            | AggregateFunc::MaxFloat64
2578            | AggregateFunc::MaxBool
2579            | AggregateFunc::MaxString
2580            | AggregateFunc::MaxDate
2581            | AggregateFunc::MaxTimestamp
2582            | AggregateFunc::MaxTimestampTz
2583            | AggregateFunc::MaxInterval
2584            | AggregateFunc::MaxTime
2585            | AggregateFunc::MaxArray
2586            | AggregateFunc::MaxList => Some(ReductionMonoid::Max(row)),
2587            AggregateFunc::MinNumeric
2588            | AggregateFunc::MinInt16
2589            | AggregateFunc::MinInt32
2590            | AggregateFunc::MinInt64
2591            | AggregateFunc::MinUInt16
2592            | AggregateFunc::MinUInt32
2593            | AggregateFunc::MinUInt64
2594            | AggregateFunc::MinMzTimestamp
2595            | AggregateFunc::MinFloat32
2596            | AggregateFunc::MinFloat64
2597            | AggregateFunc::MinBool
2598            | AggregateFunc::MinString
2599            | AggregateFunc::MinDate
2600            | AggregateFunc::MinTimestamp
2601            | AggregateFunc::MinTimestampTz
2602            | AggregateFunc::MinInterval
2603            | AggregateFunc::MinTime
2604            | AggregateFunc::MinArray
2605            | AggregateFunc::MinList => Some(ReductionMonoid::Min(row)),
2606            AggregateFunc::SumInt16
2607            | AggregateFunc::SumInt32
2608            | AggregateFunc::SumInt64
2609            | AggregateFunc::SumUInt16
2610            | AggregateFunc::SumUInt32
2611            | AggregateFunc::SumUInt64
2612            | AggregateFunc::SumFloat32
2613            | AggregateFunc::SumFloat64
2614            | AggregateFunc::SumNumeric
2615            | AggregateFunc::SumInterval
2616            | AggregateFunc::Count
2617            | AggregateFunc::Any
2618            | AggregateFunc::All
2619            | AggregateFunc::Dummy
2620            | AggregateFunc::JsonbAgg { .. }
2621            | AggregateFunc::JsonbObjectAgg { .. }
2622            | AggregateFunc::MapAgg { .. }
2623            | AggregateFunc::ArrayConcat { .. }
2624            | AggregateFunc::ListConcat { .. }
2625            | AggregateFunc::StringAgg { .. }
2626            | AggregateFunc::RowNumber { .. }
2627            | AggregateFunc::Rank { .. }
2628            | AggregateFunc::DenseRank { .. }
2629            | AggregateFunc::LagLead { .. }
2630            | AggregateFunc::FirstValue { .. }
2631            | AggregateFunc::LastValue { .. }
2632            | AggregateFunc::WindowAggregate { .. }
2633            | AggregateFunc::FusedValueWindowFunc { .. }
2634            | AggregateFunc::FusedWindowAggregate { .. } => None,
2635        }
2636    }
2637}
2638
2639mod window_agg_helpers {
2640    use crate::render::reduce::*;
2641
2642    /// TODO: It would be better for performance to do the branching that is in the methods of this
2643    /// enum at the place where we are calling `eval_fast_window_agg`. Then we wouldn't need an enum
2644    /// here, and would parameterize `eval_fast_window_agg` with one of the implementations
2645    /// directly.
2646    pub enum OneByOneAggrImpls {
2647        Accumulable(AccumulableOneByOneAggr),
2648        Hierarchical(HierarchicalOneByOneAggr),
2649        Basic(mz_expr::NaiveOneByOneAggr),
2650    }
2651
2652    impl mz_expr::OneByOneAggr for OneByOneAggrImpls {
2653        fn new(agg: &AggregateFunc, reverse: bool) -> Self {
2654            match reduction_type(agg) {
2655                ReductionType::Basic => {
2656                    OneByOneAggrImpls::Basic(mz_expr::NaiveOneByOneAggr::new(agg, reverse))
2657                }
2658                ReductionType::Accumulable => {
2659                    OneByOneAggrImpls::Accumulable(AccumulableOneByOneAggr::new(agg))
2660                }
2661                ReductionType::Hierarchical => {
2662                    OneByOneAggrImpls::Hierarchical(HierarchicalOneByOneAggr::new(agg))
2663                }
2664            }
2665        }
2666
2667        fn give(&mut self, d: &Datum) {
2668            match self {
2669                OneByOneAggrImpls::Basic(i) => i.give(d),
2670                OneByOneAggrImpls::Accumulable(i) => i.give(d),
2671                OneByOneAggrImpls::Hierarchical(i) => i.give(d),
2672            }
2673        }
2674
2675        fn get_current_aggregate<'a>(&self, temp_storage: &'a RowArena) -> Datum<'a> {
2676            // Note that the `reverse` parameter is currently forwarded only for Basic aggregations.
2677            match self {
2678                OneByOneAggrImpls::Basic(i) => i.get_current_aggregate(temp_storage),
2679                OneByOneAggrImpls::Accumulable(i) => i.get_current_aggregate(temp_storage),
2680                OneByOneAggrImpls::Hierarchical(i) => i.get_current_aggregate(temp_storage),
2681            }
2682        }
2683    }
2684
2685    pub struct AccumulableOneByOneAggr {
2686        aggr_func: AggregateFunc,
2687        accum: Accum,
2688        total: Diff,
2689    }
2690
2691    impl AccumulableOneByOneAggr {
2692        fn new(aggr_func: &AggregateFunc) -> Self {
2693            AccumulableOneByOneAggr {
2694                aggr_func: aggr_func.clone(),
2695                accum: accumulable_zero(aggr_func),
2696                total: Diff::ZERO,
2697            }
2698        }
2699
2700        fn give(&mut self, d: &Datum) {
2701            self.accum
2702                .plus_equals(&datum_to_accumulator(&self.aggr_func, d.clone()));
2703            self.total += Diff::ONE;
2704        }
2705
2706        fn get_current_aggregate<'a>(&self, temp_storage: &'a RowArena) -> Datum<'a> {
2707            temp_storage.make_datum(|packer| {
2708                packer.push(finalize_accum(&self.aggr_func, &self.accum, self.total));
2709            })
2710        }
2711    }
2712
2713    pub struct HierarchicalOneByOneAggr {
2714        aggr_func: AggregateFunc,
2715        // Warning: We are assuming that `Datum::Null` acts as the identity for `ReductionMonoid`'s
2716        // `plus_equals`. (But _not_ relying here on `ReductionMonoid::is_zero`.)
2717        monoid: ReductionMonoid,
2718    }
2719
2720    impl HierarchicalOneByOneAggr {
2721        fn new(aggr_func: &AggregateFunc) -> Self {
2722            let mut row_buf = Row::default();
2723            row_buf.packer().push(Datum::Null);
2724            HierarchicalOneByOneAggr {
2725                aggr_func: aggr_func.clone(),
2726                monoid: get_monoid(row_buf, aggr_func)
2727                    .expect("aggr_func should be a hierarchical aggregation function"),
2728            }
2729        }
2730
2731        fn give(&mut self, d: &Datum) {
2732            let mut row_buf = Row::default();
2733            row_buf.packer().push(d);
2734            let m = get_monoid(row_buf, &self.aggr_func)
2735                .expect("aggr_func should be a hierarchical aggregation function");
2736            self.monoid.plus_equals(&m);
2737        }
2738
2739        fn get_current_aggregate<'a>(&self, temp_storage: &'a RowArena) -> Datum<'a> {
2740            temp_storage.make_datum(|packer| packer.extend(self.monoid.finalize().iter()))
2741        }
2742    }
2743}
2744
2745#[cfg(test)]
2746mod tests {
2747    use super::*;
2748
2749    /// The saturating conversion that `float_to_fixed_point` replaces. Used to
2750    /// assert that the new wrapping conversion agrees on the in-range values
2751    /// where the old conversion was already correct.
2752    #[allow(clippy::as_conversions)]
2753    fn saturating_convert(n: f64) -> i128 {
2754        (n * FLOAT_SCALE) as i128
2755    }
2756
2757    #[mz_ore::test]
2758    fn float_to_fixed_point_matches_saturating_in_range() {
2759        // For values whose scaled magnitude comfortably fits in an `i128`, the
2760        // wrapping conversion must produce exactly the same result the previous
2761        // saturating cast did.
2762        let cases = [
2763            0.0,
2764            -0.0,
2765            1.0,
2766            -1.0,
2767            0.1,
2768            -0.1,
2769            0.5,
2770            -0.5,
2771            3.25,
2772            -3.25,
2773            123456.789,
2774            -123456.789,
2775            1e10,
2776            -1e10,
2777            1e20,
2778            -1e20,
2779            5e30, // large, but scaled magnitude still fits comfortably in i128
2780            -5e30,
2781        ];
2782        for n in cases {
2783            assert_eq!(
2784                float_to_fixed_point(n),
2785                saturating_convert(n),
2786                "mismatch for n = {n}"
2787            );
2788        }
2789    }
2790
2791    #[mz_ore::test]
2792    fn float_to_fixed_point_truncates_toward_zero() {
2793        // 1.75 * 2^24 = 29360128, exactly representable.
2794        assert_eq!(float_to_fixed_point(1.75), 29_360_128);
2795        assert_eq!(float_to_fixed_point(-1.75), -29_360_128);
2796
2797        // Fractional results truncate toward zero, matching the previous cast.
2798        let frac = 0.123_456_7_f64;
2799        assert_eq!(float_to_fixed_point(frac), saturating_convert(frac));
2800        assert_eq!(float_to_fixed_point(-frac), saturating_convert(-frac));
2801        assert_eq!(float_to_fixed_point(-frac), -float_to_fixed_point(frac));
2802    }
2803
2804    #[mz_ore::test]
2805    fn float_to_fixed_point_subnormals_round_to_zero() {
2806        assert_eq!(float_to_fixed_point(0.0), 0);
2807        assert_eq!(float_to_fixed_point(-0.0), 0);
2808        assert_eq!(float_to_fixed_point(f64::MIN_POSITIVE / 2.0), 0);
2809        assert_eq!(float_to_fixed_point(5e-324), 0); // smallest subnormal
2810    }
2811
2812    #[mz_ore::test]
2813    fn float_to_fixed_point_cancels_large_finite_values() {
2814        // Regression test for database-issues#11265: large finite values that
2815        // individually overflow the fixed-point domain must still sum to the
2816        // correct result when their mathematical sum is representable. The
2817        // previous saturating conversion produced `i128::MAX + i128::MIN == -1`.
2818        for &n in &[1.1e31_f64, 1e32, 5e33, 1e284] {
2819            assert_eq!(
2820                float_to_fixed_point(n).wrapping_add(float_to_fixed_point(-n)),
2821                0,
2822                "n = {n} did not cancel with -n"
2823            );
2824        }
2825    }
2826
2827    #[mz_ore::test]
2828    fn float_to_fixed_point_sum_via_accumulator() {
2829        // Exercise the full accumulate-then-finalize path for the reported case.
2830        let func = AggregateFunc::SumFloat64;
2831        let mut acc = accumulable_zero(&func);
2832        acc.plus_equals(&datum_to_accumulator(&func, Datum::from(1.1e31_f64)));
2833        acc.plus_equals(&datum_to_accumulator(&func, Datum::from(-1.1e31_f64)));
2834        let datum = finalize_accum(&func, &acc, Diff::from(2_i64));
2835        assert_eq!(datum, Datum::from(0.0_f64));
2836    }
2837
2838    /// Accumulators of every variant, in zero, accumulated, and negated states.
2839    fn sample_accums() -> Vec<Accum> {
2840        let mut cx = numeric::cx_datum();
2841        let mut numeric = |s: &str| Datum::from(cx.parse(s).unwrap());
2842        let cases: Vec<(AggregateFunc, Vec<Datum>)> = vec![
2843            (AggregateFunc::Count, vec![Datum::Null, Datum::Int64(5)]),
2844            (
2845                AggregateFunc::SumInt64,
2846                vec![Datum::Int64(-7), Datum::Int64(i64::MAX)],
2847            ),
2848            (
2849                AggregateFunc::SumUInt16,
2850                vec![Datum::UInt16(3), Datum::Null],
2851            ),
2852            (
2853                AggregateFunc::Any,
2854                vec![Datum::True, Datum::False, Datum::Null],
2855            ),
2856            (
2857                AggregateFunc::SumFloat64,
2858                vec![
2859                    Datum::from(1.5_f64),
2860                    Datum::from(f64::NAN),
2861                    Datum::from(f64::NEG_INFINITY),
2862                ],
2863            ),
2864            (
2865                AggregateFunc::SumNumeric,
2866                vec![
2867                    numeric("-12345.678"),
2868                    numeric("9e39"),
2869                    numeric("NaN"),
2870                    numeric("Infinity"),
2871                    Datum::Null,
2872                ],
2873            ),
2874            (
2875                AggregateFunc::SumInterval,
2876                vec![
2877                    Datum::Interval(Interval::new(-13, 40, 1_234_567)),
2878                    Datum::Interval(Interval::new(i32::MAX, i32::MIN, i64::MAX)),
2879                    Datum::Null,
2880                ],
2881            ),
2882        ];
2883        let mut accums = Vec::new();
2884        for (func, datums) in cases {
2885            let mut sum = accumulable_zero(&func);
2886            accums.push(sum);
2887            for datum in datums {
2888                let accum = datum_to_accumulator(&func, datum);
2889                sum.plus_equals(&accum);
2890                accums.push(accum);
2891                accums.push(accum.multiply(&Diff::from(-1_i64)));
2892            }
2893            accums.push(sum);
2894        }
2895        accums
2896    }
2897
2898    #[mz_ore::test]
2899    fn accum_columnar_round_trip() {
2900        use columnar::bytes::indexed::{DecodedStore, encode};
2901        use columnar::{AsBytes, Borrow, BorrowedOf, FromBytes, Index, Len};
2902        use differential_dataflow::trace::implementations::BatchContainer;
2903
2904        let accums = sample_accums();
2905        let container = Accum::as_columns(accums.iter());
2906        assert_eq!(container.len(), accums.len());
2907        let borrowed = container.borrow();
2908        for (index, accum) in accums.iter().enumerate() {
2909            assert_eq!(Accum::into_owned(borrowed.get(index)), *accum);
2910        }
2911        for (i, a) in accums.iter().enumerate() {
2912            for (j, b) in accums.iter().enumerate() {
2913                assert_eq!(borrowed.get(i).cmp(&borrowed.get(j)), a.cmp(b));
2914            }
2915        }
2916
2917        let bytes: Vec<&[u8]> = borrowed.as_bytes().map(|(_align, bytes)| bytes).collect();
2918        let decoded = BorrowedOf::<Accum>::from_bytes(&mut bytes.into_iter());
2919        for (index, accum) in accums.iter().enumerate() {
2920            assert_eq!(Accum::into_owned(decoded.get(index)), *accum);
2921        }
2922        // NOTE: the `i128` columns cannot be `validate`d, see the `Overflowing<i128>` test in
2923        // `mz_ore`, so this only decodes.
2924        let mut words = Vec::new();
2925        encode(&mut words, &borrowed);
2926        let decoded = BorrowedOf::<Accum>::from_store(&DecodedStore::new(&words), &mut 0);
2927        for (index, accum) in accums.iter().enumerate() {
2928            assert_eq!(Accum::into_owned(decoded.get(index)), *accum);
2929        }
2930
2931        // The arrangement's diff container, holding whole `(Vec<Accum>, Diff)` diffs.
2932        let diffs: Vec<(Vec<Accum>, Diff)> = accums
2933            .chunks(3)
2934            .map(|chunk| (chunk.to_vec(), Diff::ONE))
2935            .collect();
2936        let mut coltainer = Coltainer::<(Vec<Accum>, Diff)>::default();
2937        for diff in &diffs {
2938            coltainer.push_own(diff);
2939        }
2940        assert_eq!(coltainer.len(), diffs.len());
2941        for (index, diff) in diffs.iter().enumerate() {
2942            assert_eq!(
2943                <Coltainer<(Vec<Accum>, Diff)>>::into_owned(coltainer.index(index)),
2944                *diff
2945            );
2946        }
2947        let mut sum = <Coltainer<(Vec<Accum>, Diff)>>::into_owned(coltainer.index(0));
2948        sum.plus_equals(&sum.clone().multiply(&Diff::from(-1_i64)));
2949        assert!(sum.is_zero());
2950    }
2951}