datafusion-match-recognize 0.55.0

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
// 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.

//! Prepare bounded candidate history batches and encode their observable metadata.

use std::collections::BTreeSet;
use std::hash::BuildHasher;
use std::ops::Range;
use std::sync::Arc;

use datafusion::arrow::array::{
    ArrayRef, BooleanArray, Int64Array, StringBuilder, new_empty_array,
};
use datafusion::arrow::buffer::BooleanBuffer;
use datafusion::arrow::record_batch::{RecordBatch, RecordBatchOptions};
use datafusion::common::{
    DataFusionError, Result, internal_datafusion_err, internal_err,
};
use datafusion::execution::memory_pool::MemoryReservation;
use datafusion_hash_grouped_order::gather::interleave_compact_with_memory;

use crate::core::MatchMetadataColumn;
use crate::execution::common::coordinates::{
    absolute_row_to_usize, checked_match_number,
};
use crate::execution::common::memory::reserved_vec;
use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
use crate::execution::matching::path::{PathNode, PathStep, PathStepEquivalence, Sym};
use crate::execution::storage::collection::BatchCollection;

use super::compiler::{DeferredMetadataColumnOwner, DeferredSchemaColumnPlan};

/// History fields whose values can distinguish Deferred predicates at the same
/// match start and input row. Input rows and sequence numbers already agree.
#[derive(Clone, Debug, Default)]
pub(crate) struct DeferredHistoryProjection {
    pub(crate) symbols: BTreeSet<usize>,
    pub(crate) all_labels: bool,
    pub(crate) exclusions: bool,
    /// Equal row values cannot identify separate volatile evaluation occurrences.
    pub(crate) has_volatile_operations: bool,
}

impl DeferredHistoryProjection {
    pub(crate) fn is_empty(&self) -> bool {
        !self.has_volatile_operations
            && !self.all_labels
            && !self.exclusions
            && self.symbols.is_empty()
    }

    pub(crate) fn extend(&mut self, other: &Self) {
        self.symbols.extend(other.symbols.iter().copied());
        self.all_labels |= other.all_labels;
        self.exclusions |= other.exclusions;
        self.has_volatile_operations |= other.has_volatile_operations;
    }

    fn project(&self, step: &PathStep) -> (Option<usize>, bool) {
        let symbol = step.sym.to_index();
        (
            (self.all_labels || self.symbols.contains(&symbol)).then_some(symbol),
            self.exclusions && step.excluded,
        )
    }

    pub(crate) fn append_fingerprint(&self, previous: u64, step: &PathStep) -> u64 {
        let projected = self.project(step);
        if projected == (None, false) {
            return previous;
        }
        const HASHER: datafusion::common::hash_utils::RandomState =
            datafusion::common::hash_utils::RandomState::with_seed(0);
        HASHER.hash_one((previous, step.row, projected))
    }

    pub(crate) fn equivalent_steps(&self, left: &PathStep, right: &PathStep) -> bool {
        !self.has_volatile_operations
            && left.row == right.row
            && self.project(left) == self.project(right)
    }
}

impl PathStepEquivalence for DeferredHistoryProjection {
    fn equivalent_steps(&self, left: &PathStep, right: &PathStep) -> bool {
        self.equivalent_steps(left, right)
    }
}

#[cfg(test)]
fn ignore_history_work(_units: usize) -> Result<()> {
    Ok(())
}

/// Provider for live path metadata values.
struct PathMetadataProvider<'a> {
    steps: &'a [PathStep],
    num_rows: usize,
    sequence_start: i64,
}

