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

//! Exact, windowed presence tracking for physical input rows.

use std::collections::VecDeque;
use std::mem::size_of;
#[cfg(test)]
use std::sync::Arc;

use crate::core::AbsoluteRow;
use datafusion::common::{DataFusionError, Result, internal_err};
use datafusion::execution::memory_pool::MemoryReservation;
#[cfg(test)]
use datafusion::execution::memory_pool::{
    MemoryConsumer, MemoryPool, UnboundedMemoryPool,
};

#[cfg(test)]
use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
use crate::execution::common::progress::CoarseWorkBatch;

const BITS_PER_WORD: u64 = u64::BITS as u64;
const WORDS_PER_CHUNK: usize = 64;
const ROWS_PER_CHUNK: u64 = BITS_PER_WORD * WORDS_PER_CHUNK as u64;

#[derive(Debug)]
struct PresenceChunk([u64; WORDS_PER_CHUNK]);

impl PresenceChunk {
    const EMPTY: Self = Self([0; WORDS_PER_CHUNK]);

    fn mark(&mut self, offset: u64) {
        debug_assert!(offset < ROWS_PER_CHUNK);
        let word = usize::try_from(offset / BITS_PER_WORD)
            .expect("a presence-chunk word offset always fits usize");
        let bit = offset % BITS_PER_WORD;
        self.0[word] |= 1_u64 << bit;
    }

    fn contains(&self, offset: u64) -> bool {
        debug_assert!(offset < ROWS_PER_CHUNK);
        let word = usize::try_from(offset / BITS_PER_WORD)
            .expect("a presence-chunk word offset always fits usize");
        let bit = offset % BITS_PER_WORD;
        self.0[word] & (1_u64 << bit) != 0
    }
}

/// Exact membership for matched physical rows in a logical-partition window.
///
/// Chunks cover one contiguous absolute-row window. Missing bits are always
/// false; the structure never drops a mark because of row magnitude or
/// density. Prefixes may be discarded only after their unmatched output is
/// irrevocably finalized. Callers validate that each coordinate is physical;
/// virtual output descriptors never enter this layer.
#[derive(Debug)]
pub(crate) struct RowPresence {
    /// First row that may still be marked or queried by output finalization.
    finalized_before: AbsoluteRow,
    /// Absolute start of the first retained chunk. Always chunk-aligned.
    base_row: Option<AbsoluteRow>,
    /// Fixed-size chunks stored inline so the complete allocated deque capacity
    /// has one precise byte cost.
    chunks: VecDeque<PresenceChunk>,
    /// Accounts the actual allocated chunk slots, including reusable capacity.
    reservation: MemoryReservation,
}

impl RowPresence {
    /// Create exact presence state backed by an empty child reservation.
    pub(crate) fn try_new(reservation: MemoryReservation) -> Result<Self> {
        if reservation.size() != 0 {
            return Err(DataFusionError::Internal(format!(
                "MATCH_RECOGNIZE row-presence reservation must start empty, got {} bytes",
                reservation.size()
            )));
        }
        Ok(Self {
            finalized_before: AbsoluteRow::ZERO,
            base_row: None,
            chunks: VecDeque::new(),
            reservation,
        })
    }

    /// Create the explicit unbounded variant used by tests and benchmarks.
    #[cfg(test)]
    pub(crate) fn try_new_unbounded() -> Result<Self> {
        let pool: Arc<dyn MemoryPool> = Arc::new(UnboundedMemoryPool::default());
        let reservation = MemoryConsumer::new("MatchRowPresence[direct]").register(&pool);
        Self::try_new(reservation)
    }

    /// Mark one physical absolute row as belonging to a selected match.
    #[cfg(test)]
    pub(crate) fn mark(&mut self, row: AbsoluteRow) -> Result<()> {
        let mut completed = |_| Ok(());
        self.mark_with_work(row, &mut completed)
    }

