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

//! Cooperative work, cancellation, and elapsed-deadline accounting.

use crate::config::{
    CancellationPolicy, DEFAULT_CANCELLATION_POLL_INTERVAL, YieldPolicy,
};
use datafusion::common::{DataFusionError, Result};
use std::time::Instant;

/// Cooperative work and cancellation accounting persisted with a scan.
///
/// Work is recorded only after it completes. Cancellation polling is
/// independent of voluntary yielding, while voluntary yields are taken only
/// by callers that have reached a resumable safe point.
#[derive(Debug, Clone)]
pub(crate) struct WorkGovernor {
    #[cfg(test)]
    work_since_yield: usize,
    last_clock_epoch: u64,
    cancellation_poll_interval: usize,
    work_until_cancel_poll: usize,
    cancellation_policy: Option<CancellationPolicy>,
    execution_deadline: Option<Instant>,
    progress_epoch: u64,
}

impl Default for WorkGovernor {
    fn default() -> Self {
        Self {
            #[cfg(test)]
            work_since_yield: 0,
            last_clock_epoch: 0,
            cancellation_poll_interval: DEFAULT_CANCELLATION_POLL_INTERVAL,
            work_until_cancel_poll: DEFAULT_CANCELLATION_POLL_INTERVAL,
            cancellation_policy: None,
            execution_deadline: None,
            progress_epoch: 0,
        }
    }
}

impl WorkGovernor {
    /// Bind cancellation cadence and the optional elapsed deadline once.
    ///
    /// Rebinding the same policy is a no-op so collection heads and resumptions
    /// cannot reset the countdown or extend the deadline.
    pub(crate) fn bind_cancellation_policy(
        &mut self,
        policy: CancellationPolicy,
    ) -> Result<()> {
        match self.cancellation_policy {
            Some(bound) if bound == policy => return Ok(()),
            Some(bound) => {
                return Err(DataFusionError::Internal(format!(
                    "MATCH_RECOGNIZE cannot change a live work governor cancellation policy from {bound:?} to {policy:?}"
                )));
            }
            None if self.progress_epoch != 0 => {
                return Err(DataFusionError::Internal(
                    "MATCH_RECOGNIZE cannot bind cancellation policy after completed scan work"
                        .to_string(),
                ));
            }
            None => {}
        }

        let execution_deadline = policy
            .deadline()
            .map(|duration| {
                Instant::now().checked_add(duration).ok_or_else(|| {
                    DataFusionError::Configuration(
                        "match_recognize.limits.execution_deadline_millis is too large to add to the monotonic clock"
                            .to_string(),
                    )
                })
            })
            .transpose()?;
        let poll_interval = policy.poll_interval().get();
        self.cancellation_poll_interval = poll_interval;
        self.work_until_cancel_poll = poll_interval;
        self.execution_deadline = execution_deadline;
        self.cancellation_policy = Some(policy);
        Ok(())
    }

    /// Record completed work and poll cancellation at the amortized interval.
    ///
    /// This method never requests a voluntary yield. A caller must first
    /// publish any resumable cursor advancement, then call
    /// [`Self::take_yield_if_due`] at that safe point.
    #[inline]
    pub(crate) fn record_completed<F>(
        &mut self,
        units: usize,
        is_aborted: F,
    ) -> Result<()>
    where
        F: FnOnce() -> bool,
    {
        if units == 0 {
            return Ok(());
        }

        // Nearly every row-loop report is smaller than the cancellation
        // countdown. Keep that path small enough to inline; the cold helper
        // handles due abort/deadline polls and multi-interval batches.
        if units < self.work_until_cancel_poll {
            #[cfg(test)]
            {
                self.work_since_yield = self.work_since_yield.saturating_add(units);
            }
            self.work_until_cancel_poll -= units;
            self.progress_epoch = self.progress_epoch.wrapping_add(units as u64);
            return Ok(());
        }

        self.record_completed_slow(units, is_aborted)
    }

    #[cold]
    #[inline(never)]
    fn record_completed_slow<F>(&mut self, units: usize, is_aborted: F) -> Result<()>
    where
        F: FnOnce() -> bool,
    {
        #[cfg(test)]
        {
            self.work_since_yield = self.work_since_yield.saturating_add(units);
        }
        self.progress_epoch = self.progress_epoch.wrapping_add(units as u64);

        let work_after_first_poll = units - self.work_until_cancel_poll;
        let remainder = work_after_first_poll % self.cancellation_poll_interval;
        let next_poll_countdown = self.cancellation_poll_interval - remainder;

        if is_aborted() {
            return datafusion::common::internal_err!(
                "MATCH_RECOGNIZE execution cancelled"
            );
        }
        if self
            .execution_deadline
            .is_some_and(|deadline| Instant::now() >= deadline)
        {
            return Err(DataFusionError::Execution(
                "MATCH_RECOGNIZE execution deadline exceeded".to_string(),
            ));
        }

        self.work_until_cancel_poll = next_poll_countdown;
        Ok(())
    }