impl PathMetadataProvider<'_> {
    fn match_sequence_number(
        &self,
        memory: &MemoryReservation,
        completed: &mut HistoryWorkReporter<'_>,
    ) -> Result<ArrayRef> {
        let mut values =
            reserved_vec(self.num_rows, memory, "deferred match-sequence metadata")?;
        for start in (0..self.num_rows).step_by(COARSE_WORK_BATCH_SIZE) {
            let end = start
                .saturating_add(COARSE_WORK_BATCH_SIZE)
                .min(self.num_rows);
            for index in start..end {
                let value = if index < self.steps.len() {
                    let offset = i64::try_from(index).map_err(|_| {
                        DataFusionError::ResourcesExhausted(
                            "MATCH_RECOGNIZE match-sequence offset cannot be represented as Int64"
                                .to_string(),
                        )
                    })?;
                    self.sequence_start.checked_add(offset).ok_or_else(|| {
                        DataFusionError::ResourcesExhausted(
                            "MATCH_RECOGNIZE match-sequence number cannot be represented as Int64"
                                .to_string(),
                        )
                    })?
                } else {
                    -1
                };
                values.push(value);
            }
            completed((end - start).max(1))?;
        }
        // Arrow takes ownership of this vector's already-admitted allocation.
        let array = Arc::new(Int64Array::from(values));
        completed(1)?;
        Ok(array)
    }

    fn classifier(
        &self,
        symbol_names: &[String],
        memory: &MemoryReservation,
        completed: &mut HistoryWorkReporter<'_>,
    ) -> Result<ArrayRef> {
        let mut builder = StringBuilder::new();
        for start in (0..self.num_rows).step_by(COARSE_WORK_BATCH_SIZE) {
            let end = start
                .saturating_add(COARSE_WORK_BATCH_SIZE)
                .min(self.num_rows);
            for index in start..end {
                match self.steps.get(index).map(|step| step.sym) {
                    None | Some(Sym::Empty) => builder.append_null(),
                    Some(symbol @ Sym::User(_)) => builder.append_value(
                        symbol_names.get(symbol.to_index()).ok_or_else(|| {
                            internal_datafusion_err!(
                                "MATCH_RECOGNIZE history classifier references unknown symbol index {}",
                                symbol.to_index()
                            )
                        })?,
                    ),
                }
            }
            completed(end - start)?;
        }
        let array: ArrayRef = Arc::new(builder.finish());
        memory.try_grow(array.get_array_memory_size())?;
        Ok(array)
    }

    fn bitmap(
        &self,
        memory: &MemoryReservation,
        completed: &mut HistoryWorkReporter<'_>,
        selected: impl Fn(&PathStep) -> bool,
    ) -> Result<ArrayRef> {
        let bytes = self.num_rows.div_ceil(8);
        let mut bits = reserved_vec::<u8>(bytes, memory, "history metadata bitmap")?;
        bits.resize(bytes, 0);
        for (chunk, steps) in self.steps.chunks(COARSE_WORK_BATCH_SIZE).enumerate() {
            for (offset, step) in steps.iter().enumerate() {
                let row = chunk * COARSE_WORK_BATCH_SIZE + offset;
                if selected(step) {
                    bits[row / 8] |= 1 << (row % 8);
                }
            }
            completed(steps.len().max(1))?;
        }
        let bits = BooleanBuffer::new(bits.into(), 0, self.num_rows);
        Ok(Arc::new(BooleanArray::new(bits, None)))
    }
}

/// Encoder whose metadata and classifier columns were resolved during
/// executable construction.
#[derive(Debug, Clone)]
pub(super) struct MetadataEncoder {
    columns: Arc<[(usize, DeferredMetadataColumnOwner)]>,
    symbol_names: Arc<[String]>,
}

impl MetadataEncoder {
    pub(crate) fn try_new(
        column_plan: &DeferredSchemaColumnPlan,
        symbol_names: &[Option<String>],
    ) -> Result<Self> {
        for &(index, owner) in column_plan.metadata.iter() {
            if let DeferredMetadataColumnOwner::Classifier(symbol) = owner
                && symbol.index() >= symbol_names.len()
            {
                let name = column_plan.schema.field(index).name();
                return datafusion::common::internal_err!(
                    "MATCH_RECOGNIZE classifier-bit column '{name}' references symbol slot {} outside compiled table of length {}",
                    symbol.index(),
                    symbol_names.len()
                );
            }
        }
        let symbol_names: Arc<[String]> = symbol_names
            .iter()
            .map(|name| name.clone().unwrap_or_default())
            .collect::<Vec<_>>()
            .into();
        Ok(Self {
            columns: Arc::clone(&column_plan.metadata),
            symbol_names,
        })
    }

    #[allow(clippy::too_many_arguments)]
    fn encode_metadata(
        &self,
        steps: &[PathStep],
        match_number: u64,
        path_id: i64,
        num_rows: usize,
        sequence_start: i64,
        memory: &MemoryReservation,
        completed: &mut HistoryWorkReporter<'_>,
    ) -> Result<Vec<ArrayRef>> {
        let provider = PathMetadataProvider {
            steps,
            num_rows,
            sequence_start,
        };
        let mut columns = Vec::with_capacity(self.columns.len());
        for &(_, owner) in self.columns.iter() {
            let array = match owner {
                DeferredMetadataColumnOwner::Metadata(column) => match column {
                    MatchMetadataColumn::PathId | MatchMetadataColumn::MatchNumber => {
                        let value = if column == MatchMetadataColumn::PathId {
                            path_id
                        } else {
                            checked_match_number(match_number)?
                        };
                        let mut values =
                            reserved_vec(num_rows, memory, "constant history metadata")?;
                        values.resize(num_rows, value);
                        let array: ArrayRef = Arc::new(Int64Array::from(values));
                        completed(num_rows.max(1))?;
                        array
                    }
                    MatchMetadataColumn::MatchSequenceNumber => {
                        provider.match_sequence_number(memory, completed)?
                    }
                    MatchMetadataColumn::Classifier => {
                        provider.classifier(&self.symbol_names, memory, completed)?
                    }
                    MatchMetadataColumn::Excluded => {
                        provider.bitmap(memory, completed, |step| step.excluded)?
                    }
                },
                DeferredMetadataColumnOwner::Classifier(symbol) => {
                    let symbol = Sym::from_index(symbol.index());
                    provider.bitmap(memory, completed, |step| step.sym == symbol)?
                }
            };
            columns.push(array);
            completed(1)?;
        }

        completed(self.columns.len().max(1))?;
        Ok(columns)
    }

