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

//! Active-work slicing around matcher polls and cooperative stream yields.

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};

use datafusion::arrow::datatypes::SchemaRef;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::{DataFusionError, Result};
use datafusion::execution::RecordBatchStream;
use futures::{Stream, StreamExt};
use parking_lot::Mutex;

use crate::config::YieldPolicy;

#[derive(Debug)]
struct SliceState {
    policy: YieldPolicy,
    requested: bool,
    in_active_slice: bool,
}

/// The stream shares this control at poll boundaries; the row loop reads a copy.
#[derive(Clone, Debug)]
pub(crate) struct SliceControl(Arc<Mutex<SliceState>>);

impl Default for SliceControl {
    fn default() -> Self {
        Self(Arc::new(Mutex::new(SliceState {
            policy: YieldPolicy::Disabled,
            requested: false,
            in_active_slice: false,
        })))
    }
}

impl SliceControl {
    #[cfg(test)]
    pub(crate) fn for_test_budget(budget: std::num::NonZeroUsize) -> Self {
        Self(Arc::new(Mutex::new(SliceState {
            policy: YieldPolicy::TestBudget(budget),
            requested: false,
            in_active_slice: false,
        })))
    }

    pub(crate) fn current_policy(&self) -> YieldPolicy {
        self.0.lock().policy
    }

    /// Check the active poll's deadline between completed native work phases.
    pub(crate) async fn yield_if_expired(&self) {
        if self.current_policy().is_expired() {
            self.yield_once().await;
        }
    }

    pub(crate) async fn yield_once(&self) {
        let mut first = true;
        futures::future::poll_fn(|cx| {
            if std::mem::take(&mut first) {
                let in_active_slice = {
                    let mut state = self.0.lock();
                    state.requested = true;
                    state.in_active_slice
                };
                if !in_active_slice {
                    cx.waker().wake_by_ref();
                }
                Poll::Pending
            } else {
                Poll::Ready(())
            }
        })
        .await;
    }

    /// Request native waking for the inner stream's next `Pending` return.
    #[cfg(test)]
    fn request_yield(&self) {
        self.0.lock().requested = true;
    }
}

/// Wrap a cooperative stream and count only polling time toward each work slice.
pub(crate) fn with_active_slice<S: RecordBatchStream + Unpin>(
    stream: S,
    control: SliceControl,
    duration: Option<Duration>,
) -> impl RecordBatchStream {
    ActiveSliceStream::new(stream, control, duration, tokio::task::yield_now)
}

struct ActiveSliceStream<S, F> {
    inner: Option<S>,
    schema: SchemaRef,
    control: SliceControl,
    duration: Option<Duration>,
    elapsed: Duration,
    yield_future: Pin<Box<F>>,
    make_yield: fn() -> F,
    yielding: bool,
}

impl<S: RecordBatchStream, F: Future<Output = ()>> ActiveSliceStream<S, F> {
    fn new(
        stream: S,
        control: SliceControl,
        duration: Option<Duration>,
        make_yield: fn() -> F,
    ) -> Self {
        Self {
            schema: stream.schema(),
            inner: Some(stream),
            control,
            duration,
            elapsed: Duration::ZERO,
            yield_future: Box::pin(make_yield()),
            make_yield,
            yielding: false,
        }
    }

    fn begin_poll(&self, now: Instant) -> Result<()> {
        let policy = match self.duration {
            None => YieldPolicy::Disabled,
            Some(duration) => {
                let deadline = now
                    .checked_add(duration.saturating_sub(self.elapsed))
                    .ok_or_else(|| {
                        DataFusionError::Configuration(
                            "match_recognize.limits.yield_slice_micros cannot be added to the current monotonic clock reading"
                                .to_string(),
                        )
                    })?;
                YieldPolicy::Deadline(deadline)
            }
        };
        let mut state = self.control.0.lock();
        state.policy = policy;
        state.in_active_slice = true;
        Ok(())
    }

    fn finish_poll(&mut self, start: Instant, end: Instant, pending: bool) -> bool {
        let mut state = self.control.0.lock();
        state.policy = YieldPolicy::Disabled;
        state.in_active_slice = false;
        if pending {
            self.elapsed = Duration::ZERO;
            std::mem::take(&mut state.requested)
        } else {
            debug_assert!(!state.requested, "voluntary suspension must return Pending");
            self.elapsed = self.elapsed.saturating_add(end.duration_since(start));
            false
        }
    }
}

