datafusion-match-recognize 0.56.0

MATCH_RECOGNIZE extension for 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
// 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.

//! Prepares complete native Arrow Boolean columns across a physical batch collection.

use std::mem::size_of;
use std::sync::Arc;

use datafusion::arrow::array::{Array, AsArray, BooleanArray};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion_common::{DataFusionError, Result, internal_err};
use datafusion_execution::memory_pool::MemoryReservation;

use super::symbol_columns::MultiBatchBoolColumnsBacking;
use super::{ResolvedBoolColumn, SymbolColumn};
use crate::execution::common::memory::reserved_vec;
use crate::execution::storage::collection::BatchCollection;

/// Private native columns; each advance completes one column before cooperation.
#[derive(Debug)]
pub(crate) struct PreparingPhysicalBoolColumns {
    columns: Vec<Option<BooleanArray>>,
    pre_check_columns: Vec<BooleanArray>,
    pre_check_slots: Arc<[Option<usize>]>,
    physical_rows: usize,
    num_static_columns: usize,
    expected_columns: usize,
    next_column: usize,
    // Retained arrays and vector capacity drop before their admission.
    memory: MemoryReservation,
}

impl PreparingPhysicalBoolColumns {
    pub(crate) fn try_new(
        num_symbol_ids: usize,
        num_static_columns: usize,
        precheck_count: usize,
        pre_check_slots: Arc<[Option<usize>]>,
        rows: usize,
        memory: MemoryReservation,
    ) -> Result<Self> {
        let expected_columns = num_static_columns
            .checked_add(precheck_count)
            .ok_or_else(overflow)?;
        memory.try_grow(
            size_of::<MultiBatchBoolColumnsBacking>() + 2 * size_of::<usize>(),
        )?;
        let mut columns = reserved_vec(num_symbol_ids, &memory, "Boolean provider")?;
        columns.resize_with(num_symbol_ids, || None);
        let pre_check_columns =
            reserved_vec(precheck_count, &memory, "Boolean provider")?;
        Ok(Self {
            columns,
            pre_check_columns,
            pre_check_slots,
            physical_rows: rows,
            num_static_columns,
            expected_columns,
            next_column: 0,
            memory,
        })
    }

    pub(crate) fn advance(
        &mut self,
        batches: &BatchCollection,
        symbols: &[SymbolColumn],
        prechecks: &[ResolvedBoolColumn],
    ) -> Result<bool> {
        if batches.num_rows() != self.physical_rows {
            return internal_err!(
                "MATCH_RECOGNIZE Boolean preparation row extent changed"
            );
        }
        if self.next_column == self.expected_columns {
            return Ok(true);
        }
        if self.next_column < self.num_static_columns {
            let symbol = symbols.get(self.next_column).ok_or_else(|| {
                DataFusionError::Internal(
                    "MATCH_RECOGNIZE static Boolean layout changed".into(),
                )
            })?;
            let slot = self.columns.get_mut(symbol.id.index()).ok_or_else(|| {
                DataFusionError::Internal(format!(
                    "MATCH_RECOGNIZE symbol ID {} is outside provider slots",
                    symbol.id.index()
                ))
            })?;
            if slot.is_some() {
                return internal_err!(
                    "MATCH_RECOGNIZE duplicate static Boolean provider slot"
                );
            }
            *slot = Some(concat_column(
                batches,
                symbol.column.index(),
                "symbol",
                &self.memory,
            )?);
        } else {
            let column = prechecks
                .get(self.next_column - self.num_static_columns)
                .ok_or_else(|| {
                    DataFusionError::Internal(
                        "MATCH_RECOGNIZE Boolean precheck layout changed".into(),
                    )
                })?;
            self.pre_check_columns.push(concat_column(
                batches,
                column.index(),
                "pre-check",
                &self.memory,
            )?);
        }
        self.next_column += 1;
        Ok(self.next_column == self.expected_columns)
    }

    pub(crate) fn finish(self) -> Result<Arc<MultiBatchBoolColumnsBacking>> {
        if self.next_column != self.expected_columns {
            return internal_err!(
                "MATCH_RECOGNIZE physical Boolean preparation incomplete"
            );
        }
        Ok(Arc::new(MultiBatchBoolColumnsBacking {
            columns: self.columns,
            pre_check_columns: self.pre_check_columns,
            pre_check_slots: self.pre_check_slots,
            total_rows: self.physical_rows,
            _memory: self.memory,
        }))
    }
}

