use crate::config::{
CancellationPolicy, DEFAULT_CANCELLATION_POLL_INTERVAL, YieldPolicy,
};
use datafusion_common::{DataFusionError, Result};
use std::time::Instant;
#[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 {
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(())
}
#[inline]
pub(crate) fn record_completed<F>(
&mut self,
units: usize,
is_aborted: F,
) -> Result<()>
where
F: FnOnce() -> bool,
{
if units == 0 {
return Ok(());
}
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(())
}
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
}
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
}
#[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
}
#[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;
}
#[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
}
#[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}"
);
}
}