datafusion-match-recognize 0.56.1

SQL MATCH_RECOGNIZE row-pattern matching for Apache DataFusion
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
// Licensed under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.

//! A selected winner accumulates into one nullable primitive carry per measure.
//! Finished Arrow arrays adopt the admitted output vectors at flush.

use std::cmp::Ordering;

use super::*;
use crate::execution::common::decimal::DecimalAverager;
use crate::execution::matching::{
    ExecutableReduction, SelectedReductionOp as Op, WinningValue,
};
use crate::execution::storage::bound_columns::decode_decimal128_to_f64_bits;
use datafusion::arrow::array::{AsArray, Float64Array, PrimitiveArray};
use datafusion::arrow::buffer::{BooleanBuffer, Buffer, NullBuffer};
use datafusion::arrow::datatypes::{
    ArrowNativeTypeOp, ArrowPrimitiveType, DataType, Decimal128Type, FieldRef,
    Float32Type, Float64Type, Int32Type, Int64Type, Schema,
};
#[cfg(test)]
use datafusion::common::ScalarValue;
use datafusion::logical_expr::{EmitTo, function::AccumulatorArgs};

struct PrimitiveValues<T: ArrowPrimitiveType> {
    carry: Option<T::Native>,
    values: Vec<T::Native>,
    validity: Vec<u8>,
    memory: MemoryReservation,
}

impl<T: ArrowPrimitiveType> PrimitiveValues<T> {
    fn new(memory: &MemoryReservation) -> Self {
        Self {
            carry: None,
            values: Vec::new(),
            validity: Vec::new(),
            memory: memory.new_empty(),
        }
    }

    fn release(&mut self) {
        self.values = Vec::new();
        self.validity = Vec::new();
        self.memory.free();
    }

    fn take_array(&mut self, dtype: &DataType) -> ArrayRef {
        let values = std::mem::take(&mut self.values);
        let nulls = (!self.validity.is_empty()).then(|| {
            NullBuffer::new(BooleanBuffer::new(
                Buffer::from_vec(std::mem::take(&mut self.validity)),
                0,
                values.len(),
            ))
        });
        Arc::new(
            PrimitiveArray::<T>::new(values.into(), nulls).with_data_type(dtype.clone()),
        )
    }

    fn len(&self) -> usize {
        self.values.len()
    }

    fn reserve_result(&mut self) -> Result<()> {
        if self.values.len() == self.values.capacity() {
            try_reserve_accounted(
                &mut self.values,
                &self.memory,
                1,
                "primitive summary values",
            )?;
        }
        if self.carry.is_none() || !self.validity.is_empty() {
            self.reserve_validity(self.values.len() + 1)?;
        }
        Ok(())
    }

    fn push_reserved(&mut self) {
        let i = self.values.len();
        debug_assert!(i < self.values.capacity());
        if self.carry.is_none() {
            self.validity[i / 8] &= !(1 << (i % 8));
        }
        self.values.push(self.carry.unwrap_or(T::Native::ZERO));
    }

    fn reserve_validity(&mut self, upto: usize) -> Result<()> {
        let needed = upto.div_ceil(8);
        if self.validity.len() < needed {
            let additional = needed - self.validity.len();
            try_reserve_accounted(
                &mut self.validity,
                &self.memory,
                additional,
                "primitive summary validity",
            )?;
            self.validity.resize(needed, u8::MAX);
        }
        Ok(())
    }
}

pub(super) struct ReductionColumns {
    pub(super) slots: Vec<Option<ReductionColumn>>,
}

impl ReductionColumns {
    pub(super) fn new(
        summaries: &[ExecutableDirectCountSummary],
        memory: &mut MemoryReservation,
    ) -> Result<Option<Self>> {
        if !summaries.iter().any(|s| s.reduction().is_some()) {
            return Ok(None);
        }
        let mut slots = Vec::new();
        try_reserve_accounted(
            &mut slots,
            memory,
            summaries.len(),
            "selected reduction columns",
        )?;
        Ok(Some(Self { slots }))
    }
}

