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

//! Ordered input is committed to the partition buffer and retained history
//! together. Selection is a separate operation so lookahead can admit data
//! without advancing the physical head being matched.

use crate::execution::common::scheduling::SliceControl;
use crate::execution::matching::PartitionKey;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::task::Poll;

use super::InputBatch;
use datafusion::common::Result;
use datafusion::execution::memory_pool::MemoryReservation;
use datafusion_hash_grouped_order::GroupedBatch;

use crate::execution::common::work::WorkGovernor;
use crate::execution::metrics::PatternMetrics;
use crate::execution::storage::buffer::{
    GroupedRanges, PartitionedBuffer, RawPhysicalHead,
};
use crate::execution::storage::history_buffer::SharedHistoryBuffer;

pub(crate) struct OrderedInput {
    pub(crate) buffer: PartitionedBuffer,
    pub(crate) history: SharedHistoryBuffer,
}

/// One source of physical coordinates for the unified matcher. Admitting lookahead
/// advances history without changing the selected frontier.
pub(crate) struct PhysicalInput {
    pub(crate) classification:
        Option<Arc<crate::execution::classification::MatchAwareClassification>>,
    /// For a compact child, keep ordered history raw and attach derived arrays to
    /// the selected head only after lookahead and replay have finished.
    pub(crate) working_schema: Option<datafusion::arrow::datatypes::SchemaRef>,
    pub(crate) ordered: OrderedInput,
    pub(crate) governor: WorkGovernor,
    pub(crate) slice: SliceControl,
    pub(crate) memory: MemoryReservation,
    pub(crate) selected_end: usize,
    pub(crate) eof: bool,
    abort: Option<Arc<AtomicBool>>,
    selectable: bool,
    consecutive_batches: usize,
    open_group_start: Option<usize>,
}

pub(crate) struct SelectedHead {
    pub(crate) raw: RawPhysicalHead,
    pub(crate) origin: usize,
    pub(crate) end: usize,
    pub(crate) memory: MemoryReservation,
}

impl PhysicalInput {
    pub(crate) fn new(
        ordered: OrderedInput,
        governor: WorkGovernor,
        slice: SliceControl,
        memory: MemoryReservation,
        abort: Option<Arc<AtomicBool>>,
    ) -> Self {
        Self {
            classification: None,
            working_schema: None,
            ordered,
            governor,
            slice,
            memory,
            abort,
            selected_end: 0,
            eof: false,
            selectable: false,
            consecutive_batches: 0,
            open_group_start: None,
        }
    }

