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

//! Resumable selected-measure reduction over the final winning rows.
use super::*;
use crate::execution::matching::WinningValue;
use crate::execution::matching::row_loop::lane_scan::CompactSelection;
use datafusion::arrow::datatypes::DataType;

pub(super) type ReadRegister<'a> =
    dyn FnMut(usize, &DataType) -> Option<WinningValue> + 'a;

/// The current head can overlap history. Prefer its rebound input columns
/// and use retained history for earlier absolute rows.
fn source_span<'a>(
    batches: &'a BatchCollection,
    origin: usize,
    history: Option<&'a SharedHistoryBuffer>,
    absolute: usize,
    completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<(&'a RecordBatch, usize)> {
    if let Some(local) = absolute
        .checked_sub(origin)
        .filter(|&row| row < batches.num_rows())
    {
        let (batch, offset) = batches.locate_with_work(local, completed)?;
        return Ok((batches.batch(batch), offset));
    }
    let Some(history) = history else {
        return internal_err!(
            "selected aggregate input row {absolute} outside the retained head"
        );
    };
    let (batch, offset) = history.locate(absolute)?;
    completed(1)?;
    Ok((history.batch(batch), offset))
}

/// A General path can contain empty markers and repeated control steps.
/// The checked encoder supplies a row only when its classifier contributes.
pub(super) struct PendingSummaryRow {
    pub(super) absolute: AbsoluteRow,
    pub(super) classifier: usize,
    pub(super) sequence: i64,
    pub(super) field: usize,
}

impl PendingSummaryRow {
    #[allow(clippy::too_many_arguments)]
    pub(super) fn advance(
        &mut self,
        output: &mut OutputBatchBuilder,
        summaries: &[ExecutableDirectCountSummary],
        scratch: &mut [u64],
        edge_states: &mut [EdgeScratchState],
        batches: &BatchCollection,
        origin: usize,
        history: Option<&SharedHistoryBuffer>,
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<bool> {
        let end = (self.field + COARSE_WORK_BATCH_SIZE).min(summaries.len());
        let start = self.field;
        let mut source = None;
        for index in start..end {
            let summary = &summaries[index];
            if summary
                .symbol_id()
                .is_some_and(|id| id.index() != self.classifier)
            {
                self.field = index + 1;
                continue;
            }
            if let Some(reduction) = summary.reduction() {
                let (batch, at) = match source {
                    Some(found) => found,
                    None => {
                        let found = source_span(
                            batches,
                            origin,
                            history,
                            absolute_row_to_usize(self.absolute, "aggregate input")?,
                            completed,
                        )?;
                        source = Some(found);
                        found
                    }
                };
                output.update_reduction(
                    index,
                    batch.column(reduction.input_column),
                    at,
                    1,
                )?;
            } else {
                scratch[index] = row_summary(
                    scratch[index],
                    summary,
                    edge_states.get_mut(index),
                    self.classifier,
                    self.sequence,
                    self.absolute,
                )?;
            }
            self.field = index + 1;
        }
        completed((end - start).max(1))?;
        Ok(end == summaries.len())
    }
}

#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub(super) struct CompactReductions {
    field: usize,
    rows: usize,
    run: usize,
    offset: u64,
    edge_cursor: compact::OffsetEdgeCursor,
}