    /// Observe the shared deadline at a completed phase's resumable boundary.
    ///
    /// Taking a yield leaves cancellation and completed progress untouched.
    pub(crate) fn take_yield_if_due(&mut self, policy: YieldPolicy) -> bool {
        let due = policy.is_expired();
        #[cfg(test)]
        let due = match policy {
            YieldPolicy::TestBudget(budget) => self.work_since_yield >= budget.get(),
            _ => due,
        };
        if !due {
            return false;
        }

        #[cfg(test)]
        {
            self.work_since_yield = 0;
        }
        self.last_clock_epoch = self.progress_epoch;
        true
    }

    /// Amortize clock reads inside one owner's hot row/transition loop.
    pub(crate) fn take_yield_if_due_hot(&mut self, policy: YieldPolicy) -> bool {
        if matches!(policy, YieldPolicy::Deadline(_)) {
            if !self.clock_probe_due() {
                return false;
            }
            self.last_clock_epoch = self.progress_epoch;
        }
        self.take_yield_if_due(policy)
    }

    #[inline]
    fn clock_probe_due(&self) -> bool {
        self.progress_epoch.wrapping_sub(self.last_clock_epoch) >= 256
    }

    /// Seed only voluntary work debt for deterministic safe-point tests.
    #[cfg(test)]
    pub(crate) fn set_work_since_yield_for_test(&mut self, units: usize) {
        self.work_since_yield = units;
    }

    #[cfg(test)]
    pub(crate) const fn work_since_yield_for_test(&self) -> usize {
        self.work_since_yield
    }

    /// Seed only the next cancellation-poll boundary for deterministic owner
    /// tests without claiming completed progress.
    #[cfg(test)]
    pub(crate) fn set_work_until_cancel_poll_for_test(&mut self, units: usize) {
        assert!(self.cancellation_policy.is_some());
        assert!(units != 0 && units <= self.cancellation_poll_interval);
        self.work_until_cancel_poll = units;
    }

    /// Replace a configured deadline without sleeping in cadence tests.
    #[cfg(test)]
    pub(crate) fn set_execution_deadline_for_test(&mut self, deadline: Instant) {
        assert!(self.cancellation_policy.is_some());
        self.execution_deadline = Some(deadline);
    }

    #[cfg(test)]
    fn execution_deadline_for_test(&self) -> Option<Instant> {
        self.execution_deadline
    }

    /// Monotonic completed-work identity used by tests and benchmark preflights
    /// to prove that a cooperative return followed real progress.
    #[cfg(test)]
    pub(crate) const fn progress_epoch_for_observation(&self) -> u64 {
        self.progress_epoch
    }
}

#[cfg(test)]
mod work_governor_tests {
    use super::WorkGovernor;
    use crate::config::{
        CancellationPolicy,
        DEFAULT_CANCELLATION_POLL_INTERVAL as CANCELLATION_POLL_INTERVAL, YieldPolicy,
    };
    use std::cell::Cell;
    use std::time::{Duration, Instant};

    fn bind_policy(
        governor: &mut WorkGovernor,
        interval: usize,
        deadline_millis: usize,
    ) -> datafusion::common::Result<()> {
        governor.bind_cancellation_policy(
            CancellationPolicy::try_from_configured(interval, deadline_millis).unwrap(),
        )
    }

    fn record_and_count(governor: &mut WorkGovernor, work: usize, polls: &Cell<usize>) {
        governor
            .record_completed(work, || {
                polls.set(polls.get() + 1);
                false
            })
            .unwrap();
    }

    #[test]
    fn shared_deadline_covers_short_owners_without_changing_cancellation() {
        let deadline = YieldPolicy::Deadline(Instant::now());
        let future = YieldPolicy::Deadline(Instant::now() + Duration::from_secs(60));
        let mut long = WorkGovernor::default();
        let mut short = WorkGovernor::default();
        long.record_completed(513, || false).unwrap();
        assert!(!long.take_yield_if_due_hot(future));
        short.record_completed(1, || false).unwrap();
        assert!(!short.take_yield_if_due_hot(deadline));
        for governor in [&mut long, &mut short] {
            let progress = governor.progress_epoch;
            let countdown = governor.work_until_cancel_poll;
            assert!(governor.take_yield_if_due(deadline));
            assert_eq!(governor.work_until_cancel_poll, countdown);
            assert_eq!(governor.progress_epoch_for_observation(), progress);
        }
        long.record_completed(257, || false).unwrap();
        assert!(long.take_yield_if_due_hot(deadline));
    }