    pub(super) async fn admit(
        &mut self,
        batch: Option<InputBatch>,
        metrics: &PatternMetrics,
    ) -> Result<()> {
        let Some(batch) = batch else {
            if self.open_group_start.is_some() {
                return datafusion::common::internal_err!(
                    "MATCH_RECOGNIZE grouped input ended inside an incomplete partition"
                );
            }
            self.eof = true;
            return Ok(());
        };
        // Bind leases first so early errors and cancellation drop their data first.
        let (shared_backing, range_memory, batch, ranges) = match batch {
            InputBatch::Ordered(batch, backing) => (backing, None, batch, None),
            InputBatch::Grouped(
                GroupedBatch {
                    batch,
                    partition_ranges,
                },
                backing,
                range_memory,
            ) => (backing, range_memory, batch, Some(partition_ranges)),
        };
        if batch.num_rows() == 0
            && ranges.as_ref().is_some_and(|ranges| !ranges.is_empty())
        {
            return datafusion::common::internal_err!(
                "MATCH_RECOGNIZE empty grouped batch contains partition ranges"
            );
        }
        if batch.num_rows() != 0 {
            metrics.input_batches.add(1);
            metrics.input_rows.add(batch.num_rows());
            // Charge slice Array objects before classification or grouped validation
            // can suspend; shared_backing covers only the original arrays/buffers.
            let memory = self
                .ordered
                .history
                .admit_input(&batch, shared_backing.is_some())?;
            // Move the batch into this scope so it drops before its admission lease.
            let batch = batch;
            // Retain the raw view across classification so final accounting can
            // distinguish shared input buffers from newly allocated arrays.
            let shared_source = if shared_backing.is_some() {
                memory.try_grow(
                    batch.num_columns() * size_of::<datafusion::arrow::array::ArrayRef>(),
                )?;
                Some(batch.clone())
            } else {
                None
            };
            let batch = if let Some(classifier) = self
                .classification
                .clone()
                .filter(|c| self.working_schema.is_none() && !c.needs_neighbors())
            {
                let replacements =
                    classifier.prepare(&batch, self, &memory, None).await?;
                let (schema, mut columns, _) = batch.into_parts();
                for (index, array) in replacements {
                    columns[index] = array;
                }
                let batch = datafusion::arrow::record_batch::RecordBatch::try_new(
                    schema, columns,
                )?;
                if shared_backing.is_none() {
                    SharedHistoryBuffer::resize_input_admission(&batch, &memory, false)?;
                }
                batch
            } else {
                batch
            };
            let grouped = ranges
                .map(|ranges| {
                    GroupedRanges::admit(
                        ranges,
                        self.ordered.history.end_index(),
                        self.open_group_start,
                        &memory,
                        range_memory,
                    )
                })
                .transpose()?;
            let aborted = || {
                self.abort
                    .as_ref()
                    .is_some_and(|signal| signal.load(Ordering::Acquire))
            };
            let (same_key, open_group_start) = self
                .ordered
                .buffer
                .admit_ordered_input(
                    batch,
                    memory,
                    shared_backing,
                    shared_source,
                    grouped,
                    &mut self.ordered.history,
                    &mut self.governor,
                    &self.slice,
                    aborted,
                )
                .await?;
            self.open_group_start = open_group_start;
            let buffer = &self.ordered.buffer;
            self.selectable |=
                buffer.is_full() || (!same_key && buffer.has_partition_by());
        } else {
            self.governor.record_completed(1, || {
                self.abort
                    .as_ref()
                    .is_some_and(|signal| signal.load(Ordering::Acquire))
            })?;
        }
        self.consecutive_batches += 1;
        let policy = self.slice.current_policy();
        if self.consecutive_batches == super::READY_INPUT_BATCHES_PER_YIELD
            || self.governor.take_yield_if_due(policy)
        {
            self.consecutive_batches = 0;
            self.slice.yield_once().await;
        }
        Ok(())
    }

    pub(super) async fn select(
        &mut self,
        open_tail: Option<&PartitionKey>,
    ) -> Result<Poll<Option<SelectedHead>>> {
        if self.selectable || self.eof {
            let aborted = || {
                self.abort
                    .as_ref()
                    .is_some_and(|signal| signal.load(Ordering::Acquire))
            };
            let (raw, memory) = self
                .ordered
                .buffer
                .select_head(
                    self.eof,
                    open_tail,
                    self.memory.new_empty(),
                    &mut self.governor,
                    &self.slice,
                    aborted,
                )
                .await?;
            if let Some(raw) = raw {
                let origin = self.selected_end;
                self.selected_end =
                    origin.checked_add(raw.num_rows()).ok_or_else(|| {
                        datafusion::common::DataFusionError::ResourcesExhausted(
                            "MATCH_RECOGNIZE physical head end exceeds usize".into(),
                        )
                    })?;
                self.selectable = self.ordered.buffer.buffered_rows() != 0;
                return Ok(Poll::Ready(Some(SelectedHead {
                    raw,
                    origin,
                    end: self.selected_end,
                    memory,
                })));
            }
            self.selectable = false;
        }
        Ok(if self.eof {
            Poll::Ready(None)
        } else {
            Poll::Pending
        })
    }

