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

//! Raw-input head selection and direct publication.

use std::ops::Range;
use std::sync::Arc;

use datafusion::arrow::array::ArrayRef;
use datafusion::arrow::compute::partition;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::{Result, internal_err};
use datafusion::execution::memory_pool::MemoryReservation;

use crate::execution::common::memory::{reserved_vec, try_reserve_accounted};
use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
use crate::execution::common::scheduling::SliceControl;
use crate::execution::common::work::WorkGovernor;
use crate::execution::matching::{PartitionKey, PartitionKeyRows};
use crate::execution::storage::collection::BatchCollection;

use super::keys::{CoopWork, overflow, vector_bytes};
use super::{HeadPartitions, PartitionedBuffer, PhysicalHeadEnd, RawPhysicalHead};

impl PartitionedBuffer {
    #[allow(clippy::too_many_arguments)]
    pub(crate) async fn prepare_replay_keys(
        collection: BatchCollection,
        key_rows: Vec<PartitionKeyRows>,
        tail: Option<PartitionKey>,
        end: PhysicalHeadEnd,
        memory: MemoryReservation,
        governor: &mut WorkGovernor,
        slice: &SliceControl,
        is_aborted: impl Fn() -> bool,
    ) -> Result<(RawPhysicalHead, MemoryReservation)> {
        // Drop `memory` last, after `collection` and `key_rows` release their buffers.
        let memory = memory;
        let collection = collection;
        let key_rows = key_rows;
        let mut work = CoopWork::new(governor, slice, is_aborted);

        let continues_tail =
            continues_open_tail(tail.as_ref(), key_rows.first(), &mut work).await?;
        let partitions = discover_partitions(
            &key_rows,
            collection.num_rows(),
            end,
            continues_tail,
            &memory,
            &mut work,
        )
        .await?;
        let key_bytes = vector_bytes(&key_rows)?;
        for key in key_rows {
            drop(key);
            work.complete_one().await?;
        }
        work.flush().await?;
        memory.try_shrink(key_bytes)?;
        Ok((
            RawPhysicalHead {
                collection,
                partitions,
            },
            memory,
        ))
    }

    pub(crate) async fn select_head(
        &mut self,
        final_input: bool,
        open_tail: Option<&PartitionKey>,
        memory: MemoryReservation,
        governor: &mut WorkGovernor,
        slice: &SliceControl,
        is_aborted: impl Fn() -> bool,
    ) -> Result<(Option<RawPhysicalHead>, MemoryReservation)> {
        let mut work = CoopWork::new(governor, slice, is_aborted);
        // A threshold head may have consumed every row of the old partition.
        // Its suspended owner still needs finality when the first cached key
        // changes, even if the new partition has not reached the threshold.
        let continues_tail =
            continues_open_tail(open_tail, self.partition_columns.first(), &mut work)
                .await?;
        let closes_open_tail = open_tail.is_some() && !continues_tail;
        if self.batches.is_empty()
            || (!final_input
                && !closes_open_tail
                && self.guaranteed_safe_rows == self.buffered_rows
                && !self.flush_policy.threshold_reached(self.buffered_rows))
        {
            work.flush().await?;
            return Ok((None, memory));
        }

        let Some(partitions) = self
            .discover(
                final_input,
                continues_tail,
                closes_open_tail,
                &memory,
                &mut work,
            )
            .await?
        else {
            self.guaranteed_safe_rows = self.buffered_rows;
            work.flush().await?;
            return Ok((None, memory));
        };
        let head_rows = partitions
            .ranges
            .last()
            .expect("nonempty selected head")
            .end;
        let tail_rows = self.buffered_rows - head_rows;
        let mut tail_count = 0;
        let mut tail_total = 0usize;
        if tail_rows != 0 {
            // The newly opened partition usually occupies only the latest batch.
            for batch in self.batches.iter().rev() {
                tail_total = tail_total
                    .checked_add(batch.num_rows())
                    .ok_or_else(overflow)?;
                tail_count += 1;
                work.complete_one().await?;
                if tail_total >= tail_rows {
                    break;
                }
            }
        }
        // A batch that straddles the split contributes one view to each side.
        let head_count =
            self.batches.len() - tail_count + usize::from(tail_total > tail_rows);
        let mut head_batches_vec = reserved_vec(head_count, &memory, "replay-key")?;
        let mut cumulative = reserved_vec(head_count, &memory, "replay-key")?;
        let tail_memory = memory.new_empty();
        let mut tail_batches = reserved_vec(tail_count, &tail_memory, "replay-key")?;
        let mut tail_columns = reserved_vec(tail_count, &tail_memory, "replay-key")?;
        let mut offset = 0usize;
        let mut head_total = 0usize;
        let mut head_batches = 0usize;
        let mut boundary = None;
        for (batch, columns) in self.batches.iter().zip(&self.partition_columns) {
            let next = offset.checked_add(batch.num_rows()).ok_or_else(overflow)?;
            if offset < head_rows {
                let len = next.min(head_rows) - offset;
                memory.try_grow(batch_handle_bytes(batch)?)?;
                head_total = head_total.checked_add(len).ok_or_else(overflow)?;
                cumulative.push(head_total);
                if len == batch.num_rows() {
                    head_batches += 1;
                }
                work.native_completed(1).await?;
            }
            if next > head_rows {
                let start = head_rows.saturating_sub(offset);
                let len = next - offset - start;
                tail_memory.try_grow(batch_handle_bytes(batch)?)?;
                if start != 0 {
                    boundary = Some(batch.slice(0, start));
                    tail_batches.push(batch.slice(start, len));
                    tail_columns.push(columns.slice(start, len)?);
                }
                work.native_completed(1).await?;
            }
            offset = next;
        }
        if offset != self.buffered_rows || head_total != head_rows {
            return internal_err!(
                "MATCH_RECOGNIZE selected input does not cover its rows"
            );
        }
        let moved = self.batches.len().saturating_mul(2);
        let batches = std::mem::take(&mut self.batches);
        let mut keys = std::mem::take(&mut self.partition_columns);
        debug_assert_eq!(batches.len(), keys.len());
        let drop_keys = head_batches + usize::from(boundary.is_some());
        let mut batches = batches.into_iter();
        head_batches_vec.extend(batches.by_ref().take(head_batches));
        if let Some(batch) = boundary.take() {
            drop(batches.next());
            head_batches_vec.push(batch);
        }
        tail_batches.extend(batches);
        tail_columns.extend(keys.drain(drop_keys..));
        self.batches = tail_batches;
        self.partition_columns = tail_columns;
        self.buffered_rows = tail_rows;
        self.guaranteed_safe_rows = tail_rows;
        let old_selection_memory = self.selection_memory.replace(tail_memory);
        for key in keys {
            drop(key);
            work.complete_one().await?;
        }
        drop(old_selection_memory);
        let head = RawPhysicalHead {
            collection: BatchCollection::from_prepared_parts(
                head_batches_vec,
                cumulative,
                Arc::clone(&self.schema),
            ),
            partitions,
        };
        work.record_sync(moved)?;
        Ok((Some(head), memory))
    }