fn concat_column(
    batches: &BatchCollection,
    index: usize,
    role: &str,
    memory: &MemoryReservation,
) -> Result<BooleanArray> {
    if batches.num_batches() == 0 {
        return Ok(BooleanArray::from(Vec::<bool>::new()));
    }
    if batches.num_batches() == 1 {
        let column = boolean_column_ref(batches.batch(0), index, role)?;
        // The backing can outlive the collection and retains the source buffers.
        memory.try_grow(column.get_buffer_memory_size())?;
        return Ok(column.clone());
    }

    let retained_before = memory.size();
    let result = (|| {
        let scratch_memory = memory.new_empty();
        // Native concat returns a temporary Arc<Array> before the flat owner takes it.
        scratch_memory.try_grow(size_of::<BooleanArray>() + 2 * size_of::<usize>())?;
        let mut refs: Vec<&dyn Array> =
            reserved_vec(batches.num_batches(), &scratch_memory, "Boolean provider")?;
        let mut has_nulls = false;
        for batch_index in 0..batches.num_batches() {
            let column = boolean_column_ref(batches.batch(batch_index), index, role)?;
            has_nulls |= column.null_count() != 0;
            refs.push(column);
        }

        let bytes = batches.num_rows().checked_add(7).ok_or_else(overflow)? / 8;
        let capacity = bytes.checked_add(63).ok_or_else(overflow)? & !63;
        let payload = capacity
            .checked_mul(1 + usize::from(has_nulls))
            .ok_or_else(overflow)?;
        memory.try_grow(payload)?;
        let column = datafusion::arrow::compute::concat(&refs)?
            .as_boolean()
            .clone();
        memory.try_resize(
            retained_before
                .checked_add(column.get_buffer_memory_size())
                .ok_or_else(overflow)?,
        )?;
        Ok(column)
    })();
    if result.is_err() {
        // The failed native result and all scratch owners have already dropped.
        memory.try_resize(retained_before)?;
    }
    result
}

fn overflow() -> DataFusionError {
    DataFusionError::ResourcesExhausted(
        "MATCH_RECOGNIZE Boolean provider size exceeds usize".into(),
    )
}

