datafusion-match-recognize 0.56.0

MATCH_RECOGNIZE extension for 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
// 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.

//! Projected classifier facts for an ordered prefix and its most recent winner.

use super::SymbolFacts;
use crate::core::{AbsoluteRow, SymbolId};
use crate::execution::common::memory::try_reserve_accounted;
use datafusion_common::Result;
use datafusion_execution::memory_pool::MemoryReservation;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ClassifierDemand {
    All,
    /// Complete run transcript required, plus O(1) captures for the requested
    /// packed symbols (non-zero bitmask) to accelerate contiguous reductions
    /// and named endpoints.
    AllWithCaptures(u64),
    Symbols(u64),
}

impl ClassifierDemand {
    pub(crate) fn with_symbol(self, symbol: SymbolId) -> Self {
        match (self, symbol.packed_membership_bit()) {
            (Self::Symbols(mask), Some(bit)) => Self::Symbols(mask | bit),
            (Self::AllWithCaptures(mask), Some(bit)) => Self::AllWithCaptures(mask | bit),
            (Self::Symbols(_), None) => Self::All,
            (Self::AllWithCaptures(mask), None) => Self::AllWithCaptures(mask),
            (Self::All, _) => Self::All,
        }
    }

    pub(crate) fn with_runs(self) -> Self {
        match self {
            Self::Symbols(0) | Self::All => Self::All,
            Self::Symbols(mask) | Self::AllWithCaptures(mask) => {
                Self::AllWithCaptures(mask)
            }
        }
    }
}

#[derive(Default, Clone, Copy)]
struct CaptureSlot {
    live: SymbolFacts,
    saved: SymbolFacts,
}

pub(crate) struct SymbolCaptures {
    requested: u64,
    present: u64,
    dirty: u64,
    terminal: Option<(u64, AbsoluteRow)>,
    // Only requested entries are read. The facts themselves stay dense and pool-owned.
    slot_for_symbol: [u8; 64],
    slots: Vec<CaptureSlot>,
}

impl SymbolCaptures {
    /// The scanner owns the matching reservation for the lifetime of the table.
    pub(crate) fn try_new(mask: u64, memory: &mut MemoryReservation) -> Result<Self> {
        let len = mask.count_ones() as usize;
        let mut slots = Vec::new();
        try_reserve_accounted(&mut slots, memory, len, "selected symbol captures")?;
        slots.resize(len, CaptureSlot::default());
        let mut slot_for_symbol = [0; 64];
        let mut remaining = mask;
        for index in 0..len {
            slot_for_symbol[remaining.trailing_zeros() as usize] = index as u8;
            remaining &= remaining - 1;
        }
        Ok(Self {
            requested: mask,
            present: 0,
            dirty: 0,
            terminal: None,
            slot_for_symbol,
            slots,
        })
    }

    pub(crate) fn mask(&self) -> u64 {
        self.requested
    }

    pub(crate) fn reset(&mut self) {
        self.present = 0;
        self.dirty = 0;
        self.terminal = None;
    }

    /// Record a consuming segment before installing its acceptance. The first
    /// write after a winner saves the old slot, including absence. A subsequent
    /// acceptance makes every live slot current, even for an unrequested edge.
    /// The direct scanner consumes disjoint, nonempty spans up to a checked
    /// exclusive end. Thus a symbol's cumulative count fits in that end's u64.
    #[inline]
    pub(crate) fn observe(
        &mut self,
        bit: u64,
        first: AbsoluteRow,
        last: AbsoluteRow,
        count: u64,
        has_winner: bool,
        accepting: bool,
    ) {
        debug_assert!(bit.is_power_of_two());
        debug_assert!(first <= last && count != 0);
        debug_assert_eq!(last.as_u64() - first.as_u64(), count - 1);
        if self.requested & bit != 0 {
            let index = self.slot_for_symbol[bit.trailing_zeros() as usize];
            let slot = &mut self.slots[usize::from(index)];
            let prior = if self.present & bit == 0 {
                SymbolFacts::default()
            } else {
                slot.live
            };
            debug_assert!(prior.count == 0 || prior.last < first);
            if has_winner && !accepting && self.dirty & bit == 0 {
                slot.saved = prior;
                self.dirty |= bit;
            }
            slot.live = SymbolFacts {
                first: if prior.count == 0 { first } else { prior.first },
                last,
                count: prior.count + count,
            };
            self.present |= bit;
        }
        if accepting {
            self.dirty = 0;
            self.terminal = None;
        }
    }