enum PrimitiveResult {
    Int32(PrimitiveValues<Int32Type>),
    Int64(PrimitiveValues<Int64Type>),
    Float64(PrimitiveValues<Float64Type>),
    Decimal128(PrimitiveValues<Decimal128Type>),
}

macro_rules! primitive {
    ($value:expr, $col:ident, $body:expr) => {
        match $value {
            PrimitiveResult::Int32($col) => $body,
            PrimitiveResult::Int64($col) => $body,
            PrimitiveResult::Float64($col) => $body,
            PrimitiveResult::Decimal128($col) => $body,
        }
    };
}

pub(super) struct ReductionColumn {
    result: PrimitiveResult,
    non_null: u64,
    finalized: bool,
}

impl ReductionColumn {
    pub(super) fn new(
        spec: &ExecutableReduction,
        memory: &MemoryReservation,
    ) -> Result<Self> {
        let result = match spec.output_type {
            DataType::Int32 => PrimitiveResult::Int32(PrimitiveValues::new(memory)),
            DataType::Int64 => PrimitiveResult::Int64(PrimitiveValues::new(memory)),
            DataType::Float64 => PrimitiveResult::Float64(PrimitiveValues::new(memory)),
            DataType::Decimal128(..) => {
                PrimitiveResult::Decimal128(PrimitiveValues::new(memory))
            }
            ref other => {
                return internal_err!("unsupported selected reduction output {other}");
            }
        };
        let mut col = Self {
            result,
            non_null: 0,
            finalized: false,
        };
        col.reset(spec.op);
        Ok(col)
    }

    fn reset(&mut self, op: Op) {
        primitive!(&mut self.result, col, col.carry = None);
        if let (Op::Count, PrimitiveResult::Int64(col)) = (op, &mut self.result) {
            col.carry = Some(0);
        }
        self.non_null = 0;
        self.finalized = false;
    }

