use std::collections::VecDeque;
use std::fmt;
use std::panic::AssertUnwindSafe;
use std::pin::{Pin, pin};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::task::{Context, Poll, Waker};
use crate::execution::physical::is_match_recognize_exec;
use datafusion::arrow::array::RecordBatch;
use datafusion::arrow::datatypes::SchemaRef;
use datafusion::common::runtime::SpawnedTask;
use datafusion::execution::TaskContext;
use datafusion::execution::memory_pool::{
MemoryConsumer, MemoryLimit, MemoryPool, MemoryReservation,
};
use datafusion::physical_expr::PhysicalExpr;
use datafusion::physical_plan::aggregates::{AggregateExec, GroupClusteringMode};
use datafusion::physical_plan::execution_plan::{CardinalityEffect, EvaluationType};
use datafusion::physical_plan::filter::FilterExec;
use datafusion::physical_plan::metrics::{
ExecutionPlanMetricsSet, MetricBuilder, MetricCategory, MetricsSet,
};
use datafusion::physical_plan::projection::ProjectionExec;
use datafusion::physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec;
use datafusion::physical_plan::statistics::{ChildStats, StatisticsArgs};
use datafusion::physical_plan::{
ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlan,
ExecutionPlanProperties, PlanProperties, RecordBatchStream, ReplaceChildrenOptions,
SendableRecordBatchStream,
};
use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
use datafusion_common::{Result, Statistics, internal_err};
use futures::future::select;
use futures::{FutureExt, Stream, StreamExt};
use tokio::sync::Notify;
const AGGREGATE_BUFFER_CAPACITY: usize = 256 * 1024 * 1024;
const MAX_PARTITION_BUFFER_FLOOR: usize = 4 * 1024 * 1024;
const MIN_BOUNDED_BUFFER_CAPACITY: usize = 64 * 1024;
const BOUNDED_POOL_BUDGET_DIVISOR: usize = 8;
const BOUNDED_POOL_HEADROOM_DIVISOR: usize = 4;
pub(super) fn optimize(plan: Arc<dyn ExecutionPlan>) -> Result<Arc<dyn ExecutionPlan>> {
plan.transform_down(|plan| {
if has_limit(plan.as_ref()) {
return Ok(Transformed::new(plan, false, TreeNodeRecursion::Jump));
}
let Some(merge) = plan.downcast_ref::<SortPreservingMergeExec>() else {
return Ok(Transformed::no(plan));
};
if merge.input().output_partitioning().partition_count() <= 1
|| !has_streaming_matcher(merge.input())
{
return Ok(Transformed::no(plan));
}
let buffered = Arc::new(MatchRecognizeBufferExec::new(Arc::clone(merge.input())));
let plan = plan.replace_children(
vec![buffered],
ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
)?;
Ok(Transformed::yes(plan))
})
.map(|transformed| transformed.data)
}
fn has_limit(plan: &dyn ExecutionPlan) -> bool {
plan.fetch().is_some()
|| plan
.downcast_ref::<AggregateExec>()
.is_some_and(|aggregate| aggregate.limit_options().is_some())
}
fn has_streaming_matcher(mut plan: &Arc<dyn ExecutionPlan>) -> bool {
loop {
if has_limit(plan.as_ref()) {
return false;
}
if is_match_recognize_exec(plan.as_ref()) {
return true;
}
plan = if let Some(projection) = plan.downcast_ref::<ProjectionExec>() {
projection.input()
} else if let Some(filter) = plan.downcast_ref::<FilterExec>() {
filter.input()
} else if let Some(aggregate) = plan.downcast_ref::<AggregateExec>()
&& aggregate.group_clustering_mode() != &GroupClusteringMode::None
{
aggregate.input()
} else {
return false;
};
}
}
#[derive(Debug, Default)]
struct SharedAggregateBudget {
shared_queued_bytes: AtomicUsize,
notify: Notify,
}
impl SharedAggregateBudget {
fn add(&self, delta: usize) {
if delta > 0 {
self.shared_queued_bytes.fetch_add(delta, Ordering::SeqCst);
}
}
fn sub_and_notify(&self, delta: usize, shared_capacity: usize) {
if delta == 0 {
return;
}
let prev = self.shared_queued_bytes.fetch_sub(delta, Ordering::SeqCst);
if prev >= shared_capacity && prev.saturating_sub(delta) < shared_capacity {
self.notify.notify_waiters();
}
}
fn queued_bytes(&self) -> usize {
self.shared_queued_bytes.load(Ordering::SeqCst)
}
}
fn split_aggregate_capacity(
aggregate_capacity: usize,
partitions: usize,
) -> (usize, usize) {
let partition_floor = (aggregate_capacity / partitions.saturating_mul(2))
.min(MAX_PARTITION_BUFFER_FLOOR);
let shared_capacity =
aggregate_capacity.saturating_sub(partition_floor.saturating_mul(partitions));
(partition_floor, shared_capacity)
}
#[derive(Debug)]
struct MatchRecognizeBufferExec {
input: Arc<dyn ExecutionPlan>,
properties: Arc<PlanProperties>,
metrics: ExecutionPlanMetricsSet,
shared_budget: Arc<SharedAggregateBudget>,
}
impl MatchRecognizeBufferExec {
fn new(input: Arc<dyn ExecutionPlan>) -> Self {
let properties = Arc::new(
input
.properties()
.as_ref()
.clone()
.with_evaluation_type(EvaluationType::Eager),
);
Self {
input,
properties,
metrics: ExecutionPlanMetricsSet::new(),
shared_budget: Arc::new(SharedAggregateBudget::default()),
}
}
fn effective_buffer_budget(
&self,
pool: &Arc<dyn MemoryPool>,
) -> Option<BufferBudget> {
let partitions = self
.properties
.output_partitioning()
.partition_count()
.max(1);
let (aggregate_capacity, headroom) = match pool.memory_limit() {
MemoryLimit::Infinite => (AGGREGATE_BUFFER_CAPACITY, None),
MemoryLimit::Finite(limit) => {
let aggregate_capacity =
(limit / BOUNDED_POOL_BUDGET_DIVISOR).min(AGGREGATE_BUFFER_CAPACITY);
if aggregate_capacity / partitions < MIN_BOUNDED_BUFFER_CAPACITY {
return None;
}
let max_pool_used =
limit.saturating_sub(limit / BOUNDED_POOL_HEADROOM_DIVISOR);
(
aggregate_capacity,
Some(PoolHeadroom {
pool: Arc::clone(pool),
max_pool_used,
}),
)
}
MemoryLimit::Unknown => return None,
};
let (partition_floor, shared_capacity) =
split_aggregate_capacity(aggregate_capacity, partitions);
Some(BufferBudget {
partition_floor,
shared_capacity,
shared: Arc::clone(&self.shared_budget),
headroom,
})
}
}
impl DisplayAs for MatchRecognizeBufferExec {
fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"MatchRecognizeBufferExec: capacity={AGGREGATE_BUFFER_CAPACITY}, memory=headroom-bounded"
)
}
}
impl ExecutionPlan for MatchRecognizeBufferExec {
fn name(&self) -> &str {
Self::static_name()
}
fn properties(&self) -> &Arc<PlanProperties> {
&self.properties
}
fn maintains_input_order(&self) -> Vec<bool> {
vec![true]
}
fn cardinality_effect(&self) -> CardinalityEffect {
CardinalityEffect::Equal
}
fn benefits_from_input_partitioning(&self) -> Vec<bool> {
vec![false]
}
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
vec![&self.input]
}
fn apply_expressions(
&self,
_f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
) -> Result<TreeNodeRecursion> {
Ok(TreeNodeRecursion::Continue)
}
fn replace_children(
self: Arc<Self>,
mut children: Vec<Arc<dyn ExecutionPlan>>,
_options: ReplaceChildrenOptions,
) -> Result<Arc<dyn ExecutionPlan>> {
if children.len() != 1 {
return internal_err!(
"MatchRecognizeBufferExec requires one child, received {}",
children.len()
);
}
Ok(Arc::new(Self::new(children.swap_remove(0))))
}
fn with_new_children(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
self.replace_children(
children,
ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
)
}
fn execute(
&self,
partition: usize,
context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
let pool = Arc::clone(context.memory_pool());
let Some(budget) = self.effective_buffer_budget(&pool) else {
return self.input.execute(partition, context);
};
let reservation =
MemoryConsumer::new(format!("MatchRecognizeBufferExec[{partition}]"))
.register(&pool);
let in_stream = self.input.execute(partition, context)?;
let max_mem = MetricBuilder::new(&self.metrics)
.peak_memory_usage("max_mem_used", partition);
let max_queued = MetricBuilder::new(&self.metrics)
.with_category(MetricCategory::Rows)
.gauge("max_queued", partition);
Ok(Box::pin(HeadroomBufferStream::new(
self.schema(),
in_stream,
budget,
reservation,
max_mem,
max_queued,
)))
}
fn metrics(&self) -> Option<MetricsSet> {
Some(self.metrics.clone_inner())
}
fn child_stats_requests(&self, partition: Option<usize>) -> Vec<ChildStats> {
vec![ChildStats::At(partition)]
}
fn statistics_from_inputs(
&self,
input_stats: &[Arc<Statistics>],
_args: &StatisticsArgs,
) -> Result<Arc<Statistics>> {
Ok(Arc::clone(&input_stats[0]))
}
}
struct PoolHeadroom {
pool: Arc<dyn MemoryPool>,
max_pool_used: usize,
}
struct BufferBudget {
partition_floor: usize,
shared_capacity: usize,
shared: Arc<SharedAggregateBudget>,
headroom: Option<PoolHeadroom>,
}
struct QueuedBatch {
batch: RecordBatch,
size: usize,
reserved: usize,
}
struct QueueState {
queue: VecDeque<QueuedBatch>,
queued_bytes: usize,
shared_bytes: usize,
pressure_backoff: bool,
terminal: Option<Result<()>>,
consumer_demanding: bool,
closed: bool,
consumer_waker: Option<Waker>,
reservation: MemoryReservation,
}
fn lock_state(shared: &Mutex<QueueState>) -> MutexGuard<'_, QueueState> {
shared
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn can_pull_next(state: &QueueState, budget: &BufferBudget) -> bool {
if state.consumer_demanding && state.queue.is_empty() {
return true;
}
if state.pressure_backoff {
return false;
}
if let Some(headroom) = &budget.headroom
&& headroom.pool.reserved() >= headroom.max_pool_used
{
return false;
}
state.queued_bytes < budget.partition_floor
|| budget.shared.queued_bytes() < budget.shared_capacity
}
struct HeadroomBufferStream {
schema: SchemaRef,
shared: Arc<Mutex<QueueState>>,
shared_budget: Arc<SharedAggregateBudget>,
partition_floor: usize,
shared_capacity: usize,
producer_notify: Arc<Notify>,
_task: SpawnedTask<()>,
}
impl HeadroomBufferStream {
fn new(
schema: SchemaRef,
input: SendableRecordBatchStream,
budget: BufferBudget,
reservation: MemoryReservation,
max_mem: datafusion::physical_plan::metrics::Gauge,
max_queued: datafusion::physical_plan::metrics::Gauge,
) -> Self {
let shared_budget = Arc::clone(&budget.shared);
let partition_floor = budget.partition_floor;
let shared_capacity = budget.shared_capacity;
let shared = Arc::new(Mutex::new(QueueState {
queue: VecDeque::new(),
queued_bytes: 0,
shared_bytes: 0,
pressure_backoff: false,
terminal: None,
consumer_demanding: false,
closed: false,
consumer_waker: None,
reservation,
}));
let producer_notify = Arc::new(Notify::new());
let shared_bg = Arc::clone(&shared);
let producer_notify_bg = Arc::clone(&producer_notify);
let task = SpawnedTask::spawn(async move {
let mut input = Some(input);
let mut max_mem_in = 0usize;
let mut max_queued_in = 0usize;
loop {
loop {
let mut local_notified = pin!(producer_notify_bg.notified());
local_notified.as_mut().enable();
let mut shared_notified = pin!(budget.shared.notify.notified());
shared_notified.as_mut().enable();
let should_pull = {
let state = lock_state(&shared_bg);
if state.closed {
return;
}
can_pull_next(&state, &budget)
};
if should_pull {
break;
}
select(local_notified, shared_notified).await;
}
let polled = AssertUnwindSafe(
input
.as_mut()
.expect("producer input stream available while running")
.next(),
)
.catch_unwind()
.await;
let batch_or_end = match polled {
Ok(Some(Ok(batch))) => Some(Ok(batch)),
Ok(Some(Err(err))) => Some(Err(err)),
Ok(None) => None,
Err(panic) => {
let msg = panic
.downcast_ref::<&str>()
.map(|s| (*s).to_string())
.or_else(|| panic.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "unknown panic".to_string());
Some(internal_err!(
"MatchRecognizeBufferExec input stream panicked: {msg}"
))
}
};
let terminal = match batch_or_end {
Some(Ok(batch)) => {
let waker = {
let mut state = lock_state(&shared_bg);
if state.closed {
return;
}
let size = batch.get_array_memory_size();
let reserved = match &budget.headroom {
None => {
state.reservation.grow(size);
size
}
Some(headroom) => {
if headroom.pool.reserved().saturating_add(size)
> headroom.max_pool_used
{
state.pressure_backoff = true;
0
} else {
match state.reservation.try_grow(size) {
Ok(()) => {
if headroom.pool.reserved()
> headroom.max_pool_used
{
state.reservation.shrink(size);
state.pressure_backoff = true;
0
} else {
size
}
}
Err(_) => {
state.pressure_backoff = true;
0
}
}
}
}
};
state.queued_bytes = state.queued_bytes.saturating_add(size);
let new_shared_bytes =
state.queued_bytes.saturating_sub(budget.partition_floor);
let shared_delta =
new_shared_bytes.saturating_sub(state.shared_bytes);
state.shared_bytes = new_shared_bytes;
budget.shared.add(shared_delta);
state.queue.push_back(QueuedBatch {
batch,
size,
reserved,
});
if state.queued_bytes > max_mem_in {
max_mem_in = state.queued_bytes;
max_mem.set(max_mem_in);
}
if state.queue.len() > max_queued_in {
max_queued_in = state.queue.len();
max_queued.set(max_queued_in);
}
state.consumer_waker.take()
};
if let Some(waker) = waker {
waker.wake();
}
continue;
}
Some(Err(err)) => Err(err),
None => Ok(()),
};
drop(input.take());
let waker = {
let mut state = lock_state(&shared_bg);
if state.closed {
return;
}
state.terminal = Some(terminal);
state.consumer_waker.take()
};
if let Some(waker) = waker {
waker.wake();
}
return;
}
});
Self {
schema,
shared,
shared_budget,
partition_floor,
shared_capacity,
producer_notify,
_task: task,
}
}
}
impl Stream for HeadroomBufferStream {
type Item = Result<RecordBatch>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut state = lock_state(&self.shared);
if let Some(item) = state.queue.pop_front() {
state.queued_bytes = state.queued_bytes.saturating_sub(item.size);
let new_shared_bytes =
state.queued_bytes.saturating_sub(self.partition_floor);
let released_shared = state.shared_bytes.saturating_sub(new_shared_bytes);
state.shared_bytes = new_shared_bytes;
state.reservation.shrink(item.reserved);
state.consumer_demanding = false;
if state.queue.is_empty() {
state.pressure_backoff = false;
}
drop(state);
self.shared_budget
.sub_and_notify(released_shared, self.shared_capacity);
self.producer_notify.notify_one();
return Poll::Ready(Some(Ok(item.batch)));
}
if let Some(terminal) = state.terminal.take() {
state.consumer_demanding = false;
state.terminal = Some(Ok(()));
return match terminal {
Ok(()) => Poll::Ready(None),
Err(err) => Poll::Ready(Some(Err(err))),
};
}
state.consumer_demanding = true;
state.consumer_waker = Some(cx.waker().clone());
drop(state);
self.producer_notify.notify_one();
Poll::Pending
}
}
impl RecordBatchStream for HeadroomBufferStream {
fn schema(&self) -> SchemaRef {
Arc::clone(&self.schema)
}
}
impl Drop for HeadroomBufferStream {
fn drop(&mut self) {
let released_shared = {
let mut state = lock_state(&self.shared);
state.closed = true;
state.queue.clear();
state.reservation.free();
state.queued_bytes = 0;
std::mem::take(&mut state.shared_bytes)
};
self.shared_budget
.sub_and_notify(released_shared, self.shared_capacity);
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::AtomicBool;
use std::time::Duration;
use datafusion::arrow::array::{Int32Array, UInt8Array};
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::execution::memory_pool::{GreedyMemoryPool, UnboundedMemoryPool};
use datafusion_common::exec_err;
use tokio::time::timeout;
use super::*;
struct TestStream {
schema: SchemaRef,
items: VecDeque<Result<RecordBatch>>,
reservation: Option<MemoryReservation>,
dropped: Option<Arc<AtomicBool>>,
}
impl Drop for TestStream {
fn drop(&mut self) {
drop(self.reservation.take());
if let Some(dropped) = &self.dropped {
dropped.store(true, Ordering::Release);
}
}
}
impl Stream for TestStream {
type Item = Result<RecordBatch>;
fn poll_next(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
Poll::Ready(self.items.pop_front())
}
}
impl RecordBatchStream for TestStream {
fn schema(&self) -> SchemaRef {
Arc::clone(&self.schema)
}
}
#[derive(Debug)]
struct ConcurrentGrowthPool {
inner: Arc<GreedyMemoryPool>,
pending_peer: Mutex<Option<(MemoryReservation, usize)>>,
held_peers: Mutex<Vec<MemoryReservation>>,
}
impl fmt::Display for ConcurrentGrowthPool {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "ConcurrentGrowthPool")
}
}
impl MemoryPool for ConcurrentGrowthPool {
fn name(&self) -> &str {
"ConcurrentGrowthPool"
}
fn grow(&self, reservation: &MemoryReservation, bytes: usize) {
self.inner.grow(reservation, bytes);
}
fn shrink(&self, reservation: &MemoryReservation, bytes: usize) {
self.inner.shrink(reservation, bytes);
}
fn try_grow(&self, reservation: &MemoryReservation, bytes: usize) -> Result<()> {
self.inner.try_grow(reservation, bytes)?;
if let Some((peer, extra)) = self.pending_peer.lock().unwrap().take() {
peer.try_grow(extra)?;
self.held_peers.lock().unwrap().push(peer);
}
Ok(())
}
fn reserved(&self) -> usize {
self.inner.reserved()
}
fn memory_limit(&self) -> MemoryLimit {
self.inner.memory_limit()
}
}
fn int_schema() -> SchemaRef {
Arc::new(Schema::new(vec![Field::new("v", DataType::Int32, false)]))
}
fn int_batch(schema: &SchemaRef, values: &[i32]) -> RecordBatch {
RecordBatch::try_new(
Arc::clone(schema),
vec![Arc::new(Int32Array::from(values.to_vec()))],
)
.unwrap()
}
fn bytes_batch(num_bytes: usize) -> (SchemaRef, RecordBatch) {
let schema = Arc::new(Schema::new(vec![Field::new("b", DataType::UInt8, false)]));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(UInt8Array::from(vec![0u8; num_bytes]))],
)
.unwrap();
(schema, batch)
}
fn single_budget(capacity: usize, headroom: Option<PoolHeadroom>) -> BufferBudget {
let (partition_floor, shared_capacity) = split_aggregate_capacity(capacity, 1);
BufferBudget {
partition_floor,
shared_capacity,
shared: Arc::new(SharedAggregateBudget::default()),
headroom,
}
}
fn test_buffer(
schema: SchemaRef,
input: SendableRecordBatchStream,
budget: BufferBudget,
pool: &Arc<dyn MemoryPool>,
) -> HeadroomBufferStream {
let metrics = ExecutionPlanMetricsSet::new();
let max_mem = MetricBuilder::new(&metrics).peak_memory_usage("max_mem_used", 0);
let max_queued = MetricBuilder::new(&metrics)
.with_category(MetricCategory::Rows)
.gauge("max_queued", 0);
let reservation = MemoryConsumer::new("test_buffer").register(pool);
HeadroomBufferStream::new(schema, input, budget, reservation, max_mem, max_queued)
}
#[test]
fn split_aggregate_capacity_bounds_total_and_preserves_partition_floor() {
for partitions in [1usize, 2, 4, 16, 32, 64, 128] {
for aggregate in [
AGGREGATE_BUFFER_CAPACITY,
MIN_BOUNDED_BUFFER_CAPACITY * partitions,
4 * 1024 * 1024,
] {
let (floor, shared) = split_aggregate_capacity(aggregate, partitions);
assert!(floor <= MAX_PARTITION_BUFFER_FLOOR);
assert!(floor <= aggregate / (2 * partitions));
assert_eq!(floor * partitions + shared, aggregate);
}
}
}
#[tokio::test]
async fn poll_after_err_and_eof_returns_none_without_hanging() {
let schema = int_schema();
let pool: Arc<dyn MemoryPool> = Arc::new(UnboundedMemoryPool::default());
let err_input: SendableRecordBatchStream = Box::pin(TestStream {
schema: Arc::clone(&schema),
items: VecDeque::from([Ok(int_batch(&schema, &[1, 2])), exec_err!("boom")]),
reservation: None,
dropped: None,
});
let mut err_stream = test_buffer(
Arc::clone(&schema),
err_input,
single_budget(AGGREGATE_BUFFER_CAPACITY, None),
&pool,
);
let first = timeout(Duration::from_secs(5), err_stream.next())
.await
.expect("first batch must not hang")
.unwrap()
.unwrap();
assert_eq!(first.num_rows(), 2);
let err = timeout(Duration::from_secs(5), err_stream.next())
.await
.expect("error item must not hang")
.unwrap()
.unwrap_err();
assert!(err.to_string().contains("boom"), "{err}");
assert!(matches!(err_stream.next().now_or_never(), Some(None)));
assert!(matches!(err_stream.next().now_or_never(), Some(None)));
let eof_input: SendableRecordBatchStream = Box::pin(TestStream {
schema: Arc::clone(&schema),
items: VecDeque::from([Ok(int_batch(&schema, &[3]))]),
reservation: None,
dropped: None,
});
let mut eof_stream = test_buffer(
schema,
eof_input,
single_budget(AGGREGATE_BUFFER_CAPACITY, None),
&pool,
);
let only = timeout(Duration::from_secs(5), eof_stream.next())
.await
.expect("single batch must not hang")
.unwrap()
.unwrap();
assert_eq!(only.num_rows(), 1);
assert!(
timeout(Duration::from_secs(5), eof_stream.next())
.await
.expect("EOF must not hang")
.is_none()
);
assert!(matches!(eof_stream.next().now_or_never(), Some(None)));
}
#[tokio::test]
async fn finite_pool_headroom_caps_speculative_reservation_and_keeps_progress() {
let limit = 1024 * 1024;
let max_pool_used = limit - limit / BOUNDED_POOL_HEADROOM_DIVISOR;
let (schema, batch1) = bytes_batch(256 * 1024);
let (_, batch2) = bytes_batch(256 * 1024);
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(limit));
let external = MemoryConsumer::new("external").register(&pool);
external.try_grow(600 * 1024).unwrap();
let input: SendableRecordBatchStream = Box::pin(TestStream {
schema: Arc::clone(&schema),
items: VecDeque::from([Ok(batch1.clone()), Ok(batch2)]),
reservation: None,
dropped: None,
});
let mut stream = test_buffer(
Arc::clone(&schema),
input,
single_budget(
512 * 1024,
Some(PoolHeadroom {
pool: Arc::clone(&pool),
max_pool_used,
}),
),
&pool,
);
timeout(Duration::from_secs(5), async {
while lock_state(&stream.shared).queue.is_empty() {
tokio::task::yield_now().await;
}
})
.await
.expect("producer must speculatively queue first batch");
{
let state = lock_state(&stream.shared);
assert_eq!(state.queue.len(), 1);
assert_eq!(state.queue[0].reserved, 0);
assert!(state.pressure_backoff);
assert_eq!(state.reservation.size(), 0);
}
assert_eq!(pool.reserved(), 600 * 1024);
assert!(limit - pool.reserved() >= limit / BOUNDED_POOL_HEADROOM_DIVISOR);
let first = timeout(Duration::from_secs(5), stream.next())
.await
.unwrap()
.unwrap()
.unwrap();
assert_eq!(first.num_rows(), 256 * 1024);
let second = timeout(Duration::from_secs(5), stream.next())
.await
.unwrap()
.unwrap()
.unwrap();
assert_eq!(second.num_rows(), 256 * 1024);
assert!(
timeout(Duration::from_secs(5), stream.next())
.await
.unwrap()
.is_none()
);
drop(stream);
drop(external);
assert_eq!(pool.reserved(), 0);
let inner = Arc::new(GreedyMemoryPool::new(limit));
let inner_pool: Arc<dyn MemoryPool> = Arc::clone(&inner) as Arc<dyn MemoryPool>;
let peer = MemoryConsumer::new("concurrent_peer").register(&inner_pool);
let racing_pool = Arc::new(ConcurrentGrowthPool {
inner: Arc::clone(&inner),
pending_peer: Mutex::new(Some((peer, 600 * 1024))),
held_peers: Mutex::new(Vec::new()),
});
let racing_pool_dyn: Arc<dyn MemoryPool> =
Arc::clone(&racing_pool) as Arc<dyn MemoryPool>;
let racing_input: SendableRecordBatchStream = Box::pin(TestStream {
schema: Arc::clone(&schema),
items: VecDeque::from([Ok(batch1)]),
reservation: None,
dropped: None,
});
let mut racing_stream = test_buffer(
schema,
racing_input,
single_budget(
512 * 1024,
Some(PoolHeadroom {
pool: Arc::clone(&racing_pool_dyn),
max_pool_used,
}),
),
&racing_pool_dyn,
);
timeout(Duration::from_secs(5), async {
while lock_state(&racing_stream.shared).queue.is_empty() {
tokio::task::yield_now().await;
}
})
.await
.expect("producer must queue batch after concurrent growth rollback");
{
let state = lock_state(&racing_stream.shared);
assert_eq!(state.queue.len(), 1);
assert_eq!(state.queue[0].reserved, 0);
assert!(state.pressure_backoff);
assert_eq!(state.reservation.size(), 0);
}
assert_eq!(racing_pool.reserved(), 600 * 1024);
let drained = timeout(Duration::from_secs(5), racing_stream.next())
.await
.unwrap()
.unwrap()
.unwrap();
assert_eq!(drained.num_rows(), 256 * 1024);
assert!(
timeout(Duration::from_secs(5), racing_stream.next())
.await
.unwrap()
.is_none()
);
drop(racing_stream);
racing_pool.held_peers.lock().unwrap().clear();
assert_eq!(inner.reserved(), 0);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn child_reservation_released_before_consumer_observes_terminal() {
let schema = int_schema();
let limit = 1024 * 1024;
let max_pool_used = limit - limit / BOUNDED_POOL_HEADROOM_DIVISOR;
for is_error in [false, true] {
for _ in 0..32 {
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(limit));
let child_res = MemoryConsumer::new("child_operator").register(&pool);
child_res.try_grow(4096).unwrap();
assert_eq!(pool.reserved(), 4096);
let dropped = Arc::new(AtomicBool::new(false));
let items = if is_error {
VecDeque::from([exec_err!("child stream failed")])
} else {
VecDeque::new()
};
let input: SendableRecordBatchStream = Box::pin(TestStream {
schema: Arc::clone(&schema),
items,
reservation: Some(child_res),
dropped: Some(Arc::clone(&dropped)),
});
let mut stream = test_buffer(
Arc::clone(&schema),
input,
single_budget(
128 * 1024,
Some(PoolHeadroom {
pool: Arc::clone(&pool),
max_pool_used,
}),
),
&pool,
);
let terminal = timeout(Duration::from_secs(5), stream.next())
.await
.expect("terminal item must not hang");
if is_error {
assert!(matches!(terminal, Some(Err(_))));
} else {
assert!(terminal.is_none());
}
assert!(
dropped.load(Ordering::Acquire),
"child stream must be dropped before terminal wakeup (is_error={is_error})"
);
assert_eq!(
pool.reserved(),
0,
"child reservation must be released before terminal wakeup (is_error={is_error})"
);
assert!(matches!(stream.next().now_or_never(), Some(None)));
}
}
}
#[tokio::test]
async fn shared_aggregate_budget_caps_sibling_burst_without_starving_floor_and_wakes_on_drain()
{
let (schema, batch) = bytes_batch(64 * 1024);
let batch_bytes = batch.get_array_memory_size();
let partition_floor = batch_bytes;
let shared_capacity = 2 * batch_bytes;
let shared = Arc::new(SharedAggregateBudget::default());
let pool: Arc<dyn MemoryPool> = Arc::new(UnboundedMemoryPool::default());
let input0: SendableRecordBatchStream = Box::pin(TestStream {
schema: Arc::clone(&schema),
items: VecDeque::from([
Ok(batch.clone()),
Ok(batch.clone()),
Ok(batch.clone()),
Ok(batch.clone()),
]),
reservation: None,
dropped: None,
});
let mut stream0 = test_buffer(
Arc::clone(&schema),
input0,
BufferBudget {
partition_floor,
shared_capacity,
shared: Arc::clone(&shared),
headroom: None,
},
&pool,
);
timeout(Duration::from_secs(5), async {
while lock_state(&stream0.shared).queue.len() < 3 {
tokio::task::yield_now().await;
}
})
.await
.expect("partition 0 must fill floor + shared capacity");
for _ in 0..16 {
tokio::task::yield_now().await;
}
{
let state0 = lock_state(&stream0.shared);
assert_eq!(state0.queue.len(), 3);
assert_eq!(state0.queued_bytes, 3 * batch_bytes);
assert_eq!(state0.shared_bytes, shared_capacity);
}
assert_eq!(shared.queued_bytes(), shared_capacity);
let input1: SendableRecordBatchStream = Box::pin(TestStream {
schema: Arc::clone(&schema),
items: VecDeque::from([Ok(batch.clone()), Ok(batch.clone()), Ok(batch)]),
reservation: None,
dropped: None,
});
let mut stream1 = test_buffer(
schema,
input1,
BufferBudget {
partition_floor,
shared_capacity,
shared: Arc::clone(&shared),
headroom: None,
},
&pool,
);
timeout(Duration::from_secs(5), async {
while lock_state(&stream1.shared).queue.is_empty() {
tokio::task::yield_now().await;
}
})
.await
.expect("partition 1 must still buffer its guaranteed floor");
for _ in 0..16 {
tokio::task::yield_now().await;
}
{
let state1 = lock_state(&stream1.shared);
assert_eq!(state1.queue.len(), 1);
assert_eq!(state1.queued_bytes, partition_floor);
assert_eq!(state1.shared_bytes, 0);
}
assert_eq!(shared.queued_bytes(), shared_capacity);
for _ in 0..3 {
let item = timeout(Duration::from_secs(5), stream0.next())
.await
.expect("partition 0 pop must not hang")
.unwrap()
.unwrap();
assert_eq!(item.num_rows(), 64 * 1024);
}
timeout(Duration::from_secs(5), async {
while lock_state(&stream1.shared).queue.len() < 3 {
tokio::task::yield_now().await;
}
})
.await
.expect(
"partition 1 must wake and buffer once partition 0 releases shared budget",
);
{
let state1 = lock_state(&stream1.shared);
assert_eq!(state1.queue.len(), 3);
assert_eq!(state1.shared_bytes, shared_capacity);
}
assert_eq!(shared.queued_bytes(), shared_capacity);
assert!(
timeout(Duration::from_secs(5), stream0.next())
.await
.unwrap()
.unwrap()
.is_ok()
);
assert!(
timeout(Duration::from_secs(5), stream0.next())
.await
.unwrap()
.is_none()
);
for _ in 0..3 {
assert!(
timeout(Duration::from_secs(5), stream1.next())
.await
.unwrap()
.unwrap()
.is_ok()
);
}
assert!(
timeout(Duration::from_secs(5), stream1.next())
.await
.unwrap()
.is_none()
);
assert_eq!(shared.queued_bytes(), 0);
assert_eq!(pool.reserved(), 0);
}
#[tokio::test]
async fn dropping_buffered_stream_releases_shared_budget_and_wakes_siblings() {
let (schema, batch) = bytes_batch(64 * 1024);
let batch_bytes = batch.get_array_memory_size();
let partition_floor = batch_bytes;
let shared_capacity = 2 * batch_bytes;
let shared = Arc::new(SharedAggregateBudget::default());
let pool: Arc<dyn MemoryPool> = Arc::new(UnboundedMemoryPool::default());
let dropped = Arc::new(AtomicBool::new(false));
let input0: SendableRecordBatchStream = Box::pin(TestStream {
schema: Arc::clone(&schema),
items: VecDeque::from([
Ok(batch.clone()),
Ok(batch.clone()),
Ok(batch.clone()),
Ok(batch.clone()),
]),
reservation: None,
dropped: Some(Arc::clone(&dropped)),
});
let stream0 = test_buffer(
Arc::clone(&schema),
input0,
BufferBudget {
partition_floor,
shared_capacity,
shared: Arc::clone(&shared),
headroom: None,
},
&pool,
);
timeout(Duration::from_secs(5), async {
while lock_state(&stream0.shared).queue.len() < 3 {
tokio::task::yield_now().await;
}
})
.await
.expect("partition 0 must fill shared budget");
assert_eq!(shared.queued_bytes(), shared_capacity);
let input1: SendableRecordBatchStream = Box::pin(TestStream {
schema: Arc::clone(&schema),
items: VecDeque::from([Ok(batch.clone()), Ok(batch.clone()), Ok(batch)]),
reservation: None,
dropped: None,
});
let stream1 = test_buffer(
schema,
input1,
BufferBudget {
partition_floor,
shared_capacity,
shared: Arc::clone(&shared),
headroom: None,
},
&pool,
);
timeout(Duration::from_secs(5), async {
while lock_state(&stream1.shared).queue.is_empty() {
tokio::task::yield_now().await;
}
})
.await
.expect("partition 1 must buffer its floor");
for _ in 0..16 {
tokio::task::yield_now().await;
}
assert_eq!(lock_state(&stream1.shared).queue.len(), 1);
let state0 = Arc::downgrade(&stream0.shared);
drop(stream0);
timeout(Duration::from_secs(5), async {
while !dropped.load(Ordering::Acquire) || state0.upgrade().is_some() {
tokio::task::yield_now().await;
}
})
.await
.expect("abort-on-drop must release the producer waiting for headroom");
timeout(Duration::from_secs(5), async {
while lock_state(&stream1.shared).queue.len() < 3 {
tokio::task::yield_now().await;
}
})
.await
.expect("dropping partition 0 must wake partition 1 to use freed shared budget");
assert_eq!(shared.queued_bytes(), shared_capacity);
drop(stream1);
assert_eq!(shared.queued_bytes(), 0);
assert_eq!(pool.reserved(), 0);
}
}