impl CompactReductions {
    /// A matching register belongs to the elected Lane. Other reductions use
    /// physical input in classifier order, including excluded pattern rows.
    #[allow(clippy::too_many_arguments)]
    pub(super) fn advance(
        &mut self,
        output: &mut OutputBatchBuilder,
        summaries: &[ExecutableDirectCountSummary],
        scratch: &mut [u64],
        selected: &CompactSelection<'_>,
        batches: &BatchCollection,
        global_offset: usize,
        history: Option<&SharedHistoryBuffer>,
        read_register: &mut ReadRegister<'_>,
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<(bool, usize)> {
        let mut remaining = COARSE_WORK_BATCH_SIZE;
        let mut total_work = 0usize;
        let mut cached_batch: Option<(&RecordBatch, usize, usize)> = None;
        let result: Result<bool> = (|| {
            while self.field < summaries.len() && remaining > 0 {
                let summary = &summaries[self.field];
                let (finished, work) = if let Some(reduction) = summary.reduction() {
                    if self.rows == 0
                        && let Some(id) = reduction.managed_aggregate
                        && let Some(value) = read_register(id, &reduction.output_type)
                    {
                        output.set_reduction(self.field, value)?;
                        (true, 1)
                    } else {
                        self.reduce_input(
                            output,
                            selected,
                            summary,
                            batches,
                            global_offset,
                            history,
                            remaining,
                            &mut cached_batch,
                            &mut total_work,
                        )?
                    }
                } else if let Some(value) = compact::captured_summary(selected, summary)?
                {
                    scratch[self.field] = value;
                    (true, 1)
                } else if let Some(edge) = summary.edge().filter(|e| e.logical_offset > 0)
                {
                    let history = selected.history()?;
                    let mut budget = remaining;
                    let mut work = 0usize;
                    let mut finished = false;
                    let mut remaining_lo =
                        edge.logical_offset.saturating_sub(self.offset as usize);
                    while self.run < history.runs.len() && budget > 0 {
                        let run_idx = if edge.last {
                            history.runs.len() - 1 - self.run
                        } else {
                            self.run
                        };
                        let (run_finished, found, used) = self.edge_cursor.advance(
                            history,
                            run_idx,
                            summary.symbol_id(),
                            edge.last,
                            &mut remaining_lo,
                            budget,
                        )?;
                        self.offset = (edge.logical_offset - remaining_lo) as u64;
                        if run_finished {
                            self.run += 1;
                            self.edge_cursor = compact::OffsetEdgeCursor::default();
                        }
                        work += used;
                        budget -= used;
                        if let Some(coord) = found {
                            scratch[self.field] = coord;
                            finished = true;
                            break;
                        }
                    }
                    if !finished && self.run == history.runs.len() {
                        scratch[self.field] = 0;
                        finished = true;
                    }
                    (finished, work.max(1))
                } else {
                    let history = selected.history()?;
                    let used = compact::reduce_summary_words(
                        selected,
                        &mut self.run,
                        &mut self.offset,
                        std::slice::from_ref(summary),
                        &mut scratch[self.field..=self.field],
                        remaining,
                        &mut || Ok(()),
                    )?;
                    (self.run == history.runs.len(), used.max(1))
                };
                if finished {
                    *self = Self {
                        field: self.field + 1,
                        ..Self::default()
                    };
                }
                remaining = remaining.saturating_sub(work);
                total_work += work;
            }
            Ok(self.field == summaries.len())
        })();
        if total_work != 0 {
            let accounting = completed(total_work);
            if result.is_ok() {
                accounting?;
            }
        }
        result.map(|finished| (finished, total_work))
    }

    #[allow(clippy::too_many_arguments)]
    fn reduce_input<'a>(
        &mut self,
        output: &mut OutputBatchBuilder,
        selected: &CompactSelection<'_>,
        summary: &ExecutableDirectCountSummary,
        batches: &'a BatchCollection,
        global_offset: usize,
        history_buf: Option<&'a SharedHistoryBuffer>,
        budget: usize,
        cached_batch: &mut Option<(&'a RecordBatch, usize, usize)>,
        locate_work: &mut usize,
    ) -> Result<(bool, usize)> {
        // For an unqualified measure the whole winning extent is contiguous.
        // A named capture also suffices if all rows between its endpoints match.
        let contiguous = selected.symbol_facts(summary.symbol_id()).filter(|f| {
            f.count == 0 || f.last.as_u64() - f.first.as_u64() + 1 == f.count
        });
        let column = summary.input_column().expect("bound reduction input");
        if let Some(facts) = contiguous {
            if facts.count == 0 {
                return Ok((true, 1));
            }
            let total = facts.count as usize;
            let available = total - self.rows;
            let absolute = absolute_row_to_usize(facts.first, "compact aggregate input")?
                + self.rows;
            let (batch, at, valid_rows) = resolve_source_cached(
                batches,
                global_offset,
                history_buf,
                absolute,
                cached_batch,
                locate_work,
            )?;
            let count = available.min(budget).min(valid_rows);
            output.update_reduction(self.field, batch.column(column), at, count)?;
            self.rows += count;
            return Ok((self.rows == total, count));
        }

        let history = selected.history()?;
        let start_abs = absolute_row_to_usize(selected.start, "compact aggregate input")?;
        let total = selected.expected_steps.as_u64() as usize;
        let mut remaining = budget;
        let mut work = 0usize;
        while self.rows < total && remaining > 0 {
            let (edge, period) = history.edge_and_period(self.run, self.offset)?;
            let run_steps = history.runs[self.run].steps().as_u64();
            let run_left = run_steps - self.offset;
            let available = if period == 1 { run_left as usize } else { 1 };
            let (rows, step_work) = if summary.symbol_id() == Some(edge.symbol_id) {
                let absolute = start_abs + self.rows;
                let (batch, at, valid_rows) = resolve_source_cached(
                    batches,
                    global_offset,
                    history_buf,
                    absolute,
                    cached_batch,
                    locate_work,
                )?;
                let count = available.min(remaining).min(valid_rows);
                output.update_reduction(self.field, batch.column(column), at, count)?;
                (count, count)
            } else {
                (available, 1)
            };
            self.rows += rows;
            self.offset += rows as u64;
            if self.offset == run_steps {
                self.offset = 0;
                self.run += 1;
            }
            work += step_work;
            remaining = remaining.saturating_sub(step_work);
        }
        Ok((self.rows == total, work.max(1)))
    }
}

#[inline]
fn resolve_source_cached<'a>(
    batches: &'a BatchCollection,
    origin: usize,
    history: Option<&'a SharedHistoryBuffer>,
    absolute: usize,
    cached: &mut Option<(&'a RecordBatch, usize, usize)>,
    locate_work: &mut usize,
) -> Result<(&'a RecordBatch, usize, usize)> {
    if let Some((batch, base, valid_end)) = *cached
        && absolute >= base
        && absolute < valid_end
    {
        return Ok((batch, absolute - base, valid_end - absolute));
    }
    let in_head = absolute
        .checked_sub(origin)
        .is_some_and(|row| row < batches.num_rows());
    let (batch, at) = source_span(batches, origin, history, absolute, &mut |units| {
        *locate_work += units;
        Ok(())
    })?;
    let base = absolute - at;
    let valid_end = if !in_head && absolute < origin && batches.num_rows() > 0 {
        (base + batch.num_rows()).min(origin)
    } else {
        base + batch.num_rows()
    };
    *cached = Some((batch, base, valid_end));
    Ok((batch, at, valid_end - absolute))
}

#[cfg(test)]
mod tests {
    use super::*;
    use datafusion::arrow::array::{AsArray, Int64Array};
    use datafusion::arrow::datatypes::{Field, Int64Type};

