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

//! Typed pending-output rows and checked Arrow gather planning.

mod builder;
mod encoder;

pub(super) use builder::{OutputBatchBuilder, VIRTUAL_DEFAULT_COORD};
pub(crate) use encoder::{
    CheckedSelectedPath, SelectedPathFillOrder, SelectedPathValidation,
    SelectedPathValidator,
};
pub(super) use encoder::{
    EncodedOutputRow, MatchRowPhase, MatchRowProgress, MatchRowsEncoder,
    validate_emission_extent,
};

use crate::core::{AbsoluteRow, PhysicalRowCount};
use datafusion::arrow::array::ArrayRef;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::{DataFusionError, Result};
use datafusion::execution::memory_pool::MemoryReservation;
use std::collections::VecDeque;

struct PendingBatch {
    batch: RecordBatch,
    _memory: MemoryReservation,
}

/// Accounted output retained until the downstream stream consumes it.
/// Moving batches between queues transfers their native reservations.
pub(crate) struct PendingOutput {
    batches: VecDeque<PendingBatch>,
    memory: MemoryReservation,
}

impl PendingOutput {
    pub(crate) fn new(memory: MemoryReservation) -> Self {
        Self {
            batches: VecDeque::new(),
            memory,
        }
    }

    pub(crate) fn new_empty(&self) -> Self {
        Self::new(self.memory.new_empty())
    }
    pub(crate) fn len(&self) -> usize {
        self.batches.len()
    }
    pub(crate) fn is_empty(&self) -> bool {
        self.batches.is_empty()
    }
    #[cfg(test)]
    pub(crate) fn iter(&self) -> impl Iterator<Item = &RecordBatch> {
        self.batches.iter().map(|entry| &entry.batch)
    }
    pub(crate) fn pop_front(&mut self) -> Option<RecordBatch> {
        self.batches.pop_front().map(|entry| entry.batch)
    }

    #[cfg(test)]
    pub(crate) fn clear(&mut self) {
        self.batches = VecDeque::new();
        self.memory.free();
    }

    pub(crate) fn try_reserve(&mut self, additional: usize) -> Result<()> {
        let required = self.len().checked_add(additional).ok_or_else(|| {
            resource_error("pending output queue length overflow".into())
        })?;
        if required <= self.batches.capacity() {
            return Ok(());
        }
        let capacity = self
            .batches
            .capacity()
            .checked_mul(2)
            .ok_or_else(|| {
                resource_error("pending output queue capacity overflow".into())
            })?
            .max(required);
        let bytes = capacity
            .checked_mul(size_of::<PendingBatch>())
            .ok_or_else(|| {
                resource_error("pending output queue byte size overflow".into())
            })?;
        let memory = self.memory.new_empty();
        memory.try_grow(bytes)?;
        let mut replacement = VecDeque::new();
        replacement.try_reserve_exact(capacity).map_err(|error| {
            resource_error(format!(
                "pending output queue could not reserve {capacity} batches: {error}"
            ))
        })?;
        memory.try_resize(
            replacement
                .capacity()
                .checked_mul(size_of::<PendingBatch>())
                .ok_or_else(|| {
                    resource_error("pending output queue allocation size overflow".into())
                })?,
        )?;
        replacement.append(&mut self.batches);
        let old_batches = std::mem::replace(&mut self.batches, replacement);
        let old_memory = std::mem::replace(&mut self.memory, memory);
        drop(old_batches);
        drop(old_memory);
        Ok(())
    }

    pub(crate) fn push_back(&mut self, batch: RecordBatch) -> Result<()> {
        self.try_reserve(1)?;
        let memory = self.memory.new_empty();
        // Assembly releases its column-vector charge after staging this batch.
        let bytes = batch
            .num_columns()
            .checked_mul(size_of::<ArrayRef>())
            .and_then(|handles| batch.get_array_memory_size().checked_add(handles))
            .ok_or_else(|| {
                resource_error("pending output batch byte size overflow".into())
            })?;
        memory.try_grow(bytes)?;
        self.batches.push_back(PendingBatch {
            batch,
            _memory: memory,
        });
        Ok(())
    }