    fn update(
        &mut self,
        field: &ExecutableDirectCountSummary,
        source: &ArrayRef,
        first: usize,
        rows: usize,
        memory: &MemoryReservation,
    ) -> Result<()> {
        let spec = field.reduction().expect("bound reduction");
        if self.finalized
            || source.data_type() != &spec.input_type
            || first.checked_add(rows).is_none_or(|end| end > source.len())
        {
            return internal_err!("invalid selected reduction span");
        }
        let range = first..first + rows;
        let op = spec.op;
        match (op, &mut self.result, source.data_type()) {
            (Op::Count, PrimitiveResult::Int64(col), _) => {
                // Admitted columns have physical validity. Count bits without copying.
                let valid = source.nulls().map_or(rows, |n| {
                    n.inner()
                        .inner()
                        .count_set_bits_offset(n.offset() + first, rows)
                });
                col.carry = Some(
                    col.carry
                        .unwrap_or(0)
                        .checked_add(valid as i64)
                        .ok_or_else(|| {
                            DataFusionError::ResourcesExhausted(
                                "selected COUNT exceeds Int64".into(),
                            )
                        })?,
                );
            }
            (_, PrimitiveResult::Int64(col), DataType::Int32) => fold(
                col,
                op,
                source.as_primitive::<Int32Type>(),
                range,
                i64::from,
            ),
            (_, PrimitiveResult::Int64(col), DataType::Int64) => {
                fold(col, op, source.as_primitive::<Int64Type>(), range, |v| v)
            }
            (_, PrimitiveResult::Int32(col), DataType::Int32) => {
                fold(col, op, source.as_primitive::<Int32Type>(), range, |v| v)
            }
            (Op::Min | Op::Max, PrimitiveResult::Float64(col), source_ty) => {
                match source_ty {
                    DataType::Float64 => {
                        fold(col, op, source.as_primitive::<Float64Type>(), range, |v| v)
                    }
                    DataType::Float32 => fold(
                        col,
                        op,
                        source.as_primitive::<Float32Type>(),
                        range,
                        f64::from,
                    ),
                    DataType::Int32 => fold(
                        col,
                        op,
                        source.as_primitive::<Int32Type>(),
                        range,
                        f64::from,
                    ),
                    DataType::Int64 => {
                        fold(col, op, source.as_primitive::<Int64Type>(), range, |v| {
                            v as f64
                        })
                    }
                    DataType::Decimal128(_, scale) => fold(
                        col,
                        op,
                        source.as_primitive::<Decimal128Type>(),
                        range,
                        |v| f64::from_bits(decode_decimal128_to_f64_bits(v, *scale)),
                    ),
                    _ => {
                        return internal_err!(
                            "invalid selected Float64 reduction source"
                        );
                    }
                }
            }
            (Op::Avg | Op::Sum, PrimitiveResult::Float64(col), _) => {
                // Fast finite-only path for exact integer and Decimal128 sources:
                // converted values are strictly finite and bounded well below
                // f64::MAX, so IEEE addition cannot synthesize NaN or +/-inf.
                match source.data_type() {
                    DataType::Int32 => {
                        let accepted = sum_finite_float64(
                            col,
                            source.as_primitive::<Int32Type>(),
                            range,
                            f64::from,
                        );
                        self.non_null += accepted;
                    }
                    DataType::Int64 => {
                        let accepted = sum_finite_float64(
                            col,
                            source.as_primitive::<Int64Type>(),
                            range,
                            |v| v as f64,
                        );
                        self.non_null += accepted;
                    }
                    DataType::Decimal128(_, scale) => {
                        let accepted = sum_finite_float64(
                            col,
                            source.as_primitive::<Decimal128Type>(),
                            range,
                            |v| f64::from_bits(decode_decimal128_to_f64_bits(v, *scale)),
                        );
                        self.non_null += accepted;
                    }
                    _ => {
                        // Denial while evaluating a non-finite pair leaves the whole
                        // input span available for a retry at the same cursor.
                        let mut carry = col.carry;
                        let mut accepted = 0;
                        let mut add = |value: f64| -> Result<()> {
                            let previous = carry.unwrap_or(0.0);
                            let sum = previous + value;
                            // A single NaN supplies the only payload. Equal payloads
                            // also agree after IEEE quieting. With infinity and finite
                            // values the host add produces the ordinary signed infinity.
                            let ambiguous = sum.is_nan()
                                && ((previous.is_nan()
                                    && value.is_nan()
                                    && (previous.to_bits() | (1 << 51))
                                        != (value.to_bits() | (1 << 51)))
                                    || (previous.is_infinite() && value.is_infinite()));
                            carry = Some(if ambiguous {
                                exceptional_float_add(
                                    op,
                                    previous,
                                    value,
                                    field.field().arrow_field(),
                                    memory,
                                )?
                            } else {
                                sum
                            });
                            accepted += 1;
                            Ok(())
                        };
                        match source.data_type() {
                            DataType::Float64 => visit_valid(
                                source.as_primitive::<Float64Type>(),
                                range,
                                &mut add,
                            )?,
                            DataType::Float32 => visit_valid(
                                source.as_primitive::<Float32Type>(),
                                range,
                                |v| add(f64::from(v)),
                            )?,
                            _ => {
                                return internal_err!(
                                    "invalid selected Float64 reduction source"
                                );
                            }
                        }
                        col.carry = carry;
                        self.non_null += accepted;
                    }
                }
            }
            (_, PrimitiveResult::Decimal128(col), DataType::Decimal128(..)) => {
                let input = source.as_primitive::<Decimal128Type>();
                if op == Op::Avg {
                    visit_valid(input, range, |value| {
                        col.carry = Some(col.carry.unwrap_or(0).wrapping_add(value));
                        self.non_null += 1;
                        Ok(())
                    })?;
                } else {
                    fold(col, op, input, range, |v| v);
                }
            }
            _ => return internal_err!("incompatible selected reduction types"),
        }
        Ok(())
    }

