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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
// 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.

//! Reusable Arrow output construction, gathering, and finalization.

use std::sync::Arc;

use crate::core::{AbsoluteRow, MatchMetadataColumn};
use crate::execution::storage::PendingOutput;
use datafusion::arrow::array::{
    Array, ArrayBuilder, ArrayRef, BooleanBuilder, Int64Builder, StringBuilder,
    new_null_array,
};
#[cfg(test)]
use datafusion::arrow::datatypes::Schema;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::{DataFusionError, Result, internal_err};
use datafusion::execution::memory_pool::MemoryReservation;

use crate::execution::common::coordinates::{
    absolute_row_from_usize, absolute_row_to_usize,
};
use crate::execution::common::memory::try_reserve_accounted;
use crate::execution::common::progress::{COARSE_WORK_BATCH_SIZE, CoarseWorkBatch};
use crate::execution::matching::{ExecutableDirectCountSummary, ExecutableRowStreamPlan};
use crate::execution::storage::collection::BatchCollection;
use crate::execution::storage::history_buffer::SharedHistoryBuffer;
use crate::execution::storage::row_presence::RowPresence;

use super::GatherPlan;
use super::encoder::{EncodedClassifier, EncodedOutputRow};

mod gather;
mod metadata;
pub(in crate::execution::storage) use gather::VIRTUAL_DEFAULT_COORD;

mod assembly;
mod reduction;

/// Native one-row output retains its cardinality when every measure is projected away.
enum SummaryOutputStorage {
    Ordinary,
    DirectCounts {
        automaton: Arc<crate::nfa::CompiledAutomaton>,
        summaries: Arc<[ExecutableDirectCountSummary]>,
        columns: Vec<DirectCountColumn>,
        reductions: Option<reduction::ReductionColumns>,
        row_capacity: usize,
    },
}

struct DirectCountColumn {
    // Count, one-based input position, or metadata endpoint word as declared by the summary.
    values: Vec<u64>,
    memory: MemoryReservation,
    prepared_array: Option<(ArrayRef, MemoryReservation)>,
}

const CLASSIFIER_RESERVATION_CHUNK: usize = 1024;

/// Owns every persisted pending output row and every reusable Arrow builder.
pub(in crate::execution::storage) struct OutputBatchBuilder {
    class_builder: Option<StringBuilder>,
    class_bytes: usize,
    class_reserved: usize,
    match_num_builder: Option<Int64Builder>,
    seq_builder: Option<Int64Builder>,
    excluded_builder: Option<BooleanBuilder>,
    classifier_bits_builders: Vec<BooleanBuilder>,
    summary_output: SummaryOutputStorage,
    stream: Arc<ExecutableRowStreamPlan>,
    row_refs: Vec<AbsoluteRow>,
    // Without input columns, gathering needs only cardinality. Metadata and
    // summaries keep their own column storage, with no source descriptors.
    rows_without_input: Option<usize>,
    min_buffered_row: Option<usize>,
    flush_threshold: usize,
    memory: MemoryReservation,
}

impl OutputBatchBuilder {
    pub(in crate::execution::storage) fn needs_input_gather(&self) -> bool {
        self.rows_without_input.is_none()
    }

    pub(in crate::execution::storage) fn needs_compact_classifier(&self) -> bool {
        self.class_builder.is_some()
            || self.excluded_builder.is_some()
            || !self.classifier_bits_builders.is_empty()
    }

    pub(in crate::execution::storage) fn reserve_compact_rows(
        &mut self,
        rows: usize,
        total_class_bytes: usize,
    ) -> Result<()> {
        let before = self.class_bytes;
        self.reserve_classifier_bytes_total(rows, total_class_bytes)?;
        self.reserve_rows(rows, "compact matched rows")
            .inspect_err(|_| self.rollback_class_bytes(before))
    }

    /// One unit per row in each populated column; cardinality alone is constant work.
    pub(in crate::execution::storage) fn compact_segment_work(
        &self,
        rows: usize,
    ) -> usize {
        let columns = usize::from(self.needs_input_gather())
            + usize::from(self.class_builder.is_some())
            + usize::from(self.match_num_builder.is_some())
            + usize::from(self.seq_builder.is_some())
            + usize::from(self.excluded_builder.is_some())
            + self.classifier_bits_builders.len();
        rows.saturating_mul(columns)
    }

    #[allow(clippy::too_many_arguments)]
    pub(in crate::execution::storage) fn append_reserved_compact_segment(
        &mut self,
        rows: usize,
        source_floor: usize,
        classifier: Option<EncodedClassifier<'_>>,
        match_number: i64,
        first_sequence: i64,
        excluded: bool,
    ) -> usize {
        let work = self.compact_segment_work(rows);
        if let Some(count) = &mut self.rows_without_input {
            *count += rows;
        } else {
            let start = source_floor as u64;
            let end = start + rows as u64;
            self.row_refs.extend((start..end).map(AbsoluteRow::new));
        }
        self.retain_source_floor(source_floor);
        if let Some(builder) = &mut self.class_builder {
            let classifier = classifier.expect("compact classifier metadata bound");
            for _ in 0..rows {
                builder.append_value(classifier.name);
            }
        }
        if let Some(builder) = &mut self.match_num_builder {
            builder.append_value_n(match_number, rows);
        }
        if let Some(builder) = &mut self.seq_builder {
            for offset in 0..rows {
                builder.append_value(first_sequence + offset as i64);
            }
        }
        if let Some(builder) = &mut self.excluded_builder {
            builder.append_n(rows, excluded);
        }
        for (builder, symbol) in self
            .classifier_bits_builders
            .iter_mut()
            .zip(self.stream.classifier_bitset_symbol_ids().iter())
        {
            builder.append_n(
                rows,
                classifier.is_some_and(|value| value.symbol.to_index() == symbol.index()),
            );
        }
        work
    }