fn boolean_column_ref<'a>(
    batch: &'a RecordBatch,
    column_idx: usize,
    role: &str,
) -> Result<&'a BooleanArray> {
    let Some(field) = batch.schema_ref().fields().get(column_idx) else {
        return internal_err!(
            "MATCH_RECOGNIZE internal {role} column index {column_idx} is out of bounds for input schema with {} columns",
            batch.num_columns()
        );
    };
    let column = batch.column(column_idx);
    column.as_boolean_opt().ok_or_else(|| {
        DataFusionError::Internal(format!(
            "MATCH_RECOGNIZE internal {role} column '{}' has type {}, expected Boolean",
            field.name(),
            column.data_type()
        ))
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::SymbolId;
    use datafusion::arrow::array::{ArrayRef, BooleanArray, Int32Array};
    use datafusion::arrow::datatypes::{DataType, Field, Schema};
    use datafusion_execution::memory_pool::{
        GreedyMemoryPool, MemoryConsumer, MemoryPool,
    };
    use std::sync::Arc;

    fn make_test_memory(limit: usize) -> (Arc<dyn MemoryPool>, MemoryReservation) {
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(limit));
        let reservation = MemoryConsumer::new("test_consumer").register(&pool);
        (pool, reservation)
    }

    fn make_boolean_batch(cols: Vec<Vec<Option<bool>>>) -> RecordBatch {
        let schema = Arc::new(Schema::new(
            (0..cols.len())
                .map(|i| Field::new(format!("col_{i}"), DataType::Boolean, true))
                .collect::<Vec<_>>(),
        ));
        let arrays: Vec<ArrayRef> = cols
            .into_iter()
            .map(|col| Arc::new(BooleanArray::from(col)) as ArrayRef)
            .collect();
        RecordBatch::try_new(schema, arrays).unwrap()
    }

    #[test]
    fn multiple_batches_concatenate_symbol_and_precheck_values_before_release() {
        let (pool, memory) = make_test_memory(100_000);

        let batch1 = make_boolean_batch(vec![
            vec![Some(true), Some(false)],
            vec![Some(false), Some(true)],
        ]);
        let batch2 = make_boolean_batch(vec![
            vec![Some(true), None],
            vec![Some(false), Some(false)],
        ]);
        let collection = BatchCollection::try_new(
            vec![batch1, batch2],
            Arc::new(Schema::new(vec![
                Field::new("col_0", DataType::Boolean, true),
                Field::new("col_1", DataType::Boolean, true),
            ])),
        )
        .unwrap();

        let symbol = SymbolColumn {
            id: SymbolId::try_new(1, 3).unwrap(),
            column: ResolvedBoolColumn::new_validated(0),
        };
        let precheck = ResolvedBoolColumn::new_validated(1);
        let pre_check_slots: Arc<[Option<usize>]> = Arc::from([None, Some(0)]);

        let mut preparer = PreparingPhysicalBoolColumns::try_new(
            3,
            1,
            1,
            Arc::clone(&pre_check_slots),
            4,
            memory,
        )
        .unwrap();

        assert!(pool.reserved() > 0);

        let complete1 = preparer
            .advance(&collection, std::slice::from_ref(&symbol), &[precheck])
            .unwrap();
        assert!(!complete1);

        let complete2 = preparer
            .advance(&collection, &[symbol], &[precheck])
            .unwrap();
        assert!(complete2);

        assert!(preparer.advance(&collection, &[], &[precheck]).unwrap());

        let backing = preparer.finish().unwrap();
        assert_eq!(backing.num_rows(), 4);

        assert_eq!(
            backing.columns[1].as_ref().unwrap(),
            &BooleanArray::from(vec![Some(true), Some(false), Some(true), None]),
        );
        assert_eq!(
            &backing.pre_check_columns[0],
            &BooleanArray::from(vec![false, true, false, false]),
        );

        assert!(pool.reserved() > 0);
        drop(backing);
        assert_eq!(pool.reserved(), 0);
    }

    #[test]
    fn single_input_views_share_admission_and_retain_the_source() {
        use super::super::symbol_columns::MultiBatchBoolColumns;
        use crate::execution::matching::symbols::BoolColumnProvider;
        let (initial_pool, initial_memory) = make_test_memory(5);
        assert!(matches!(
            PreparingPhysicalBoolColumns::try_new(
                100,
                1,
                1,
                Arc::from([]),
                10,
                initial_memory
            ),
            Err(DataFusionError::ResourcesExhausted(_)),
        ));
        assert_eq!(initial_pool.reserved(), 0);
        const LIMIT: usize = 100_000;
        let (pool, memory) = make_test_memory(LIMIT);
        let batch = make_boolean_batch(vec![vec![
            Some(false),
            Some(true),
            None,
            Some(true),
            Some(false),
        ]])
        .slice(1, 3);
        let collection =
            BatchCollection::try_new(vec![batch.clone()], batch.schema()).unwrap();

        let symbol = SymbolColumn {
            id: SymbolId::try_new(1, 2).unwrap(),
            column: ResolvedBoolColumn::new_validated(0),
        };
        let mut preparer =
            PreparingPhysicalBoolColumns::try_new(2, 1, 0, Arc::from([]), 3, memory)
                .unwrap();

        let before = pool.reserved();
        let buffer_bytes = batch.column(0).get_buffer_memory_size();
        let competitor = MemoryConsumer::new("competitor").register(&pool);
        competitor
            .try_grow(LIMIT - before - buffer_bytes + 1)
            .unwrap();
        assert!(matches!(
            preparer.advance(&collection, std::slice::from_ref(&symbol), &[]),
            Err(DataFusionError::ResourcesExhausted(_))
        ));
        assert_eq!(pool.reserved(), before + competitor.size());
        competitor.shrink(1);
        assert!(preparer.advance(&collection, &[symbol], &[]).unwrap());
        assert_eq!(pool.reserved(), LIMIT);
        drop(competitor);
        let backing = preparer.finish().unwrap();
        assert_eq!(backing.num_rows(), 3);
        assert_eq!(
            backing.columns[1].as_ref().unwrap(),
            &BooleanArray::from(vec![Some(true), None, Some(true)])
        );
        let retained = pool.reserved();
        assert_eq!(retained, before + buffer_bytes);
        let first = MultiBatchBoolColumns::for_range(Arc::clone(&backing), 0, 1).unwrap();
        let second =
            MultiBatchBoolColumns::for_range(Arc::clone(&backing), 1, 3).unwrap();
        assert_eq!(pool.reserved(), retained);
        let id = SymbolId::try_new(1, 2).unwrap();
        assert!(first.symbol_is_present(id, &mut |_| Ok(())).unwrap());
        assert!(second.symbol_is_present(id, &mut |_| Ok(())).unwrap());
        drop(collection);
        drop(batch);
        drop(backing);
        drop(first);
        assert_eq!(pool.reserved(), retained);
        assert!(!second.get_bool_with_loc(id, second.locate(0).unwrap()));
        assert!(second.get_bool_with_loc(id, second.locate(1).unwrap()));
        drop(second);
        assert_eq!(pool.reserved(), 0);
    }

    #[test]
    fn boolean_preparation_rejects_wrong_types_and_missing_ordinals() {
        let schema = Arc::new(Schema::new(vec![Field::new(
            "__mr_symbol_a",
            DataType::Int32,
            false,
        )]));
        let batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![Arc::new(Int32Array::from(vec![1, 2])) as ArrayRef],
        )
        .unwrap();
        let collection = BatchCollection::try_new(vec![batch], schema).unwrap();
        for (column, fragment) in [
            (0, "expected Boolean"),
            (1, "is out of bounds for input schema"),
        ] {
            let (_, memory) = make_test_memory(100_000);
            let symbol = SymbolColumn {
                id: SymbolId::try_new(1, 2).unwrap(),
                column: ResolvedBoolColumn::new_validated(column),
            };
            let mut preparer =
                PreparingPhysicalBoolColumns::try_new(2, 1, 0, Arc::from([]), 2, memory)
                    .unwrap();
            let error = preparer
                .advance(&collection, &[symbol], &[])
                .unwrap_err()
                .to_string();
            assert!(error.contains(fragment), "column{column}: {error}");
            if column == 0 {
                assert!(
                    error.contains("__mr_symbol_a") && error.contains("Int32"),
                    "{error}"
                );
            }
        }
    }
}