    fn set(&mut self, spec: &ExecutableReduction, value: WinningValue) -> Result<()> {
        match (&mut self.result, value) {
            (PrimitiveResult::Int32(col), WinningValue::Int32(v)) => col.carry = v,
            (PrimitiveResult::Int64(col), WinningValue::Int64(v))
                if v.is_some() || spec.op != Op::Count =>
            {
                col.carry = v
            }
            (PrimitiveResult::Float64(col), WinningValue::Float64(v)) => col.carry = v,
            (PrimitiveResult::Decimal128(col), WinningValue::Decimal128(v)) => {
                col.carry = v
            }
            _ => return internal_err!("invalid forwarded selected aggregate"),
        }
        self.finalized = true;
        Ok(())
    }

    pub(super) fn reserve(&mut self, spec: &ExecutableReduction) -> Result<()> {
        if !self.finalized && spec.op == Op::Avg && self.non_null != 0 {
            match (&mut self.result, &spec.input_type, &spec.output_type) {
                (PrimitiveResult::Float64(col), _, _) => {
                    col.carry = col.carry.map(|sum| sum / self.non_null as f64)
                }
                (
                    PrimitiveResult::Decimal128(col),
                    DataType::Decimal128(_, scale),
                    DataType::Decimal128(p, s),
                ) => {
                    let avg = DecimalAverager::<Decimal128Type>::try_new(*scale, *p, *s)?;
                    col.carry = col
                        .carry
                        .map(|sum| avg.avg(sum, i128::from(self.non_null)))
                        .transpose()?;
                }
                _ => return internal_err!("invalid selected AVG result"),
            }
        }
        // Keep the finalized carry through a capacity denial and retry.
        self.finalized = true;
        primitive!(&mut self.result, col, col.reserve_result())
    }

    pub(super) fn append_reserved(&mut self, op: Op) {
        debug_assert!(self.finalized);
        primitive!(&mut self.result, col, col.push_reserved());
        self.reset(op);
    }

    pub(super) fn len(&self) -> usize {
        primitive!(&self.result, col, col.len())
    }

    pub(super) fn prepare_array(
        &mut self,
        dtype: &DataType,
        memory: &MemoryReservation,
    ) -> Result<ArrayRef> {
        // The existing value and validity leases cover the adopted vectors until
        // the complete batch has been validated. All primitive headers have
        // the same layout regardless of their native value width.
        memory.try_grow(size_of::<Float64Array>() + 2 * size_of::<usize>())?;
        Ok(primitive!(&mut self.result, col, col.take_array(dtype)))
    }

    pub(super) fn release(&mut self) {
        primitive!(&mut self.result, col, col.release());
    }
}

fn visit_valid<T: ArrowPrimitiveType>(
    input: &PrimitiveArray<T>,
    range: std::ops::Range<usize>,
    mut f: impl FnMut(T::Native) -> Result<()>,
) -> Result<()> {
    let values = &input.values()[range.clone()];
    match input.nulls() {
        None => {
            for v in values {
                f(*v)?;
            }
        }
        Some(nulls) => {
            for (offset, v) in values.iter().enumerate() {
                if nulls.is_valid(range.start + offset) {
                    f(*v)?;
                }
            }
        }
    }
    Ok(())
}

fn sum_finite_float64<I: ArrowPrimitiveType>(
    out: &mut PrimitiveValues<Float64Type>,
    input: &PrimitiveArray<I>,
    range: std::ops::Range<usize>,
    convert: impl Fn(I::Native) -> f64,
) -> u64 {
    let values = &input.values()[range.clone()];
    if values.is_empty() {
        return 0;
    }
    let mut sum = out.carry.unwrap_or(0.0);
    let accepted = match input.nulls() {
        None => {
            for &raw in values {
                sum += convert(raw);
            }
            values.len() as u64
        }
        Some(nulls) => {
            let mut count = 0u64;
            for (offset, &raw) in values.iter().enumerate() {
                if nulls.is_valid(range.start + offset) {
                    sum += convert(raw);
                    count += 1;
                }
            }
            count
        }
    };
    if accepted != 0 {
        out.carry = Some(sum);
    }
    accepted
}