    #[cfg(test)]
    fn encode_metadata_with_work(
        &self,
        steps: &[PathStep],
        match_number: u64,
        path_id: i64,
        num_rows: usize,
        sequence_start: i64,
        completed: &mut HistoryWorkReporter<'_>,
    ) -> Result<Vec<ArrayRef>> {
        let memory = crate::execution::common::memory::new_unbounded_state_memory();
        self.encode_metadata(
            steps,
            match_number,
            path_id,
            num_rows,
            sequence_start,
            &memory,
            completed,
        )
    }
}

type HistoryWorkReporter<'a> = dyn FnMut(usize) -> Result<()> + 'a;
fn capacity_error() -> DataFusionError {
    DataFusionError::ResourcesExhausted("Deferred history capacity exceeds usize".into())
}

#[derive(Debug)]
pub(super) struct PreparedHistoryBatch {
    pub(crate) batch: RecordBatch,
    pub(crate) predicate_row: Option<usize>,
    pub(crate) memory: MemoryReservation,
}

/// Owns gathering, metadata, and final column assembly across bounded advances.
/// Arrays precede their reservations so cancellation releases buffers first.
#[derive(Debug)]
pub(super) struct HistoryPreparation {
    indices: Vec<usize>,
    source_batches: Vec<usize>,
    interleave_indices: Vec<(usize, usize)>,
    columns: Vec<ArrayRef>,
    metadata: std::vec::IntoIter<ArrayRef>,
    head: usize,
    rows: usize,
    predicate_row: Option<usize>,
    // All owned arrays and scratch precede their single reservation.
    memory: MemoryReservation,
}