    pub(crate) fn prepare_append(&mut self, staged: &Self) -> Result<()> {
        if self.is_empty() {
            Ok(())
        } else {
            self.try_reserve(staged.len())
        }
    }

    /// Empty destinations take ownership of the admitted queue allocation.
    /// Other destinations reserve capacity at the publication gate.
    pub(crate) fn append(&mut self, staged: &mut Self) {
        if staged.is_empty() {
            return;
        }
        if self.is_empty() {
            std::mem::swap(self, staged);
            return;
        }
        assert!(self.batches.capacity() - self.len() >= staged.len());
        self.batches.append(&mut staged.batches);
    }
}

impl std::ops::Index<usize> for PendingOutput {
    type Output = RecordBatch;
    fn index(&self, index: usize) -> &Self::Output {
        &self.batches[index].batch
    }
}

#[cfg(test)]
impl From<PendingOutput> for Vec<RecordBatch> {
    fn from(mut output: PendingOutput) -> Self {
        std::iter::from_fn(|| output.pop_front()).collect()
    }
}

#[cfg(test)]
impl Default for PendingOutput {
    fn default() -> Self {
        Self::new(
            crate::execution::common::memory::new_unbounded_state_memory().new_empty(),
        )
    }
}

/// Incrementally validated source-relative coordinates for one Arrow output flush.
///
/// Validation retains only a contiguous range and cardinality. The output
/// builder owns the row descriptors until gathering completes; copying resolves
/// those descriptors again rather than retaining a second coordinate vector.
/// The accumulator remains unchanged if validation fails partway through.
#[derive(Debug)]
pub(super) struct GatherPlan {
    rows: usize,
    contiguous_start: Option<usize>,
    source_origin: AbsoluteRow,
    source_end: AbsoluteRow,
}

impl GatherPlan {
    pub(super) fn try_empty(
        source_origin: AbsoluteRow,
        source_rows: usize,
    ) -> Result<Self> {
        let source_rows_u64 = u64::try_from(source_rows).map_err(|_| {
            resource_error(format!(
                "source row count {source_rows} cannot be represented as u64"
            ))
        })?;
        let source_end = source_origin
            .checked_add(PhysicalRowCount::new(source_rows_u64))
            .ok_or_else(|| {
                resource_error(format!(
                    "absolute source extent overflows at origin {source_origin} with {source_rows} rows"
                ))
            })?;

        Ok(Self {
            rows: 0,
            contiguous_start: None,
            source_origin,
            source_end,
        })
    }

    pub(super) fn relative_input_row(&self, row: AbsoluteRow) -> Result<usize> {
        let Some(relative) = row.checked_offset_from(self.source_origin) else {
            return Err(invariant_error(format!(
                "output input row {row} precedes source origin {}",
                self.source_origin
            )));
        };
        if row >= self.source_end {
            return Err(invariant_error(format!(
                "output input row {row} is outside source extent {}..{}",
                self.source_origin, self.source_end
            )));
        }
        usize::try_from(relative.as_u64()).map_err(|_| {
            resource_error(format!(
                "source-relative output row {} cannot be represented as usize on this platform",
                relative.as_u64()
            ))
        })
    }

    pub(super) fn try_push(&mut self, row: AbsoluteRow) -> Result<()> {
        let rows = self
            .rows
            .checked_add(1)
            .ok_or_else(|| resource_error("output row count exceeds usize".into()))?;
        let relative = self.relative_input_row(row)?;
        let contiguous_start = if self.rows == 0 {
            Some(relative)
        } else {
            self.contiguous_start
                .filter(|&start| start.checked_add(self.rows) == Some(relative))
        };
        self.contiguous_start = contiguous_start;
        self.rows = rows;
        Ok(())
    }

    pub(super) fn len(&self) -> usize {
        self.rows
    }

    /// The first coordinate of an uninterrupted physical input range.
    /// Batch resolution separately checks that the range fits one Arrow batch.
    pub(super) fn contiguous_input_start(&self) -> Option<usize> {
        self.contiguous_start
    }
}

fn invariant_error(message: String) -> DataFusionError {
    DataFusionError::Internal(format!("MATCH_RECOGNIZE gather invariant: {message}"))
}