fn fold<T: ArrowPrimitiveType, I: ArrowPrimitiveType>(
    out: &mut PrimitiveValues<T>,
    op: Op,
    input: &PrimitiveArray<I>,
    range: std::ops::Range<usize>,
    convert: impl Fn(I::Native) -> T::Native,
) {
    let values = &input.values()[range.clone()];
    if values.is_empty() {
        return;
    }
    match (op, input.nulls()) {
        (Op::Sum, None) => {
            let mut acc = out.carry.unwrap_or(T::Native::ZERO);
            for &raw in values {
                acc = acc.add_wrapping(convert(raw));
            }
            out.carry = Some(acc);
        }
        (Op::Sum, Some(nulls)) => {
            let mut acc = out.carry.unwrap_or(T::Native::ZERO);
            let mut any = out.carry.is_some();
            for (offset, &raw) in values.iter().enumerate() {
                if nulls.is_valid(range.start + offset) {
                    acc = acc.add_wrapping(convert(raw));
                    any = true;
                }
            }
            if any {
                out.carry = Some(acc);
            }
        }
        (Op::Min | Op::Max, None) => {
            let ordering = if op == Op::Min {
                Ordering::Less
            } else {
                Ordering::Greater
            };
            let mut acc = out.carry.unwrap_or_else(|| convert(values[0]));
            for &raw in values {
                let v = convert(raw);
                if v.compare(acc) == ordering {
                    acc = v;
                }
            }
            out.carry = Some(acc);
        }
        (Op::Min | Op::Max, Some(nulls)) => {
            let ordering = if op == Op::Min {
                Ordering::Less
            } else {
                Ordering::Greater
            };
            let mut carry = out.carry;
            for (offset, &raw) in values.iter().enumerate() {
                if nulls.is_valid(range.start + offset) {
                    let v = convert(raw);
                    carry = Some(match carry {
                        Some(prior) if v.compare(prior) != ordering => prior,
                        _ => v,
                    });
                }
            }
            out.carry = carry;
        }
        (Op::Count | Op::Avg, _) => {
            unreachable!("fold only handles Sum, Min, and Max")
        }
    }
}

// LLVM can choose which input NaN payload an add returns. Evaluate the
// exceptional pair with the installed grouped operator's own addition.
// Only two Float64 values and one group are ever live here.
#[cold]
fn exceptional_float_add(
    op: Op,
    previous: f64,
    value: f64,
    field: FieldRef,
    memory: &MemoryReservation,
) -> Result<f64> {
    use datafusion::functions_aggregate::{average::avg_udaf, sum::sum_udaf};
    let scratch = memory.new_empty();
    // One accumulator object and its single-group state, two input scalars,
    // two state arrays (count and sum for AVG), their bitmaps and Arc headers.
    scratch.try_grow(2048)?;
    let udf = if op == Op::Avg {
        avg_udaf()
    } else {
        sum_udaf()
    };
    let mut acc = udf.create_groups_accumulator(AccumulatorArgs {
        return_field: Arc::clone(&field),
        schema: &Schema::empty(),
        ignore_nulls: false,
        order_bys: &[],
        is_reversed: false,
        name: "selected",
        is_distinct: false,
        exprs: &[],
        expr_fields: std::slice::from_ref(&field),
    })?;
    let pair: ArrayRef = Arc::new(Float64Array::from(vec![previous, value]));
    acc.update_batch(&[pair], &[0, 0], None, 1)?;
    let sums = if op == Op::Avg {
        acc.state(EmitTo::All)?.pop().expect("AVG sum state")
    } else {
        acc.evaluate(EmitTo::All)?
    };
    Ok(sums.as_primitive::<Float64Type>().value(0))
}