impl HistoryPreparation {
    /// Admit one bounded part of a proposed path in chronological order.
    /// The scanner records ancestry newest-first. Following rows carry no
    /// match label, sequence number or exclusion, even when they share a batch.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn candidate_chunk(
        plan: &DeferredSchemaColumnPlan,
        collection: &BatchCollection,
        encoder: &MetadataEncoder,
        arena: &[PathNode],
        reversed: &[u32],
        following: Range<usize>,
        candidate: u32,
        match_number: u64,
        head: usize,
        partition_end: usize,
        memory: &MemoryReservation,
        completed: &mut HistoryWorkReporter<'_>,
    ) -> Result<Self> {
        let end = head
            .checked_add(collection.num_rows())
            .ok_or_else(capacity_error)?;
        if partition_end < head
            || partition_end > end
            || (!following.is_empty()
                && (following.start < head || following.end > partition_end))
        {
            return datafusion::common::internal_err!(
                "candidate history outside logical partition"
            );
        }
        let memory = memory.new_empty();
        let count = reversed
            .len()
            .checked_add(following.len())
            .ok_or_else(capacity_error)?;
        debug_assert!(count <= COARSE_WORK_BATCH_SIZE);
        let mut steps = Vec::with_capacity(reversed.len());
        let mut indices = Vec::with_capacity(count);
        let mut sequence = 1;
        let mut predicate_row = None;
        for &index in reversed.iter().rev() {
            let node = arena.get(index as usize).ok_or_else(|| {
                datafusion::common::internal_datafusion_err!(
                    "candidate history node outside arena"
                )
            })?;
            let row = absolute_row_to_usize(node.step.row, "history path row")?;
            if !(head..partition_end).contains(&row) {
                return internal_err!("candidate history outside logical partition");
            }
            if steps.is_empty() {
                sequence = i64::from(node.depth) + 1;
            }
            if index == candidate {
                predicate_row = Some(steps.len());
            }
            steps.push(node.step);
            indices.push(row);
        }
        indices.extend(following);
        completed(count.max(1))?;
        let rows = indices.len();
        let metadata_columns = encoder.encode_metadata(
            &steps,
            match_number,
            i64::from(candidate) + 1,
            rows,
            sequence,
            &memory,
            completed,
        )?;
        let mut preparation =
            Self::try_new(plan, indices, metadata_columns, head, memory)?;
        preparation.predicate_row = predicate_row;
        if !plan.input_ordinals.is_empty() {
            // Candidate rows already fit one coarse chunk; locate them now so
            // the next advance can spend its budget assembling columns.
            preparation.locate_rows(collection, completed)?;
        }
        Ok(preparation)
    }

    fn try_new(
        plan: &DeferredSchemaColumnPlan,
        indices: Vec<usize>,
        metadata: Vec<ArrayRef>,
        head: usize,
        memory: MemoryReservation,
    ) -> Result<Self> {
        let rows = indices.len();
        Ok(Self {
            indices,
            source_batches: Vec::new(),
            interleave_indices: Vec::new(),
            columns: Vec::with_capacity(plan.schema.fields().len()),
            metadata: metadata.into_iter(),
            head,
            rows,
            predicate_row: None,
            memory,
        })
    }

    fn locate_rows(
        &mut self,
        collection: &BatchCollection,
        completed: &mut HistoryWorkReporter<'_>,
    ) -> Result<()> {
        let stop =
            (self.interleave_indices.len() + COARSE_WORK_BATCH_SIZE).min(self.rows);
        while self.interleave_indices.len() < stop {
            let position = self.interleave_indices.len();
            let row = self.indices[position];
            let local = row.checked_sub(self.head).ok_or_else(|| {
                internal_datafusion_err!(
                    "history row {row} precedes collection head {}",
                    self.head
                )
            })?;
            if local >= collection.num_rows() {
                return internal_err!(
                    "history row {row} is outside a collection with head {} and {} rows",
                    self.head,
                    collection.num_rows()
                );
            }
            // locate_with_work already reports this work and cancellation.
            let (batch, offset) = collection.locate_with_work(local, completed)?;
            // Keep one source per used batch: interleave concatenates dictionary
            // values, including nested dictionaries, for every source entry.
            // Chronological paths reuse the last entry directly; arbitrary
            // coordinates search only this bounded chunk's selected batches.
            let source = if self.source_batches.last() == Some(&batch) {
                self.source_batches.len() - 1
            } else if let Some(source) =
                self.source_batches.iter().position(|&used| used == batch)
            {
                source
            } else {
                let source = self.source_batches.len();
                self.source_batches.push(batch);
                source
            };
            self.interleave_indices.push((source, offset));
        }
        Ok(())
    }

    pub(crate) fn advance(
        &mut self,
        plan: &DeferredSchemaColumnPlan,
        collection: &BatchCollection,
        completed: &mut HistoryWorkReporter<'_>,
    ) -> Result<Option<PreparedHistoryBatch>> {
        if !plan.input_ordinals.is_empty() && self.interleave_indices.len() < self.rows {
            self.locate_rows(collection, completed)?;
            return Ok(None);
        }
        let width = plan.schema.fields().len();
        for index in (self.columns.len()..width).take(COARSE_WORK_BATCH_SIZE) {
            let metadata_used = plan.metadata.len() - self.metadata.len();
            let array = if plan
                .metadata
                .get(metadata_used)
                .is_some_and(|(slot, _)| *slot == index)
            {
                self.metadata.next().expect("encoded metadata slot")
            } else {
                let source = plan.input_ordinals[index - metadata_used];
                let array = if self.rows == 0 {
                    new_empty_array(plan.schema.field(index).data_type())
                } else {
                    let mut arrays = Vec::with_capacity(self.source_batches.len());
                    for &batch in &self.source_batches {
                        let column =
                            collection.batch(batch).columns().get(source).ok_or_else(
                                || {
                                    internal_datafusion_err!(
                                        "history source column {source} is missing"
                                    )
                                },
                            )?;
                        arrays.push(column.as_ref());
                    }
                    interleave_compact_with_memory(
                        &arrays,
                        &self.interleave_indices,
                        None,
                    )?
                };
                self.memory.try_grow(array.get_array_memory_size())?;
                array
            };
            self.columns.push(array);
            // One opaque Arrow kernel per column, over at most one path chunk.
            completed(self.rows.max(1))?;
        }
        if self.columns.len() < width {
            return Ok(None);
        }
        let batch = RecordBatch::try_new_with_options(
            Arc::clone(&plan.schema),
            std::mem::take(&mut self.columns),
            &RecordBatchOptions::new().with_row_count(Some(self.rows)),
        )?;
        Ok(Some(PreparedHistoryBatch {
            batch,
            predicate_row: self.predicate_row,
            memory: self.memory.take(),
        }))
    }
}

#[cfg(test)]
#[path = "tests/projection.rs"]
mod projection_tests;

#[cfg(test)]
#[path = "tests/encoder.rs"]
mod encoder_tests;

#[cfg(test)]
#[path = "tests/history.rs"]
mod history_tests;

#[cfg(test)]
#[path = "tests/gather.rs"]
mod gather_tests;