    #[test]
    fn cancellation_cadence_handles_default_custom_and_oversized_charges() {
        for (configured, charges) in [
            (
                None,
                &[
                    (CANCELLATION_POLL_INTERVAL - 1, 0, false),
                    (1, 1, false),
                    (CANCELLATION_POLL_INTERVAL - 1, 1, false),
                    (1, 2, true),
                ][..],
            ),
            (Some(3), &[(2, 0, false), (1, 1, false), (3, 2, false)][..]),
            (
                None,
                &[
                    (CANCELLATION_POLL_INTERVAL + 1, 1, false),
                    (CANCELLATION_POLL_INTERVAL - 2, 1, false),
                    (1, 2, false),
                ][..],
            ),
        ] {
            let mut governor = WorkGovernor::default();
            if let Some(interval) = configured {
                bind_policy(&mut governor, interval, 0).unwrap();
            }
            let polls = Cell::new(0);
            let mut progress = 0;
            for &(units, expected_polls, aborted) in charges {
                let result = governor.record_completed(units, || {
                    polls.set(polls.get() + 1);
                    aborted
                });
                if aborted {
                    assert!(result.unwrap_err().to_string().contains("cancelled"));
                } else {
                    result.unwrap();
                }
                progress += units as u64;
                assert_eq!(
                    polls.get(),
                    expected_polls,
                    "configured={configured:?}, units={units}"
                );
                assert_eq!(governor.progress_epoch_for_observation(), progress);
                assert!(!governor.take_yield_if_due(YieldPolicy::Disabled));
            }
        }
    }

    #[test]
    fn zero_work_changes_no_accounting_and_never_polls() {
        let mut governor = WorkGovernor::default();
        let polled = Cell::new(false);

        governor
            .record_completed(0, || {
                polled.set(true);
                true
            })
            .unwrap();

        assert!(!polled.get());
        assert_eq!(governor.progress_epoch_for_observation(), 0);
        assert!(!governor.take_yield_if_due(YieldPolicy::from_test_budget(1)));
    }

    #[test]
    fn identical_policy_rebind_preserves_countdown_and_deadline() {
        let mut governor = WorkGovernor::default();
        let policy = CancellationPolicy::try_from_configured(3, 60_000).unwrap();
        governor.bind_cancellation_policy(policy).unwrap();
        let deadline = governor.execution_deadline_for_test();

        governor.record_completed(2, || false).unwrap();
        governor.bind_cancellation_policy(policy).unwrap();
        assert_eq!(governor.execution_deadline_for_test(), deadline);

        let polls = Cell::new(0usize);
        record_and_count(&mut governor, 1, &polls);
        assert_eq!(polls.get(), 1, "rebind must not restart the countdown");
    }

    #[test]
    fn expired_deadline_is_observed_only_when_the_poll_cadence_is_due() {
        let mut governor = WorkGovernor::default();
        bind_policy(&mut governor, 3, 1).unwrap();
        governor.set_execution_deadline_for_test(
            Instant::now()
                .checked_sub(Duration::from_millis(1))
                .unwrap(),
        );
        let abort_polls = Cell::new(0usize);

        record_and_count(&mut governor, 2, &abort_polls);
        assert_eq!(abort_polls.get(), 0);

        let error = governor
            .record_completed(1, || {
                abort_polls.set(abort_polls.get() + 1);
                false
            })
            .expect_err("the expired deadline must fail at the next cadence poll");
        assert!(error.to_string().contains("deadline exceeded"), "{error}");
        assert_eq!(abort_polls.get(), 1);
        assert_eq!(governor.progress_epoch_for_observation(), 3);
    }

    #[test]
    fn cancellation_policy_cannot_change_after_binding_or_completed_work() {
        let mut bound = WorkGovernor::default();
        bind_policy(&mut bound, 3, 0).unwrap();
        let error = bind_policy(&mut bound, 4, 0).unwrap_err();
        assert!(error.to_string().contains("cannot change"), "{error}");

        let mut already_used = WorkGovernor::default();
        already_used.record_completed(1, || false).unwrap();
        let error = bind_policy(&mut already_used, 3, 0).unwrap_err();
        assert!(
            error.to_string().contains("after completed scan work"),
            "{error}"
        );
    }
}