    /// Mark one row while reporting runtime-sized chunk growth in coarse
    /// completed-work batches.
    pub(crate) fn mark_with_work(
        &mut self,
        row: AbsoluteRow,
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<()> {
        if row < self.finalized_before {
            return Err(DataFusionError::Internal(format!(
                "MATCH_RECOGNIZE cannot mark physical row {row} after presence was finalized through {}",
                self.finalized_before
            )));
        }

        let target_base = chunk_base(row);
        let chunk_index = match self.base_row {
            None => {
                self.ensure_capacity(1)?;
                self.chunks.push_back(PresenceChunk::EMPTY);
                self.base_row = Some(target_base);
                0
            }
            Some(base) if target_base < base => {
                return internal_err!(
                    "MATCH_RECOGNIZE cannot mark physical row {row} before retained presence base {base}"
                );
            }
            Some(base) => {
                let target_index = chunk_distance(base, target_base)?;
                let required = target_index
                    .checked_add(1)
                    .ok_or_else(|| resource_error("chunk count exceeds usize"))?;
                self.ensure_capacity(required)?;
                let old_len = self.chunks.len();
                let mut work = CoarseWorkBatch::new(completed);
                while self.chunks.len() < required {
                    self.chunks.push_back(PresenceChunk::EMPTY);
                    if let Err(error) = work.complete_one() {
                        self.chunks.truncate(old_len);
                        return Err(error);
                    }
                }
                if let Err(error) = work.finish() {
                    self.chunks.truncate(old_len);
                    return Err(error);
                }
                target_index
            }
        };
        let offset = row.as_u64() % ROWS_PER_CHUNK;
        self.chunks
            .get_mut(chunk_index)
            .ok_or_else(|| invariant_error("marked row has no retained chunk"))?
            .mark(offset);
        Ok(())
    }

    /// Test whether a physical absolute row belongs to any selected match.
    pub(crate) fn contains(&self, row: AbsoluteRow) -> bool {
        if row < self.finalized_before {
            return false;
        }
        let Some(base) = self.base_row else {
            return false;
        };
        let Some(distance) = row.as_u64().checked_sub(base.as_u64()) else {
            return false;
        };
        let Ok(chunk_index) = usize::try_from(distance / ROWS_PER_CHUNK) else {
            return false;
        };
        let offset = distance % ROWS_PER_CHUNK;
        self.chunks
            .get(chunk_index)
            .is_some_and(|chunk| chunk.contains(offset))
    }

    /// First absolute row whose matched/unmatched status is not finalized.
    pub(crate) const fn first_unfinalized_row(&self) -> AbsoluteRow {
        self.finalized_before
    }

    /// Irrevocably discard membership for rows before `end_exclusive`.
    ///
    /// Repeating or moving an already-finalized boundary backward is a no-op.
    /// Retained deque capacity remains charged and reusable by later chunks.
    #[cfg(test)]
    pub(crate) fn trim_prefix(&mut self, end_exclusive: AbsoluteRow) {
        let mut completed = |_| Ok(());
        self.trim_prefix_with_work(end_exclusive, &mut completed)
            .expect("the no-op row-presence work callback cannot fail");
    }

    /// Trim a finalized prefix while making a cancellation error atomic with
    /// respect to presence membership and its finalized boundary.
    pub(crate) fn trim_prefix_with_work(
        &mut self,
        end_exclusive: AbsoluteRow,
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<()> {
        if end_exclusive <= self.finalized_before {
            return Ok(());
        }

        let Some(base) = self.base_row else {
            self.finalized_before = end_exclusive;
            return Ok(());
        };
        if end_exclusive <= base {
            self.finalized_before = end_exclusive;
            return Ok(());
        }

        let distance = end_exclusive.as_u64() - base.as_u64();
        let removable = usize::try_from(distance / ROWS_PER_CHUNK)
            .unwrap_or(usize::MAX)
            .min(self.chunks.len());
        // Probe the complete front range before mutating the deque. Presence
        // chunks have no destructor, so the subsequent front drain is an
        // infallible metadata commit rather than a second element walk.
        let mut work = CoarseWorkBatch::new(completed);
        for _ in self.chunks.iter().take(removable) {
            work.complete_one()?;
        }
        work.finish()?;
        drop(self.chunks.drain(..removable));

        if self.chunks.is_empty() {
            self.base_row = None;
            self.finalized_before = end_exclusive;
            return Ok(());
        }

        // A non-empty deque proves the quotient was not capped by its length,
        // so the new front is the globally aligned chunk containing the trim
        // boundary. This avoids unchecked coordinate arithmetic.
        self.base_row = Some(chunk_base(end_exclusive));
        // contains and mark both check this floor. Bits below it cannot be
        // observed or reused before the whole front chunk is discarded.
        self.finalized_before = end_exclusive;
        Ok(())
    }

    #[cfg(test)]
    fn retained_chunks(&self) -> usize {
        self.chunks.len()
    }

    #[cfg(test)]
    pub(crate) fn reserved_bytes(&self) -> usize {
        self.reservation.size()
    }

    fn ensure_capacity(&mut self, required_chunks: usize) -> Result<()> {
        if required_chunks <= self.chunks.capacity() {
            return Ok(());
        }

        let previous_bytes = allocation_bytes(self.chunks.capacity())?;
        let doubled = self
            .chunks
            .capacity()
            .checked_mul(2)
            .ok_or_else(|| resource_error("chunk capacity growth overflow"))?;
        let target_capacity = required_chunks
            .max(doubled)
            .max(1)
            .checked_next_power_of_two()
            .ok_or_else(|| resource_error("chunk capacity growth overflow"))?;
        let target_bytes = allocation_bytes(target_capacity)?;
        let delta = target_bytes.saturating_sub(previous_bytes);

        self.reservation
            .try_grow(delta)
            .map_err(|error| resource_error(error.to_string()))?;

        let reserve_additional = target_capacity.saturating_sub(self.chunks.len());
        if let Err(error) = self.chunks.try_reserve_exact(reserve_additional) {
            self.reservation.shrink(delta);
            return Err(resource_error(error.to_string()));
        }

        self.reservation.resize(
            self.chunks
                .capacity()
                .saturating_mul(size_of::<PresenceChunk>()),
        );
        Ok(())
    }
}

fn chunk_base(row: AbsoluteRow) -> AbsoluteRow {
    AbsoluteRow::new(row.as_u64() / ROWS_PER_CHUNK * ROWS_PER_CHUNK)
}

fn chunk_distance(start: AbsoluteRow, end: AbsoluteRow) -> Result<usize> {
    let rows = end
        .as_u64()
        .checked_sub(start.as_u64())
        .ok_or_else(|| invariant_error("presence chunk range is reversed"))?;
    if rows % ROWS_PER_CHUNK != 0 {
        return Err(invariant_error("presence chunk base is not aligned"));
    }
    usize::try_from(rows / ROWS_PER_CHUNK)
        .map_err(|_| resource_error("chunk distance cannot be represented as usize"))
}

fn allocation_bytes(capacity: usize) -> Result<usize> {
    capacity
        .checked_mul(size_of::<PresenceChunk>())
        .ok_or_else(|| resource_error("allocated chunk bytes exceed usize"))
}

fn resource_error(detail: impl std::fmt::Display) -> DataFusionError {
    DataFusionError::ResourcesExhausted(format!(
        "MATCH_RECOGNIZE exact row-presence storage could not grow: {detail}"
    ))
}

fn invariant_error(detail: impl std::fmt::Display) -> DataFusionError {
    DataFusionError::Internal(format!(
        "MATCH_RECOGNIZE row-presence invariant failed: {detail}"
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryPool};

    const MILLION_ROW_NEIGHBORS: [u64; 3] = [999_999, 1_000_000, 1_000_001];

    #[test]
    fn presence_is_exact_at_high_origins_and_word_and_chunk_edges() {
        let mut sparse = RowPresence::try_new_unbounded().unwrap();
        for row in MILLION_ROW_NEIGHBORS {
            sparse.mark(AbsoluteRow::new(row)).unwrap();
        }
        for (row, present) in [
            (999_998, false),
            (999_999, true),
            (1_000_000, true),
            (1_000_001, true),
            (1_000_002, false),
        ] {
            assert_eq!(sparse.contains(AbsoluteRow::new(row)), present);
        }
        for boundary in [BITS_PER_WORD, ROWS_PER_CHUNK] {
            let mut dense = RowPresence::try_new_unbounded().unwrap();
            for row in boundary - 2..=boundary + 1 {
                dense.mark(AbsoluteRow::new(row)).unwrap();
            }
            for row in boundary - 3..=boundary + 2 {
                assert_eq!(
                    dense.contains(AbsoluteRow::new(row)),
                    (boundary - 2..=boundary + 1).contains(&row)
                );
            }
        }
    }

    #[test]
    fn prefix_finalization_reuses_charged_capacity_until_terminal_release() {
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1 << 20));
        let reservation = MemoryConsumer::new("presence-lifetime").register(&pool);
        let mut presence = RowPresence::try_new(reservation).unwrap();
        for row in [0, 4_095, 4_096, 8_193] {
            presence.mark(AbsoluteRow::new(row)).unwrap();
        }
        let charged = pool.reserved();
        assert!(charged >= 3 * size_of::<PresenceChunk>());
        presence.trim_prefix(AbsoluteRow::new(4_096));
        assert!(!presence.contains(AbsoluteRow::ZERO));
        assert!(!presence.contains(AbsoluteRow::new(4_095)));
        assert!(presence.contains(AbsoluteRow::new(4_096)));
        for end in [8_000, 8_000, 7_000] {
            presence.trim_prefix(AbsoluteRow::new(end));
        }
        assert_eq!(presence.first_unfinalized_row(), AbsoluteRow::new(8_000));
        assert!(!presence.contains(AbsoluteRow::new(4_096)));
        assert!(presence.contains(AbsoluteRow::new(8_193)));
        assert!(presence.mark(AbsoluteRow::new(7_999)).is_err());
        presence.trim_prefix(AbsoluteRow::new(3 * ROWS_PER_CHUNK));
        assert_eq!(presence.retained_chunks(), 0);
        assert_eq!(pool.reserved(), charged);
        presence.mark(AbsoluteRow::new(4 * ROWS_PER_CHUNK)).unwrap();
        assert!(presence.contains(AbsoluteRow::new(4 * ROWS_PER_CHUNK)));
        assert_eq!(pool.reserved(), charged);
        drop(presence);
        assert_eq!(pool.reserved(), 0);
    }

    #[test]
    fn row_presence_admission_denial_keeps_empty_and_populated_state_atomic() {
        let chunk_bytes = size_of::<PresenceChunk>();
        for (populated, limit, rejected_row) in [
            (false, chunk_bytes - 1, 1_000_000),
            (true, 2 * chunk_bytes - 1, ROWS_PER_CHUNK),
            (true, 64 * chunk_bytes, 64 * ROWS_PER_CHUNK),
        ] {
            let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(limit));
            let reservation = MemoryConsumer::new("presence-denial").register(&pool);
            let mut presence = RowPresence::try_new(reservation).unwrap();
            if populated {
                presence.mark(AbsoluteRow::ZERO).unwrap();
            }
            let before = (
                presence.contains(AbsoluteRow::ZERO),
                presence.retained_chunks(),
                presence.reserved_bytes(),
            );
            let rejected = AbsoluteRow::new(rejected_row);
            let error = presence.mark(rejected).unwrap_err();
            assert!(matches!(error, DataFusionError::ResourcesExhausted(_)));
            assert!(!presence.contains(rejected));
            assert_eq!(
                (
                    presence.contains(AbsoluteRow::ZERO),
                    presence.retained_chunks(),
                    presence.reserved_bytes()
                ),
                before
            );
            assert_eq!(pool.reserved(), before.2);
            drop(presence);
            assert_eq!(pool.reserved(), 0);
        }
    }