    pub(crate) async fn chunks<T>(
        &mut self,
        mut advance: impl FnMut(
            &mut OrderedInput,
            &mut dyn FnMut(usize) -> Result<()>,
        ) -> Result<Option<T>>,
    ) -> Result<T> {
        let aborted = || {
            self.abort
                .as_ref()
                .is_some_and(|signal| signal.load(Ordering::Acquire))
        };
        let mut policy = self.slice.current_policy();
        loop {
            if let Some(value) = advance(&mut self.ordered, &mut |units| {
                self.governor.record_completed(units, aborted)
            })? {
                return Ok(value);
            }
            if self.governor.take_yield_if_due(policy) {
                self.slice.yield_once().await;
                policy = self.slice.current_policy();
            }
        }
    }

    pub(crate) async fn record_work(&mut self, units: usize) -> Result<()> {
        self.governor.record_completed(units, || {
            self.abort
                .as_ref()
                .is_some_and(|signal| signal.load(Ordering::Acquire))
        })?;
        if self.governor.take_yield_if_due(self.slice.current_policy()) {
            self.slice.yield_once().await;
        }
        Ok(())
    }

    pub(crate) async fn prune(&mut self, floor: usize) -> Result<()> {
        let floor = floor.min(self.selected_end);
        self.chunks(|ordered, work| {
            Ok(ordered.history.prune_chunk(floor, work)?.then_some(()))
        })
        .await
    }
}

#[cfg(test)]
mod tests;

#[cfg(test)]
mod admission_drop_tests {
    use super::*;
    use crate::execution::classification::{
        MatchAwareClassification, StaticClassification, StaticRule,
    };
    use datafusion::arrow::array::{Array, ArrayRef, Int32Array};
    use datafusion::arrow::record_batch::RecordBatch;
    use datafusion::common::{DataFusionError, ScalarValue};
    use datafusion::execution::memory_pool::{
        GreedyMemoryPool, MemoryConsumer, MemoryLimit, MemoryPool,
    };
    use datafusion::logical_expr::Operator;
    use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
    use datafusion_hash_grouped_order::PartitionRange;
    use std::fmt::{Display, Formatter};
    use std::num::NonZeroUsize;
    use std::sync::Weak;
    use std::sync::atomic::AtomicUsize;

    #[derive(Debug)]
    struct ObservedPool {
        inner: GreedyMemoryPool,
        source: Weak<dyn Array>,
        armed: AtomicBool,
        fail_at: AtomicUsize,
        grows: AtomicUsize,
        releases: AtomicUsize,
        premature_release: AtomicBool,
    }

