Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions datafusion/common/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1130,6 +1130,22 @@ config_namespace! {
///
/// Disabled by default, set to a number greater than 0 for enabling it.
pub hash_join_buffering_capacity: usize, default = 0

/// Join-wide byte threshold for runtime adaptive build-side selection in
/// partitioned hash joins.
///
/// When greater than 0, eligible partitioned hash joins sample the planned
/// build side up to this threshold before building the hash table. If the
/// planned build side exceeds the threshold, the join releases its dynamic
/// filter to `true`, samples the planned probe side, and swaps build and probe
/// roles in-stream when the planned probe side completes within the threshold.
///
/// Non-dynamic-filter cross-input dependencies between the left and right
/// inputs are not supported when adaptive mode is enabled (inputs must be
/// independent relational streams).
///
/// Disabled by default (0).
pub hash_join_adaptive_build_side_threshold_bytes: usize, default = 0
}
}

Expand Down Expand Up @@ -3931,6 +3947,7 @@ impl Display for OutputFormat {
mod tests {
#[cfg(feature = "parquet")]
use crate::assert_contains;
#[cfg(feature = "parquet")]
use crate::config::TableParquetOptions;
use crate::config::{
ConfigEntry, ConfigExtension, ConfigField, ConfigFileType, ExtensionOptions,
Expand Down
121 changes: 111 additions & 10 deletions datafusion/physical-expr/src/expressions/dynamic_filters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -327,19 +327,27 @@ impl DynamicFilterPhysicalExpr {
// Load the current inner, increment generation, and store the new one
let mut current = self.inner.write();
let new_generation = current.generation + 1;
let is_complete = current.is_complete;
*current = Inner {
// Preserve the expression id across updates.
expression_id: current.expression_id,
generation: new_generation,
expr: new_expr,
is_complete: current.is_complete,
is_complete,
};
drop(current); // Release the lock before broadcasting

// Broadcast the new state to all waiters
let _ = self.state_watch.send(FilterState::InProgress {
generation: new_generation,
});
let state = if is_complete {
FilterState::Complete {
generation: new_generation,
}
} else {
FilterState::InProgress {
generation: new_generation,
}
};
// Publish under the write lock with `send_replace` so the watch channel
// always retains the latest state (even with zero active receivers) and
// updates cannot reorder past `mark_complete()`.
self.state_watch.send_replace(state);
Ok(())
}

Expand All @@ -351,10 +359,11 @@ impl DynamicFilterPhysicalExpr {
let mut current = self.inner.write();
let current_generation = current.generation;
current.is_complete = true;
drop(current);

// Broadcast completion to all waiters
let _ = self.state_watch.send(FilterState::Complete {
// Publish under the write lock with `send_replace` so late subscribers
// and concurrent `wait_complete()` calls observe completion even when
// there were zero active receivers at the moment `mark_complete()` ran.
self.state_watch.send_replace(FilterState::Complete {
generation: current_generation,
});
}
Expand Down Expand Up @@ -392,7 +401,13 @@ impl DynamicFilterPhysicalExpr {
return;
}

// Subscribe before re-checking `is_complete` so a concurrent
// `mark_complete()` between the fast-path check and `subscribe()`
// cannot be missed.
let mut rx = self.state_watch.subscribe();
if self.inner.read().is_complete {
return;
}
let _ = rx
.wait_for(|state| matches!(state, FilterState::Complete { .. }))
.await;
Expand Down Expand Up @@ -1010,6 +1025,92 @@ mod test {
dynamic_filter.wait_complete().await;
}

#[test]
fn test_mark_complete_with_zero_receivers_updates_watch_state() {
use std::future::Future;
use std::task::{Context, Poll, Waker};

let dynamic_filter =
DynamicFilterPhysicalExpr::new(vec![], lit(42) as Arc<dyn PhysicalExpr>);

// Update and mark complete while zero receivers are subscribed.
// `send_replace` must persist the `Complete` state in `state_watch`
// so a waiter that already passed an earlier `is_complete` check and
// subsequently calls `subscribe()` cannot hang.
dynamic_filter
.update(lit(43) as Arc<dyn PhysicalExpr>)
.unwrap();
dynamic_filter.mark_complete();

let mut rx = dynamic_filter.state_watch.subscribe();
assert_eq!(
*rx.borrow(),
FilterState::Complete { generation: 2 },
"state_watch must store Complete even when marked complete with zero receivers"
);

let mut cx = Context::from_waker(Waker::noop());
let mut wait_fut = std::pin::pin!(
rx.wait_for(|state| matches!(state, FilterState::Complete { .. }))
);
assert!(
matches!(wait_fut.as_mut().poll(&mut cx), Poll::Ready(Ok(_))),
"subscribing after zero-receiver mark_complete must resolve immediately"
);

// A subsequent update must not regress the watch state back to InProgress.
dynamic_filter
.update(lit(44) as Arc<dyn PhysicalExpr>)
.unwrap();
assert_eq!(
*dynamic_filter.state_watch.subscribe().borrow(),
FilterState::Complete { generation: 3 }
);
}

#[test]
fn test_wait_complete_no_lost_wakeup_across_subscribe_window() {
use std::sync::{Barrier, mpsc};
use std::thread;
use std::time::Duration;

// Repeatedly race `mark_complete()` (starting with 0 receivers) against
// `wait_complete()` across two OS threads to exercise the window
// between the `is_complete` check and `state_watch.subscribe()`.
const ITERS: usize = 500;
let (done_tx, done_rx) = mpsc::channel();

let runner = thread::spawn(move || {
let rt = tokio::runtime::Builder::new_current_thread()
.build()
.expect("build current-thread runtime");
for _ in 0..ITERS {
let filter = Arc::new(DynamicFilterPhysicalExpr::new(
vec![],
lit(42) as Arc<dyn PhysicalExpr>,
));
let barrier = Arc::new(Barrier::new(2));
let producer_filter = Arc::clone(&filter);
let producer_barrier = Arc::clone(&barrier);

let producer = thread::spawn(move || {
producer_barrier.wait();
producer_filter.mark_complete();
});

barrier.wait();
rt.block_on(filter.wait_complete());
producer.join().expect("producer panicked");
}
let _ = done_tx.send(());
});

done_rx
.recv_timeout(Duration::from_secs(10))
.expect("wait_complete hung across check-then-subscribe window");
runner.join().expect("runner panicked");
}

#[test]
fn test_with_new_children_independence() {
// Create a schema with columns a, b, c, d
Expand Down
1 change: 1 addition & 0 deletions datafusion/physical-plan/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ tokio = { workspace = true, features = [
"rt-multi-thread",
"fs",
"parking_lot",
"test-util",
] }

[[bench]]
Expand Down
Loading
Loading