    #[test]
    fn resolve_source_cached_stops_overlapping_history_at_origin() -> Result<()> {
        let schema = Arc::new(Schema::new(vec![Field::new("v", DataType::Int64, false)]));
        let history_batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![Arc::new(Int64Array::from(vec![10_i64, 20, 30, 40, 50]))],
        )?;
        let head_batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![Arc::new(Int64Array::from(vec![300_i64, 400, 500]))],
        )?;
        let head = BatchCollection::try_new(vec![head_batch], Arc::clone(&schema))?;
        let mut history = SharedHistoryBuffer::new(
            Arc::clone(&schema),
            crate::execution::common::memory::new_unbounded_state_memory().new_empty(),
        );
        history.append(history_batch)?;

        let mut cached = None;
        let mut locate_work = 0;

        let (batch, at, valid_rows) = resolve_source_cached(
            &head,
            2,
            Some(&history),
            0,
            &mut cached,
            &mut locate_work,
        )?;
        assert_eq!((at, valid_rows), (0, 2));
        assert_eq!(batch.column(0).as_primitive::<Int64Type>().value(at), 10);

        let (batch, at, valid_rows) = resolve_source_cached(
            &head,
            2,
            Some(&history),
            1,
            &mut cached,
            &mut locate_work,
        )?;
        assert_eq!((at, valid_rows), (1, 1));
        assert_eq!(batch.column(0).as_primitive::<Int64Type>().value(at), 20);

        let (batch, at, valid_rows) = resolve_source_cached(
            &head,
            2,
            Some(&history),
            2,
            &mut cached,
            &mut locate_work,
        )?;
        assert_eq!((at, valid_rows), (0, 3));
        assert_eq!(batch.column(0).as_primitive::<Int64Type>().value(at), 300);

        let (batch, at, valid_rows) = resolve_source_cached(
            &head,
            2,
            Some(&history),
            3,
            &mut cached,
            &mut locate_work,
        )?;
        assert_eq!((at, valid_rows), (1, 2));
        assert_eq!(batch.column(0).as_primitive::<Int64Type>().value(at), 400);

        // An empty head has no overlapping rows to prefer over retained history.
        let empty_head = BatchCollection::try_new(vec![], schema)?;
        let mut empty_cached = None;
        let (batch, at, valid_rows) = resolve_source_cached(
            &empty_head,
            2,
            Some(&history),
            0,
            &mut empty_cached,
            &mut locate_work,
        )?;
        assert_eq!((at, valid_rows), (0, 5));
        assert_eq!(batch.column(0).as_primitive::<Int64Type>().value(at), 10);
        Ok(())
    }
}