fn resource_error(message: String) -> DataFusionError {
    DataFusionError::ResourcesExhausted(format!(
        "MATCH_RECOGNIZE gather resource limit: {message}"
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pending_output_transfers_charges_and_rejects_unadmitted_batches() {
        use datafusion::arrow::array::Int32Array;
        use datafusion::arrow::datatypes::{DataType, Field, Schema};
        use datafusion::execution::memory_pool::{
            GreedyMemoryPool, MemoryConsumer, MemoryPool,
        };
        use std::sync::Arc;

        let batch = RecordBatch::try_new(
            Arc::new(Schema::new(vec![Field::new(
                "value",
                DataType::Int32,
                false,
            )])),
            vec![Arc::new(Int32Array::from(vec![1; 3]))],
        )
        .unwrap();
        for occupied_destination in [false, true] {
            let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(4096));
            let mut published = PendingOutput::new(
                MemoryConsumer::new("output-publication-test").register(&pool),
            );
            let mut expected = Vec::new();
            if occupied_destination {
                published.push_back(batch.slice(0, 1)).unwrap();
                expected.push(batch.slice(0, 1));
            }
            let mut staged = published.new_empty();
            staged.push_back(batch.clone()).unwrap();
            expected.push(batch.clone());
            let before_preparation = pool.reserved();
            published.prepare_append(&staged).unwrap();
            let admitted = pool.reserved();
            if !occupied_destination {
                assert_eq!(admitted, before_preparation);
            }
            published.append(&mut staged);
            assert!(staged.is_empty());
            assert_eq!(
                pool.reserved(),
                admitted,
                "publication must transfer, not readmit"
            );
            let staging_slots = staged.memory.size();
            staged.clear();
            assert_eq!(pool.reserved(), admitted - staging_slots);
            for expected in expected {
                let before = pool.reserved();
                assert_eq!(published.pop_front().unwrap(), expected);
                assert_eq!(
                    pool.reserved(),
                    before
                        - expected.get_array_memory_size()
                        - expected.num_columns() * size_of::<ArrayRef>()
                );
            }
            assert!(published.pop_front().is_none());
            // A stream keeps the empty staging owner across publications.
            // Both queue allocations stay charged after their batches drain.
            for _ in 0..3 {
                staged.push_back(batch.clone()).unwrap();
                published.prepare_append(&staged).unwrap();
                published.append(&mut staged);
                assert!(staged.is_empty());
                assert_eq!(published.pop_front().unwrap(), batch);
                assert_eq!(
                    pool.reserved(),
                    published.memory.size() + staged.memory.size()
                );
            }
            drop((published, staged));
            assert_eq!(pool.reserved(), 0);
        }

        let pool: Arc<dyn MemoryPool> =
            Arc::new(GreedyMemoryPool::new(size_of::<PendingBatch>()));
        let mut queue =
            PendingOutput::new(MemoryConsumer::new("denied-output-test").register(&pool));
        queue.try_reserve(1).unwrap();
        let admitted = pool.reserved();
        assert!(matches!(
            queue.push_back(batch),
            Err(DataFusionError::ResourcesExhausted(_))
        ));
        assert!(queue.is_empty());
        assert_eq!(
            pool.reserved(),
            admitted,
            "denied array charge must not leak"
        );
        queue.clear();
        assert_eq!(pool.reserved(), 0);
    }

    #[test]
    fn pending_output_accounts_for_wide_batch_column_handles() {
        use datafusion::arrow::array::NullArray;
        use datafusion::arrow::datatypes::{DataType, Field, Schema};
        use datafusion::execution::memory_pool::{
            GreedyMemoryPool, MemoryConsumer, MemoryPool,
        };
        use std::sync::Arc;

        let width = 256;
        let schema = Arc::new(Schema::new(
            (0..width)
                .map(|column| Field::new(format!("c{column}"), DataType::Null, true))
                .collect::<Vec<_>>(),
        ));
        let columns: Vec<ArrayRef> = (0..width)
            .map(|_| Arc::new(NullArray::new(1)) as ArrayRef)
            .collect();
        let batch = RecordBatch::try_new(schema, columns).unwrap();
        let array_bytes = batch.get_array_memory_size();
        let batch_bytes = array_bytes + width * size_of::<ArrayRef>();
        for admit_handles in [false, true] {
            let limit = size_of::<PendingBatch>()
                + if admit_handles {
                    batch_bytes
                } else {
                    array_bytes
                };
            let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(limit));
            let mut queue = PendingOutput::new(
                MemoryConsumer::new("wide-output-test").register(&pool),
            );
            queue.try_reserve(1).unwrap();
            let queue_bytes = pool.reserved();
            let result = queue.push_back(batch.clone());
            if admit_handles {
                result.unwrap();
                assert_eq!(pool.reserved(), queue_bytes + batch_bytes);
                assert_eq!(queue.pop_front().unwrap(), batch);
            } else {
                assert!(matches!(
                    result,
                    Err(DataFusionError::ResourcesExhausted(_))
                ));
            }
            assert!(queue.is_empty());
            assert_eq!(pool.reserved(), queue_bytes);
            drop(queue);
            assert_eq!(pool.reserved(), 0);
        }
    }

    #[test]
    fn gather_coordinates_preserve_large_absolute_domains() {
        let physical_max = AbsoluteRow::new(u64::from(u32::MAX));
        let late_origin = AbsoluteRow::new(u64::from(u32::MAX) + 10_000);
        for (origin, source_rows, rows, expected) in [
            (physical_max, 1, &[physical_max][..], &[0][..]),
            (
                late_origin,
                3,
                &[late_origin, AbsoluteRow::new(late_origin.as_u64() + 2)][..],
                &[0, 2][..],
            ),
        ] {
            let mut plan = GatherPlan::try_empty(origin, source_rows).unwrap();
            for &row in rows {
                plan.try_push(row).unwrap();
            }
            assert_eq!(plan.len(), rows.len());
            let physical_coordinates = rows
                .iter()
                .map(|row| plan.relative_input_row(*row).unwrap())
                .collect::<Vec<_>>();
            assert_eq!(physical_coordinates, expected);
        }
    }

    #[test]
    fn gather_range_admission_requires_uninterrupted_physical_rows() {
        for (rows, expected) in [
            (vec![1, 2, 3], Some(1)),
            (vec![1, 3, 4], None),
            (vec![1, 1, 2], None),
            (vec![2, 1, 2], None),
        ] {
            let mut plan = GatherPlan::try_empty(AbsoluteRow::new(100), 5).unwrap();
            for row in rows {
                plan.try_push(AbsoluteRow::new(100 + row)).unwrap();
            }
            assert_eq!(plan.len(), 3);
            assert_eq!(plan.contiguous_input_start(), expected);
        }
    }

    #[test]
    fn gather_rejects_outside_rows_without_losing_valid_boundary_rows() {
        let mut plan = GatherPlan::try_empty(AbsoluteRow::new(100), 2).unwrap();
        plan.try_push(AbsoluteRow::new(100)).unwrap();
        for row in [AbsoluteRow::new(99), AbsoluteRow::new(102)] {
            let error = plan.try_push(row).unwrap_err();
            assert!(matches!(error, DataFusionError::Internal(_)));
            assert_eq!(plan.len(), 1);
            assert_eq!(plan.contiguous_input_start(), Some(0));
        }
        plan.try_push(AbsoluteRow::new(101)).unwrap();
        assert_eq!(plan.len(), 2);
        assert_eq!(plan.contiguous_input_start(), Some(0));
    }

    #[test]
    #[cfg(target_pointer_width = "64")]
    fn gather_relative_coordinates_can_exceed_u32() {
        let mut plan =
            GatherPlan::try_empty(AbsoluteRow::ZERO, u32::MAX as usize + 2).unwrap();
        plan.try_push(AbsoluteRow::new(u64::from(u32::MAX) + 1))
            .unwrap();
        assert_eq!(plan.len(), 1);
        assert_eq!(plan.contiguous_input_start(), Some(u32::MAX as usize + 1));
    }

    #[test]
    fn gather_rejects_unrepresentable_source_extents() {
        let error = GatherPlan::try_empty(AbsoluteRow::MAX, 1).unwrap_err();
        assert!(matches!(error, DataFusionError::ResourcesExhausted(message)
            if message.contains("absolute source extent")));
    }
}