    async fn discover<F: Fn() -> bool>(
        &self,
        final_input: bool,
        continues_tail: bool,
        closes_open_tail: bool,
        memory: &MemoryReservation,
        work: &mut CoopWork<'_, F>,
    ) -> Result<Option<HeadPartitions>> {
        let views = &self.partition_columns;
        let last = views.last().expect("nonempty buffered input");
        if let Some(groups) = &last.batch.grouped {
            let (tail_rows, closed) = groups.tail(last);
            let total = self.buffered_rows;
            let (rows, end) = if final_input {
                (total, PhysicalHeadEnd::InputEnd)
            } else if closed {
                (total, PhysicalHeadEnd::PartitionBoundary)
            } else if tail_rows < total {
                (total - tail_rows, PhysicalHeadEnd::PartitionBoundary)
            } else if self.flush_policy.threshold_reached(total) {
                (total, PhysicalHeadEnd::OpenTail)
            } else {
                return Ok(None);
            };
            let partitions =
                discover_partitions(views, rows, end, continues_tail, memory, work)
                    .await?;
            return Ok(Some(partitions));
        }

        let (head_rows, end) = if final_input {
            (self.buffered_rows, PhysicalHeadEnd::InputEnd)
        } else {
            let rows = self.buffered_rows;
            let tail_start =
                if self.guaranteed_safe_rows > 0 && self.guaranteed_safe_rows == rows {
                    Some(0)
                } else {
                    // Include one proven row to detect a boundary after the cached prefix.
                    let start = self.guaranteed_safe_rows.saturating_sub(1);
                    let ranges = ranges(views, start, rows - start, memory, work).await?;
                    let result = ranges.last().map(|tail| {
                        if tail.start == 0 {
                            0
                        } else {
                            start + tail.start
                        }
                    });
                    let bytes = vector_bytes(&ranges)?;
                    drop(ranges);
                    memory.try_shrink(bytes)?;
                    result
                };
            match tail_start {
                Some(0)
                    if closes_open_tail || self.flush_policy.threshold_reached(rows) =>
                {
                    (rows, PhysicalHeadEnd::OpenTail)
                }
                Some(split_idx) if split_idx != 0 => {
                    (split_idx, PhysicalHeadEnd::PartitionBoundary)
                }
                _ => return Ok(None),
            }
        };

        let partitions =
            discover_partitions(views, head_rows, end, continues_tail, memory, work)
                .await?;
        Ok(Some(partitions))
    }
}