    /// Append a contiguous, already checked symbol segment. Gathered input
    /// retains sequential row references; metadata uses the ordinary builders.
    #[allow(clippy::too_many_arguments)]
    pub(in crate::execution::storage) fn append_compact_rows(
        &mut self,
        rows: usize,
        source_floor: usize,
        classifier: Option<EncodedClassifier<'_>>,
        match_number: i64,
        first_sequence: i64,
        excluded: bool,
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<()> {
        if self.rows_without_input.is_none() {
            let end = source_floor.checked_add(rows).ok_or_else(|| {
                DataFusionError::ResourcesExhausted(
                    "MATCH_RECOGNIZE compact source end exceeds usize".into(),
                )
            })?;
            let _ = absolute_row_from_usize(source_floor, "compact source start")?;
            let _ = absolute_row_from_usize(end, "compact source end")?;
        }
        let class_before = self.class_bytes;
        self.reserve_classified_rows(rows, classifier, "compact matched rows")?;
        let estimated_work = self.compact_segment_work(rows);
        if let Err(error) = completed(estimated_work + 1) {
            self.rollback_class_bytes(class_before);
            return Err(error);
        }
        let work = self.append_reserved_compact_segment(
            rows,
            source_floor,
            classifier,
            match_number,
            first_sequence,
            excluded,
        );
        debug_assert_eq!(work, estimated_work);
        Ok(())
    }

    pub(in crate::execution::storage) fn try_new(
        stream: Arc<ExecutableRowStreamPlan>,
        flush_threshold: usize,
        pending_row_capacity: usize,
        memory: MemoryReservation,
    ) -> Result<Self> {
        Self::try_new_inner(
            stream,
            SummaryOutputStorage::Ordinary,
            flush_threshold,
            pending_row_capacity,
            memory,
        )
    }

    pub(in crate::execution::storage) fn try_new_direct_counts(
        stream: Arc<ExecutableRowStreamPlan>,
        summaries: Arc<[ExecutableDirectCountSummary]>,
        automaton: Arc<crate::nfa::CompiledAutomaton>,
        flush_threshold: usize,
        pending_row_capacity: usize,
        mut memory: MemoryReservation,
    ) -> Result<Self> {
        let mut columns = Vec::new();
        try_reserve_accounted(
            &mut columns,
            &memory,
            summaries.len(),
            "count-summary columns",
        )?;
        let mut reductions = reduction::ReductionColumns::new(&summaries, &mut memory)?;
        for summary in summaries.iter() {
            if let Some(reductions) = &mut reductions {
                let slot = summary
                    .reduction()
                    .map(|spec| reduction::ReductionColumn::new(spec, &memory))
                    .transpose()?;
                reductions.slots.push(slot);
            }
            columns.push(DirectCountColumn {
                values: Vec::new(),
                memory: memory.new_empty(),
                prepared_array: None,
            });
        }
        Self::try_new_inner(
            stream,
            SummaryOutputStorage::DirectCounts {
                automaton,
                summaries,
                columns,
                reductions,
                row_capacity: 0,
            },
            flush_threshold,
            pending_row_capacity,
            memory,
        )
    }

    fn try_new_inner(
        stream: Arc<ExecutableRowStreamPlan>,
        summary_output: SummaryOutputStorage,
        flush_threshold: usize,
        pending_row_capacity: usize,
        memory: MemoryReservation,
    ) -> Result<Self> {
        let layout = &stream;
        let mut row_refs = Vec::new();
        let rows_without_input = stream
            .spec()
            .passthrough_input_indices()
            .is_empty()
            .then_some(0);
        if rows_without_input.is_none() {
            try_reserve_accounted(
                &mut row_refs,
                &memory,
                pending_row_capacity,
                "pending output row references",
            )?;
        }

        let has_classifier = layout.has_classifier();
        let has_match_number = layout.match_number_column().is_some();
        let has_sequence_number = layout.has_sequence_number();
        let has_excluded = layout.has_excluded();
        let mut classifier_bits_builders = Vec::new();
        classifier_bits_builders
            .try_reserve(layout.classifier_bitset_symbol_ids().len())
            .map_err(|error| {
                DataFusionError::ResourcesExhausted(format!(
                    "MATCH_RECOGNIZE classifier metadata builders could not reserve {} entries: {error}",
                    layout.classifier_bitset_symbol_ids().len()
                ))
            })?;
        classifier_bits_builders.resize_with(
            layout.classifier_bitset_symbol_ids().len(),
            BooleanBuilder::new,
        );
        Ok(Self {
            class_builder: has_classifier.then(StringBuilder::new),
            class_bytes: 0,
            class_reserved: 0,
            match_num_builder: has_match_number.then(Int64Builder::new),
            seq_builder: has_sequence_number.then(Int64Builder::new),
            excluded_builder: has_excluded.then(BooleanBuilder::new),
            classifier_bits_builders,
            summary_output,
            stream,
            row_refs,
            rows_without_input,
            min_buffered_row: None,
            flush_threshold,
            memory,
        })
    }

    #[inline]
    pub(in crate::execution::storage) fn len(&self) -> usize {
        self.rows_without_input.unwrap_or(self.row_refs.len())
    }

    #[inline]
    pub(in crate::execution::storage) fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub(in crate::execution::storage) const fn min_buffered_row(&self) -> Option<usize> {
        self.min_buffered_row
    }

    pub(in crate::execution::storage) fn reserve_row(
        &mut self,
        row: EncodedOutputRow<'_>,
    ) -> Result<()> {
        self.reserve_classified_rows(1, row.classifier, row.reservation_context())
    }

    fn reserve_classifier_bytes(&mut self, rows: usize, value_len: usize) -> Result<()> {
        if self.class_builder.is_none() {
            return Ok(());
        }
        let Some(total_value_bytes) = rows.checked_mul(value_len) else {
            return Err(DataFusionError::ResourcesExhausted(
                "MATCH_RECOGNIZE classifier string buffer exceeds i32 offset limit"
                    .into(),
            ));
        };
        self.reserve_classifier_bytes_total(rows, total_value_bytes)
    }

    fn reserve_classifier_bytes_total(
        &mut self,
        rows: usize,
        total_value_bytes: usize,
    ) -> Result<()> {
        if let Some(builder) = &self.class_builder {
            if !builder
                .values_slice()
                .len()
                .checked_add(total_value_bytes)
                .is_some_and(|total| total <= i32::MAX as usize)
            {
                return Err(DataFusionError::ResourcesExhausted(
                    "MATCH_RECOGNIZE classifier string buffer exceeds i32 offset limit"
                        .into(),
                ));
            }
            let bytes = rows
                .checked_mul(size_of::<i32>())
                .and_then(|offsets| offsets.checked_add(total_value_bytes))
                .and_then(|bytes| bytes.checked_add(rows.div_ceil(8)))
                .ok_or_else(|| {
                    DataFusionError::ResourcesExhausted(
                        "MATCH_RECOGNIZE classifier byte count overflow".into(),
                    )
                })?;
            let required = self.class_bytes.checked_add(bytes).ok_or_else(|| {
                DataFusionError::ResourcesExhausted(
                    "MATCH_RECOGNIZE classifier byte count overflow".into(),
                )
            })?;
            if required > self.class_reserved {
                let target = required
                    .checked_next_multiple_of(CLASSIFIER_RESERVATION_CHUNK)
                    .unwrap_or(required);
                let delta = target - self.class_reserved;
                match self.memory.try_grow(delta) {
                    Ok(()) => self.class_reserved = target,
                    Err(DataFusionError::ResourcesExhausted(_)) if target > required => {
                        self.memory.try_grow(required - self.class_reserved)?;
                        self.class_reserved = required;
                    }
                    Err(error) => return Err(error),
                }
            }
            self.class_bytes = required;
        }
        Ok(())
    }

    pub(in crate::execution::storage) const fn class_bytes(&self) -> usize {
        self.class_bytes
    }

    pub(in crate::execution::storage) fn rollback_class_bytes(&mut self, before: usize) {
        self.class_bytes = before;
        let _ = self.release_unused_classifier_bytes();
    }

    pub(super) fn release_unused_classifier_bytes(&mut self) -> Result<()> {
        let excess = self.class_reserved.saturating_sub(self.class_bytes);
        if excess != 0 {
            self.memory.try_shrink(excess)?;
            self.class_reserved -= excess;
        }
        Ok(())
    }

    fn reserve_classified_rows(
        &mut self,
        rows: usize,
        classifier: Option<EncodedClassifier<'_>>,
        context: &str,
    ) -> Result<()> {
        let before = self.class_bytes;
        self.reserve_classifier_bytes(rows, classifier.map_or(0, |c| c.name.len()))?;
        self.reserve_rows(rows, context)
            .inspect_err(|_| self.rollback_class_bytes(before))
    }

    fn reserve_rows(&mut self, additional: usize, context: &str) -> Result<()> {
        if let Some(rows) = self.rows_without_input {
            rows.checked_add(additional).ok_or_else(|| {
                DataFusionError::ResourcesExhausted(
                    "MATCH_RECOGNIZE pending output row count overflow".into(),
                )
            })?;
            return Ok(());
        }
        // This private vector grows together with its pool lease and keeps
        // both through a flush. Its admitted capacity covers existing slots.
        if additional <= self.row_refs.capacity() - self.row_refs.len() {
            return Ok(());
        }
        self.release_unused_classifier_bytes()?;
        try_reserve_accounted(&mut self.row_refs, &self.memory, additional, context)
    }

    /// Publish a descriptor after the façade has completed any fallible
    /// presence update required for a matched physical row.
    #[inline(always)]
    pub(in crate::execution::storage) fn begin_reserved_row(
        &mut self,
        row: EncodedOutputRow<'_>,
    ) {
        if let Some(rows) = &mut self.rows_without_input {
            // reserve_row checked this increment before the presence update.
            *rows += 1;
        } else {
            self.row_refs.push(row.row_ref);
        }
        self.retain_source_floor(row.source_floor);

        if let Some(builder) = &mut self.class_builder {
            if let Some(classifier) = row.classifier {
                builder.append_value(classifier.name);
            } else {
                builder.append_null();
            }
        }

        if let Some(builder) = &mut self.match_num_builder {
            builder.append_value(row.match_number);
        }
        if let Some(builder) = &mut self.seq_builder {
            builder.append_value(row.sequence_number);
        }
        if let Some(builder) = &mut self.excluded_builder {
            builder.append_value(row.excluded);
        }
    }

    /// Reserve all summary fields before consuming any result. Both captured
    /// facts and resumable reductions commit through the same append operation.
    pub(in crate::execution::storage) fn reserve_summary(
        &mut self,
        count: usize,
    ) -> Result<()> {
        let SummaryOutputStorage::DirectCounts {
            columns,
            summaries,
            reductions,
            row_capacity,
            ..
        } = &mut self.summary_output
        else {
            return internal_err!(
                "MATCH_RECOGNIZE direct count-summary row requires direct-count output storage"
            );
        };
        if count != columns.len() {
            return internal_err!(
                "MATCH_RECOGNIZE count-summary row has {} values, expected {}",
                count,
                columns.len()
            );
        }
        if let Some(reductions) = reductions {
            for ((column, slot), summary) in columns
                .iter_mut()
                .zip(reductions.slots.iter_mut())
                .zip(summaries.iter())
            {
                if let Some(slot) = slot {
                    slot.reserve(summary.reduction().expect("bound reduction"))?;
                } else if column.values.len() == column.values.capacity() {
                    try_reserve_accounted(
                        &mut column.values,
                        &column.memory,
                        1,
                        "count-summary values",
                    )?;
                }
            }
        } else if columns
            .first()
            .is_some_and(|column| column.values.len() >= *row_capacity)
        {
            // Admit capacity in every column before committing any of this row's
            // values. Most rows fit the capacity admitted at the last growth.
            let mut capacity = usize::MAX;
            for column in columns.iter_mut() {
                try_reserve_accounted(
                    &mut column.values,
                    &column.memory,
                    1,
                    "count-summary values",
                )?;
                capacity = capacity.min(column.values.capacity());
            }
            *row_capacity = capacity;
        }
        Ok(())
    }

    pub(in crate::execution::storage) fn append_summary(
        &mut self,
        values: &mut [u64],
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<()> {
        let SummaryOutputStorage::DirectCounts {
            columns,
            summaries,
            reductions,
            ..
        } = &mut self.summary_output
        else {
            return internal_err!(
                "MATCH_RECOGNIZE direct count-summary row requires direct-count output storage"
            );
        };
        if values.len() != columns.len() {
            return internal_err!(
                "MATCH_RECOGNIZE count-summary row has {} values, expected {}",
                values.len(),
                columns.len()
            );
        }
        let mut work = CoarseWorkBatch::new(completed);
        for (index, value) in values.iter_mut().enumerate() {
            let fact = std::mem::take(value);
            if let Some(slot) = reductions.as_mut().and_then(|r| r.slots[index].as_mut())
            {
                slot.append_reserved(
                    summaries[index].reduction().expect("bound reduction").op,
                );
            } else {
                let column = &mut columns[index];
                debug_assert!(column.values.len() < column.values.capacity());
                column.values.push(fact);
            }
            work.complete_one()?;
        }
        work.finish()
    }

    pub(in crate::execution::storage) fn retain_source_floor(
        &mut self,
        source_floor: usize,
    ) {
        self.min_buffered_row = Some(
            self.min_buffered_row
                .map_or(source_floor, |row| row.min(source_floor)),
        );
    }

    pub(in crate::execution::storage) fn append_classifier_fields(
        &mut self,
        classifier: Option<usize>,
        work: &mut CoarseWorkBatch<'_>,
    ) -> Result<()> {
        for (builder, symbol) in self
            .classifier_bits_builders
            .iter_mut()
            .zip(self.stream.classifier_bitset_symbol_ids().iter())
        {
            builder.append_value(classifier == Some(symbol.index()));
            work.complete_one()?;
        }
        Ok(())
    }

    #[cfg(test)]
    pub(in crate::execution::storage) fn append_reserved_row(
        &mut self,
        row: EncodedOutputRow<'_>,
        work: &mut CoarseWorkBatch<'_>,
    ) -> Result<()> {
        self.begin_reserved_row(row);
        self.append_classifier_fields(
            row.classifier_symbol().map(|symbol| symbol.to_index()),
            work,
        )
    }

    #[inline]
    pub(in crate::execution::storage) fn batch_size(&self) -> usize {
        self.flush_threshold.max(1)
    }

    #[inline]
    pub(in crate::execution::storage) fn rows_until_flush(&self) -> usize {
        self.flush_threshold.saturating_sub(self.len()).max(1)
    }

    /// Stage unfinalized unmatched rows in `[first_unfinalized_row, end)` directly into
    /// pending output buffers so consecutive closed partitions can share a single output
    /// batch instead of materializing one RecordBatch per SQL partition.
    ///
    /// Returns `Ok(true)` once `row_presence` has been finalized through `end`, or
    /// `Ok(false)` when yielding after one bounded chunk.
    pub(in crate::execution::storage) fn append_unmatched_prefix_chunk(
        &mut self,
        end: usize,
        row_presence: &mut RowPresence,
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<bool> {
        if !matches!(self.summary_output, SummaryOutputStorage::Ordinary) {
            return internal_err!(
                "MATCH_RECOGNIZE native selected-summary output cannot append unmatched rows"
            );
        }
        let start = absolute_row_to_usize(
            row_presence.first_unfinalized_row(),
            "row-presence finalization start",
        )?;
        if start >= end {
            return Ok(true);
        }
        let max_unmatched = self.rows_until_flush();
        let scan_limit = self.batch_size().max(COARSE_WORK_BATCH_SIZE);
        let scan_end = start.saturating_add(scan_limit).min(end);
        let before_len = self.len();
        let before_min_row = self.min_buffered_row;
        let class_before = self.class_bytes;
        let mut chunk_end = start;
        let mut unmatched_count = 0usize;
        let mut first_unmatched: Option<usize> = None;
        let prepared = (|| -> Result<()> {
            let mut work = CoarseWorkBatch::new(&mut *completed);
            for index in start..scan_end {
                let row = absolute_row_from_usize(index, "unmatched output row")?;
                if !row_presence.contains(row) {
                    if first_unmatched.is_none() {
                        first_unmatched = Some(index);
                    }
                    if self.rows_without_input.is_none() {
                        self.reserve_classified_rows(
                            1,
                            None,
                            "unmatched output row references",
                        )?;
                        self.row_refs.push(row);
                    }
                    unmatched_count += 1;
                }
                chunk_end = index + 1;
                work.complete_one()?;
                if unmatched_count == max_unmatched {
                    break;
                }
            }
            work.finish()?;
            if unmatched_count != 0 && self.rows_without_input.is_some() {
                self.reserve_classified_rows(
                    unmatched_count,
                    None,
                    "unmatched output rows",
                )?;
            }
            let trimmed_end =
                absolute_row_from_usize(chunk_end, "row-presence finalization boundary")?;
            row_presence.trim_prefix_with_work(trimmed_end, &mut *completed)?;
            Ok(())
        })();
        if let Err(error) = prepared {
            self.row_refs.truncate(before_len);
            self.min_buffered_row = before_min_row;
            self.rollback_class_bytes(class_before);
            return Err(error);
        }
        if unmatched_count != 0 {
            if let Some(rows) = &mut self.rows_without_input {
                *rows += unmatched_count;
            }
            if let Some(floor) = first_unmatched {
                self.retain_source_floor(floor);
            }
            if let Some(builder) = &mut self.class_builder {
                builder.append_nulls(unmatched_count);
            }
            if let Some(builder) = &mut self.match_num_builder {
                builder.append_nulls(unmatched_count);
            }
            if let Some(builder) = &mut self.seq_builder {
                builder.append_nulls(unmatched_count);
            }
            if let Some(builder) = &mut self.excluded_builder {
                builder.append_n(unmatched_count, false);
            }
            for builder in &mut self.classifier_bits_builders {
                builder.append_n(unmatched_count, false);
            }
        }
        Ok(chunk_end >= end)
    }

    #[inline]
    pub(in crate::execution::storage) fn maybe_flush_with_work(
        &mut self,
        batches: &BatchCollection,
        global_offset: usize,
        history: Option<&SharedHistoryBuffer>,
        pending_output: &mut PendingOutput,
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<()> {
        if self.len() >= self.flush_threshold {
            pending_output.try_reserve(1).map_err(|error| {
                DataFusionError::ResourcesExhausted(format!(
                    "MATCH_RECOGNIZE threshold output could not reserve one staged batch slot: {error}"
                ))
            })?;
            if let Some(batch) =
                self.flush_collection(batches, global_offset, history, completed)?
            {
                pending_output.push_back(batch)?;
            }
        }
        Ok(())
    }

    #[cfg(test)]
    pub(in crate::execution::storage) fn validate_pending_metadata_len(
        &self,
        expected: usize,
    ) -> Result<()> {
        self.validate_pending_output(expected, &mut |_| Ok(()))
    }

    fn validate_pending_output(
        &self,
        expected: usize,
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<()> {
        let validate = |name: &str, index: Option<usize>, actual: usize| {
            if actual == expected {
                Ok(())
            } else {
                let name = match index {
                    Some(index) => format!("{name} {index}"),
                    None => name.to_owned(),
                };
                Err(DataFusionError::Internal(format!(
                    "MATCH_RECOGNIZE pending output builder {name} has {actual} rows but row descriptors have {expected}"
                )))
            }
        };

        if let Some(builder) = &self.class_builder {
            validate("classifier", None, builder.len())?;
        }
        if let Some(builder) = &self.match_num_builder {
            validate("match number", None, builder.len())?;
        }
        if let Some(builder) = &self.seq_builder {
            validate("match sequence number", None, builder.len())?;
        }
        if let Some(builder) = &self.excluded_builder {
            validate("excluded", None, builder.len())?;
        }
        for (index, builder) in self.classifier_bits_builders.iter().enumerate() {
            validate("classifier bit", Some(index), builder.len())?;
        }
        let summary_fields = match &self.summary_output {
            SummaryOutputStorage::Ordinary => 0,
            SummaryOutputStorage::DirectCounts {
                columns,
                reductions,
                ..
            } => {
                for (index, column) in columns.iter().enumerate() {
                    if let Some(slot) =
                        reductions.as_ref().and_then(|r| r.slots[index].as_ref())
                    {
                        let rows = match &column.prepared_array {
                            Some((array, _)) => array.len(),
                            None => slot.len(),
                        };
                        validate("selected reduction", Some(index), rows)?;
                        continue;
                    }
                    validate("count summary", Some(index), column.values.len())?;
                }
                columns.len()
            }
        };
        completed(4 + self.classifier_bits_builders.len() + summary_fields)
    }

    #[cfg(test)]
    pub(in crate::execution::storage) fn validate_no_pending_builder_tail(
        &self,
    ) -> Result<()> {
        if !self.is_empty() || self.min_buffered_row.is_some() {
            return internal_err!(
                "MATCH_RECOGNIZE selected-match failure retained a pending row"
            );
        }
        self.validate_pending_metadata_len(0)
    }

    #[cfg(test)]
    pub(in crate::execution::storage) fn inject_pending_input(
        &mut self,
        row: AbsoluteRow,
        source_floor: usize,
        match_number: i64,
    ) {
        self.reserve_rows(1, "test output row").unwrap();
        if let Some(rows) = &mut self.rows_without_input {
            *rows += 1;
        } else {
            self.row_refs.push(row);
        }
        self.min_buffered_row = Some(source_floor);
        if let Some(builder) = &mut self.match_num_builder {
            builder.append_value(match_number);
        }
    }

    #[cfg(test)]
    pub(in crate::execution::storage) fn set_min_buffered_row(
        &mut self,
        row: Option<usize>,
    ) {
        self.min_buffered_row = row;
    }

    fn empty_passthrough_batch(&self, num_rows: usize) -> Result<RecordBatch> {
        Ok(RecordBatch::try_new_with_options(
            Arc::clone(self.stream.passthrough_schema()),
            vec![],
            &datafusion::arrow::record_batch::RecordBatchOptions::new()
                .with_row_count(Some(num_rows)),
        )?)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{
        EmptyMatchesMode, MatchRecognizeOutputSpec, MatchSummaryField, NormalizedPattern,
        Pattern, RowsPerMatch, Symbol, SymbolId,
    };
    use crate::execution::common::memory::new_unbounded_state_memory;
    use crate::execution::matching::path::Sym;
    use crate::execution::matching::{
        ExecutableDirectCountSummary, ExecutableOutputFinalizer, ExecutableOutputPlan,
    };
    use crate::nfa::CompiledAutomaton;
    use datafusion::arrow::array::{
        Array, BooleanArray, Int32Array, Int64Array, StringArray,
    };
    use datafusion::arrow::datatypes::{DataType, Field};

    pub(super) fn test_case(
        metadata_columns: Vec<MatchMetadataColumn>,
        classifier: bool,
    ) -> (OutputBatchBuilder, BatchCollection) {
        test_case_with_inputs(vec![0], metadata_columns, classifier)
    }

    fn test_case_with_inputs(
        input_columns: Vec<usize>,
        metadata_columns: Vec<MatchMetadataColumn>,
        classifier: bool,
    ) -> (OutputBatchBuilder, BatchCollection) {
        let schema = Arc::new(Schema::new(vec![
            Field::new("id", DataType::Int32, false),
            Field::new(crate::core::symbol_col_name("A"), DataType::Boolean, false),
        ]));
        let batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![
                Arc::new(Int32Array::from(vec![10, 20, 30])),
                Arc::new(BooleanArray::from(vec![true, false, false])),
            ],
        )
        .unwrap();
        let batches = BatchCollection::try_new(vec![batch], Arc::clone(&schema)).unwrap();
        let pattern = NormalizedPattern::Ast(Pattern::Symbol(Symbol::Named("A".into())));
        let compiled = CompiledAutomaton::compile(&pattern, &["A".into()]).unwrap();
        let spec = MatchRecognizeOutputSpec::new(
            input_columns,
            metadata_columns,
            if classifier {
                vec!["A".into()]
            } else {
                Vec::new()
            },
        );
        let a = SymbolId::try_new(1, compiled.num_symbols()).expect("valid A slot");
        let classifier_ids = classifier.then_some(a).into_iter().collect::<Arc<[_]>>();
        let resolved = ExecutableOutputPlan::try_rows(
            schema.as_ref(),
            spec,
            classifier_ids,
            RowsPerMatch::AllRows(EmptyMatchesMode::Show),
            &compiled,
        )
        .unwrap();
        let builder = OutputBatchBuilder::try_new(
            Arc::clone(resolved.stream()),
            16,
            17,
            new_unbounded_state_memory().new_empty(),
        )
        .unwrap();
        (builder, batches)
    }

    fn representative(row: usize) -> EncodedOutputRow<'static> {
        EncodedOutputRow {
            row_ref: AbsoluteRow::new(row as u64),
            source_floor: row,
            classifier: None,
            match_number: 1,
            sequence_number: 1,
            excluded: false,
            matched_physical_row: Some(AbsoluteRow::new(row as u64)),
        }
    }

    fn admit_summary_representative(
        builder: &mut OutputBatchBuilder,
        row: EncodedOutputRow<'_>,
    ) {
        // These typed-summary test_cases have no classifier bitset columns.
        builder.reserve_row(row).unwrap();
        builder.begin_reserved_row(row);
    }

    #[test]
    fn outputs_without_input_columns_keep_cardinality_and_unmatched_metadata() {
        use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
        use datafusion::execution::memory_pool::{
            GreedyMemoryPool, MemoryConsumer, MemoryPool,
        };

        for metadata in [vec![], vec![MatchMetadataColumn::MatchNumber]] {
            let (mut builder, batches) =
                test_case_with_inputs(vec![], metadata.clone(), false);
            let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1 << 20));
            builder.memory =
                MemoryConsumer::new("unmatched-cardinality-test").register(&pool);
            let chunk_size = builder.batch_size().max(COARSE_WORK_BATCH_SIZE);
            let batch = batches.batch(0);
            let batches = BatchCollection::try_new(
                vec![batch.clone(); chunk_size / batch.num_rows() + 2],
                Arc::clone(batches.schema()),
            )
            .unwrap();
            let rows = batches.num_rows();
            let mut presence = RowPresence::try_new_unbounded().unwrap();
            for index in [0, chunk_size] {
                let row = representative(index);
                builder.reserve_row(row).unwrap();
                builder.begin_reserved_row(row);
                presence.mark(AbsoluteRow::new(index as u64)).unwrap();
            }
            assert_eq!(builder.len(), 2);
            assert_eq!(builder.row_refs.capacity(), 0);
            let mut scanned = 0;
            let mut outputs = Vec::new();
            loop {
                let mut work = 0;
                let finished = builder
                    .append_unmatched_prefix_chunk(rows, &mut presence, &mut |units| {
                        work += units;
                        Ok(())
                    })
                    .unwrap();
                assert!(work > 0);
                scanned += work;
                assert!(builder.len() <= builder.batch_size());
                assert_eq!(pool.reserved(), 0, "unmatched rows only need a count");
                if (builder.len() >= builder.batch_size() || finished)
                    && let Some(batch) = builder
                        .flush_collection(&batches, 0, None, &mut |_| Ok(()))
                        .unwrap()
                {
                    assert!(batch.num_rows() <= builder.batch_size());
                    assert_eq!(batch.num_columns(), metadata.len());
                    outputs.push(batch);
                }
                if finished {
                    break;
                }
            }
            assert_eq!(scanned, rows);
            assert_eq!(
                presence.first_unfinalized_row(),
                AbsoluteRow::new(rows as u64)
            );
            assert!(
                outputs.len() > 1,
                "unmatched rows must flush in <= flush_threshold batches"
            );
            let output = datafusion::arrow::compute::concat_batches(
                builder.stream.schema(),
                &outputs,
            )
            .unwrap();
            assert_eq!(output.num_rows(), rows);
            assert_eq!(output.num_columns(), metadata.len());
            if !metadata.is_empty() {
                let mut expected = vec![None; rows];
                expected[..2].fill(Some(1));
                assert_eq!(output.column(0).as_ref(), &Int64Array::from(expected));
            }
            builder.validate_no_pending_builder_tail().unwrap();
        }
    }

    #[test]
    fn representative_optional_builder_subsets_stay_aligned_after_each_append() {
        let optional_metadata = [
            MatchMetadataColumn::Classifier,
            MatchMetadataColumn::MatchNumber,
            MatchMetadataColumn::MatchSequenceNumber,
            MatchMetadataColumn::Excluded,
        ];
        for (mask, classifier_bits) in [
            (0, false),
            (15, true),
            (1, false),
            (2, false),
            (4, false),
            (8, false),
            (0, true),
            (9, true),
        ] {
            let metadata_columns = optional_metadata
                .iter()
                .enumerate()
                .filter_map(|(index, column)| {
                    (mask & (1 << index) != 0).then_some(*column)
                })
                .collect::<Vec<_>>();
            let (mut builder, batches) =
                test_case(metadata_columns.clone(), classifier_bits);
            let classifier = EncodedClassifier {
                symbol: Sym::from_index(1),
                name: "A",
            };
            let rows = [
                EncodedOutputRow {
                    row_ref: AbsoluteRow::new(0),
                    source_floor: 0,
                    classifier: Some(classifier),
                    match_number: 7,
                    sequence_number: 1,
                    excluded: true,
                    matched_physical_row: Some(AbsoluteRow::new(0)),
                },
                EncodedOutputRow {
                    row_ref: AbsoluteRow::new(1),
                    source_floor: 1,
                    classifier: None,
                    match_number: 7,
                    sequence_number: 2,
                    excluded: true,
                    matched_physical_row: Some(AbsoluteRow::new(1)),
                },
                EncodedOutputRow {
                    row_ref: AbsoluteRow::new(2),
                    source_floor: 2,
                    classifier: None,
                    match_number: 7,
                    sequence_number: -1,
                    excluded: false,
                    matched_physical_row: None,
                },
            ];
            for (index, row) in rows.into_iter().enumerate() {
                builder.reserve_row(row).unwrap();
                let mut completed = |_| Ok(());
                let mut work = CoarseWorkBatch::new(&mut completed);
                builder.append_reserved_row(row, &mut work).unwrap();
                work.finish().unwrap();
                builder.validate_pending_metadata_len(index + 1).unwrap();
            }

            let output = builder
                .flush_collection(&batches, 0, None, &mut |_| Ok(()))
                .unwrap()
                .unwrap();
            assert_eq!(output.num_rows(), 3);
            assert_eq!(
                output.column(0).as_ref(),
                &Int32Array::from(vec![Some(10), Some(20), Some(30)])
            );
            let expected: Vec<(MatchMetadataColumn, ArrayRef)> = vec![
                (
                    MatchMetadataColumn::Classifier,
                    Arc::new(StringArray::from(vec![Some("A"), None, None])),
                ),
                (
                    MatchMetadataColumn::MatchNumber,
                    Arc::new(Int64Array::from(vec![7, 7, 7])),
                ),
                (
                    MatchMetadataColumn::MatchSequenceNumber,
                    Arc::new(Int64Array::from(vec![1, 2, -1])),
                ),
                (
                    MatchMetadataColumn::Excluded,
                    Arc::new(BooleanArray::from(vec![true, true, false])),
                ),
            ];
            for (column, values) in expected {
                if metadata_columns.contains(&column) {
                    assert_eq!(
                        output.column_by_name(column.as_ref()).unwrap().as_ref(),
                        values.as_ref()
                    );
                }
            }
            if classifier_bits {
                assert_eq!(
                    output.column(output.num_columns() - 1).as_ref(),
                    &BooleanArray::from(vec![true, false, false])
                );
            }
        }
    }

    #[test]
    fn direct_count_values_are_admitted_before_append_and_reused_by_arrow() -> Result<()>
    {
        use datafusion::execution::memory_pool::{
            GreedyMemoryPool, MemoryConsumer, MemoryPool,
        };

        const LIMIT: usize = 4096;
        const WIDTH: usize = 2;
        let schema = Arc::new(Schema::empty());
        let batches = BatchCollection::try_new(vec![], Arc::clone(&schema))?;
        let pattern = NormalizedPattern::Ast(Pattern::Symbol(Symbol::Named("A".into())));
        let compiled = Arc::new(CompiledAutomaton::compile(&pattern, &["A".into()])?);
        let summaries = (0..WIDTH)
            .map(|index| {
                ExecutableDirectCountSummary::new(
                    MatchSummaryField::new(
                        index,
                        Arc::new(Field::new("count", DataType::Int64, false)),
                    ),
                    None,
                )
            })
            .collect();
        let resolved = ExecutableOutputPlan::try_direct_counts(
            &schema,
            MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
            Arc::from([]),
            summaries,
            &compiled,
        )?;
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(LIMIT));
        let memory = MemoryConsumer::new("direct-count-output-test").register(&pool);
        let blocker = memory.new_empty();
        let mut completed = |_| Ok(());

        for deny in [true, false] {
            let ExecutableOutputFinalizer::DirectCounts { summaries } =
                resolved.finalizer()
            else {
                unreachable!()
            };
            let mut builder = OutputBatchBuilder::try_new_direct_counts(
                Arc::clone(resolved.stream()),
                Arc::clone(summaries),
                Arc::clone(&compiled),
                1024,
                1025,
                memory.new_empty(),
            )?;
            let baseline = pool.reserved();
            assert_eq!(baseline, WIDTH * size_of::<DirectCountColumn>());
            admit_summary_representative(&mut builder, representative(0));
            let mut counts = [42, 7];
            if deny {
                // Leave room for one column. Neither column may consume its value.
                blocker.try_grow(LIMIT - baseline - size_of::<i64>())?;
            }
            let append = builder
                .reserve_summary(counts.len())
                .and_then(|()| builder.append_summary(&mut counts, &mut |_| Ok(())));
            let SummaryOutputStorage::DirectCounts { columns, .. } =
                &builder.summary_output
            else {
                unreachable!();
            };
            if deny {
                assert!(matches!(
                    append,
                    Err(DataFusionError::ResourcesExhausted(_))
                ));
                assert_eq!(counts, [42, 7]);
                assert!(columns.iter().all(|column| column.values.is_empty()));
                assert_eq!(pool.reserved(), LIMIT);
            } else {
                append?;
                assert_eq!(pool.reserved(), baseline + WIDTH * size_of::<i64>());
                let value_buffers = columns
                    .iter()
                    .map(|column| column.values.as_ptr())
                    .collect::<Vec<_>>();
                // Assembly can admit the array headers and column references,
                // with no room to charge the COUNT values a second time.
                let assembly_bytes =
                    WIDTH * (size_of::<ArrayRef>() + size_of::<Int64Array>());
                blocker.try_grow(LIMIT - pool.reserved() - assembly_bytes)?;
                let batch = builder
                    .flush_collection(&batches, 0, None, &mut completed)?
                    .unwrap();
                assert_eq!(batch.num_rows(), 1);
                for ((column, value), buffer) in
                    batch.columns().iter().zip([42, 7]).zip(value_buffers)
                {
                    let array = column.as_any().downcast_ref::<Int64Array>().unwrap();
                    assert_eq!(array.value(0), value);
                    assert_eq!(array.values().as_ptr(), buffer.cast());
                }
                assert_eq!(pool.reserved(), baseline + blocker.size());
            }
            drop(builder);
            assert_eq!(pool.reserved(), blocker.size());
            blocker.free();
            assert_eq!(pool.reserved(), 0);
        }
        Ok(())
    }

    #[test]
    fn visible_row_reference_reservation_tracks_growth_until_discard() {
        use datafusion::execution::memory_pool::{
            GreedyMemoryPool, MemoryConsumer, MemoryPool,
        };

        let (ordinary, batches) = test_case(vec![], false);
        let stream = Arc::clone(&ordinary.stream);
        drop(ordinary);
        const LIMIT: usize = 4096;
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(LIMIT));
        let reservation =
            MemoryConsumer::new("visible-output-row-refs-test").register(&pool);
        let blocker = reservation.new_empty();
        blocker.try_grow(LIMIT).unwrap();
        let mut builder =
            OutputBatchBuilder::try_new(stream, 16, 0, reservation).unwrap();

        let row = representative(0);
        let error = builder.reserve_row(row).unwrap_err();
        assert!(matches!(error, DataFusionError::ResourcesExhausted(_)));
        assert!(builder.is_empty());
        assert_eq!(builder.row_refs.capacity(), 0);
        assert_eq!(pool.reserved(), LIMIT);
        drop(blocker);
        assert_eq!(pool.reserved(), 0);

        builder.reserve_row(row).unwrap();
        let retained = builder.row_refs.capacity() * size_of::<AbsoluteRow>();
        assert!(retained > 0);
        assert_eq!(pool.reserved(), retained);
        let mut completed = |_| Ok(());
        let mut work = CoarseWorkBatch::new(&mut completed);
        builder.append_reserved_row(row, &mut work).unwrap();
        work.finish().unwrap();
        builder
            .flush_collection(&batches, 0, None, &mut |_| Ok(()))
            .unwrap()
            .unwrap();
        assert_eq!(pool.reserved(), retained);

        drop(builder);
        assert_eq!(pool.reserved(), 0);
    }