impl SummaryOutputStorage {
    fn reduction_mut(
        &mut self,
        index: usize,
    ) -> Result<(&ExecutableDirectCountSummary, &mut ReductionColumn)> {
        if let Self::DirectCounts {
            summaries,
            reductions: Some(reductions),
            ..
        } = self
            && let Some(slot) = reductions.slots.get_mut(index).and_then(Option::as_mut)
        {
            return Ok((&summaries[index], slot));
        }
        internal_err!("selected output {index} is not a bound reduction")
    }
}

impl OutputBatchBuilder {
    pub(in crate::execution::storage) fn update_reduction(
        &mut self,
        index: usize,
        source: &ArrayRef,
        first: usize,
        rows: usize,
    ) -> Result<()> {
        let (summary, slot) = self.summary_output.reduction_mut(index)?;
        slot.update(summary, source, first, rows, &self.memory)
    }

    pub(in crate::execution::storage) fn reset_reductions(&mut self) {
        if let SummaryOutputStorage::DirectCounts {
            summaries,
            reductions: Some(reductions),
            ..
        } = &mut self.summary_output
        {
            for (slot, summary) in reductions.slots.iter_mut().zip(summaries.iter()) {
                if let Some(slot) = slot {
                    slot.reset(summary.reduction().expect("bound reduction").op);
                }
            }
        }
    }

    pub(in crate::execution::storage) fn set_reduction(
        &mut self,
        index: usize,
        value: WinningValue,
    ) -> Result<()> {
        let (summary, slot) = self.summary_output.reduction_mut(index)?;
        slot.set(summary.reduction().expect("bound reduction"), value)
    }
}

#[cfg(test)]
mod tests;

#[cfg(test)]
#[test]
fn selected_decimal_float64_reductions_match_arrow_cast_bits() -> Result<()> {
    use crate::core::MatchSummaryField;
    use crate::execution::common::memory::new_unbounded_state_memory;
    use datafusion::arrow::array::Decimal128Array;
    use datafusion::arrow::compute::cast;
    use datafusion::arrow::datatypes::Field;

    for scale in [2, -5, -23, 23, 25] {
        for magnitude in [
            17_i128,
            (1_i128 << 53) + 1,
            (1_i128 << 53) + 3,
            12_345_678_901_234_567_890_123_456_789_012_345_678,
        ] {
            for raw in [magnitude, -magnitude] {
                for nullable in [false, true] {
                    let values = if nullable {
                        vec![None, Some(raw), None]
                    } else {
                        vec![Some(raw)]
                    };
                    let source: ArrayRef = Arc::new(
                        Decimal128Array::from(values)
                            .with_precision_and_scale(38, scale)?,
                    );
                    let casted = cast(&source, &DataType::Float64)?;
                    let expected = casted
                        .as_primitive::<Float64Type>()
                        .value(usize::from(nullable))
                        .to_bits();
                    for op in [Op::Sum, Op::Avg, Op::Min, Op::Max] {
                        let summary = ExecutableDirectCountSummary::new_reduction(
                            MatchSummaryField::new(
                                0,
                                Arc::new(Field::new("v", DataType::Float64, true)),
                            ),
                            None,
                            ExecutableReduction {
                                op,
                                input_column: 0,
                                input_type: source.data_type().clone(),
                                output_type: DataType::Float64,
                                managed_aggregate: None,
                            },
                        );
                        let spec = summary.reduction().unwrap();
                        let memory = new_unbounded_state_memory();
                        let mut column = ReductionColumn::new(spec, &memory)?;
                        // NULL-only spans must not disturb the single converted value.
                        for row in 0..source.len() {
                            column.update(&summary, &source, row, 1, &memory)?;
                        }
                        column.reserve(spec)?;
                        let PrimitiveResult::Float64(result) = &column.result else {
                            panic!("expected Float64 reduction");
                        };
                        assert_eq!(
                            result.carry.unwrap().to_bits(),
                            expected,
                            "{op:?}, raw={raw}, scale={scale}, nullable={nullable}"
                        );
                    }
                }
            }
        }
    }
    Ok(())
}