impl<S: RecordBatchStream + Unpin, F: Future<Output = ()>> Stream
    for ActiveSliceStream<S, F>
{
    type Item = Result<RecordBatch>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();
        if this.inner.is_none() {
            return Poll::Ready(None);
        }
        loop {
            if this.yielding {
                std::task::ready!(this.yield_future.as_mut().poll(cx));
                this.yield_future.as_mut().set((this.make_yield)());
                this.yielding = false;
            }

            if this.elapsed != Duration::ZERO
                && this
                    .duration
                    .is_some_and(|duration| this.elapsed >= duration)
            {
                this.elapsed = Duration::ZERO;
                this.yielding = true;
                continue;
            }

            let start = Instant::now();
            if let Err(error) = this.begin_poll(start) {
                this.inner = None;
                return Poll::Ready(Some(Err(error)));
            }
            let result = this
                .inner
                .as_mut()
                .expect("terminal streams return before polling")
                .poll_next_unpin(cx);
            let requested = this.finish_poll(start, Instant::now(), result.is_pending());
            if requested {
                this.yielding = true;
                continue;
            }
            if matches!(result, Poll::Ready(None | Some(Err(_)))) {
                this.inner = None;
            }
            return result;
        }
    }
}

impl<S: RecordBatchStream + Unpin, F: Future<Output = ()>> RecordBatchStream
    for ActiveSliceStream<S, F>
{
    fn schema(&self) -> SchemaRef {
        Arc::clone(&self.schema)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use datafusion::arrow::datatypes::Schema;
    use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
    use futures::task::{ArcWake, waker};

    #[test]
    fn active_time_accumulates_ready_work_and_excludes_poll_gaps() {
        let control = SliceControl::default();
        let input = RecordBatchStreamAdapter::new(
            Arc::new(Schema::empty()),
            futures::stream::empty(),
        );
        let mut stream = ActiveSliceStream::new(
            input,
            control.clone(),
            Some(Duration::from_millis(1)),
            tokio::task::yield_now,
        );
        let first = Instant::now();
        stream.begin_poll(first).unwrap();
        assert_eq!(
            control.current_policy(),
            YieldPolicy::Deadline(first + Duration::from_millis(1))
        );
        assert!(!stream.finish_poll(first, first + Duration::from_micros(300), false));
        assert_eq!(control.current_policy(), YieldPolicy::Disabled);

        let second = first + Duration::from_secs(60);
        stream.begin_poll(second).unwrap();
        assert_eq!(
            control.current_policy(),
            YieldPolicy::Deadline(second + Duration::from_micros(700))
        );
        assert!(!stream.finish_poll(second, second + Duration::from_micros(200), false));
        assert_eq!(stream.elapsed, Duration::from_micros(500));

        let third = second + Duration::from_secs(60);
        stream.begin_poll(third).unwrap();
        assert!(!stream.finish_poll(third, third + Duration::from_micros(100), true));
        assert_eq!(stream.elapsed, Duration::ZERO);
        stream.begin_poll(third).unwrap();
        assert_eq!(
            control.current_policy(),
            YieldPolicy::Deadline(third + Duration::from_millis(1))
        );
    }

    #[derive(Default)]
    struct WakeCount(AtomicUsize);

    impl ArcWake for WakeCount {
        fn wake_by_ref(arc_self: &Arc<Self>) {
            arc_self.0.fetch_add(1, Ordering::Relaxed);
        }
    }

    #[test]
    fn native_yield_preserves_pending_wakes_output_and_terminal_ownership() {
        let control = SliceControl::default();
        let inner_control = control.clone();
        let polls = Arc::new(AtomicUsize::new(0));
        let inner_polls = Arc::clone(&polls);
        let owner = Arc::new(());
        let weak_owner = Arc::downgrade(&owner);
        let schema = Arc::new(Schema::empty());
        let batch = RecordBatch::new_empty(Arc::clone(&schema));
        let input = RecordBatchStreamAdapter::new(
            schema,
            futures::stream::poll_fn(move |cx| {
                let _retained = &owner;
                match inner_polls.fetch_add(1, Ordering::Relaxed) {
                    0 => {
                        cx.waker().wake_by_ref();
                        Poll::Pending
                    }
                    1 | 3 => {
                        inner_control.request_yield();
                        Poll::Pending
                    }
                    2 => Poll::Ready(Some(Ok(batch.clone()))),
                    4 => Poll::Ready(Some(Err(DataFusionError::Execution(
                        "test_case".into(),
                    )))),
                    _ => panic!("terminal input must not be polled"),
                }
            }),
        );
        let mut stream =
            ActiveSliceStream::new(input, control, None, tokio::task::yield_now);
        let wake_count = Arc::new(WakeCount::default());
        let waker = waker(Arc::clone(&wake_count));
        let mut cx = Context::from_waker(&waker);

        let wakes = wake_count.0.load(Ordering::Relaxed);
        assert!(stream.poll_next_unpin(&mut cx).is_pending());
        assert!(!stream.yielding);
        assert!(wake_count.0.load(Ordering::Relaxed) > wakes);
        let wakes = wake_count.0.load(Ordering::Relaxed);
        assert!(stream.poll_next_unpin(&mut cx).is_pending());
        assert!(stream.yielding);
        assert!(wake_count.0.load(Ordering::Relaxed) > wakes);
        assert!(matches!(
            stream.poll_next_unpin(&mut cx),
            Poll::Ready(Some(Ok(_)))
        ));
        assert!(!stream.yielding);
        let wakes = wake_count.0.load(Ordering::Relaxed);
        assert!(stream.poll_next_unpin(&mut cx).is_pending());
        assert!(wake_count.0.load(Ordering::Relaxed) > wakes);
        assert!(matches!(
            stream.poll_next_unpin(&mut cx),
            Poll::Ready(Some(Err(_)))
        ));
        assert!(weak_owner.upgrade().is_none());
        stream.elapsed = Duration::MAX;
        assert!(matches!(stream.poll_next_unpin(&mut cx), Poll::Ready(None)));
        assert_eq!(polls.load(Ordering::Relaxed), 5);
    }

    #[test]
    fn yield_once_through_active_slice_stream_wakes_exactly_once() {
        let control = SliceControl::default();
        let inner_control = control.clone();
        let schema = Arc::new(Schema::empty());
        let batch = RecordBatch::new_empty(Arc::clone(&schema));
        let input = RecordBatchStreamAdapter::new(
            schema,
            futures::stream::once(Box::pin(async move {
                inner_control.yield_once().await;
                Ok(batch)
            })),
        );
        let mut stream =
            ActiveSliceStream::new(input, control.clone(), None, tokio::task::yield_now);
        let wake_count = Arc::new(WakeCount::default());
        let waker = waker(Arc::clone(&wake_count));
        let mut cx = Context::from_waker(&waker);

        let wakes = wake_count.0.load(Ordering::Relaxed);
        assert!(stream.poll_next_unpin(&mut cx).is_pending());
        assert!(stream.yielding);
        assert_eq!(wake_count.0.load(Ordering::Relaxed), wakes + 1);
        assert!(matches!(
            stream.poll_next_unpin(&mut cx),
            Poll::Ready(Some(Ok(_)))
        ));
        assert!(!stream.yielding);

        // Outside an active slice poll, yield_once must still self-wake once.
        let mut standalone = Box::pin(control.yield_once());
        let wakes = wake_count.0.load(Ordering::Relaxed);
        assert!(standalone.as_mut().poll(&mut cx).is_pending());
        assert_eq!(wake_count.0.load(Ordering::Relaxed), wakes + 1);
        assert!(standalone.as_mut().poll(&mut cx).is_ready());
    }

    #[test]
    fn exhausted_ready_slice_yields_before_polling_and_overflow_fuses() {
        for overflow in [false, true] {
            let polls = Arc::new(AtomicUsize::new(0));
            let observed = Arc::clone(&polls);
            let input = RecordBatchStreamAdapter::new(
                Arc::new(Schema::empty()),
                futures::stream::poll_fn(move |_| {
                    observed.fetch_add(1, Ordering::Relaxed);
                    Poll::Ready(None)
                }),
            );
            let mut stream = ActiveSliceStream::new(
                input,
                SliceControl::default(),
                Some(if overflow {
                    Duration::MAX
                } else {
                    Duration::from_millis(1)
                }),
                tokio::task::yield_now,
            );
            let waker = futures::task::noop_waker();
            let mut cx = Context::from_waker(&waker);
            if overflow {
                assert!(matches!(
                    stream.poll_next_unpin(&mut cx),
                    Poll::Ready(Some(Err(DataFusionError::Configuration(_))))
                ));
                assert_eq!(polls.load(Ordering::Relaxed), 0);
            } else {
                stream.elapsed = Duration::from_millis(1);
                assert!(stream.poll_next_unpin(&mut cx).is_pending());
                assert_eq!(
                    polls.load(Ordering::Relaxed),
                    0,
                    "expired slice must yield before its first input poll"
                );
                assert!(matches!(stream.poll_next_unpin(&mut cx), Poll::Ready(None)));
                assert_eq!(polls.load(Ordering::Relaxed), 1);
            }
            let before = polls.load(Ordering::Relaxed);
            stream.elapsed = Duration::MAX;
            assert!(matches!(stream.poll_next_unpin(&mut cx), Poll::Ready(None)));
            assert_eq!(
                polls.load(Ordering::Relaxed),
                before,
                "terminal stream must remain fused"
            );
        }
    }
}