    impl Display for ObservedPool {
        fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
            Display::fmt(&self.inner, formatter)
        }
    }

    impl MemoryPool for ObservedPool {
        fn name(&self) -> &str {
            self.inner.name()
        }
        fn grow(&self, reservation: &MemoryReservation, additional: usize) {
            self.inner.grow(reservation, additional);
        }
        fn shrink(&self, reservation: &MemoryReservation, bytes: usize) {
            if self.armed.load(Ordering::Relaxed) {
                self.releases.fetch_add(1, Ordering::Relaxed);
                if self.source.strong_count() != 0 {
                    self.premature_release.store(true, Ordering::Relaxed);
                }
            }
            self.inner.shrink(reservation, bytes);
        }
        fn try_grow(
            &self,
            reservation: &MemoryReservation,
            additional: usize,
        ) -> Result<()> {
            let attempt = self.grows.fetch_add(1, Ordering::Relaxed) + 1;
            if attempt == self.fail_at.load(Ordering::Relaxed) {
                return Err(DataFusionError::ResourcesExhausted(
                    "injected admission denial".into(),
                ));
            }
            self.inner.try_grow(reservation, additional)
        }
        fn reserved(&self) -> usize {
            self.inner.reserved()
        }
        fn memory_limit(&self) -> MemoryLimit {
            self.inner.memory_limit()
        }
    }

    #[tokio::test]
    async fn admission_error_and_cancellation_drop_arrays_before_leases() -> Result<()> {
        // Deny input admission, the shared-source clone, or the finished lane array;
        // otherwise cancel while classification is suspended before publication.
        for fail_at in [1, 2, 3, usize::MAX] {
            let batch = RecordBatch::try_from_iter([
                (
                    "value",
                    Arc::new(Int32Array::from(vec![7; 1024])) as ArrayRef,
                ),
                (
                    "lane",
                    Arc::new(datafusion::arrow::array::UInt64Array::from(vec![0; 1024]))
                        as ArrayRef,
                ),
            ])?;
            let source = Arc::downgrade(batch.column(0));
            let pool = Arc::new(ObservedPool {
                inner: GreedyMemoryPool::new(1 << 20),
                source: source.clone(),
                armed: AtomicBool::new(false),
                fail_at: AtomicUsize::new(usize::MAX),
                grows: AtomicUsize::new(0),
                releases: AtomicUsize::new(0),
                premature_release: AtomicBool::new(false),
            });
            let native_pool: Arc<dyn MemoryPool> = pool.clone();
            let memory =
                MemoryConsumer::new("ordered-input-drop-test").register(&native_pool);
            let schema = batch.schema();
            let mut input = PhysicalInput::new(
                OrderedInput {
                    buffer: PartitionedBuffer::new(Arc::clone(&schema), vec![], 1),
                    history: SharedHistoryBuffer::new(schema, memory.new_empty()),
                },
                WorkGovernor::default(),
                SliceControl::for_test_budget(NonZeroUsize::MIN),
                memory,
                None,
            );
            input.classification = Some(Arc::new(MatchAwareClassification {
                demanded: vec![],
                offsets_only_demanded: false,
                classifier: Arc::new(
                    StaticClassification::for_predicates(vec![StaticRule::Literal(
                        0,
                        Operator::Eq,
                        ScalarValue::Int32(Some(7)),
                    )])
                    .unwrap(),
                ),
                predicates: vec![],
                eager: 0,
                lane_column: Some(1),
                required: 0,
            }));
            let baseline = pool.reserved();
            let backing = input.memory.new_empty();
            backing.try_grow(batch.get_array_memory_size())?;
            let ranges = vec![PartitionRange {
                start: 0,
                end: 1024,
                is_complete: true,
            }];
            let range_memory = input.memory.new_empty();
            range_memory.try_grow(ranges.capacity() * size_of::<PartitionRange>())?;
            let batch = InputBatch::Grouped(
                GroupedBatch {
                    batch,
                    partition_ranges: ranges,
                },
                Some(Arc::new(backing)),
                Some(range_memory),
            );
            pool.grows.store(0, Ordering::Relaxed);
            pool.fail_at.store(fail_at, Ordering::Relaxed);
            pool.armed.store(true, Ordering::Relaxed);
            let metrics = PatternMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
            let mut admitting = Box::pin(input.admit(Some(batch), &metrics));
            if fail_at == usize::MAX {
                assert!(futures::poll!(admitting.as_mut()).is_pending());
                assert!(source.strong_count() > 0);
                assert_eq!(pool.releases.load(Ordering::Relaxed), 0);
            } else {
                assert!(matches!(
                    admitting.as_mut().await,
                    Err(DataFusionError::ResourcesExhausted(_))
                ));
                assert_eq!(pool.grows.load(Ordering::Relaxed), fail_at);
            }
            drop(admitting);
            pool.armed.store(false, Ordering::Relaxed);
            assert!(pool.releases.load(Ordering::Relaxed) > 0);
            assert!(
                !pool.premature_release.load(Ordering::Relaxed),
                "failure point {fail_at}"
            );
            assert!(source.upgrade().is_none());
            assert_eq!(pool.reserved(), baseline);
            assert_eq!(input.ordered.history.end_index(), 0);
            assert_eq!(input.ordered.buffer.buffered_rows(), 0);
        }
        Ok(())
    }
}