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,
}
#[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
}
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;
}
#[cfg(test)]
fn request_yield(&self) {
self.0.lock().requested = true;
}
}
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);
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"
);
}
}
}