/// Discover logical ranges and the canonical open key for selected or replayed
/// input without combining independently encoded key arrays.
async fn discover_partitions<F: Fn() -> bool>(
    views: &[PartitionKeyRows],
    rows: usize,
    end: PhysicalHeadEnd,
    continues_tail: bool,
    memory: &MemoryReservation,
    work: &mut CoopWork<'_, F>,
) -> Result<HeadPartitions> {
    let ranges = if views.first().is_some_and(|v| v.batch.grouped.is_some()) {
        super::grouped::ranges(views, rows, memory, work).await?
    } else {
        ranges(views, 0, rows, memory, work).await?
    };
    let open_key = if let Some(mut row) = open_key_position(&ranges, end, continues_tail)
    {
        let mut key = None;
        for view in views {
            if row < view.rows {
                key = Some(view.slice(row, 1)?);
                break;
            }
            row -= view.rows;
            work.complete_one().await?;
        }
        if key.is_none() {
            return internal_err!("MATCH_RECOGNIZE open key is outside selected input");
        }
        key
    } else {
        None
    };
    work.native_completed(1).await?;
    Ok(HeadPartitions {
        ranges,
        continues_tail,
        open_key,
        end,
    })
}

fn batch_handle_bytes(batch: &RecordBatch) -> Result<usize> {
    batch
        .num_columns()
        .checked_mul(size_of::<ArrayRef>())
        .ok_or_else(overflow)
}

/// Only a newly opened tail needs to establish a canonical key. All earlier
/// ranges finish in this head or carry a key from the preceding head.
fn open_key_position(
    ranges: &[Range<usize>],
    end: PhysicalHeadEnd,
    continues: bool,
) -> Option<usize> {
    if end.ends_partition() || (continues && ranges.len() == 1) {
        return None;
    }
    ranges.last().map(|range| range.start)
}

/// Ordered input compares a head's first row to its predecessor once, before
/// publishing the head. Replay uses this same test against its retained start.
async fn continues_open_tail<F: Fn() -> bool>(
    tail: Option<&PartitionKey>,
    first: Option<&PartitionKeyRows>,
    work: &mut CoopWork<'_, F>,
) -> Result<bool> {
    let (Some(tail), Some(first)) = (tail, first) else {
        return Ok(false);
    };
    if let Some(groups) = &first.batch.grouped {
        return Ok(tail.group_start() == Some(groups.start_at(first.offset)));
    }
    if tail.len() != first.batch.values.num_columns() {
        return internal_err!(
            "MATCH_RECOGNIZE open tail and cached input keys have different widths"
        );
    }
    for column in 0..tail.len() {
        let same = super::same_partition_rows(
            &tail.column(column),
            0,
            first.batch.values.column(column),
            first.offset,
        )?;
        work.native_completed(COARSE_WORK_BATCH_SIZE).await?;
        if !same {
            return Ok(false);
        }
    }
    Ok(true)
}

/// Discover within each view, then join equal boundary rows. Concatenating keys
/// would impose dictionary-capacity and run-end limits on otherwise valid views.
async fn ranges<F: Fn() -> bool>(
    views: &[PartitionKeyRows],
    mut start: usize,
    len: usize,
    memory: &MemoryReservation,
    work: &mut CoopWork<'_, F>,
) -> Result<Vec<Range<usize>>> {
    let mut result: Vec<Range<usize>> = Vec::new();
    let mut position = 0;
    let mut previous: Option<&PartitionKeyRows> = None;
    for view in views {
        if position == len {
            break;
        }
        if start >= view.rows {
            start -= view.rows;
            work.complete_one().await?;
            continue;
        }
        let rows = (view.rows - start).min(len - position);
        let scratch = memory.new_empty();
        let selected = view.slice(start, rows)?;
        let mut columns =
            reserved_vec(selected.batch.values.num_columns(), &scratch, "replay-key")?;
        for column in 0..selected.batch.values.num_columns() {
            columns.push(selected.column(column));
        }
        let local = if columns.is_empty() {
            std::iter::once(0..rows).collect()
        } else {
            partition(&columns)?.ranges()
        };
        scratch.try_grow(vector_bytes(&local)?)?;
        work.native_completed(columns.len() * 2 + 1).await?;

        let mut joins = previous.is_some();
        if let Some(before) = previous {
            for column in 0..columns.len() {
                joins = super::same_partition_rows(
                    before.batch.values.column(column),
                    before.offset + before.rows - 1,
                    view.batch.values.column(column),
                    view.offset + start,
                )?;
                work.native_completed(COARSE_WORK_BATCH_SIZE).await?;
                if !joins {
                    break;
                }
            }
        }
        try_reserve_accounted(
            &mut result,
            memory,
            local.len() - usize::from(joins),
            "replay-key",
        )?;
        for (index, range) in local.iter().enumerate() {
            let end = position + range.end;
            if index == 0 && joins {
                result.last_mut().unwrap().end = end;
            } else {
                result.push(position + range.start..end);
            }
            work.complete_one().await?;
        }
        position += rows;
        start = 0;
        previous = Some(view);
    }
    if position != len {
        return internal_err!("MATCH_RECOGNIZE ordered views do not cover the head");
    }
    Ok(result)
}