    /// Peel one winning row. A suspended first-occurrence search leaves the
    /// table untouched; the caller retains its search position across polls.
    pub(crate) fn peel_prefix_row(
        &mut self,
        bit: u64,
        row: AbsoluteRow,
        find_next_first: impl FnOnce() -> Result<Option<AbsoluteRow>>,
    ) -> Result<bool> {
        debug_assert!(bit.is_power_of_two());
        debug_assert_eq!(self.dirty, 0);
        debug_assert!(self.terminal.is_none());
        if self.requested & bit == 0 {
            return Ok(true);
        }
        let slot = &mut self.slots
            [usize::from(self.slot_for_symbol[bit.trailing_zeros() as usize])];
        debug_assert!(self.present & bit != 0 && slot.live.first == row);
        if slot.live.count > 1 {
            let Some(next) = find_next_first()? else {
                return Ok(false);
            };
            debug_assert!(row < next && next <= slot.live.last);
            slot.live.first = next;
            slot.live.count -= 1;
        } else {
            self.present &= !bit;
            slot.live = SymbolFacts::default();
        }
        Ok(true)
    }

    /// Save a lower terminal without changing the preferred live prefix.
    pub(crate) fn accept_alternative(&mut self, bit: u64, row: AbsoluteRow) {
        self.dirty = 0;
        self.terminal = Some((bit, row));
    }

    pub(crate) fn at_winner(&self, symbol: SymbolId) -> Option<SymbolFacts> {
        let bit = symbol.packed_membership_bit()?;
        if self.requested & bit == 0 {
            return None;
        }
        let index = self.slot_for_symbol[symbol.index() - 1];
        let slot = &self.slots[usize::from(index)];
        let mut facts = if self.dirty & bit != 0 {
            slot.saved
        } else if self.present & bit != 0 {
            slot.live
        } else {
            SymbolFacts::default()
        };
        if let Some((terminal, row)) =
            self.terminal.filter(|(terminal, _)| *terminal == bit)
        {
            debug_assert_eq!(terminal, bit);
            if facts.count == 0 {
                facts.first = row;
            }
            facts.last = row;
            facts.count += 1;
        }
        Some(facts)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::execution::matching::row_loop::lane_scan::CompactSelection;
    use datafusion_common::DataFusionError;
    use datafusion_execution::memory_pool::{
        GreedyMemoryPool, MemoryConsumer, MemoryPool,
    };
    use std::sync::Arc;

    fn symbol(index: usize) -> SymbolId {
        SymbolId::try_new(index, 66).unwrap()
    }

    fn facts(first: u64, last: u64, count: u64) -> SymbolFacts {
        SymbolFacts {
            first: AbsoluteRow::new(first),
            last: AbsoluteRow::new(last),
            count,
        }
    }

    #[test]
    fn peeling_preserves_requested_facts_absence_and_pool_charge() -> Result<()> {
        for winners in [vec![1, 1, 1], vec![1, 2, 1, 4, 2, 1], vec![2, 1, 2]] {
            for requested in [0, 1, 3, 7, 15] {
                let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(4096));
                let mut memory = MemoryConsumer::new("suffix captures").register(&pool);
                let mut captures = SymbolCaptures::try_new(requested, &mut memory)?;
                let row = AbsoluteRow::new;
                for (i, &bit) in winners.iter().enumerate() {
                    captures.observe(bit, row(i as u64), row(i as u64), 1, false, true);
                }
                let charged = memory.size();
                for (i, &bit) in winners.iter().enumerate() {
                    let next = winners[i + 1..]
                        .iter()
                        .position(|&b| b == bit)
                        .map(|n| row((i + n + 1) as u64));
                    if next.is_some() && requested & bit != 0 {
                        let before =
                            captures.at_winner(symbol(bit.trailing_zeros() as usize + 1));
                        assert!(
                            !captures.peel_prefix_row(bit, row(i as u64), || Ok(None))?
                        );
                        assert_eq!(
                            captures.at_winner(symbol(bit.trailing_zeros() as usize + 1)),
                            before
                        );
                    }
                    assert!(captures.peel_prefix_row(bit, row(i as u64), || Ok(next))?);
                    for index in 0..4 {
                        let id = symbol(index + 1);
                        let expected = if requested & (1 << index) == 0 {
                            None
                        } else {
                            let rows: Vec<_> = winners
                                .iter()
                                .enumerate()
                                .skip(i + 1)
                                .filter(|(_, b)| **b == 1 << index)
                                .map(|(j, _)| j as u64)
                                .collect();
                            Some(rows.first().map_or(SymbolFacts::default(), |&first| {
                                facts(first, *rows.last().unwrap(), rows.len() as u64)
                            }))
                        };
                        assert_eq!(captures.at_winner(id), expected);
                    }
                    assert_eq!(memory.size(), charged);
                }
                drop((captures, memory));
                assert_eq!(pool.reserved(), 0);
            }
        }
        Ok(())
    }