    #[test]
    fn contiguous_flush_copies_when_final_assembly_exceeds_the_pool() {
        use datafusion::execution::memory_pool::{
            GreedyMemoryPool, MemoryConsumer, MemoryPool,
        };

        let mut metadata = Int64Builder::new();
        metadata.append_slice(&[1, 1]);
        let metadata_bytes = metadata.finish().get_array_memory_size();
        let input_column_slot = size_of::<ArrayRef>();
        assert!(metadata_bytes > input_column_slot);

        for (headroom, copies_input) in [
            // Only the slice and its one-column vector fit.
            (0, true),
            // The replacement vector and first metadata array fit. The second
            // array needs more than the remaining one column slot.
            (3 * input_column_slot + metadata_bytes, true),
            (1 << 20, false),
        ] {
            let (mut builder, test_case_batches) = test_case(
                vec![
                    MatchMetadataColumn::MatchNumber,
                    MatchMetadataColumn::MatchSequenceNumber,
                ],
                false,
            );
            let schema = Arc::clone(test_case_batches.schema());
            let input = Arc::new(Int32Array::from_iter_values(0..8192));
            let slice_bytes = input.slice(1, 2).get_array_memory_size();
            let input_slice = input.values().as_ptr().wrapping_add(1);
            let flag = Arc::new(BooleanArray::from(vec![true; input.len()]));
            let batch =
                RecordBatch::try_new(Arc::clone(&schema), vec![input, flag]).unwrap();
            let batches = BatchCollection::try_new(vec![batch], schema).unwrap();
            let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(
                slice_bytes + input_column_slot + headroom,
            ));
            builder.memory =
                MemoryConsumer::new("flush-slice-copy-fallback").register(&pool);
            for (index, sequence) in [(1, 7), (2, 8)] {
                let mut row = representative(index);
                row.sequence_number = sequence;
                builder.reserve_row(row).unwrap();
                builder.begin_reserved_row(row);
            }

            let output = builder
                .flush_collection(&batches, 0, None, &mut |_| Ok(()))
                .unwrap()
                .unwrap();
            let values = output
                .column(0)
                .as_any()
                .downcast_ref::<Int32Array>()
                .unwrap();
            assert_eq!(values.values().as_ref(), &[1, 2]);
            assert_eq!(values.values().as_ptr() != input_slice, copies_input);
            assert_eq!(output.column(1).as_ref(), &Int64Array::from(vec![1, 1]));
            assert_eq!(output.column(2).as_ref(), &Int64Array::from(vec![7, 8]));
            builder.validate_no_pending_builder_tail().unwrap();
            assert_eq!(pool.reserved(), 0);
        }
    }

    #[test]
    fn failed_assembly_releases_temporary_columns() {
        use datafusion::execution::memory_pool::{
            GreedyMemoryPool, MemoryConsumer, MemoryPool,
        };

        for cancel in [false, true] {
            let (mut builder, batches) = test_case(
                vec![
                    MatchMetadataColumn::MatchNumber,
                    MatchMetadataColumn::Excluded,
                ],
                false,
            );
            let limit = 1 << 20;
            let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(limit));
            builder.memory = MemoryConsumer::new("assembly-discard-test").register(&pool);
            let row = representative(0);
            builder.reserve_row(row).unwrap();
            let mut completed = |_| Ok(());
            let mut work = CoarseWorkBatch::new(&mut completed);
            builder.append_reserved_row(row, &mut work).unwrap();
            work.finish().unwrap();

            let columns = vec![batches.batch(0).column(0).slice(0, 1)];
            let memory = builder.memory.new_empty();
            memory
                .try_grow(
                    columns[0].get_array_memory_size()
                        + columns.capacity() * size_of::<ArrayRef>(),
                )
                .unwrap();
            let data = gather::GatherBatch {
                batch: RecordBatch::try_new(
                    Arc::clone(builder.stream.passthrough_schema()),
                    columns,
                )
                .unwrap(),
                memory,
            };
            let occupied = MemoryConsumer::new("assembly-admission-test").register(&pool);
            if !cancel {
                // The three-column vector fits, but the first finished array does not.
                occupied
                    .try_grow(limit - pool.reserved() - 3 * size_of::<ArrayRef>())
                    .unwrap();
            }
            let Err(error) = builder.finish_batch(
                data,
                1,
                assembly::AssemblyInput::Gathered,
                &mut |_| {
                    assert!(cancel);
                    internal_err!("cancelled output assembly")
                },
            ) else {
                panic!("assembly must fail");
            };
            if cancel {
                assert!(error.to_string().contains("cancelled output assembly"));
            } else {
                assert!(matches!(error, DataFusionError::ResourcesExhausted(_)));
            }
            assert_eq!(builder.len(), 1);
            assert_eq!(pool.reserved(), occupied.size());
            drop(occupied);

            drop(builder);

            assert_eq!(pool.reserved(), 0);
        }
    }

    #[test]
    fn reserve_classifier_bytes_rejects_i32_offset_overflow_without_growing_memory() {
        let (mut builder, _batches) =
            test_case(vec![MatchMetadataColumn::Classifier], false);
        builder
            .class_builder
            .as_mut()
            .expect("classifier builder")
            .append_value("abcd");
        let before = builder.memory.size();

        // Exceeding i32::MAX total string bytes must fail before growing memory.
        let err = builder
            .reserve_classifier_bytes(1, i32::MAX as usize - 3)
            .unwrap_err();
        assert!(matches!(err, DataFusionError::ResourcesExhausted(_)));
        assert!(
            err.to_string()
                .contains("classifier string buffer exceeds i32 offset limit")
        );
        assert_eq!(builder.memory.size(), before);
        assert_eq!(builder.class_reserved, 0);
        assert_eq!(builder.class_bytes, 0);

        // Multiplication overflow in rows * value_len must also fail cleanly.
        let err = builder.reserve_classifier_bytes(usize::MAX, 2).unwrap_err();
        assert!(matches!(err, DataFusionError::ResourcesExhausted(_)));
        assert!(
            err.to_string()
                .contains("classifier string buffer exceeds i32 offset limit")
        );
        assert_eq!(builder.memory.size(), before);
        assert_eq!(builder.class_reserved, 0);
        assert_eq!(builder.class_bytes, 0);

        // Staying at or below i32::MAX succeeds and accounts memory.
        builder
            .reserve_classifier_bytes(1, i32::MAX as usize - 4)
            .unwrap();
        assert!(builder.memory.size() > before);
        assert!(builder.class_reserved > 0);
        assert!(builder.class_bytes > 0);
    }

    #[test]
    fn classifier_reservation_amortizes_credit_falls_back_in_tight_pool_and_releases_on_flush()
    -> Result<()> {
        use datafusion::execution::memory_pool::{
            GreedyMemoryPool, MemoryConsumer, MemoryPool,
        };

        // 1. Prepaid chunk credit is reused across rows without growing the reservation.
        let (template, batches) = test_case(vec![MatchMetadataColumn::Classifier], false);
        let stream = Arc::clone(&template.stream);
        drop(template);
        let generous_pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1 << 20));
        let mut builder = OutputBatchBuilder::try_new(
            Arc::clone(&stream),
            16,
            0,
            MemoryConsumer::new("classifier-credit-reuse").register(&generous_pool),
        )?;
        builder.reserve_classifier_bytes(1, 3)?;
        let single_row_bytes = 3 + size_of::<i32>() + 1;
        assert_eq!(builder.class_bytes, single_row_bytes);
        assert_eq!(builder.class_reserved, CLASSIFIER_RESERVATION_CHUNK);
        assert_eq!(builder.memory.size(), CLASSIFIER_RESERVATION_CHUNK);
        for step in 2..=16 {
            builder.reserve_classifier_bytes(1, 3)?;
            assert_eq!(builder.class_bytes, step * single_row_bytes);
            assert_eq!(builder.class_reserved, CLASSIFIER_RESERVATION_CHUNK);
            assert_eq!(builder.memory.size(), CLASSIFIER_RESERVATION_CHUNK);
        }
        drop(builder);
        assert_eq!(generous_pool.reserved(), 0);

        // 2. When a tight pool cannot fit the rounded chunk, exact admission succeeds.
        let tight_limit = 2 * single_row_bytes;
        assert!(tight_limit < CLASSIFIER_RESERVATION_CHUNK);
        let tight_pool: Arc<dyn MemoryPool> =
            Arc::new(GreedyMemoryPool::new(tight_limit));
        let mut tight_builder = OutputBatchBuilder::try_new(
            Arc::clone(&stream),
            16,
            0,
            MemoryConsumer::new("classifier-tight-pool").register(&tight_pool),
        )?;
        tight_builder.reserve_classifier_bytes(1, 3)?;
        assert_eq!(tight_builder.class_bytes, single_row_bytes);
        assert_eq!(tight_builder.class_reserved, single_row_bytes);
        assert_eq!(tight_builder.memory.size(), single_row_bytes);
        tight_builder.reserve_classifier_bytes(1, 3)?;
        assert_eq!(tight_builder.class_bytes, 2 * single_row_bytes);
        assert_eq!(tight_builder.class_reserved, 2 * single_row_bytes);
        assert_eq!(tight_builder.memory.size(), 2 * single_row_bytes);
        let err = tight_builder.reserve_classifier_bytes(1, 3).unwrap_err();
        assert!(matches!(err, DataFusionError::ResourcesExhausted(_)));
        assert_eq!(tight_builder.class_bytes, 2 * single_row_bytes);
        assert_eq!(tight_builder.class_reserved, 2 * single_row_bytes);
        assert_eq!(tight_builder.memory.size(), 2 * single_row_bytes);
        drop(tight_builder);
        assert_eq!(tight_pool.reserved(), 0);

        // 3. Flushing releases all classifier memory and resets class_bytes without leaking.
        let flush_pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1 << 20));
        let mut flush_builder = OutputBatchBuilder::try_new(
            stream,
            16,
            16,
            MemoryConsumer::new("classifier-flush-release").register(&flush_pool),
        )?;
        let row_ref_bytes = flush_builder.memory.size();
        let classifier = Some(EncodedClassifier {
            symbol: Sym::from_index(1),
            name: "A",
        });
        for index in 0..3 {
            let mut row = representative(index);
            row.classifier = classifier;
            flush_builder.reserve_row(row)?;
            flush_builder.begin_reserved_row(row);
        }
        assert!(flush_builder.class_bytes > 0);
        assert_eq!(flush_builder.class_reserved, CLASSIFIER_RESERVATION_CHUNK);
        assert_eq!(
            flush_builder.memory.size(),
            row_ref_bytes + CLASSIFIER_RESERVATION_CHUNK
        );
        let batch = flush_builder
            .flush_collection(&batches, 0, None, &mut |_| Ok(()))?
            .expect("flushed batch");
        assert_eq!(batch.num_rows(), 3);
        assert_eq!(flush_builder.class_bytes, 0);
        assert_eq!(flush_builder.class_reserved, 0);
        assert_eq!(flush_builder.memory.size(), row_ref_bytes);
        assert_eq!(flush_pool.reserved(), row_ref_bytes);
        drop(flush_builder);
        assert_eq!(flush_pool.reserved(), 0);
        Ok(())
    }
}