    #[test]
    fn cancellation_during_sparse_growth_preserves_published_membership() {
        let mut presence = RowPresence::try_new_unbounded().unwrap();
        presence.mark(AbsoluteRow::ZERO).unwrap();
        let retained_chunks = presence.retained_chunks();
        let rejected_row = AbsoluteRow::new(130 * ROWS_PER_CHUNK);
        let mut completed_units = 0usize;
        let error = presence
            .mark_with_work(rejected_row, &mut |units| {
                completed_units += units;
                if units == COARSE_WORK_BATCH_SIZE {
                    return Err(DataFusionError::Internal(
                        "injected presence growth cancellation".to_string(),
                    ));
                }
                Ok(())
            })
            .expect_err("sparse chunk initialization must be cancellable");

        assert!(error.to_string().contains("growth cancellation"));
        assert!(completed_units <= COARSE_WORK_BATCH_SIZE + 1);
        assert!(presence.contains(AbsoluteRow::ZERO));
        assert!(!presence.contains(rejected_row));
        assert_eq!(presence.retained_chunks(), retained_chunks);
        assert_eq!(presence.first_unfinalized_row(), AbsoluteRow::ZERO);
    }

    #[test]
    fn cancellation_during_prefix_trim_rolls_back_chunks_and_boundary() {
        let mut presence = RowPresence::try_new_unbounded().unwrap();
        let last_row = AbsoluteRow::new(130 * ROWS_PER_CHUNK);
        presence.mark(AbsoluteRow::ZERO).unwrap();
        presence.mark(last_row).unwrap();
        let retained_chunks = presence.retained_chunks();
        let mut completed_units = 0usize;
        let error = presence
            .trim_prefix_with_work(AbsoluteRow::new(100 * ROWS_PER_CHUNK), &mut |units| {
                completed_units += units;
                if units == COARSE_WORK_BATCH_SIZE {
                    return Err(DataFusionError::Internal(
                        "injected presence trim cancellation".to_string(),
                    ));
                }
                Ok(())
            })
            .expect_err("long prefix trimming must be cancellable");

        assert!(error.to_string().contains("trim cancellation"));
        assert_eq!(completed_units, COARSE_WORK_BATCH_SIZE);
        assert_eq!(presence.first_unfinalized_row(), AbsoluteRow::ZERO);
        assert_eq!(presence.retained_chunks(), retained_chunks);
        assert!(presence.contains(AbsoluteRow::ZERO));
        assert!(presence.contains(last_row));
    }
}