    #[test]
    fn later_extensions_preserve_each_accepted_symbol_prefix() -> Result<()> {
        let (a, b, c, absent) = (symbol(1), symbol(64), symbol(2), symbol(9));
        let (a_bit, b_bit, c_bit, absent_bit) = (1, 1 << 63, 2, 1 << 8);
        let mask = a_bit | b_bit | absent_bit;
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1024));
        let mut memory = MemoryConsumer::new("accepted symbols").register(&pool);
        let mut table = SymbolCaptures::try_new(mask, &mut memory)?;
        let row = AbsoluteRow::new;
        table.observe(a_bit, row(0), row(1), 2, false, false);
        table.observe(c_bit, row(2), row(2), 1, false, true);
        table.observe(a_bit, row(3), row(3), 1, true, false);
        table.observe(b_bit, row(4), row(5), 2, true, false);
        table.observe(a_bit, row(6), row(6), 1, true, false);
        // An unsuccessful suffix changed A twice and introduced B.
        let selection = CompactSelection::from_captures(row(0), row(2), row(2), &table)?;
        assert_eq!(selection.symbol_facts(None), Some(facts(0, 2, 3)));
        assert_eq!(selection.symbol_facts(Some(a)), Some(facts(0, 1, 2)));
        assert_eq!(
            selection.symbol_facts(Some(b)),
            Some(SymbolFacts::default())
        );
        assert_eq!(
            selection.symbol_facts(Some(absent)),
            Some(SymbolFacts::default())
        );
        assert_eq!(selection.symbol_facts(Some(c)), None);
        assert!(selection.history().is_err());

        // The unrequested C accepts the live A/B values, then B changes again.
        table.observe(c_bit, row(7), row(7), 1, true, true);
        table.observe(b_bit, row(8), row(8), 1, true, false);
        assert_eq!(table.at_winner(a), Some(facts(0, 6, 4)));
        assert_eq!(table.at_winner(b), Some(facts(4, 5, 2)));
        table.observe(a_bit, row(9), row(9), 1, true, true);
        assert_eq!(table.at_winner(a), Some(facts(0, 9, 5)));
        assert_eq!(table.at_winner(b), Some(facts(4, 8, 3)));

        let capacity = memory.size();
        table.reset();
        assert_eq!(table.mask(), mask);
        assert_eq!(table.at_winner(a), Some(SymbolFacts::default()));
        assert_eq!(table.at_winner(b), Some(SymbolFacts::default()));
        table.observe(b_bit, row(2), row(3), 2, false, true);
        assert_eq!(table.at_winner(b), Some(facts(2, 3, 2)));
        table.observe(absent_bit, row(4), row(4), 1, true, true);
        assert_eq!(table.at_winner(absent), Some(facts(4, 4, 1)));
        assert_eq!(table.at_winner(b), Some(facts(2, 3, 2)));
        assert_eq!(table.at_winner(a), Some(SymbolFacts::default()));
        assert_eq!(memory.size(), capacity);
        let extent = CompactSelection::from_extent(row(2), row(3), row(3))?;
        assert_eq!(extent.symbol_facts(None), Some(facts(2, 3, 2)));
        assert_eq!(extent.symbol_facts(Some(b)), None);
        drop((table, memory));
        assert_eq!(pool.reserved(), 0);
        Ok(())
    }

    #[test]
    fn terminal_alternative_keeps_the_preferred_live_prefix_separate() -> Result<()> {
        let memory = crate::execution::common::memory::new_unbounded_state_memory();
        let mut reservation = memory.new_empty();
        let mut captures = SymbolCaptures::try_new(3, &mut reservation)?;
        let row = AbsoluteRow::new;
        captures.observe(1, row(0), row(2), 3, false, false);
        captures.accept_alternative(2, row(3));
        captures.observe(1, row(3), row(8), 6, true, false);
        assert_eq!(captures.at_winner(symbol(1)), Some(facts(0, 2, 3)));
        assert_eq!(captures.at_winner(symbol(2)), Some(facts(3, 3, 1)));
        captures.observe(2, row(9), row(9), 1, true, true);
        assert_eq!(captures.at_winner(symbol(1)), Some(facts(0, 8, 9)));
        assert_eq!(captures.at_winner(symbol(2)), Some(facts(9, 9, 1)));
        Ok(())
    }

    #[test]
    fn capture_demand_and_pool_admission_follow_requested_symbols() -> Result<()> {
        let demand = ClassifierDemand::Symbols(0)
            .with_symbol(symbol(1))
            .with_symbol(symbol(64));
        assert_eq!(demand, ClassifierDemand::Symbols(1 | (1 << 63)));
        assert_eq!(demand.with_symbol(symbol(65)), ClassifierDemand::All);
        assert_eq!(
            ClassifierDemand::All.with_symbol(symbol(1)),
            ClassifierDemand::All
        );
        assert_eq!(
            ClassifierDemand::Symbols(0).with_runs(),
            ClassifierDemand::All
        );
        assert_eq!(
            ClassifierDemand::Symbols(1 | (1 << 2)).with_runs(),
            ClassifierDemand::AllWithCaptures(1 | (1 << 2))
        );
        assert_eq!(
            ClassifierDemand::AllWithCaptures(1)
                .with_symbol(symbol(2))
                .with_symbol(symbol(65))
                .with_runs(),
            ClassifierDemand::AllWithCaptures(1 | (1 << 1))
        );
        let pool: Arc<dyn MemoryPool> =
            Arc::new(GreedyMemoryPool::new(size_of::<CaptureSlot>()));
        let mut memory = MemoryConsumer::new("capture admission").register(&pool);
        let empty = SymbolCaptures::try_new(0, &mut memory)?;
        assert_eq!(empty.mask(), 0);
        assert_eq!(memory.size(), 0);
        assert!(matches!(
            SymbolCaptures::try_new(3, &mut memory),
            Err(DataFusionError::ResourcesExhausted(_))
        ));
        assert_eq!(pool.reserved(), 0);
        let one = SymbolCaptures::try_new(1 << 63, &mut memory)?;
        assert_eq!(memory.size(), size_of::<CaptureSlot>());
        assert_eq!(one.at_winner(symbol(64)), Some(SymbolFacts::default()));
        drop((one, memory));
        assert_eq!(pool.reserved(), 0);
        Ok(())
    }
}